Issues with Sensor Template to Reject Outlier Sensor Data

Hello All,

I have a sensor (an Aranet4) which has the tendency to return spurious outlier data every so often. In order to try to solve this problem I have set up a template via the GUI.

The “state template” code is as follows

{% set sensor_fixed = states('sensor.sensor_fixed') | lower %}
{% set sensor_raw= states('sensor.f6_a8_9c_17_3c_b5_humidity') | float %} 
{% if sensor_fixed == "unavailable" or sensor_fixed == "unknown" %}
{{ sensor_raw }}
{% elif (sensor_raw - states('sensor.sensor_fixed') | float) | abs > 10 %}
{{ states('sensor.sensor_fixed') | float }}
{% else %}
{{ states('sensor.sensor_raw') | float }}
{% endif %}

Unfortunately - something still seems to be slipping through and I’m still getting bad readings

What am I doing wrong ?

I guess you should check what sensor.sensor_fixed and sensor.f6_a8_9c_17_3c_b5_humidity was at the time of the spike.
I would guess the raw one was 100 and the fixed one is 0, unavailable or unknown

What is the name of the template sensor that you’ve created in the UI? I’d assume it is called “Sensor Fixed” with an entity_id of sensor.sensor_fixed but that doesn’t match with the graph that you screenshotted. It looks like you’re graphing the original sensor, which of course isn’t going to change by creating a new template sensor.

You’ve also got states('sensor.sensor_raw') in your code and it’s not clear to me that an entity with that entity_id actually exists. I would assume the raw sensor is actually sensor.f6_a8_9c_17_3c_b5_humidity. Perhaps that last else clause should just be {{ sensor_raw }}

This isn’t your issue, but it’s generally bad practice to keep referring back to the state machine multiple times in your template because the states of devices could be changing during execution of your code. Set the state of the entity to a variable and refer back to that variable rather than re-accessing the state object. Also you can use this.state to refer to the state of the template sensor itself.