]> git.basschouten.com Git - openhab-addons.git/blob
30a49dc3c195df630de162295b2d92c909a21970
[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.math.BigDecimal;
18 import java.time.Duration;
19 import java.time.Instant;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Set;
29 import java.util.TreeSet;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.CopyOnWriteArrayList;
32 import java.util.concurrent.Future;
33 import java.util.concurrent.TimeUnit;
34 import java.util.stream.Collectors;
35 import java.util.stream.Stream;
36
37 import org.eclipse.jdt.annotation.NonNullByDefault;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.openhab.binding.hue.internal.action.DynamicsActions;
40 import org.openhab.binding.hue.internal.api.dto.clip2.Alerts;
41 import org.openhab.binding.hue.internal.api.dto.clip2.ColorXy;
42 import org.openhab.binding.hue.internal.api.dto.clip2.Dimming;
43 import org.openhab.binding.hue.internal.api.dto.clip2.Effects;
44 import org.openhab.binding.hue.internal.api.dto.clip2.Gamut2;
45 import org.openhab.binding.hue.internal.api.dto.clip2.MetaData;
46 import org.openhab.binding.hue.internal.api.dto.clip2.MirekSchema;
47 import org.openhab.binding.hue.internal.api.dto.clip2.ProductData;
48 import org.openhab.binding.hue.internal.api.dto.clip2.Resource;
49 import org.openhab.binding.hue.internal.api.dto.clip2.ResourceReference;
50 import org.openhab.binding.hue.internal.api.dto.clip2.Resources;
51 import org.openhab.binding.hue.internal.api.dto.clip2.TimedEffects;
52 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ActionType;
53 import org.openhab.binding.hue.internal.api.dto.clip2.enums.EffectType;
54 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ResourceType;
55 import org.openhab.binding.hue.internal.api.dto.clip2.enums.SceneRecallAction;
56 import org.openhab.binding.hue.internal.api.dto.clip2.enums.SmartSceneRecallAction;
57 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ZigbeeStatus;
58 import org.openhab.binding.hue.internal.api.dto.clip2.helper.Setters;
59 import org.openhab.binding.hue.internal.config.Clip2ThingConfig;
60 import org.openhab.binding.hue.internal.exceptions.ApiException;
61 import org.openhab.binding.hue.internal.exceptions.AssetNotLoadedException;
62 import org.openhab.core.i18n.TimeZoneProvider;
63 import org.openhab.core.library.types.DateTimeType;
64 import org.openhab.core.library.types.DecimalType;
65 import org.openhab.core.library.types.HSBType;
66 import org.openhab.core.library.types.IncreaseDecreaseType;
67 import org.openhab.core.library.types.OnOffType;
68 import org.openhab.core.library.types.PercentType;
69 import org.openhab.core.library.types.QuantityType;
70 import org.openhab.core.library.types.StringType;
71 import org.openhab.core.library.unit.MetricPrefix;
72 import org.openhab.core.library.unit.Units;
73 import org.openhab.core.thing.Bridge;
74 import org.openhab.core.thing.Channel;
75 import org.openhab.core.thing.ChannelUID;
76 import org.openhab.core.thing.Thing;
77 import org.openhab.core.thing.ThingRegistry;
78 import org.openhab.core.thing.ThingStatus;
79 import org.openhab.core.thing.ThingStatusDetail;
80 import org.openhab.core.thing.ThingTypeUID;
81 import org.openhab.core.thing.ThingUID;
82 import org.openhab.core.thing.binding.BaseThingHandler;
83 import org.openhab.core.thing.binding.BridgeHandler;
84 import org.openhab.core.thing.binding.ThingHandlerService;
85 import org.openhab.core.thing.binding.builder.ThingBuilder;
86 import org.openhab.core.thing.link.ItemChannelLink;
87 import org.openhab.core.thing.link.ItemChannelLinkRegistry;
88 import org.openhab.core.types.Command;
89 import org.openhab.core.types.RefreshType;
90 import org.openhab.core.types.State;
91 import org.openhab.core.types.StateOption;
92 import org.openhab.core.types.UnDefType;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
95
96 /**
97  * Handler for things based on CLIP 2 'device', 'room', or 'zone resources.
98  *
99  * @author Andrew Fiddian-Green - Initial contribution.
100  */
101 @NonNullByDefault
102 public class Clip2ThingHandler extends BaseThingHandler {
103
104     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DEVICE, THING_TYPE_ROOM,
105             THING_TYPE_ZONE);
106
107     private static final Set<ResourceType> SUPPORTED_SCENE_TYPES = Set.of(ResourceType.SCENE, ResourceType.SMART_SCENE);
108
109     private static final Duration DYNAMICS_ACTIVE_WINDOW = Duration.ofSeconds(10);
110
111     private static final String LK_WISER_DIMMER_MODEL_ID = "LK Dimmer";
112
113     private final Logger logger = LoggerFactory.getLogger(Clip2ThingHandler.class);
114
115     /**
116      * A map of service Resources whose state contributes to the overall state of this thing. It is a map between the
117      * resource ID (string) and a Resource object containing the last known state. e.g. a DEVICE thing may support a
118      * LIGHT service whose Resource contributes to its overall state, or a ROOM or ZONE thing may support a
119      * GROUPED_LIGHT service whose Resource contributes to the its overall state.
120      */
121     private final Map<String, Resource> serviceContributorsCache = new ConcurrentHashMap<>();
122
123     /**
124      * A map of Resource IDs which are targets for commands to be sent. It is a map between the type of command
125      * (ResourcesType) and the resource ID to which the command shall be sent. e.g. a LIGHT 'on' command shall be sent
126      * to the respective LIGHT resource ID.
127      */
128     private final Map<ResourceType, String> commandResourceIds = new ConcurrentHashMap<>();
129
130     /**
131      * Button devices contain one or more physical buttons, each of which is represented by a BUTTON Resource with its
132      * own unique resource ID, and a respective controlId that indicates which button it is in the device. e.g. a dimmer
133      * pad has four buttons (controlId's 1..4) each represented by a BUTTON Resource with a unique resource ID. This is
134      * a map between the resource ID and its respective controlId.
135      */
136     private final Map<String, Integer> controlIds = new ConcurrentHashMap<>();
137
138     /**
139      * The set of channel IDs that are supported by this thing. e.g. an on/off light may support 'switch' and
140      * 'zigbeeStatus' channels, whereas a complex light may support 'switch', 'brightness', 'color', 'color temperature'
141      * and 'zigbeeStatus' channels.
142      */
143     private final Set<String> supportedChannelIdSet = new HashSet<>();
144
145     /**
146      * A map of scene IDs versus scene Resources for the scenes that contribute to and command this thing. It is a map
147      * between the resource ID (string) and a Resource object containing the scene's last known state.
148      */
149     private final Map<String, Resource> sceneContributorsCache = new ConcurrentHashMap<>();
150
151     /**
152      * A map of scene names versus scene Resources for the scenes that contribute to and command this thing. e.g. a
153      * command for a scene named 'Energize' shall be sent to the respective SCENE resource ID.
154      */
155     private final Map<String, Resource> sceneResourceEntries = new ConcurrentHashMap<>();
156
157     /**
158      * A list of API v1 thing channel UIDs that are linked to items. It is used in the process of replicating the
159      * Item/Channel links from a legacy v1 thing to this API v2 thing.
160      */
161     private final List<ChannelUID> legacyLinkedChannelUIDs = new CopyOnWriteArrayList<>();
162
163     private final ThingRegistry thingRegistry;
164     private final ItemChannelLinkRegistry itemChannelLinkRegistry;
165     private final Clip2StateDescriptionProvider stateDescriptionProvider;
166     private final TimeZoneProvider timeZoneProvider;
167
168     private String resourceId = "?";
169     private Resource thisResource;
170     private Duration dynamicsDuration = Duration.ZERO;
171     private Instant dynamicsExpireTime = Instant.MIN;
172     private Instant buttonGroupLastUpdated = Instant.MIN;
173
174     private boolean disposing;
175     private boolean hasConnectivityIssue;
176     private boolean updateSceneContributorsDone;
177     private boolean updateLightPropertiesDone;
178     private boolean updatePropertiesDone;
179     private boolean updateDependenciesDone;
180     private boolean applyOffTransitionWorkaround;
181
182     private @Nullable Future<?> alertResetTask;
183     private @Nullable Future<?> dynamicsResetTask;
184     private @Nullable Future<?> updateDependenciesTask;
185     private @Nullable Future<?> updateServiceContributorsTask;
186
187     public Clip2ThingHandler(Thing thing, Clip2StateDescriptionProvider stateDescriptionProvider,
188             TimeZoneProvider timeZoneProvider, ThingRegistry thingRegistry,
189             ItemChannelLinkRegistry itemChannelLinkRegistry) {
190         super(thing);
191
192         ThingTypeUID thingTypeUID = thing.getThingTypeUID();
193         if (THING_TYPE_DEVICE.equals(thingTypeUID)) {
194             thisResource = new Resource(ResourceType.DEVICE);
195         } else if (THING_TYPE_ROOM.equals(thingTypeUID)) {
196             thisResource = new Resource(ResourceType.ROOM);
197         } else if (THING_TYPE_ZONE.equals(thingTypeUID)) {
198             thisResource = new Resource(ResourceType.ZONE);
199         } else {
200             throw new IllegalArgumentException("Wrong thing type " + thingTypeUID.getAsString());
201         }
202
203         this.thingRegistry = thingRegistry;
204         this.itemChannelLinkRegistry = itemChannelLinkRegistry;
205         this.stateDescriptionProvider = stateDescriptionProvider;
206         this.timeZoneProvider = timeZoneProvider;
207     }
208
209     /**
210      * Add a channel ID to the supportedChannelIdSet set. If the channel supports dynamics (timed transitions) then add
211      * the respective channel as well.
212      *
213      * @param channelId the channel ID to add.
214      */
215     private void addSupportedChannel(String channelId) {
216         if (!disposing && !updateDependenciesDone) {
217             synchronized (supportedChannelIdSet) {
218                 logger.debug("{} -> addSupportedChannel() '{}' added to supported channel set", resourceId, channelId);
219                 supportedChannelIdSet.add(channelId);
220                 if (DYNAMIC_CHANNELS.contains(channelId)) {
221                     clearDynamicsChannel();
222                 }
223             }
224         }
225     }
226
227     /**
228      * Cancel the given task.
229      *
230      * @param cancelTask the task to be cancelled (may be null)
231      * @param mayInterrupt allows cancel() to interrupt the thread.
232      */
233     private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
234         if (Objects.nonNull(cancelTask)) {
235             cancelTask.cancel(mayInterrupt);
236         }
237     }
238
239     /**
240      * Clear the dynamics channel parameters.
241      */
242     private void clearDynamicsChannel() {
243         dynamicsExpireTime = Instant.MIN;
244         dynamicsDuration = Duration.ZERO;
245         updateState(CHANNEL_2_DYNAMICS, new QuantityType<>(0, MetricPrefix.MILLI(Units.SECOND)), true);
246     }
247
248     @Override
249     public void dispose() {
250         logger.debug("{} -> dispose()", resourceId);
251         disposing = true;
252         cancelTask(alertResetTask, true);
253         cancelTask(dynamicsResetTask, true);
254         cancelTask(updateDependenciesTask, true);
255         cancelTask(updateServiceContributorsTask, true);
256         alertResetTask = null;
257         dynamicsResetTask = null;
258         updateDependenciesTask = null;
259         updateServiceContributorsTask = null;
260         legacyLinkedChannelUIDs.clear();
261         sceneContributorsCache.clear();
262         sceneResourceEntries.clear();
263         supportedChannelIdSet.clear();
264         commandResourceIds.clear();
265         serviceContributorsCache.clear();
266         controlIds.clear();
267     }
268
269     /**
270      * Get the bridge handler.
271      *
272      * @throws AssetNotLoadedException if the handler does not exist.
273      */
274     private Clip2BridgeHandler getBridgeHandler() throws AssetNotLoadedException {
275         Bridge bridge = getBridge();
276         if (Objects.nonNull(bridge)) {
277             BridgeHandler handler = bridge.getHandler();
278             if (handler instanceof Clip2BridgeHandler) {
279                 return (Clip2BridgeHandler) handler;
280             }
281         }
282         throw new AssetNotLoadedException("Bridge handler missing");
283     }
284
285     /**
286      * Do a double lookup to get the cached resource that matches the given ResourceType.
287      *
288      * @param resourceType the type to search for.
289      * @return the Resource, or null if not found.
290      */
291     private @Nullable Resource getCachedResource(ResourceType resourceType) {
292         String commandResourceId = commandResourceIds.get(resourceType);
293         return Objects.nonNull(commandResourceId) ? serviceContributorsCache.get(commandResourceId) : null;
294     }
295
296     /**
297      * Return a ResourceReference to this handler's resource.
298      *
299      * @return a ResourceReference instance.
300      */
301     public ResourceReference getResourceReference() {
302         return new ResourceReference().setId(resourceId).setType(thisResource.getType());
303     }
304
305     /**
306      * Register the 'DynamicsAction' service.
307      */
308     @Override
309     public Collection<Class<? extends ThingHandlerService>> getServices() {
310         return Set.of(DynamicsActions.class);
311     }
312
313     @Override
314     public void handleCommand(ChannelUID channelUID, Command commandParam) {
315         if (RefreshType.REFRESH.equals(commandParam)) {
316             if (thing.getStatus() == ThingStatus.ONLINE) {
317                 refreshAllChannels();
318             }
319             return;
320         }
321
322         Channel channel = thing.getChannel(channelUID);
323         if (channel == null) {
324             if (logger.isDebugEnabled()) {
325                 logger.debug("{} -> handleCommand() channelUID:{} does not exist", resourceId, channelUID);
326
327             } else {
328                 logger.warn("Command received for channel '{}' which is not in thing '{}'.", channelUID,
329                         thing.getUID());
330             }
331             return;
332         }
333
334         ResourceType lightResourceType = thisResource.getType() == ResourceType.DEVICE ? ResourceType.LIGHT
335                 : ResourceType.GROUPED_LIGHT;
336
337         Resource putResource = null;
338         String putResourceId = null;
339         Command command = commandParam;
340         String channelId = channelUID.getId();
341         Resource cache = getCachedResource(lightResourceType);
342
343         switch (channelId) {
344             case CHANNEL_2_ALERT:
345                 putResource = Setters.setAlert(new Resource(lightResourceType), command, cache);
346                 cancelTask(alertResetTask, false);
347                 alertResetTask = scheduler.schedule(
348                         () -> updateState(channelUID, new StringType(ActionType.NO_ACTION.name())), 10,
349                         TimeUnit.SECONDS);
350                 break;
351
352             case CHANNEL_2_EFFECT:
353                 putResource = Setters.setEffect(new Resource(lightResourceType), command, cache).setOnOff(OnOffType.ON);
354                 break;
355
356             case CHANNEL_2_COLOR_TEMP_PERCENT:
357                 if (command instanceof IncreaseDecreaseType) {
358                     if (Objects.nonNull(cache)) {
359                         State current = cache.getColorTemperaturePercentState();
360                         if (current instanceof PercentType) {
361                             int sign = IncreaseDecreaseType.INCREASE == command ? 1 : -1;
362                             int percent = ((PercentType) current).intValue() + (sign * (int) Resource.PERCENT_DELTA);
363                             command = new PercentType(Math.min(100, Math.max(0, percent)));
364                         }
365                     }
366                 } else if (command instanceof OnOffType) {
367                     command = OnOffType.OFF == command ? PercentType.ZERO : PercentType.HUNDRED;
368                 }
369                 putResource = Setters.setColorTemperaturePercent(new Resource(lightResourceType), command, cache);
370                 break;
371
372             case CHANNEL_2_COLOR_TEMP_ABSOLUTE:
373                 putResource = Setters.setColorTemperatureAbsolute(new Resource(lightResourceType), command, cache);
374                 break;
375
376             case CHANNEL_2_COLOR:
377                 putResource = new Resource(lightResourceType);
378                 if (command instanceof HSBType) {
379                     HSBType color = ((HSBType) command);
380                     putResource = Setters.setColorXy(putResource, color, cache);
381                     command = color.getBrightness();
382                 }
383                 // NB fall through for handling of brightness and switch related commands !!
384
385             case CHANNEL_2_BRIGHTNESS:
386                 putResource = Objects.nonNull(putResource) ? putResource : new Resource(lightResourceType);
387                 if (command instanceof IncreaseDecreaseType) {
388                     if (Objects.nonNull(cache)) {
389                         State current = cache.getBrightnessState();
390                         if (current instanceof PercentType) {
391                             int sign = IncreaseDecreaseType.INCREASE == command ? 1 : -1;
392                             double percent = ((PercentType) current).doubleValue() + (sign * Resource.PERCENT_DELTA);
393                             command = new PercentType(new BigDecimal(Math.min(100f, Math.max(0f, percent)),
394                                     Resource.PERCENT_MATH_CONTEXT));
395                         }
396                     }
397                 }
398                 if (command instanceof PercentType) {
399                     PercentType brightness = (PercentType) command;
400                     putResource = Setters.setDimming(putResource, brightness, cache);
401                     Double minDimLevel = Objects.nonNull(cache) ? cache.getMinimumDimmingLevel() : null;
402                     minDimLevel = Objects.nonNull(minDimLevel) ? minDimLevel : Dimming.DEFAULT_MINIMUM_DIMMIMG_LEVEL;
403                     command = OnOffType.from(brightness.doubleValue() >= minDimLevel);
404                 }
405                 // NB fall through for handling of switch related commands !!
406
407             case CHANNEL_2_SWITCH:
408                 putResource = Objects.nonNull(putResource) ? putResource : new Resource(lightResourceType);
409                 putResource.setOnOff(command);
410                 applyDeviceSpecificWorkArounds(command, putResource);
411                 break;
412
413             case CHANNEL_2_COLOR_XY_ONLY:
414                 putResource = Setters.setColorXy(new Resource(lightResourceType), command, cache);
415                 break;
416
417             case CHANNEL_2_DIMMING_ONLY:
418                 putResource = Setters.setDimming(new Resource(lightResourceType), command, cache);
419                 break;
420
421             case CHANNEL_2_ON_OFF_ONLY:
422                 putResource = new Resource(lightResourceType).setOnOff(command);
423                 applyDeviceSpecificWorkArounds(command, putResource);
424                 break;
425
426             case CHANNEL_2_TEMPERATURE_ENABLED:
427                 putResource = new Resource(ResourceType.TEMPERATURE).setEnabled(command);
428                 break;
429
430             case CHANNEL_2_MOTION_ENABLED:
431                 putResource = new Resource(ResourceType.MOTION).setEnabled(command);
432                 break;
433
434             case CHANNEL_2_LIGHT_LEVEL_ENABLED:
435                 putResource = new Resource(ResourceType.LIGHT_LEVEL).setEnabled(command);
436                 break;
437
438             case CHANNEL_2_SECURITY_CONTACT_ENABLED:
439                 putResource = new Resource(ResourceType.CONTACT).setEnabled(command);
440                 break;
441
442             case CHANNEL_2_SCENE:
443                 if (command instanceof StringType) {
444                     Resource scene = sceneResourceEntries.get(((StringType) command).toString());
445                     if (Objects.nonNull(scene)) {
446                         ResourceType putResourceType = scene.getType();
447                         putResource = new Resource(putResourceType);
448                         switch (putResourceType) {
449                             case SCENE:
450                                 putResource.setRecallAction(SceneRecallAction.ACTIVE);
451                                 break;
452                             case SMART_SCENE:
453                                 putResource.setRecallAction(SmartSceneRecallAction.ACTIVATE);
454                                 break;
455                             default:
456                                 logger.debug("{} -> handleCommand() type '{}' is not a supported scene type",
457                                         resourceId, putResourceType);
458                                 return;
459                         }
460                         putResourceId = scene.getId();
461                     }
462                 }
463                 break;
464
465             case CHANNEL_2_DYNAMICS:
466                 Duration clearAfter = Duration.ZERO;
467                 if (command instanceof QuantityType<?>) {
468                     QuantityType<?> durationMs = ((QuantityType<?>) command).toUnit(MetricPrefix.MILLI(Units.SECOND));
469                     if (Objects.nonNull(durationMs) && durationMs.longValue() > 0) {
470                         Duration duration = Duration.ofMillis(durationMs.longValue());
471                         dynamicsDuration = duration;
472                         dynamicsExpireTime = Instant.now().plus(DYNAMICS_ACTIVE_WINDOW);
473                         clearAfter = DYNAMICS_ACTIVE_WINDOW;
474                         logger.debug("{} -> handleCommand() dynamics setting {} valid for {}", resourceId, duration,
475                                 clearAfter);
476                     }
477                 }
478                 cancelTask(dynamicsResetTask, false);
479                 dynamicsResetTask = scheduler.schedule(() -> clearDynamicsChannel(), clearAfter.toMillis(),
480                         TimeUnit.MILLISECONDS);
481                 return;
482
483             default:
484                 if (logger.isDebugEnabled()) {
485                     logger.debug("{} -> handleCommand() channelUID:{} unknown", resourceId, channelUID);
486                 } else {
487                     logger.warn("Command received for unknown channel '{}'.", channelUID);
488                 }
489                 return;
490         }
491
492         if (putResource == null) {
493             if (logger.isDebugEnabled()) {
494                 logger.debug("{} -> handleCommand() command:{} not supported on channelUID:{}", resourceId, command,
495                         channelUID);
496             } else {
497                 logger.warn("Command '{}' is not supported on channel '{}'.", command, channelUID);
498             }
499             return;
500         }
501
502         putResourceId = Objects.nonNull(putResourceId) ? putResourceId : commandResourceIds.get(putResource.getType());
503         if (putResourceId == null) {
504             if (logger.isDebugEnabled()) {
505                 logger.debug(
506                         "{} -> handleCommand() channelUID:{}, command:{}, putResourceType:{} => missing resource ID",
507                         resourceId, channelUID, command, putResource.getType());
508             } else {
509                 logger.warn("Command '{}' for channel '{}' cannot be processed by thing '{}'.", command, channelUID,
510                         thing.getUID());
511             }
512             return;
513         }
514
515         if (DYNAMIC_CHANNELS.contains(channelId)) {
516             if (Instant.now().isBefore(dynamicsExpireTime) && !dynamicsDuration.isZero()
517                     && !dynamicsDuration.isNegative()) {
518                 if (ResourceType.SCENE == putResource.getType()) {
519                     putResource.setRecallDuration(dynamicsDuration);
520                 } else if (CHANNEL_2_EFFECT == channelId) {
521                     putResource.setTimedEffectsDuration(dynamicsDuration);
522                 } else {
523                     putResource.setDynamicsDuration(dynamicsDuration);
524                 }
525             }
526         }
527
528         putResource.setId(putResourceId);
529         logger.debug("{} -> handleCommand() put resource {}", resourceId, putResource);
530
531         try {
532             Resources resources = getBridgeHandler().putResource(putResource);
533             if (resources.hasErrors()) {
534                 logger.info("Command '{}' for thing '{}', channel '{}' succeeded with errors: {}", command,
535                         thing.getUID(), channelUID, String.join("; ", resources.getErrors()));
536             }
537         } catch (ApiException | AssetNotLoadedException e) {
538             if (logger.isDebugEnabled()) {
539                 logger.debug("{} -> handleCommand() error {}", resourceId, e.getMessage(), e);
540             } else {
541                 logger.warn("Command '{}' for thing '{}', channel '{}' failed with error '{}'.", command,
542                         thing.getUID(), channelUID, e.getMessage());
543             }
544         } catch (InterruptedException e) {
545         }
546     }
547
548     private void refreshAllChannels() {
549         if (!updateDependenciesDone) {
550             return;
551         }
552         cancelTask(updateServiceContributorsTask, false);
553         updateServiceContributorsTask = scheduler.schedule(() -> {
554             try {
555                 updateServiceContributors();
556             } catch (ApiException | AssetNotLoadedException e) {
557                 logger.debug("{} -> handleCommand() error {}", resourceId, e.getMessage(), e);
558             } catch (InterruptedException e) {
559             }
560         }, 3, TimeUnit.SECONDS);
561     }
562
563     /**
564      * Apply device specific work-arounds needed for given command.
565      *
566      * @param command the handled command.
567      * @param putResource the resource that will be adjusted if needed.
568      */
569     private void applyDeviceSpecificWorkArounds(Command command, Resource putResource) {
570         if (command == OnOffType.OFF && applyOffTransitionWorkaround) {
571             putResource.setDynamicsDuration(dynamicsDuration);
572         }
573     }
574
575     /**
576      * Handle a 'dynamics' command for the given channel ID for the given dynamics duration.
577      *
578      * @param channelId the ID of the target channel.
579      * @param command the new target state.
580      * @param duration the transition duration.
581      */
582     public synchronized void handleDynamicsCommand(String channelId, Command command, QuantityType<?> duration) {
583         if (DYNAMIC_CHANNELS.contains(channelId)) {
584             Channel dynamicsChannel = thing.getChannel(CHANNEL_2_DYNAMICS);
585             Channel targetChannel = thing.getChannel(channelId);
586             if (Objects.nonNull(dynamicsChannel) && Objects.nonNull(targetChannel)) {
587                 logger.debug("{} - handleDynamicsCommand() channelId:{}, command:{}, duration:{}", resourceId,
588                         channelId, command, duration);
589                 handleCommand(dynamicsChannel.getUID(), duration);
590                 handleCommand(targetChannel.getUID(), command);
591                 return;
592             }
593         }
594         logger.warn("Dynamics command '{}' for thing '{}', channel '{}' and duration'{}' failed.", command,
595                 thing.getUID(), channelId, duration);
596     }
597
598     @Override
599     public void initialize() {
600         Clip2ThingConfig config = getConfigAs(Clip2ThingConfig.class);
601
602         String resourceId = config.resourceId;
603         if (resourceId.isBlank()) {
604             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
605                     "@text/offline.api2.conf-error.resource-id-missing");
606             return;
607         }
608         thisResource.setId(resourceId);
609         this.resourceId = resourceId;
610         logger.debug("{} -> initialize()", resourceId);
611
612         updateThingFromLegacy();
613         updateStatus(ThingStatus.UNKNOWN);
614
615         dynamicsDuration = Duration.ZERO;
616         dynamicsExpireTime = Instant.MIN;
617
618         disposing = false;
619         hasConnectivityIssue = false;
620         updatePropertiesDone = false;
621         updateDependenciesDone = false;
622         updateLightPropertiesDone = false;
623         updateSceneContributorsDone = false;
624
625         Bridge bridge = getBridge();
626         if (Objects.nonNull(bridge)) {
627             BridgeHandler bridgeHandler = bridge.getHandler();
628             if (bridgeHandler instanceof Clip2BridgeHandler) {
629                 ((Clip2BridgeHandler) bridgeHandler).childInitialized();
630             }
631         }
632     }
633
634     /**
635      * Update the channel state depending on a new resource sent from the bridge.
636      *
637      * @param resource a Resource object containing the new state.
638      */
639     public void onResource(Resource resource) {
640         if (disposing) {
641             return;
642         }
643         boolean resourceConsumed = false;
644         if (resourceId.equals(resource.getId())) {
645             if (resource.hasFullState()) {
646                 thisResource = resource;
647                 if (!updatePropertiesDone) {
648                     updateProperties(resource);
649                     resourceConsumed = updatePropertiesDone;
650                 }
651             }
652             if (!updateDependenciesDone) {
653                 resourceConsumed = true;
654                 cancelTask(updateDependenciesTask, false);
655                 updateDependenciesTask = scheduler.submit(() -> updateDependencies());
656             }
657         } else {
658             Resource cachedResource = getResourceFromCache(resource);
659             if (cachedResource != null) {
660                 Setters.setResource(resource, cachedResource);
661                 resourceConsumed = updateChannels(resource);
662                 putResourceToCache(resource);
663                 if (ResourceType.LIGHT == resource.getType() && !updateLightPropertiesDone) {
664                     updateLightProperties(resource);
665                 }
666             }
667         }
668         if (resourceConsumed) {
669             logger.debug("{} -> onResource() consumed resource {}", resourceId, resource);
670         }
671     }
672
673     private void putResourceToCache(Resource resource) {
674         if (SUPPORTED_SCENE_TYPES.contains(resource.getType())) {
675             sceneContributorsCache.put(resource.getId(), resource);
676         } else {
677             serviceContributorsCache.put(resource.getId(), resource);
678         }
679     }
680
681     private @Nullable Resource getResourceFromCache(Resource resource) {
682         return SUPPORTED_SCENE_TYPES.contains(resource.getType()) //
683                 ? sceneContributorsCache.get(resource.getId())
684                 : serviceContributorsCache.get(resource.getId());
685     }
686
687     /**
688      * Update the thing internal state depending on a full list of resources sent from the bridge. If the resourceType
689      * is SCENE then call updateScenes(), otherwise if the resource refers to this thing, consume it via onResource() as
690      * any other resource, or else if the resourceType nevertheless matches the thing type, set the thing state offline.
691      *
692      * @param resourceType the type of the resources in the list.
693      * @param fullResources the full list of resources of the given type.
694      */
695     public void onResourcesList(ResourceType resourceType, List<Resource> fullResources) {
696         if (resourceType == ResourceType.SCENE) {
697             updateSceneContributors(fullResources);
698         } else {
699             fullResources.stream().filter(r -> resourceId.equals(r.getId())).findAny()
700                     .ifPresentOrElse(r -> onResource(r), () -> {
701                         if (resourceType == thisResource.getType()) {
702                             logger.debug("{} -> onResourcesList() configuration error: unknown resourceId", resourceId);
703                             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE,
704                                     "@text/offline.api2.gone.resource-id-unknown");
705                         }
706                     });
707         }
708     }
709
710     /**
711      * Process the incoming Resource to initialize the alert channel.
712      *
713      * @param resource a Resource possibly with an Alerts element.
714      */
715     private void updateAlertChannel(Resource resource) {
716         Alerts alerts = resource.getAlerts();
717         if (Objects.nonNull(alerts)) {
718             List<StateOption> stateOptions = alerts.getActionValues().stream().map(action -> action.name())
719                     .map(actionId -> new StateOption(actionId, actionId)).collect(Collectors.toList());
720             if (!stateOptions.isEmpty()) {
721                 stateDescriptionProvider.setStateOptions(new ChannelUID(thing.getUID(), CHANNEL_2_ALERT), stateOptions);
722                 logger.debug("{} -> updateAlerts() found {} associated alerts", resourceId, stateOptions.size());
723             }
724         }
725     }
726
727     /**
728      * If this v2 thing has a matching v1 legacy thing in the system, then for each channel in the v1 thing that
729      * corresponds to an equivalent channel in this v2 thing, and for all items that are linked to the v1 channel,
730      * create a new channel/item link between that item and the respective v2 channel in this thing.
731      */
732     private void updateChannelItemLinksFromLegacy() {
733         if (!disposing) {
734             legacyLinkedChannelUIDs.forEach(legacyLinkedChannelUID -> {
735                 String targetChannelId = REPLICATE_CHANNEL_ID_MAP.get(legacyLinkedChannelUID.getId());
736                 if (Objects.nonNull(targetChannelId)) {
737                     Channel targetChannel = thing.getChannel(targetChannelId);
738                     if (Objects.nonNull(targetChannel)) {
739                         ChannelUID uid = targetChannel.getUID();
740                         itemChannelLinkRegistry.getLinkedItems(legacyLinkedChannelUID).forEach(linkedItem -> {
741                             String item = linkedItem.getName();
742                             if (!itemChannelLinkRegistry.isLinked(item, uid)) {
743                                 if (logger.isDebugEnabled()) {
744                                     logger.debug(
745                                             "{} -> updateChannelItemLinksFromLegacy() item:{} linked to channel:{}",
746                                             resourceId, item, uid);
747                                 } else {
748                                     logger.info("Item '{}' linked to thing '{}' channel '{}'", item, thing.getUID(),
749                                             targetChannelId);
750                                 }
751                                 itemChannelLinkRegistry.add(new ItemChannelLink(item, uid));
752                             }
753                         });
754                     }
755                 }
756             });
757             legacyLinkedChannelUIDs.clear();
758         }
759     }
760
761     /**
762      * Set the active list of channels by removing any that had initially been created by the thing XML declaration, but
763      * which in fact did not have data returned from the bridge i.e. channels which are not in the supportedChannelIdSet
764      *
765      * Also warn if there are channels in the supportedChannelIdSet set which are not in the thing.
766      *
767      * Adjusts the channel list so that only the highest level channel is available in the normal channel list. If a
768      * light supports the color channel, then it's brightness and switch can be commanded via the 'B' part of the HSB
769      * channel value. And if it supports the brightness channel the switch can be controlled via the brightness. So we
770      * can remove these lower level channels from the normal channel list.
771      *
772      * For more advanced applications, it is necessary to orthogonally command the color xy parameter, dimming
773      * parameter, and/or on/off parameter independently. So we add corresponding advanced level 'CHANNEL_2_BLAH_ONLY'
774      * channels for that purpose. Since they are advanced level, normal users should normally not be confused by them,
775      * yet advanced users can use them nevertheless.
776      */
777     private void updateChannelList() {
778         if (!disposing) {
779             synchronized (supportedChannelIdSet) {
780                 logger.debug("{} -> updateChannelList()", resourceId);
781
782                 if (supportedChannelIdSet.contains(CHANNEL_2_COLOR)) {
783                     supportedChannelIdSet.add(CHANNEL_2_COLOR_XY_ONLY);
784                     //
785                     supportedChannelIdSet.remove(CHANNEL_2_BRIGHTNESS);
786                     supportedChannelIdSet.add(CHANNEL_2_DIMMING_ONLY);
787                     //
788                     supportedChannelIdSet.remove(CHANNEL_2_SWITCH);
789                     supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
790                 }
791                 if (supportedChannelIdSet.contains(CHANNEL_2_BRIGHTNESS)) {
792                     supportedChannelIdSet.add(CHANNEL_2_DIMMING_ONLY);
793                     //
794                     supportedChannelIdSet.remove(CHANNEL_2_SWITCH);
795                     supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
796                 }
797                 if (supportedChannelIdSet.contains(CHANNEL_2_SWITCH)) {
798                     supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
799                 }
800
801                 /*
802                  * This binding creates its dynamic list of channels by a 'subtractive' method i.e. the full set of
803                  * channels is initially created from the thing type xml, and then for any channels where UndfType.NULL
804                  * data is returned, the respective channel is removed from the full list. However in seldom cases
805                  * UndfType.NULL may wrongly be returned, so we should log a warning here just in case.
806                  */
807                 if (logger.isDebugEnabled()) {
808                     supportedChannelIdSet.stream().filter(channelId -> Objects.isNull(thing.getChannel(channelId)))
809                             .forEach(channelId -> logger.debug(
810                                     "{} -> updateChannelList() required channel '{}' missing", resourceId, channelId));
811                 } else {
812                     supportedChannelIdSet.stream().filter(channelId -> Objects.isNull(thing.getChannel(channelId)))
813                             .forEach(channelId -> logger.warn(
814                                     "Thing '{}' is missing required channel '{}'. Please recreate the thing!",
815                                     thing.getUID(), channelId));
816                 }
817
818                 // get list of unused channels
819                 List<Channel> unusedChannels = thing.getChannels().stream()
820                         .filter(channel -> !supportedChannelIdSet.contains(channel.getUID().getId()))
821                         .collect(Collectors.toList());
822
823                 // remove any unused channels
824                 if (!unusedChannels.isEmpty()) {
825                     if (logger.isDebugEnabled()) {
826                         unusedChannels.stream().map(channel -> channel.getUID().getId())
827                                 .forEach(channelId -> logger.debug(
828                                         "{} -> updateChannelList() removing unused channel '{}'", resourceId,
829                                         channelId));
830                     }
831                     updateThing(editThing().withoutChannels(unusedChannels).build());
832                 }
833             }
834         }
835     }
836
837     /**
838      * Update the state of the existing channels.
839      *
840      * @param resource the Resource containing the new channel state.
841      * @return true if the channel was found and updated.
842      */
843     private boolean updateChannels(Resource resource) {
844         logger.debug("{} -> updateChannels() from resource {}", resourceId, resource);
845         boolean fullUpdate = resource.hasFullState();
846         switch (resource.getType()) {
847             case BUTTON:
848                 if (fullUpdate) {
849                     addSupportedChannel(CHANNEL_2_BUTTON_LAST_EVENT);
850                     addSupportedChannel(CHANNEL_2_BUTTON_LAST_UPDATED);
851                     controlIds.put(resource.getId(), resource.getControlId());
852                 } else {
853                     State buttonState = resource.getButtonEventState(controlIds);
854                     updateState(CHANNEL_2_BUTTON_LAST_EVENT, buttonState, fullUpdate);
855                 }
856                 // Update channel from timestamp if last button pressed.
857                 State buttonLastUpdatedState = resource.getButtonLastUpdatedState(timeZoneProvider.getTimeZone());
858                 if (buttonLastUpdatedState instanceof DateTimeType) {
859                     Instant buttonLastUpdatedInstant = ((DateTimeType) buttonLastUpdatedState).getInstant();
860                     if (buttonLastUpdatedInstant.isAfter(buttonGroupLastUpdated)) {
861                         updateState(CHANNEL_2_BUTTON_LAST_UPDATED, buttonLastUpdatedState, fullUpdate);
862                         buttonGroupLastUpdated = buttonLastUpdatedInstant;
863                     }
864                 } else if (Instant.MIN.equals(buttonGroupLastUpdated)) {
865                     updateState(CHANNEL_2_BUTTON_LAST_UPDATED, buttonLastUpdatedState, fullUpdate);
866                 }
867                 break;
868
869             case DEVICE_POWER:
870                 updateState(CHANNEL_2_BATTERY_LEVEL, resource.getBatteryLevelState(), fullUpdate);
871                 updateState(CHANNEL_2_BATTERY_LOW, resource.getBatteryLowState(), fullUpdate);
872                 break;
873
874             case LIGHT:
875                 if (fullUpdate) {
876                     updateEffectChannel(resource);
877                 }
878                 updateState(CHANNEL_2_COLOR_TEMP_PERCENT, resource.getColorTemperaturePercentState(), fullUpdate);
879                 updateState(CHANNEL_2_COLOR_TEMP_ABSOLUTE, resource.getColorTemperatureAbsoluteState(), fullUpdate);
880                 updateState(CHANNEL_2_COLOR, resource.getColorState(), fullUpdate);
881                 updateState(CHANNEL_2_COLOR_XY_ONLY, resource.getColorXyState(), fullUpdate);
882                 updateState(CHANNEL_2_EFFECT, resource.getEffectState(), fullUpdate);
883                 // fall through for dimming and on/off related channels
884
885             case GROUPED_LIGHT:
886                 if (fullUpdate) {
887                     updateAlertChannel(resource);
888                 }
889                 updateState(CHANNEL_2_BRIGHTNESS, resource.getBrightnessState(), fullUpdate);
890                 updateState(CHANNEL_2_DIMMING_ONLY, resource.getDimmingState(), fullUpdate);
891                 updateState(CHANNEL_2_SWITCH, resource.getOnOffState(), fullUpdate);
892                 updateState(CHANNEL_2_ON_OFF_ONLY, resource.getOnOffState(), fullUpdate);
893                 updateState(CHANNEL_2_ALERT, resource.getAlertState(), fullUpdate);
894                 break;
895
896             case LIGHT_LEVEL:
897                 updateState(CHANNEL_2_LIGHT_LEVEL, resource.getLightLevelState(), fullUpdate);
898                 updateState(CHANNEL_2_LIGHT_LEVEL_LAST_UPDATED,
899                         resource.getLightLevelLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
900                 updateState(CHANNEL_2_LIGHT_LEVEL_ENABLED, resource.getEnabledState(), fullUpdate);
901                 break;
902
903             case MOTION:
904             case CAMERA_MOTION:
905                 updateState(CHANNEL_2_MOTION, resource.getMotionState(), fullUpdate);
906                 updateState(CHANNEL_2_MOTION_LAST_UPDATED,
907                         resource.getMotionLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
908                 updateState(CHANNEL_2_MOTION_ENABLED, resource.getEnabledState(), fullUpdate);
909                 break;
910
911             case RELATIVE_ROTARY:
912                 if (fullUpdate) {
913                     addSupportedChannel(CHANNEL_2_ROTARY_STEPS);
914                     addSupportedChannel(CHANNEL_2_ROTARY_STEPS_LAST_UPDATED);
915                 } else {
916                     updateState(CHANNEL_2_ROTARY_STEPS, resource.getRotaryStepsState(), fullUpdate);
917                 }
918                 updateState(CHANNEL_2_ROTARY_STEPS_LAST_UPDATED,
919                         resource.getRotaryStepsLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
920                 break;
921
922             case TEMPERATURE:
923                 updateState(CHANNEL_2_TEMPERATURE, resource.getTemperatureState(), fullUpdate);
924                 updateState(CHANNEL_2_TEMPERATURE_LAST_UPDATED,
925                         resource.getTemperatureLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
926                 updateState(CHANNEL_2_TEMPERATURE_ENABLED, resource.getEnabledState(), fullUpdate);
927                 break;
928
929             case ZIGBEE_CONNECTIVITY:
930                 updateConnectivityState(resource);
931                 break;
932
933             case SCENE:
934                 updateState(CHANNEL_2_SCENE, resource.getSceneState(), fullUpdate);
935                 break;
936
937             case CONTACT:
938                 updateState(CHANNEL_2_SECURITY_CONTACT, resource.getContactState(), fullUpdate);
939                 updateState(CHANNEL_2_SECURITY_CONTACT_LAST_UPDATED,
940                         resource.getContactLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
941                 updateState(CHANNEL_2_SECURITY_CONTACT_ENABLED, resource.getEnabledState(), fullUpdate);
942                 break;
943
944             case TAMPER:
945                 updateState(CHANNEL_2_SECURITY_TAMPER, resource.getTamperState(), fullUpdate);
946                 updateState(CHANNEL_2_SECURITY_TAMPER_LAST_UPDATED,
947                         resource.getTamperLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
948                 break;
949
950             case SMART_SCENE:
951                 updateState(CHANNEL_2_SCENE, resource.getSmartSceneState(), fullUpdate);
952                 break;
953
954             default:
955                 return false;
956         }
957         if (thisResource.getType() == ResourceType.DEVICE) {
958             updateState(CHANNEL_2_LAST_UPDATED, new DateTimeType(), fullUpdate);
959         }
960         return true;
961     }
962
963     /**
964      * Check the Zigbee connectivity and set the thing online status accordingly. If the thing is offline then set all
965      * its channel states to undefined, otherwise execute a refresh command to update channels to the latest current
966      * state.
967      *
968      * @param resource a Resource that potentially contains the Zigbee connectivity state.
969      */
970     private void updateConnectivityState(Resource resource) {
971         ZigbeeStatus zigbeeStatus = resource.getZigbeeStatus();
972         if (Objects.nonNull(zigbeeStatus)) {
973             logger.debug("{} -> updateConnectivityState() thingStatus:{}, zigbeeStatus:{}", resourceId,
974                     thing.getStatus(), zigbeeStatus);
975             hasConnectivityIssue = zigbeeStatus != ZigbeeStatus.CONNECTED;
976             if (hasConnectivityIssue) {
977                 if (thing.getStatusInfo().getStatusDetail() != ThingStatusDetail.COMMUNICATION_ERROR) {
978                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
979                             "@text/offline.api2.comm-error.zigbee-connectivity-issue");
980                     supportedChannelIdSet.forEach(channelId -> updateState(channelId, UnDefType.UNDEF));
981                 }
982             } else if (thing.getStatus() != ThingStatus.ONLINE) {
983                 updateStatus(ThingStatus.ONLINE);
984                 refreshAllChannels();
985             }
986         }
987     }
988
989     /**
990      * Get all resources needed for building the thing state. Build the forward / reverse contributor lookup maps. Set
991      * up the final list of channels in the thing.
992      */
993     private synchronized void updateDependencies() {
994         if (!disposing && !updateDependenciesDone) {
995             logger.debug("{} -> updateDependencies()", resourceId);
996             try {
997                 if (!updatePropertiesDone) {
998                     logger.debug("{} -> updateDependencies() properties not initialized", resourceId);
999                     return;
1000                 }
1001                 if (!updateSceneContributorsDone && !updateSceneContributors()) {
1002                     logger.debug("{} -> updateDependencies() scenes not initialized", resourceId);
1003                     return;
1004                 }
1005                 updateLookups();
1006                 updateServiceContributors();
1007                 updateChannelList();
1008                 updateChannelItemLinksFromLegacy();
1009                 if (!hasConnectivityIssue) {
1010                     updateStatus(ThingStatus.ONLINE);
1011                 }
1012                 updateDependenciesDone = true;
1013             } catch (ApiException e) {
1014                 logger.debug("{} -> updateDependencies() {}", resourceId, e.getMessage(), e);
1015                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
1016             } catch (AssetNotLoadedException e) {
1017                 logger.debug("{} -> updateDependencies() {}", resourceId, e.getMessage(), e);
1018                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
1019                         "@text/offline.api2.conf-error.assets-not-loaded");
1020             } catch (InterruptedException e) {
1021             }
1022         }
1023     }
1024
1025     /**
1026      * Process the incoming Resource to initialize the fixed resp. timed effects channel.
1027      *
1028      * @param resource a Resource possibly containing a fixed and/or timed effects element.
1029      */
1030     public void updateEffectChannel(Resource resource) {
1031         Effects fixedEffects = resource.getFixedEffects();
1032         TimedEffects timedEffects = resource.getTimedEffects();
1033         List<StateOption> stateOptions = Stream
1034                 .concat(Objects.nonNull(fixedEffects) ? fixedEffects.getStatusValues().stream() : Stream.empty(),
1035                         Objects.nonNull(timedEffects) ? timedEffects.getStatusValues().stream() : Stream.empty())
1036                 .map(effect -> {
1037                     String effectName = EffectType.of(effect).name();
1038                     return new StateOption(effectName, effectName);
1039                 }).distinct().collect(Collectors.toList());
1040         if (!stateOptions.isEmpty()) {
1041             stateDescriptionProvider.setStateOptions(new ChannelUID(thing.getUID(), CHANNEL_2_EFFECT), stateOptions);
1042             logger.debug("{} -> updateEffects() found {} effects", resourceId, stateOptions.size());
1043         }
1044     }
1045
1046     /**
1047      * Update the light properties.
1048      *
1049      * @param resource a Resource object containing the property data.
1050      */
1051     private synchronized void updateLightProperties(Resource resource) {
1052         if (!disposing && !updateLightPropertiesDone) {
1053             logger.debug("{} -> updateLightProperties()", resourceId);
1054
1055             Dimming dimming = resource.getDimming();
1056             thing.setProperty(PROPERTY_DIMMING_RANGE, Objects.nonNull(dimming) ? dimming.toPropertyValue() : null);
1057
1058             MirekSchema mirekSchema = resource.getMirekSchema();
1059             thing.setProperty(PROPERTY_COLOR_TEMP_RANGE,
1060                     Objects.nonNull(mirekSchema) ? mirekSchema.toPropertyValue() : null);
1061
1062             ColorXy colorXy = resource.getColorXy();
1063             Gamut2 gamut = Objects.nonNull(colorXy) ? colorXy.getGamut2() : null;
1064             thing.setProperty(PROPERTY_COLOR_GAMUT, Objects.nonNull(gamut) ? gamut.toPropertyValue() : null);
1065
1066             updateLightPropertiesDone = true;
1067         }
1068     }
1069
1070     /**
1071      * Initialize the lookup maps of resources that contribute to the thing state.
1072      */
1073     private void updateLookups() {
1074         if (!disposing) {
1075             logger.debug("{} -> updateLookups()", resourceId);
1076             // get supported services
1077             List<ResourceReference> services = thisResource.getServiceReferences();
1078
1079             // add supported services to contributorsCache
1080             serviceContributorsCache.clear();
1081             serviceContributorsCache.putAll(services.stream()
1082                     .collect(Collectors.toMap(ResourceReference::getId, r -> new Resource(r.getType()))));
1083
1084             // add supported services to commandResourceIds
1085             commandResourceIds.clear();
1086             commandResourceIds.putAll(services.stream() // use a 'mergeFunction' to prevent duplicates
1087                     .collect(Collectors.toMap(ResourceReference::getType, ResourceReference::getId, (r1, r2) -> r1)));
1088         }
1089     }
1090
1091     /**
1092      * Update the primary device properties.
1093      *
1094      * @param resource a Resource object containing the property data.
1095      */
1096     private synchronized void updateProperties(Resource resource) {
1097         if (!disposing && !updatePropertiesDone) {
1098             logger.debug("{} -> updateProperties()", resourceId);
1099             Map<String, String> properties = new HashMap<>(thing.getProperties());
1100
1101             // resource data
1102             properties.put(PROPERTY_RESOURCE_TYPE, thisResource.getType().toString());
1103             properties.put(PROPERTY_RESOURCE_NAME, thisResource.getName());
1104
1105             // owner information
1106             ResourceReference owner = thisResource.getOwner();
1107             if (Objects.nonNull(owner)) {
1108                 String ownerId = owner.getId();
1109                 if (Objects.nonNull(ownerId)) {
1110                     properties.put(PROPERTY_OWNER, ownerId);
1111                 }
1112                 ResourceType ownerType = owner.getType();
1113                 properties.put(PROPERTY_OWNER_TYPE, ownerType.toString());
1114             }
1115
1116             // metadata
1117             MetaData metaData = thisResource.getMetaData();
1118             if (Objects.nonNull(metaData)) {
1119                 properties.put(PROPERTY_RESOURCE_ARCHETYPE, metaData.getArchetype().toString());
1120             }
1121
1122             // product data
1123             ProductData productData = thisResource.getProductData();
1124             if (Objects.nonNull(productData)) {
1125                 String modelId = productData.getModelId();
1126
1127                 // standard properties
1128                 properties.put(PROPERTY_RESOURCE_ID, resourceId);
1129                 properties.put(Thing.PROPERTY_MODEL_ID, modelId);
1130                 properties.put(Thing.PROPERTY_VENDOR, productData.getManufacturerName());
1131                 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, productData.getSoftwareVersion());
1132                 String hardwarePlatformType = productData.getHardwarePlatformType();
1133                 if (Objects.nonNull(hardwarePlatformType)) {
1134                     properties.put(Thing.PROPERTY_HARDWARE_VERSION, hardwarePlatformType);
1135                 }
1136
1137                 // hue specific properties
1138                 properties.put(PROPERTY_PRODUCT_NAME, productData.getProductName());
1139                 properties.put(PROPERTY_PRODUCT_ARCHETYPE, productData.getProductArchetype().toString());
1140                 properties.put(PROPERTY_PRODUCT_CERTIFIED, productData.getCertified().toString());
1141
1142                 // Check device for needed work-arounds.
1143                 if (LK_WISER_DIMMER_MODEL_ID.equals(modelId)) {
1144                     // Apply transition time as a workaround for LK Wiser Dimmer firmware bug.
1145                     // Additional details here: https://techblog.vindvejr.dk/?p=455
1146                     applyOffTransitionWorkaround = true;
1147                     logger.debug("{} -> enabling work-around for turning off LK Wiser Dimmer", resourceId);
1148                 }
1149             }
1150
1151             thing.setProperties(properties);
1152             updatePropertiesDone = true;
1153         }
1154     }
1155
1156     /**
1157      * Execute an HTTP GET command to fetch the resources data for the referenced resource.
1158      *
1159      * @param reference to the required resource.
1160      * @throws ApiException if a communication error occurred.
1161      * @throws AssetNotLoadedException if one of the assets is not loaded.
1162      * @throws InterruptedException
1163      */
1164     private void updateResource(ResourceReference reference)
1165             throws ApiException, AssetNotLoadedException, InterruptedException {
1166         if (!disposing) {
1167             logger.debug("{} -> updateResource() from resource {}", resourceId, reference);
1168             getBridgeHandler().getResources(reference).getResources().stream()
1169                     .forEach(resource -> onResource(resource));
1170         }
1171     }
1172
1173     /**
1174      * Fetch the full list of normal resp. smart scenes from the bridge, and call
1175      * {@code updateSceneContributors(List<Resource> allScenes)}
1176      *
1177      * @throws ApiException if a communication error occurred.
1178      * @throws AssetNotLoadedException if one of the assets is not loaded.
1179      * @throws InterruptedException
1180      */
1181     public boolean updateSceneContributors() throws ApiException, AssetNotLoadedException, InterruptedException {
1182         if (!disposing && !updateSceneContributorsDone) {
1183             List<Resource> allScenes = new ArrayList<>();
1184             for (ResourceType type : SUPPORTED_SCENE_TYPES) {
1185                 allScenes.addAll(getBridgeHandler().getResources(new ResourceReference().setType(type)).getResources());
1186             }
1187             updateSceneContributors(allScenes);
1188         }
1189         return updateSceneContributorsDone;
1190     }
1191
1192     /**
1193      * Process the incoming list of normal resp. smart scene resources to find those which contribute to this thing. And
1194      * if there are any, include a scene channel in the supported channel list, and populate its respective state
1195      * options.
1196      *
1197      * @param allScenes the full list of normal resp. smart scene resources.
1198      */
1199     public synchronized boolean updateSceneContributors(List<Resource> allScenes) {
1200         if (!disposing && !updateSceneContributorsDone) {
1201             sceneContributorsCache.clear();
1202             sceneResourceEntries.clear();
1203
1204             ResourceReference thisReference = getResourceReference();
1205             Set<Resource> scenes = allScenes.stream().filter(s -> thisReference.equals(s.getGroup()))
1206                     .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Resource::getName))));
1207
1208             if (!scenes.isEmpty()) {
1209                 sceneContributorsCache.putAll(scenes.stream().collect(Collectors.toMap(s -> s.getId(), s -> s)));
1210                 sceneResourceEntries.putAll(scenes.stream().collect(Collectors.toMap(s -> s.getName(), s -> s)));
1211
1212                 State state = scenes.stream().filter(s -> s.getSceneActive().orElse(false)).map(s -> s.getSceneState())
1213                         .findAny().orElse(UnDefType.UNDEF);
1214
1215                 updateState(CHANNEL_2_SCENE, state, true);
1216
1217                 stateDescriptionProvider.setStateOptions(new ChannelUID(thing.getUID(), CHANNEL_2_SCENE), scenes
1218                         .stream().map(s -> s.getName()).map(n -> new StateOption(n, n)).collect(Collectors.toList()));
1219
1220                 logger.debug("{} -> updateSceneContributors() found {} normal resp. smart scenes", resourceId,
1221                         scenes.size());
1222             }
1223             updateSceneContributorsDone = true;
1224         }
1225         return updateSceneContributorsDone;
1226     }
1227
1228     /**
1229      * Execute a series of HTTP GET commands to fetch the resource data for all service resources that contribute to the
1230      * thing state.
1231      *
1232      * @throws ApiException if a communication error occurred.
1233      * @throws AssetNotLoadedException if one of the assets is not loaded.
1234      * @throws InterruptedException
1235      */
1236     private void updateServiceContributors() throws ApiException, AssetNotLoadedException, InterruptedException {
1237         if (!disposing) {
1238             logger.debug("{} -> updateServiceContributors() called for {} contributors", resourceId,
1239                     serviceContributorsCache.size());
1240             ResourceReference reference = new ResourceReference();
1241             for (var entry : serviceContributorsCache.entrySet()) {
1242                 updateResource(reference.setId(entry.getKey()).setType(entry.getValue().getType()));
1243             }
1244         }
1245     }
1246
1247     /**
1248      * Update the channel state, and if appropriate add the channel ID to the set of supportedChannelIds. Calls either
1249      * OH core updateState() or triggerChannel() methods depending on the channel kind.
1250      *
1251      * Note: the particular 'UnDefType.UNDEF' value of the state argument is used to specially indicate the undefined
1252      * state, but yet that its channel shall nevertheless continue to be present in the thing.
1253      *
1254      * @param channelID the id of the channel.
1255      * @param state the new state of the channel.
1256      * @param fullUpdate if true always update the channel, otherwise only update if state is not 'UNDEF'.
1257      */
1258     private void updateState(String channelID, State state, boolean fullUpdate) {
1259         boolean isDefined = state != UnDefType.NULL;
1260         Channel channel = thing.getChannel(channelID);
1261
1262         if ((fullUpdate || isDefined) && Objects.nonNull(channel)) {
1263             logger.debug("{} -> updateState() '{}' update with '{}' (fullUpdate:{}, isDefined:{})", resourceId,
1264                     channelID, state, fullUpdate, isDefined);
1265
1266             switch (channel.getKind()) {
1267                 case STATE:
1268                     updateState(channelID, state);
1269                     break;
1270
1271                 case TRIGGER:
1272                     if (state instanceof DecimalType) {
1273                         triggerChannel(channelID, String.valueOf(((DecimalType) state).intValue()));
1274                     }
1275             }
1276         }
1277         if (fullUpdate && isDefined) {
1278             addSupportedChannel(channelID);
1279         }
1280     }
1281
1282     /**
1283      * Check if a PROPERTY_LEGACY_THING_UID value was set by the discovery process, and if so, clone the legacy thing's
1284      * settings into this thing.
1285      */
1286     private void updateThingFromLegacy() {
1287         if (isInitialized()) {
1288             logger.warn("Cannot update thing '{}' from legacy thing since handler already initialized.",
1289                     thing.getUID());
1290             return;
1291         }
1292         Map<String, String> properties = thing.getProperties();
1293         String legacyThingUID = properties.get(PROPERTY_LEGACY_THING_UID);
1294         if (Objects.nonNull(legacyThingUID)) {
1295             Thing legacyThing = thingRegistry.get(new ThingUID(legacyThingUID));
1296             if (Objects.nonNull(legacyThing)) {
1297                 ThingBuilder editBuilder = editThing();
1298
1299                 String location = legacyThing.getLocation();
1300                 if (Objects.nonNull(location) && !location.isBlank()) {
1301                     editBuilder = editBuilder.withLocation(location);
1302                 }
1303
1304                 // save list of legacyLinkedChannelUIDs for use after channel list is initialised
1305                 legacyLinkedChannelUIDs.clear();
1306                 legacyLinkedChannelUIDs.addAll(legacyThing.getChannels().stream().map(Channel::getUID)
1307                         .filter(uid -> REPLICATE_CHANNEL_ID_MAP.containsKey(uid.getId())
1308                                 && itemChannelLinkRegistry.isLinked(uid))
1309                         .collect(Collectors.toList()));
1310
1311                 Map<String, String> newProperties = new HashMap<>(properties);
1312                 newProperties.remove(PROPERTY_LEGACY_THING_UID);
1313
1314                 updateThing(editBuilder.withProperties(newProperties).build());
1315             }
1316         }
1317     }
1318 }