let’s say you have the real sensor value (your sensor.sensor.river_pro_101859_battery) you can create a template sensor to to retain the last good value (your sensor.river_pro_101859_battery_preserved).
- platform: template
sensors:
river_pro_101859_battery_preserved:
friendly_name: River Pro 101859 Battery Preserved
icon_template: mdi:battery-90
unit_of_measurement: "%"
value_template: >-
{% if states('sensor.river_pro_101859_battery') not in ['unknown', 'unavailable'] %}
{{ states('input_number.river_pro_101859_battery') }}
{% else %}
{{ states('input_number.river_pro_101859_battery_preserved') }}
{% endif %}
- platform: template
sensors:
river_pro_101859_total_input_preserved:
friendly_name: River Pro 101859 Total Input Preserved
icon_template: mdi:flash
unit_of_measurement: W
value_template: >-
{% if states('sensor.river_pro_101859_total_input') not in ['unknown', 'unavailable'] %}
{{ states('sensor.river_pro_101859_total_input')|float(0)|round(0) }}
{% else %}
{{ ( states ('0.0')|float(0))|round(0) }}
{% endif %}
Edit: that’s not exactly the same code but the trick is the |float(0) part.
Hi Pete, thanks for the super quick response. I actually tried your suggested code. And after testing, I found that when my device (solar inverter) is available and I restart HA, everything is okay. But the the solar inverter is offline and I restart HA, the entities again go back to unknown/unavailable.
I am sharing my code below. It would be great if you could suggest a solution to it.
- platform: template
sensors:
mauli_solar_energy_total_preserved:
friendly_name: Solar Production Total Preserved
unit_of_measurement: "kWh"
value_template: >-
{% if states('sensor.mauli_solar_energy_total') not in ['unknown', 'unavailable'] %}
{{ states('sensor.mauli_solar_energy_total')|float(0)|round(0) }}
{% else %}
{{ states('sensor.mauli_solar_energy_total_preserved') }}
{% endif %}
this sounds to me that the value of the sensor mauli_solar_energy_total_preserved is being reset at boot. And since the inverter is offline it can’t get a valid number from the if statement.
You could add | float(0) to the else statement as well to replace the unkown state by ‘0’ but I guess that’s not want you want, right?
By the way, did you create an input_number helper?