Is it possible to use “last changed to on” somehow, rather than just “last_changed”?
Last_changed will reflect both ‘off to on’ and ‘on to off’ changes.
I’m looking for a solution that only reflects last_change to ‘ON’ state.
Is it possible to use “last changed to on” somehow, rather than just “last_changed”?
Last_changed will reflect both ‘off to on’ and ‘on to off’ changes.
I’m looking for a solution that only reflects last_change to ‘ON’ state.
Create an input_datetime
helper. Then:
automation:
alias: Records time of last change to on state
trigger:
- platform: state
entity_id: sensor.your_sensor
from: 'off'
to: 'on'
action:
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.your_input_datetime
data:
timestamp: "{{ now().timestamp() }}"
Thank you for the help, Troon.
If I understand correctly, in the example below, I would just need to substitute as_timestamp(states.binary_sensor.south_central_pir.last_changed
for your_input_datetime
, which make things nice and simple.
What would be the correct syntax for doing this?
value_template: "{{ as_timestamp(now()) - as_timestamp(states.binary_sensor.south_central_pir.last_changed) | int < 20 }}"
value_template: "{{ (as_timestamp(now()) - as_timestamp(states('input_datetime.your_input_datetime')))|int < 20 }}"
That will be true if the input_datetime
contains a time less than 20 seconds ago, although note that a sensor or automation using this template will only update every minute.
Note the warning in this section.
Thanks, Troon.
In that case, that won’t do what I need.
I need to run an automation only if an input boolean has gone from ‘off’ to ‘on’ in the last 20 seconds.
I’ll need to find another way.
Sorry, wasn’t clear there: it will trigger on an update to the input_datetime
, which if you use the above automation will be “instant” on the change in state of the sensor.
Why not just trigger on the sensor change itself? Your original request was to “reflect last_change to ‘ON’ state”, which you’d need the input_datetime
to do. If you just want to react to that happening, then use the automation trigger as above.
It’s probably me that’s not being clear.
I want an automation to trigger on an event, but only if another event has occurred in the last 20 seconds.
Using the timestamp is the only way I can figure how to do that.
What did you mean by “a sensor or automation using this template will only update every minute”?
I meant that the now()
part will trigger evaluation of the template every minute. Any change to the input_datetime
will trigger an evaluation immediately on a change of value.
So yes, this will work for you. Use “my” automation to store the last-change-to-on time, then use the above condition template in “your” automation to ensure that this change-to-on is less than 20s old.
Thank you for clarifying that.
I appreciate your help.