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.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
26 import java.util.Objects;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
30 import java.util.concurrent.Future;
31 import java.util.concurrent.TimeUnit;
32 import java.util.stream.Collectors;
33 import java.util.stream.Stream;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.binding.hue.internal.action.DynamicsActions;
38 import org.openhab.binding.hue.internal.config.Clip2ThingConfig;
39 import org.openhab.binding.hue.internal.dto.clip2.Alerts;
40 import org.openhab.binding.hue.internal.dto.clip2.ColorXy;
41 import org.openhab.binding.hue.internal.dto.clip2.Dimming;
42 import org.openhab.binding.hue.internal.dto.clip2.Effects;
43 import org.openhab.binding.hue.internal.dto.clip2.Gamut2;
44 import org.openhab.binding.hue.internal.dto.clip2.MetaData;
45 import org.openhab.binding.hue.internal.dto.clip2.MirekSchema;
46 import org.openhab.binding.hue.internal.dto.clip2.ProductData;
47 import org.openhab.binding.hue.internal.dto.clip2.Resource;
48 import org.openhab.binding.hue.internal.dto.clip2.ResourceReference;
49 import org.openhab.binding.hue.internal.dto.clip2.Resources;
50 import org.openhab.binding.hue.internal.dto.clip2.TimedEffects;
51 import org.openhab.binding.hue.internal.dto.clip2.enums.ActionType;
52 import org.openhab.binding.hue.internal.dto.clip2.enums.EffectType;
53 import org.openhab.binding.hue.internal.dto.clip2.enums.ResourceType;
54 import org.openhab.binding.hue.internal.dto.clip2.enums.SceneRecallAction;
55 import org.openhab.binding.hue.internal.dto.clip2.enums.SmartSceneRecallAction;
56 import org.openhab.binding.hue.internal.dto.clip2.enums.ZigbeeStatus;
57 import org.openhab.binding.hue.internal.dto.clip2.helper.Setters;
58 import org.openhab.binding.hue.internal.exceptions.ApiException;
59 import org.openhab.binding.hue.internal.exceptions.AssetNotLoadedException;
60 import org.openhab.core.i18n.TimeZoneProvider;
61 import org.openhab.core.library.types.DateTimeType;
62 import org.openhab.core.library.types.DecimalType;
63 import org.openhab.core.library.types.HSBType;
64 import org.openhab.core.library.types.IncreaseDecreaseType;
65 import org.openhab.core.library.types.OnOffType;
66 import org.openhab.core.library.types.PercentType;
67 import org.openhab.core.library.types.QuantityType;
68 import org.openhab.core.library.types.StringType;
69 import org.openhab.core.library.unit.MetricPrefix;
70 import org.openhab.core.library.unit.Units;
71 import org.openhab.core.thing.Bridge;
72 import org.openhab.core.thing.Channel;
73 import org.openhab.core.thing.ChannelUID;
74 import org.openhab.core.thing.Thing;
75 import org.openhab.core.thing.ThingRegistry;
76 import org.openhab.core.thing.ThingStatus;
77 import org.openhab.core.thing.ThingStatusDetail;
78 import org.openhab.core.thing.ThingTypeUID;
79 import org.openhab.core.thing.ThingUID;
80 import org.openhab.core.thing.binding.BaseThingHandler;
81 import org.openhab.core.thing.binding.BridgeHandler;
82 import org.openhab.core.thing.binding.ThingHandlerService;
83 import org.openhab.core.thing.binding.builder.ThingBuilder;
84 import org.openhab.core.thing.link.ItemChannelLink;
85 import org.openhab.core.thing.link.ItemChannelLinkRegistry;
86 import org.openhab.core.types.Command;
87 import org.openhab.core.types.RefreshType;
88 import org.openhab.core.types.State;
89 import org.openhab.core.types.StateOption;
90 import org.openhab.core.types.UnDefType;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
95 * Handler for things based on CLIP 2 'device', 'room', or 'zone resources.
97 * @author Andrew Fiddian-Green - Initial contribution.
100 public class Clip2ThingHandler extends BaseThingHandler {
102 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DEVICE, THING_TYPE_ROOM,
105 private static final Set<ResourceType> SUPPORTED_SCENE_TYPES = Set.of(ResourceType.SCENE, ResourceType.SMART_SCENE);
107 private static final Duration DYNAMICS_ACTIVE_WINDOW = Duration.ofSeconds(10);
109 private static final String LK_WISER_DIMMER_MODEL_ID = "LK Dimmer";
111 private final Logger logger = LoggerFactory.getLogger(Clip2ThingHandler.class);
114 * A map of service Resources whose state contributes to the overall state of this thing. It is a map between the
115 * resource ID (string) and a Resource object containing the last known state. e.g. a DEVICE thing may support a
116 * LIGHT service whose Resource contributes to its overall state, or a ROOM or ZONE thing may support a
117 * GROUPED_LIGHT service whose Resource contributes to the its overall state.
119 private final Map<String, Resource> serviceContributorsCache = new ConcurrentHashMap<>();
122 * A map of Resource IDs which are targets for commands to be sent. It is a map between the type of command
123 * (ResourcesType) and the resource ID to which the command shall be sent. e.g. a LIGHT 'on' command shall be sent
124 * to the respective LIGHT resource ID.
126 private final Map<ResourceType, String> commandResourceIds = new ConcurrentHashMap<>();
129 * Button devices contain one or more physical buttons, each of which is represented by a BUTTON Resource with its
130 * own unique resource ID, and a respective controlId that indicates which button it is in the device. e.g. a dimmer
131 * pad has four buttons (controlId's 1..4) each represented by a BUTTON Resource with a unique resource ID. This is
132 * a map between the resource ID and its respective controlId.
134 private final Map<String, Integer> controlIds = new ConcurrentHashMap<>();
137 * The set of channel IDs that are supported by this thing. e.g. an on/off light may support 'switch' and
138 * 'zigbeeStatus' channels, whereas a complex light may support 'switch', 'brightness', 'color', 'color temperature'
139 * and 'zigbeeStatus' channels.
141 private final Set<String> supportedChannelIdSet = new HashSet<>();
144 * A map of scene IDs versus scene Resources for the scenes that contribute to and command this thing. It is a map
145 * between the resource ID (string) and a Resource object containing the scene's last known state.
147 private final Map<String, Resource> sceneContributorsCache = new ConcurrentHashMap<>();
150 * A map of scene names versus scene Resources for the scenes that contribute to and command this thing. e.g. a
151 * command for a scene named 'Energize' shall be sent to the respective SCENE resource ID.
153 private final Map<String, Resource> sceneResourceEntries = new ConcurrentHashMap<>();
156 * A list of API v1 thing channel UIDs that are linked to items. It is used in the process of replicating the
157 * Item/Channel links from a legacy v1 thing to this API v2 thing.
159 private final List<ChannelUID> legacyLinkedChannelUIDs = new CopyOnWriteArrayList<>();
161 private final ThingRegistry thingRegistry;
162 private final ItemChannelLinkRegistry itemChannelLinkRegistry;
163 private final Clip2StateDescriptionProvider stateDescriptionProvider;
164 private final TimeZoneProvider timeZoneProvider;
166 private String resourceId = "?";
167 private Resource thisResource;
168 private Duration dynamicsDuration = Duration.ZERO;
169 private Instant dynamicsExpireTime = Instant.MIN;
170 private Instant buttonGroupLastUpdated = Instant.MIN;
172 private boolean disposing;
173 private boolean hasConnectivityIssue;
174 private boolean updateSceneContributorsDone;
175 private boolean updateLightPropertiesDone;
176 private boolean updatePropertiesDone;
177 private boolean updateDependenciesDone;
178 private boolean applyOffTransitionWorkaround;
180 private @Nullable Future<?> alertResetTask;
181 private @Nullable Future<?> dynamicsResetTask;
182 private @Nullable Future<?> updateDependenciesTask;
183 private @Nullable Future<?> updateServiceContributorsTask;
185 public Clip2ThingHandler(Thing thing, Clip2StateDescriptionProvider stateDescriptionProvider,
186 TimeZoneProvider timeZoneProvider, ThingRegistry thingRegistry,
187 ItemChannelLinkRegistry itemChannelLinkRegistry) {
190 ThingTypeUID thingTypeUID = thing.getThingTypeUID();
191 if (THING_TYPE_DEVICE.equals(thingTypeUID)) {
192 thisResource = new Resource(ResourceType.DEVICE);
193 } else if (THING_TYPE_ROOM.equals(thingTypeUID)) {
194 thisResource = new Resource(ResourceType.ROOM);
195 } else if (THING_TYPE_ZONE.equals(thingTypeUID)) {
196 thisResource = new Resource(ResourceType.ZONE);
198 throw new IllegalArgumentException("Wrong thing type " + thingTypeUID.getAsString());
201 this.thingRegistry = thingRegistry;
202 this.itemChannelLinkRegistry = itemChannelLinkRegistry;
203 this.stateDescriptionProvider = stateDescriptionProvider;
204 this.timeZoneProvider = timeZoneProvider;
208 * Add a channel ID to the supportedChannelIdSet set. If the channel supports dynamics (timed transitions) then add
209 * the respective channel as well.
211 * @param channelId the channel ID to add.
213 private void addSupportedChannel(String channelId) {
214 if (!disposing && !updateDependenciesDone) {
215 synchronized (supportedChannelIdSet) {
216 logger.debug("{} -> addSupportedChannel() '{}' added to supported channel set", resourceId, channelId);
217 supportedChannelIdSet.add(channelId);
218 if (DYNAMIC_CHANNELS.contains(channelId)) {
219 clearDynamicsChannel();
226 * Cancel the given task.
228 * @param cancelTask the task to be cancelled (may be null)
229 * @param mayInterrupt allows cancel() to interrupt the thread.
231 private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
232 if (Objects.nonNull(cancelTask)) {
233 cancelTask.cancel(mayInterrupt);
238 * Clear the dynamics channel parameters.
240 private void clearDynamicsChannel() {
241 dynamicsExpireTime = Instant.MIN;
242 dynamicsDuration = Duration.ZERO;
243 updateState(CHANNEL_2_DYNAMICS, new QuantityType<>(0, MetricPrefix.MILLI(Units.SECOND)), true);
247 public void dispose() {
248 logger.debug("{} -> dispose()", resourceId);
250 cancelTask(alertResetTask, true);
251 cancelTask(dynamicsResetTask, true);
252 cancelTask(updateDependenciesTask, true);
253 cancelTask(updateServiceContributorsTask, true);
254 alertResetTask = null;
255 dynamicsResetTask = null;
256 updateDependenciesTask = null;
257 updateServiceContributorsTask = null;
258 legacyLinkedChannelUIDs.clear();
259 sceneContributorsCache.clear();
260 sceneResourceEntries.clear();
261 supportedChannelIdSet.clear();
262 commandResourceIds.clear();
263 serviceContributorsCache.clear();
268 * Get the bridge handler.
270 * @throws AssetNotLoadedException if the handler does not exist.
272 private Clip2BridgeHandler getBridgeHandler() throws AssetNotLoadedException {
273 Bridge bridge = getBridge();
274 if (Objects.nonNull(bridge)) {
275 BridgeHandler handler = bridge.getHandler();
276 if (handler instanceof Clip2BridgeHandler) {
277 return (Clip2BridgeHandler) handler;
280 throw new AssetNotLoadedException("Bridge handler missing");
284 * Do a double lookup to get the cached resource that matches the given ResourceType.
286 * @param resourceType the type to search for.
287 * @return the Resource, or null if not found.
289 private @Nullable Resource getCachedResource(ResourceType resourceType) {
290 String commandResourceId = commandResourceIds.get(resourceType);
291 return Objects.nonNull(commandResourceId) ? serviceContributorsCache.get(commandResourceId) : null;
295 * Return a ResourceReference to this handler's resource.
297 * @return a ResourceReference instance.
299 public ResourceReference getResourceReference() {
300 return new ResourceReference().setId(resourceId).setType(thisResource.getType());
304 * Register the 'DynamicsAction' service.
307 public Collection<Class<? extends ThingHandlerService>> getServices() {
308 return Set.of(DynamicsActions.class);
312 public void handleCommand(ChannelUID channelUID, Command commandParam) {
313 if (RefreshType.REFRESH.equals(commandParam)) {
314 if (thing.getStatus() == ThingStatus.ONLINE) {
315 refreshAllChannels();
320 Channel channel = thing.getChannel(channelUID);
321 if (channel == null) {
322 if (logger.isDebugEnabled()) {
323 logger.debug("{} -> handleCommand() channelUID:{} does not exist", resourceId, channelUID);
326 logger.warn("Command received for channel '{}' which is not in thing '{}'.", channelUID,
332 ResourceType lightResourceType = thisResource.getType() == ResourceType.DEVICE ? ResourceType.LIGHT
333 : ResourceType.GROUPED_LIGHT;
335 Resource putResource = null;
336 String putResourceId = null;
337 Command command = commandParam;
338 String channelId = channelUID.getId();
339 Resource cache = getCachedResource(lightResourceType);
342 case CHANNEL_2_ALERT:
343 putResource = Setters.setAlert(new Resource(lightResourceType), command, cache);
344 cancelTask(alertResetTask, false);
345 alertResetTask = scheduler.schedule(
346 () -> updateState(channelUID, new StringType(ActionType.NO_ACTION.name())), 10,
350 case CHANNEL_2_EFFECT:
351 putResource = Setters.setEffect(new Resource(lightResourceType), command, cache).setOnOff(OnOffType.ON);
354 case CHANNEL_2_COLOR_TEMP_PERCENT:
355 if (command instanceof IncreaseDecreaseType) {
356 if (Objects.nonNull(cache)) {
357 State current = cache.getColorTemperaturePercentState();
358 if (current instanceof PercentType) {
359 int sign = IncreaseDecreaseType.INCREASE == command ? 1 : -1;
360 int percent = ((PercentType) current).intValue() + (sign * (int) Resource.PERCENT_DELTA);
361 command = new PercentType(Math.min(100, Math.max(0, percent)));
364 } else if (command instanceof OnOffType) {
365 command = OnOffType.OFF == command ? PercentType.ZERO : PercentType.HUNDRED;
367 putResource = Setters.setColorTemperaturePercent(new Resource(lightResourceType), command, cache);
370 case CHANNEL_2_COLOR_TEMP_ABSOLUTE:
371 putResource = Setters.setColorTemperatureAbsolute(new Resource(lightResourceType), command, cache);
374 case CHANNEL_2_COLOR:
375 putResource = new Resource(lightResourceType);
376 if (command instanceof HSBType) {
377 HSBType color = ((HSBType) command);
378 putResource = Setters.setColorXy(putResource, color, cache);
379 command = color.getBrightness();
381 // NB fall through for handling of brightness and switch related commands !!
383 case CHANNEL_2_BRIGHTNESS:
384 putResource = Objects.nonNull(putResource) ? putResource : new Resource(lightResourceType);
385 if (command instanceof IncreaseDecreaseType) {
386 if (Objects.nonNull(cache)) {
387 State current = cache.getBrightnessState();
388 if (current instanceof PercentType) {
389 int sign = IncreaseDecreaseType.INCREASE == command ? 1 : -1;
390 double percent = ((PercentType) current).doubleValue() + (sign * Resource.PERCENT_DELTA);
391 command = new PercentType(new BigDecimal(Math.min(100f, Math.max(0f, percent)),
392 Resource.PERCENT_MATH_CONTEXT));
396 if (command instanceof PercentType) {
397 PercentType brightness = (PercentType) command;
398 putResource = Setters.setDimming(putResource, brightness, cache);
399 Double minDimLevel = Objects.nonNull(cache) ? cache.getMinimumDimmingLevel() : null;
400 minDimLevel = Objects.nonNull(minDimLevel) ? minDimLevel : Dimming.DEFAULT_MINIMUM_DIMMIMG_LEVEL;
401 command = OnOffType.from(brightness.doubleValue() >= minDimLevel);
403 // NB fall through for handling of switch related commands !!
405 case CHANNEL_2_SWITCH:
406 putResource = Objects.nonNull(putResource) ? putResource : new Resource(lightResourceType);
407 putResource.setOnOff(command);
408 applyDeviceSpecificWorkArounds(command, putResource);
411 case CHANNEL_2_COLOR_XY_ONLY:
412 putResource = Setters.setColorXy(new Resource(lightResourceType), command, cache);
415 case CHANNEL_2_DIMMING_ONLY:
416 putResource = Setters.setDimming(new Resource(lightResourceType), command, cache);
419 case CHANNEL_2_ON_OFF_ONLY:
420 putResource = new Resource(lightResourceType).setOnOff(command);
421 applyDeviceSpecificWorkArounds(command, putResource);
424 case CHANNEL_2_TEMPERATURE_ENABLED:
425 putResource = new Resource(ResourceType.TEMPERATURE).setEnabled(command);
428 case CHANNEL_2_MOTION_ENABLED:
429 putResource = new Resource(ResourceType.MOTION).setEnabled(command);
432 case CHANNEL_2_LIGHT_LEVEL_ENABLED:
433 putResource = new Resource(ResourceType.LIGHT_LEVEL).setEnabled(command);
436 case CHANNEL_2_SECURITY_CONTACT_ENABLED:
437 putResource = new Resource(ResourceType.CONTACT).setEnabled(command);
440 case CHANNEL_2_SCENE:
441 if (command instanceof StringType) {
442 Resource scene = sceneResourceEntries.get(((StringType) command).toString());
443 if (Objects.nonNull(scene)) {
444 ResourceType putResourceType = scene.getType();
445 putResource = new Resource(putResourceType);
446 switch (putResourceType) {
448 putResource.setRecallAction(SceneRecallAction.ACTIVE);
451 putResource.setRecallAction(SmartSceneRecallAction.ACTIVATE);
454 logger.debug("{} -> handleCommand() type '{}' is not a supported scene type",
455 resourceId, putResourceType);
458 putResourceId = scene.getId();
463 case CHANNEL_2_DYNAMICS:
464 Duration clearAfter = Duration.ZERO;
465 if (command instanceof QuantityType<?>) {
466 QuantityType<?> durationMs = ((QuantityType<?>) command).toUnit(MetricPrefix.MILLI(Units.SECOND));
467 if (Objects.nonNull(durationMs) && durationMs.longValue() > 0) {
468 Duration duration = Duration.ofMillis(durationMs.longValue());
469 dynamicsDuration = duration;
470 dynamicsExpireTime = Instant.now().plus(DYNAMICS_ACTIVE_WINDOW);
471 clearAfter = DYNAMICS_ACTIVE_WINDOW;
472 logger.debug("{} -> handleCommand() dynamics setting {} valid for {}", resourceId, duration,
476 cancelTask(dynamicsResetTask, false);
477 dynamicsResetTask = scheduler.schedule(() -> clearDynamicsChannel(), clearAfter.toMillis(),
478 TimeUnit.MILLISECONDS);
482 if (logger.isDebugEnabled()) {
483 logger.debug("{} -> handleCommand() channelUID:{} unknown", resourceId, channelUID);
485 logger.warn("Command received for unknown channel '{}'.", channelUID);
490 if (putResource == null) {
491 if (logger.isDebugEnabled()) {
492 logger.debug("{} -> handleCommand() command:{} not supported on channelUID:{}", resourceId, command,
495 logger.warn("Command '{}' is not supported on channel '{}'.", command, channelUID);
500 putResourceId = Objects.nonNull(putResourceId) ? putResourceId : commandResourceIds.get(putResource.getType());
501 if (putResourceId == null) {
502 if (logger.isDebugEnabled()) {
504 "{} -> handleCommand() channelUID:{}, command:{}, putResourceType:{} => missing resource ID",
505 resourceId, channelUID, command, putResource.getType());
507 logger.warn("Command '{}' for channel '{}' cannot be processed by thing '{}'.", command, channelUID,
513 if (DYNAMIC_CHANNELS.contains(channelId)) {
514 if (Instant.now().isBefore(dynamicsExpireTime) && !dynamicsDuration.isZero()
515 && !dynamicsDuration.isNegative()) {
516 if (ResourceType.SCENE == putResource.getType()) {
517 putResource.setRecallDuration(dynamicsDuration);
518 } else if (CHANNEL_2_EFFECT == channelId) {
519 putResource.setTimedEffectsDuration(dynamicsDuration);
521 putResource.setDynamicsDuration(dynamicsDuration);
526 putResource.setId(putResourceId);
527 logger.debug("{} -> handleCommand() put resource {}", resourceId, putResource);
530 Resources resources = getBridgeHandler().putResource(putResource);
531 if (resources.hasErrors()) {
532 logger.info("Command '{}' for thing '{}', channel '{}' succeeded with errors: {}", command,
533 thing.getUID(), channelUID, String.join("; ", resources.getErrors()));
535 } catch (ApiException | AssetNotLoadedException e) {
536 if (logger.isDebugEnabled()) {
537 logger.debug("{} -> handleCommand() error {}", resourceId, e.getMessage(), e);
539 logger.warn("Command '{}' for thing '{}', channel '{}' failed with error '{}'.", command,
540 thing.getUID(), channelUID, e.getMessage());
542 } catch (InterruptedException e) {
546 private void refreshAllChannels() {
547 if (!updateDependenciesDone) {
550 cancelTask(updateServiceContributorsTask, false);
551 updateServiceContributorsTask = scheduler.schedule(() -> {
553 updateServiceContributors();
554 } catch (ApiException | AssetNotLoadedException e) {
555 logger.debug("{} -> handleCommand() error {}", resourceId, e.getMessage(), e);
556 } catch (InterruptedException e) {
558 }, 3, TimeUnit.SECONDS);
562 * Apply device specific work-arounds needed for given command.
564 * @param command the handled command.
565 * @param putResource the resource that will be adjusted if needed.
567 private void applyDeviceSpecificWorkArounds(Command command, Resource putResource) {
568 if (command == OnOffType.OFF && applyOffTransitionWorkaround) {
569 putResource.setDynamicsDuration(dynamicsDuration);
574 * Handle a 'dynamics' command for the given channel ID for the given dynamics duration.
576 * @param channelId the ID of the target channel.
577 * @param command the new target state.
578 * @param duration the transition duration.
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);
592 logger.warn("Dynamics command '{}' for thing '{}', channel '{}' and duration'{}' failed.", command,
593 thing.getUID(), channelId, duration);
597 public void initialize() {
598 Clip2ThingConfig config = getConfigAs(Clip2ThingConfig.class);
600 String resourceId = config.resourceId;
601 if (resourceId.isBlank()) {
602 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
603 "@text/offline.api2.conf-error.resource-id-bad");
606 thisResource.setId(resourceId);
607 this.resourceId = resourceId;
608 logger.debug("{} -> initialize()", resourceId);
610 updateThingFromLegacy();
611 updateStatus(ThingStatus.UNKNOWN);
613 dynamicsDuration = Duration.ZERO;
614 dynamicsExpireTime = Instant.MIN;
617 hasConnectivityIssue = false;
618 updatePropertiesDone = false;
619 updateDependenciesDone = false;
620 updateLightPropertiesDone = false;
621 updateSceneContributorsDone = false;
623 Bridge bridge = getBridge();
624 if (Objects.nonNull(bridge)) {
625 BridgeHandler bridgeHandler = bridge.getHandler();
626 if (bridgeHandler instanceof Clip2BridgeHandler) {
627 ((Clip2BridgeHandler) bridgeHandler).childInitialized();
633 * Update the channel state depending on a new resource sent from the bridge.
635 * @param resource a Resource object containing the new state.
637 public void onResource(Resource resource) {
639 boolean resourceConsumed = false;
640 String incomingResourceId = resource.getId();
641 if (resourceId.equals(incomingResourceId)) {
642 if (resource.hasFullState()) {
643 thisResource = resource;
644 if (!updatePropertiesDone) {
645 updateProperties(resource);
646 resourceConsumed = updatePropertiesDone;
649 if (!updateDependenciesDone) {
650 resourceConsumed = true;
651 cancelTask(updateDependenciesTask, false);
652 updateDependenciesTask = scheduler.submit(() -> updateDependencies());
654 } else if (SUPPORTED_SCENE_TYPES.contains(resource.getType())) {
655 Resource cachedScene = sceneContributorsCache.get(incomingResourceId);
656 if (Objects.nonNull(cachedScene)) {
657 Setters.setResource(resource, cachedScene);
658 resourceConsumed = updateChannels(resource);
659 sceneContributorsCache.put(incomingResourceId, resource);
662 Resource cachedService = serviceContributorsCache.get(incomingResourceId);
663 if (Objects.nonNull(cachedService)) {
664 Setters.setResource(resource, cachedService);
665 resourceConsumed = updateChannels(resource);
666 serviceContributorsCache.put(incomingResourceId, resource);
667 if (ResourceType.LIGHT == resource.getType() && !updateLightPropertiesDone) {
668 updateLightProperties(resource);
672 if (resourceConsumed) {
673 logger.debug("{} -> onResource() consumed resource {}", resourceId, resource);
679 * Update the thing internal state depending on a full list of resources sent from the bridge. If the resourceType
680 * is SCENE then call updateScenes(), otherwise if the resource refers to this thing, consume it via onResource() as
681 * any other resource, or else if the resourceType nevertheless matches the thing type, set the thing state offline.
683 * @param resourceType the type of the resources in the list.
684 * @param fullResources the full list of resources of the given type.
686 public void onResourcesList(ResourceType resourceType, List<Resource> fullResources) {
687 if (resourceType == ResourceType.SCENE) {
688 updateSceneContributors(fullResources);
690 fullResources.stream().filter(r -> resourceId.equals(r.getId())).findAny()
691 .ifPresentOrElse(r -> onResource(r), () -> {
692 if (resourceType == thisResource.getType()) {
693 logger.debug("{} -> onResourcesList() configuration error: unknown resourceId", resourceId);
694 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
695 "@text/offline.api2.conf-error.resource-id-bad");
702 * Process the incoming Resource to initialize the alert channel.
704 * @param resource a Resource possibly with an Alerts element.
706 private void updateAlertChannel(Resource resource) {
707 Alerts alerts = resource.getAlerts();
708 if (Objects.nonNull(alerts)) {
709 List<StateOption> stateOptions = alerts.getActionValues().stream().map(action -> action.name())
710 .map(actionId -> new StateOption(actionId, actionId)).collect(Collectors.toList());
711 if (!stateOptions.isEmpty()) {
712 stateDescriptionProvider.setStateOptions(new ChannelUID(thing.getUID(), CHANNEL_2_ALERT), stateOptions);
713 logger.debug("{} -> updateAlerts() found {} associated alerts", resourceId, stateOptions.size());
719 * If this v2 thing has a matching v1 legacy thing in the system, then for each channel in the v1 thing that
720 * corresponds to an equivalent channel in this v2 thing, and for all items that are linked to the v1 channel,
721 * create a new channel/item link between that item and the respective v2 channel in this thing.
723 private void updateChannelItemLinksFromLegacy() {
725 legacyLinkedChannelUIDs.forEach(legacyLinkedChannelUID -> {
726 String targetChannelId = REPLICATE_CHANNEL_ID_MAP.get(legacyLinkedChannelUID.getId());
727 if (Objects.nonNull(targetChannelId)) {
728 Channel targetChannel = thing.getChannel(targetChannelId);
729 if (Objects.nonNull(targetChannel)) {
730 ChannelUID uid = targetChannel.getUID();
731 itemChannelLinkRegistry.getLinkedItems(legacyLinkedChannelUID).forEach(linkedItem -> {
732 String item = linkedItem.getName();
733 if (!itemChannelLinkRegistry.isLinked(item, uid)) {
734 if (logger.isDebugEnabled()) {
736 "{} -> updateChannelItemLinksFromLegacy() item:{} linked to channel:{}",
737 resourceId, item, uid);
739 logger.info("Item '{}' linked to thing '{}' channel '{}'", item, thing.getUID(),
742 itemChannelLinkRegistry.add(new ItemChannelLink(item, uid));
748 legacyLinkedChannelUIDs.clear();
753 * Set the active list of channels by removing any that had initially been created by the thing XML declaration, but
754 * which in fact did not have data returned from the bridge i.e. channels which are not in the supportedChannelIdSet
756 * Also warn if there are channels in the supportedChannelIdSet set which are not in the thing.
758 * Adjusts the channel list so that only the highest level channel is available in the normal channel list. If a
759 * light supports the color channel, then it's brightness and switch can be commanded via the 'B' part of the HSB
760 * channel value. And if it supports the brightness channel the switch can be controlled via the brightness. So we
761 * can remove these lower level channels from the normal channel list.
763 * For more advanced applications, it is necessary to orthogonally command the color xy parameter, dimming
764 * parameter, and/or on/off parameter independently. So we add corresponding advanced level 'CHANNEL_2_BLAH_ONLY'
765 * channels for that purpose. Since they are advanced level, normal users should normally not be confused by them,
766 * yet advanced users can use them nevertheless.
768 private void updateChannelList() {
770 synchronized (supportedChannelIdSet) {
771 logger.debug("{} -> updateChannelList()", resourceId);
773 if (supportedChannelIdSet.contains(CHANNEL_2_COLOR)) {
774 supportedChannelIdSet.add(CHANNEL_2_COLOR_XY_ONLY);
776 supportedChannelIdSet.remove(CHANNEL_2_BRIGHTNESS);
777 supportedChannelIdSet.add(CHANNEL_2_DIMMING_ONLY);
779 supportedChannelIdSet.remove(CHANNEL_2_SWITCH);
780 supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
782 if (supportedChannelIdSet.contains(CHANNEL_2_BRIGHTNESS)) {
783 supportedChannelIdSet.add(CHANNEL_2_DIMMING_ONLY);
785 supportedChannelIdSet.remove(CHANNEL_2_SWITCH);
786 supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
788 if (supportedChannelIdSet.contains(CHANNEL_2_SWITCH)) {
789 supportedChannelIdSet.add(CHANNEL_2_ON_OFF_ONLY);
793 * This binding creates its dynamic list of channels by a 'subtractive' method i.e. the full set of
794 * channels is initially created from the thing type xml, and then for any channels where UndfType.NULL
795 * data is returned, the respective channel is removed from the full list. However in seldom cases
796 * UndfType.NULL may wrongly be returned, so we should log a warning here just in case.
798 if (logger.isDebugEnabled()) {
799 supportedChannelIdSet.stream().filter(channelId -> Objects.isNull(thing.getChannel(channelId)))
800 .forEach(channelId -> logger.debug(
801 "{} -> updateChannelList() required channel '{}' missing", resourceId, channelId));
803 supportedChannelIdSet.stream().filter(channelId -> Objects.isNull(thing.getChannel(channelId)))
804 .forEach(channelId -> logger.warn(
805 "Thing '{}' is missing required channel '{}'. Please recreate the thing!",
806 thing.getUID(), channelId));
809 // get list of unused channels
810 List<Channel> unusedChannels = thing.getChannels().stream()
811 .filter(channel -> !supportedChannelIdSet.contains(channel.getUID().getId()))
812 .collect(Collectors.toList());
814 // remove any unused channels
815 if (!unusedChannels.isEmpty()) {
816 if (logger.isDebugEnabled()) {
817 unusedChannels.stream().map(channel -> channel.getUID().getId())
818 .forEach(channelId -> logger.debug(
819 "{} -> updateChannelList() removing unused channel '{}'", resourceId,
822 updateThing(editThing().withoutChannels(unusedChannels).build());
829 * Update the state of the existing channels.
831 * @param resource the Resource containing the new channel state.
832 * @return true if the channel was found and updated.
834 private boolean updateChannels(Resource resource) {
835 logger.debug("{} -> updateChannels() from resource {}", resourceId, resource);
836 boolean fullUpdate = resource.hasFullState();
837 switch (resource.getType()) {
840 addSupportedChannel(CHANNEL_2_BUTTON_LAST_EVENT);
841 addSupportedChannel(CHANNEL_2_BUTTON_LAST_UPDATED);
842 controlIds.put(resource.getId(), resource.getControlId());
844 State buttonState = resource.getButtonEventState(controlIds);
845 updateState(CHANNEL_2_BUTTON_LAST_EVENT, buttonState, fullUpdate);
847 // Update channel from timestamp if last button pressed.
848 State buttonLastUpdatedState = resource.getButtonLastUpdatedState(timeZoneProvider.getTimeZone());
849 if (buttonLastUpdatedState instanceof DateTimeType) {
850 Instant buttonLastUpdatedInstant = ((DateTimeType) buttonLastUpdatedState).getInstant();
851 if (buttonLastUpdatedInstant.isAfter(buttonGroupLastUpdated)) {
852 updateState(CHANNEL_2_BUTTON_LAST_UPDATED, buttonLastUpdatedState, fullUpdate);
853 buttonGroupLastUpdated = buttonLastUpdatedInstant;
855 } else if (Instant.MIN.equals(buttonGroupLastUpdated)) {
856 updateState(CHANNEL_2_BUTTON_LAST_UPDATED, buttonLastUpdatedState, fullUpdate);
861 updateState(CHANNEL_2_BATTERY_LEVEL, resource.getBatteryLevelState(), fullUpdate);
862 updateState(CHANNEL_2_BATTERY_LOW, resource.getBatteryLowState(), fullUpdate);
867 updateEffectChannel(resource);
869 updateState(CHANNEL_2_COLOR_TEMP_PERCENT, resource.getColorTemperaturePercentState(), fullUpdate);
870 updateState(CHANNEL_2_COLOR_TEMP_ABSOLUTE, resource.getColorTemperatureAbsoluteState(), fullUpdate);
871 updateState(CHANNEL_2_COLOR, resource.getColorState(), fullUpdate);
872 updateState(CHANNEL_2_COLOR_XY_ONLY, resource.getColorXyState(), fullUpdate);
873 updateState(CHANNEL_2_EFFECT, resource.getEffectState(), fullUpdate);
874 // fall through for dimming and on/off related channels
878 updateAlertChannel(resource);
880 updateState(CHANNEL_2_BRIGHTNESS, resource.getBrightnessState(), fullUpdate);
881 updateState(CHANNEL_2_DIMMING_ONLY, resource.getDimmingState(), fullUpdate);
882 updateState(CHANNEL_2_SWITCH, resource.getOnOffState(), fullUpdate);
883 updateState(CHANNEL_2_ON_OFF_ONLY, resource.getOnOffState(), fullUpdate);
884 updateState(CHANNEL_2_ALERT, resource.getAlertState(), fullUpdate);
888 updateState(CHANNEL_2_LIGHT_LEVEL, resource.getLightLevelState(), fullUpdate);
889 updateState(CHANNEL_2_LIGHT_LEVEL_LAST_UPDATED,
890 resource.getLightLevelLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
891 updateState(CHANNEL_2_LIGHT_LEVEL_ENABLED, resource.getEnabledState(), fullUpdate);
896 updateState(CHANNEL_2_MOTION, resource.getMotionState(), fullUpdate);
897 updateState(CHANNEL_2_MOTION_LAST_UPDATED,
898 resource.getMotionLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
899 updateState(CHANNEL_2_MOTION_ENABLED, resource.getEnabledState(), fullUpdate);
902 case RELATIVE_ROTARY:
904 addSupportedChannel(CHANNEL_2_ROTARY_STEPS);
905 addSupportedChannel(CHANNEL_2_ROTARY_STEPS_LAST_UPDATED);
907 updateState(CHANNEL_2_ROTARY_STEPS, resource.getRotaryStepsState(), fullUpdate);
909 updateState(CHANNEL_2_ROTARY_STEPS_LAST_UPDATED,
910 resource.getRotaryStepsLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
914 updateState(CHANNEL_2_TEMPERATURE, resource.getTemperatureState(), fullUpdate);
915 updateState(CHANNEL_2_TEMPERATURE_LAST_UPDATED,
916 resource.getTemperatureLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
917 updateState(CHANNEL_2_TEMPERATURE_ENABLED, resource.getEnabledState(), fullUpdate);
920 case ZIGBEE_CONNECTIVITY:
921 updateConnectivityState(resource);
925 updateState(CHANNEL_2_SCENE, resource.getSceneState(), fullUpdate);
929 updateState(CHANNEL_2_SECURITY_CONTACT, resource.getContactState(), fullUpdate);
930 updateState(CHANNEL_2_SECURITY_CONTACT_LAST_UPDATED,
931 resource.getContactLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
932 updateState(CHANNEL_2_SECURITY_CONTACT_ENABLED, resource.getEnabledState(), fullUpdate);
936 updateState(CHANNEL_2_SECURITY_TAMPER, resource.getTamperState(), fullUpdate);
937 updateState(CHANNEL_2_SECURITY_TAMPER_LAST_UPDATED,
938 resource.getTamperLastUpdatedState(timeZoneProvider.getTimeZone()), fullUpdate);
942 updateState(CHANNEL_2_SCENE, resource.getSmartSceneState(), fullUpdate);
948 if (thisResource.getType() == ResourceType.DEVICE) {
949 updateState(CHANNEL_2_LAST_UPDATED, new DateTimeType(), fullUpdate);
955 * Check the Zigbee connectivity and set the thing online status accordingly. If the thing is offline then set all
956 * its channel states to undefined, otherwise execute a refresh command to update channels to the latest current
959 * @param resource a Resource that potentially contains the Zigbee connectivity state.
961 private void updateConnectivityState(Resource resource) {
962 ZigbeeStatus zigbeeStatus = resource.getZigbeeStatus();
963 if (Objects.nonNull(zigbeeStatus)) {
964 logger.debug("{} -> updateConnectivityState() thingStatus:{}, zigbeeStatus:{}", resourceId,
965 thing.getStatus(), zigbeeStatus);
966 hasConnectivityIssue = zigbeeStatus != ZigbeeStatus.CONNECTED;
967 if (hasConnectivityIssue) {
968 if (thing.getStatusInfo().getStatusDetail() != ThingStatusDetail.COMMUNICATION_ERROR) {
969 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
970 "@text/offline.api2.comm-error.zigbee-connectivity-issue");
971 supportedChannelIdSet.forEach(channelId -> updateState(channelId, UnDefType.UNDEF));
973 } else if (thing.getStatus() != ThingStatus.ONLINE) {
974 updateStatus(ThingStatus.ONLINE);
975 refreshAllChannels();
981 * Get all resources needed for building the thing state. Build the forward / reverse contributor lookup maps. Set
982 * up the final list of channels in the thing.
984 private synchronized void updateDependencies() {
985 if (!disposing && !updateDependenciesDone) {
986 logger.debug("{} -> updateDependencies()", resourceId);
988 if (!updatePropertiesDone) {
989 logger.debug("{} -> updateDependencies() properties not initialized", resourceId);
992 if (!updateSceneContributorsDone && !updateSceneContributors()) {
993 logger.debug("{} -> updateDependencies() scenes not initialized", resourceId);
997 updateServiceContributors();
999 updateChannelItemLinksFromLegacy();
1000 if (!hasConnectivityIssue) {
1001 updateStatus(ThingStatus.ONLINE);
1003 updateDependenciesDone = true;
1004 } catch (ApiException e) {
1005 logger.debug("{} -> updateDependencies() {}", resourceId, e.getMessage(), e);
1006 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
1007 } catch (AssetNotLoadedException e) {
1008 logger.debug("{} -> updateDependencies() {}", resourceId, e.getMessage(), e);
1009 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
1010 "@text/offline.api2.conf-error.assets-not-loaded");
1011 } catch (InterruptedException e) {
1017 * Process the incoming Resource to initialize the fixed resp. timed effects channel.
1019 * @param resource a Resource possibly containing a fixed and/or timed effects element.
1021 public void updateEffectChannel(Resource resource) {
1022 Effects fixedEffects = resource.getFixedEffects();
1023 TimedEffects timedEffects = resource.getTimedEffects();
1024 List<StateOption> stateOptions = Stream
1025 .concat(Objects.nonNull(fixedEffects) ? fixedEffects.getStatusValues().stream() : Stream.empty(),
1026 Objects.nonNull(timedEffects) ? timedEffects.getStatusValues().stream() : Stream.empty())
1028 String effectName = EffectType.of(effect).name();
1029 return new StateOption(effectName, effectName);
1030 }).distinct().collect(Collectors.toList());
1031 if (!stateOptions.isEmpty()) {
1032 stateDescriptionProvider.setStateOptions(new ChannelUID(thing.getUID(), CHANNEL_2_EFFECT), stateOptions);
1033 logger.debug("{} -> updateEffects() found {} effects", resourceId, stateOptions.size());
1038 * Update the light properties.
1040 * @param resource a Resource object containing the property data.
1042 private synchronized void updateLightProperties(Resource resource) {
1043 if (!disposing && !updateLightPropertiesDone) {
1044 logger.debug("{} -> updateLightProperties()", resourceId);
1046 Dimming dimming = resource.getDimming();
1047 thing.setProperty(PROPERTY_DIMMING_RANGE, Objects.nonNull(dimming) ? dimming.toPropertyValue() : null);
1049 MirekSchema mirekSchema = resource.getMirekSchema();
1050 thing.setProperty(PROPERTY_COLOR_TEMP_RANGE,
1051 Objects.nonNull(mirekSchema) ? mirekSchema.toPropertyValue() : null);
1053 ColorXy colorXy = resource.getColorXy();
1054 Gamut2 gamut = Objects.nonNull(colorXy) ? colorXy.getGamut2() : null;
1055 thing.setProperty(PROPERTY_COLOR_GAMUT, Objects.nonNull(gamut) ? gamut.toPropertyValue() : null);
1057 updateLightPropertiesDone = true;
1062 * Initialize the lookup maps of resources that contribute to the thing state.
1064 private void updateLookups() {
1066 logger.debug("{} -> updateLookups()", resourceId);
1067 // get supported services
1068 List<ResourceReference> services = thisResource.getServiceReferences();
1070 // add supported services to contributorsCache
1071 serviceContributorsCache.clear();
1072 serviceContributorsCache.putAll(services.stream()
1073 .collect(Collectors.toMap(ResourceReference::getId, r -> new Resource(r.getType()))));
1075 // add supported services to commandResourceIds
1076 commandResourceIds.clear();
1077 commandResourceIds.putAll(services.stream() // use a 'mergeFunction' to prevent duplicates
1078 .collect(Collectors.toMap(ResourceReference::getType, ResourceReference::getId, (r1, r2) -> r1)));
1083 * Update the primary device properties.
1085 * @param resource a Resource object containing the property data.
1087 private synchronized void updateProperties(Resource resource) {
1088 if (!disposing && !updatePropertiesDone) {
1089 logger.debug("{} -> updateProperties()", resourceId);
1090 Map<String, String> properties = new HashMap<>(thing.getProperties());
1093 properties.put(PROPERTY_RESOURCE_TYPE, thisResource.getType().toString());
1094 properties.put(PROPERTY_RESOURCE_NAME, thisResource.getName());
1096 // owner information
1097 ResourceReference owner = thisResource.getOwner();
1098 if (Objects.nonNull(owner)) {
1099 String ownerId = owner.getId();
1100 if (Objects.nonNull(ownerId)) {
1101 properties.put(PROPERTY_OWNER, ownerId);
1103 ResourceType ownerType = owner.getType();
1104 properties.put(PROPERTY_OWNER_TYPE, ownerType.toString());
1108 MetaData metaData = thisResource.getMetaData();
1109 if (Objects.nonNull(metaData)) {
1110 properties.put(PROPERTY_RESOURCE_ARCHETYPE, metaData.getArchetype().toString());
1114 ProductData productData = thisResource.getProductData();
1115 if (Objects.nonNull(productData)) {
1116 String modelId = productData.getModelId();
1118 // standard properties
1119 properties.put(PROPERTY_RESOURCE_ID, resourceId);
1120 properties.put(Thing.PROPERTY_MODEL_ID, modelId);
1121 properties.put(Thing.PROPERTY_VENDOR, productData.getManufacturerName());
1122 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, productData.getSoftwareVersion());
1123 String hardwarePlatformType = productData.getHardwarePlatformType();
1124 if (Objects.nonNull(hardwarePlatformType)) {
1125 properties.put(Thing.PROPERTY_HARDWARE_VERSION, hardwarePlatformType);
1128 // hue specific properties
1129 properties.put(PROPERTY_PRODUCT_NAME, productData.getProductName());
1130 properties.put(PROPERTY_PRODUCT_ARCHETYPE, productData.getProductArchetype().toString());
1131 properties.put(PROPERTY_PRODUCT_CERTIFIED, productData.getCertified().toString());
1133 // Check device for needed work-arounds.
1134 if (LK_WISER_DIMMER_MODEL_ID.equals(modelId)) {
1135 // Apply transition time as a workaround for LK Wiser Dimmer firmware bug.
1136 // Additional details here: https://techblog.vindvejr.dk/?p=455
1137 applyOffTransitionWorkaround = true;
1138 logger.debug("{} -> enabling work-around for turning off LK Wiser Dimmer", resourceId);
1142 thing.setProperties(properties);
1143 updatePropertiesDone = true;
1148 * Execute an HTTP GET command to fetch the resources data for the referenced resource.
1150 * @param reference to the required resource.
1151 * @throws ApiException if a communication error occurred.
1152 * @throws AssetNotLoadedException if one of the assets is not loaded.
1153 * @throws InterruptedException
1155 private void updateResource(ResourceReference reference)
1156 throws ApiException, AssetNotLoadedException, InterruptedException {
1158 logger.debug("{} -> updateResource() from resource {}", resourceId, reference);
1159 getBridgeHandler().getResources(reference).getResources().stream()
1160 .forEach(resource -> onResource(resource));
1165 * Fetch the full list of normal resp. smart scenes from the bridge, and call
1166 * {@code updateSceneContributors(List<Resource> allScenes)}
1168 * @throws ApiException if a communication error occurred.
1169 * @throws AssetNotLoadedException if one of the assets is not loaded.
1170 * @throws InterruptedException
1172 public boolean updateSceneContributors() throws ApiException, AssetNotLoadedException, InterruptedException {
1173 if (!disposing && !updateSceneContributorsDone) {
1174 List<Resource> allScenes = new ArrayList<>();
1175 for (ResourceType type : SUPPORTED_SCENE_TYPES) {
1176 allScenes.addAll(getBridgeHandler().getResources(new ResourceReference().setType(type)).getResources());
1178 updateSceneContributors(allScenes);
1180 return updateSceneContributorsDone;
1184 * Process the incoming list of normal resp. smart scene resources to find those which contribute to this thing. And
1185 * if there are any, include a scene channel in the supported channel list, and populate its respective state
1188 * @param allScenes the full list of normal resp. smart scene resources.
1190 public synchronized boolean updateSceneContributors(List<Resource> allScenes) {
1191 if (!disposing && !updateSceneContributorsDone) {
1192 sceneContributorsCache.clear();
1193 sceneResourceEntries.clear();
1195 ResourceReference thisReference = getResourceReference();
1196 List<Resource> scenes = allScenes.stream().filter(s -> thisReference.equals(s.getGroup()))
1197 .collect(Collectors.toList());
1199 if (!scenes.isEmpty()) {
1200 sceneContributorsCache.putAll(scenes.stream().collect(Collectors.toMap(s -> s.getId(), s -> s)));
1201 sceneResourceEntries.putAll(scenes.stream().collect(Collectors.toMap(s -> s.getName(), s -> s)));
1203 State state = scenes.stream().filter(s -> s.getSceneActive().orElse(false)).map(s -> s.getSceneState())
1204 .findAny().orElse(UnDefType.UNDEF);
1206 updateState(CHANNEL_2_SCENE, state, true);
1208 stateDescriptionProvider.setStateOptions(new ChannelUID(thing.getUID(), CHANNEL_2_SCENE), scenes
1209 .stream().map(s -> s.getName()).map(n -> new StateOption(n, n)).collect(Collectors.toList()));
1211 logger.debug("{} -> updateSceneContributors() found {} normal resp. smart scenes", resourceId,
1214 updateSceneContributorsDone = true;
1216 return updateSceneContributorsDone;
1220 * Execute a series of HTTP GET commands to fetch the resource data for all service resources that contribute to the
1223 * @throws ApiException if a communication error occurred.
1224 * @throws AssetNotLoadedException if one of the assets is not loaded.
1225 * @throws InterruptedException
1227 private void updateServiceContributors() throws ApiException, AssetNotLoadedException, InterruptedException {
1229 logger.debug("{} -> updateServiceContributors() called for {} contributors", resourceId,
1230 serviceContributorsCache.size());
1231 ResourceReference reference = new ResourceReference();
1232 for (var entry : serviceContributorsCache.entrySet()) {
1233 updateResource(reference.setId(entry.getKey()).setType(entry.getValue().getType()));
1239 * Update the channel state, and if appropriate add the channel ID to the set of supportedChannelIds. Calls either
1240 * OH core updateState() or triggerChannel() methods depending on the channel kind.
1242 * Note: the particular 'UnDefType.UNDEF' value of the state argument is used to specially indicate the undefined
1243 * state, but yet that its channel shall nevertheless continue to be present in the thing.
1245 * @param channelID the id of the channel.
1246 * @param state the new state of the channel.
1247 * @param fullUpdate if true always update the channel, otherwise only update if state is not 'UNDEF'.
1249 private void updateState(String channelID, State state, boolean fullUpdate) {
1250 boolean isDefined = state != UnDefType.NULL;
1251 Channel channel = thing.getChannel(channelID);
1253 if ((fullUpdate || isDefined) && Objects.nonNull(channel)) {
1254 logger.debug("{} -> updateState() '{}' update with '{}' (fullUpdate:{}, isDefined:{})", resourceId,
1255 channelID, state, fullUpdate, isDefined);
1257 switch (channel.getKind()) {
1259 updateState(channelID, state);
1263 if (state instanceof DecimalType) {
1264 triggerChannel(channelID, String.valueOf(((DecimalType) state).intValue()));
1268 if (fullUpdate && isDefined) {
1269 addSupportedChannel(channelID);
1274 * Check if a PROPERTY_LEGACY_THING_UID value was set by the discovery process, and if so, clone the legacy thing's
1275 * settings into this thing.
1277 private void updateThingFromLegacy() {
1278 if (isInitialized()) {
1279 logger.warn("Cannot update thing '{}' from legacy thing since handler already initialized.",
1283 Map<String, String> properties = thing.getProperties();
1284 String legacyThingUID = properties.get(PROPERTY_LEGACY_THING_UID);
1285 if (Objects.nonNull(legacyThingUID)) {
1286 Thing legacyThing = thingRegistry.get(new ThingUID(legacyThingUID));
1287 if (Objects.nonNull(legacyThing)) {
1288 ThingBuilder editBuilder = editThing();
1290 String location = legacyThing.getLocation();
1291 if (Objects.nonNull(location) && !location.isBlank()) {
1292 editBuilder = editBuilder.withLocation(location);
1295 // save list of legacyLinkedChannelUIDs for use after channel list is initialised
1296 legacyLinkedChannelUIDs.clear();
1297 legacyLinkedChannelUIDs.addAll(legacyThing.getChannels().stream().map(Channel::getUID)
1298 .filter(uid -> REPLICATE_CHANNEL_ID_MAP.containsKey(uid.getId())
1299 && itemChannelLinkRegistry.isLinked(uid))
1300 .collect(Collectors.toList()));
1302 Map<String, String> newProperties = new HashMap<>(properties);
1303 newProperties.remove(PROPERTY_LEGACY_THING_UID);
1305 updateThing(editBuilder.withProperties(newProperties).build());