This should be a pretty simple automation but for some reason it’s not working as expected. I simply want the switch to turn off automatically 3 hours after it was turned on but it’s not turning off.
When manually toggling the switch it definitely changes state correctly in Dev Tools but the below just does not work. I’ve tried minutes instead of hours but that didn’t work either so can anyone see what’s wrong with the below?
- alias: Charger Auto Off
id: charger_auto_off
mode: single
trigger:
- platform: state
entity_id: switch.battery_charger
to: 'on'
for:
hours: 3
condition: []
action:
service: switch.turn_off
entity_id: switch.battery_charger
That is because that trigger is asking for the switch to be on for 3 hours before it triggers. You need to trigger with the switch but put the timer in under actions, “wait for a time to pass” or add a timer helper and trigger that to then trigger the off after the timer ends.
That’s generally not good practice. Automations ideally should run as a single, “instant” flow.
I wonder if the switch is going offline / unavailable during that period, messing up the timing? If that is the case, the timer helper suggestion might be the answer.
@c0ntax — can you paste the history chart for that switch?
Yeah, that’s the problem. It goes what I guess is unavailable or unknown at about 10:10 AM, then twice more after that — which means it’s not staying on for three hours.
Options:
the timer helper idea above
another automation triggered on the charger going on from off that stores the current time plus three hours in an input_datetime helper — then this automation triggers from that helper in a time trigger
- alias: Charger Auto Off timer set
id: c8ccd1eb-491b-4405-8722-036c4e5e9474
trigger:
- platform: state
entity_id: switch.battery_charger
from: 'off'
to: 'on'
action:
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.charger_auto_off
data:
timestamp: "{{ now().timestamp() + 10800 }}"
- alias: Charger Auto Off
id: charger_auto_off
trigger:
- platform: time
at: input_datetime.charger_auto_off
# etc
That’s the problem with waiting for 3 hours anything can happen, that’s what I was trying to suggest. But then it could do the same with wait for a time to pass. Not sure if timer helpers continue to count down if HA restarted, but at least they are independent of the switch or wifi wobbles.
Timers will be restored to their correct state and time on Home Assistant startup and restarts when configured with the restore option. However, automations using the timer.finished event will not trigger if the timer expires when Home Assistant is not running.