Prevent how "last_changed" gets reset after reboot

Hi all,

Sometimes I forget to timely replace a battery in one of my battery-powered devices, - typical a PIR or door-window sensor. I noticed that the indicators for battery level are not much reliable.
As result I’m too late replacing batteries. The devices run out of power and communication to HA stops.

To improve this, I want to monitor state changes. If a state hasn’t changed for more than a week, I want HA to send a notification to check its battery.

I think I can determine this in YAML with this code to find the time since last state change.

{{ as_timestamp(now()) - as_timestamp(states.binary_sensor.bijkeuken_deur_sensor_106.last_changed) > (3600*24*7) }}

Next step would be an automation to trigger a notification if the above is true.

It works but only problem is that after I reboot HA, the last changed status gets updated.

In the image you see the status of sensor “irresponsive…” is true (last change more than 7days old), changes to false after a reboot. This while the state of the door sensor remains open, because the battery is depleted.

How can I prevent that “last_changed” gets updated after HA gets power cycled?

2 Likes

The answer to your question is: You cannot prevent it.

It’s a long-requested feature (value of last_changed survives a restart) but has never been implemented.

2019 Feature Request

2020 WTH

2022 WTH

The workaround is to store the value in an entity whose value is able to survive a restart (like Input Helpers and Trigger-based Template Sensors).

1 Like

thanks. I was not aware of that.
Any known workaround maybe?

Known workarounds are mentioned in my post above.

1 Like