How to get the state of lights (on/off) as a condition with the area_id?

So I have an automation that takes the area_id of the trigger:


And fires that

What I’d like to do is use this same area_id and use it as a condition, so the automation only fires if the lights are off.

Something like…

{{is_state('light.area_id(trigger.entity_id)', 'on')}}

But it isn’t translating that area_id(trigger.entity_id) to the area_id and interpolating it into the entity name.

Is there any way to do this?

Thanks in advance!

You want the condition to confirm that all lights in the given area_id are off?

Yes, exactly.

{{ expand(area_entities(area_name(trigger.entity_id)) | select('match', 'light'))
   | selectattr('state', 'eq', 'on') | list | count == 0 }}

It works, thank you!

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic is resolved. This helps other users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.

1 Like

For some reason area_name did not work for me, but area_id did work. So just in case someone else faces the same problem:

{{expand(area_entities(area_id(|select('match', 'light'))|selectattr('state', 'eq', 'on')|list|count == 0}}

That’s odd because area_name accepts the id of a device, entity, or area and returns an area name. area_entities accepts an area name or id.

Thanks for the head start @123.

To elaborate on this. I wanted to see if any light in the house is on. So I used the light domain to do this.

But some lights (bar1 to 6) are joined as a group, so I wanted to exclude those to keep the count correct.

Unfortunately I could not find a (working) way to exlclude these entities using some sort of (regular)expression.

{% set excluded_lights = ['light.bar1_light', 'light.bar2_light', 'light.bar3_light', 'light.bar4_light', 'light.bar5_light', 'light.bar6_light'] %}
{{ expand(states.light)|rejectattr('entity_id', 'in', excluded_lights)|selectattr('state', 'eq', 'on')|list|count}}