Blockly makes it really easy to manage Timers. If you add the OHRT Block library managing Timers becomes even easier.
That’s a standard motion sensor timer. See Design Pattern: Motion Sensor Timer.
You can probably handle this use case just using Expire on the Item. When motion is detected send an ON command to the switch. Set the expire metadata on the Switch and it will turn OFF ten minutes after the last ON command.
The indentation implies that the timerCat = createTimer...
lines and below belong to the second if statement but they are outside the { }. Because it’s outside the if statements, you end up creating a new timer every time the rule runs but you only end up canceling it if the second if statement is true. That may be fine but you really should use consistent indentation for readable code.
Only indent when there’s a new context. So lines after a (, [, or { should be indented and then the indentation removed after the corresponding ), ], and }. Your indentation is all over the place making the intent and actual implemetation of the rule hard to understand.
Presumably you’d only want to run this rule at all when the CatMotion Item is updated to ON so add that to the trigger and you don’t have to test for it.
Item CatMotion received update ON
If the fountain is already ON reschedule the Timer.
If the fountain is OFF, create a new Timer.
You should get in the habbit of saving Timers in the cache also.
rule "Cat Fountain"
when
Item CatMotion received update ON
then
var timer = privateCache.get('timer'); // get the timer, null if there is no timer
// command the fountain to ON if it isn't already
if(LivingRoomFountain.state != ON) {
LivingRoomFountain.sendCommand(ON)
}
// if there is no timer, create one
if(timer === null) {
privateCache.put('timer', createTimer(now.plusMinutes(10), [ |
LivingRoomFountain.sendCommand(OFF)
privateCache.put('timer', null)
])
}
// there already is a timer, reschedule it
else {
timer.reschedule(now.plusMinutes(10))
}
end
Note, I recommend against new development of rules in Rules DSL. It has become a substandard language for rules development. If you are not a great programmer I recommend Blockly. If you are a programmer any of the other languages will serve you better.
Unfortunately, it’s saying the error is happening at the very top of the code (line 0, column 0). But because it’s comming from the scheduler uit might be complaining about the first line of the timer.
I do notice you are missing the |
in your lambda definition. That might be the issue. I don’t know for sure. I haven’t used Rules DSL for years now and I’m getting rusty on all of the many many quirks of the language.
Note, a rescheduled timer is really easy in Blockly. It’s just a single block and all the tracking and cancelling and rescheduling stuff is handled for you: