Retain last state change data of a sensor after reboot

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.

1 Like

This! It can’t be that hard to make it easy for so many people

1 Like

This is what you guys aren’t understanding. It is the device state. When HA restarts, it queries the devices and updates the state based on what the device reported. Therefor, HA reports the devices state. What you guys want is different. You want HA to check it’s last internal state for the device, and if it matches the startup state, you don’t want it to report a state change. I.e. You want to use the last internal state before startup.

1 Like

Great, as long as the log is clean and not cluttered with troubleshooting events :slight_smile: that are not required atm. A tick that ignores possible wrong stuff due to reboot/ some other process eg db related?

There definitely is misunderstanding, but in the other team than you think. Do an experiment:

  • Turn on wifi humidifier
  • Turn on Zigbee bulb
  • Open door with zigbee contact sensor
  • Open Z2M and check those 2 zigbee devices
  • My zigbee sensor also blink when it changes state (closes, open), so I’ll observe that one too.
  • Restart HA
  • Wait for HA to start

And now the observations:

  • Humidifier did not stop, and in HA, there is no state change (no off/on in history due to restart). It retained the state perfectly fine.
  • Zigbee light did not go off. It stayed on. In Z2M, it was online the whole time (connected via mosquito → z2m → HA). Z2m also shows “on” the whole time. Yet, HA starts, show it “unknown” for a minute and then shows it as “on”.
  • Doors did not close. Sensor did not blink => did not send any new state. Z2M shows the sensor online, and “open” the whole time. Yet, HA starts and has it as unavailable, and only after some time shows it as open.

So clearly, the devices - be it sensors or actors - did not change at all. And HA handles it properly for wifi devices (at least the VeSync humidifier I tried). Z2M still has the proper state of all devices. So how can HA say “the device changed”? That is simply not true.

1 Like

IMHO topic is not about state itselves, but about last_changed & last_updated attributes.

In case of HA rebooted and state remain the same as before reboot,

  • they show time from HA reboot, not from actual state change/update.
1 Like

But that is because HA, on reboot, changes state of zigbee devices to unknown/unavailable. And only after it gets next mqtt message, it updates the state to what it actually is. That explains the time of last change, but the whole procedure is just wrong. The device state did not change. So why HA starts with unknown/unavailable. Should just load the last state it has saved, and even if it is the 0.1% where this would be wrong, it gets fixed with the next mqtt message. But no, HA just wants it to be wrong 99.9% to account for the unprobable, but possible case when you happen to open/close doors in the minute when HA is restarting…

1 Like

I agree, reporting a state has changed by design while it didn’t in the real word is a lie.
If a state has really changed while it was starting, then either HA can detect this by pinging the devices (powered device) so it will change the state to whatever it is now, or it can’t (battery devices), then it’s a technical limitation, that we can understand and accept as users.

1 Like

There’s nothing to experiment with here. HA has the ability to restore states, but each integration has to take advantage of it. There are plenty of integrations that restore state. Most notably: input_xxx helpers, trigger based template sensors, many MQTT entities, etc.


The main argument the team uses against allowing restore state on specific integrations is this scenario:

Your device is on. HA knows your device is on. You turn off HA. Your device turns on and off 4 times while HA is off, and the device lands on the state on. You start up HA. What is the correct last_updated/changed? At this point, Home Assistant only knows about the state prior to shutdown and the state at startup.

The development team chose the philosophy: Choose the state at startup if we don’t know what the device did during shutdown. Which is ultimately why some integrations are allowed restore state.


Keep in mind, I’d rather have the states restored at startup. I’m not arguing against this, I even voted for this. I just remember the “official statement” the last time the development team replied to a similar request. This post is not an invitation for a debate.

1 Like

I stumbled upon this FR a while ago, when I was annoyed by the fact that the last_changed value does not survive reboot. I really like to see when a motion sensor was last triggered (changed) so I can see if that room was used recently or not.

It would be nice if it would survive the restart, or just give us the option to decide if we want to restore it. I hope someday we get this implemented.

4 Likes