Hi, I can’t figure out why this automation doesn’t work with the condition that my AC switch has been in the OFF state for at least 4 hours. If I remove the condition, the automation triggers at 2p just as it should. Config check is also happy with the condition and I assure you that the AC switch has been OFF for over 30 hours as seen in my history.
Also, I promise I searched a lot before posting and this was the closest that I found, but it did not help.
- id: '1554653702787'
alias: Home - Temp (Afternoon)
trigger:
- at: '14:00:00'
platform: time
condition:
- condition: state
entity_id: switch.air_conditioner
state: 'off'
for:
hours: 4
minutes: 0
seconds: 0
action:
- data:
entity_id: climate.living_room
temperature: '73'
service: climate.set_temperature
Is it possible that you have restarted HA less than 4 hours before 2p? The way state conditions work is they check the entity’s state’s last_changed field. When HA starts last_changed will be set to that time, and then updated when the state (i.e., state.state) actually changes. So, if HA restarts after 10a, then the condition cannot be true at 2p (even if the physical switch last change before 10a.)
You can test this by entering {{ utcnow() - states.switch.air_conditioner.last_changed }}
in the Template editor (e.g., right around 2p when you think the automation should trigger) and it will tell you how long since the switch changed (or how long since HA started, whichever happened last.)
1 Like
Oh wow! I didn’t know that restarting would cause the state to restart. I think you’re correct about that.
Is there a way for me to program this to instead be conditioned that it has not been on for 4 hours (as opposed to it has been off for 4 hours)?
Not being on is basically the same thing as being off.
The issue is that, at least for the state condition, it doesn’t know about any state changes before HA started. Certainly it can’t know about state changes while HA is not running. And it doesn’t try to go into the history of the entity (i.e., from the database) to figure that out when HA starts (probably mainly because there’s no way to know when the last change might have happened, because it might have been while HA wasn’t running. Make sense?)
To solve your problem, don’t restart HA.
But seriously, there are a couple of ways to remember when the last change was (at least while HA was running.) E.g., you could use an SQL Sensor. Or you could use an automation with an Input Number to record the timestamp when the switch changes. These could potentially give you information from previous runs of HA (and therefore span the gap while HA wasn’t running.) Of course, they can’t help with knowing if the last time the switch changed if that happened while HA wasn’t running.
Thanks so much! I may try one of those or just not worry about it anymore.
1 Like