This is why it is so important to get the curly brackets right. One way to ensure that is to use proper indentation so you can see where the different contexts start and end.
Here is your rule, as written, with proper indentation.
var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.Rule Name");
var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");
logger.info("Temp Timer Alert Rule Started");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");
var now = ZonedDateTime.now();
var runme = function(){
logger.info("Email Sent");
var Actions = Java.type("org.openhab.core.model.script.actions.Things");
var mailActions = Actions.getActions("mail","mail:smtp:SMTP_Server");
mailActions.sendHtmlMail("xxx@gmail.com", "Timer Cancel Test", "Test");
this.timer = undefined; // reset the timer back to undefined
}
logger.info("this.timer = " + this.timer);
if(this.timer === undefined)
if(items["Temperature_Second_Floor"] > 80) {
this.timer = ScriptExecution.createTimer(now.plusSeconds(900), runme);
}
else {
if(items["Temperature_Second_Floor"] < 79)
this.timer.cancel();
}
logger.info("this.timer = " + this.timer)
Now perhaps you notice the error? this.timer.cancel()
is only called in a block of code where this.timer
can only ever be undefined
. Nothing. but a log statement is executed when this.timer
isn’t undefined
and you can’t call cancel()
on something that is undefined
.
Do you mean that else clause to go with that first if statement?
if(this.timer === undefined) {
if(items["Temperature_Second_Floor"] > 80) {
this.timer = ScriptExecution.createTimer(now.plusSeconds(900), runme);
}
}
else {
if(items["Temperature_Second_Floor"] < 79) {
this.timer.cancel();
}
}
Notice how all the if statements now have { }. Before it wasn’t really clear which if statement you intended the else clause to go with. Adding the indentation above showed that it went with the second if statement. By adding { } I have forced the else to go with the first if statement. It also makes it more clear to humans reading the code which one it goes with.
And even if you make a mistake, the indentation shows your intent, it shows which if you intend the else to go with and that makes it easier for you or us to spot missing {} type errors.
Maybe the code makes more sense to human readers if we reorder the checks…,
if(items["Temperature_Second_Floor"] > 80) {
if(this.timer === undefined) {
this.timer = ScriptExecution.createTimer(now.plusSeconds(900), runme);
}
}
else if(items["Temperature_Second_Floor"] < 79) {
if(this.timer !== undefined){
this.timer.cancel();
}
}
In either case notice how proper indentation and use of curly brackets makes it much easier to tell what is going on. It’s not just to make the code pretty; it’s vital to make the code understandable.