Request
Home Assistant currently limits the usefulness of expand
when used in Template Sensors.
As opposed to how it currently works, it should expand the group first and then create listeners for each entity in the group.
I believe the code responsible for identifying entities within a template is here. It’s a complex regex pattern that (if I understand it correctly) creates a capturing group containing all entities requiring listeners.
The regex pattern would need to be enhanced so that it recognizes the presence of expand()
and then proceeds to extract its members. It’s a non-trivial challenge because determining a group’s membership is well beyond what the regex pattern currently does.
Background
The expand
function reveals a group’s members. For example, this template:
- expands the
my_lights
group - select all of the group’s entities that are
on
- displays the result as a list of State objects.
{{ expand('group.my_lights') | selectattr('state', 'eq', 'on') | list }}
It’s the first step, expanding the group, that is so very useful because it simplifies code maintenance (i.e. makes your life easier). It lets you define a group then expand that group in automations, scripts, etc. If you add a new entity to the group, you do not have to revise all the automations, scripts, etc where the group was used. Excellent! Unfortunately, this does not currently work properly with a Template Sensor (or any other Template-based integration).
At startup, Home Assistant examines all Template Sensors and identifies the entities that must be monitored. Unfortunately, the only entities it will detect in the previous template are no entities at all. It will not expand the group and identify the entities within the group.group.my_lights
The current workaround is to list all of the group’s members in the entity_id
option.
- platform: template
sensors:
all_lights:
friendly_name: 'Lights'
entity_id:
- light.kitchen
- light.foyer
- light.garage
- light.hallway
- light.bathroom
- light.porch
- light.patio
value_template: >-
{{ expand('group.my_lights') | selectattr('state', 'eq', 'on') | list | count }}
However, this workaround loses the advantage of having created a group because now the group’s members have to be repeated in entity_id
. Effectively, you’ve defined the group in more than one place.
Ideally, when Home Assistant encounters expand('group.whatever')
in a Template Sensor, it should expand the group and create listeners for each entity within the group (and not a listener for the group itself, as it currently does).
EDIT
Correction. As per pnbruckner’s explanation below, I’ve now indicated that the result of the template above is a list of State objects (i.e. each group member is represented by its full State object, not simply its entity_id). To get a comma-delimited list of entity_ids you would need to use a few more filters in the template: