2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.hue.internal.handler;
15 import static org.openhab.binding.hue.internal.HueBindingConstants.*;
17 import java.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;
27 import java.util.Objects;
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;
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;
97 * Handler for things based on CLIP 2 'device', 'room', or 'zone resources.
99 * @author Andrew Fiddian-Green - Initial contribution.
102 public class Clip2ThingHandler extends BaseThingHandler {
104 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DEVICE, THING_TYPE_ROOM,
107 private static final Set<ResourceType> SUPPORTED_SCENE_TYPES = Set.of(ResourceType.SCENE, ResourceType.SMART_SCENE);
109 private static final Duration DYNAMICS_ACTIVE_WINDOW = Duration.ofSeconds(10);
111 private static final String LK_WISER_DIMMER_MODEL_ID = "LK Dimmer";
113 private final Logger logger = LoggerFactory.getLogger(Clip2ThingHandler.class);
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.
121 private final Map<String, Resource> serviceContributorsCache = new ConcurrentHashMap<>();
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.
128 private final Map<ResourceType, String> commandResourceIds = new ConcurrentHashMap<>();
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.
136 private final Map<String, Integer> controlIds = new ConcurrentHashMap<>();
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.
143 private final Set<String> supportedChannelIdSet = new HashSet<>();
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.
149 private final Map<String, Resource> sceneContributorsCache = new ConcurrentHashMap<>();
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.
155 private final Map<String, Resource> sceneResourceEntries = new ConcurrentHashMap<>();
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.
161 private final List<ChannelUID> legacyLinkedChannelUIDs = new CopyOnWriteArrayList<>();
163 private final ThingRegistry thingRegistry;
164 private final ItemChannelLinkRegistry itemChannelLinkRegistry;
165 private final Clip2StateDescriptionProvider stateDescriptionProvider;
166 private final TimeZoneProvider timeZoneProvider;
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;
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;
182 private @Nullable Future<?> alertResetTask;
183 private @Nullable Future<?> dynamicsResetTask;
184 private @Nullable Future<?> updateDependenciesTask;
185 private @Nullable Future<?> updateServiceContributorsTask;
187 public Clip2ThingHandler(Thing thing, Clip2StateDescriptionProvider stateDescriptionProvider,
188 TimeZoneProvider timeZoneProvider, ThingRegistry thingRegistry,
189 ItemChannelLinkRegistry itemChannelLinkRegistry) {
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);
200 throw new IllegalArgumentException("Wrong thing type " + thingTypeUID.getAsString());
203 this.thingRegistry = thingRegistry;
204 this.itemChannelLinkRegistry = itemChannelLinkRegistry;
205 this.stateDescriptionProvider = stateDescriptionProvider;
206 this.timeZoneProvider = timeZoneProvider;
210 * Add a channel ID to the supportedChannelIdSet set. If the channel supports dynamics (timed transitions) then add
211 * the respective channel as well.
213 * @param channelId the channel ID to add.
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();
228 * Cancel the given task.
230 * @param cancelTask the task to be cancelled (may be null)
231 * @param mayInterrupt allows cancel() to interrupt the thread.
233 private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
234 if (Objects.nonNull(cancelTask)) {
235 cancelTask.cancel(mayInterrupt);
240 * Clear the dynamics channel parameters.
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);
249 public void dispose() {
250 logger.debug("{} -> dispose()", resourceId);
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();
270 * Get the bridge handler.
272 * @throws AssetNotLoadedException if the handler does not exist.
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;
282 throw new AssetNotLoadedException("Bridge handler missing");
286 * Do a double lookup to get the cached resource that matches the given ResourceType.
288 * @param resourceType the type to search for.
289 * @return the Resource, or null if not found.
291 private @Nullable Resource getCachedResource(ResourceType resourceType) {
292 String commandResourceId = commandResourceIds.get(resourceType);
293 return Objects.nonNull(commandResourceId) ? serviceContributorsCache.get(commandResourceId) : null;
297 * Return a ResourceReference to this handler's resource.
299 * @return a ResourceReference instance.
301 public ResourceReference getResourceReference() {
302 return new ResourceReference().setId(resourceId).setType(thisResource.getType());
306 * Register the 'DynamicsAction' service.
309 public Collection<Class<? extends ThingHandlerService>> getServices() {
310 return Set.of(DynamicsActions.class);
314 public void handleCommand(ChannelUID channelUID, Command commandParam) {
315 if (RefreshType.REFRESH.equals(commandParam)) {
316 if (thing.getStatus() == ThingStatus.ONLINE) {
317 refreshAllChannels();
322 Channel channel = thing.getChannel(channelUID);
323 if (channel == null) {
324 if (logger.isDebugEnabled()) {
325 logger.debug("{} -> handleCommand() channelUID:{} does not exist", resourceId, channelUID);
328 logger.warn("Command received for channel '{}' which is not in thing '{}'.", channelUID,
334 ResourceType lightResourceType = thisResource.getType() == ResourceType.DEVICE ? ResourceType.LIGHT
335 : ResourceType.GROUPED_LIGHT;
337 Resource putResource = null;
338 String putResourceId = null;
339 Command command = commandParam;
340 String channelId = channelUID.getId();
341 Resource cache = getCachedResource(lightResourceType);
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,
352 case CHANNEL_2_EFFECT:
353 putResource = Setters.setEffect(new Resource(lightResourceType), command, cache).setOnOff(OnOffType.ON);
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)));
366 } else if (command instanceof OnOffType) {
367 command = OnOffType.OFF == command ? PercentType.ZERO : PercentType.HUNDRED;
369 putResource = Setters.setColorTemperaturePercent(new Resource(lightResourceType), command, cache);
372 case CHANNEL_2_COLOR_TEMP_ABSOLUTE:
373 putResource = Setters.setColorTemperatureAbsolute(new Resource(lightResourceType), command, cache);
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();
383 // NB fall through for handling of brightness and switch related commands !!
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));
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);
405 // NB fall through for handling of switch related commands !!
407 case CHANNEL_2_SWITCH:
408 putResource = Objects.nonNull(putResource) ? putResource : new Resource(lightResourceType);
409 putResource.setOnOff(command);
410 applyDeviceSpecificWorkArounds(command, putResource);
413 case CHANNEL_2_COLOR_XY_ONLY:
414 putResource = Setters.setColorXy(new Resource(lightResourceType), command, cache);
417 case CHANNEL_2_DIMMING_ONLY:
418 putResource = Setters.setDimming(new Resource(lightResourceType), command, cache);
421 case CHANNEL_2_ON_OFF_ONLY:
422 putResource = new Resource(lightResourceType).setOnOff(command);
423 applyDeviceSpecificWorkArounds(command, putResource);
426 case CHANNEL_2_TEMPERATURE_ENABLED:
427 putResource = new Resource(ResourceType.TEMPERATURE).setEnabled(command);
430 case CHANNEL_2_MOTION_ENABLED:
431 putResource = new Resource(ResourceType.MOTION).setEnabled(command);
434 case CHANNEL_2_LIGHT_LEVEL_ENABLED:
435 putResource = new Resource(ResourceType.LIGHT_LEVEL).setEnabled(command);
438 case CHANNEL_2_SECURITY_CONTACT_ENABLED:
439 putResource = new Resource(ResourceType.CONTACT).setEnabled(command);
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) {
450 putResource.setRecallAction(SceneRecallAction.ACTIVE);
453 putResource.setRecallAction(SmartSceneRecallAction.ACTIVATE);
456 logger.debug("{} -> handleCommand() type '{}' is not a supported scene type",
457 resourceId, putResourceType);
460 putResourceId = scene.getId();
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,
478 cancelTask(dynamicsResetTask, false);
479 dynamicsResetTask = scheduler.schedule(() -> clearDynamicsChannel(), clearAfter.toMillis(),
480 TimeUnit.MILLISECONDS);
484 if (logger.isDebugEnabled()) {
485 logger.debug("{} -> handleCommand() channelUID:{} unknown", resourceId, channelUID);
487 logger.warn("Command received for unknown channel '{}'.", channelUID);
492 if (putResource == null) {
493 if (logger.isDebugEnabled()) {
494 logger.debug("{} -> handleCommand() command:{} not supported on channelUID:{}", resourceId, command,
497 logger.warn("Command '{}' is not supported on channel '{}'.", command, channelUID);
502 putResourceId = Objects.nonNull(putResourceId) ? putResourceId : commandResourceIds.get(putResource.getType());
503 if (putResourceId == null) {
504 if (logger.isDebugEnabled()) {
506 "{} -> handleCommand() channelUID:{}, command:{}, putResourceType:{} => missing resource ID",
507 resourceId, channelUID, command, putResource.getType());
509 logger.warn("Command '{}' for channel '{}' cannot be processed by thing '{}'.", command, channelUID,
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);
523 putResource.setDynamicsDuration(dynamicsDuration);
528 putResource.setId(putResourceId);
529 logger.debug("{} -> handleCommand() put resource {}", resourceId, putResource);
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()));
537 } catch (ApiException | AssetNotLoadedException e) {
538 if (logger.isDebugEnabled()) {
539 logger.debug("{} -> handleCommand() error {}", resourceId, e.getMessage(), e);
541 logger.warn("Command '{}' for thing '{}', channel '{}' failed with error '{}'.", command,
542 thing.getUID(), channelUID, e.getMessage());
544 } catch (InterruptedException e) {
548 private void refreshAllChannels() {
549 if (!updateDependenciesDone) {
552 cancelTask(updateServiceContributorsTask, false);
553 updateServiceContributorsTask = scheduler.schedule(() -> {
555 updateServiceContributors();
556 } catch (ApiException | AssetNotLoadedException e) {
557 logger.debug("{} -> handleCommand() error {}", resourceId, e.getMessage(), e);
558 } catch (InterruptedException e) {
560 }, 3, TimeUnit.SECONDS);
564 * Apply device specific work-arounds needed for given command.
566 * @param command the handled command.
567 * @param putResource the resource that will be adjusted if needed.
569 private void applyDeviceSpecificWorkArounds(Command command, Resource putResource) {
570 if (command == OnOffType.OFF && applyOffTransitionWorkaround) {
571 putResource.setDynamicsDuration(dynamicsDuration);
576 * Handle a 'dynamics' command for the given channel ID for the given dynamics duration.
578 * @param channelId the ID of the target channel.
579 * @param command the new target state.
580 * @param duration the transition duration.
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);
594 logger.warn("Dynamics command '{}' for thing '{}', channel '{}' and duration'{}' failed.", command,
595 thing.getUID(), channelId, duration);
599 public void initialize() {
600 Clip2ThingConfig config = getConfigAs(Clip2ThingConfig.class);
602 String resourceId = config.resourceId;
603 if (resourceId.isBlank()) {
604 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
605 "@text/offline.api2.conf-error.resource-id-bad");
608 thisResource.setId(resourceId);
609 this.resourceId = resourceId;
610 logger.debug("{} -> initialize()", resourceId);
612 updateThingFromLegacy();
613 updateStatus(ThingStatus.UNKNOWN);
615 dynamicsDuration = Duration.ZERO;
616 dynamicsExpireTime = Instant.MIN;
619 hasConnectivityIssue = false;
620 updatePropertiesDone = false;
621 updateDependenciesDone = false;
622 updateLightPropertiesDone = false;
623 updateSceneContributorsDone = false;
625 Bridge bridge = getBridge();
626 if (Objects.nonNull(bridge)) {
627 BridgeHandler bridgeHandler = bridge.getHandler();
628 if (bridgeHandler instanceof Clip2BridgeHandler) {
629 ((Clip2BridgeHandler) bridgeHandler).childInitialized();
635 * Update the channel state depending on a new resource sent from the bridge.
637 * @param resource a Resource object containing the new state.
639 public void onResource(Resource resource) {
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;
652 if (!updateDependenciesDone) {
653 resourceConsumed = true;
654 cancelTask(updateDependenciesTask, false);
655 updateDependenciesTask = scheduler.submit(() -> updateDependencies());
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);
668 if (resourceConsumed) {
669 logger.debug("{} -> onResource() consumed resource {}", resourceId, resource);
673 private void putResourceToCache(Resource resource) {
674 if (SUPPORTED_SCENE_TYPES.contains(resource.getType())) {
675 sceneContributorsCache.put(resource.getId(), resource);
677 serviceContributorsCache.put(resource.getId(), resource);
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());
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.
692 * @param resourceType the type of the resources in the list.
693 * @param fullResources the full list of resources of the given type.
695 public void onResourcesList(ResourceType resourceType, List<Resource> fullResources) {
696 if (resourceType == ResourceType.SCENE) {
697 updateSceneContributors(fullResources);
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.CONFIGURATION_ERROR,
704 "@text/offline.api2.conf-error.resource-id-bad");
711 * Process the incoming Resource to initialize the alert channel.
713 * @param resource a Resource possibly with an Alerts element.
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());
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.
732 private void updateChannelItemLinksFromLegacy() {
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()) {
745 "{} -> updateChannelItemLinksFromLegacy() item:{} linked to channel:{}",
746 resourceId, item, uid);
748 logger.info("Item '{}' linked to thing '{}' channel '{}'", item, thing.getUID(),
751 itemChannelLinkRegistry.add(new ItemChannelLink(item, uid));
757 legacyLinkedChannelUIDs.clear();
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
765 * Also warn if there are channels in the supportedChannelIdSet set which are not in the thing.
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.
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.
777 private void updateChannelList() {
779 synchronized (supportedChannelIdSet) {
780 logger.debug("{} -> updateChannelList()", resourceId);
782 if (supportedChannelIdSet.contains(CHANNEL_2_COLOR)) {
783 supportedChannelIdSet.add(CHANNEL_2_COLOR_XY_ONLY);
785 supportedChannelIdSet.remove(CHANNEL_2_BRIGHTNESS);
786 supportedChannelIdSet.add(CHANNEL_2_DIMMING_ONLY);
788 supportedChannelIdSet.remove(CHANNEL_2_SWITCH);
789 supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
791 if (supportedChannelIdSet.contains(CHANNEL_2_BRIGHTNESS)) {
792 supportedChannelIdSet.add(CHANNEL_2_DIMMING_ONLY);
794 supportedChannelIdSet.remove(CHANNEL_2_SWITCH);
795 supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
797 if (supportedChannelIdSet.contains(CHANNEL_2_SWITCH)) {
798 supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
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.
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));
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));
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());
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,
831 updateThing(editThing().withoutChannels(unusedChannels).build());
838 * Update the state of the existing channels.
840 * @param resource the Resource containing the new channel state.
841 * @return true if the channel was found and updated.
843 private boolean updateChannels(Resource resource) {
844 logger.debug("{} -> updateChannels() from resource {}", resourceId, resource);
845 boolean fullUpdate = resource.hasFullState();
846 switch (resource.getType()) {
849 addSupportedChannel(CHANNEL_2_BUTTON_LAST_EVENT);
850 addSupportedChannel(CHANNEL_2_BUTTON_LAST_UPDATED);
851 controlIds.put(resource.getId(), resource.getControlId());
853 State buttonState = resource.getButtonEventState(controlIds);
854 updateState(CHANNEL_2_BUTTON_LAST_EVENT, buttonState, fullUpdate);
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;
864 } else if (Instant.MIN.equals(buttonGroupLastUpdated)) {
865 updateState(CHANNEL_2_BUTTON_LAST_UPDATED, buttonLastUpdatedState, fullUpdate);
870 updateState(CHANNEL_2_BATTERY_LEVEL, resource.getBatteryLevelState(), fullUpdate);
871 updateState(CHANNEL_2_BATTERY_LOW, resource.getBatteryLowState(), fullUpdate);
876 updateEffectChannel(resource);
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
887 updateAlertChannel(resource);
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);
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);
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);
911 case RELATIVE_ROTARY:
913 addSupportedChannel(CHANNEL_2_ROTARY_STEPS);
914 addSupportedChannel(CHANNEL_2_ROTARY_STEPS_LAST_UPDATED);
916 updateState(CHANNEL_2_ROTARY_STEPS, resource.getRotaryStepsState(), fullUpdate);
918 updateState(CHANNEL_2_ROTARY_STEPS_LAST_UPDATED,
919 resource.getRotaryStepsLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
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);
929 case ZIGBEE_CONNECTIVITY:
930 updateConnectivityState(resource);
934 updateState(CHANNEL_2_SCENE, resource.getSceneState(), fullUpdate);
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);
945 updateState(CHANNEL_2_SECURITY_TAMPER, resource.getTamperState(), fullUpdate);
946 updateState(CHANNEL_2_SECURITY_TAMPER_LAST_UPDATED,
947 resource.getTamperLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
951 updateState(CHANNEL_2_SCENE, resource.getSmartSceneState(), fullUpdate);
957 if (thisResource.getType() == ResourceType.DEVICE) {
958 updateState(CHANNEL_2_LAST_UPDATED, new DateTimeType(), fullUpdate);
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
968 * @param resource a Resource that potentially contains the Zigbee connectivity state.
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));
982 } else if (thing.getStatus() != ThingStatus.ONLINE) {
983 updateStatus(ThingStatus.ONLINE);
984 refreshAllChannels();
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.
993 private synchronized void updateDependencies() {
994 if (!disposing && !updateDependenciesDone) {
995 logger.debug("{} -> updateDependencies()", resourceId);
997 if (!updatePropertiesDone) {
998 logger.debug("{} -> updateDependencies() properties not initialized", resourceId);
1001 if (!updateSceneContributorsDone && !updateSceneContributors()) {
1002 logger.debug("{} -> updateDependencies() scenes not initialized", resourceId);
1006 updateServiceContributors();
1007 updateChannelList();
1008 updateChannelItemLinksFromLegacy();
1009 if (!hasConnectivityIssue) {
1010 updateStatus(ThingStatus.ONLINE);
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) {
1026 * Process the incoming Resource to initialize the fixed resp. timed effects channel.
1028 * @param resource a Resource possibly containing a fixed and/or timed effects element.
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())
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());
1047 * Update the light properties.
1049 * @param resource a Resource object containing the property data.
1051 private synchronized void updateLightProperties(Resource resource) {
1052 if (!disposing && !updateLightPropertiesDone) {
1053 logger.debug("{} -> updateLightProperties()", resourceId);
1055 Dimming dimming = resource.getDimming();
1056 thing.setProperty(PROPERTY_DIMMING_RANGE, Objects.nonNull(dimming) ? dimming.toPropertyValue() : null);
1058 MirekSchema mirekSchema = resource.getMirekSchema();
1059 thing.setProperty(PROPERTY_COLOR_TEMP_RANGE,
1060 Objects.nonNull(mirekSchema) ? mirekSchema.toPropertyValue() : null);
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);
1066 updateLightPropertiesDone = true;
1071 * Initialize the lookup maps of resources that contribute to the thing state.
1073 private void updateLookups() {
1075 logger.debug("{} -> updateLookups()", resourceId);
1076 // get supported services
1077 List<ResourceReference> services = thisResource.getServiceReferences();
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()))));
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)));
1092 * Update the primary device properties.
1094 * @param resource a Resource object containing the property data.
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());
1102 properties.put(PROPERTY_RESOURCE_TYPE, thisResource.getType().toString());
1103 properties.put(PROPERTY_RESOURCE_NAME, thisResource.getName());
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);
1112 ResourceType ownerType = owner.getType();
1113 properties.put(PROPERTY_OWNER_TYPE, ownerType.toString());
1117 MetaData metaData = thisResource.getMetaData();
1118 if (Objects.nonNull(metaData)) {
1119 properties.put(PROPERTY_RESOURCE_ARCHETYPE, metaData.getArchetype().toString());
1123 ProductData productData = thisResource.getProductData();
1124 if (Objects.nonNull(productData)) {
1125 String modelId = productData.getModelId();
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);
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());
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);
1151 thing.setProperties(properties);
1152 updatePropertiesDone = true;
1157 * Execute an HTTP GET command to fetch the resources data for the referenced resource.
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
1164 private void updateResource(ResourceReference reference)
1165 throws ApiException, AssetNotLoadedException, InterruptedException {
1167 logger.debug("{} -> updateResource() from resource {}", resourceId, reference);
1168 getBridgeHandler().getResources(reference).getResources().stream()
1169 .forEach(resource -> onResource(resource));
1174 * Fetch the full list of normal resp. smart scenes from the bridge, and call
1175 * {@code updateSceneContributors(List<Resource> allScenes)}
1177 * @throws ApiException if a communication error occurred.
1178 * @throws AssetNotLoadedException if one of the assets is not loaded.
1179 * @throws InterruptedException
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());
1187 updateSceneContributors(allScenes);
1189 return updateSceneContributorsDone;
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
1197 * @param allScenes the full list of normal resp. smart scene resources.
1199 public synchronized boolean updateSceneContributors(List<Resource> allScenes) {
1200 if (!disposing && !updateSceneContributorsDone) {
1201 sceneContributorsCache.clear();
1202 sceneResourceEntries.clear();
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))));
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)));
1212 State state = scenes.stream().filter(s -> s.getSceneActive().orElse(false)).map(s -> s.getSceneState())
1213 .findAny().orElse(UnDefType.UNDEF);
1215 updateState(CHANNEL_2_SCENE, state, true);
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()));
1220 logger.debug("{} -> updateSceneContributors() found {} normal resp. smart scenes", resourceId,
1223 updateSceneContributorsDone = true;
1225 return updateSceneContributorsDone;
1229 * Execute a series of HTTP GET commands to fetch the resource data for all service resources that contribute to the
1232 * @throws ApiException if a communication error occurred.
1233 * @throws AssetNotLoadedException if one of the assets is not loaded.
1234 * @throws InterruptedException
1236 private void updateServiceContributors() throws ApiException, AssetNotLoadedException, InterruptedException {
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()));
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.
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.
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'.
1258 private void updateState(String channelID, State state, boolean fullUpdate) {
1259 boolean isDefined = state != UnDefType.NULL;
1260 Channel channel = thing.getChannel(channelID);
1262 if ((fullUpdate || isDefined) && Objects.nonNull(channel)) {
1263 logger.debug("{} -> updateState() '{}' update with '{}' (fullUpdate:{}, isDefined:{})", resourceId,
1264 channelID, state, fullUpdate, isDefined);
1266 switch (channel.getKind()) {
1268 updateState(channelID, state);
1272 if (state instanceof DecimalType) {
1273 triggerChannel(channelID, String.valueOf(((DecimalType) state).intValue()));
1277 if (fullUpdate && isDefined) {
1278 addSupportedChannel(channelID);
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.
1286 private void updateThingFromLegacy() {
1287 if (isInitialized()) {
1288 logger.warn("Cannot update thing '{}' from legacy thing since handler already initialized.",
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();
1299 String location = legacyThing.getLocation();
1300 if (Objects.nonNull(location) && !location.isBlank()) {
1301 editBuilder = editBuilder.withLocation(location);
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()));
1311 Map<String, String> newProperties = new HashMap<>(properties);
1312 newProperties.remove(PROPERTY_LEGACY_THING_UID);
1314 updateThing(editBuilder.withProperties(newProperties).build());