Use last value instead of unknown

Use this.state to get the last known value.

In the following example (a fragment of a Template Sensor), if the value of sensor.outside_temp is not unknown or unavailable then that value is reported. Otherwise the Template Sensor uses its existing value (this.state).

  state: >
    {% set x = states('sensor.outside_temp') %}
    {{ x if has_value(x) else this.state | default(0, true) }}

The default is there for this reason:
When you first create the Template Sensor, it won’t have an existing value for this.state. So if at that moment sensor.outside_temp has the bad luck of being unknown or unavailable then default will be used to report 0.

NOTE

Perhaps a better way to do this is to create a Trigger-based Template Sensor with a State Trigger that listens for changes to sensor.outside_temp but ignores any state-change to unknown or unavailable (using the not_to option). A Trigger-based Template Sensor retains its value after a restart.

template:
  - trigger:
      - platform: state
        entity_id: sensor.outside_temp
        not_to:
          - unknown
          - unavailable
    sensor:
      - name: Outside Temperature
        state: '{{ trigger.to_state.state }}'
        device_class: temperature
        unit_of_measurement: '°C'

EDIT

Corrected typo.

15 Likes