]> git.basschouten.com Git - openhab-addons.git/blob
aabdf973577c68c331ff8f31e81476b657061d60
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.io.IOException;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.Optional;
24 import java.util.Set;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.Future;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.hue.internal.config.Clip2BridgeConfig;
34 import org.openhab.binding.hue.internal.connection.Clip2Bridge;
35 import org.openhab.binding.hue.internal.connection.HueTlsTrustManagerProvider;
36 import org.openhab.binding.hue.internal.discovery.Clip2ThingDiscoveryService;
37 import org.openhab.binding.hue.internal.dto.clip2.MetaData;
38 import org.openhab.binding.hue.internal.dto.clip2.ProductData;
39 import org.openhab.binding.hue.internal.dto.clip2.Resource;
40 import org.openhab.binding.hue.internal.dto.clip2.ResourceReference;
41 import org.openhab.binding.hue.internal.dto.clip2.Resources;
42 import org.openhab.binding.hue.internal.dto.clip2.enums.Archetype;
43 import org.openhab.binding.hue.internal.dto.clip2.enums.ResourceType;
44 import org.openhab.binding.hue.internal.exceptions.ApiException;
45 import org.openhab.binding.hue.internal.exceptions.AssetNotLoadedException;
46 import org.openhab.binding.hue.internal.exceptions.HttpUnauthorizedException;
47 import org.openhab.core.config.core.Configuration;
48 import org.openhab.core.i18n.LocaleProvider;
49 import org.openhab.core.i18n.TranslationProvider;
50 import org.openhab.core.io.net.http.HttpClientFactory;
51 import org.openhab.core.io.net.http.TlsTrustManagerProvider;
52 import org.openhab.core.thing.Bridge;
53 import org.openhab.core.thing.ChannelUID;
54 import org.openhab.core.thing.Thing;
55 import org.openhab.core.thing.ThingRegistry;
56 import org.openhab.core.thing.ThingStatus;
57 import org.openhab.core.thing.ThingStatusDetail;
58 import org.openhab.core.thing.ThingTypeUID;
59 import org.openhab.core.thing.ThingUID;
60 import org.openhab.core.thing.binding.BaseBridgeHandler;
61 import org.openhab.core.thing.binding.ThingHandler;
62 import org.openhab.core.thing.binding.ThingHandlerService;
63 import org.openhab.core.thing.binding.builder.BridgeBuilder;
64 import org.openhab.core.types.Command;
65 import org.openhab.core.types.RefreshType;
66 import org.osgi.framework.Bundle;
67 import org.osgi.framework.FrameworkUtil;
68 import org.osgi.framework.ServiceRegistration;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 /**
73  * Bridge handler for a CLIP 2 bridge. It communicates with the bridge via CLIP 2 end points, and reads and writes API
74  * V2 resource objects. It also subscribes to the server's SSE event stream, and receives SSE events from it.
75  *
76  * @author Andrew Fiddian-Green - Initial contribution.
77  */
78 @NonNullByDefault
79 public class Clip2BridgeHandler extends BaseBridgeHandler {
80
81     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE_API2);
82
83     private static final int FAST_SCHEDULE_MILLI_SECONDS = 500;
84     private static final int APPLICATION_KEY_MAX_TRIES = 600; // i.e. 300 seconds, 5 minutes
85     private static final int RECONNECT_DELAY_SECONDS = 10;
86     private static final int RECONNECT_MAX_TRIES = 5;
87
88     private static final ResourceReference DEVICE = new ResourceReference().setType(ResourceType.DEVICE);
89     private static final ResourceReference ROOM = new ResourceReference().setType(ResourceType.ROOM);
90     private static final ResourceReference ZONE = new ResourceReference().setType(ResourceType.ZONE);
91     private static final ResourceReference BRIDGE = new ResourceReference().setType(ResourceType.BRIDGE);
92     private static final ResourceReference BRIDGE_HOME = new ResourceReference().setType(ResourceType.BRIDGE_HOME);
93     private static final ResourceReference SCENE = new ResourceReference().setType(ResourceType.SCENE);
94
95     /**
96      * List of resource references that need to be mass down loaded.
97      * NOTE: the SCENE resources must be mass down loaded first!
98      */
99     private static final List<ResourceReference> MASS_DOWNLOAD_RESOURCE_REFERENCES = List.of(SCENE, DEVICE, ROOM, ZONE);
100
101     private final Logger logger = LoggerFactory.getLogger(Clip2BridgeHandler.class);
102
103     private final HttpClientFactory httpClientFactory;
104     private final ThingRegistry thingRegistry;
105     private final Bundle bundle;
106     private final LocaleProvider localeProvider;
107     private final TranslationProvider translationProvider;
108
109     private @Nullable Clip2Bridge clip2Bridge;
110     private @Nullable ServiceRegistration<?> trustManagerRegistration;
111     private @Nullable Clip2ThingDiscoveryService discoveryService;
112
113     private @Nullable Future<?> checkConnectionTask;
114     private @Nullable Future<?> updateOnlineStateTask;
115     private @Nullable ScheduledFuture<?> scheduledUpdateTask;
116     private Map<Integer, Future<?>> resourcesEventTasks = new ConcurrentHashMap<>();
117
118     private boolean assetsLoaded;
119     private int applKeyRetriesRemaining;
120     private int connectRetriesRemaining;
121
122     public Clip2BridgeHandler(Bridge bridge, HttpClientFactory httpClientFactory, ThingRegistry thingRegistry,
123             LocaleProvider localeProvider, TranslationProvider translationProvider) {
124         super(bridge);
125         this.httpClientFactory = httpClientFactory;
126         this.thingRegistry = thingRegistry;
127         this.bundle = FrameworkUtil.getBundle(getClass());
128         this.localeProvider = localeProvider;
129         this.translationProvider = translationProvider;
130     }
131
132     /**
133      * Cancel the given task.
134      *
135      * @param cancelTask the task to be cancelled (may be null)
136      * @param mayInterrupt allows cancel() to interrupt the thread.
137      */
138     private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
139         if (Objects.nonNull(cancelTask)) {
140             cancelTask.cancel(mayInterrupt);
141         }
142     }
143
144     /**
145      * Check if assets are loaded.
146      *
147      * @throws AssetNotLoadedException if assets not loaded.
148      */
149     private void checkAssetsLoaded() throws AssetNotLoadedException {
150         if (!assetsLoaded) {
151             throw new AssetNotLoadedException("Assets not loaded");
152         }
153     }
154
155     /**
156      * Try to connect and set the online status accordingly. If the connection attempt throws an
157      * HttpUnAuthorizedException then try to register the existing application key, or create a new one, with the hub.
158      * If the connection attempt throws an ApiException then set the thing status to offline. This method is called on a
159      * scheduler thread, which reschedules itself repeatedly until the thing is shutdown.
160      */
161     private synchronized void checkConnection() {
162         logger.debug("checkConnection()");
163
164         boolean retryApplicationKey = false;
165         boolean retryConnection = false;
166
167         try {
168             checkAssetsLoaded();
169             getClip2Bridge().testConnectionState();
170             updateSelf(); // go online
171         } catch (HttpUnauthorizedException unauthorizedException) {
172             logger.debug("checkConnection() {}", unauthorizedException.getMessage(), unauthorizedException);
173             if (applKeyRetriesRemaining > 0) {
174                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
175                         "@text/offline.api2.conf-error.press-pairing-button");
176                 try {
177                     registerApplicationKey();
178                     retryApplicationKey = true;
179                 } catch (HttpUnauthorizedException e) {
180                     retryApplicationKey = true;
181                 } catch (ApiException e) {
182                     setStatusOfflineWithCommunicationError(e);
183                 } catch (IllegalStateException e) {
184                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
185                             "@text/offline.api2.conf-error.read-only");
186                 } catch (AssetNotLoadedException e) {
187                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
188                             "@text/offline.api2.conf-error.assets-not-loaded");
189                 } catch (InterruptedException e) {
190                     return;
191                 }
192             } else {
193                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
194                         "@text/offline.api2.conf-error.not-authorized");
195             }
196         } catch (ApiException e) {
197             logger.debug("checkConnection() {}", e.getMessage(), e);
198             setStatusOfflineWithCommunicationError(e);
199             retryConnection = connectRetriesRemaining > 0;
200         } catch (AssetNotLoadedException e) {
201             logger.debug("checkConnection() {}", e.getMessage(), e);
202             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
203                     "@text/offline.api2.conf-error.assets-not-loaded");
204         } catch (InterruptedException e) {
205             return;
206         }
207
208         int milliSeconds;
209         if (retryApplicationKey) {
210             // short delay used during attempts to create or validate an application key
211             milliSeconds = FAST_SCHEDULE_MILLI_SECONDS;
212             applKeyRetriesRemaining--;
213         } else {
214             // default delay, set via configuration parameter, used as heart-beat 'just-in-case'
215             Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
216             milliSeconds = config.checkMinutes * 60000;
217             if (retryConnection) {
218                 // exponential back off delay used during attempts to reconnect
219                 int backOffDelay = 60000 * (int) Math.pow(2, RECONNECT_MAX_TRIES - connectRetriesRemaining);
220                 milliSeconds = Math.min(milliSeconds, backOffDelay);
221                 connectRetriesRemaining--;
222             }
223         }
224
225         // this method schedules itself to be called again in a loop..
226         cancelTask(checkConnectionTask, false);
227         checkConnectionTask = scheduler.schedule(() -> checkConnection(), milliSeconds, TimeUnit.MILLISECONDS);
228     }
229
230     private void setStatusOfflineWithCommunicationError(Exception e) {
231         Throwable cause = e.getCause();
232         String causeMessage = cause == null ? null : cause.getMessage();
233         if (causeMessage == null || causeMessage.isEmpty()) {
234             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
235                     "@text/offline.api2.comm-error.exception [\"" + e.getMessage() + "\"]");
236         } else {
237             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
238                     "@text/offline.api2.comm-error.exception [\"" + e.getMessage() + " -> " + causeMessage + "\"]");
239         }
240     }
241
242     /**
243      * If a child thing has been added, and the bridge is online, update the child's data.
244      */
245     public void childInitialized() {
246         if (thing.getStatus() == ThingStatus.ONLINE) {
247             updateThingsScheduled(5000);
248         }
249     }
250
251     @Override
252     public void dispose() {
253         if (assetsLoaded) {
254             disposeAssets();
255         }
256     }
257
258     /**
259      * Dispose the bridge handler's assets. Called from dispose() on a thread, so that dispose() itself can complete
260      * faster.
261      */
262     private void disposeAssets() {
263         logger.debug("disposeAssets() {}", this);
264         synchronized (this) {
265             assetsLoaded = false;
266             cancelTask(checkConnectionTask, true);
267             cancelTask(updateOnlineStateTask, true);
268             cancelTask(scheduledUpdateTask, true);
269             checkConnectionTask = null;
270             updateOnlineStateTask = null;
271             scheduledUpdateTask = null;
272             synchronized (resourcesEventTasks) {
273                 resourcesEventTasks.values().forEach(task -> cancelTask(task, true));
274                 resourcesEventTasks.clear();
275             }
276             ServiceRegistration<?> registration = trustManagerRegistration;
277             if (Objects.nonNull(registration)) {
278                 registration.unregister();
279                 trustManagerRegistration = null;
280             }
281             Clip2Bridge bridge = clip2Bridge;
282             if (Objects.nonNull(bridge)) {
283                 bridge.close();
284                 clip2Bridge = null;
285             }
286             Clip2ThingDiscoveryService disco = discoveryService;
287             if (Objects.nonNull(disco)) {
288                 disco.abortScan();
289             }
290         }
291     }
292
293     /**
294      * Return the application key for the console app.
295      *
296      * @return the application key.
297      */
298     public String getApplicationKey() {
299         Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
300         return config.applicationKey;
301     }
302
303     /**
304      * Get the Clip2Bridge connection and throw an exception if it is null.
305      *
306      * @return the Clip2Bridge.
307      * @throws AssetNotLoadedException if the Clip2Bridge is null.
308      */
309     private Clip2Bridge getClip2Bridge() throws AssetNotLoadedException {
310         Clip2Bridge clip2Bridge = this.clip2Bridge;
311         if (Objects.nonNull(clip2Bridge)) {
312             return clip2Bridge;
313         }
314         throw new AssetNotLoadedException("Clip2Bridge is null");
315     }
316
317     /**
318      * Return the IP address for the console app.
319      *
320      * @return the IP address.
321      */
322     public String getIpAddress() {
323         Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
324         return config.ipAddress;
325     }
326
327     /**
328      * Get the v1 legacy Hue bridge (if any) which has the same IP address as this.
329      *
330      * @return Optional result containing the legacy bridge (if any found).
331      */
332     public Optional<Thing> getLegacyBridge() {
333         String ipAddress = getIpAddress();
334         return Objects.nonNull(ipAddress)
335                 ? thingRegistry.getAll().stream()
336                         .filter(thing -> thing.getThingTypeUID().equals(THING_TYPE_BRIDGE)
337                                 && ipAddress.equals(thing.getConfiguration().get("ipAddress")))
338                         .findFirst()
339                 : Optional.empty();
340     }
341
342     /**
343      * Get the v1 legacy Hue thing (if any) which has a Bridge having the same IP address as this, and an ID that
344      * matches the given parameter.
345      *
346      * @param targetIdV1 the idV1 attribute to match.
347      * @return Optional result containing the legacy thing (if found).
348      */
349     public Optional<Thing> getLegacyThing(String targetIdV1) {
350         Optional<Thing> legacyBridge = getLegacyBridge();
351         if (legacyBridge.isEmpty()) {
352             return Optional.empty();
353         }
354
355         String config;
356         if (targetIdV1.startsWith("/lights/")) {
357             config = LIGHT_ID;
358         } else if (targetIdV1.startsWith("/sensors/")) {
359             config = SENSOR_ID;
360         } else if (targetIdV1.startsWith("/groups/")) {
361             config = GROUP_ID;
362         } else {
363             return Optional.empty();
364         }
365
366         ThingUID legacyBridgeUID = legacyBridge.get().getUID();
367         return thingRegistry.getAll().stream() //
368                 .filter(thing -> legacyBridgeUID.equals(thing.getBridgeUID())
369                         && V1_THING_TYPE_UIDS.contains(thing.getThingTypeUID())) //
370                 .filter(thing -> {
371                     Object id = thing.getConfiguration().get(config);
372                     return (id instanceof String) && targetIdV1.endsWith("/" + (String) id);
373                 }).findFirst();
374     }
375
376     /**
377      * Return a localized text.
378      *
379      * @param key the i18n text key.
380      * @param arguments for parameterized translation.
381      * @return the localized text.
382      */
383     public String getLocalizedText(String key, @Nullable Object @Nullable... arguments) {
384         String result = translationProvider.getText(bundle, key, key, localeProvider.getLocale(), arguments);
385         return Objects.nonNull(result) ? result : key;
386     }
387
388     /**
389      * Execute an HTTP GET for a resources reference object from the server.
390      *
391      * @param reference containing the resourceType and (optionally) the resourceId of the resource to get. If the
392      *            resourceId is null then all resources of the given type are returned.
393      * @return the resource, or null if something fails.
394      * @throws ApiException if a communication error occurred.
395      * @throws AssetNotLoadedException if one of the assets is not loaded.
396      * @throws InterruptedException
397      */
398     public Resources getResources(ResourceReference reference)
399             throws ApiException, AssetNotLoadedException, InterruptedException {
400         logger.debug("getResources() {}", reference);
401         checkAssetsLoaded();
402         return getClip2Bridge().getResources(reference);
403     }
404
405     /**
406      * Getter for the scheduler.
407      *
408      * @return the scheduler.
409      */
410     public ScheduledExecutorService getScheduler() {
411         return scheduler;
412     }
413
414     @Override
415     public Collection<Class<? extends ThingHandlerService>> getServices() {
416         return Set.of(Clip2ThingDiscoveryService.class);
417     }
418
419     @Override
420     public void handleCommand(ChannelUID channelUID, Command command) {
421         if (RefreshType.REFRESH.equals(command)) {
422             return;
423         }
424         logger.warn("Bridge thing '{}' has no channels, only REFRESH command supported.", thing.getUID());
425     }
426
427     @Override
428     public void initialize() {
429         updateThingFromLegacy();
430         updateStatus(ThingStatus.UNKNOWN);
431         applKeyRetriesRemaining = APPLICATION_KEY_MAX_TRIES;
432         connectRetriesRemaining = RECONNECT_MAX_TRIES;
433         initializeAssets();
434     }
435
436     /**
437      * Initialize the bridge handler's assets.
438      */
439     private void initializeAssets() {
440         logger.debug("initializeAssets() {}", this);
441         synchronized (this) {
442             Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
443
444             String ipAddress = config.ipAddress;
445             if (ipAddress.isBlank()) {
446                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
447                         "@text/offline.conf-error-no-ip-address");
448                 return;
449             }
450
451             try {
452                 if (!Clip2Bridge.isClip2Supported(ipAddress)) {
453                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
454                             "@text/offline.api2.conf-error.clip2-not-supported");
455                     return;
456                 }
457             } catch (IOException e) {
458                 logger.trace("initializeAssets() communication error on '{}'", ipAddress, e);
459                 setStatusOfflineWithCommunicationError(e);
460                 return;
461             }
462
463             HueTlsTrustManagerProvider trustManagerProvider = new HueTlsTrustManagerProvider(ipAddress + ":443",
464                     config.useSelfSignedCertificate);
465
466             if (Objects.isNull(trustManagerProvider.getPEMTrustManager())) {
467                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
468                         "@text/offline.api2.conf-error.certificate-load");
469                 return;
470             }
471
472             trustManagerRegistration = FrameworkUtil.getBundle(getClass()).getBundleContext()
473                     .registerService(TlsTrustManagerProvider.class.getName(), trustManagerProvider, null);
474
475             String applicationKey = config.applicationKey;
476             applicationKey = Objects.nonNull(applicationKey) ? applicationKey : "";
477
478             try {
479                 clip2Bridge = new Clip2Bridge(httpClientFactory, this, ipAddress, applicationKey);
480             } catch (ApiException e) {
481                 logger.trace("initializeAssets() communication error on '{}'", ipAddress, e);
482                 setStatusOfflineWithCommunicationError(e);
483                 return;
484             }
485
486             assetsLoaded = true;
487         }
488         cancelTask(checkConnectionTask, false);
489         checkConnectionTask = scheduler.submit(() -> checkConnection());
490     }
491
492     /**
493      * Called when the connection goes offline. Schedule a reconnection.
494      */
495     public void onConnectionOffline() {
496         if (assetsLoaded) {
497             cancelTask(checkConnectionTask, false);
498             checkConnectionTask = scheduler.schedule(() -> checkConnection(), RECONNECT_DELAY_SECONDS,
499                     TimeUnit.SECONDS);
500         }
501     }
502
503     /**
504      * Called when the connection goes online. Schedule a general state update.
505      */
506     public void onConnectionOnline() {
507         cancelTask(updateOnlineStateTask, false);
508         updateOnlineStateTask = scheduler.schedule(() -> updateOnlineState(), 0, TimeUnit.MILLISECONDS);
509     }
510
511     /**
512      * Called when an SSE event message comes in with a valid list of resources. For each resource received, inform all
513      * child thing handlers with the respective resource.
514      *
515      * @param resources a list of incoming resource objects.
516      */
517     public void onResourcesEvent(List<Resource> resources) {
518         if (assetsLoaded) {
519             synchronized (resourcesEventTasks) {
520                 int index = resourcesEventTasks.size();
521                 resourcesEventTasks.put(index, scheduler.submit(() -> {
522                     onResourcesEventTask(resources);
523                     resourcesEventTasks.remove(index);
524                 }));
525             }
526         }
527     }
528
529     private void onResourcesEventTask(List<Resource> resources) {
530         logger.debug("onResourcesEventTask() resource count {}", resources.size());
531         getThing().getThings().forEach(thing -> {
532             ThingHandler handler = thing.getHandler();
533             if (handler instanceof Clip2ThingHandler) {
534                 resources.forEach(resource -> {
535                     ((Clip2ThingHandler) handler).onResource(resource);
536                 });
537             }
538         });
539     }
540
541     /**
542      * Execute an HTTP PUT to send a Resource object to the server.
543      *
544      * @param resource the resource to put.
545      * @return the resource, which may contain errors.
546      * @throws ApiException if a communication error occurred.
547      * @throws AssetNotLoadedException if one of the assets is not loaded.
548      * @throws InterruptedException
549      */
550     public Resources putResource(Resource resource) throws ApiException, AssetNotLoadedException, InterruptedException {
551         logger.debug("putResource() {}", resource);
552         checkAssetsLoaded();
553         return getClip2Bridge().putResource(resource);
554     }
555
556     /**
557      * Register the application key with the hub. If the current application key is empty it will create a new one.
558      *
559      * @throws HttpUnauthorizedException if the communication was OK but the registration failed anyway.
560      * @throws ApiException if a communication error occurred.
561      * @throws AssetNotLoadedException if one of the assets is not loaded.
562      * @throws IllegalStateException if the configuration cannot be changed e.g. read only.
563      * @throws InterruptedException
564      */
565     private void registerApplicationKey() throws HttpUnauthorizedException, ApiException, AssetNotLoadedException,
566             IllegalStateException, InterruptedException {
567         logger.debug("registerApplicationKey()");
568         Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
569         String newApplicationKey = getClip2Bridge().registerApplicationKey(config.applicationKey);
570         Configuration configuration = editConfiguration();
571         configuration.put(Clip2BridgeConfig.APPLICATION_KEY, newApplicationKey);
572         updateConfiguration(configuration);
573     }
574
575     /**
576      * Register the discovery service.
577      *
578      * @param discoveryService new discoveryService.
579      */
580     public void registerDiscoveryService(Clip2ThingDiscoveryService discoveryService) {
581         this.discoveryService = discoveryService;
582     }
583
584     /**
585      * Unregister the discovery service.
586      */
587     public void unregisterDiscoveryService() {
588         discoveryService = null;
589     }
590
591     /**
592      * Update the bridge's online state and update its dependent things. Called when the connection goes online.
593      */
594     private void updateOnlineState() {
595         if (assetsLoaded && (thing.getStatus() != ThingStatus.ONLINE)) {
596             logger.debug("updateOnlineState()");
597             connectRetriesRemaining = RECONNECT_MAX_TRIES;
598             updateStatus(ThingStatus.ONLINE);
599             updateThingsScheduled(500);
600             Clip2ThingDiscoveryService discoveryService = this.discoveryService;
601             if (Objects.nonNull(discoveryService)) {
602                 discoveryService.startScan(null);
603             }
604         }
605     }
606
607     /**
608      * Update the bridge thing properties.
609      *
610      * @throws ApiException if a communication error occurred.
611      * @throws AssetNotLoadedException if one of the assets is not loaded.
612      * @throws InterruptedException
613      */
614     private void updateProperties() throws ApiException, AssetNotLoadedException, InterruptedException {
615         logger.debug("updateProperties()");
616         Map<String, String> properties = new HashMap<>(thing.getProperties());
617
618         for (Resource device : getClip2Bridge().getResources(BRIDGE).getResources()) {
619             // set the serial number
620             String bridgeId = device.getBridgeId();
621             if (Objects.nonNull(bridgeId)) {
622                 properties.put(Thing.PROPERTY_SERIAL_NUMBER, bridgeId);
623             }
624             break;
625         }
626
627         for (Resource device : getClip2Bridge().getResources(DEVICE).getResources()) {
628             MetaData metaData = device.getMetaData();
629             if (Objects.nonNull(metaData) && metaData.getArchetype() == Archetype.BRIDGE_V2) {
630                 // set resource properties
631                 properties.put(PROPERTY_RESOURCE_ID, device.getId());
632                 properties.put(PROPERTY_RESOURCE_TYPE, device.getType().toString());
633
634                 // set metadata properties
635                 String metaDataName = metaData.getName();
636                 if (Objects.nonNull(metaDataName)) {
637                     properties.put(PROPERTY_RESOURCE_NAME, metaDataName);
638                 }
639                 properties.put(PROPERTY_RESOURCE_ARCHETYPE, metaData.getArchetype().toString());
640
641                 // set product data properties
642                 ProductData productData = device.getProductData();
643                 if (Objects.nonNull(productData)) {
644                     // set generic thing properties
645                     properties.put(Thing.PROPERTY_MODEL_ID, productData.getModelId());
646                     properties.put(Thing.PROPERTY_VENDOR, productData.getManufacturerName());
647                     properties.put(Thing.PROPERTY_FIRMWARE_VERSION, productData.getSoftwareVersion());
648                     String hardwarePlatformType = productData.getHardwarePlatformType();
649                     if (Objects.nonNull(hardwarePlatformType)) {
650                         properties.put(Thing.PROPERTY_HARDWARE_VERSION, hardwarePlatformType);
651                     }
652
653                     // set hue specific properties
654                     properties.put(PROPERTY_PRODUCT_NAME, productData.getProductName());
655                     properties.put(PROPERTY_PRODUCT_ARCHETYPE, productData.getProductArchetype().toString());
656                     properties.put(PROPERTY_PRODUCT_CERTIFIED, productData.getCertified().toString());
657                 }
658                 break; // we only needed the BRIDGE_V2 resource
659             }
660         }
661         thing.setProperties(properties);
662     }
663
664     /**
665      * Update the thing's own state. Called sporadically in case any SSE events may have been lost.
666      */
667     private void updateSelf() {
668         logger.debug("updateSelf()");
669         try {
670             checkAssetsLoaded();
671             updateProperties();
672             getClip2Bridge().open();
673         } catch (ApiException e) {
674             logger.trace("updateSelf() {}", e.getMessage(), e);
675             setStatusOfflineWithCommunicationError(e);
676             onConnectionOffline();
677         } catch (AssetNotLoadedException e) {
678             logger.trace("updateSelf() {}", e.getMessage(), e);
679             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
680                     "@text/offline.api2.conf-error.assets-not-loaded");
681         } catch (InterruptedException e) {
682         }
683     }
684
685     /**
686      * Check if a PROPERTY_LEGACY_THING_UID value was set by the discovery process, and if so, clone the legacy thing's
687      * settings into this thing.
688      */
689     private void updateThingFromLegacy() {
690         if (isInitialized()) {
691             logger.warn("Cannot update bridge thing '{}' from legacy since handler already initialized.",
692                     thing.getUID());
693             return;
694         }
695         Map<String, String> properties = thing.getProperties();
696         String legacyThingUID = properties.get(PROPERTY_LEGACY_THING_UID);
697         if (Objects.nonNull(legacyThingUID)) {
698             Thing legacyThing = thingRegistry.get(new ThingUID(legacyThingUID));
699             if (Objects.nonNull(legacyThing)) {
700                 BridgeBuilder editBuilder = editThing();
701
702                 String location = legacyThing.getLocation();
703                 if (Objects.nonNull(location) && !location.isBlank()) {
704                     editBuilder = editBuilder.withLocation(location);
705                 }
706
707                 Object userName = legacyThing.getConfiguration().get(USER_NAME);
708                 if (userName instanceof String) {
709                     Configuration configuration = thing.getConfiguration();
710                     configuration.put(Clip2BridgeConfig.APPLICATION_KEY, userName);
711                     editBuilder = editBuilder.withConfiguration(configuration);
712                 }
713
714                 Map<String, String> newProperties = new HashMap<>(properties);
715                 newProperties.remove(PROPERTY_LEGACY_THING_UID);
716
717                 updateThing(editBuilder.withProperties(newProperties).build());
718             }
719         }
720     }
721
722     /**
723      * Execute the mass download of all relevant resource types, and inform all child thing handlers.
724      */
725     private void updateThingsNow() {
726         logger.debug("updateThingsNow()");
727         try {
728             Clip2Bridge bridge = getClip2Bridge();
729             for (ResourceReference reference : MASS_DOWNLOAD_RESOURCE_REFERENCES) {
730                 ResourceType resourceType = reference.getType();
731                 List<Resource> resourceList = bridge.getResources(reference).getResources();
732                 if (resourceType == ResourceType.ZONE) {
733                     // add special 'All Lights' zone to the zone resource list
734                     resourceList.addAll(bridge.getResources(BRIDGE_HOME).getResources());
735                 }
736                 getThing().getThings().forEach(thing -> {
737                     ThingHandler handler = thing.getHandler();
738                     if (handler instanceof Clip2ThingHandler) {
739                         ((Clip2ThingHandler) handler).onResourcesList(resourceType, resourceList);
740                     }
741                 });
742             }
743         } catch (ApiException | AssetNotLoadedException e) {
744             if (logger.isDebugEnabled()) {
745                 logger.debug("updateThingsNow() unexpected exception", e);
746             } else {
747                 logger.warn("Unexpected exception '{}' while updating things.", e.getMessage());
748             }
749         } catch (InterruptedException e) {
750         }
751     }
752
753     /**
754      * Schedule a task to call updateThings(). It prevents floods of GET calls when multiple child things are added at
755      * the same time.
756      *
757      * @param delayMilliSeconds the delay before running the next task.
758      */
759     private void updateThingsScheduled(int delayMilliSeconds) {
760         ScheduledFuture<?> task = this.scheduledUpdateTask;
761         if (Objects.isNull(task) || task.getDelay(TimeUnit.MILLISECONDS) < 100) {
762             cancelTask(scheduledUpdateTask, false);
763             scheduledUpdateTask = scheduler.schedule(() -> updateThingsNow(), delayMilliSeconds, TimeUnit.MILLISECONDS);
764         }
765     }
766 }