ECMA Scripting: using averageSince

Converting my latest DSL rules to ECMA, but got stuck on my “Washing machine” rule.

if (items["Schakel_Wasmachine_Power"].averageSince(now.minusMinutes(2)) < 0.2) events.postUpdate ("Wasmachine_Status", 0);
else if (items["Schakel_Wasmachine_Power"].averageSince(now.minusMinutes(2))> 10) events.postUpdate ("Wasmachine_Status", 2);
else if (items["Schakel_Wasmachine_Power"].averageSince(now.minusMinutes(2))< 6) {
    if (items["Wasmachine_Status"] == 0) events.postUpdate ("Wasmachine_Status", 1);
    else if (items["Wasmachine_Status"] == 2) events.postUpdate ("Wasmachine_Status", 3);
}

This gives me this error:
[ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'a8095b93d4' failed: ReferenceError: "now" is not defined in <eval> at line number 1

How to define “now” ?

var ZonedDateTime = Java.type(“java.time.ZonedDateTime”);

ZonedDateTime.now()

There are three things here.

  1. items["Schakel_Wasmachine_Power"] isn’t the Item. It’s just the Item’s state. It’s not the Item itself. Even in Rules DSL you can’t call Schakel_Wasmachine_Power.state.averageSince(now.minusMinutes(2)). To get the actual Item you have to pull it from the Image registry. var myItem = ir.getItem("MyItem");.

  2. now only exists like that in Rules DSL. You have to import java.time.ZonedDateTime and then call now() to get the equivalent.

  3. Rules DSL does some sneaky magic in the background to make it appear that Items have a bunch of methods that they don’t really have. That sneakiness doesn’t exist in the other languages. That’s why you can’t use myItem.sendCommand(), for example. Persistence is the same thing. You have to use the PersistenceExtensions.

var PersistenceExtensions = Java.type("org.openhab.core.persistence.extensions.PersistenceExtensions");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");

var avg = PersistenceExtensions.averageSince(ir.getItem("MyItem"), ZonedDateTime.now().minusMinutes(2));
1 Like