Retain last state change data of a sensor after reboot

Unfortunately, despite the great response in votes, the request has not yet been implemented. If it is helpful, I have shared some examples of sensors to keep the last_state on reboot.

Bumping this, really annoying

Nice to quickly see when a device was last used, motion detected

5 Likes

Yep. Not so nice to have 100 sensors that tells you when you restarted Home Assistant as per current behaviour. More useful to preserve the actual last change/update rather than last restart of HA core :slight_smile:

But for some reason, people developing the HA core does not like this so it probably will not happen. You will have to write custom automations/triggers and update the state of your additional helpers to fix this. Bloating everything.

It has been discussed before, and for a long time, e.g. here:

A lot of bumps. No code change :wink:

3 Likes

I hope you found the answer since then, but just in case: last_changed records the last time the value was changed, last_updated the last time the value was given.

If the sensor receives a new value and it is the same as the old value, it will only affect last_updated, not last_changed.

Nah! I’m still running 0.94 and haven’t rebooted in years…:roll_eyes:

Yes, I have, thanks!

At the risk of being accused of throwing the baby with the dirty water, I wonder if it would be worth just removing these. Almost anything you base off of these will

  • at best create many questions from household members and yourself of why the data seems wrong
  • at worst, produce really wrong behavior that causes false alarms and notifications and family scares

For as long as we need to restart HA regularly – minimally once every few weeks to pick up latest updates, and for some of us, much more frequently, these fields are either useless or confusing or dangerous.

4 Likes

Big plus one. The only reason why I realized I needed this was the awesome multiple entity row card: GitHub - benct/lovelace-multiple-entity-row: Show multiple entity states and attributes on entity rows in Home Assistant's Lovelace UI

1 Like

Thereis one more downside of this, and that is current implementation of “device triggers”. If you don’t use state trigger “door sensor state goes from off to on”, but use “device trigger” su as “door opened”, it doesn’t hav the “from” condition. And that means, after restart, change from “unknown” to “on” happens, which triggers any automation that has “when door opens”. That’s clearly wrong, as the doors didn’t move an inch.

Zigbee lights supports one nice functionality: power on behaviour. And you can choosefor yourself whether you want the light to stay off or go to it’s previous state when power is lost and then restored.

Nabu Casa people think it’s absolutely necesary to change status of every single thing, and trigger all automations after restart, while users think the oposite (as seen in the votes and discussion in similar topics). Why not implement HA variant of “power on behaviour”? Just a simple boolean in settings. Do you want every single change sensor to trigger change and update last-changed after restart? Your choice. That would make Nabu Casa people have it their way, while allowing users to set it to their preference. Could that be implemented?

3 Likes

Bumping this.

I have been trying to implement a watchdog for my MQTT devices to check when they were last seen, the current solution I have is disrupted on every restart. My logic is if an MQTT device last changed > 24 hours ago, then flag as potentially disconnected. If I restart HA (once a week for updates or multiple time a day if I’m working on something), I lose the last time the device checked in so my watch dog is useless for 24 hours after a restart.

Bumping this as well. I need to keep a closer look at by battery devices.

Just last week a Smoke detector (Fibaro) kept stuck on 40% battery left. DIgging in to it stopped logging changes battery/temperature etc for weeks already.

We NEED this feature!

1 Like

+1, this is long overdue.

We need this,
at least I need this
a change from 10.2 to 10.2 is not a change. some monitoring fails for me if I get an unexpected state update when nothing is changed.

however, this might affect automations as well.
if state = ‘X’ for 1 hour.

when will the automtion start checking? does a timer start at the beginning of this state change or will it be calculated back? becaust if the former is the case as automations do not survive a reboot, this part needs to be rewritten as well, And I think that would be the bottleneck here.


This is the graph showing my hourly rain rate… The red circles are when I restarted HA.
HA registers these as ‘updates’ even though there was no update, the value/measurement was unavailable for a brief period during the restart.
It would be good if there would be an option to not register a value/sensor being ‘unavailable’ as a value change since there was no proven change of value/state then (there could have been, but HA did not detect it as it was offline).

