Rules, while loop doesn't work

Hi guys,

this community helped me a lot in the past by just reading the posts. Thank you for that! But now i can’t find a suitable answer an I’m hoping you coult help me out.

I’m trying to create a rule, that sets light scene to 0, if lights are off for 30 minutes. Of course it might happen, that lights are turned on again and the timer has to be reset.

I tried this within a rule, that is triggered by a change of the light scene, but it doesn’t set the light scene to 0.

while(Kueche_Helligkeit.state !== 0) //Kueche_Helligkeit = 0 means lights are off
{
if (timer3 !== null) {timer3.cancel()}
timer3 = null
timer3 = createTimer(now.plusMinutes(30), [|
if (Kueche_Helligkeit.state == 0) //checks if lights are really off
{
sendCommand(Kueche_Lichtszene, 0) //should set light scene to 0
}
])
}

I would be really glad if you can tell me what I’ve done wrong or how it could be done right. Thanks!

You really don’t want while loops in rules. The best rules are event driven - something happens, triggers a rule, rule does this or that and finishes immediately.

Many tasks are more easily accomplished with multiple smaller rules, don’t be afraid to break tasks up.

Alright, let’s start by using a global timer reference that survives between rules runs, and can be shared by different rules. You’ll find this use often in timer examples.

Next, have a rule that triggers on ‘lights off’.
Have that rule create a timer for 30 seconds later.

The task in the timer code is to “set light scene 0”, whatever that is.

Now have another rule that triggers on ‘lights on’.
Have that rule cancel the the timer.

2 Likes

With your hints I thought about it again and came to a working solution.
I did it without the while loop and moved the code below into another rule, which reacts on changes of brightness. And tadah! It works.

if (timer3 !== null) {timer3.cancel()}
timer3 = null
timer3 = createTimer(now.plusMinutes(30), [|
if (Kueche_Helligkeit.state == 0) //checks if lights are really off
{
sendCommand(Kueche_Lichtszene, 0) //should set light scene to 0
}
])

Thanks!