Template entity_id in script while

Tags: #<Tag:0x00007f326d6c8e68> #<Tag:0x00007f326d6c8cd8>

Can you use templating in a while loop for the entity_id?

I have tried this, but that is not a valid method:

dimmer_brighten_light:
  alias: Dimmer - Brighten Light
  sequence:
    - repeat:
        while:
          - condition: state
            entity_id: "{{ entity }}"
            state: "on"
        sequence:
          - service: light.turn_on
            data_template:
              brightness_step: 20
              entity_id: "{{ entity }}"
          - delay:
              milliseconds: 500
  mode: parallel
  max: 10

Your condition is always true, you will have an endless loop.

1 Like

it doesn’t work because templates are not allowed everywhere. Switch the condition to a template condition and you should be good to go

dimmer_brighten_light:
  alias: Dimmer - Brighten Light
  sequence:
    - repeat:
        while:
          - condition: template
            value_template: "{{ is_state(entity, 'on') and state_attr(entity, 'brightness') < target_brightness | default(255) }}"
        sequence:
          - service: light.turn_on
            data_template:
              brightness_step: 20
              entity_id: "{{ entity }}"
          - delay:
              milliseconds: 500
  mode: parallel
  max: 10

EDIT: Also added another variable target_brightness. If you omit that variable, it defaults to 255 and the automation will turn off when the light is fully illuminated.

I don’t understand how this loop will end? The light will be on all the time, so the while condition is always true.

yep, you’re right… but maybe that’s what he wants. :man_shrugging: I was just pointing out why the automation wasn’t working.

EDIT: I just fixed that in the template, so now it will stop when it reaches target brightness.

1 Like

The automation that starts the script will also end the script on button release

It will probably not work, because Home Assistant doesn’t adjust the brightness attribute of the light fast enough. I remember others trying this but the result was always a flaky or non-working dimming.
If the lights are ZigBee there are options like Controller X and if the lights are integrated through DeCONZ, there’s a service for smooth dimming