[SOLVED] Help understanding rules

First things first:
Use code fences when publishing code

Second, while loops and Thread:sleep inside rules are bad ideas (Especially a while loop with a Thread::sleep inside it!!)

Use this:

//// !!!!! There three variable declaration go AT THE TOP of the rules file  !!!!!
var Timer sleepTimer = null   // timer variable
var percent = 100                 //  global variable so the timer lamdba can access it
var color = 10                 //  global variable so the timer lamdba can access it

rule "Go to sleep"
when
    Item Scene_Slaapkamer changed to 9
then
    //Go from from a bright orang-red to soft red (and off)
    logInfo("GoToSleep", "Starting", Scene_Slaapkamer.state.toString)
    ColorSlaapkamer.sendCommand("10,100,100")
    percent = 100
    color = 10
    
    // No need to check if the scene number is 9 because that was the rule trigger

    if (sleepTimer === null) {                                //If there is no timer
        sleepTimer = createTimer(now(), [ |                   // then create one to start immediately
            ColorSlaapkamer.sendCommand(color.toString + ",100," + percent.toString)
            color = percent / 10
            percent = percent - 5
            logInfo("GoToSleep", color.toString, percent.toString)
            if (percent > 0) { // if the light is still ON then run the timer again in 30s
                sleepTimer.reshedule(now.plusSeconds(30))
            }
            else { // if the percent has reached 0 then we cancel the timer and turn off the light
                sleepTimer = null
                SwSlaapkamer.sendCommand(OFF)
                Scene_Slaapkamer.sendCommand(0)
                logInfo("GoToSleep", "Finshed ")
            }
        ])
    }
end
3 Likes