Looping light from dim to bright while holding button?


I’m trying to create an automation that will dim my light from 1-254 and loop that while a device is in state ‘on’ and break the loop as soon as the device turns to ‘off’. Does anyone know if this is possible and how to do it?

Here is some pseudo code showing what I wanner do:

i = light.brightness
way = up
while ( state( button, 'on' ) ):
  if ( i == 254 ):
    way = down
  if ( i == 1 ):
    way = up
  if ( way == up ):
  if ( way == down):
  light.brightness = i

It’s been done by @Danielhiversen.
I think it’s posted in the xiaomi gateway thread.

I’m doing that with AppDamon: Rotating brightness for lights triggered by events
And here’s another solution using AppDaemon: App that cycles a lights brightness between max and min while a button/switch is held down

Nice thanks! That is working great.