Automation: Turn off all lights, except X

Hello!

I have an automation that turns all light off when all family members has left the house.

However, I want the lights in the windows to continue being on.

What would be a simple way of achieving this? :slight_smile:

This has worked for me. Test it in the template section once you modify the exclude.

  - service: home_assistant.turn_off
    data:
      entity_id: >-
        {% set domains = ['light','switch','fan','media_player'] %}
        {% set exclude = ['light.example1','light.example2'] %}
        {%- for device in states|selectattr('domain','in', domains)|rejectattr('entity_id','in',exclude)|selectattr('state','in','on') %}
          {%- if loop.first %}{%- else %},{% endif %}
          {{device.entity_id }}
          {%- if loop.last %}{% endif %}
        {%- endfor  %}
5 Likes

Hi, I am trying to use your script to turn off all lights except for the excluded ones. How ever the server: home_assistant.turn_off doesn’t exist. If I use homeassistant.turn_off and run it turns all lights off and doesn’t seem to exclude the list of lights I created. I tested this in the template section and the list of lights it creates is correct. Any ideas? Thanks!

It should be homeassistant.turn_off

Another way to do the same thing:

  - service: home_assistant.turn_off
    target:
      entity_id: >
        {{ expand(states.light, states.switch, states.fan, states.media_player)
          | rejectattr('entity_id', 'in',  ['light.example1', 'light.example2', 'switch.whatever'])
          | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
3 Likes

Yes agreed, but still not sure why it is simply turning all lights off I need it to execute the ignored lights

Try the template I posted above in the Template Editor.

If it lists the entities correctly, use Developer Tools > Services to test the entire service call (be sure to replace the original example’s data: with target:).

That worked perfectly not sure what I was doing wrong but this solved it, thanks so much!!

Tip:

If you have any Hue groups and you want to exclude them, you can add this line to the template:

  | rejectattr('attributes.is_hue_group', 'defined')
1 Like

Great tips, thanks. Is it a bug or is it working differently with entity helpers for grouped lights. How can I include also those?

A light group entity has an attribute named entity_id that contains a list of light entities.

What do you want to do with it?