One more timer question

I know this issue has been discussed many times but I guess I am too old to see what I am doing wrong.
I have a motion sensor it is normally closed, it opens when it senses movement.
I want to program a script to set the state as occupied when motion is detected and empty after 10 minutes of no motion detection.

This is my script, which is triggered every time there is a change in the state of the motion sensor

var Timer ktimer
if(Sensors_KitchenMotionSensor.state == CLOSED){
ktimer = createTimer(now.plusSeconds(600), [|
          KitchenOccupancy.postUpdate("EMPTY")])
  }
else
{
KitchenOccupancy.postUpdate("OCCUPIED")
if(ktimer != null){
ktimer.cancel
ktimer=null
}
}

The timer never gets cancelled, on the first movement (open) signal the status changes from empty to occupied and 10 minutes later it goes back to empty no matter how many times the sensor detects movement.

Thank you

You can’t define ktimer locally, it has to be a global var. Therefor, if you want a timer which can be cancelled, you have to use a rules file:

var Timer ktimer = null  // set global vars on top of first rule in file

rule "Motion sensor"
when
    Item Sensors_KitchenMotionSensor changed
then
    ktimer?.cancel
    if(Sensors_KitchenMotionSensor.state == CLOSED) {
        ktimer = createTimer(now.plusSeconds(600), [ |
            KitchenOccupancy.postUpdate("EMPTY")
        ])
    } else {
        KitchenOccupancy.postUpdate("OCCUPIED")
    }
end

Thank you, one more question, what does the ? in
ktimer?.cancel

mean, I had not seen that before

Null safe feature call

Only call the method on a non null object. Saves you from doing if timer !== Null