Trigger on last_changed not working?

Hi,

I’m trying to fire some automation when a sensor has not changed for x time. I’ve read quite some topics and I have various attempts for usable templates working in my dev-tools environment. However using these in sensors, binary sensors or automation triggers they just don’t seem to work.

Example of binary sensor that needs to be switched on after 5 sec of no change:

test:
  friendly_name: test
  value_template: "{{(as_timestamp(now()) - as_timestamp(states.binary_sensor.bathroom_humidity_dropping.last_changed)) | int > 5}}"

If I run the template I see it switching from true to false (and vice versa) but the sensor remains unchanged

Example of regular sensor that should display the # seconds since last change:

- platform: template
  sensors:
    humidity_drop_last_update:
      value_template: '{{(as_timestamp(now()) - as_timestamp(states.binary_sensor.bathroom_humidity_dropping.last_changed)) | int}}'

Again, when running the template I see a nice output in seconds. The sensor however does not update…

And for the automation:

  trigger:
  - platform: template
    value_template: '{{(as_timestamp(now()) - as_timestamp(states.binary_sensor.bathroom_humidity_dropping.last_changed) | int > 60)}}'

again with no result…

What am I doing wrong here?

1 Like

Now() doesn’t update templates.

So what’s a proper alternative then?

A possible solution (using a one-minute resolution) by making use of the time sensor.

Define time sensor (this gets updated every minute):

- platform: time_date
  display_options:
    - 'date_time'

Binary sensor using a template to determine the last update time, rounded to minutes. The enitty_id ‘date_time’ makes sure the binary sensor is updated every minute.

bathroom_humidity_dropping_stabilized:
  friendly_name: Humidity drop stabilized
  value_template: >-
    {{ ((as_timestamp(states.sensor.date_time.last_changed) | int - as_timestamp(states.binary_sensor.bathroom_humidity_dropping.last_changed)) / 60) | round() >= 5 }}
  entity_id: sensor.date_time