Device_tracker state automation constantly triggering

Hi,
I want to build an automation that turns on my laptop’s docking station when the laptop is on and off when the laptop is off / in standby.

To spare me some repetition, I templated this like so:

alias: '[Power] Switch Thinkpad Dock with Thinkpad State'
trigger:
  - platform: state
    entity_id: device_tracker.thinkpad
action:
  service_template: >
    {%if is_state('device_tracker.thinkpad', 'home') %}
    switch.turn_on
    {%else%}
    switch.turn_off
    {%endif%}
  data:
    entity_id: switch.thinkpad

The problem is, that this triggers every 5s or so and not only when the device_tracker state changes.
Does anyone know why that is?

I can split this into two automations for the homenot_home and not_homehome state transitions and it will work as expected, but I’d rather have a single piece of code to maintain.

Sebastian

You can run the following in your Developer Tools -> Template to see if it’s actually updating/changing state that frequently.

{{ (as_timestamp(now())-as_timestamp(states.device_tracker.thinkpad.last_updated)) }}

{{ (as_timestamp(now())-as_timestamp(states.device_tracker.thinkpad.last_changed)) }}

You could create a binary_sensor to ping the laptop for the trigger changing your service_template if statement to ‘on’

- platform: ping
  host: x.x.x.x
  name: Thinkpad
  scan_interval: 5
  count: 5

You’ve not set a state to your platform, so every time something changes on your entity, it triggers the automation
if you want to trigger only when arriving or leaving home, adjust the trigger like so:

trigger:
  - platform: state
    entity_id: device_tracker.thinkpad
    to: 'home'
  - platform: state
    entity_id: device_tracker.thinkpad
    from: 'home'

Ah, I see - the state is not changing, but for some reason is updated every 5 seconds.
I thought the automation would only trigger when the state actually changes.
Well, I guess not…

I can live with setting two triggers - that beats having two differnt automations by far :slight_smile:

Thanks, both of you!

Sebastian

You can increase the device_tracker scan interval and see if coincides with the automation running. But I agree with you, I have many automations that just wait for a state change then executes based on the template.

My automations usually look like the following instead of using is_state

{% if states.device_tracker.thinkpad.state == 'home') %}

EDIT looks like is_state() and states() is the recommended way. So don’t do it like me.

Haha, I was just about to refer you to that page :wink:
I have used the {{ states.some_entity.state }} syntax too and now prefer the is_state() et. al. variants.

Sebastian