Action if device was in State xyz for exactly 55 seconds

I have a coffee machine that has an HA integration. I want to know if the last run program was the “milk clean” program, so if ran it last before turning it of I want to set a state “coffee machine clean”

However the machine doesn’t provide that data, however it outputs if its idle or doing something. The clean program takes 54-57 seconds, everything else takes some other amount of time.

So it goes idle, running (for x seconds), idle

I now want to set a state “clean” if the last “running” state took 55 (+/- some delta) seconds. If the last program took some other amount of time, set it to “dirty”.

Additional complication, when turning on it goes to running as well, but for a very short amount of time. It also changes from off to running instead of from idle to running.

Any pointers on how I can achieve this?

I’m technically inclined but rather new to HA, so any help would be appreciated.

As a template sensor or automation?

I don’t know really, what’s the difference? Ultimately I want to trigger a light to be green or red or off

In that case you probably need an automation, unless you also want a text saying clean/dirty on the dashboard

description: ""
mode: single
triggers:
  - trigger: state
    entity_id:
      - sensor.something
    to: running
    for:
      hours: 0
      minutes: 0
      seconds: 55
conditions: []
actions:
  - action: light.turn_on
    metadata: {}
    data: {}
    target:
      entity_id: light.red_light

This automation would also trigger if one of the other, non-cleaning, programs ran for longer than 55 seconds.

I think your trigger should be when the coffee maker’s sensor goes from running and then you can calculate and test the time it was in that state in a template condition using something like this template:

{% set time = as_timestamp( trigger.to_state.last_changed ) - as_timestamp( trigger.from_state.last_changed ) %}
{{ time >= 54 and time <= 57 }}
1 Like