In SCADA systems, a measurement being unavailable is captured as its quality rather than its value changing which makes sense and gives the users (or the system) more flexibility. It would be good if HA could implement similar functionality.

2 Likes

I got excited there for a second. Thought this was a community mod to actually add the feature, lol.

Just came here if there was a “elegant” solution here. Only a feature integrated into the core can solve this. It kind of is also a basic feature I believe. I understand HA gets updates from the components and then sets the states, but until then there it is important to have prev state restored. most esp based solutions we have do not send this state to HA. instead we have to rely on prev state.

We are in November 2024, and the problem still exists, it’s disheartening.

On top of that, the database is filled with gigabytes of useless logs.

2 Likes

We are in January 2025. HA still has the bug to report a state change while there were no state change with the device when HA restarts.
This is really a bug and not a feature request from a user perspective.
We expect the device state not any internal state…

1 Like

BTW my concern was with detecting issues with sensors. I had a script relying on last updated date. in my case it’s only for temperature. if no change with one of the sensor within 12 hours, it means it’s failing (temperature has to change for sure over 12 hours) so I get a notification with the list of failed devices.

Because ‘last updated date’ is wrong when you restart HA, I built another script, where I retrieve the temperature 12 hours ago and compare with current, and send a notification with the list when temperature is the same.

I use a SQL sensor (based on the SQL integration), instead or the history integration as I don’t want to create one history sensor per device!!

sharing with you the SQL, Just replace the 3 devices I kept to illustrate the script, with your IDs.:


SELECT
  GROUP_CONCAT(meta.entity_id, ', ') AS state

FROM
  states_meta AS meta
  LEFT JOIN states AS curr ON curr.metadata_id = meta.metadata_id
    AND curr.last_updated_ts = (
      SELECT MAX(last_updated_ts)
      FROM states
      WHERE metadata_id = meta.metadata_id
    )
  LEFT JOIN states AS past ON past.metadata_id = meta.metadata_id
    AND past.last_updated_ts = (
      SELECT MAX(last_updated_ts)
      FROM states
      WHERE metadata_id = meta.metadata_id
        AND last_updated_ts <= strftime('%s', 'now', '-12 hours') 
    )
WHERE
  meta.entity_id IN (
    'sensor.garage_temperature',  //replace with yours
    'sensor.jardin_temperature_temperature', //replace with yours
    'sensor.salon_temperature_temperature' //replace with yours
  )
  AND curr.state == past.state;

and in the config set ‘state’ for column name, do not change the other fields (well you can but it’s optional).

The “SQLite Web” integration is nice to build and test queries!!

I named my SQL entity “list_of_dead_devices” so in your automation you can use sensor.list_of_dead_devices
if empty, no dead devices, otherwise it’s a list of failed devices, comma separated that you can simply add to your notification.

that’ my automation code( replace the name of the SQL entity by your name or just use mine)

alias: Detect sensor failure
description: >-
  Checks if temperature sensor hasn't updated in 12 hours. Add new device to
  list_of_dead_devices (SQL entity)
triggers:
  - hours: "8"
    minutes: "00"
    seconds: "00"
    trigger: time_pattern
conditions:
  - condition: template
    value_template: |
      {{ states('sensor.list_of_dead_devices') not in ['unknown', 'None', ''] }}
actions:
  - action: script.simple_notification
    data:
      title: Detection sensor failure
      message: |
        The following sensors have the same temperature as 12 hours ago:
         - {{ states('sensor.list_of_dead_devices').replace('sensor.', '').replace(', ', '\n- ') }}.
mode: single

I just found another argument so that last_changed does not change when restarting HA. In automations, in condition ‘IF FOR some time’, value of last_changed is used in code to check whether the condition is met.

So it simply check two things:

  • Is there currently a state we want? And this is ok because sensor state is correct after HA restart.
  • Is condition time longer than time to last_changed? And this is problem because in reality sensor not change state during HA restart.

I have seen the ideas of creating additional variables such as last_on, but I think it would only complicate the system and not solve all the problems - e.g. with automation.

So… making last_changed persistent or the possibility of choosing (persistent or not) should solve all problems, also with automations.