How to break a repeating loop without waiting for delay to end

I have an automation, which triggers when my bedroom window is opened for more than a certain period (calculated value). When it does, it runs this script:

alias: Bedroom window
sequence:
  - service: mopidy.snapshot
    data:
      entity_id: media_player.mopidy
  - service: media_player.volume_set
    target:
      entity_id: media_player.mopidy
    data:
      volume_level: 1
  - repeat:
      until:
        - condition: state
          entity_id: sensor.bedroom_window_closed
          state: 'True'
      sequence:
        - service: tts.microsoft_say
          data:
            entity_id: media_player.mopidy
            message: Hey, close the bedroom window!
        - delay: '00:03:00'
  - service: mopidy.restore
    data:
      entity_id: media_player.mopidy
mode: single

Everything works OK, what annoys me is, that when I close the window, I have to wait for delay in the loop to pass before mopidy gets restored (especially annoying, if I close it just after the loop restarted, as it takes whole three minutes to the end).
Is there any way to “break” the loop as soon as the sensor changes?
Or any other idea, how to achieve he same script behaviour with annother approach?

Instead of the 3 minute delay try using a wait for trigger node with time out enabled like this.

alias: Bedroom window
sequence:
  - service: mopidy.snapshot
    data:
      entity_id: media_player.mopidy
  - service: media_player.volume_set
    target:
      entity_id: media_player.mopidy
    data:
      volume_level: 1
  - repeat:
      until:
        - condition: state
          entity_id: sensor.bedroom_window_closed
          state: 'True'
      sequence:
        - service: tts.microsoft_say
          data:
            entity_id: media_player.mopidy
            message: Hey, close the bedroom window!
        - wait_for_trigger:
            - platform: state
              entity_id: binary_sensor.window
              to: 'off'
          timeout: '00:03:00'
  - service: mopidy.restore
    data:
      entity_id: media_player.mopidy
mode: single

Please change the binary sensor entity to your window sensor

4 Likes

Great idea, just tried it and it works perfectly. Thx for your input!