Get last recorded value and time from history database for a sensor?

Hi,

Is there a way to get the last value (and it’s timestamp) for a sensor from the history database, in a template, or via JS in button-card, please?

I notice the last_updated attribute resets to now() when I restart HA. I’ really after the last time a sensort was really seen :smiley:

Cheers :+1:

Maybe state your intended purpose?
There might be other ways…

Literally to see if a sensor is dead (battery etc).

The last_updated attribute is mostly functional, but a restart of HA will reset it, making everything look alive until the timeout I’ve defined (hour or two) is reached.

I reasoned that if chart cards can pull the history data, maybe I can??? Literally the last value would be perfect…

There is the ‘unavailable’ state for that.
Each integration implements (or should) a specific logic to determine if an entity is available or “dead”.

You sure could have reasons to overrule the builtin logic, but you have to be careful about relying on “time since last changed” only.
For instance, on low-consumptions devices, it could take days before the battery level drops by 1%…

1 Like

Thank you Chris. The ones I’m having most trouble with are the BLE (via HACS) thermometers… I don’t seem to get an “unavailable” from those - but now you told me about it, I will have a look at their code and see if it tries to ever return that.

I have only a few classes of device with batteries and they’re all pretty chatty, but I take your point that that may not always be the case.

To actually do what your topic title says, you’d need to use an SQL sensor with an appropriate query, perhaps using something like WHERE NOT state = 'unavailable' LIMIT 1.

You’d need to do a bit of SELECTing to work out what it really is that you’re looking for though. I use sqlite3 on the command line, but I’m using Docker so that may not be available to you.

1 Like

Hi Troon,

I am interested in keeping some data long term (outside climate for one). So it was part of another sub project to notify certain data off to a better database somewhere (whether that be something local or remote I don’t know yet) - but I could tie this to that…

Still a bit confused why it’s “not a thing” to be able to get at the internal history that the charts use, though…

Sorry if I’ve missed the point, but the standard HA SQLite database is the internal history that the charts use.

2 Likes

Ah - I’ll give that a try then. Thanks mate. Apologies - I have not got a full understanding the architecture yet.

1 Like