Improving homeassistant.turn_off and light.turn_off

I believe that many users of home assistant are building scripts and automations to turn off all lights for bedtime or leaving the home.

Calling the services as of now takes a long time depending on the number of lights.

What I have found is that by only calling the lights that are turned on, the result is instant and a much better experience.

What I am doing right now is using a template, but I think this should just be integrated into the services. There is no reason to turn off a light that is already turned off.

service: homeassistant.turn_off
data_template:
  entity_id: >
    {% set group_id = 'light.lightgroup_indoor' %}  {% set on_states = ['on']
    %}  {{ states | selectattr('entity_id','in', state_attr(group_id,
    'entity_id')) | selectattr('state','in',on_states) |
    map(attribute='entity_id') | join(', ') }}

Slightly OT…

When states is used in a template by itself to iterate all states on the system, the template is re-rendered each time any state changed event happens if any part of the state is accessed. When merely counting states, the template is only re-rendered when a state is added or removed from the system. On busy systems with many entities or hundreds of thousands state changed events per day, templates may re-render more than desirable. From: Rate Limiting Updates

Instead you can use something like:

{% set group_id = 'light.lightgroup_indoor' %}
{% set on_states = ['on'] %}
{{ expand(state_attr(group_id, 'entity_id'))| selectattr('state','in', on_states)
| map(attribute='entity_id') | join(', ') }}
1 Like
service: homeassistant.turn_off
target:
  entity_id: >
    {{ expand(state_attr('light.lightgroup_indoor', 'entity_id'))
        | selectattr('state','eq','on')
        | map(attribute='entity_id') | list }}
1 Like