How to trigger on state change including condition of prior state?

I am looking to set up an automation based on a motion detector binary sensor. I want the automation to trigger when the sensor goes to ‘on’, but ONLY if it has been ‘off’ more than 5 minutes previously (i.e. new motion).

I was thinking about making a second variable that is true whenever the state has been off > 5 minutes, and making it be a condition in the automation, but I’m afraid it will turn false when the sensor triggers before the automation can fire.

Thanks!

I thought at one time there was a ‘for’ condition. I can’t seem to find it in the docs. It may still be there, but I’m not sure.

edit: for as in ‘for x amount of time’

The variable for is relative to the new state, not the previous state.

That could work if you add a delay_off to keep it on for a few seconds extra, but it’s not necessary since all the data you need is available in the trigger variable. The last_changed property of the from_state will hold a datetime object reflecting when the previous state change occurred (in this case when the door closed). Add your offset to that time, and compare it to the current time.

trigger:
  - platform: state
    entity_id: binary_sensor.example
    from: 'off'
    to: 'on'
condition:
  - condition: template
    value_template: >
      {{ now() - trigger.from_state.last_changed >= timedelta(minutes=5) }}
1 Like

Wouldn’t this do the same?

trigger:
  - platform: state
    entity_id: binary_sensor.example
    from: 'off'
    to: 'on'
condition:
  - condition: state
    for:
      minutes: 5
    entity_id: binary_sensor.example
    state: 'off'

No, that will always fail. The test that condition poses is “Check if the state is ‘off’ and has been so for at least 5 minutes”… but the current state is “on” not “off”.

Ugh, that should have been obvious to me. I need to remind myself not to try to think after consecutive 60 hour work weeks.

1 Like