I have an issue with a timer rule and although I think this should be quite simple and there are some examples available I cannot get it running properly.
I have a bedroom lamp and when I turn it on it should turn off after 180 minutes. I found a working example for this and it works. However it runs into an issue if I manually turn the lamp off and on again while the timer is running.
My expected behavior is: When I manually turn the lamp off and on while the timer is running the 180 minutes timer should reset and start again.
So I tried it with this but the lamp does not turn off:
rule "Bloom Light Timer"
when
Item Light_B_Bloom changed
then
//reset timer if triggered again
if(varTimer!=null) {
varTimer.cancel
varTimer = null
}
if (Light_B_Bloom.state==ON) {
//Do something immediatelly
logInfo( "FILE", "RULE: Bloom Lamp started, 180 minutes timer active")
sendTelegram("bot1", "Bloom Lamp started, 180 minutes timer active")
//Do Something in 3h hours
varTimer = createTimer(now.plusMinutes(180)) [|
if (Light_B_Bloom.state==ON) {
sendTelegram("bot1", "Bloom Lamp turned off after 180 minute timer expired")
sendCommand(Light_B_Bloom, OFF)
}
]
}
end
It is based on a code example I found somewhere in the forum claiming that it works, but no luck for me
Also maybe someone could tell me if the variables in rules indeed persist. “varTimer” is defined in this rule and based what I read in the forums in order to reset/cancel the timer I can do this also in the same rule when it gets executed again.
If this is true, would there be an issue if I use the variable name “varTimer” also in another rule or rulefile?
At the top of the rule file, after any imports and not in a rule, do you have this?
var Timer varTimer = null
This is a global variable. If you need to use something similar in another rule, you should be more specific in the naming, like bloom_light_timer. From the looks of it, you (or the original poster of the example that you got the rule from) may have had a typo.
rule "Light timer start"
when
sLight changed from OFF to ON
then
sLightTimer.postUpdate(ON)
end
rule "Light timer switch off"
when
sLightTimer received update
then
if (sLightTimer.state == OFF){
sLight.sendCommand(OFF)
}
end
Everytime the light is switched on, the timer item is reset.
When the timer expires, switch the light off.
If you switch it off manually before the timer expires, the timer will have no effect after the 180 minutes apart from sending another OFF command to a light that is already switched off.
If you switch it on again before the timer had expired, it receives another update and resets back to the preset expiration time.
I tried the expire binding but unfortunately this is not working if the switch is commanded via alexa and it is untagged to avoid duplicate names.
expire command works only if comanded via openhab.