I wrote a script to switch on or off lights or switches that are in a mixed state (some are on, some are off) in an area
mixed_switch:
sequence:
- alias: set variables
variables:
# retrieve area from automation parameters
area: "{{ area }}"
# get all switches in the area
switches: "{{ expand(area_entities(area)) | selectattr('domain', 'eq', 'switch')| map(attribute = 'entity_id') | list }}"
# check which switches are on and off
count_on_switches: "{{ expand(lights) | selectattr('state','eq', 'on') | list | count }}"
count_off_switches: "{{ expand(lights) | selectattr('state','eq', 'off') | list | count }}"
# idem for lights
lights: "{{ expand(area_entities(area)) | selectattr('domain', 'eq', 'light')| map(attribute = 'entity_id') | list }}"
count_on_lights: "{{ expand(lights) | selectattr('state','eq', 'on') | list | count }}"
count_off_lights: "{{ expand(lights) | selectattr('state','eq', 'off') | list | count }}"
# depending on how many devices are on and off make the decision of the global state
light_action: "{{ iif( count_on_switches + count_on_lights >= count_off_switches + count_off_lights, 'off', 'on' ) }}"
- alias: debug variables
service: persistent_notification.create
data:
message: "{{switches}} {{count_on_switches}} {{count_off_switches}} {{lights}} {{count_on_lights}} {{count_off_switches}} {{light_action}} area: {{area}}"
title: "debug"
- alias: turn all lamps on or off
service: homeassistant.turn_{{ light_action }}
target:
area_id:
- "{{ area_id(area) }}"
The first version of this script only assessed switches and worked. This one, however, crashes with
domotique-hass-1 | 2023-02-11 20:11:23.274 ERROR (MainThread) [homeassistant.components.script.mixed_switch] mixed_switch: Error executing script. Error rendering template for variables at pos 1: UndefinedError: 'lights' is undefined
I did all kinds of tests in the Dev elopment Tools to replicate the script and all the bts work fine. For instance
{% set a = expand(area_entities('parents | lights')) | selectattr('domain', 'eq', 'light')| map(attribute = 'entity_id') | list %}
{{ expand(a) | selectattr('state','eq', 'off') | list | count }}
correctly outputs 2
(two lights in the area are indeed off).
What does the error exactly mean?