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 home → not_home and not_home → home state transitions and it will work as expected, but I’d rather have a single piece of code to maintain.
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
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
I have used the {{ states.some_entity.state }} syntax too and now prefer the is_state() et. al. variants.