Example of a Lambda Function for timing the turning on and off of Lights (or switches)

An alternative approach, if the timeout on your lights remains fixed, is to use the Expire bindings. That will eliminate the need to create and track any Timers at all. I’ve updated my Motion Sensor Design Pattern to show how it would work with Expire.

Your lambda handles the case where the time the light stays on can change based on time of day or some other criteria so the Expire binding might be of limited use. But if you only have one timeout value times I would probably do something like the following (NOTE: I don’t use Dimmers so don’t know if Dimmers work differently with the Expire binding, I’d love for someone to confirm it works):

Item

Dimmer landingMain { channel="...", expire="60s,command=0" } // command=OFF might work too

Rule
Note: I use Time of Day below to detect night.

val int landingNightBrightness = 10 // if the value doesn't change, make it a constant using val

rule "Landing LA Motion Detection"
when
    Item AeonS6MotionLA changed to OPEN // assumes the motion sensor changes back to CLOSED at some point, not all do in which case use received update or use Expire to turn Motion Sensor Item back off
then
    logInfo("Aeon Motion", "Landing Detected!")

    if(LandingMotionEnabled.state == ON) {
        if(TimeOfDay.state == "NIGHT") landingMain.sendCommand(landingNightBrightness)
        else landingMain.sendCommand(100)
    }
    else {
        logInfo("Landing Light", "Landing Light Motion Disabled - ignoring")
    }
end

Note: I made some minor changes to eliminate some unnecessary lines of code. For example, by using changed to OPEN there is no need to check if the motion sensor is OPEN in the rule nor a need to log out the motion sensor’s state. By swapping to check if the LandingMotionEnabled is ON instead of OFF there is no need for the return false and frankly the else is only needed if you want to keep the log statement.

The above is complete. No timers, no lambdas, no extra complexity. I highly recommend using Expire if the Timer time is fixed. Use of Expire and some minor changes to the rule described in the note has taken this from 56 lines of code (not counting blanks) to 14.

If the Timer time is not fixed, I recommend using the above lambda.

3 Likes