Dynamically create items in rule (OH2)

Hi all,

I would like to create (& delete) items dynamically in a rule and assign them to a group; this works ok with the code below:

var StringItem temporaryItem = (new StringItem(UUID.randomUUID().toString()))
    temporaryItem.label = "ABC [%s]"
    gPositionUpdateIntervalsPatrik.addMember(temporaryItem)
    temporaryItem.postUpdate("Test")
    if (gPositionUpdateIntervalsPatrik.allMembers.size > 10) {
        var oldItem = gPositionUpdateIntervalsPatrik.allMembers.last
        gPositionUpdateIntervalsPatrik.removeMember(oldItem)
    }

The items are created and deleted as expected; but the “postUpdate” does not work. I did some google searches & suspect that I need to register ( & unregister) the items in the item registry as well. Unfortunately I did not find a way the get access to the ItemRegistry from the rule. Is there a way to do this?

If not, that would be very nice - as for example access to the IOC container, or @ least the most relevant things (like this registry) would make the engine even more powerful.

Btw.: Use case currently is only a debug thing; which I could also solve differently - but a future project will be a podcast player & there this dynamic stuff would be very handy.

with kind regards,
Patrik

Hi Patrik,

since creating this post a long time is past. Have you found a solution for dynamic add/ remove groups to items?

I found a solution based on the initial post’s suggestion:
(The rule is adding items according to missed phone calls.)

import org.eclipse.smarthome.model.script.ScriptServiceUtil
import java.util.UUID

rule “anrufliste”
when
Item fboxRinging changed to ON
then
var StringItem temporaryItem = (new StringItem(UUID.randomUUID().toString()))
ScriptServiceUtil.getItemRegistry.add(temporaryItem)
temporaryItem.label = fboxIncomingCall.state.toString()
Anrufliste.addMember(temporaryItem)
if (Anrufliste.allMembers.size > 10) {
var oldItem = Anrufliste.allMembers.last
Anrufliste.removeMember(oldItem)
}
end

1 Like

Are these items retained after reboot, when created from script?
Or do you have to recreate them after reboot?