I’ve been looking around on how to get the last timestamp a switch is turned on but still not get satisfying answer. Several threads here tried to get last_changed state from the sensor. But I’m trying to get one from a switch entity. I tried to adopt it to my sensor template like below, but I don’t get an updated time when I turn on my switch. Moreover, the sensor template time is always resetted to the time my HA booted.
For a little background, I’ve built a custom fish feeder using ESP8266 with esphome firmware. The esphome integrates very well with HA and creates a switch for me so I can manually turn on the feeder from HA. The problem is there are several ways to turn on the feeder :
Using physical button on the feeder (which will pass switch.turn_on command to HA)
Using HA frontend where I have the switch entity
HA automation where I set the feeder switch to turn-on automatically at 6AM and 6PM
I want to know the last time the switch is turned on (from any way above) to make sure I’m not over or under feeding the fish. Thank you for all your help…
Pretty sure that HA will always report the last state changed as the last boot time. It is part of the way that state machine works.
I have worked around this by publishing the timestamp to a MQTT topic with persistent flag set each time the state actually changes. This way it preserves it during a HA restart.
Good idea! So you use the mqtt topic as a sort of variable to store the time that persist between HA reboot? Could you please share that bit of code here? Would love to take a look, and I think I can add some codes to publish mqtt in esphome codes…
Example is that I have a camera sitting over my pool chlorinator. An automation runs every 30 minutes during daylight hours that calls a script to publish retained message to an MQTT topic and take the snapshot.
I also have 6 Bruh multi-sensors that I built and I use very similar automations to keep track of when the last motion was detected on each of them.
I do a nightly HA restart just after midnight to work around an issue with some Broadlink switches I have. This restart forces the MQTT connections to refresh from the last retained message in the topic, so the “yesterday” logic is automatically handled by that. If you don’t do a nightly restart then you would probably need an automation to do this for you (not sure exactly how though)
… and if it is easier, you could create a SQL sensor to query the HA database directly.
sensor:
- platform: sql
queries:
- name: Real Last Update
query: "SELECT state FROM states WHERE entity_id = 'sensor.name' ORDER BY created DESC LIMIT 1;"
column: 'state'
replacing sensor.name with the name of your sensor
I am not 100% certain this will work, but give it a try and see how it goes!
I steer clear of direct SQL queries, but to be honest, I have no idea why