While loop - max amount of times to loop

Hi all,

alias: Garage door sensor - open
description: ""
trigger:
  - type: opened
    platform: device
    device_id: 20c899214f655d89e75f88f732f4a0d4
    entity_id: binary_sensor.contact_sensor
    domain: binary_sensor
    for:
      hours: 0
      minutes: 30
      seconds: 0
condition:
  - type: is_temperature
    condition: device
    device_id: 82a5c3f3fde79af293a92d5aaa5bc632
    entity_id: sensor.tv_outside_temperature
    domain: sensor
    below: 12
action:
  - repeat:
      while:
        - type: is_open
          condition: device
          device_id: 20c899214f655d89e75f88f732f4a0d4
          entity_id: binary_sensor.contact_sensor
          domain: binary_sensor
      sequence:
        - service: tts.cloud_say
          data:
            message: gherejno darvajo bandh karo
            language: gu-IN
            entity_id: media_player.nestmini0148
        - delay:
            hours: 0
            minutes: 0
            seconds: 15
            milliseconds: 0
  - service: notify.mobile_app_sm_s908b
    data:
      title: Garage door is open sensor
      message: Garage door is open sensor
mode: single

I am trying to make this say “close the door” (in Gujurati for my grandma) whilst the door sensor is open. However, I’d like it to do this 10 times maximum. How can I do this? Not sure whether I could just use a ‘variable’ as usual with a while loop inside the while loop?

Add a second condition to while that confirms the value of repeat.index is less than or equal to 10.

The following example uses a Template Condition in shorthand notation to check if repeat.index is <= 10.

action:
  - repeat:
      while:
        - type: is_open
          condition: device
          device_id: 20c899214f655d89e75f88f732f4a0d4
          entity_id: binary_sensor.contact_sensor
          domain: binary_sensor
        - "{{ repeat.index <= 10 }}"
      sequence:

Reference: repeat - while

Thanks very much!

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic is resolved. This helps other users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.