event.itemState == "ON" always false

I’m not sure what I’m doing wrong here. The if condition testing the implicit variable event.itemState always returns false even when the trigger item changed to ON:
2025-01-02 20:29:28.492 [INFO ] [penhab.automation.script.ui.Daemmrig] - Dämmrig = ON

Here’s my short script:

configuration: {}
triggers:
  - id: "1"
    configuration:
      itemName: Module202AUWRL65reLSRS_Relais6
    type: core.ItemStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: |-
        console.info(`Dämmrig = ${event.itemState}`);

        var item = items.getItem("gDaemmrig");

        if (eventItem.state == "ON") {
          item.sendCommand("ON");
        } else {
          item.sendCommand("OFF");
        }
    type: script.ScriptAction

Check your code, you use ‚eventItem.state’ instead on event.itemState

Oh yes, that was a typo, sorry. Just corrected it but

event.itemState == "ON"

still evaluates to false.

I can‘t find the docu at the moment, but I think it should be
‚if (event.itemState.toString() == ‘ON’ ) if you compare with a string

I think it should be event.itemState == ON.

See the ‘Note’ under the first table (about Java vs Javascript types): JavaScript Scripting - Automation | openHAB.

Yes, that works. I’d have sworn that I had tried this before but apparently I didn’t. Thanks a lot!

This results in an error:
Script execution of rule with UID 'Daemmrig' failed: org.graalvm.polyglot.PolyglotException: ReferenceError: "ON" is not defined

Maybe your item is not a „switch item“

Yep, it is a “proper” switch.

That would only work if, like the line above it in the example in the docs you imported the ON Java object from runtime.

In order to avoid messing with the Java objects using the .toString() approach is preferable.

To summarize and explain a bit, for managed rules like this, the JS Scripting add-on does not have the opportunity to replace the Java event Object with a JS Scripting equivalent. Constantly this is one of the few places remaining where you have to deal with it differently. In this case, event.itemState is the Java State Object instead of a String like you would get everywhere else.

There is some effort ongoing to see if there is a way to fix this and I’m personally looking for a work around in OHRT.

In the mean time, when using managed rules, remember to call toString() and all should be well.

1 Like