[SOLVED] Increase/decrease Item value in steps until given state

This code can’t possibly be what you intend to do. Here is what it does, in English, assuming it worked as written without the error.

  1. Initialize the vol variable to 50

  2. enter a while loop that will loop from 50 to 85 (35 iterations).

  3. Inside each iteration create a Timer that goes off in 15 seconds.

  4. Inside the timer send the vol value to the Squeezebox.

As a result, you will end up with 35 Timers that in 15 seconds (plus a few milliseconds) all run at the same time and send the command to the Squeezebox at pretty much the same time.

It looks like what you are after is a Thread::sleep, not a Timer. Thread::sleep(x) vs timers in rules - #3 by rlkoshak. A Timer schedules something to take place in the future. A Thread::sleep causes the Rule to wait the given amount of time before continuing.

But Thread::sleep is a dangerous thing to use. Long running Rules can cause all sorts of problems.

So use a Design Pattern: Looping Timers instead.

var Timer volTimer = null

rule "increase volume"
when
    Time cron "0 30 10 * * ? *" or
    Item TestSwitch received command ON
then
    volTimer?.cancel

    var vol = 51
    volTimer = createTimer(now, [|
        SqueezeLivingRoomVolulme.sendCommand(vol)
        logInfo("Squeeze", "Living Room: increasing volume to " + vol)

        vol = vol + 1
        if(vol < 86) volTimer.reschedule(now.plusSeconds(15))
        else volTimer = null
    ])
end    

NOTE: The error message you are seeing is almost certainly caused by the fact that you are trying to assign a new value to a val. val means constant. You need to define vol as a var.

Also, I’m not sure if you can embed the iteration inside the while loop like that. But a while loop is not the right loop to implement this anyway. You would want to use a for loop.

for(var vol = 50; vol < 86; vol = vol + 1) {
1 Like