Automation is not working condition: template

Hello everyone, I can’t understand why my automation is not working. Can anyone help?

- alias: Lights Off
  trigger:
    - platform: state
      entity_id: binary_sensor.door_window_sensor_1
      to: 'off'

  condition:
      - condition: template
        value_template: '{{ as_timestamp(now()) - as_timestamp(states.binary_sensor.door_window_sensor_1.last_changed) | int > 7 }}'

  action:
    - service: light.turn_off
      entity_id: light.spot_lights

dev-template editor shows correct values

What exactly are you trying to achieve?

The way it is currently written it can never work. It’s triggering when the sensor changes, but the condition requires the change to have happen at least 7 sec ago.

I want the light to turn off when I close the door only if the door has been open for more than 7 seconds. But automation never works.

Ok, thanks. You can do that using the for: option:

- alias: Lights Off
  trigger:
    - platform: state
      entity_id: binary_sensor.door_window_sensor_1
      to: 'off'
      for: 7
  action:
    - service: light.turn_off
      entity_id: light.spot_lights

This will trigger only if the sensor changes to ‘off’ and stays ‘off’ for 7 seconds.

I need the light to not turn off when I close the door if the door is open for less than 7 seconds

Ah, ok. Sorry, missed that. :blush:

- alias: Lights Off
  trigger:
    - platform: state
      entity_id: binary_sensor.door_window_sensor_1
      to: 'off'

  condition:
      - condition: template
        value_template: >
          {{ trigger.from_state and
             (now() - trigger.from_state.last_changed).total_seconds() > 7 }}

  action:
    - service: light.turn_off
      entity_id: light.spot_lights
2 Likes

Oh, sorry, I missed the syntax :smile: It works, thank you very much !!

1 Like

I like how your template first tests for trigger.from_state to be true before using it in a calculation (which would otherwise fail if trigger.from_state wasn’t available). :+1:

1 Like