Rule to change a switch state depending on group members

Hello,

I’m looking for a rule that will turn a switch on if all members of a group are on.
On the other hand, I also need a rule to turn the switch off again if one or more group members are switched off.
Is anyone able to help me out, cause I can’t seem to wrap my head around it and create the right rule.

Thank you very much for your time.

Kind regards,
Guido Jurriens

Let’s assume you have following items

Group gItemsGroup

Switch Item01	"Switch 01"		(gItemsGroup)
Switch Item02	"Switch 02"		(gItemsGroup)
Switch Item03	"Switch 03"		(gItemsGroup)
Switch Item04	"Switch 04"		(gItemsGroup)
Switch Item05	"Switch 05"		(gItemsGroup)
Switch Item06	"Switch 06"		(gItemsGroup)


Switch ControlItem	"[MAP(testgroup.map):%s]"

You can use a rule like this:

import org.openhab.core.library.types.*
import org.openhab.core.library.items.*
import org.openhab.core.types.*
import org.eclipse.xtext.xbase.lib.*


rule "Group Test"
when
	Item gItemsGroup received update
then
	Thread::sleep(500)
	var boolean bAllON = true
	gItemsGroup?.allMembers.filter(s | s.state!=ON).forEach[i|
		//logInfo("GROUP TEST","ITEM =(" + i.name  + ") state=(" + i.state.toString + ")")
		bAllON = false
	]
	if (bAllON) {
		ControlItem.sendCommand(ON)
	} else {
		ControlItem.sendCommand(OFF)
	}				
end

testgroup.map contains

OFF=ONE MEMBER OFF
ON=ALL MEMBERS ON
undefined=???

Thank you for the code.
I can probably rewrite this to my situation :wink:

If you define your group with the AND function, the value of the Group item will be ON when all the items in the group are on. For example, from my items,

Group:Switch:AND(ON, OFF) FullyAutomatic "Fully Automatic [ (%d) ]" <switch>

Where the items are

Switch AutomaticLights "Lights Controlled Automatically" <switch> (FullyAutomatic)
Switch AutomaticTemperature "Temperature Controlled Automatically" <temperature> (FullyAutomatic)

Which I think is the behaviour you are after, but without any scripting.

Thank you, that’s an even better solution.
I just tried it and it works great !!!