THE PROBLEM
Quite a few of my automations depend on the last time an entity was in a certain state. Eg. I only want to do something if a light was last on before 9pm. Or do something if a door was last closed at least 5 minutes ago.
If I look at the history log of an entity, the data I need is there! But there is no easy or intuitive way to get it. Current solutions are massively complex requiring direct queries against the database, or setting up seperate automations to track the state of the entity using helpers to store the data.
A BETTER SOLUTION
Give us a method we can call in templates.
state_ended(‘entity_id’, ‘entity_state’) returns a date time object.
eg. state_ended(‘switch.air_purifier’, ‘on’)
Pass in the entity id and entity state, and it will return the last time the entity stopped being in that state.
And another similar one:
state_started(‘entity_id’, ‘entity_state’) returns a date time object.
eg. state_started(‘switch.air_purifier’, ‘on’)
Pass in the entity id and entity state, and it will return the last time the entity started being in that state.
Obviously the limitation is how far back the history for that entity goes, but that’s fine. This is a simpler, more integrated solution for a common problem. Plus you can do cool things like calculate how long an entity was last in a state.