Effective Energy Reading Filtering with Custom Template Sensor

Hello everyone, I wanted to share my recent experience in creating a custom template sensor to filter abnormal energy readings. After months of research and trial and error, I found that the built-in filters weren’t sufficient for my needs, especially since energy consumption values only increase or reset to zero.

I initially tried developing a custom component but realized a template sensor could achieve the same results with more flexibility. The key was setting the max_jump value to filter out unrealistic spikes or drops in readings. Here’s the code I developed:

python
{% set max_jump = 0.1 %}
{% set raw = states(‘sensor.123_test_sensor’) %}
{% set last_state = this.state %}
{% set raw_invalid = raw in [‘unknown’, ‘unavailable’, ‘none’, ‘’] %}
{% set last_invalid = last_state in [‘unknown’, ‘unavailable’, ‘none’, ‘’] %}

{% if raw_invalid and last_invalid %}
unavailable
{% elif raw_invalid %}
{{ last_state }}
{% elif last_invalid %}
{{ raw | float }}
{% else %}
{% set current = raw | float %}
{% set last = last_state | float %}

{% if (current - last) | abs <= max_jump %}
{{ current }}
{% else %}
{{ last }}
{% endif %}
{% endif %}

I’ve been running this setup without issues, but I’m always open to feedback to improve it further. The ability to adjust the max_jump value in the UI is a significant advantage, as it avoids the hassle of recreating the filter from scratch. I believe this solution could be invaluable for others looking to ensure accurate energy readings. Thanks to the community for the inspiration and support! Let me know if you have any suggestions or questions.