Problem counting entities

Hi,

I try to determine the number of batteries with less than 20%. I figured out how to to count those with exactliy 20%, but not with less than 20%. Here’s my code in the sensor template:

{% set label = 'batteries' %}
{% set threshold = '20' %}
{% set num = (label_entities(label) | select('is_state',threshold) | list | count) %}
{{num}}

I tried a “solution” i found in via google

{% set label = 'batteries' %}
{% set threshold = '20' %}
{% set num = (label_entities(label) | selectattr('state','lt',threshold) | list | count) %}
{{num}}

but i get that error: “UndefinedError: ‘str object’ has no attribute ‘state’”

How can i count the entities ?

The label_entities() function returns a list of entity IDs which are just strings. By themselves they do not contain any state data. You need to use the states() function to get the state values from those IDs. The map() filter allows us to iterate all the items in a list through another function. We can use it to get the states as actual integers, then perform the selection and count:

{% set label = 'batteries' %}
{% set threshold = 20 %}
{% set num = (label_entities(label) | map('states') 
| map('int',0) | select('lt', threshold) | list | count) %}
{{num}}

just for inspiration, have a look at low-battery-notifications-and-actions.yaml · GitHub