I’ve setup a rule that notifies me when I left the bathroom window open cause I often forget to close it. The rule should remind me after half an hour and then every 15 minutes if the window still has not been closed. The following code is mostly working but apparently there is one flaw that must have something to do with the context of the keyword ‘this’ in the code.
What happens is:
- I open the window
- After 30 minutes I get a notification that the window is open for 30 minutes
- I close the window (the timer should be stopped since this is what always happens when the window handle is used)
- I receive a notification that the window has been closed (bottom of the code snippet) so the closing was detected
- 15 Minutes later I receive a notification that the window is open for 45 minutes
- This goes on every 15 minutes…
=> The outcome of 5 and 6 lets me know that in fact I do not cancel the 15 minute timer that was setup in the sendNotificationAndReschedule method. However I do not really understand why… Maybe someone with better javascript skills than me can explain what I do wrong here?
var NotificationAction = Java.type("org.openhab.io.openhabcloud.NotificationAction");
var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");
// Reset timer when handle is used
if (this.timer != undefined) {
this.timer.cancel();
this.timer = undefined;
}
var sendNotificationAndReschedule = function(passedTime) {
var msg = "Badezimmerfenster ist seit " + passedTime + " Minuten geöffnet";
NotificationAction.sendBroadcastNotification(msg, "window", "Info");
events.postUpdate('window_bath_notification_active', ON);
var rescheduleTime = 15;
var reschedule = ZonedDateTime.now().plusMinutes(rescheduleTime);
this.timer = ScriptExecution.createTimerWithArgument(reschedule, passedTime + rescheduleTime, function(passedTime) {
this.timer = undefined;
sendNotificationAndReschedule(passedTime)
});
};
// Window handle was opened
if(newState != "Geschlossen") {
var in30Minutes = ZonedDateTime.now().plusMinutes(30);
this.timer = ScriptExecution.createTimer(in30Minutes, function() {
this.timer = undefined;
sendNotificationAndReschedule(30);
});
} else {
// Send window closed notification when window was reported to be open before
if(ir.getItem('window_bath_notification_active').state == ON) {
var msg = "Badezimmerfenster wurde geschlossen";
NotificationAction.sendBroadcastNotification(msg, "window", "Info");
events.postUpdate('window_bath_notification_active', OFF);
}
}
I guess I have to use call, apply or bind to explicitly set the context but this really a trial and error approach for me right now. What is generally the context of ‘this’ in a rule code?