Time an entity was in its 'on' state

I’m using the following simple trigger to action when an entity state is in that state for a certain duration:

trigger:
  - platform: state
    entity_id:
      - binary_sensor.lumi_lumi_sensor_magnet_aq2_opening
    to: "on"
    for:
      hours: 0
      minutes: 5
      seconds: 0

But my understanding is that will only trigger once, when the 5 minute threshold has passed.

I’d like to turn this into a template trigger, which effectively keeps trying the automation until the template evaluates to false.

So my template looks something like this

{{ (now() - states.binary_sensor.lumi_lumi_sensor_magnet_aq2_opening.last_changed).total_seconds()>600}}

But I’ve yet to determine if the last change turned it to on or off, so I’ve extended it to:

{{ states('binary_sensor.lumi_lumi_sensor_magnet_aq2_opening')=='on' and (now() - states.binary_sensor.lumi_lumi_sensor_magnet_aq2_opening.last_changed).total_seconds()>600}}

Is there a better/cleaner/more modern way of doing this ?

Can you explain why?

There may be a better way.

Comment not regarding the logic, but consider using the is_state function instead.

I posted on another thread that I noticed one of my lights was left on overnight.
At first i checked the automation to see if I had an error, then discovered this:

Error while executing automation automation.hall_lights_top_floor_v2: Failed to send request: device did not respond

It pretty rare this happens, but I thought I could use the template to check if the hall light was left on for more than 5 minutes and switch it off… and if the device doesn’t respond, try again.

I guess that also means I should consider a maximum number of retries if for example, the device has genuinely fallen off the network.

That would be the way I would approach this.

In your actions use a repeat while loop. In the loop sequence turn your light off and wait a short delay.

For the while conditions, only loop while the light is on and the loop count is less than a maximum number of retries you choose.

Also if the loop exits because it exceeded the maximum number of retries, send you a notification of failing to turn the light off.

I’ve avoided the loop for cases where I have a flaky connection or device by using a wait for state trigger with a timeout. I’d then wait on the desired state for x amount if time. I find it a bit simpler. I had loops originally, but changed it when this functionality came out.

Using the wait only tries once though. At least with a loop you have a few goes at it.

Yes, you’re right. I typically only retry once — with an inline second service call if the first failed.