Descendants of [groupname] in JavaScript

Hi All,

I’m in the middle of moving from Jython → JS scripting.
I have many rules relying on “Descendants of groupname received update” trigger in Jython.
The reason for that is the group model i’m using with two levels nested groups for different services.

Is there a way to create the same in JS scripting?

See JavaScript Scripting - Automation | openHAB

items.MyGroup.descendents

I saw that but it can’t be used as a trigger for rules in JS… right?

In Jython i can use

@when("Descendent of GROUP_NAME received command [COMMAND]")

which will get me the item in the children groups belonging to the group name.

Is there a similar trigger i can use in JS? I couldn’t find one.

There is no rule trigger that works with descendants of a Group. The Jython helper library kind of cheated and invented such a trigger by unrolling the descendants and creating a separate trigger for each individually. All the other languages use the built in triggers and there isn’t a trigger that supports descendants.

To get the same, assuming you are using .js files and not the UI, you can dynamically create the rule triggers the same way that Jython’s helper library did it behind the scenes. As with the Jython implementation, you’ll have to reload the file every time you change the Group membership.

I only use the UI so I’m just taking a stab at it but I think it would look something like this:

// Create functions like this, maybe put them in a personal library for reuse
const generateItemStateChangedTriggers = (groupName) => {
  return items[groupName].descendents.map( item => triggers.ItemStateChangedTrigger(item.name) ]
}

rules.JSRule( {
  name: "My rule name",
  description: "My rule description",
  triggers: generateItemStateChangedTriggers('MyGroup'),
  execute: (event) =>
...

Or you can just do it inline since it’s just a one liner call to map.

triggers: items['MyGroup'].descendents.map( item => triggers.ItemStateChangedTrigger(item.name) ),

If you are working with the UI, you’ll need to use a GenericEventTrigger configured to match all Item changes (for example) and then use a rule condition to ignore those except from Items that are descendants from the Group you care about.

The disadvantage here is the rule will be constantly be triggering but the advantage is you won’t have to reload the rule if you change the Group membership.

Edit: I was helping someone with map in Rules DSL and used that syntax instead of JS syntax. Doh!

ahh… i get it… i thought it was something hidden in the rule engine :slight_smile:

Thanks alot for the example and the details… will give it a shot and report back…

Thanks again for the great support :slight_smile:

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.