Automation door closing trigger, but only if it has been open for more than 2 minutes

I’m trying to make an automation to turn back on my thermostat after it has been turned off. My trigger would be when my door closes, but I want a condition so it only proceeds when the door has been open for 2 minutes before closing it, so it won’t run on every door closing.

Here is my automation so far, but I think the issue is with my condition: it checks for the last status change, but this status change will never be more than 2 minutes, because the state change is my trigger also.

alias: "Heater on when doors and windows closed "
description: ""
trigger:
  - platform: state
    entity_id:
      - binary_sensor.doors_and_windows
    from: "on"
    to: "off"
condition:
  - condition: and
    conditions:
      - condition: template
        value_template: >-
          {{ (as_timestamp(now()) -
          as_timestamp(states.binary_sensor.doors_and_windows.last_changed)) >
          121 }}
      - condition: numeric_state
        entity_id: sensor.esphome_web_dd1c11_water_temperature
        below: 30
        enabled: true
action:
  - service: climate.turn_on
    metadata: {}
    data: {}
    target:
      entity_id: climate.heater
mode: single

Try this:

      - condition: template
        value_template: >-
          {{ trigger.to_state.last_changed - trigger.from_state.last_changed >= timedelta(minutes=2) }}

Basically it’s calculating the amount of time that has passed since the last time the door’s state changed and the most recent time. It then tests if the result is more than 2 minutes.

Thank you, it worked!
I really need to get better with jinja2 :smiley:
This is the full working automation.
It triggers when my door sensor changes from open to closed and runs only when the door has been open for more than 121 seconds AND the water temp in my mixed fuel heater is under 30 (so they cannot heat at the same time, causes issues).
Then it switches my thermostat back on, and sends a notification.

alias: "Heater on when doors and windows closed "
description: ""
trigger:
  - platform: state
    entity_id:
      - binary_sensor.doors_and_windows
    from: "on"
    to: "off"
condition:
  - condition: and
    conditions:
      - condition: template
        value_template: >-
          {{ trigger.to_state.last_changed - trigger.from_state.last_changed >=
          timedelta(seconds=121) }}
      - condition: numeric_state
        entity_id: sensor.esphome_web_dd1c11_water_temperature
        below: 30
        enabled: true
action:
  - service: climate.turn_on
    metadata: {}
    data: {}
    target:
      entity_id: climate.heater
    enabled: true
  - service: notify.persistent_notification
    metadata: {}
    data:
      message: Szellőztetés vége
      title: Termosztát bekapcsolt
mode: single
1 Like