Template sensor: counting entities with numerical states 'less than' a threshold

I think I’m getting close here, but I’m still getting an error in the Template Editor. I’m attempting to count all of the entities in the group “batteries” that have a state less than or equal to a threshold:

        {% set threshold = 50 | int %}
        {% set nss = namespace(res=0) %}
        {% for sensor in state_attr('group.batteries', 'entity_id') | count %}
        {% if states(sensor) | int <= threshold %}
        {% set nss.res = nss.res + 1 %}
        {% endif %}
        {% endfor %}
        {{ nss.res }}

Where am I going wrong?

Try this version.

{% set threshold = 50 %}
{{ state_attr('group.batteries', 'entity_id')
  | map('states') | map('int', 0)
  | select('<=', threshold)
  | list | count }}

NOTE

If you prefer to use your version, here it is with corrections and some minor adjustments.

{% set threshold = 50 %}
{% set nss = namespace(res=0) %}
{% for sensor in state_attr('group.batteries', 'entity_id')
   if states(sensor) | int(0) <= threshold %}
{% set nss.res = nss.res + 1 %}
{% endfor %}
{{ nss.res }}
1 Like

BINGO! This works perfectly. Thank you for your help.

1 Like