JS 2021: How to loop through things

I try to loop through all things in order to access their properties (like IP Address, location, Label, etc.) but fail due to lack of documentation (or better: I am incapable of understanding existing ECMA scripts 2021 docs…)
I’d really want to achieve that by internal code and not via calling external REST API.

I tried the whole day different approaches but with no luck. Here is one of my attempts:

var ThingRegistry = Java.type('org.openhab.core.thing.ThingRegistry');
things.thingRegistry.getAll().forEach(thing => console.log("Status:",thing.getLabel()));

could somebody please be so kind as to guide me in the right direction?

ok. found this post and now it works:

var tReg = osgi.getService('org.openhab.core.thing.ThingRegistry');
tReg.getAll().forEach(thing => console.log("Status:",thing.getLabel()));

I know how to filter if I just want to access things of a specific binding (.filter) which is a string operation. Does anybody know if I can filter directly, i.e. instead of getAll() I am thinking of specifying a bundleId. Is this possible?

It’s not just a String operation. But this is one of the cases where, since you’ve bypassed the openhab-js library (by necessity, I don’t think openhab-js wraps the Thing API) you are working with a Java List, not a JavaScript Array. So you can either use Java’s Streaming API or use utils.javaListToJsArray(tReg.getAll()) to convert the Java List to a JS Array and then use the JavaScript filter.

1 Like