I have a sensor that sometimes goes into the “unavailable” state.
How can I skip this state so that even when it is unavailable it always shows the last state?
Or how can I make another sensor that will always keep the last state (skipping the “unavailable” state)
By “persistent” people also usually mean one that also survives HA restarts as well as system reboots (remembering the last value). Here is how you do it a simple way:
-
The only measurable “variables” which survive not losing their value for this are input helpers. If the sensor you are discussing is text, create an input text sensor, and f the sensor value a number then create an input number, etc.
-
Create an automation that whenever your original sensor changes value, with the condition that only if the value is NOT “unavailable” (and I presume you also mean “unknown” as well?), it just sets the value of your input helper to be the state of your original sensor.
Once you see that your code is working and your input helper is always displaying the correct information, then just hide the original sensor, and in all of your automations/dashboards then use the input helper sensor you created instead.
Hope that helps!
You can use a trigger-based template sensor also, which does the same thing as an input_helper and automation but does it all in one entity.
template:
- trigger:
- trigger: state
entity_id: sensor.my_original_sensor
not_to:
- unknown
- unavailable
sensor:
- name: "New Sensor"
state: "{{ trigger.to_state.state }}"
I actually started forming my answer in this manner too, and agree this would actually be a simpler solution - but would not survive restarts/reboots and so if “sensor.my_original_sensor” was ever stuck in an unavailable or unknown state for a long period of time upon a restart/reboot it would not be helpful in that one situation.
Thanks. This second solution is enough for me. I don’t need history etc. HA restart occurs very rarely so it may be.
Trigger-based template sensors (and binary sensors) will persist across restarts. Other trigger-based template entities, and all state-based template entities, do not.
From the docs:
The state, including attributes, of trigger-based sensors and binary sensors is restored when Home Assistant is restarted.
Super.
Where is this data kept? Does the database grow and keep history?
By default, all entities (whether they restore their state after a restart or not) will have their history stored by the recorder integration. As specified on that page, the default duration for history is 10 days.
However, if the entity is a sensor
and has state_class
defined, then that entity will also have statistics generated for it. The hourly statistics are retained indefinitely. Those statistics are stored in the same database as the recorder database, but in a separate table.