ECMA-rule: fetch all items with a certain tag

I’m trying to fetch all items with a certain tag.

My specific use case would be to “turn off all lights” - which I could do by putting all items in a group. But just for the fun of it I’d like to use tags for that.

So:
How can I fetch all items, which are tagged with “light” for a start?

Additionally:
How can I fetch all “light” tagged items, which also have “status” stagged => so I can set the dimming value to a specific setting?

Which ECMA, 5.1 or 11?

If 11:

var tag1and2 = items.getItemsByTag("tag1", "tag2");

That will return a JavaScript Array of openhab-js Item Objects (JS wrapper around the Java Item Objects) of all the Items that have both tag1 and tag2.

If 5.1

var tag1andtag2 = ir.getItemsByTag('tag1', 'tag2');

That will give you a java.util.Set<Item> (I think) of Java Item Objects that have both tag1 and tag2.

I don’t understand the question. do you mean those with a “status” tag, or a status property of “staged”? I’m unaware of such a status on Items so need more info to explore what you are after if the latter. If the former, see above.

Note, the ItemRegistry has more methods available on it than is exposed through openhab-js. See ItemRegistry (openHAB Core 3.3.0-SNAPSHOT API). If you are using ECMAScript 11, you can get direct access to the itemRegistry by adding

var {itemRegistry} = require('@runtime');

If there isn’t a method that does exactly what you need, you can get all the Items from the registry using itemRegistry.getItems() and then filter down to what you want.

1 Like

oh… The “new” ECMA 11 was totally not on my screen as of now. I think I’ll have to think and move to 2021! :wink:

Sorry, if this was misleading - I use the tag "status" (Semantic class) for dimmable "lights" (Semantic property) and "switch" (Semantic class) for switchable lights. So my intend was to say “please set all lights to 20%”.

so, thanks for the heads up - I’ll migrate to 11 and then work from there!

Be sure to look at the docs for the add-on. It comes with helper libraries (openhab-js) out of the box which does a good job of normalizing all the interactions with OH so that you are working with ECMAScript Objects instead of Java Objects, side stepping a lot of type errors.

It also works significantly differently from JSR223 ECMAScript 5.1 and its Helper Libraries.

I posted a bunch of examples at Some JS Scripting UI Rules Examples.

Also don’t miss that Blockly is now pretty complete when it comes to openHAB support so if a graphical representation of rules is more your speed there isn’t too much you can’t do in Blockly now.

Also look at the rule templates in the Marketplace. These can save you from having to write any code at all in a number of circumstances.

1 Like