2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.hue.internal.handler;
15 import static org.openhab.binding.hue.internal.HueBindingConstants.*;
17 import java.io.IOException;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.Objects;
23 import java.util.Optional;
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;
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;
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.
76 * @author Andrew Fiddian-Green - Initial contribution.
79 public class Clip2BridgeHandler extends BaseBridgeHandler {
81 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE_API2);
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;
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);
96 * List of resource references that need to be mass down loaded.
97 * NOTE: the SCENE resources must be mass down loaded first!
99 private static final List<ResourceReference> MASS_DOWNLOAD_RESOURCE_REFERENCES = List.of(SCENE, DEVICE, ROOM, ZONE);
101 private final Logger logger = LoggerFactory.getLogger(Clip2BridgeHandler.class);
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;
109 private @Nullable Clip2Bridge clip2Bridge;
110 private @Nullable ServiceRegistration<?> trustManagerRegistration;
111 private @Nullable Clip2ThingDiscoveryService discoveryService;
113 private @Nullable Future<?> checkConnectionTask;
114 private @Nullable Future<?> updateOnlineStateTask;
115 private @Nullable ScheduledFuture<?> scheduledUpdateTask;
116 private Map<Integer, Future<?>> resourcesEventTasks = new ConcurrentHashMap<>();
118 private boolean assetsLoaded;
119 private int applKeyRetriesRemaining;
120 private int connectRetriesRemaining;
122 public Clip2BridgeHandler(Bridge bridge, HttpClientFactory httpClientFactory, ThingRegistry thingRegistry,
123 LocaleProvider localeProvider, TranslationProvider translationProvider) {
125 this.httpClientFactory = httpClientFactory;
126 this.thingRegistry = thingRegistry;
127 this.bundle = FrameworkUtil.getBundle(getClass());
128 this.localeProvider = localeProvider;
129 this.translationProvider = translationProvider;
133 * Cancel the given task.
135 * @param cancelTask the task to be cancelled (may be null)
136 * @param mayInterrupt allows cancel() to interrupt the thread.
138 private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
139 if (Objects.nonNull(cancelTask)) {
140 cancelTask.cancel(mayInterrupt);
145 * Check if assets are loaded.
147 * @throws AssetNotLoadedException if assets not loaded.
149 private void checkAssetsLoaded() throws AssetNotLoadedException {
151 throw new AssetNotLoadedException("Assets not loaded");
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.
161 private synchronized void checkConnection() {
162 logger.debug("checkConnection()");
164 boolean retryApplicationKey = false;
165 boolean retryConnection = false;
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");
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) {
193 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
194 "@text/offline.api2.conf-error.not-authorized");
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) {
209 if (retryApplicationKey) {
210 // short delay used during attempts to create or validate an application key
211 milliSeconds = FAST_SCHEDULE_MILLI_SECONDS;
212 applKeyRetriesRemaining--;
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--;
225 // this method schedules itself to be called again in a loop..
226 cancelTask(checkConnectionTask, false);
227 checkConnectionTask = scheduler.schedule(() -> checkConnection(), milliSeconds, TimeUnit.MILLISECONDS);
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() + "\"]");
237 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
238 "@text/offline.api2.comm-error.exception [\"" + e.getMessage() + " -> " + causeMessage + "\"]");
243 * If a child thing has been added, and the bridge is online, update the child's data.
245 public void childInitialized() {
246 if (thing.getStatus() == ThingStatus.ONLINE) {
247 updateThingsScheduled(5000);
252 public void dispose() {
259 * Dispose the bridge handler's assets. Called from dispose() on a thread, so that dispose() itself can complete
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();
276 ServiceRegistration<?> registration = trustManagerRegistration;
277 if (Objects.nonNull(registration)) {
278 registration.unregister();
279 trustManagerRegistration = null;
281 Clip2Bridge bridge = clip2Bridge;
282 if (Objects.nonNull(bridge)) {
286 Clip2ThingDiscoveryService disco = discoveryService;
287 if (Objects.nonNull(disco)) {
294 * Return the application key for the console app.
296 * @return the application key.
298 public String getApplicationKey() {
299 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
300 return config.applicationKey;
304 * Get the Clip2Bridge connection and throw an exception if it is null.
306 * @return the Clip2Bridge.
307 * @throws AssetNotLoadedException if the Clip2Bridge is null.
309 private Clip2Bridge getClip2Bridge() throws AssetNotLoadedException {
310 Clip2Bridge clip2Bridge = this.clip2Bridge;
311 if (Objects.nonNull(clip2Bridge)) {
314 throw new AssetNotLoadedException("Clip2Bridge is null");
318 * Return the IP address for the console app.
320 * @return the IP address.
322 public String getIpAddress() {
323 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
324 return config.ipAddress;
328 * Get the v1 legacy Hue bridge (if any) which has the same IP address as this.
330 * @return Optional result containing the legacy bridge (if any found).
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")))
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.
346 * @param targetIdV1 the idV1 attribute to match.
347 * @return Optional result containing the legacy thing (if found).
349 public Optional<Thing> getLegacyThing(String targetIdV1) {
350 Optional<Thing> legacyBridge = getLegacyBridge();
351 if (legacyBridge.isEmpty()) {
352 return Optional.empty();
356 if (targetIdV1.startsWith("/lights/")) {
358 } else if (targetIdV1.startsWith("/sensors/")) {
360 } else if (targetIdV1.startsWith("/groups/")) {
363 return Optional.empty();
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())) //
371 Object id = thing.getConfiguration().get(config);
372 return (id instanceof String) && targetIdV1.endsWith("/" + (String) id);
377 * Return a localized text.
379 * @param key the i18n text key.
380 * @param arguments for parameterized translation.
381 * @return the localized text.
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;
389 * Execute an HTTP GET for a resources reference object from the server.
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
398 public Resources getResources(ResourceReference reference)
399 throws ApiException, AssetNotLoadedException, InterruptedException {
400 logger.debug("getResources() {}", reference);
402 return getClip2Bridge().getResources(reference);
406 * Getter for the scheduler.
408 * @return the scheduler.
410 public ScheduledExecutorService getScheduler() {
415 public Collection<Class<? extends ThingHandlerService>> getServices() {
416 return Set.of(Clip2ThingDiscoveryService.class);
420 public void handleCommand(ChannelUID channelUID, Command command) {
421 if (RefreshType.REFRESH.equals(command)) {
424 logger.warn("Bridge thing '{}' has no channels, only REFRESH command supported.", thing.getUID());
428 public void initialize() {
429 updateThingFromLegacy();
430 updateStatus(ThingStatus.UNKNOWN);
431 applKeyRetriesRemaining = APPLICATION_KEY_MAX_TRIES;
432 connectRetriesRemaining = RECONNECT_MAX_TRIES;
437 * Initialize the bridge handler's assets.
439 private void initializeAssets() {
440 logger.debug("initializeAssets() {}", this);
441 synchronized (this) {
442 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
444 String ipAddress = config.ipAddress;
445 if (ipAddress.isBlank()) {
446 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
447 "@text/offline.conf-error-no-ip-address");
452 if (!Clip2Bridge.isClip2Supported(ipAddress)) {
453 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
454 "@text/offline.api2.conf-error.clip2-not-supported");
457 } catch (IOException e) {
458 logger.trace("initializeAssets() communication error on '{}'", ipAddress, e);
459 setStatusOfflineWithCommunicationError(e);
463 HueTlsTrustManagerProvider trustManagerProvider = new HueTlsTrustManagerProvider(ipAddress + ":443",
464 config.useSelfSignedCertificate);
466 if (Objects.isNull(trustManagerProvider.getPEMTrustManager())) {
467 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
468 "@text/offline.api2.conf-error.certificate-load");
472 trustManagerRegistration = FrameworkUtil.getBundle(getClass()).getBundleContext()
473 .registerService(TlsTrustManagerProvider.class.getName(), trustManagerProvider, null);
475 String applicationKey = config.applicationKey;
476 applicationKey = Objects.nonNull(applicationKey) ? applicationKey : "";
479 clip2Bridge = new Clip2Bridge(httpClientFactory, this, ipAddress, applicationKey);
480 } catch (ApiException e) {
481 logger.trace("initializeAssets() communication error on '{}'", ipAddress, e);
482 setStatusOfflineWithCommunicationError(e);
488 cancelTask(checkConnectionTask, false);
489 checkConnectionTask = scheduler.submit(() -> checkConnection());
493 * Called when the connection goes offline. Schedule a reconnection.
495 public void onConnectionOffline() {
497 cancelTask(checkConnectionTask, false);
498 checkConnectionTask = scheduler.schedule(() -> checkConnection(), RECONNECT_DELAY_SECONDS,
504 * Called when the connection goes online. Schedule a general state update.
506 public void onConnectionOnline() {
507 cancelTask(updateOnlineStateTask, false);
508 updateOnlineStateTask = scheduler.schedule(() -> updateOnlineState(), 0, TimeUnit.MILLISECONDS);
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.
515 * @param resources a list of incoming resource objects.
517 public void onResourcesEvent(List<Resource> resources) {
519 synchronized (resourcesEventTasks) {
520 int index = resourcesEventTasks.size();
521 resourcesEventTasks.put(index, scheduler.submit(() -> {
522 onResourcesEventTask(resources);
523 resourcesEventTasks.remove(index);
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);
542 * Execute an HTTP PUT to send a Resource object to the server.
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
550 public Resources putResource(Resource resource) throws ApiException, AssetNotLoadedException, InterruptedException {
551 logger.debug("putResource() {}", resource);
553 return getClip2Bridge().putResource(resource);
557 * Register the application key with the hub. If the current application key is empty it will create a new one.
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
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);
576 * Register the discovery service.
578 * @param discoveryService new discoveryService.
580 public void registerDiscoveryService(Clip2ThingDiscoveryService discoveryService) {
581 this.discoveryService = discoveryService;
585 * Unregister the discovery service.
587 public void unregisterDiscoveryService() {
588 discoveryService = null;
592 * Update the bridge's online state and update its dependent things. Called when the connection goes online.
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);
608 * Update the bridge thing properties.
610 * @throws ApiException if a communication error occurred.
611 * @throws AssetNotLoadedException if one of the assets is not loaded.
612 * @throws InterruptedException
614 private void updateProperties() throws ApiException, AssetNotLoadedException, InterruptedException {
615 logger.debug("updateProperties()");
616 Map<String, String> properties = new HashMap<>(thing.getProperties());
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);
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());
634 // set metadata properties
635 String metaDataName = metaData.getName();
636 if (Objects.nonNull(metaDataName)) {
637 properties.put(PROPERTY_RESOURCE_NAME, metaDataName);
639 properties.put(PROPERTY_RESOURCE_ARCHETYPE, metaData.getArchetype().toString());
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);
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());
658 break; // we only needed the BRIDGE_V2 resource
661 thing.setProperties(properties);
665 * Update the thing's own state. Called sporadically in case any SSE events may have been lost.
667 private void updateSelf() {
668 logger.debug("updateSelf()");
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) {
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.
689 private void updateThingFromLegacy() {
690 if (isInitialized()) {
691 logger.warn("Cannot update bridge thing '{}' from legacy since handler already initialized.",
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();
702 String location = legacyThing.getLocation();
703 if (Objects.nonNull(location) && !location.isBlank()) {
704 editBuilder = editBuilder.withLocation(location);
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);
714 Map<String, String> newProperties = new HashMap<>(properties);
715 newProperties.remove(PROPERTY_LEGACY_THING_UID);
717 updateThing(editBuilder.withProperties(newProperties).build());
723 * Execute the mass download of all relevant resource types, and inform all child thing handlers.
725 private void updateThingsNow() {
726 logger.debug("updateThingsNow()");
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());
736 getThing().getThings().forEach(thing -> {
737 ThingHandler handler = thing.getHandler();
738 if (handler instanceof Clip2ThingHandler) {
739 ((Clip2ThingHandler) handler).onResourcesList(resourceType, resourceList);
743 } catch (ApiException | AssetNotLoadedException e) {
744 if (logger.isDebugEnabled()) {
745 logger.debug("updateThingsNow() unexpected exception", e);
747 logger.warn("Unexpected exception '{}' while updating things.", e.getMessage());
749 } catch (InterruptedException e) {
754 * Schedule a task to call updateThings(). It prevents floods of GET calls when multiple child things are added at
757 * @param delayMilliSeconds the delay before running the next task.
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);