Dealing with errors in template sensors

If you work with Home Assistant, you probably already use some template sensors.
Often, these are simple sensors that provide calculated values based on other sensors, such as an average or the sum of the values of similar real sensors.
Ex: You would like to have a single sensor with a “total” value which is the mathematical sum of multiple other sensor values.

But what would happen if any of the source sensors would become unavailable and/or has an “unknown” state? What would the result of your calculation be?
In the best case the result would probably be wrong…

When does it matter?

If you only use the current value of a template sensor to display it, it probably doesn’t matter all that much, although your history might contain some oddities.

This example shows a (total) kWh template sensor that doesn’t handle errors well. At times a zero value is returned by the template calculation resulting in huge jumps in this graph.

However, when you have such a sensor that occasionaly returns bogus values, any derivative value will also be wrong. It should be no suprise automations and decisions based on such data might have undesired results as well.
It is therefore important to ensure you handle any potential error well.

A derivative sensor calculating the “per hour” electricity usage based on the above kWh sensor. Because the source kWh sensor value jumps to 0 and then back again, this derivative sensor assumes a huge energy usage in a small amount of time.

Root-Cause

Identifing the root-cause of an issue is not always easy, but it is always whise to check upstream to see if any of the source sensors display strange behaviour. In this case, the kWh sensor was a template sensor with this below configuration

#Total consumed (Day + Night)
- platform: template
  sensors:
    electricity_consumed:
      friendly_name: "Total Electricity Consumed"
      unique_id: "sensor.total_electricity_consumed"
      unit_of_measurement: "kWh"
      value_template: "{{ states('sensor.p1_electricity_consumed_day')|float + states('sensor.p1_electricity_consumed_night')|float |round(2) }}"

Should be fairly simple: The total electricity usage is the sum of the day and night usage. (Line #8.)
But what if for some reason “electricity_consumed_day” or “electricity_consumed_night” is not (yet) known?
Exactly, you get the above graphs…

(In this case the electricity_consumed_day/night sensors are populated by MQTT and by design these entries are not persistent. This unwanted behaviour will therefor occur upon Home Asistant restart, MQTT broker restart, MQTT client disconect etc…)

Fixing it

HomeAssistant already takes care of most of the required stuff and if a sensor is non-functional for some reason, it normally has one of the following states in HA: “unavailable”, “unknown”, or “none”.
Creating resilient template sensors is just a matter of checking for these states in the “value_template”.

A fix for the problem is this situation would be:

#Total consumed (Day + Night)
- platform: template
  sensors:
    electricity_consumed:
      friendly_name: "Total Electricity Consumed"
      unique_id: "sensor.total_electricity_consumed"
      unit_of_measurement: "kWh"
      value_template: >
        {% if states('sensor.p1_electricity_consumed_day') in ['unavailable', 'unknown', 'none'] %}
          {{ states('sensor.total_electricity_consumed') }}
        {% elif states('sensor.p1_electricity_consumed_night') in ['unavailable', 'unknown', 'none'] %}
          {{ states('sensor.total_electricity_consumed') }}
        {% else %}
          {{ states('sensor.p1_electricity_consumed_day')|float + states('sensor.p1_electricity_consumed_night')|float |round(2) }}
        {% endif %}

This value template checks the source sensors (Line #9 / #11) and if something is wrong the current kWh value is returned. (Line #10 / #12)
Only if both source sensors have a valid state (real value) the calculation is made (Line #14).