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 // check connection to the hub
165 ThingStatusDetail thingStatus;
168 getClip2Bridge().testConnectionState();
169 thingStatus = ThingStatusDetail.NONE;
170 } catch (HttpUnauthorizedException e) {
171 logger.debug("checkConnection() {}", e.getMessage(), e);
172 thingStatus = ThingStatusDetail.CONFIGURATION_ERROR;
173 } catch (ApiException e) {
174 logger.debug("checkConnection() {}", e.getMessage(), e);
175 thingStatus = ThingStatusDetail.COMMUNICATION_ERROR;
176 } catch (AssetNotLoadedException e) {
177 logger.debug("checkConnection() {}", e.getMessage(), e);
178 thingStatus = ThingStatusDetail.HANDLER_INITIALIZING_ERROR;
179 } catch (InterruptedException e) {
183 // update the thing status
184 boolean retryApplicationKey = false;
185 boolean retryConnection = false;
186 switch (thingStatus) {
187 case CONFIGURATION_ERROR:
188 if (applKeyRetriesRemaining > 0) {
189 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
190 "@text/offline.api2.conf-error.press-pairing-button");
192 registerApplicationKey();
193 retryApplicationKey = true;
194 } catch (HttpUnauthorizedException e) {
195 retryApplicationKey = true;
196 } catch (ApiException e) {
197 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
198 "@text/offline.communication-error");
199 } catch (IllegalStateException e) {
200 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
201 "@text/offline.api2.conf-error.read-only");
202 } catch (AssetNotLoadedException e) {
203 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
204 "@text/offline.api2.conf-error.assets-not-loaded");
205 } catch (InterruptedException e) {
209 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
210 "@text/offline.api2.conf-error.not-authorized");
214 case COMMUNICATION_ERROR:
215 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
216 "@text/offline.communication-error");
217 retryConnection = connectRetriesRemaining > 0;
220 case HANDLER_INITIALIZING_ERROR:
221 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
222 "@text/offline.api2.conf-error.assets-not-loaded");
227 updateSelf(); // go online
232 if (retryApplicationKey) {
233 // short delay used during attempts to create or validate an application key
234 milliSeconds = FAST_SCHEDULE_MILLI_SECONDS;
235 applKeyRetriesRemaining--;
237 // default delay, set via configuration parameter, used as heart-beat 'just-in-case'
238 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
239 milliSeconds = config.checkMinutes * 60000;
240 if (retryConnection) {
241 // exponential back off delay used during attempts to reconnect
242 int backOffDelay = 60000 * (int) Math.pow(2, RECONNECT_MAX_TRIES - connectRetriesRemaining);
243 milliSeconds = Math.min(milliSeconds, backOffDelay);
244 connectRetriesRemaining--;
248 // this method schedules itself to be called again in a loop..
249 cancelTask(checkConnectionTask, false);
250 checkConnectionTask = scheduler.schedule(() -> checkConnection(), milliSeconds, TimeUnit.MILLISECONDS);
254 * If a child thing has been added, and the bridge is online, update the child's data.
256 public void childInitialized() {
257 if (thing.getStatus() == ThingStatus.ONLINE) {
258 updateThingsScheduled(5000);
263 public void dispose() {
270 * Dispose the bridge handler's assets. Called from dispose() on a thread, so that dispose() itself can complete
273 private void disposeAssets() {
274 logger.debug("disposeAssets() {}", this);
275 synchronized (this) {
276 assetsLoaded = false;
277 cancelTask(checkConnectionTask, true);
278 cancelTask(updateOnlineStateTask, true);
279 cancelTask(scheduledUpdateTask, true);
280 checkConnectionTask = null;
281 updateOnlineStateTask = null;
282 scheduledUpdateTask = null;
283 synchronized (resourcesEventTasks) {
284 resourcesEventTasks.values().forEach(task -> cancelTask(task, true));
285 resourcesEventTasks.clear();
287 ServiceRegistration<?> registration = trustManagerRegistration;
288 if (Objects.nonNull(registration)) {
289 registration.unregister();
290 trustManagerRegistration = null;
292 Clip2Bridge bridge = clip2Bridge;
293 if (Objects.nonNull(bridge)) {
297 Clip2ThingDiscoveryService disco = discoveryService;
298 if (Objects.nonNull(disco)) {
305 * Return the application key for the console app.
307 * @return the application key.
309 public String getApplicationKey() {
310 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
311 return config.applicationKey;
315 * Get the Clip2Bridge connection and throw an exception if it is null.
317 * @return the Clip2Bridge.
318 * @throws AssetNotLoadedException if the Clip2Bridge is null.
320 private Clip2Bridge getClip2Bridge() throws AssetNotLoadedException {
321 Clip2Bridge clip2Bridge = this.clip2Bridge;
322 if (Objects.nonNull(clip2Bridge)) {
325 throw new AssetNotLoadedException("Clip2Bridge is null");
329 * Return the IP address for the console app.
331 * @return the IP address.
333 public String getIpAddress() {
334 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
335 return config.ipAddress;
339 * Get the v1 legacy Hue bridge (if any) which has the same IP address as this.
341 * @return Optional result containing the legacy bridge (if any found).
343 public Optional<Thing> getLegacyBridge() {
344 String ipAddress = getIpAddress();
345 return Objects.nonNull(ipAddress)
346 ? thingRegistry.getAll().stream()
347 .filter(thing -> thing.getThingTypeUID().equals(THING_TYPE_BRIDGE)
348 && ipAddress.equals(thing.getConfiguration().get("ipAddress")))
354 * Get the v1 legacy Hue thing (if any) which has a Bridge having the same IP address as this, and an ID that
355 * matches the given parameter.
357 * @param targetIdV1 the idV1 attribute to match.
358 * @return Optional result containing the legacy thing (if found).
360 public Optional<Thing> getLegacyThing(String targetIdV1) {
361 Optional<Thing> legacyBridge = getLegacyBridge();
362 if (legacyBridge.isEmpty()) {
363 return Optional.empty();
367 if (targetIdV1.startsWith("/lights/")) {
369 } else if (targetIdV1.startsWith("/sensors/")) {
371 } else if (targetIdV1.startsWith("/groups/")) {
374 return Optional.empty();
377 ThingUID legacyBridgeUID = legacyBridge.get().getUID();
378 return thingRegistry.getAll().stream() //
379 .filter(thing -> legacyBridgeUID.equals(thing.getBridgeUID())
380 && V1_THING_TYPE_UIDS.contains(thing.getThingTypeUID())) //
382 Object id = thing.getConfiguration().get(config);
383 return (id instanceof String) && targetIdV1.endsWith("/" + (String) id);
388 * Return a localized text.
390 * @param key the i18n text key.
391 * @param arguments for parameterized translation.
392 * @return the localized text.
394 public String getLocalizedText(String key, @Nullable Object @Nullable... arguments) {
395 String result = translationProvider.getText(bundle, key, key, localeProvider.getLocale(), arguments);
396 return Objects.nonNull(result) ? result : key;
400 * Execute an HTTP GET for a resources reference object from the server.
402 * @param reference containing the resourceType and (optionally) the resourceId of the resource to get. If the
403 * resourceId is null then all resources of the given type are returned.
404 * @return the resource, or null if something fails.
405 * @throws ApiException if a communication error occurred.
406 * @throws AssetNotLoadedException if one of the assets is not loaded.
407 * @throws InterruptedException
409 public Resources getResources(ResourceReference reference)
410 throws ApiException, AssetNotLoadedException, InterruptedException {
411 logger.debug("getResources() {}", reference);
413 return getClip2Bridge().getResources(reference);
417 * Getter for the scheduler.
419 * @return the scheduler.
421 public ScheduledExecutorService getScheduler() {
426 public Collection<Class<? extends ThingHandlerService>> getServices() {
427 return Set.of(Clip2ThingDiscoveryService.class);
431 public void handleCommand(ChannelUID channelUID, Command command) {
432 if (RefreshType.REFRESH.equals(command)) {
435 logger.warn("Bridge thing '{}' has no channels, only REFRESH command supported.", thing.getUID());
439 public void initialize() {
440 updateThingFromLegacy();
441 updateStatus(ThingStatus.UNKNOWN);
442 applKeyRetriesRemaining = APPLICATION_KEY_MAX_TRIES;
443 connectRetriesRemaining = RECONNECT_MAX_TRIES;
448 * Initialize the bridge handler's assets.
450 private void initializeAssets() {
451 logger.debug("initializeAssets() {}", this);
452 synchronized (this) {
453 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
455 String ipAddress = config.ipAddress;
456 if (ipAddress.isBlank()) {
457 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
458 "@text/offline.conf-error-no-ip-address");
463 if (!Clip2Bridge.isClip2Supported(ipAddress)) {
464 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
465 "@text/offline.api2.conf-error.clip2-not-supported");
468 } catch (IOException e) {
469 logger.trace("initializeAssets() communication error on '{}'", ipAddress, e);
470 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
471 "@text/offline.api2.comm-error.exception [\"" + e.getMessage() + "\"]");
475 HueTlsTrustManagerProvider trustManagerProvider = new HueTlsTrustManagerProvider(ipAddress + ":443",
476 config.useSelfSignedCertificate);
478 if (Objects.isNull(trustManagerProvider.getPEMTrustManager())) {
479 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
480 "@text/offline.api2.conf-error.certificate-load");
484 trustManagerRegistration = FrameworkUtil.getBundle(getClass()).getBundleContext()
485 .registerService(TlsTrustManagerProvider.class.getName(), trustManagerProvider, null);
487 String applicationKey = config.applicationKey;
488 applicationKey = Objects.nonNull(applicationKey) ? applicationKey : "";
491 clip2Bridge = new Clip2Bridge(httpClientFactory, this, ipAddress, applicationKey);
492 } catch (ApiException e) {
493 logger.trace("initializeAssets() communication error on '{}'", ipAddress, e);
494 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
495 "@text/offline.api2.comm-error.exception [\"" + e.getMessage() + "\"]");
501 cancelTask(checkConnectionTask, false);
502 checkConnectionTask = scheduler.submit(() -> checkConnection());
506 * Called when the connection goes offline. Schedule a reconnection.
508 public void onConnectionOffline() {
510 cancelTask(checkConnectionTask, false);
511 checkConnectionTask = scheduler.schedule(() -> checkConnection(), RECONNECT_DELAY_SECONDS,
517 * Called when the connection goes online. Schedule a general state update.
519 public void onConnectionOnline() {
520 cancelTask(updateOnlineStateTask, false);
521 updateOnlineStateTask = scheduler.schedule(() -> updateOnlineState(), 0, TimeUnit.MILLISECONDS);
525 * Called when an SSE event message comes in with a valid list of resources. For each resource received, inform all
526 * child thing handlers with the respective resource.
528 * @param resources a list of incoming resource objects.
530 public void onResourcesEvent(List<Resource> resources) {
532 synchronized (resourcesEventTasks) {
533 int index = resourcesEventTasks.size();
534 resourcesEventTasks.put(index, scheduler.submit(() -> {
535 onResourcesEventTask(resources);
536 resourcesEventTasks.remove(index);
542 private void onResourcesEventTask(List<Resource> resources) {
543 logger.debug("onResourcesEventTask() resource count {}", resources.size());
544 getThing().getThings().forEach(thing -> {
545 ThingHandler handler = thing.getHandler();
546 if (handler instanceof Clip2ThingHandler) {
547 resources.forEach(resource -> {
548 ((Clip2ThingHandler) handler).onResource(resource);
555 * Execute an HTTP PUT to send a Resource object to the server.
557 * @param resource the resource to put.
558 * @throws ApiException if a communication error occurred.
559 * @throws AssetNotLoadedException if one of the assets is not loaded.
560 * @throws InterruptedException
562 public void putResource(Resource resource) throws ApiException, AssetNotLoadedException, InterruptedException {
563 logger.debug("putResource() {}", resource);
565 getClip2Bridge().putResource(resource);
569 * Register the application key with the hub. If the current application key is empty it will create a new one.
571 * @throws HttpUnauthorizedException if the communication was OK but the registration failed anyway.
572 * @throws ApiException if a communication error occurred.
573 * @throws AssetNotLoadedException if one of the assets is not loaded.
574 * @throws IllegalStateException if the configuration cannot be changed e.g. read only.
575 * @throws InterruptedException
577 private void registerApplicationKey() throws HttpUnauthorizedException, ApiException, AssetNotLoadedException,
578 IllegalStateException, InterruptedException {
579 logger.debug("registerApplicationKey()");
580 Clip2BridgeConfig config = getConfigAs(Clip2BridgeConfig.class);
581 String newApplicationKey = getClip2Bridge().registerApplicationKey(config.applicationKey);
582 Configuration configuration = editConfiguration();
583 configuration.put(Clip2BridgeConfig.APPLICATION_KEY, newApplicationKey);
584 updateConfiguration(configuration);
588 * Register the discovery service.
590 * @param discoveryService new discoveryService.
592 public void registerDiscoveryService(Clip2ThingDiscoveryService discoveryService) {
593 this.discoveryService = discoveryService;
597 * Unregister the discovery service.
599 public void unregisterDiscoveryService() {
600 discoveryService = null;
604 * Update the bridge's online state and update its dependent things. Called when the connection goes online.
606 private void updateOnlineState() {
607 if (assetsLoaded && (thing.getStatus() != ThingStatus.ONLINE)) {
608 logger.debug("updateOnlineState()");
609 connectRetriesRemaining = RECONNECT_MAX_TRIES;
610 updateStatus(ThingStatus.ONLINE);
611 updateThingsScheduled(500);
612 Clip2ThingDiscoveryService discoveryService = this.discoveryService;
613 if (Objects.nonNull(discoveryService)) {
614 discoveryService.startScan(null);
620 * Update the bridge thing properties.
622 * @throws ApiException if a communication error occurred.
623 * @throws AssetNotLoadedException if one of the assets is not loaded.
624 * @throws InterruptedException
626 private void updateProperties() throws ApiException, AssetNotLoadedException, InterruptedException {
627 logger.debug("updateProperties()");
628 Map<String, String> properties = new HashMap<>(thing.getProperties());
630 for (Resource device : getClip2Bridge().getResources(BRIDGE).getResources()) {
631 // set the serial number
632 String bridgeId = device.getBridgeId();
633 if (Objects.nonNull(bridgeId)) {
634 properties.put(Thing.PROPERTY_SERIAL_NUMBER, bridgeId);
639 for (Resource device : getClip2Bridge().getResources(DEVICE).getResources()) {
640 MetaData metaData = device.getMetaData();
641 if (Objects.nonNull(metaData) && metaData.getArchetype() == Archetype.BRIDGE_V2) {
642 // set resource properties
643 properties.put(PROPERTY_RESOURCE_ID, device.getId());
644 properties.put(PROPERTY_RESOURCE_TYPE, device.getType().toString());
646 // set metadata properties
647 String metaDataName = metaData.getName();
648 if (Objects.nonNull(metaDataName)) {
649 properties.put(PROPERTY_RESOURCE_NAME, metaDataName);
651 properties.put(PROPERTY_RESOURCE_ARCHETYPE, metaData.getArchetype().toString());
653 // set product data properties
654 ProductData productData = device.getProductData();
655 if (Objects.nonNull(productData)) {
656 // set generic thing properties
657 properties.put(Thing.PROPERTY_MODEL_ID, productData.getModelId());
658 properties.put(Thing.PROPERTY_VENDOR, productData.getManufacturerName());
659 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, productData.getSoftwareVersion());
660 String hardwarePlatformType = productData.getHardwarePlatformType();
661 if (Objects.nonNull(hardwarePlatformType)) {
662 properties.put(Thing.PROPERTY_HARDWARE_VERSION, hardwarePlatformType);
665 // set hue specific properties
666 properties.put(PROPERTY_PRODUCT_NAME, productData.getProductName());
667 properties.put(PROPERTY_PRODUCT_ARCHETYPE, productData.getProductArchetype().toString());
668 properties.put(PROPERTY_PRODUCT_CERTIFIED, productData.getCertified().toString());
670 break; // we only needed the BRIDGE_V2 resource
673 thing.setProperties(properties);
677 * Update the thing's own state. Called sporadically in case any SSE events may have been lost.
679 private void updateSelf() {
680 logger.debug("updateSelf()");
684 getClip2Bridge().open();
685 } catch (ApiException e) {
686 logger.trace("updateSelf() {}", e.getMessage(), e);
687 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
688 "@text/offline.api2.comm-error.exception [\"" + e.getMessage() + "\"]");
689 onConnectionOffline();
690 } catch (AssetNotLoadedException e) {
691 logger.trace("updateSelf() {}", e.getMessage(), e);
692 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
693 "@text/offline.api2.conf-error.assets-not-loaded");
694 } catch (InterruptedException e) {
699 * Check if a PROPERTY_LEGACY_THING_UID value was set by the discovery process, and if so, clone the legacy thing's
700 * settings into this thing.
702 private void updateThingFromLegacy() {
703 if (isInitialized()) {
704 logger.warn("Cannot update bridge thing '{}' from legacy since handler already initialized.",
708 Map<String, String> properties = thing.getProperties();
709 String legacyThingUID = properties.get(PROPERTY_LEGACY_THING_UID);
710 if (Objects.nonNull(legacyThingUID)) {
711 Thing legacyThing = thingRegistry.get(new ThingUID(legacyThingUID));
712 if (Objects.nonNull(legacyThing)) {
713 BridgeBuilder editBuilder = editThing();
715 String location = legacyThing.getLocation();
716 if (Objects.nonNull(location) && !location.isBlank()) {
717 editBuilder = editBuilder.withLocation(location);
720 Object userName = legacyThing.getConfiguration().get(USER_NAME);
721 if (userName instanceof String) {
722 Configuration configuration = thing.getConfiguration();
723 configuration.put(Clip2BridgeConfig.APPLICATION_KEY, userName);
724 editBuilder = editBuilder.withConfiguration(configuration);
727 Map<String, String> newProperties = new HashMap<>(properties);
728 newProperties.remove(PROPERTY_LEGACY_THING_UID);
730 updateThing(editBuilder.withProperties(newProperties).build());
736 * Execute the mass download of all relevant resource types, and inform all child thing handlers.
738 private void updateThingsNow() {
739 logger.debug("updateThingsNow()");
741 Clip2Bridge bridge = getClip2Bridge();
742 for (ResourceReference reference : MASS_DOWNLOAD_RESOURCE_REFERENCES) {
743 ResourceType resourceType = reference.getType();
744 List<Resource> resourceList = bridge.getResources(reference).getResources();
745 if (resourceType == ResourceType.ZONE) {
746 // add special 'All Lights' zone to the zone resource list
747 resourceList.addAll(bridge.getResources(BRIDGE_HOME).getResources());
749 getThing().getThings().forEach(thing -> {
750 ThingHandler handler = thing.getHandler();
751 if (handler instanceof Clip2ThingHandler) {
752 ((Clip2ThingHandler) handler).onResourcesList(resourceType, resourceList);
756 } catch (ApiException | AssetNotLoadedException e) {
757 if (logger.isDebugEnabled()) {
758 logger.debug("updateThingsNow() unexpected exception", e);
760 logger.warn("Unexpected exception '{}' while updating things.", e.getMessage());
762 } catch (InterruptedException e) {
767 * Schedule a task to call updateThings(). It prevents floods of GET calls when multiple child things are added at
770 * @param delayMilliSeconds the delay before running the next task.
772 private void updateThingsScheduled(int delayMilliSeconds) {
773 ScheduledFuture<?> task = this.scheduledUpdateTask;
774 if (Objects.isNull(task) || task.getDelay(TimeUnit.MILLISECONDS) < 100) {
775 cancelTask(scheduledUpdateTask, false);
776 scheduledUpdateTask = scheduler.schedule(() -> updateThingsNow(), delayMilliSeconds, TimeUnit.MILLISECONDS);