Simple template sensor with last state memory


My home assistant is connected to an external community sensor, but the sensor is sometimes offline (unavailable). I want to create my template sensor, who save last state of external sensor and show the last state if the external sensor is unavailable. If the external sensor works I want to show value from it.
I build my first template in my configuration.yaml:

  - sensor:
      - unique_id: sensor_pm10_LastState
        name: >
            {% if "unavailable" != states("sensor.sensor_pm10") | string %}
              {{ "Wrocław PM 10" }}
            {% else %}
              {{ "Wrocław PM 10 (offline)" }}
            {% endif %}
        unit_of_measurement: "μg/m³"
        icon: "mdi:molecule"
        state: >
            {% set pm10 = states("sensor.sensor_pm10") | string %}
            {% if pm10 != 'unavailable' %}
              {% set pm10_last_state = pm10 | float %}
              {{ pm10 | float }}
            {% else %}
              {{ pm10_last_state | float }}
            {% endif %}

What am I doing wrong? What can I do better?

Please help.


I suggest you use a Trigger-based Template Sensor because its value is preserved after a restart.

  - trigger:
      - platform: state
        entity_id: sensor.sensor_pm10
      - unique_id: sensor_pm10_LastState
        name: "Wrocław PM 10{{ ' (offline)' if trigger.to_state.state == 'unavailable' else '' }}"
        unit_of_measurement: "μg/m³"
        icon: "mdi:molecule"
        state: >
          {% set pm10 = states('sensor.sensor_pm10') %}
          {{ pm10 if trigger.to_state.state != 'unavailable' else this.state }}

Its initial value will be unknown until it is triggered (by sensor.sensor_pm10).


Tnx for reply, but I get only unknown value from your template sensor :frowning:

Has the value of sensor.sensor_pm10 changed yet?

The Trigger-based Template Sensor will initially report unknown until it is triggered by a change in the value of sensor.sensor_pm10.


As the value changed your template sensor started working great :slight_smile:

That’s good.

For the final test, wait until sensor.sensor_pm10 is unavailable then check what the Trigger-based Template Sensor reports.

I realize it may take some time before this happens so just reply whenever it occurs.

Works great :slight_smile: TNX :slight_smile:

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.

1 Like