When searching for a good way to turn off all lights except x, y and z I didn’t find any solutions that are functional and easy configurable at the same time.
So this is a minimal example of my approach. Everything is configured in one config file (scripts.yaml) and easy to maintain for future changes. This method can be adapted for other device classes as well. If you want to turn off all media players or switches excluding some entities, just change the service call in line 4 and the exclude list below.
Prerequisite: This approach requires the service to accept entity_ids as comma separated lists. At the time of writing I successfully tested this with the light, switch and media_player turn_on & turn_off service calls. There maybe others as well, but be prepared, that it might not work for your use case.
all_out:
sequence:
- service: light.turn_off
data_template:
entity_id: >
{% set exclude_light = [
'light.house_number',
'light.aquarium',
'light.entrance'
] %}
{%- for device in states.light|rejectattr('entity_id','in',exclude_light)|rejectattr('state','in','off') %}{%- if loop.first %}{%- else %}, {% endif %}{{device.entity_id }}{%- if loop.last %}{% endif %}{%- endfor %}
Some explanation for the data_template:
set exclude_light
is a list of entity_ids that shouldn’t be affected by the script, i.e. excluded. You won’t get errors, if you forget to delete the comma after the last entry, but of course it’s good programming style if you remember to do it.
states.light|rejectattr('entity_id','in',exclude_light)|rejectattr('state','in','off')
is a set of (jinja) filters for objects.
It starts with all light entity objects known to HA (states.light
). The first filter excludes all light entities from the list with an entity_id
contained in the exclude_light
list defined before: “…|rejectattr('entity_id','in',exclude_light)
…”
The second filter excludes all lights which are already off and don’t need to be switched off again: “...|rejectattr('state','in','off')...
”. You may omit this filter, as it not crucial for the template to work, but just turning off devices that actually need to be turned off significantly reduces the noise on the HA event bus if you have a lot of devices in your config.
The filtered list is fetched to the for
loop. The loop concatenates the entity_ids ({{device.entity_id }}
) of the remaining entities to a comma separated list, omiting commas for the first ({%- if loop.first %}{%- else %}, {% endif %}
) and the last ({%- if loop.last %}{% endif %}
) loop pass to suppress commas before the first and after the last entity_id.