]> git.basschouten.com Git - openhab-addons.git/blob
cfea061f28e0e9488b8f80d13788ce7a1e2049b0
[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         pendingShadeInitializations.clear();
168         webTargets = new HDPowerViewWebTargets(httpClient, host);
169         refreshInterval = config.refresh;
170         hardRefreshPositionInterval = config.hardRefresh;
171         hardRefreshBatteryLevelInterval = config.hardRefreshBatteryLevel;
172         initializeChannels();
173         schedulePoll();
174     }
175
176     private void initializeChannels() {
177         // Rebuild dynamic channels and synchronize with cache.
178         updateThing(editThing().withChannels(new ArrayList<Channel>()).build());
179         sceneCache.clear();
180         sceneCollectionCache.clear();
181         scheduledEventCache.clear();
182         deprecatedChannelsCreated = false;
183     }
184
185     public @Nullable HDPowerViewWebTargets getWebTargets() {
186         return webTargets;
187     }
188
189     @Override
190     public void handleRemoval() {
191         super.handleRemoval();
192         stopPoll();
193     }
194
195     @Override
196     public void dispose() {
197         super.dispose();
198         stopPoll();
199         pendingShadeInitializations.clear();
200     }
201
202     @Override
203     public void childHandlerInitialized(final ThingHandler childHandler, final Thing childThing) {
204         logger.debug("Child handler initialized: {}", childThing.getUID());
205         if (childHandler instanceof HDPowerViewShadeHandler) {
206             ShadeData shadeData = pendingShadeInitializations.remove(childThing.getUID());
207             if (shadeData != null) {
208                 if (shadeData.id > 0) {
209                     updateShadeThing(shadeData.id, childThing, shadeData);
210                 } else {
211                     updateUnknownShadeThing(childThing);
212                 }
213             }
214         }
215         super.childHandlerInitialized(childHandler, childThing);
216     }
217
218     @Override
219     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
220         logger.debug("Child handler disposed: {}", childThing.getUID());
221         if (childHandler instanceof HDPowerViewShadeHandler) {
222             pendingShadeInitializations.remove(childThing.getUID());
223         }
224         super.childHandlerDisposed(childHandler, childThing);
225     }
226
227     private void schedulePoll() {
228         scheduleSoftPoll();
229         scheduleHardPoll();
230     }
231
232     private void scheduleSoftPoll() {
233         ScheduledFuture<?> future = this.pollFuture;
234         if (future != null) {
235             future.cancel(false);
236         }
237         logger.debug("Scheduling poll every {} ms", refreshInterval);
238         this.pollFuture = scheduler.scheduleWithFixedDelay(this::poll, 0, refreshInterval, TimeUnit.MILLISECONDS);
239     }
240
241     private void scheduleHardPoll() {
242         ScheduledFuture<?> future = this.hardRefreshPositionFuture;
243         if (future != null) {
244             future.cancel(false);
245         }
246         if (hardRefreshPositionInterval > 0) {
247             logger.debug("Scheduling hard position refresh every {} minutes", hardRefreshPositionInterval);
248             this.hardRefreshPositionFuture = scheduler.scheduleWithFixedDelay(this::requestRefreshShadePositions, 1,
249                     hardRefreshPositionInterval, TimeUnit.MINUTES);
250         }
251
252         future = this.hardRefreshBatteryLevelFuture;
253         if (future != null) {
254             future.cancel(false);
255         }
256         if (hardRefreshBatteryLevelInterval > 0) {
257             logger.debug("Scheduling hard battery level refresh every {} hours", hardRefreshBatteryLevelInterval);
258             this.hardRefreshBatteryLevelFuture = scheduler.scheduleWithFixedDelay(
259                     this::requestRefreshShadeBatteryLevels, 1, hardRefreshBatteryLevelInterval, TimeUnit.HOURS);
260         }
261     }
262
263     private synchronized void stopPoll() {
264         ScheduledFuture<?> future = this.pollFuture;
265         if (future != null) {
266             future.cancel(true);
267         }
268         this.pollFuture = null;
269
270         future = this.hardRefreshPositionFuture;
271         if (future != null) {
272             future.cancel(true);
273         }
274         this.hardRefreshPositionFuture = null;
275
276         future = this.hardRefreshBatteryLevelFuture;
277         if (future != null) {
278             future.cancel(true);
279         }
280         this.hardRefreshBatteryLevelFuture = null;
281     }
282
283     private synchronized void poll() {
284         try {
285             logger.debug("Polling for state");
286             updateFirmwareProperties();
287             pollShades();
288
289             List<Scene> scenes = updateSceneChannels();
290             List<SceneCollection> sceneCollections = updateSceneGroupChannels();
291             List<ScheduledEvent> scheduledEvents = updateAutomationChannels(scenes, sceneCollections);
292
293             // Scheduled events should also have their current state updated if event has been
294             // enabled or disabled through app or other integration.
295             updateAutomationStates(scheduledEvents);
296         } catch (HubInvalidResponseException e) {
297             Throwable cause = e.getCause();
298             if (cause == null) {
299                 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
300             } else {
301                 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
302             }
303         } catch (HubMaintenanceException e) {
304             // exceptions are logged in HDPowerViewWebTargets
305         } catch (HubException e) {
306             logger.warn("Error connecting to bridge: {}", e.getMessage());
307             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage());
308         }
309     }
310
311     private void updateFirmwareProperties()
312             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
313         if (firmwareVersions != null) {
314             return;
315         }
316         HDPowerViewWebTargets webTargets = this.webTargets;
317         if (webTargets == null) {
318             throw new ProcessingException("Web targets not initialized");
319         }
320         FirmwareVersions firmwareVersions = webTargets.getFirmwareVersions();
321         Firmware mainProcessor = firmwareVersions.mainProcessor;
322         if (mainProcessor == null) {
323             logger.warn("Main processor firmware version missing in response.");
324             return;
325         }
326         logger.debug("Main processor firmware version received: {}, {}", mainProcessor.name, mainProcessor.toString());
327         Map<String, String> properties = editProperties();
328         String mainProcessorName = mainProcessor.name;
329         if (mainProcessorName != null) {
330             properties.put(HDPowerViewBindingConstants.PROPERTY_FIRMWARE_NAME, mainProcessorName);
331         }
332         properties.put(Thing.PROPERTY_FIRMWARE_VERSION, mainProcessor.toString());
333         Firmware radio = firmwareVersions.radio;
334         if (radio != null) {
335             logger.debug("Radio firmware version received: {}", radio.toString());
336             properties.put(HDPowerViewBindingConstants.PROPERTY_RADIO_FIRMWARE_VERSION, radio.toString());
337         }
338         updateProperties(properties);
339     }
340
341     private void pollShades() throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
342         HDPowerViewWebTargets webTargets = this.webTargets;
343         if (webTargets == null) {
344             throw new ProcessingException("Web targets not initialized");
345         }
346
347         Shades shades = webTargets.getShades();
348         List<ShadeData> shadesData = shades.shadeData;
349         if (shadesData == null) {
350             throw new HubInvalidResponseException("Missing 'shades.shadeData' element");
351         }
352
353         updateStatus(ThingStatus.ONLINE);
354         logger.debug("Received data for {} shades", shadesData.size());
355
356         Map<Integer, ShadeData> idShadeDataMap = getIdShadeDataMap(shadesData);
357         Map<Thing, Integer> thingIdMap = getShadeThingIdMap();
358         for (Entry<Thing, Integer> item : thingIdMap.entrySet()) {
359             Thing thing = item.getKey();
360             int shadeId = item.getValue();
361             ShadeData shadeData = idShadeDataMap.get(shadeId);
362             if (shadeData != null) {
363                 updateShadeThing(shadeId, thing, shadeData);
364             } else {
365                 updateUnknownShadeThing(thing);
366             }
367         }
368     }
369
370     private void updateShadeThing(int shadeId, Thing thing, ShadeData shadeData) {
371         HDPowerViewShadeHandler thingHandler = ((HDPowerViewShadeHandler) thing.getHandler());
372         if (thingHandler == null) {
373             logger.debug("Shade '{}' handler not initialized", shadeId);
374             pendingShadeInitializations.put(thing.getUID(), shadeData);
375             return;
376         }
377         ThingStatus thingStatus = thingHandler.getThing().getStatus();
378         switch (thingStatus) {
379             case UNKNOWN:
380             case ONLINE:
381             case OFFLINE:
382                 logger.debug("Updating shade '{}'", shadeId);
383                 thingHandler.onReceiveUpdate(shadeData);
384                 break;
385             case UNINITIALIZED:
386             case INITIALIZING:
387                 logger.debug("Shade '{}' handler not yet ready; status: {}", shadeId, thingStatus);
388                 pendingShadeInitializations.put(thing.getUID(), shadeData);
389                 break;
390             case REMOVING:
391             case REMOVED:
392             default:
393                 logger.debug("Ignoring shade update for shade '{}' in status {}", shadeId, thingStatus);
394                 break;
395         }
396     }
397
398     private void updateUnknownShadeThing(Thing thing) {
399         String shadeId = thing.getUID().getId();
400         logger.debug("Shade '{}' has no data in hub", shadeId);
401         HDPowerViewShadeHandler thingHandler = ((HDPowerViewShadeHandler) thing.getHandler());
402         if (thingHandler == null) {
403             logger.debug("Shade '{}' handler not initialized", shadeId);
404             pendingShadeInitializations.put(thing.getUID(), new ShadeData());
405             return;
406         }
407         ThingStatus thingStatus = thingHandler.getThing().getStatus();
408         switch (thingStatus) {
409             case UNKNOWN:
410             case ONLINE:
411             case OFFLINE:
412                 thing.setStatusInfo(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.GONE,
413                         "@text/offline.gone.shade-unknown-to-hub"));
414                 break;
415             case UNINITIALIZED:
416             case INITIALIZING:
417                 logger.debug("Shade '{}' handler not yet ready; status: {}", shadeId, thingStatus);
418                 pendingShadeInitializations.put(thing.getUID(), new ShadeData());
419                 break;
420             case REMOVING:
421             case REMOVED:
422             default:
423                 logger.debug("Ignoring shade status update for shade '{}' in status {}", shadeId, thingStatus);
424                 break;
425         }
426     }
427
428     private List<Scene> fetchScenes()
429             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
430         HDPowerViewWebTargets webTargets = this.webTargets;
431         if (webTargets == null) {
432             throw new ProcessingException("Web targets not initialized");
433         }
434
435         Scenes scenes = webTargets.getScenes();
436         List<Scene> sceneData = scenes.sceneData;
437         if (sceneData == null) {
438             throw new HubInvalidResponseException("Missing 'scenes.sceneData' element");
439         }
440         logger.debug("Received data for {} scenes", sceneData.size());
441
442         return sceneData;
443     }
444
445     private List<Scene> updateSceneChannels()
446             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
447         List<Scene> scenes = fetchScenes();
448
449         if (scenes.size() == sceneCache.size() && sceneCache.containsAll(scenes)) {
450             // Duplicates are not allowed. Reordering is not supported.
451             logger.debug("Preserving scene channels, no changes detected");
452             return scenes;
453         }
454
455         logger.debug("Updating all scene channels, changes detected");
456         sceneCache = new CopyOnWriteArrayList<Scene>(scenes);
457
458         List<Channel> allChannels = new ArrayList<>(getThing().getChannels());
459         allChannels.removeIf(c -> HDPowerViewBindingConstants.CHANNEL_GROUP_SCENES.equals(c.getUID().getGroupId()));
460
461         SceneChannelBuilder channelBuilder = SceneChannelBuilder
462                 .create(this.translationProvider,
463                         new ChannelGroupUID(thing.getUID(), HDPowerViewBindingConstants.CHANNEL_GROUP_SCENES))
464                 .withScenes(scenes).withChannels(allChannels);
465
466         updateThing(editThing().withChannels(channelBuilder.build()).build());
467
468         createDeprecatedSceneChannels(scenes);
469
470         return scenes;
471     }
472
473     /**
474      * Create backwards compatible scene channels if any items configured before release 3.2
475      * are still linked. Users should have a reasonable amount of time to migrate to the new
476      * scene channels that are connected to a channel group.
477      */
478     private void createDeprecatedSceneChannels(List<Scene> scenes) {
479         if (deprecatedChannelsCreated) {
480             // Only do this once.
481             return;
482         }
483         ChannelGroupUID channelGroupUid = new ChannelGroupUID(thing.getUID(),
484                 HDPowerViewBindingConstants.CHANNEL_GROUP_SCENES);
485         for (Scene scene : scenes) {
486             String channelId = Integer.toString(scene.id);
487             ChannelUID newChannelUid = new ChannelUID(channelGroupUid, channelId);
488             ChannelUID deprecatedChannelUid = new ChannelUID(getThing().getUID(), channelId);
489             String description = translationProvider.getText("dynamic-channel.scene-activate.deprecated.description",
490                     scene.getName());
491             Channel channel = ChannelBuilder.create(deprecatedChannelUid, CoreItemFactory.SWITCH)
492                     .withType(sceneChannelTypeUID).withLabel(scene.getName()).withDescription(description).build();
493             logger.debug("Creating deprecated channel '{}' ('{}') to probe for linked items", deprecatedChannelUid,
494                     scene.getName());
495             updateThing(editThing().withChannel(channel).build());
496             if (this.isLinked(deprecatedChannelUid) && !this.isLinked(newChannelUid)) {
497                 logger.warn("Created deprecated channel '{}' ('{}'), please link items to '{}' instead",
498                         deprecatedChannelUid, scene.getName(), newChannelUid);
499             } else {
500                 if (this.isLinked(newChannelUid)) {
501                     logger.debug("Removing deprecated channel '{}' ('{}') since new channel '{}' is linked",
502                             deprecatedChannelUid, scene.getName(), newChannelUid);
503
504                 } else {
505                     logger.debug("Removing deprecated channel '{}' ('{}') since it has no linked items",
506                             deprecatedChannelUid, scene.getName());
507                 }
508                 updateThing(editThing().withoutChannel(deprecatedChannelUid).build());
509             }
510         }
511         deprecatedChannelsCreated = true;
512     }
513
514     private List<SceneCollection> fetchSceneCollections()
515             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
516         HDPowerViewWebTargets webTargets = this.webTargets;
517         if (webTargets == null) {
518             throw new ProcessingException("Web targets not initialized");
519         }
520
521         SceneCollections sceneCollections = webTargets.getSceneCollections();
522         List<SceneCollection> sceneCollectionData = sceneCollections.sceneCollectionData;
523         if (sceneCollectionData == null) {
524             throw new HubInvalidResponseException("Missing 'sceneCollections.sceneCollectionData' element");
525         }
526         logger.debug("Received data for {} sceneCollections", sceneCollectionData.size());
527
528         return sceneCollectionData;
529     }
530
531     private List<SceneCollection> updateSceneGroupChannels()
532             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
533         List<SceneCollection> sceneCollections = fetchSceneCollections();
534
535         if (sceneCollections.size() == sceneCollectionCache.size()
536                 && sceneCollectionCache.containsAll(sceneCollections)) {
537             // Duplicates are not allowed. Reordering is not supported.
538             logger.debug("Preserving scene group channels, no changes detected");
539             return sceneCollections;
540         }
541
542         logger.debug("Updating all scene group channels, changes detected");
543         sceneCollectionCache = new CopyOnWriteArrayList<SceneCollection>(sceneCollections);
544
545         List<Channel> allChannels = new ArrayList<>(getThing().getChannels());
546         allChannels
547                 .removeIf(c -> HDPowerViewBindingConstants.CHANNEL_GROUP_SCENE_GROUPS.equals(c.getUID().getGroupId()));
548
549         SceneGroupChannelBuilder channelBuilder = SceneGroupChannelBuilder
550                 .create(this.translationProvider,
551                         new ChannelGroupUID(thing.getUID(), HDPowerViewBindingConstants.CHANNEL_GROUP_SCENE_GROUPS))
552                 .withSceneCollections(sceneCollections).withChannels(allChannels);
553
554         updateThing(editThing().withChannels(channelBuilder.build()).build());
555
556         return sceneCollections;
557     }
558
559     private List<ScheduledEvent> fetchScheduledEvents()
560             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
561         HDPowerViewWebTargets webTargets = this.webTargets;
562         if (webTargets == null) {
563             throw new ProcessingException("Web targets not initialized");
564         }
565
566         ScheduledEvents scheduledEvents = webTargets.getScheduledEvents();
567         List<ScheduledEvent> scheduledEventData = scheduledEvents.scheduledEventData;
568         if (scheduledEventData == null) {
569             throw new HubInvalidResponseException("Missing 'scheduledEvents.scheduledEventData' element");
570         }
571         logger.debug("Received data for {} scheduledEvents", scheduledEventData.size());
572
573         return scheduledEventData;
574     }
575
576     private List<ScheduledEvent> updateAutomationChannels(List<Scene> scenes, List<SceneCollection> sceneCollections)
577             throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
578         List<ScheduledEvent> scheduledEvents = fetchScheduledEvents();
579
580         if (scheduledEvents.size() == scheduledEventCache.size() && scheduledEventCache.containsAll(scheduledEvents)) {
581             // Duplicates are not allowed. Reordering is not supported.
582             logger.debug("Preserving automation channels, no changes detected");
583             return scheduledEvents;
584         }
585
586         logger.debug("Updating all automation channels, changes detected");
587         scheduledEventCache = new CopyOnWriteArrayList<ScheduledEvent>(scheduledEvents);
588
589         List<Channel> allChannels = new ArrayList<>(getThing().getChannels());
590         allChannels
591                 .removeIf(c -> HDPowerViewBindingConstants.CHANNEL_GROUP_AUTOMATIONS.equals(c.getUID().getGroupId()));
592         AutomationChannelBuilder channelBuilder = AutomationChannelBuilder
593                 .create(this.translationProvider,
594                         new ChannelGroupUID(thing.getUID(), HDPowerViewBindingConstants.CHANNEL_GROUP_AUTOMATIONS))
595                 .withScenes(scenes).withSceneCollections(sceneCollections).withScheduledEvents(scheduledEvents)
596                 .withChannels(allChannels);
597         updateThing(editThing().withChannels(channelBuilder.build()).build());
598
599         return scheduledEvents;
600     }
601
602     private void updateAutomationStates(List<ScheduledEvent> scheduledEvents) {
603         ChannelGroupUID channelGroupUid = new ChannelGroupUID(thing.getUID(),
604                 HDPowerViewBindingConstants.CHANNEL_GROUP_AUTOMATIONS);
605         for (ScheduledEvent scheduledEvent : scheduledEvents) {
606             String scheduledEventId = Integer.toString(scheduledEvent.id);
607             ChannelUID channelUid = new ChannelUID(channelGroupUid, scheduledEventId);
608             updateState(channelUid, scheduledEvent.enabled ? OnOffType.ON : OnOffType.OFF);
609         }
610     }
611
612     private Map<Thing, Integer> getShadeThingIdMap() {
613         Map<Thing, Integer> ret = new HashMap<>();
614         getThing().getThings().stream()
615                 .filter(thing -> HDPowerViewBindingConstants.THING_TYPE_SHADE.equals(thing.getThingTypeUID()))
616                 .forEach(thing -> {
617                     int id = thing.getConfiguration().as(HDPowerViewShadeConfiguration.class).id;
618                     if (id > 0) {
619                         ret.put(thing, id);
620                     }
621                 });
622         return ret;
623     }
624
625     private Map<Integer, ShadeData> getIdShadeDataMap(List<ShadeData> shadeData) {
626         Map<Integer, ShadeData> ret = new HashMap<>();
627         for (ShadeData shade : shadeData) {
628             if (shade.id > 0) {
629                 ret.put(shade.id, shade);
630             }
631         }
632         return ret;
633     }
634
635     private void requestRefreshShadePositions() {
636         Map<Thing, Integer> thingIdMap = getShadeThingIdMap();
637         for (Entry<Thing, Integer> item : thingIdMap.entrySet()) {
638             Thing thing = item.getKey();
639             if (thing.getStatusInfo().getStatusDetail() == ThingStatusDetail.GONE) {
640                 // Skip shades unknown to the Hub.
641                 logger.debug("Shade '{}' is unknown, skipping position refresh", item.getValue());
642                 continue;
643             }
644             ThingHandler handler = thing.getHandler();
645             if (handler instanceof HDPowerViewShadeHandler) {
646                 ((HDPowerViewShadeHandler) handler).requestRefreshShadePosition();
647             } else {
648                 int shadeId = item.getValue();
649                 logger.debug("Shade '{}' handler not initialized", shadeId);
650             }
651         }
652     }
653
654     private void requestRefreshShadeBatteryLevels() {
655         Map<Thing, Integer> thingIdMap = getShadeThingIdMap();
656         for (Entry<Thing, Integer> item : thingIdMap.entrySet()) {
657             Thing thing = item.getKey();
658             if (thing.getStatusInfo().getStatusDetail() == ThingStatusDetail.GONE) {
659                 // Skip shades unknown to the Hub.
660                 logger.debug("Shade '{}' is unknown, skipping battery level refresh", item.getValue());
661                 continue;
662             }
663             ThingHandler handler = thing.getHandler();
664             if (handler instanceof HDPowerViewShadeHandler) {
665                 ((HDPowerViewShadeHandler) handler).requestRefreshShadeBatteryLevel();
666             } else {
667                 int shadeId = item.getValue();
668                 logger.debug("Shade '{}' handler not initialized", shadeId);
669             }
670         }
671     }
672 }