Can automation using sensor templates to handle how long a sensor has been in a particular state?

The goal is to see if a garage door switch has been on for more than N minutes and then if it has, send an email every M minutes after (for example, if the garage door has been opened for more than an 60 minutes, send an email every 15 minutes until someone closes it).

I noticed there is a way in automation to send something after N minutes (using trigger with after) but that appears to happen only once. What seemed like it might work was to have an automation run every 15 minutes that checked if the garage door state has been opened for more than 60 minutes (based on last_changed) and send an email if it has.

I tried to do this via templates, but it appears that while the automation is triggered every 15 minutes, the sensor template is not re-evaluated to come up with a new true/false value. The system always shows “false” (because when the sensor initially triggers, the last_changed value == now() so always < 3600). If I wait a while and manually try the same “{% if” statement in the template debugger, I can get “true” after the desired time.

Any idea why the template is not re-evaluated during the automation? Suggestions on how to achieve the general goal of “send email every 15 minutes after event seen 60 minutes ago”?

– charles

  - platform: template
        friendly_name: 'Garage door still open'
        value_template:  >-
      {%- if is_state("binary_sensor.garage_door", "on") and ((as_timestamp(now()) - as_timestamp(states.binary_sensor.garage_door.last_changed))  > 3600) -%}
      {%- else -%}
      {%- endif -%}

  - alias: "Email garage door open"
      platform: time
      minutes: '/15'
      seconds: 23
      - condition: state
        entity_id: sensor.garage_door_still_open
        state: "true"
      service: notify.smtpNotifier
        message: "home-assistant says garage door still open"
        title: "home-assistant: garage door"
1 Like

Did you ever figure out how to do this? I’d like to do something similar. I think for your case the alert component would do what you want. For me I’d like to trigger a script so I can’t use the alert component.

You should give appdaemon a look.

Ha ha we actually solve almost exactly this situation in the thread @Mike_D links to, and it’s lesson one! You can certainly modify the last line to be recursive (essentially it will call itself over and over again in 15 minutes intervals) while checking to see if the sensor is still in the improper state before it sends a new notification.

Very cool!