Skip to content

Filtering out invalid sensor values (spikes)

Max Chodorowski edited this page Dec 11, 2020 · 1 revision

Some sensors may produce invalid data from time to time which can mess up stats gathered for a long period of time. It is pretty common for remote sensor/devices which are relying on lower frequencies (like 433Hz) or the batter powered ones (when battery is dying).

To skip the invalid states we need to create template sensor where we specify the condition e.g.:

value_template: >
  {% if states('sensor.owl_energy_total') | int > 200000 %}
   {{ states('sensor.energy_total') }}
  {% else %}
   {{ states('sensor.real_energy_total') }}
  {% endif %}

What it does is that it returns real sensor value if it's not higher than 200k, otherwise it returns its own previous/current state. Simple as that.

Here is more complete example taken from my config. The problem I was having was that energy sensor is producing 0 state from time to time. This was messing up utility meter sensors and the values counted for daily/monthly/yearly usage was completely broken. So that is my solution (additionally converting Wh to kWh and rounding the result):

- platform: template
  sensors:
    energy_total:
      friendly_name: "Energy total"
      unit_of_measurement: kWh
      value_template: >
        {% if states('sensor.owl_energy_total') | float == 0 %}
         {{ states('sensor.energy_total') }}
        {% else %}
         {{ states('sensor.owl_energy_total') | float | multiply(0.001) | round(1) }}
        {% endif %}

Clone this wiki locally