Group items & forEach loops


I’ve moved from openHAB 1.x to 2.0 (latest Snapshot) and I wanted to clean up my rule mess.
Basically I’m looking for a smart solution to switch my lights on/off.

At the very beginning I thought it would be easy to use a group switch but I thought it would be possible to assign a single subgroup to multiple parent groups for instance:

Group All

Group:Switch:OR(ON, OFF) AllLight
Group:Switch:OR(ON, OFF) GuestLight

Group LowerGroundLightA (AllLight)
Group LowerGroundLightB (AllLight)
Group GroundLightA (AllLight)
Group GroundLightB (AllLight, GuestLight)

but this didn’t work. Then I decided to use forEach loop (see below) but I don’t know if there’s something smarter I could do? I want to minimize my group assignments as much as possible.
Btw what’s the meaning of the question mark if I use a forEach loop (e.g. gLightAll?.allMembers.forEach).
Thanks a lot, Manuel

Let me share a sample rule which is used to switch off all lights:

		gLightAll.allMembers.forEach [ item | item.sendCommand(OFF) ]
		gLightGuest.allMembers.forEach [ item | item.sendCommand(OFF) ]
		gLightLiving.allMembers.forEach [ item | item.sendCommand(OFF) ]

Item setup:

Group All

Group gKG						"KG"					(All)
Group gEG						"EG"					(All)
Group gOG						"OG"					(All)
Group gOUT						"Außen"					(All)
Group gMISC						"Control"				(All)

Group gKGController				"KG"					(All)
Group gEGController				"EG"					(All)
Group gOGController				"OG"					(All)
Group gOUTController			"Außen"					(All)
Group gMISCController			"Andere"				(All)

Group gScene					"Szenen"				(All)
Group gLightAll					"Zentral Licht"				(gScene)
Group gLightGuest				"Zentral Licht o. Gast"			(gScene)
Group gLightLiving				"Zentral Licht o. Wohnen"		(gScene)

Group gKGLight					"KG Licht"				(gLightAll)
Group gEGLight					"EG Licht"				(gLightAll)
Group gOGLight					"OG Licht"				(gLightAll)
Group gOUTLight					"Außen Licht"				(gLightAll)
1 Like

That is the equivalent to the following code:

if(gLightAll.allMembers != null)
    gLightAll.allMembers.forEach[ ...

It is a shortcut to test for null and if it is null skip over the statement. I personally don’t use ? in this context any longer because I want an error if for some reason allMembers is null when I expect it to not be null.

In what way did it not work?

I don’t really use subgroups so have no experience to draw upon but it seems like it should work. However, you might need to define the subgroups as Switches too.

Group:Switch:OR(ON, OFF) LowerGroundLightA (AllLight)

Short of using the Groups directly, the forEach loops are probably your best bets.

Well I wanted to know whether a subgroup could be a member of multiple parent groups?
For instance (I’m referring to the last line):

Group All
Group All_Lights (All)
Group Indoor_Lights (All)

Group LG_Lights (All_Lights, Indoor_Lights)


Yes, it can.