I have integrated my HUE System into openHab, using the presence detection (HUE-Motion) to
switch lights ON or OFF. Therefore I have written a simple “Switch OFF” rule.
It’s working but I don’t like the coding, also my feeling is sometimes it’s no working as expected.
What I’m looking for is the following:
If some is leaving the room and presence changed to OFF, start a 60 sec countdown, if no-one returns switch the light off, if someone returns within the 60 sec, cancel the rule.
Here is my coding
rule "Presence in Kitchen switched to OFF"
when
Item KMotionPresence changed to OFF
then
if(LightRoofKitchen.state == ON){
Thread::sleep(30000)
logInfo("RULE", "Presence is waiting 1")
if(KMotionPresence.state == OFF){
Thread::sleep(30000)
logInfo("RULE", "Presence is waiting 2")
if(KMotionPresence.state == OFF){
logInfo("RULE", "Light switched OFF, because of no presence")
LightRoofKitchen.sendCommand(OFF)
}
}
}
end
This item, when turned ON will turn itself OFF after 1 minute unless updated to ON
So, knowing that, your rule becomes:
rule "Presence in Kitchen changed"
when
Item KMotionPresence changed
then
KMotionPresence_Timer.sendCommand(ON) //Start timer whenever presence changes in the Kitchen
end
rule "Kitchen Presence Timer expires"
when
Item KMotionPresence_Timer changed to OFF
then
if(KMotionPresence == OFF && LightRoofKitchen.state == ON) {
logInfo("RULE", "Light switched OFF, because of no presence")
LightRoofKitchen.sendCommand(OFF)
}
end
The logic issue in the original rule posted is that while the “sleep” is running, additional triggers can take place.
Additional copies of your rule will start up, each coming to a sleep/wait. (This is a bad, resource-consuming idea as already pointed out).
As those sleeps run out, each rule will try to turn OFF the light based on what presence is now, and ignoring anything that happened in the meantime.
To fix the logic error, you need a way to reset, cancel, or restart the timing when something happens during the waiting time.
The expire method takes care of that for you.
There are other ways too, if you prefer not to create an additional Item.