Run a script when a switch is toggled 4 times within 10 seconds

Hello friends,

I’m having trouble creating an automation that runs a script when a switch (switch.0xa4c138ca72662ea8) is toggled 4 times within 10 seconds.

The idea is that if I toggle the switch at the entrance four times, all the lights in the apartment will turn off. I have a script (blackout) that turns off all the switches in the apartment.

Has anyone already realized something like this and can help?

Thanks very much

One way to do this:

Create a counter, Counter - Home Assistant

Create an automation that increments this counter whenever your switch changes from off to on.

trigger:
  - platform: state
    entity_id: switch.0xa4c138ca72662ea8
    from: 'off'
    to: 'on'
action:
  - service: counter.increment
    target:
      entity_id: counter.your_counter_here

Create another automation that resets the counter whenever the switch has not changed for 10 seconds:

trigger:
  - platform: state
    entity_id: switch.0xa4c138ca72662ea8
    to: 
    for: 10
action:
  - service: counter.reset
    target:
      entity_id: counter.your_counter_here

Your third and final automation triggers if this counter ever reaches 4 and turns your lights off:

trigger:
  - platform: numeric_state
    entity_id: counter.your_counter_here
    above: 3
action:
  - service: script.blackout

If you are feeling adventurous you could combine all these automations into one with trigger ids and a choose action. However for simplicity having three automations is easier to understand.

As a final note you should change entity ids like this switch.0xa4c138ca72662ea8 to something more meaningful when you add them to home assistant, e.g. switch.front_door_lights. If you do it later you have to change the entity id everywhere you have already used it.

3 Likes

Thank you very much! That worked perfectly!

1 Like

Nice one! I tries to combine them into 1 automation and assign each trigger an Id but it does not work as it seems the whole automation is locked while one trigger is in use so only the reset trigger gets the action