Error in rule "cannot invoke method public abstract boolean" - timer, motion sensor

Hello all,

I need help again.
I have created a rule that should ensure that light in a room is controlled by a motion sensor - but only when it is dark enough. For this I use the motionsensor, the illuminancesensor and a timer.
If motion is still detected after the light is switched on for the first time, the time should be extended.
If I switch the light off manually via a button, everything should be “reset” again.

Unfortunately I get now and then the following error in the log (Then it happens that I enter the room and the light does not turn on.):

Rule 'HTR Motion Sensor ON': cannot invoke method public abstract boolean org.eclipse.smarthome.model.script.actions.Timer.cancel() on null

Here are my rules:

var Timer timer = null

rule "HTR Motion Sensor ON" 
when 
    Item MotionSensorPresence changed from OFF to ON
then
    
        if((timer === null || timer.hasTerminated) && (LightLevelSensorIlluminance.state < 10|lx)) {
            timer = null
            GF_LaundryRoom_Light.sendCommand(ON)
            logInfo("Licht", "HTR über Bewegungsmelder an")
        }
        else {
            timer.cancel
            timer = null
            logInfo("Licht", "HTR Bewegung erkannt -> Timer gelöscht")
            if(GF_LaundryRoom_Light.state == OFF) {
            GF_LaundryRoom_Light.sendCommand(ON)
            logInfo("Licht", "HTR Licht AN nach manuellem AUS")
            }
        }
    
end

rule "HTR Motion Sensor OFF"
when
    Item MotionSensorPresence changed from ON to OFF
then
    logInfo("Licht", "HTR Keine Bewegung mehr erkannt -> Timer gestartet")
    timer = createTimer(now.plusSeconds(50), [ |
        timer.cancel
        timer = null
        GF_LaundryRoom_Light.sendCommand(OFF)
        logInfo("Licht", "HTR Timer abgelaufen -> Licht aus")
    ])
end

Any ideas?

Greetings

So, if timer variable is null but light level is more than 10, we will go to the else clause;

timer.cancel

and this blows up because null is null and has no .cancel method.
You can test to see if it is null before trying to cancel.
There is a handy shorthand for that -

1 Like

Thank you very much for the very quick reply. I immediately implemented your hint yesterday and tried to test all possible cases.

So far no more error messages!!!

I am always surprised how great it works here in the forum!
Thanks a lot!!!