Toggle Automation

I have a device relay that I need to toggle every 2 hours, so I’ve set up an automation for that purpose. However, since the device is located in a remote area of the house, there are times when it goes offline. To address this issue, I have included a delay in the automation, ensuring that it waits for the device to come back online before toggling it.

However, I’m concerned about what would happen if the device doesn’t come back online before the next scheduled trigger. Will two instances of the automation run simultaneously? How can I prevent this from happening? Is there a better approach to achieve my goal?

You decide this with the ‘mode’ setting (if you’re using the UI it’s under the 3 dot menu as ‘change mode)’. The default is single, which means the automation will only run one at a time (and if it triggers again while it’s currently running, it won’t run again).

2 Likes

You can also specify a timeout if you use a wait or wait for trigger. Just make this less than 2 hours.

https://www.home-assistant.io/docs/scripts#wait-timeout

1 Like

I assume the device is modeled as a switch in Home Assistant. When the switch is offline, is its state reported as unavailable?

If it is then I have a suggestion that doesn’t require the automation to employ a delay or other methods of waiting.


EDIT

Trigger-based Template Sensor

template:
  - trigger:
      - platform: time_pattern
        hours: '/2'
    binary_sensor:
      - name: Toggler Schedule
        state: "{{ iif(this.state | default('off', true), 'on', 'off') }}"

Automation

alias: example
trigger:
  - platform: state
    entity_id: binary_sensor.toggler_schedule
    from:
      - 'on'
      - 'off'
    to:
      - 'off'    
      - 'on'
  - platform: state
    entity_id: switch.your_switch
    from:
      - 'unavailable'
condition: []
action:
  - service: "switch.turn_{{ states('binary_sensor.toggler_schedule') }}"
    target:
      entity_id: switch.your_switch

If the switch becomes unavailable when it disconnects from the network, the moment it reconnects and its state changes, the automation sets it to the correct state based on whether the current time is within an off period or on period (where the period is 2 hours).