Support retrieving the last known value in templates for unavailable sensor entities

There are tons of forum posts of people who also face this problem but it seems there is no nice solution to this: In my case, the entities of my PV inverter become unavailable once the device shuts down over night. The entities have a red exclamation mark next to them and all template sensors that use them (e.g. to calculate the daily yield of different systems) also show “unavailable”.
However, if I click on a respective entity I can see the last value and all previous values of the entity in its history.

image

It would be nice if one could use a filter or if there was a default attribute “last_value” populated for each sensor that could be used to avoid the above issues, i.e. to ensure that all other entities using this value still work.

Switch to a trigger-based template sensor using a State trigger set not to trigger on the “unavailable” state value.

Do you happen to have an example for how this could be done? I’ve been searching and I tried out different things but nothing works :confused:

template:
  - trigger:
      - platform: state
        entity_id: sensor.symo_total_energy_example
        not_to:
          - unknown
          - unavailable
    sensor:
      - name: Symo Total Energy stable
        state: "{{ trigger.to_state.state }}" 
3 Likes

Thanks a lot - I will give it a try (I believe I have to wait until tomorrow / until the device turns on again for the sensor to contain a value).

There is, but you must use a template sensor to filter it.

template:
  - sensor:
      - name: Symo Total Energy stable
        device_class: energy
        state_class: total_increasing
        unit_of_measurement: kWh
        state: >
          {% if has_value('sensor.pv_energy') %}
            {{ states('sensor.pv_energy') }}
          {% else %}
            {{ this.state }}
          {% endif %}

Or in more compact form:

template:
  - sensor:
      - name: Symo Total Energy stable
        device_class: energy
        state_class: total_increasing
        unit_of_measurement: kWh
        state: "{{ states('sensor.pv_energy') if has_value('sensor.pv_energy') else this.state }}"

Or

template:
  - sensor:
      - name: Symo Total Energy stable
        device_class: energy
        state_class: total_increasing
        unit_of_measurement: kWh
        state: "{{ iif(has_value('sensor.pv_energy'), states('sensor.pv_energy'), this.state) }}"

EDIT: way too slow (I did not scroll down to see it had been answered already). Drew’s answer is another way using triggered template sensors.

2 Likes