How to execute rule when multiple actions occur with a certain time frame

Hi All,

I was wondering if someone could help me out. I wanted to see if it’s possible that if two actions occur within a certain time frame then turn some lights on.

Basically, I want certain lights to turn on when the following two events happen within 5 minutes of each other:
Phone is updated to ON
Front door sensor is updated to OPEN

Thanks for any advice

var Timer phoneTimer = null
var Timer doorTimer = null

rule "Phone updated to ON"
when
    Item Phone received update ON
then
    // Timer is running, the door sensor triggered five minutes or less ago
    if(doorTimer != null && !doorTimer.hasTerminated){
        Lights.sendCommand(ON)
    }

    // Create a Timer for the other event
    else {
        phoneTimer = createTimer(now.plusMinutes(5), [| phoneTimer = null])
    }
end

rule "Door updated to ON"
when
    Item Door received update ON
then
    // Timer is running, the door sensor triggered five minutes or less ago
    if(phoneTimer != null && !phoneTimer.hasTerminated){
        Lights.sendCommand(ON)
    }

    // Create a Timer for the other event
    else {
        doorTimer = createTimer(now.plusMinutes(5), [| doorTimer = null])
    }
end

It could be further collapsed using a lambda but I wanted to keep this simple.

Theory of Operation:

When one of the sensors triggers, it sets a five minute Timer. When the other sensor triggers, it looks to see if there is a running Timer for the other sensor. If there is we know that the other sensor went off less than five minutes ago so turn on the light. The Timer itself doesn’t do anything but reset itself to null when it expires.

2 Likes

You rock thank you!