OH3 JavaScript Rules: The item triggering a rule (triggeringItem / itemName) remains "undefined"

Platform information:

  • Homematic IP Hardware: CCU2 (2.59.7), multiple Homematic IP devices
  • openHAB Hardware: Raspi 3 (Raspian OS 10)
  • openHAB Software: 3.1.0 Release Build, running on Docker 2.9.1
  • openHAB Bindings: Homematic Binding (logging the heating, controlling lights and blinds), Gardena Binding for Gardena Gateway / smart irrigation control (logging soil humidity), Alexa Binding (controlling the Homematic lights)

I’m trying to use the name of an item (and maybe the description) that triggered a rule in a rule that pushes messages to the OH iOS App, to send warnings if specific sensors run out of battery / cannot be reached).

Everything works great, but I can’t get the triggeringItem-part to work. Maybe I’m also doing an extremely stupid error. I also read through this thread, this one and this one, but no change. So chances are that even if I put another two hours into this, it won’t change.

I’m writing all my rules in the main UI (is this maybe the problem?)

triggers:
  - id: "1"
    configuration:
      groupName: Unreach_Group
    type: core.GroupStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >-
        var NotificationAction = org.openhab.io.openhabcloud.NotificationAction;
        var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);

        // First I learned about triggeringItem, which I tried with the following two lines
        var event1 = org.openhab.core.items.events.ItemCommandEvent;
        logger.warn(event1.triggeringItem);

        // And after some more research I stumbled upon itemName, which replaced triggeringItem?
        var event2 = org.openhab.core.types.State;
        logger.warn(event2.itemName);

        // Disabled for now / the testing
        //  NotificationAction.sendNotification('xxx@xxx.de', 'Test.')
    type: script.ScriptAction

The openHAB log does not throw any errors, but instead of containing the names of the triggering items, both attempts (event1.triggeringItem and event2.itemName) are shown as “undefined”.

17:27:02.633 [WARN ] [org.openhab.rule.unreach_on          ] - undefined
17:27:02.678 [WARN ] [org.openhab.rule.unreach_on          ] - undefined

I then stumbled upon this thread here, but even if I take the pretty basic example and create a test.rules (so an actual file within /openhab_conf/rules/) it throws an error:
17:33:07.549 [ERROR] [.internal.handler.ScriptActionHandler] - Script execution of rule with UID 'test-1' failed: An error occurred during the script execution: index=0, size=0 in test

I hope I’m just missing a small piece of the puzzle that causes all of this to make sense? :wink:

The event variable is automatically injected into the script context by the rules engine. You do not and should not attempt to redefine it yourself. In this case you need nothing more than to just use event.itemName wherever you need it. As a most basic example from your code:

triggers:
  - id: "1"
    configuration:
      groupName: Unreach_Group
    type: core.GroupStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >-
        var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);

        logger.warn(event.itemName);
    type: script.ScriptAction

Thanks @JustinG. What you describe was my very first attempt.

Using precisely your code results in the following log (was also the trigger for me to attempt to redefine it myself):

18:27:47.658 [ERROR] [.internal.handler.ScriptActionHandler] - Script execution of rule with UID 'unreach_on' failed: ReferenceError: "event" is not defined in <eval> at line number 2

Are you testing the rule by pushing the play button in the editor window?

The rules engine automatically injects the event variable into the script context…but only if there’s been an event which triggers the rule. If you just hit the run now button (or press ctrl-r), there’s no item event associated with the running of the rule and therefore no event and no event variable.

D’uh, I read about this earlier on and thought I did make sure that that’s not the root cause of the error message. Turned out I was wrong.

Thanks a lot!

I ended up with the following rule to monitor the “unreach”-flag of my Homematic IP-devices, in case this is helpful for someone else.

triggers:
  - id: "1"
    configuration:
      groupName: Unreach_Group
    type: core.GroupStateChangeTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >-
        var logger =
        Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' +
        ctx.ruleUID);
        var NotificationAction = org.openhab.io.openhabcloud.NotificationAction;
        // item = "ON": Device not reachable
        // item = "OFF": Device reachable
        if (event.itemState == 'ON' && event.oldItemState == 'OFF') {
          logger.warn(event.itemName + " offline.");
          NotificationAction.sendNotification('xxx@xxx.de', event.itemName + " offline.")
        }
        else if (event.itemState == 'OFF' && event.oldItemState == 'ON') {
          logger.warn(event.itemName + " wieder online.");
          NotificationAction.sendNotification('xxx@xxx.de', event.itemName + " offline.")
        }
    type: script.ScriptAction

@JustinG, quick follow-up question: Any idea how to get the item Label (not the item Name) of the triggering item? Tried out multiple things which I thought make sense (e.g. event.itemName.label or event.itemName.getLabel() ), but all of them resulted in “undefined” as the result. The item name works as well, but doesn’t look that nice in the push messages (since they’re often a bit more technical / cryptic).

A name is a name, it doesn’t have a label. You’ll be wanting to get the Item object of that name, using getItem()

1 Like

Thanks for the hint, @rossko57, got it to work after some syntax trial-and-error. :wink:

var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
var NotificationAction = org.openhab.io.openhabcloud.NotificationAction;

// item = "ON": Device not reachable
// item = "OFF": Device reachable
if (event.itemState == 'ON' && event.oldItemState == 'OFF') {
  logger.warn(ir.getItem(event.itemName).getLabel() + " offline.");
  NotificationAction.sendNotification('xxx@xxx.de', ir.getItem(event.itemName).getLabel() + " offline.")
}
else if (event.itemState == 'OFF' && event.oldItemState == 'ON') {
  logger.warn(ir.getItem(event.itemName).getLabel() + " online.");
  NotificationAction.sendNotification('xxx@xxx.de', ir.getItem(event.itemName).getLabel() + " online.")
}
1 Like