Automation/Script/Template for setting the state of switches

I imagine there are multitude of ways to accomplish this, but I’m looking for the simplest one.

I have 12 switches and I only want one to be on at any given time. So if any switch is on and I turn on a different switch, I want to make sure all other switches are off. I started down the path of creating an automation that when any switch changed state from off to on the automation would turn off all switches, then turn on the switch that initially triggered the automation. I couldn’t figure out how to know which switch changed state, which is why I started this question. As I was typing this, it occurred to me that that probably wouldn’t work anyway because the final step of turning the switch on would likely trigger the automation again, and get stuck in a loop.

The kind of brute force way would be to create a unique automation per switch that would turn off all other switches, but defining 12 automations seems like a clumsy solution.

Any suggestions?

You can filter who switches by using a template condition:
{{ trigger.to_state.context.user_id != none }}

This way the automation should only trigger when its done by a user. An automation would have no id and thus fail this template.

trigger.entity_id contains the entity_id of the switch that triggered the automation’s State Trigger. So your switch.turn_off action will use a template to identify which switch to turn off.

- action: switch.turn_off
  target:
    entity_id: "{{ trigger.entity_id }}"

Ensure the automation’s mode is set to single.

mode: single
max_exceeded: silent

Reference:

1 Like

Thank you, this gave me some key info. Using what you gave me mostly works. By that I mean since this the automation is triggered by a switch changing state to on, turning all switches off and then turning the switch that initially changed state to on again is not perfect, but I’m going to see if I can figure that our on my own.

You only need to turn off whatever is currently on, other than the switch that was just turned on. It can be done with a template.

alias: example 
triggers:
  - trigger: state
    entity_id:
      - switch.first
      - switch.second
      - switch.third
      - switch.fourth
      - switch.etc
    from: 'off'
    to: 'on'
conditions: []
actions:
  - action: switch.turn_off
    target:
      entity_id: >
        {{ ['switch.first', 'switch.second', 
            'switch.third', 'switch.fourth', 'switch.etc']
          | reject('eq', trigger.entity_id)
          | expand 
          | selectattr('state', 'eq', 'on')
          | map(attribute='entity_id')
          | list }}
1 Like