How to use trigger instead of until loop?

Hi. I am trying to wrap my head around how best to do what I am wanting to do, my example below is not quite right.

What I want to happen is:

  1. the sound “wrong answer” to be played when the door is open.
  2. Wait for 10 seconds.
  3. If the door is closed at the end of this first 10 seconds then end the automation.
  4. otherwise “call to attention” sound should be played every 10 seconds until the door is closed.
  5. play the “oh finally” sound IMMEDIATELY when the door is closed, even if the 10 second delay in step 4 has not elapsed.

What is happening is that the “oh finally” sound is played only at the end of the 10 second “until” loop. Obviously the “delay” statement in the loop is the reason for this because the door state is only evaluated every 10 seconds. What I want is for the loop to exit immediately if the door is closed. I think I need to use a timer or a trigger, instead, but I am not really understanding how to go about this.

Thanks! :slight_smile:

alias: 000 new automation for hallway door
description: ""
trigger:
  - platform: state
    entity_id:
      - binary_sensor.door_03_opening
    from: "off"
    to: "on"
action:
  - service: media_player.play_media
    data:
      media_content_id: media-source://media_source/local/wrong-answer-129254.mp3
      media_content_type: music
    target:
      entity_id:
        - media_player.downstairs
  - delay:
      hours: 0
      minutes: 0
      seconds: 10
      milliseconds: 0
  - condition: state
    entity_id: binary_sensor.door_03_opening
    state: "on"
  - repeat:
      sequence:
        - condition: state
          entity_id: binary_sensor.door_03_opening
          state: "on"
        - service: media_player.play_media
          target:
            entity_id: media_player.downstairs
          data:
            media_content_id: >-
              media-source://media_source/local/error-call-to-attention-129258.mp3
            media_content_type: audio/mpeg
        - delay:
            hours: 0
            minutes: 0
            seconds: 10
            milliseconds: 0
      until:
        - condition: state
          entity_id: binary_sensor.door_03_opening
          state: "off"
  - service: media_player.play_media
    data:
      media_content_id: media-source://media_source/local/oh-finally-355.mp3
      media_content_type: music
    target:
      entity_id: media_player.downstairs
mode: single

I’d add the door closing as a new trigger, give it a name, modify the actions to use a choose, and set the mode to restart. In pseudo-code

Triggers:
	doorOpen
	doorClose
Actions:
	Choose:
		Triggered by doorOpen
			Play 'wrong answer'
			Repeat every 10 seconds
				Play 'call to attention'
		Triggered by doorClose
			Play 'finally'