For a couple years now, I’ve been wanting/looking for a way to construct an item from its name as a string. There are other ways to do this, and the most popular requires the item to be in a group, which can have it’s challenges. I’ll keep this short and SWEET… I finally figured it out, and it is extremely simple!
For OH 2.x, you’ll need this import…
import org.eclipse.smarthome.model.script.ScriptServiceUtil
For OH 3.x, this import instead…
import org.openhab.core.model.script.ScriptServiceUtil
You can then access an item by its string name, like this…
val testItem = ScriptServiceUtil.getItemRegistry.getItem("Virtual_Switch_1")
In this example, testItem
is returned as an Item. In most cases, you will want to use it as a GenericItem, so instead of the above, you’ll need to cast it…
val testItem = ScriptServiceUtil.getItemRegistry.getItem("Virtual_Switch_1") as GenericItem
If an Item cannot be found with a name matching the string used, you will get an error like…
2020-05-5 5:55:55.555 [ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'Generate error from bad Item name': Item 'bad_name' could not be found in the item registry
The getItems
(note the s) method can be used to avoid this error. See this post below.
Happy HABing!!!