I have been reading a lot on this subject and I know it’s a “hot topic”, but I need help.
I’m trying to show in the frontend how long a window has been left open. Normally, thats easy: read the last_changed state attribute of the magnetic sensor.
However, I am restarting HA a lot these days, because I’m always adding new stuff and learning. So each restart, the last_changed is reset to the time HA restarted.
I tried to overcome this by creating some input_datetime helpers to store the last_changed value, using an automation that runs when the sensor changes state (i.e. window opens or closes)
This has been fine until I noticed that the value is reset when HA restarts while the window is open.
During startup, the sensor has the state ‘off’, and it takes a few seconds until HA gets the updated state from the sensor (which is ‘on’)… At that time, HA the automation detects a ‘state change’ and triggers overwriting the last_changed in my input_datetime.
Any ideas how to avoid this?
I tried with another input_boolean that stores the last_known_state, and compare it in the automaiton, but it doesnt work when the window is opened or closed DURING HA restart.
Thanks. I tried it. Got it to work with MariaDB, but…it doesnt really work for me
My guess its because of the sensor (Xiaomi Door & window sensor)
These are the last states recorded in the DB
2021-02-16 17:06:08 on
2021-02-16 17:05:16 off
2021-02-16 17:05:16 off
2021-02-16 17:03:57 on <- after opening the contact, I restarted HA
2021-02-16 17:03:56 off
At 17:03:57 i’ve opened the contact, then restarted HA. After restart, I found 3 more states in the DB: two with OFF and one with ON.
So i cannot diferentiate between the real state changes and the ‘fake’ ones.
You can enhance the automation with a condition so that it doesn’t update the input_datetime if Home Assistant was recently restarted (say within the last 30 seconds).
The Uptime sensor records the time when the system is restarted. The automation’s condition can use it to calculate the elapsed time since restart.
That’s a good question. As far as I know, the documentation doesn’t describe the order or sequence of how things are initialized. Maybe there is something in the Developer Docs but I am not sure.