(template) automation based on last_changed

Hi everybody,

I have one particular binary_sensor (via zigbee2mqtt) that disconnects too often. It is a door reed sensor. In order to determine whether or not it is still connected to the network, I want to create an automation that notifies me if that particular sensor’s state.last_changed value is older than x.

I made a template sensor for this: {{ (as_timestamp(now()) - (as_timestamp(states.binary_sensor.zwischenzimmer_tuer_contact.last_changed))) | timestamp_custom("%H:%M", false)}}. The door’s state has changed 6 minutes ago; the sensor’s value is 00:06, which is correct.

However, I am not sure how to continue from here.

My automation currently looks like this

# Update the sensor every 15 minutes
  - alias: "[Helper] ZZ Tür Update"
      - platform: time_pattern
        minutes: 15
      - service: homeassistant.update_entity
        entity_id: sensor.zzt_last_update
# Send notification when last_change was longer than 8 hours ago
  - alias: "[Helper] ZZ Tür Notify"
      - platform: time_pattern
        minutes: 30
      condition: numeric_state
      entity_id: sensor.zzt_last_update
# ...? what goes here?

I thought that perhaps I have to create another template sensor that equals to 08:00:00, convert it to as_timestamp, then work from there on… but this seems like it is way too complicated.

Is it possible to make an automation based upon this sensor (sensor.zzt_last_update) not changing for 8 hours? Or what is the best way to create an action where there has not been an value change for this door sensor?

Thank you for your ideas :slight_smile:

1 Like

make a binary sensor instead of a sensor and then use this as the value template:

{{ (as_timestamp(now()) - as_timestamp(states.binary_sensor.zwischenzimmer_tuer_contact.last_changed)) / 3600 > 8  }}

then use the binary sensor going to true to trigger the notification.

1 Like

Thank you so much @finity, this works perfectly.

I’ll add an input_number to this so that I can easily modify the amount of hours as well.

Is it somehow possible to define a list of sensors I want to do this for, and apply it to all of them? Or would I have to manually create one binary_sensor and two automations (one to homeassistant.update_entity the template binary sensor, one to trigger the notification) for each sensor I want to do this with?

not that I know of.