Bedroom motion sensor rule

You don’t need to cancel motionTimer inside motionTimer’s lambda. The motionTimer has already triggered, there is nothing to cancel. Just don’t do anything and set motionTimer to null at the end.

It helps to treat [ ] as a new context just like { } and indent all the code between them. It really helps one understand what the context is.

Consider failing fast. This can shorten Rules and reduce the number of indents leading to over all simpler Rules. For example, “Motion sensor while sleeping” only does something if the Sun is OFF and MotionSensor is ON. So

when
    if(Sun.state != OFF || MotionSensor.state != ON) return;

    SleepWalk = if(Door.state == ON) 1 else 0 // this is a ternary operator
    logInfo("sleepwalk", "sleepwalk = " + SleepWalk)

end

The above is part of Design Pattern: How to Structure a Rule. The same can be applied to the Motion Sensor Rule to simplify it a little bit as well.

Using Design Pattern: Expire Binding Based Timers could also simplify things a little bit as it will move the Timer body to it’s own Rule.

2 Likes