]> git.basschouten.com Git - openhab-addons.git/blob
18014108b3e16c0605293566d1411f7c224881d6
[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.hdpowerview.internal.handler;
14
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.CopyOnWriteArrayList;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
25 import javax.ws.rs.ProcessingException;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.HttpClient;
30 import org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants;
31 import org.openhab.binding.hdpowerview.internal.HDPowerViewTranslationProvider;
32 import org.openhab.binding.hdpowerview.internal.HDPowerViewWebTargets;
33 import org.openhab.binding.hdpowerview.internal.api.Firmware;
34 import org.openhab.binding.hdpowerview.internal.api.responses.FirmwareVersions;
35 import org.openhab.binding.hdpowerview.internal.api.responses.SceneCollections;
36 import org.openhab.binding.hdpowerview.internal.api.responses.SceneCollections.SceneCollection;
37 import org.openhab.binding.hdpowerview.internal.api.responses.Scenes;
38 import org.openhab.binding.hdpowerview.internal.api.responses.Scenes.Scene;
39 import org.openhab.binding.hdpowerview.internal.api.responses.ScheduledEvents;
40 import org.openhab.binding.hdpowerview.internal.api.responses.ScheduledEvents.ScheduledEvent;
41 import org.openhab.binding.hdpowerview.internal.api.responses.Shades;
42 import org.openhab.binding.hdpowerview.internal.api.responses.Shades.ShadeData;
43 import org.openhab.binding.hdpowerview.internal.builders.AutomationChannelBuilder;
44 import org.openhab.binding.hdpowerview.internal.builders.SceneChannelBuilder;
45 import org.openhab.binding.hdpowerview.internal.builders.SceneGroupChannelBuilder;
46 import org.openhab.binding.hdpowerview.internal.config.HDPowerViewHubConfiguration;
47 import org.openhab.binding.hdpowerview.internal.config.HDPowerViewShadeConfiguration;
48 import org.openhab.binding.hdpowerview.internal.exceptions.HubException;
49 import org.openhab.binding.hdpowerview.internal.exceptions.HubInvalidResponseException;
50 import org.openhab.binding.hdpowerview.internal.exceptions.HubMaintenanceException;
51 import org.openhab.binding.hdpowerview.internal.exceptions.HubProcessingException;
52 import org.openhab.core.library.CoreItemFactory;
53 import org.openhab.core.library.types.OnOffType;
54 import org.openhab.core.thing.Bridge;
55 import org.openhab.core.thing.Channel;
56 import org.openhab.core.thing.ChannelGroupUID;
57 import org.openhab.core.thing.ChannelUID;
58 import org.openhab.core.thing.Thing;
59 import org.openhab.core.thing.ThingStatus;
60 import org.openhab.core.thing.ThingStatusDetail;
61 import org.openhab.core.thing.ThingStatusInfo;
62 import org.openhab.core.thing.ThingUID;
63 import org.openhab.core.thing.binding.BaseBridgeHandler;
64 import org.openhab.core.thing.binding.ThingHandler;
65 import org.openhab.core.thing.binding.builder.ChannelBuilder;
66 import org.openhab.core.thing.type.ChannelTypeUID;
67 import org.openhab.core.types.Command;
68 import org.openhab.core.types.RefreshType;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 /**
73  * The {@link HDPowerViewHubHandler} is responsible for handling commands, which
74  * are sent to one of the channels.
75  *
76  * @author Andy Lintner - Initial contribution
77  * @author Andrew Fiddian-Green - Added support for secondary rail positions
78  * @author Jacob Laursen - Added support for scene groups and automations
79  */
80 @NonNullByDefault
81 public class HDPowerViewHubHandler extends BaseBridgeHandler {
82
83     private final Logger logger = LoggerFactory.getLogger(HDPowerViewHubHandler.class);
84     private final HttpClient httpClient;
85     private final HDPowerViewTranslationProvider translationProvider;
86     private final ConcurrentHashMap<ThingUID, ShadeData> pendingShadeInitializations = new ConcurrentHashMap<>();
87
88     private long refreshInterval;
89     private long hardRefreshPositionInterval;
90     private long hardRefreshBatteryLevelInterval;
91
92     private @Nullable HDPowerViewWebTargets webTargets;
93     private @Nullable ScheduledFuture<?> pollFuture;
94     private @Nullable ScheduledFuture<?> hardRefreshPositionFuture;
95     private @Nullable ScheduledFuture<?> hardRefreshBatteryLevelFuture;
96
97     private List<Scene> sceneCache = new CopyOnWriteArrayList<>();
98     private List<SceneCollection> sceneCollectionCache = new CopyOnWriteArrayList<>();
99     private List<ScheduledEvent> scheduledEventCache = new CopyOnWriteArrayList<>();
100     private @Nullable FirmwareVersions firmwareVersions;
101     private Boolean deprecatedChannelsCreated = false;
102
103     private final ChannelTypeUID sceneChannelTypeUID = new ChannelTypeUID(HDPowerViewBindingConstants.BINDING_ID,
104             HDPowerViewBindingConstants.CHANNELTYPE_SCENE_ACTIVATE);
105
106     private final ChannelTypeUID sceneGroupChannelTypeUID = new ChannelTypeUID(HDPowerViewBindingConstants.BINDING_ID,
107             HDPowerViewBindingConstants.CHANNELTYPE_SCENE_GROUP_ACTIVATE);
108
109     private final ChannelTypeUID automationChannelTypeUID = new ChannelTypeUID(HDPowerViewBindingConstants.BINDING_ID,
110             HDPowerViewBindingConstants.CHANNELTYPE_AUTOMATION_ENABLED);
111
112     public HDPowerViewHubHandler(Bridge bridge, HttpClient httpClient,
113             HDPowerViewTranslationProvider translationProvider) {
114         super(bridge);
115         this.httpClient = httpClient;
116         this.translationProvider = translationProvider;
117     }
118
119     @Override
120     public void handleCommand(ChannelUID channelUID, Command command) {
121         if (RefreshType.REFRESH == command) {
122             requestRefreshShadePositions();
123             return;
124         }
125
126         Channel channel = getThing().getChannel(channelUID.getId());
127         if (channel == null) {
128             return;
129         }
130
131         try {
132             HDPowerViewWebTargets webTargets = this.webTargets;
133             if (webTargets == null) {
134                 throw new ProcessingException("Web targets not initialized");
135             }
136             int id = Integer.parseInt(channelUID.getIdWithoutGroup());
137             if (sceneChannelTypeUID.equals(channel.getChannelTypeUID()) && OnOffType.ON == command) {
138                 webTargets.activateScene(id);
139                 // Reschedule soft poll for immediate shade position update.
140                 scheduleSoftPoll();
141             } else if (sceneGroupChannelTypeUID.equals(channel.getChannelTypeUID()) && OnOffType.ON == command) {
142                 webTargets.activateSceneCollection(id);
143                 // Reschedule soft poll for immediate shade position update.
144                 scheduleSoftPoll();
145             } else if (automationChannelTypeUID.equals(channel.getChannelTypeUID())) {
146                 webTargets.enableScheduledEvent(id, OnOffType.ON == command);
147             }
148         } catch (HubMaintenanceException e) {
149             // exceptions are logged in HDPowerViewWebTargets
150         } catch (NumberFormatException | HubException e) {
151             logger.debug("Unexpected error {}", e.getMessage());
152         }
153     }
154
155     @Override
156     public void initialize() {
157         logger.debug("Initializing hub");
158         HDPowerViewHubConfiguration config = getConfigAs(HDPowerViewHubConfiguration.class);
159         String host = config.host;
160
161         if (host == null || host.isEmpty()) {
162             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
163                     "@text/offline.conf-error.no-host-address");
164             return;
165         }
166
167         updateStatus(ThingStatus.UNKNOWN);
168         pendingShadeInitializations.clear();
169         webTargets = new HDPowerViewWebTargets(httpClient, host);
170         refreshInterval = config.refresh;
171         hardRefreshPositionInterval = config.hardRefresh;
172         hardRefreshBatteryLevelInterval = config.hardRefreshBatteryLevel;
173         initializeChannels();
174         firmwareVersions = null;
175         schedulePoll();
176     }
177
178     private void initializeChannels() {
179         // Rebuild dynamic channels and synchronize with cache.
180         updateThing(editThing().withChannels(new ArrayList<Channel>()).build());
181         sceneCache.clear();
182         sceneCollectionCache.clear();
183         scheduledEventCache.clear();
184         deprecatedChannelsCreated = false;
185     }
186
187     public @Nullable HDPowerViewWebTargets getWebTargets() {
188         return webTargets;
189     }
190
191     @Override
192     public void handleRemoval() {
193         super.handleRemoval();
194         stopPoll();
195     }
196
197     @Override
198     public void dispose() {
199         super.dispose();
200         stopPoll();
201         pendingShadeInitializations.clear();
202     }
203
204     @Override
205     public void childHandlerInitialized(final ThingHandler childHandler, final Thing childThing) {
206         logger.debug("Child handler initialized: {}", childThing.getUID());
207         if (childHandler instanceof HDPowerViewShadeHandler) {
208             ShadeData shadeData = pendingShadeInitializations.remove(childThing.getUID());
209             if (shadeData != null) {
210                 if (shadeData.id > 0) {
211                     updateShadeThing(shadeData.id, childThing, shadeData);
212                 } else {
213                     updateUnknownShadeThing(childThing);
214                 }
215             }
216         }
217         super.childHandlerInitialized(childHandler, childThing);
218     }
219
220     @Override
221     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
222         logger.debug("Child handler disposed: {}", childThing.getUID());
223         if (childHandler instanceof HDPowerViewShadeHandler) {
224             pendingShadeInitializations.remove(childThing.getUID());
225         }
226         super.childHandlerDisposed(childHandler, childThing);
227     }
228
229     private void schedulePoll() {
230         scheduleSoftPoll();
231         scheduleHardPoll();
232     }
233
234     private void scheduleSoftPoll() {
235         ScheduledFuture<?> future = this.pollFuture;
236         if (future != null) {
237             future.cancel(false);
238         }
239         logger.debug("Scheduling poll every {} ms", refreshInterval);
240         this.pollFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, refreshInterval, TimeUnit.MILLISECONDS);
241     }
242
243     private void scheduleHardPoll() {
244         ScheduledFuture<?> future = this.hardRefreshPositionFuture;
245         if (future != null) {
246             future.cancel(false);
247         }
248         if (hardRefreshPositionInterval > 0) {
249             logger.debug("Scheduling hard position refresh every {} minutes", hardRefreshPositionInterval);
250             this.hardRefreshPositionFuture = scheduler.scheduleWithFixedDelay(this::requestRefreshShadePositions, 1,
251                     hardRefreshPositionInterval, TimeUnit.MINUTES);
252         }
253
254         future = this.hardRefreshBatteryLevelFuture;
255         if (future != null) {
256             future.cancel(false);
257         }
258         if (hardRefreshBatteryLevelInterval > 0) {
259             logger.debug("Scheduling hard battery level refresh every {} hours", hardRefreshBatteryLevelInterval);
260             this.hardRefreshBatteryLevelFuture = scheduler.scheduleWithFixedDelay(
261                     this::requestRefreshShadeBatteryLevels, 1, hardRefreshBatteryLevelInterval, TimeUnit.HOURS);
262         }
263     }
264
265     private synchronized void stopPoll() {
266         ScheduledFuture<?> future = this.pollFuture;
267         if (future != null) {
268             future.cancel(true);
269         }
270         this.pollFuture = null;
271
272         future = this.hardRefreshPositionFuture;
273         if (future != null) {
274             future.cancel(true);
275         }
276         this.hardRefreshPositionFuture = null;
277
278         future = this.hardRefreshBatteryLevelFuture;
279         if (future != null) {
280             future.cancel(true);
281         }
282         this.hardRefreshBatteryLevelFuture = null;
283     }
284
285     private synchronized void poll() {
286         try {
287             updateFirmwareProperties();
288         } catch (HubException e) {
289             logger.warn("Failed to update firmware properties: {}", e.getMessage());
290         }
291
292         try {
293             logger.debug("Polling for state");
294             pollShades();
295
296             List<Scene> scenes = updateSceneChannels();
297             List<SceneCollection> sceneCollections = updateSceneGroupChannels();
298             List<ScheduledEvent> scheduledEvents = updateAutomationChannels(scenes, sceneCollections);
299
300             // Scheduled events should also have their current state updated if event has been
301             // enabled or disabled through app or other integration.
302             updateAutomationStates(scheduledEvents);
303         } catch (HubInvalidResponseException e) {
304             Throwable cause = e.getCause();
305             if (cause == null) {
306                 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
307             } else {
308                 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
309             }
310         } catch (HubMaintenanceException e) {
311             // exceptions are logged in HDPowerViewWebTargets
312         } catch (HubException e) {
313             logger.warn("Error connecting to bridge: {}", e.getMessage());
314             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
315         }
316     }
317
318     private void updateFirmwareProperties()
319             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
320         if (firmwareVersions != null) {
321             return;
322         }
323         HDPowerViewWebTargets webTargets = this.webTargets;
324         if (webTargets == null) {
325             throw new ProcessingException("Web targets not initialized");
326         }
327         FirmwareVersions firmwareVersions = webTargets.getFirmwareVersions();
328         Firmware mainProcessor = firmwareVersions.mainProcessor;
329         if (mainProcessor == null) {
330             logger.warn("Main processor firmware version missing in response.");
331             return;
332         }
333         logger.debug("Main processor firmware version received: {}, {}", mainProcessor.name, mainProcessor.toString());
334         Map<String, String> properties = editProperties();
335         String mainProcessorName = mainProcessor.name;
336         if (mainProcessorName != null) {
337             properties.put(HDPowerViewBindingConstants.PROPERTY_FIRMWARE_NAME, mainProcessorName);
338         }
339         properties.put(Thing.PROPERTY_FIRMWARE_VERSION, mainProcessor.toString());
340         Firmware radio = firmwareVersions.radio;
341         if (radio != null) {
342             logger.debug("Radio firmware version received: {}", radio.toString());
343             properties.put(HDPowerViewBindingConstants.PROPERTY_RADIO_FIRMWARE_VERSION, radio.toString());
344         }
345         updateProperties(properties);
346     }
347
348     private void pollShades() throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
349         HDPowerViewWebTargets webTargets = this.webTargets;
350         if (webTargets == null) {
351             throw new ProcessingException("Web targets not initialized");
352         }
353
354         Shades shades = webTargets.getShades();
355         List<ShadeData> shadesData = shades.shadeData;
356         if (shadesData == null) {
357             throw new HubInvalidResponseException("Missing 'shades.shadeData' element");
358         }
359
360         updateStatus(ThingStatus.ONLINE);
361         logger.debug("Received data for {} shades", shadesData.size());
362
363         Map<Integer, ShadeData> idShadeDataMap = getIdShadeDataMap(shadesData);
364         Map<Thing, Integer> thingIdMap = getShadeThingIdMap();
365         for (Entry<Thing, Integer> item : thingIdMap.entrySet()) {
366             Thing thing = item.getKey();
367             int shadeId = item.getValue();
368             ShadeData shadeData = idShadeDataMap.get(shadeId);
369             if (shadeData != null) {
370                 updateShadeThing(shadeId, thing, shadeData);
371             } else {
372                 updateUnknownShadeThing(thing);
373             }
374         }
375     }
376
377     private void updateShadeThing(int shadeId, Thing thing, ShadeData shadeData) {
378         HDPowerViewShadeHandler thingHandler = ((HDPowerViewShadeHandler) thing.getHandler());
379         if (thingHandler == null) {
380             logger.debug("Shade '{}' handler not initialized", shadeId);
381             pendingShadeInitializations.put(thing.getUID(), shadeData);
382             return;
383         }
384         ThingStatus thingStatus = thingHandler.getThing().getStatus();
385         switch (thingStatus) {
386             case UNKNOWN:
387             case ONLINE:
388             case OFFLINE:
389                 logger.debug("Updating shade '{}'", shadeId);
390                 thingHandler.onReceiveUpdate(shadeData);
391                 break;
392             case UNINITIALIZED:
393             case INITIALIZING:
394                 logger.debug("Shade '{}' handler not yet ready; status: {}", shadeId, thingStatus);
395                 pendingShadeInitializations.put(thing.getUID(), shadeData);
396                 break;
397             case REMOVING:
398             case REMOVED:
399             default:
400                 logger.debug("Ignoring shade update for shade '{}' in status {}", shadeId, thingStatus);
401                 break;
402         }
403     }
404
405     private void updateUnknownShadeThing(Thing thing) {
406         String shadeId = thing.getUID().getId();
407         logger.debug("Shade '{}' has no data in hub", shadeId);
408         HDPowerViewShadeHandler thingHandler = ((HDPowerViewShadeHandler) thing.getHandler());
409         if (thingHandler == null) {
410             logger.debug("Shade '{}' handler not initialized", shadeId);
411             pendingShadeInitializations.put(thing.getUID(), new ShadeData());
412             return;
413         }
414         ThingStatus thingStatus = thingHandler.getThing().getStatus();
415         switch (thingStatus) {
416             case UNKNOWN:
417             case ONLINE:
418             case OFFLINE:
419                 thing.setStatusInfo(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.GONE,
420                         "@text/offline.gone.shade-unknown-to-hub"));
421                 break;
422             case UNINITIALIZED:
423             case INITIALIZING:
424                 logger.debug("Shade '{}' handler not yet ready; status: {}", shadeId, thingStatus);
425                 pendingShadeInitializations.put(thing.getUID(), new ShadeData());
426                 break;
427             case REMOVING:
428             case REMOVED:
429             default:
430                 logger.debug("Ignoring shade status update for shade '{}' in status {}", shadeId, thingStatus);
431                 break;
432         }
433     }
434
435     private List<Scene> fetchScenes()
436             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
437         HDPowerViewWebTargets webTargets = this.webTargets;
438         if (webTargets == null) {
439             throw new ProcessingException("Web targets not initialized");
440         }
441
442         Scenes scenes = webTargets.getScenes();
443         List<Scene> sceneData = scenes.sceneData;
444         if (sceneData == null) {
445             throw new HubInvalidResponseException("Missing 'scenes.sceneData' element");
446         }
447         logger.debug("Received data for {} scenes", sceneData.size());
448
449         return sceneData;
450     }
451
452     private List<Scene> updateSceneChannels()
453             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
454         List<Scene> scenes = fetchScenes();
455
456         if (scenes.size() == sceneCache.size() && sceneCache.containsAll(scenes)) {
457             // Duplicates are not allowed. Reordering is not supported.
458             logger.debug("Preserving scene channels, no changes detected");
459             return scenes;
460         }
461
462         logger.debug("Updating all scene channels, changes detected");
463         sceneCache = new CopyOnWriteArrayList<Scene>(scenes);
464
465         List<Channel> allChannels = new ArrayList<>(getThing().getChannels());
466         allChannels.removeIf(c -> HDPowerViewBindingConstants.CHANNEL_GROUP_SCENES.equals(c.getUID().getGroupId()));
467
468         SceneChannelBuilder channelBuilder = SceneChannelBuilder
469                 .create(this.translationProvider,
470                         new ChannelGroupUID(thing.getUID(), HDPowerViewBindingConstants.CHANNEL_GROUP_SCENES))
471                 .withScenes(scenes).withChannels(allChannels);
472
473         updateThing(editThing().withChannels(channelBuilder.build()).build());
474
475         createDeprecatedSceneChannels(scenes);
476
477         return scenes;
478     }
479
480     /**
481      * Create backwards compatible scene channels if any items configured before release 3.2
482      * are still linked. Users should have a reasonable amount of time to migrate to the new
483      * scene channels that are connected to a channel group.
484      */
485     private void createDeprecatedSceneChannels(List<Scene> scenes) {
486         if (deprecatedChannelsCreated) {
487             // Only do this once.
488             return;
489         }
490         ChannelGroupUID channelGroupUid = new ChannelGroupUID(thing.getUID(),
491                 HDPowerViewBindingConstants.CHANNEL_GROUP_SCENES);
492         for (Scene scene : scenes) {
493             String channelId = Integer.toString(scene.id);
494             ChannelUID newChannelUid = new ChannelUID(channelGroupUid, channelId);
495             ChannelUID deprecatedChannelUid = new ChannelUID(getThing().getUID(), channelId);
496             String description = translationProvider.getText("dynamic-channel.scene-activate.deprecated.description",
497                     scene.getName());
498             Channel channel = ChannelBuilder.create(deprecatedChannelUid, CoreItemFactory.SWITCH)
499                     .withType(sceneChannelTypeUID).withLabel(scene.getName()).withDescription(description).build();
500             logger.debug("Creating deprecated channel '{}' ('{}') to probe for linked items", deprecatedChannelUid,
501                     scene.getName());
502             updateThing(editThing().withChannel(channel).build());
503             if (this.isLinked(deprecatedChannelUid) && !this.isLinked(newChannelUid)) {
504                 logger.warn("Created deprecated channel '{}' ('{}'), please link items to '{}' instead",
505                         deprecatedChannelUid, scene.getName(), newChannelUid);
506             } else {
507                 if (this.isLinked(newChannelUid)) {
508                     logger.debug("Removing deprecated channel '{}' ('{}') since new channel '{}' is linked",
509                             deprecatedChannelUid, scene.getName(), newChannelUid);
510
511                 } else {
512                     logger.debug("Removing deprecated channel '{}' ('{}') since it has no linked items",
513                             deprecatedChannelUid, scene.getName());
514                 }
515                 updateThing(editThing().withoutChannel(deprecatedChannelUid).build());
516             }
517         }
518         deprecatedChannelsCreated = true;
519     }
520
521     private List<SceneCollection> fetchSceneCollections()
522             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
523         HDPowerViewWebTargets webTargets = this.webTargets;
524         if (webTargets == null) {
525             throw new ProcessingException("Web targets not initialized");
526         }
527
528         SceneCollections sceneCollections = webTargets.getSceneCollections();
529         List<SceneCollection> sceneCollectionData = sceneCollections.sceneCollectionData;
530         if (sceneCollectionData == null) {
531             throw new HubInvalidResponseException("Missing 'sceneCollections.sceneCollectionData' element");
532         }
533         logger.debug("Received data for {} sceneCollections", sceneCollectionData.size());
534
535         return sceneCollectionData;
536     }
537
538     private List<SceneCollection> updateSceneGroupChannels()
539             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
540         List<SceneCollection> sceneCollections = fetchSceneCollections();
541
542         if (sceneCollections.size() == sceneCollectionCache.size()
543                 && sceneCollectionCache.containsAll(sceneCollections)) {
544             // Duplicates are not allowed. Reordering is not supported.
545             logger.debug("Preserving scene group channels, no changes detected");
546             return sceneCollections;
547         }
548
549         logger.debug("Updating all scene group channels, changes detected");
550         sceneCollectionCache = new CopyOnWriteArrayList<SceneCollection>(sceneCollections);
551
552         List<Channel> allChannels = new ArrayList<>(getThing().getChannels());
553         allChannels
554                 .removeIf(c -> HDPowerViewBindingConstants.CHANNEL_GROUP_SCENE_GROUPS.equals(c.getUID().getGroupId()));
555
556         SceneGroupChannelBuilder channelBuilder = SceneGroupChannelBuilder
557                 .create(this.translationProvider,
558                         new ChannelGroupUID(thing.getUID(), HDPowerViewBindingConstants.CHANNEL_GROUP_SCENE_GROUPS))
559                 .withSceneCollections(sceneCollections).withChannels(allChannels);
560
561         updateThing(editThing().withChannels(channelBuilder.build()).build());
562
563         return sceneCollections;
564     }
565
566     private List<ScheduledEvent> fetchScheduledEvents()
567             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
568         HDPowerViewWebTargets webTargets = this.webTargets;
569         if (webTargets == null) {
570             throw new ProcessingException("Web targets not initialized");
571         }
572
573         ScheduledEvents scheduledEvents = webTargets.getScheduledEvents();
574         List<ScheduledEvent> scheduledEventData = scheduledEvents.scheduledEventData;
575         if (scheduledEventData == null) {
576             throw new HubInvalidResponseException("Missing 'scheduledEvents.scheduledEventData' element");
577         }
578         logger.debug("Received data for {} scheduledEvents", scheduledEventData.size());
579
580         return scheduledEventData;
581     }
582
583     private List<ScheduledEvent> updateAutomationChannels(List<Scene> scenes, List<SceneCollection> sceneCollections)
584             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
585         List<ScheduledEvent> scheduledEvents = fetchScheduledEvents();
586
587         if (scheduledEvents.size() == scheduledEventCache.size() && scheduledEventCache.containsAll(scheduledEvents)) {
588             // Duplicates are not allowed. Reordering is not supported.
589             logger.debug("Preserving automation channels, no changes detected");
590             return scheduledEvents;
591         }
592
593         logger.debug("Updating all automation channels, changes detected");
594         scheduledEventCache = new CopyOnWriteArrayList<ScheduledEvent>(scheduledEvents);
595
596         List<Channel> allChannels = new ArrayList<>(getThing().getChannels());
597         allChannels
598                 .removeIf(c -> HDPowerViewBindingConstants.CHANNEL_GROUP_AUTOMATIONS.equals(c.getUID().getGroupId()));
599         AutomationChannelBuilder channelBuilder = AutomationChannelBuilder
600                 .create(this.translationProvider,
601                         new ChannelGroupUID(thing.getUID(), HDPowerViewBindingConstants.CHANNEL_GROUP_AUTOMATIONS))
602                 .withScenes(scenes).withSceneCollections(sceneCollections).withScheduledEvents(scheduledEvents)
603                 .withChannels(allChannels);
604         updateThing(editThing().withChannels(channelBuilder.build()).build());
605
606         return scheduledEvents;
607     }
608
609     private void updateAutomationStates(List<ScheduledEvent> scheduledEvents) {
610         ChannelGroupUID channelGroupUid = new ChannelGroupUID(thing.getUID(),
611                 HDPowerViewBindingConstants.CHANNEL_GROUP_AUTOMATIONS);
612         for (ScheduledEvent scheduledEvent : scheduledEvents) {
613             String scheduledEventId = Integer.toString(scheduledEvent.id);
614             ChannelUID channelUid = new ChannelUID(channelGroupUid, scheduledEventId);
615             updateState(channelUid, scheduledEvent.enabled ? OnOffType.ON : OnOffType.OFF);
616         }
617     }
618
619     private Map<Thing, Integer> getShadeThingIdMap() {
620         Map<Thing, Integer> ret = new HashMap<>();
621         getThing().getThings().stream()
622                 .filter(thing -> HDPowerViewBindingConstants.THING_TYPE_SHADE.equals(thing.getThingTypeUID()))
623                 .forEach(thing -> {
624                     int id = thing.getConfiguration().as(HDPowerViewShadeConfiguration.class).id;
625                     if (id > 0) {
626                         ret.put(thing, id);
627                     }
628                 });
629         return ret;
630     }
631
632     private Map<Integer, ShadeData> getIdShadeDataMap(List<ShadeData> shadeData) {
633         Map<Integer, ShadeData> ret = new HashMap<>();
634         for (ShadeData shade : shadeData) {
635             if (shade.id > 0) {
636                 ret.put(shade.id, shade);
637             }
638         }
639         return ret;
640     }
641
642     private void requestRefreshShadePositions() {
643         Map<Thing, Integer> thingIdMap = getShadeThingIdMap();
644         for (Entry<Thing, Integer> item : thingIdMap.entrySet()) {
645             Thing thing = item.getKey();
646             if (thing.getStatusInfo().getStatusDetail() == ThingStatusDetail.GONE) {
647                 // Skip shades unknown to the Hub.
648                 logger.debug("Shade '{}' is unknown, skipping position refresh", item.getValue());
649                 continue;
650             }
651             ThingHandler handler = thing.getHandler();
652             if (handler instanceof HDPowerViewShadeHandler) {
653                 ((HDPowerViewShadeHandler) handler).requestRefreshShadePosition();
654             } else {
655                 int shadeId = item.getValue();
656                 logger.debug("Shade '{}' handler not initialized", shadeId);
657             }
658         }
659     }
660
661     private void requestRefreshShadeBatteryLevels() {
662         Map<Thing, Integer> thingIdMap = getShadeThingIdMap();
663         for (Entry<Thing, Integer> item : thingIdMap.entrySet()) {
664             Thing thing = item.getKey();
665             if (thing.getStatusInfo().getStatusDetail() == ThingStatusDetail.GONE) {
666                 // Skip shades unknown to the Hub.
667                 logger.debug("Shade '{}' is unknown, skipping battery level refresh", item.getValue());
668                 continue;
669             }
670             ThingHandler handler = thing.getHandler();
671             if (handler instanceof HDPowerViewShadeHandler) {
672                 ((HDPowerViewShadeHandler) handler).requestRefreshShadeBatteryLevel();
673             } else {
674                 int shadeId = item.getValue();
675                 logger.debug("Shade '{}' handler not initialized", shadeId);
676             }
677         }
678     }
679 }