I created a label called ‘activity’ to count the number of devices with the state ‘on’ and display that count in a badge but I’m having a hard time getting this to work. {{ states | selectattr('attributes.labels', 'in', ['activity']) | list | count }}
always returns ‘0’ even though devices that have the label ‘activity’ are on.
A label is not part of an entity’s attributes. Therefore you cannot use attributes.label
in a selectattr
.
There are specific functions for working with labels.
The following example gets a list of entity_ids representing all entity’s with the “activity” label, gets their state, selects only the ones that are on
, then returns the quantity.
{{ label_entities('activity') | select('is_state', 'on') | count }}
Be advised that you stated you were attempting to “count the number of devices” with a template that begins with states
(which contains information about all entities).
The word “device” has special meaning in Home Assistant and is different from another term named “entity”. Your template, had it worked, would have reported the number of entities that are on
(not devices).
A device is a virtual model of a physical device and consists of one or more entities.
Reference
Thank you so much for that! Here is a working template that I have in my configuration.yaml:
- name: "Activity Devices Count"
unit_of_measurement: "Devices"
state: >
{{ label_entities('activity')
| select('is_state', 'on')
| list
| length }}
You’re welcome!
Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.
For more information about the Solution tag, refer to guideline 21 in the FAQ.
For future reference, the following Community Guide explains how to format your code.
Thank you for that! I was trying to figure it out. It’s like you were trying to read my mind. Thanks again.
Can you help me with this one too? I’m trying to return all batteries that have the batteries label that have a state that is less than 30. This is what I have so far but this only returns 1 item which actually has a state of 30
{{ label_entities('batteries') | select('is_state', '30') | list | length }}
{{ label_entities('batteries') | map('states')
| map('float', 0) | select('<', 30) | list
| count }}
It starts by generating a list of entity_ids for all entities having a “batteries” label.
It executes the states
filter on each entity_id in the list.
It executes the float
filter on each state value in the list (to convert it from a string to a number). If the state value is non-numeric, it will replace it with 0.
It creates a list containing all state values less than 30.
It counts the number of items in the list.
You’re a wizard! Thanks again! This is working for me:
{{ label_entities('batteries') | map('states')
| map('float', 0)
| select('<', 40)
| list
| length }}