]> git.basschouten.com Git - openhab-addons.git/blob
f8860bde8789cd47ea99573e327a9940d1e638bb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.hue.internal.handler;
14
15 import static org.openhab.binding.hue.internal.HueBindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Objects;
21 import java.util.Set;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24 import java.util.stream.Collectors;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.hue.internal.FullGroup;
29 import org.openhab.binding.hue.internal.Scene;
30 import org.openhab.binding.hue.internal.State;
31 import org.openhab.binding.hue.internal.StateUpdate;
32 import org.openhab.binding.hue.internal.dto.ColorTemperature;
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;
52
53 /**
54  * {@link HueGroupHandler} is the handler for a hue group of lights. It uses the {@link HueClient} to execute the
55  * actual command.
56  *
57  * @author Laurent Garnier - Initial contribution
58  */
59 @NonNullByDefault
60 public class HueGroupHandler extends BaseThingHandler implements HueLightActionsHandler, GroupStatusListener {
61
62     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_GROUP);
63     public static final String PROPERTY_MEMBERS = "members";
64
65     private final Logger logger = LoggerFactory.getLogger(HueGroupHandler.class);
66     private final HueStateDescriptionProvider stateDescriptionOptionProvider;
67
68     private @NonNullByDefault({}) String groupId;
69
70     private @Nullable Integer lastSentColorTemp;
71     private @Nullable Integer lastSentBrightness;
72
73     private ColorTemperature colorTemperatureCapabilties = new ColorTemperature();
74     private long defaultFadeTime = 400;
75
76     private @Nullable HueClient hueClient;
77
78     private @Nullable ScheduledFuture<?> scheduledFuture;
79     private @Nullable FullGroup lastFullGroup;
80
81     private List<String> consoleScenesList = List.of();
82
83     public HueGroupHandler(Thing thing, HueStateDescriptionProvider stateDescriptionOptionProvider) {
84         super(thing);
85         this.stateDescriptionOptionProvider = stateDescriptionOptionProvider;
86     }
87
88     @Override
89     public void initialize() {
90         logger.debug("Initializing hue group handler.");
91         Bridge bridge = getBridge();
92         initializeThing((bridge == null) ? null : bridge.getStatus());
93     }
94
95     @Override
96     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
97         logger.debug("bridgeStatusChanged {}", bridgeStatusInfo);
98         initializeThing(bridgeStatusInfo.getStatus());
99     }
100
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);
106             if (time != null) {
107                 defaultFadeTime = time.longValueExact();
108             }
109
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);
115                 } else {
116                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
117                 }
118             } else {
119                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
120             }
121         } else {
122             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
123                     "@text/offline.conf-error-no-group-id");
124         }
125     }
126
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);
132         }
133     }
134
135     @Override
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);
143                 hueClient = null;
144             }
145             groupId = null;
146         }
147     }
148
149     protected synchronized @Nullable HueClient getHueClient() {
150         if (hueClient == null) {
151             Bridge bridge = getBridge();
152             if (bridge == null) {
153                 return null;
154             }
155             ThingHandler handler = bridge.getHandler();
156             if (handler instanceof HueBridgeHandler) {
157                 HueClient bridgeHandler = (HueClient) handler;
158                 hueClient = bridgeHandler;
159                 bridgeHandler.registerGroupStatusListener(this);
160             } else {
161                 return null;
162             }
163         }
164         return hueClient;
165     }
166
167     @Override
168     public void handleCommand(ChannelUID channelUID, Command command) {
169         handleCommand(channelUID.getId(), command, defaultFadeTime);
170     }
171
172     @Override
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.");
177             return;
178         }
179
180         FullGroup group = bridgeHandler.getGroupById(groupId);
181         if (group == null) {
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");
185             return;
186         }
187
188         Integer lastColorTemp;
189         StateUpdate newState = null;
190         switch (channel) {
191             case CHANNEL_COLOR:
192                 if (command instanceof HSBType) {
193                     HSBType hsbCommand = (HSBType) command;
194                     if (hsbCommand.getBrightness().intValue() == 0) {
195                         newState = LightStateConverter.toOnOffLightState(OnOffType.OFF);
196                     } else {
197                         newState = LightStateConverter.toColorLightState(hsbCommand, group.getState());
198                         newState.setOn(true);
199                         newState.setTransitionTime(fadeTime);
200                     }
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);
210                     }
211                 }
212                 break;
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);
224                     }
225                 }
226                 break;
227             case CHANNEL_COLORTEMPERATURE_ABS:
228                 if (command instanceof DecimalType) {
229                     newState = LightStateConverter.toColorTemperatureLightState((DecimalType) command,
230                             colorTemperatureCapabilties);
231                     newState.setTransitionTime(fadeTime);
232                 }
233                 break;
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);
244                     }
245                 }
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);
252                 }
253                 break;
254             case CHANNEL_SWITCH:
255                 if (command instanceof OnOffType) {
256                     newState = LightStateConverter.toOnOffLightState((OnOffType) command);
257                 }
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);
264                 }
265                 break;
266             case CHANNEL_ALERT:
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);
275                         return;
276                     } else {
277                         scheduleAlertStateRestore(command);
278                     }
279                 }
280                 break;
281             case CHANNEL_SCENE:
282                 if (command instanceof StringType) {
283                     newState = new StateUpdate().setScene(command.toString());
284                 }
285                 break;
286             default:
287                 break;
288         }
289         if (newState != null) {
290             cacheNewState(newState);
291             bridgeHandler.updateGroupState(group, newState, fadeTime);
292         } else {
293             logger.debug("Command sent to an unknown channel id: {}:{}", getThing().getUID(), channel);
294         }
295     }
296
297     /**
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.
300      *
301      * @param newState the state to be cached
302      */
303     private void cacheNewState(StateUpdate newState) {
304         Integer tmpBrightness = newState.getBrightness();
305         if (tmpBrightness != null) {
306             lastSentBrightness = tmpBrightness;
307         }
308         Integer tmpColorTemp = newState.getColorTemperature();
309         if (tmpColorTemp != null) {
310             lastSentColorTemp = tmpColorTemp;
311         }
312     }
313
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);
321         }
322         return stateUpdate;
323     }
324
325     private @Nullable Integer getCurrentColorTemp(@Nullable State groupState) {
326         Integer colorTemp = lastSentColorTemp;
327         if (colorTemp == null && groupState != null) {
328             return groupState.getColorTemperature();
329         }
330         return colorTemp;
331     }
332
333     private @Nullable StateUpdate convertBrightnessChangeToStateUpdate(IncreaseDecreaseType command, FullGroup group) {
334         Integer currentBrightness = getCurrentBrightness(group.getState());
335         if (currentBrightness == null) {
336             return null;
337         }
338         int newBrightness = LightStateConverter.toAdjustedBrightness(command, currentBrightness);
339         return createBrightnessStateUpdate(currentBrightness, newBrightness);
340     }
341
342     private @Nullable Integer getCurrentBrightness(@Nullable State groupState) {
343         if (lastSentBrightness == null && groupState != null) {
344             return groupState.isOn() ? groupState.getBrightness() : 0;
345         }
346         return lastSentBrightness;
347     }
348
349     private StateUpdate createBrightnessStateUpdate(int currentBrightness, int newBrightness) {
350         StateUpdate lightUpdate = new StateUpdate();
351         if (newBrightness == 0) {
352             lightUpdate.turnOff();
353         } else {
354             lightUpdate.setBrightness(newBrightness);
355             if (currentBrightness == 0) {
356                 lightUpdate.turnOn();
357             }
358         }
359         return lightUpdate;
360     }
361
362     @Override
363     public void channelLinked(ChannelUID channelUID) {
364         HueClient handler = getHueClient();
365         if (handler != null) {
366             FullGroup group = handler.getGroupById(groupId);
367             if (group != null) {
368                 onGroupStateChanged(group);
369             }
370         }
371     }
372
373     @Override
374     public boolean onGroupStateChanged(FullGroup group) {
375         logger.trace("onGroupStateChanged() was called for group {}", group.getId());
376
377         State state = group.getState();
378
379         final FullGroup lastState = lastFullGroup;
380         if (lastState == null || !Objects.equals(lastState.getState(), state)) {
381             lastFullGroup = group;
382         } else {
383             return true;
384         }
385
386         logger.trace("New state for group {}", groupId);
387
388         initializeProperties(group);
389
390         lastSentColorTemp = null;
391         lastSentBrightness = null;
392
393         updateStatus(ThingStatus.ONLINE);
394
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());
398
399         HSBType hsbType = LightStateConverter.toHSBType(state);
400         if (!state.isOn()) {
401             hsbType = new HSBType(hsbType.getHue(), hsbType.getSaturation(), PercentType.ZERO);
402         }
403         updateState(CHANNEL_COLOR, hsbType);
404
405         PercentType brightnessPercentType = state.isOn() ? LightStateConverter.toBrightnessPercentType(state)
406                 : PercentType.ZERO;
407         updateState(CHANNEL_BRIGHTNESS, brightnessPercentType);
408
409         updateState(CHANNEL_SWITCH, OnOffType.from(state.isOn()));
410
411         updateState(CHANNEL_COLORTEMPERATURE,
412                 LightStateConverter.toColorTemperaturePercentType(state, colorTemperatureCapabilties));
413         updateState(CHANNEL_COLORTEMPERATURE_ABS, LightStateConverter.toColorTemperature(state));
414
415         return true;
416     }
417
418     @Override
419     public void onGroupAdded(FullGroup group) {
420         onGroupStateChanged(group);
421     }
422
423     @Override
424     public void onGroupRemoved() {
425         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/offline.group-removed");
426     }
427
428     @Override
429     public void onGroupGone() {
430         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "@text/offline.group-removed");
431     }
432
433     /**
434      * Sets the state options for applicable scenes.
435      */
436     @Override
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);
443             if (group != null) {
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());
450             }
451         }
452         stateDescriptionOptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_SCENE),
453                 stateOptions);
454     }
455
456     /**
457      * Schedules restoration of the alert item state to {@link LightStateConverter#ALERT_MODE_NONE} after a given time.
458      * <br>
459      * Based on the initial command:
460      * <ul>
461      * <li>For {@link LightStateConverter#ALERT_MODE_SELECT} restoration will be triggered after <strong>2
462      * seconds</strong>.
463      * <li>For {@link LightStateConverter#ALERT_MODE_LONG_SELECT} restoration will be triggered after <strong>15
464      * seconds</strong>.
465      * </ul>
466      * This method also cancels any previously scheduled restoration.
467      *
468      * @param command The {@link Command} sent to the item
469      */
470     private void scheduleAlertStateRestore(Command command) {
471         cancelScheduledFuture();
472         int delay = getAlertDuration(command);
473
474         if (delay > 0) {
475             scheduledFuture = scheduler.schedule(() -> {
476                 updateState(CHANNEL_ALERT, new StringType(LightStateConverter.ALERT_MODE_NONE));
477             }, delay, TimeUnit.MILLISECONDS);
478         }
479     }
480
481     /**
482      * This method will cancel previously scheduled alert item state
483      * restoration.
484      */
485     private void cancelScheduledFuture() {
486         ScheduledFuture<?> scheduledJob = scheduledFuture;
487         if (scheduledJob != null) {
488             scheduledJob.cancel(true);
489             scheduledFuture = null;
490         }
491     }
492
493     /**
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}.
496      *
497      * @param command The initial command sent to the alert item.
498      * @return Based on the initial command will return:
499      *         <ul>
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.
503      *         </ul>
504      */
505     private int getAlertDuration(Command command) {
506         int delay;
507         switch (command.toString()) {
508             case LightStateConverter.ALERT_MODE_LONG_SELECT:
509                 delay = 15000;
510                 break;
511             case LightStateConverter.ALERT_MODE_SELECT:
512                 delay = 2000;
513                 break;
514             default:
515                 delay = -1;
516                 break;
517         }
518
519         return delay;
520     }
521
522     public List<String> listScenesForConsole() {
523         return consoleScenesList;
524     }
525
526     @Override
527     public String getGroupId() {
528         return groupId;
529     }
530 }