2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.hue.internal.handler;
15 import static org.openhab.binding.hue.internal.HueBindingConstants.*;
17 import java.math.BigDecimal;
18 import java.util.List;
20 import java.util.Objects;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24 import java.util.stream.Collectors;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.hue.internal.dto.ColorTemperature;
29 import org.openhab.binding.hue.internal.dto.FullGroup;
30 import org.openhab.binding.hue.internal.dto.Scene;
31 import org.openhab.binding.hue.internal.dto.State;
32 import org.openhab.binding.hue.internal.dto.StateUpdate;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.HSBType;
35 import org.openhab.core.library.types.IncreaseDecreaseType;
36 import org.openhab.core.library.types.OnOffType;
37 import org.openhab.core.library.types.PercentType;
38 import org.openhab.core.library.types.StringType;
39 import org.openhab.core.thing.Bridge;
40 import org.openhab.core.thing.ChannelUID;
41 import org.openhab.core.thing.Thing;
42 import org.openhab.core.thing.ThingStatus;
43 import org.openhab.core.thing.ThingStatusDetail;
44 import org.openhab.core.thing.ThingStatusInfo;
45 import org.openhab.core.thing.ThingTypeUID;
46 import org.openhab.core.thing.binding.BaseThingHandler;
47 import org.openhab.core.thing.binding.ThingHandler;
48 import org.openhab.core.types.Command;
49 import org.openhab.core.types.StateOption;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * {@link HueGroupHandler} is the handler for a hue group of lights. It uses the {@link HueClient} to execute the
57 * @author Laurent Garnier - Initial contribution
60 public class HueGroupHandler extends BaseThingHandler implements HueLightActionsHandler, GroupStatusListener {
62 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_GROUP);
63 public static final String PROPERTY_MEMBERS = "members";
65 private final Logger logger = LoggerFactory.getLogger(HueGroupHandler.class);
66 private final HueStateDescriptionProvider stateDescriptionOptionProvider;
68 private @NonNullByDefault({}) String groupId;
70 private @Nullable Integer lastSentColorTemp;
71 private @Nullable Integer lastSentBrightness;
73 private ColorTemperature colorTemperatureCapabilties = new ColorTemperature();
74 private long defaultFadeTime = 400;
76 private @Nullable HueClient hueClient;
78 private @Nullable ScheduledFuture<?> scheduledFuture;
79 private @Nullable FullGroup lastFullGroup;
81 private List<String> consoleScenesList = List.of();
83 public HueGroupHandler(Thing thing, HueStateDescriptionProvider stateDescriptionOptionProvider) {
85 this.stateDescriptionOptionProvider = stateDescriptionOptionProvider;
89 public void initialize() {
90 logger.debug("Initializing Hue group handler.");
91 Bridge bridge = getBridge();
92 initializeThing((bridge == null) ? null : bridge.getStatus());
96 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
97 logger.debug("bridgeStatusChanged {}", bridgeStatusInfo);
98 initializeThing(bridgeStatusInfo.getStatus());
101 private void initializeThing(@Nullable ThingStatus bridgeStatus) {
102 logger.debug("initializeThing thing {} bridge status {}", getThing().getUID(), bridgeStatus);
103 final String configGroupId = (String) getConfig().get(GROUP_ID);
104 if (configGroupId != null) {
105 BigDecimal time = (BigDecimal) getConfig().get(FADETIME);
107 defaultFadeTime = time.longValueExact();
110 groupId = configGroupId;
111 // note: this call implicitly registers our handler as a listener on the bridge
112 if (getHueClient() != null) {
113 if (bridgeStatus == ThingStatus.ONLINE) {
114 updateStatus(ThingStatus.ONLINE);
116 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
119 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
122 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
123 "@text/offline.conf-error-no-group-id");
127 private synchronized void initializeProperties(@Nullable FullGroup fullGroup) {
128 if (fullGroup != null) {
129 Map<String, String> properties = editProperties();
130 properties.put(PROPERTY_MEMBERS, fullGroup.getLightIds().stream().collect(Collectors.joining(",")));
131 updateProperties(properties);
136 public void dispose() {
137 logger.debug("Hue group handler disposes. Unregistering listener.");
138 cancelScheduledFuture();
139 if (groupId != null) {
140 HueClient bridgeHandler = getHueClient();
141 if (bridgeHandler != null) {
142 bridgeHandler.unregisterGroupStatusListener(this);
149 protected synchronized @Nullable HueClient getHueClient() {
150 if (hueClient == null) {
151 Bridge bridge = getBridge();
152 if (bridge == null) {
155 ThingHandler handler = bridge.getHandler();
156 if (handler instanceof HueBridgeHandler) {
157 HueClient bridgeHandler = (HueClient) handler;
158 hueClient = bridgeHandler;
159 bridgeHandler.registerGroupStatusListener(this);
168 public void handleCommand(ChannelUID channelUID, Command command) {
169 handleCommand(channelUID.getId(), command, defaultFadeTime);
173 public void handleCommand(String channel, Command command, long fadeTime) {
174 HueClient bridgeHandler = getHueClient();
175 if (bridgeHandler == null) {
176 logger.debug("Hue Bridge handler not found. Cannot handle command without bridge.");
180 FullGroup group = bridgeHandler.getGroupById(groupId);
182 logger.debug("Hue group not known on bridge. Cannot handle command.");
183 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
184 "@text/offline.conf-error-wrong-group-id");
188 Integer lastColorTemp;
189 StateUpdate newState = null;
192 if (command instanceof HSBType) {
193 HSBType hsbCommand = (HSBType) command;
194 if (hsbCommand.getBrightness().intValue() == 0) {
195 newState = LightStateConverter.toOnOffLightState(OnOffType.OFF);
197 newState = LightStateConverter.toColorLightState(hsbCommand, group.getState());
198 newState.setOn(true);
199 newState.setTransitionTime(fadeTime);
201 } else if (command instanceof PercentType) {
202 newState = LightStateConverter.toBrightnessLightState((PercentType) command);
203 newState.setTransitionTime(fadeTime);
204 } else if (command instanceof OnOffType) {
205 newState = LightStateConverter.toOnOffLightState((OnOffType) command);
206 } else if (command instanceof IncreaseDecreaseType) {
207 newState = convertBrightnessChangeToStateUpdate((IncreaseDecreaseType) command, group);
208 if (newState != null) {
209 newState.setTransitionTime(fadeTime);
213 case CHANNEL_COLORTEMPERATURE:
214 if (command instanceof PercentType) {
215 newState = LightStateConverter.toColorTemperatureLightStateFromPercentType((PercentType) command,
216 colorTemperatureCapabilties);
217 newState.setTransitionTime(fadeTime);
218 } else if (command instanceof OnOffType) {
219 newState = LightStateConverter.toOnOffLightState((OnOffType) command);
220 } else if (command instanceof IncreaseDecreaseType) {
221 newState = convertColorTempChangeToStateUpdate((IncreaseDecreaseType) command, group);
222 if (newState != null) {
223 newState.setTransitionTime(fadeTime);
227 case CHANNEL_COLORTEMPERATURE_ABS:
228 if (command instanceof DecimalType) {
229 newState = LightStateConverter.toColorTemperatureLightState((DecimalType) command,
230 colorTemperatureCapabilties);
231 newState.setTransitionTime(fadeTime);
234 case CHANNEL_BRIGHTNESS:
235 if (command instanceof PercentType) {
236 newState = LightStateConverter.toBrightnessLightState((PercentType) command);
237 newState.setTransitionTime(fadeTime);
238 } else if (command instanceof OnOffType) {
239 newState = LightStateConverter.toOnOffLightState((OnOffType) command);
240 } else if (command instanceof IncreaseDecreaseType) {
241 newState = convertBrightnessChangeToStateUpdate((IncreaseDecreaseType) command, group);
242 if (newState != null) {
243 newState.setTransitionTime(fadeTime);
246 lastColorTemp = lastSentColorTemp;
247 if (newState != null && lastColorTemp != null) {
248 // make sure that the light also has the latest color temp
249 // this might not have been yet set in the light, if it was off
250 newState.setColorTemperature(lastColorTemp, colorTemperatureCapabilties);
251 newState.setTransitionTime(fadeTime);
255 if (command instanceof OnOffType) {
256 newState = LightStateConverter.toOnOffLightState((OnOffType) command);
258 lastColorTemp = lastSentColorTemp;
259 if (newState != null && lastColorTemp != null) {
260 // make sure that the light also has the latest color temp
261 // this might not have been yet set in the light, if it was off
262 newState.setColorTemperature(lastColorTemp, colorTemperatureCapabilties);
263 newState.setTransitionTime(fadeTime);
267 if (command instanceof StringType) {
268 newState = LightStateConverter.toAlertState((StringType) command);
269 if (newState == null) {
270 // Unsupported StringType is passed. Log a warning
271 // message and return.
272 logger.warn("Unsupported String command: {}. Supported commands are: {}, {}, {} ", command,
273 LightStateConverter.ALERT_MODE_NONE, LightStateConverter.ALERT_MODE_SELECT,
274 LightStateConverter.ALERT_MODE_LONG_SELECT);
277 scheduleAlertStateRestore(command);
282 if (command instanceof StringType) {
283 newState = new StateUpdate().setScene(command.toString());
289 if (newState != null) {
290 cacheNewState(newState);
291 bridgeHandler.updateGroupState(group, newState, fadeTime);
293 logger.debug("Command sent to an unknown channel id: {}:{}", getThing().getUID(), channel);
298 * Caches the new state that is sent to the bridge. This is necessary in case the lights are off when the values are
299 * sent. In this case, the values are not yet set in the lights.
301 * @param newState the state to be cached
303 private void cacheNewState(StateUpdate newState) {
304 Integer tmpBrightness = newState.getBrightness();
305 if (tmpBrightness != null) {
306 lastSentBrightness = tmpBrightness;
308 Integer tmpColorTemp = newState.getColorTemperature();
309 if (tmpColorTemp != null) {
310 lastSentColorTemp = tmpColorTemp;
314 private @Nullable StateUpdate convertColorTempChangeToStateUpdate(IncreaseDecreaseType command, FullGroup group) {
315 StateUpdate stateUpdate = null;
316 Integer currentColorTemp = getCurrentColorTemp(group.getState());
317 if (currentColorTemp != null) {
318 int newColorTemp = LightStateConverter.toAdjustedColorTemp(command, currentColorTemp,
319 colorTemperatureCapabilties);
320 stateUpdate = new StateUpdate().setColorTemperature(newColorTemp, colorTemperatureCapabilties);
325 private @Nullable Integer getCurrentColorTemp(@Nullable State groupState) {
326 Integer colorTemp = lastSentColorTemp;
327 if (colorTemp == null && groupState != null) {
328 return groupState.getColorTemperature();
333 private @Nullable StateUpdate convertBrightnessChangeToStateUpdate(IncreaseDecreaseType command, FullGroup group) {
334 Integer currentBrightness = getCurrentBrightness(group.getState());
335 if (currentBrightness == null) {
338 int newBrightness = LightStateConverter.toAdjustedBrightness(command, currentBrightness);
339 return createBrightnessStateUpdate(currentBrightness, newBrightness);
342 private @Nullable Integer getCurrentBrightness(@Nullable State groupState) {
343 if (lastSentBrightness == null && groupState != null) {
344 return groupState.isOn() ? groupState.getBrightness() : 0;
346 return lastSentBrightness;
349 private StateUpdate createBrightnessStateUpdate(int currentBrightness, int newBrightness) {
350 StateUpdate lightUpdate = new StateUpdate();
351 if (newBrightness == 0) {
352 lightUpdate.turnOff();
354 lightUpdate.setBrightness(newBrightness);
355 if (currentBrightness == 0) {
356 lightUpdate.turnOn();
363 public void channelLinked(ChannelUID channelUID) {
364 HueClient handler = getHueClient();
365 if (handler != null) {
366 FullGroup group = handler.getGroupById(groupId);
368 onGroupStateChanged(group);
374 public boolean onGroupStateChanged(FullGroup group) {
375 logger.trace("onGroupStateChanged() was called for group {}", group.getId());
377 State state = group.getState();
379 final FullGroup lastState = lastFullGroup;
380 if (lastState == null || !Objects.equals(lastState.getState(), state)) {
381 lastFullGroup = group;
386 logger.trace("New state for group {}", groupId);
388 initializeProperties(group);
390 lastSentColorTemp = null;
391 lastSentBrightness = null;
393 updateStatus(ThingStatus.ONLINE);
395 logger.debug("onGroupStateChanged Group {}: on {} bri {} hue {} sat {} temp {} mode {} XY {}", group.getName(),
396 state.isOn(), state.getBrightness(), state.getHue(), state.getSaturation(), state.getColorTemperature(),
397 state.getColorMode(), state.getXY());
399 HSBType hsbType = LightStateConverter.toHSBType(state);
401 hsbType = new HSBType(hsbType.getHue(), hsbType.getSaturation(), PercentType.ZERO);
403 updateState(CHANNEL_COLOR, hsbType);
405 PercentType brightnessPercentType = state.isOn() ? LightStateConverter.toBrightnessPercentType(state)
407 updateState(CHANNEL_BRIGHTNESS, brightnessPercentType);
409 updateState(CHANNEL_SWITCH, OnOffType.from(state.isOn()));
411 updateState(CHANNEL_COLORTEMPERATURE,
412 LightStateConverter.toColorTemperaturePercentType(state, colorTemperatureCapabilties));
413 updateState(CHANNEL_COLORTEMPERATURE_ABS, LightStateConverter.toColorTemperature(state));
419 public void onGroupAdded(FullGroup group) {
420 onGroupStateChanged(group);
424 public void onGroupRemoved() {
425 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/offline.group-removed");
429 public void onGroupGone() {
430 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "@text/offline.group-removed");
434 * Sets the state options for applicable scenes.
437 public void onScenesUpdated(List<Scene> updatedScenes) {
438 List<StateOption> stateOptions = List.of();
439 consoleScenesList = List.of();
440 HueClient handler = getHueClient();
441 if (handler != null) {
442 FullGroup group = handler.getGroupById(groupId);
444 stateOptions = updatedScenes.stream().filter(scene -> scene.isApplicableTo(group))
445 .map(Scene::toStateOption).collect(Collectors.toList());
446 consoleScenesList = updatedScenes
447 .stream().filter(scene -> scene.isApplicableTo(group)).map(scene -> "Id is \"" + scene.getId()
448 + "\" for scene \"" + scene.toStateOption().getLabel() + "\"")
449 .collect(Collectors.toList());
452 stateDescriptionOptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_SCENE),
457 * Schedules restoration of the alert item state to {@link LightStateConverter#ALERT_MODE_NONE} after a given time.
459 * Based on the initial command:
461 * <li>For {@link LightStateConverter#ALERT_MODE_SELECT} restoration will be triggered after <strong>2
463 * <li>For {@link LightStateConverter#ALERT_MODE_LONG_SELECT} restoration will be triggered after <strong>15
466 * This method also cancels any previously scheduled restoration.
468 * @param command The {@link Command} sent to the item
470 private void scheduleAlertStateRestore(Command command) {
471 cancelScheduledFuture();
472 int delay = getAlertDuration(command);
475 scheduledFuture = scheduler.schedule(() -> {
476 updateState(CHANNEL_ALERT, new StringType(LightStateConverter.ALERT_MODE_NONE));
477 }, delay, TimeUnit.MILLISECONDS);
482 * This method will cancel previously scheduled alert item state
485 private void cancelScheduledFuture() {
486 ScheduledFuture<?> scheduledJob = scheduledFuture;
487 if (scheduledJob != null) {
488 scheduledJob.cancel(true);
489 scheduledFuture = null;
494 * This method returns the time in <strong>milliseconds</strong> after
495 * which, the state of the alert item has to be restored to {@link LightStateConverter#ALERT_MODE_NONE}.
497 * @param command The initial command sent to the alert item.
498 * @return Based on the initial command will return:
500 * <li><strong>2000</strong> for {@link LightStateConverter#ALERT_MODE_SELECT}.
501 * <li><strong>15000</strong> for {@link LightStateConverter#ALERT_MODE_LONG_SELECT}.
502 * <li><strong>-1</strong> for any command different from the previous two.
505 private int getAlertDuration(Command command) {
507 switch (command.toString()) {
508 case LightStateConverter.ALERT_MODE_LONG_SELECT:
511 case LightStateConverter.ALERT_MODE_SELECT:
522 public List<String> listScenesForConsole() {
523 return consoleScenesList;
527 public String getGroupId() {