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