I’m running OpenHAB 2.5.0M1 on Ubuntu with Zulu JVM 8.33.0.1 on an old laptop.
Here’s a way to toggle all lights on or off with a switch. You even get OpenHAB notifications for the state changes.
I assigned all lights to the gLight
group and created a All_Lights_Toggle
Switch item to control all lights from the sitemap, but make sure to not assign it to the gLight
group (otherwise you have to check for that switch in the rules later on, which makes it needlessly more complex).
Switch All_Lights_Toggle "All lights" <light>
For my rules, I use locks and define the notification recipient address (linked to my MyOpenHAB account):
import java.util.concurrent.locks.ReentrantLock
val ReentrantLock lock = new ReentrantLock()
val String notificationRecipient = "user@domain"
I use one rule for managing the state of the All_Lights_Toggle
switch:
rule "A light changed"
when
Member of gLight changed to ON
or Member of gLight changed to OFF
then
lock.lock()
try {
val Number numPoweredLights = gLight.members.filter[ s | (s.state == ON) && (s.name !== All_Lights_Toggle.name) ].size
logDebug("LightChanged", "A member of gLight changed: {} set from '{}' to '{}' - {} light(s) are ON",
triggeringItem.name, previousState, triggeringItem.state, numPoweredLights)
if (numPoweredLights == 0) {
All_Lights_Toggle.sendCommand(OFF)
} else {
All_Lights_Toggle.sendCommand(ON)
}
} finally {
lock.unlock()
}
end
And I use one rule for switching on or off the lights based on the state change of the All_Lights_Toggle
switch:
rule "All Lights Toggle Switch"
when
Item All_Lights_Toggle changed to OFF
or Item All_Lights_Toggle changed to ON
then
lock.lock()
try {
val toggleState = if ( triggeringItem.state == ON ) { OFF } else { ON }
var lightsToToggle = gLight.members.filter[ s | s.state == toggleState ]
val Number lightsToToggleCount = lightsToToggle.size
logInfo("AllLightsSwitchRule", "Info: '{}' has state '{}'", triggeringItem.name, triggeringItem.state)
if (lightsToToggleCount == 0) {
logWarn("AllLightsSwitchRule", "All lights are already '{}'", toggleState)
return;
}
// Compute the list of lights to toggle BEFORE changing their state (or you'd get 'null') !
val listToggledLights = lightsToToggle.map[ name ].reduce[ s, name | s + ", " + name ]
lightsToToggle.forEach [ i |
logInfo("AllLightsSwitchRule", "Light '" + i.name + "' is '" + i.state.toString + "' - will switch '" + triggeringItem.state + "'")
i.sendCommand(triggeringItem.state)
]
sendNotification(notificationRecipient, "ℹ️ Switching " + triggeringItem.state + " " + lightsToToggleCount + " light(s): " + listToggledLights)
} finally {
lock.unlock()
}
end
Note: I see that I have to reload the light status frame from time to time, as I’m also using one switch in the gLight
group to control 4 lights (linked to 4 channels). Apparently OpenHAB isn’t able to always post the correct status without a reload for that particular Item
.
Have fun!