I’m trying to create an automation that’s easy to maintain. Specifically, one where I can create a mapping of “key device” to a list of “value” devices, and I want to say if any of the associated “value” devices are in a different state to their “key” device, the “key” device should re-enforce it’s status.
I do this because sometimes Zigbee signals don’t necessarily get through (in groups). So if I have a group containing, say, 18 devices, it may be that 3 or 4 didn’t change their status with the rest. It happens. I want to run this automation periodically to ‘rectify’ the status of the switch with the devices it controls.
Here is my sample script:
variables:
switches:
"light.driveway_lights": [
"light.post_1_light_small",
"light.post_1_light_medium",
"light.post_1_light_tall",
"light.post_2_light_small",
"light.post_2_light_medium",
"light.post_2_light_tall",
"light.post_3_light_small",
"light.post_3_light_medium",
"light.post_3_light_tall",
"light.post_4_light_small",
"light.post_4_light_medium",
"light.post_4_light_tall",
"light.post_5_light_small",
"light.post_5_light_medium",
"light.post_5_light_tall",
"light.post_6_light_small",
"light.post_6_light_medium",
"light.post_6_light_tall",
"light.driveway_lights_slave",
]
"light.porch_lights": [
"light.porch_left_lights_small",
"light.porch_left_lights_medium",
"light.porch_left_lights_tall",
"light.porch_right_lights_small",
"light.porch_right_lights_medium",
"light.porch_right_lights_tall",
]
"light.rear_door_lights": [
"light.rear_door_left_light_left",
"light.rear_door_left_light_right",
"light.rear_door_right_light_left",
"light.rear_door_right_light_right",
]
"light.deck_post_lights": [
"light.deck_post_left_light_small",
"light.deck_post_left_light_medium",
"light.deck_post_left_light_tall",
"light.deck_post_right_light_small",
"light.deck_post_right_light_medium",
"light.deck_post_right_light_tall",
]
action:
{%- for switch in switches -%}
{%- set switch_state = states(switch) -%}
- if:
- condition: or
conditions:
{%- for entity in switches[switch] -%}
- condition: device
{%- if switch_state -%}
type: is_off
{%- else -%}
type: is_on
{%- endif -%}
device_id: "{{ device(entity) }}"
entity_id: "{{ entity }}"
domain: "{{ entity.split('.')[0] }}"
{%- endfor -%}
then:
{%- if switch_state -%}
- type: turn_on
{%- else -%}
- type: turn_off
{%- endif -%}
device_id: "{{ device(switch) }}"
entity_id: "{{ switch }}"
domain: "{{ switch.split('.')[0] }}"
{%- endfor -%}
However, it won’t let me put the jinja code (the for in this case) after the action: - which I need it to be able to expand into multiple if statements.
Sure, I could easily create a separate if statement for each switch mentioned in the variables, but the idea of this is to be easily maintainable. I should be able to add a new entry to ‘switches’ and reload automations and have it ‘Just Work’ ™ to update the actions part.
How would I go about achieving this?