I want to store the last successful run (one of the conditions of the if clause is met) to the variable “letzterDurchlauf”. When the rule is triggered next time from the motion sensor I want to access the DateTime of the last successful run using this.letzterDurchlauf. But the variable “letzterDurchlauf” does not get the DateTime set in the last run with "this.letzterDurchlauf = time.ZonedDateTime.now(). It contains the value of the initialization of the actual run and not the value of the last run.
The workaround would be to store the state in a switch item which will be set to OFF at midnight and set to ON after the last successful run. But I wonder that I cannot use the context “this” to store the last execution which I set to “now” after the last successful run. I know that this way would not “survive” a restart or changes of the rule - which is stated here - OH 3 Examples: Writing and using JavaScript Libraries in MainUI created Rules
this.letzterDurchlauf and letzterDurchlauf are the same reference inside your Script-instance. And the first thing you do is to set letzterDurchlauf to now.
If I’m not wrong something like this is what you want:
var jetzt = time.ZonedDateTime.now();
// Das "if" ist keine Schleife sondern eine Bedingung
console.log("Letzter Durchlauf (vor Schleife):", this.letzterDurchlauf);
console.log("Jetzt (vor Schleife):", jetzt);
if (this.letzterDurchlauf === undefined || this.letzterDurchlauf.isBefore(jetzt.minusHours(12))) {
// this.letzterDurchlauf could be undefined at this point
console.log("Letzter Durchlauf (Schleife) 1.Wert:", this.letzterDurchlauf);
this.letzterDurchlauf = jetzt;
console.log("Letzter Durchlauf (Schleife) 2.Wert:", this.letzterDurchlauf);
}
console.log("Letzter Durchlauf (ausserhalb Schleife):", this.letzterDurchlauf);
Be aware that your statement is true every 12 hours.
Hi David,
for sure if contains a condition and not a loop - I just copied the comments from a loop and did not changed it for now
Just tried your suggestion (and changed the condition to jetzt.minusMinutes(1)) and the result is the following:
2022-01-26 21:45:56.073 [INFO ] [org.openhab.automation.script ] - this.Letzter Durchlauf (vor Zuweisung): “2022-01-26T21:45:56.060+01:00[SYSTEM]”
Thanks David and Rich for your suggestions. I found the fault. The order of the conditions in the IF statement is important. After I gave the conditions of undefined and null to the first and second place and the .isBefore condition to the last place, I got the correct result.