How to create group of entities which can then be used in various places in HA?

I feel that I’m duplicating code and an wondering if there is a better way to do it.

I have created a group of lights, starting with all lights and then filtering out some:

{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.friendly_name', 'contains', 'Air Quality') | map(attribute='attributes.friendly_name') }}

I have used this group to create a numeric sensor:

{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.friendly_name', 'contains', 'Air Quality') | map(attribute='attributes.friendly_name') | list | count }}

I have used this group to enumerate a list of all these lights in a notification message:

{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.friendly_name', 'contains', 'Air Quality') | map(attribute="attributes.friendly_name") | join(', ') }}

I’m concerned that when I want to filter out additional lights in the future that I’ll have to do this is multiple places and it will become untenable.

Is there a way that I can not duplicate the code used to create this list of entities?

1 Like

One simple and reliable method is to store the list in an attribute of a Template sensor.

template:
  - binary_sensor:
      - name: On Lights
        state: |
          {{ states.light | selectattr('state', 'eq', 'on') 
          | rejectattr('attributes.friendly_name', 'contains', 'Air Quality') 
          | list | count > 0 }}
        attributes:
          entity_id: | 
            {{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.friendly_name', 'contains', 'Air Quality') 
            | map(attribute='entity_id') | list }}

You can use any attribute name you like, I’ve used entity_id so it matches the way existing group helper and group entities work.

1 Like

Thank you for the suggestion. How do I then use the data placed into the entity attribute to reduce code duplication when I wish to use this list of entities when creating a new entity?

In this example, use:

{{ is_state('binary_sensor.on_lights', 'on') }}

to return true if any of your selection is on, and:

{{ state_attr('binary_sensor.on_lights', 'entity_id') }}

to access the list.

Your bedtime reading:

3 Likes