Templating - jinja syntax question

I would like to take the average of a series of sensors, so long as they are reporting a valid number as their state (which they do under ‘normal’ circumstances).

I know how to do this but it would take me a lot of lines and I feel sure there is simple (possibly even one line) way to do this that I just don’t know because my jinja/python skills are not good enough.

Anyone care to help?


e.g.

sensor.sensor1 = 2
sensor.sensor2 = 3
sensor.sensor3 = 4
sensor.sensor4 = ‘unknown’

would return 3


sensor.sensor1 = 3
sensor.sensor2 = 4
sensor.sensor3 = 5
sensor.sensor4 = 6

would return 4.5

Number of ways to do this. If you want to filter unknown states, you need to use namespace:

{% set entities = [] %} # fill in with entity names as strings
{% set foo = namespace(cnt=0, val=0) %}
{% for e in entities %}
{% set s = states(e) %}
{% if s != None %}
{% set foo.cnt = foo.cnt + 1 %}
{% set foo.val = foo.val + s | float %}
{% endif %}
{% endfor %}
{{ foo.val / foo.cnt }}

So I’m on my phone so the quotes will be wrong, change them to the correct quote type. I haven’t tested it but it should work.

1 Like

Thanks, I’m also away now but will adapt this to my needs later…