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.dto.clip2;
15 import java.math.BigDecimal;
16 import java.math.MathContext;
17 import java.math.RoundingMode;
18 import java.time.Duration;
19 import java.util.List;
21 import java.util.Objects;
22 import java.util.Optional;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.hue.internal.dto.clip2.enums.ActionType;
27 import org.openhab.binding.hue.internal.dto.clip2.enums.RecallAction;
28 import org.openhab.binding.hue.internal.dto.clip2.enums.ResourceType;
29 import org.openhab.binding.hue.internal.dto.clip2.enums.ZigbeeStatus;
30 import org.openhab.binding.hue.internal.exceptions.DTOPresentButEmptyException;
31 import org.openhab.core.library.types.DecimalType;
32 import org.openhab.core.library.types.HSBType;
33 import org.openhab.core.library.types.OnOffType;
34 import org.openhab.core.library.types.PercentType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.library.types.StringType;
37 import org.openhab.core.types.Command;
38 import org.openhab.core.types.State;
39 import org.openhab.core.types.UnDefType;
40 import org.openhab.core.util.ColorUtil;
41 import org.openhab.core.util.ColorUtil.Gamut;
43 import com.google.gson.JsonElement;
44 import com.google.gson.JsonObject;
45 import com.google.gson.annotations.SerializedName;
48 * Complete Resource information DTO for CLIP 2.
50 * Note: all fields are @Nullable because some cases do not (must not) use them.
52 * @author Andrew Fiddian-Green - Initial contribution
55 public class Resource {
57 public static final double PERCENT_DELTA = 30f;
58 public static final MathContext PERCENT_MATH_CONTEXT = new MathContext(4, RoundingMode.HALF_UP);
61 * The SSE event mechanism sends resources in a sparse (skeleton) format that only includes state fields whose
62 * values have changed. A sparse resource does not contain the full state of the resource. And the absence of any
63 * field from such a resource does not indicate that the field value is UNDEF, but rather that the value is the same
64 * as what it was previously set to by the last non-sparse resource.
66 private transient boolean hasSparseData;
68 private @Nullable String type;
69 private @Nullable String id;
70 private @Nullable @SerializedName("bridge_id") String bridgeId;
71 private @Nullable @SerializedName("id_v1") String idV1;
72 private @Nullable ResourceReference owner;
73 private @Nullable MetaData metadata;
74 private @Nullable @SerializedName("product_data") ProductData productData;
75 private @Nullable List<ResourceReference> services;
76 private @Nullable OnState on;
77 private @Nullable Dimming dimming;
78 private @Nullable @SerializedName("color_temperature") ColorTemperature colorTemperature;
79 private @Nullable ColorXy color;
80 private @Nullable Alerts alert;
81 private @Nullable Effects effects;
82 private @Nullable @SerializedName("timed_effects") TimedEffects timedEffects;
83 private @Nullable ResourceReference group;
84 private @Nullable List<ActionEntry> actions;
85 private @Nullable Recall recall;
86 private @Nullable Boolean enabled;
87 private @Nullable LightLevel light;
88 private @Nullable Button button;
89 private @Nullable Temperature temperature;
90 private @Nullable Motion motion;
91 private @Nullable @SerializedName("power_state") Power powerState;
92 private @Nullable @SerializedName("relative_rotary") RelativeRotary relativeRotary;
93 private @Nullable List<ResourceReference> children;
94 private @Nullable JsonElement status;
95 private @Nullable @SuppressWarnings("unused") Dynamics dynamics;
100 * @param resourceType
102 public Resource(@Nullable ResourceType resourceType) {
103 if (Objects.nonNull(resourceType)) {
104 setType(resourceType);
108 public @Nullable List<ActionEntry> getActions() {
112 public @Nullable Alerts getAlerts() {
116 public State getAlertState() {
117 Alerts alerts = this.alert;
118 if (Objects.nonNull(alerts)) {
119 if (!alerts.getActionValues().isEmpty()) {
120 ActionType alertType = alerts.getAction();
121 if (Objects.nonNull(alertType)) {
122 return new StringType(alertType.name());
124 return new StringType(ActionType.NO_ACTION.name());
127 return UnDefType.NULL;
130 public String getArchetype() {
131 MetaData metaData = getMetaData();
132 if (Objects.nonNull(metaData)) {
133 return metaData.getArchetype().toString();
135 return getType().toString();
138 public State getBatteryLevelState() {
139 Power powerState = this.powerState;
140 return Objects.nonNull(powerState) ? powerState.getBatteryLevelState() : UnDefType.NULL;
143 public State getBatteryLowState() {
144 Power powerState = this.powerState;
145 return Objects.nonNull(powerState) ? powerState.getBatteryLowState() : UnDefType.NULL;
148 public @Nullable String getBridgeId() {
149 String bridgeId = this.bridgeId;
150 return Objects.isNull(bridgeId) || bridgeId.isBlank() ? null : bridgeId;
154 * Get the brightness as a PercentType. If off the brightness is 0, otherwise use dimming value.
156 * @return a PercentType with the dimming state, or UNDEF, or NULL
158 public State getBrightnessState() {
159 Dimming dimming = this.dimming;
160 if (Objects.nonNull(dimming)) {
162 // if off the brightness is 0, otherwise it is dimming value
163 OnState on = this.on;
164 double brightness = Objects.nonNull(on) && !on.isOn() ? 0f
165 : Math.max(0f, Math.min(100f, dimming.getBrightness()));
166 return new PercentType(new BigDecimal(brightness, PERCENT_MATH_CONTEXT));
167 } catch (DTOPresentButEmptyException e) {
168 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
171 return UnDefType.NULL;
174 public @Nullable Button getButton() {
179 * Get the state corresponding to a button's last event value multiplied by the controlId found for it in the given
180 * controlIds map. States are decimal values formatted like '1002' where the first digit is the button's controlId
181 * and the last digit is the ordinal value of the button's last event.
183 * @param controlIds the map of control ids to be referenced.
186 public State getButtonEventState(Map<String, Integer> controlIds) {
187 Button button = this.button;
188 if (Objects.nonNull(button)) {
190 return new DecimalType(
191 (controlIds.getOrDefault(getId(), 0).intValue() * 1000) + button.getLastEvent().ordinal());
192 } catch (IllegalArgumentException e) {
196 return UnDefType.NULL;
199 public State getButtonLastEventState() {
200 Button button = this.button;
201 return Objects.nonNull(button) ? button.getLastEventState() : UnDefType.NULL;
204 public List<ResourceReference> getChildren() {
205 List<ResourceReference> children = this.children;
206 return Objects.nonNull(children) ? children : List.of();
210 * Get the color as an HSBType. This returns an HSB that is based on an amalgamation of the color xy, dimming, and
211 * on/off JSON elements. It takes its 'H' & 'S' parts from the 'ColorXy' JSON element, and its 'B' part from the
212 * on/off resp. dimming JSON elements. If off the B part is 0, otherwise it is the dimming element value. Note: this
213 * method is only to be used on cached state DTOs which already have a defined color gamut.
215 * @return an HSBType containing the current color and brightness level, or UNDEF or NULL.
217 public State getColorState() {
218 ColorXy color = this.color;
219 if (Objects.nonNull(color)) {
221 Gamut gamut = color.getGamut();
222 gamut = Objects.nonNull(gamut) ? gamut : ColorUtil.DEFAULT_GAMUT;
223 HSBType hsb = ColorUtil.xyToHsb(color.getXY(), gamut);
224 OnState on = this.on;
225 Dimming dimming = this.dimming;
226 double brightness = Objects.nonNull(on) && !on.isOn() ? 0
227 : Objects.nonNull(dimming) ? Math.max(0, Math.min(100, dimming.getBrightness())) : 50;
228 return new HSBType(hsb.getHue(), hsb.getSaturation(),
229 new PercentType(new BigDecimal(brightness, PERCENT_MATH_CONTEXT)));
230 } catch (DTOPresentButEmptyException e) {
231 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
234 return UnDefType.NULL;
237 public @Nullable ColorTemperature getColorTemperature() {
238 return colorTemperature;
241 public State getColorTemperatureAbsoluteState() {
242 ColorTemperature colorTemp = colorTemperature;
243 if (Objects.nonNull(colorTemp)) {
245 QuantityType<?> colorTemperature = colorTemp.getAbsolute();
246 if (Objects.nonNull(colorTemperature)) {
247 return colorTemperature;
249 } catch (DTOPresentButEmptyException e) {
250 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
253 return UnDefType.NULL;
257 * Get the colour temperature in percent. Note: this method is only to be used on cached state DTOs which already
258 * have a defined mirek schema.
260 * @return a PercentType with the colour temperature percentage.
262 public State getColorTemperaturePercentState() {
263 ColorTemperature colorTemperature = this.colorTemperature;
264 if (Objects.nonNull(colorTemperature)) {
266 Double percent = colorTemperature.getPercent();
267 if (Objects.nonNull(percent)) {
268 return new PercentType(new BigDecimal(percent, PERCENT_MATH_CONTEXT));
270 } catch (DTOPresentButEmptyException e) {
271 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
274 return UnDefType.NULL;
277 public @Nullable ColorXy getColorXy() {
282 * Return an HSB where the HS part is derived from the color xy JSON element (only), so the B part is 100%
284 * @return an HSBType.
286 public State getColorXyState() {
287 ColorXy color = this.color;
288 if (Objects.nonNull(color)) {
290 Gamut gamut = color.getGamut();
291 gamut = Objects.nonNull(gamut) ? gamut : ColorUtil.DEFAULT_GAMUT;
292 HSBType hsb = ColorUtil.xyToHsb(color.getXY(), gamut);
293 return new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.HUNDRED);
294 } catch (DTOPresentButEmptyException e) {
295 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
298 return UnDefType.NULL;
301 public int getControlId() {
302 MetaData metadata = this.metadata;
303 return Objects.nonNull(metadata) ? metadata.getControlId() : 0;
306 public @Nullable Dimming getDimming() {
311 * Return a PercentType which is derived from the dimming JSON element (only).
313 * @return a PercentType.
315 public State getDimmingState() {
316 Dimming dimming = this.dimming;
317 if (Objects.nonNull(dimming)) {
319 double dimmingValue = Math.max(0f, Math.min(100f, dimming.getBrightness()));
320 return new PercentType(new BigDecimal(dimmingValue, PERCENT_MATH_CONTEXT));
321 } catch (DTOPresentButEmptyException e) {
322 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
325 return UnDefType.NULL;
328 public @Nullable Effects getEffects() {
332 public State getEffectState() {
333 Effects effects = this.effects;
334 return Objects.nonNull(effects) ? new StringType(effects.getStatus().name()) : UnDefType.NULL;
337 public @Nullable Boolean getEnabled() {
341 public State getEnabledState() {
342 Boolean enabled = this.enabled;
343 return Objects.nonNull(enabled) ? OnOffType.from(enabled.booleanValue()) : UnDefType.NULL;
346 public @Nullable Gamut getGamut() {
347 ColorXy color = this.color;
348 return Objects.nonNull(color) ? color.getGamut() : null;
351 public @Nullable ResourceReference getGroup() {
355 public String getId() {
357 return Objects.nonNull(id) ? id : "";
360 public String getIdV1() {
361 String idV1 = this.idV1;
362 return Objects.nonNull(idV1) ? idV1 : "";
365 public @Nullable LightLevel getLightLevel() {
369 public State getLightLevelState() {
370 LightLevel light = this.light;
371 return Objects.nonNull(light) ? light.getLightLevelState() : UnDefType.NULL;
374 public @Nullable MetaData getMetaData() {
378 public @Nullable Double getMinimumDimmingLevel() {
379 Dimming dimming = this.dimming;
380 return Objects.nonNull(dimming) ? dimming.getMinimumDimmingLevel() : null;
383 public @Nullable MirekSchema getMirekSchema() {
384 ColorTemperature colorTemp = this.colorTemperature;
385 return Objects.nonNull(colorTemp) ? colorTemp.getMirekSchema() : null;
388 public @Nullable Motion getMotion() {
392 public State getMotionState() {
393 Motion motion = this.motion;
394 return Objects.nonNull(motion) ? motion.getMotionState() : UnDefType.NULL;
397 public State getMotionValidState() {
398 Motion motion = this.motion;
399 return Objects.nonNull(motion) ? motion.getMotionValidState() : UnDefType.NULL;
402 public String getName() {
403 MetaData metaData = getMetaData();
404 if (Objects.nonNull(metaData)) {
405 String name = metaData.getName();
406 if (Objects.nonNull(name)) {
410 return getType().toString();
414 * Return the state of the On/Off element (only).
416 public State getOnOffState() {
418 OnState on = this.on;
419 return Objects.nonNull(on) ? OnOffType.from(on.isOn()) : UnDefType.NULL;
420 } catch (DTOPresentButEmptyException e) {
421 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
425 public @Nullable OnState getOnState() {
429 public @Nullable ResourceReference getOwner() {
433 public @Nullable Power getPowerState() {
437 public @Nullable ProductData getProductData() {
441 public String getProductName() {
442 ProductData productData = getProductData();
443 if (Objects.nonNull(productData)) {
444 return productData.getProductName();
446 return getType().toString();
449 public @Nullable Recall getRecall() {
453 public @Nullable RelativeRotary getRelativeRotary() {
454 return relativeRotary;
457 public State getRelativeRotaryActionState() {
458 RelativeRotary relativeRotary = this.relativeRotary;
459 return Objects.nonNull(relativeRotary) ? relativeRotary.getActionState() : UnDefType.NULL;
462 public State getRotaryStepsState() {
463 RelativeRotary relativeRotary = this.relativeRotary;
464 return Objects.nonNull(relativeRotary) ? relativeRotary.getStepsState() : UnDefType.NULL;
468 * Check if the scene resource contains a 'status.active' element. If such an element is present, returns a Boolean
469 * Optional whose value depends on the value of that element, or an empty Optional if it is not.
471 * @return true, false, or empty.
473 public Optional<Boolean> getSceneActive() {
474 if (ResourceType.SCENE == getType()) {
475 JsonElement status = this.status;
476 if (Objects.nonNull(status) && status.isJsonObject()) {
477 JsonElement active = ((JsonObject) status).get("active");
478 if (Objects.nonNull(active) && active.isJsonPrimitive()) {
479 return Optional.of(!"inactive".equalsIgnoreCase(active.getAsString()));
483 return Optional.empty();
487 * If the getSceneActive() optional result is empty return 'UnDefType.NULL'. Otherwise if the optional result is
488 * present and 'true' (i.e. the scene is active) return the scene name. Or finally (the optional result is present
489 * and 'false') return 'UnDefType.UNDEF'.
491 * @return either 'UnDefType.NULL', a StringType containing the (active) scene name, or 'UnDefType.UNDEF'.
493 public State getSceneState() {
494 Optional<Boolean> active = getSceneActive();
495 return active.isEmpty() ? UnDefType.NULL : active.get() ? new StringType(getName()) : UnDefType.UNDEF;
498 public List<ResourceReference> getServiceReferences() {
499 List<ResourceReference> services = this.services;
500 return Objects.nonNull(services) ? services : List.of();
503 public JsonObject getStatus() {
504 JsonElement status = this.status;
505 if (Objects.nonNull(status) && status.isJsonObject()) {
506 return status.getAsJsonObject();
508 return new JsonObject();
511 public @Nullable Temperature getTemperature() {
515 public State getTemperatureState() {
516 Temperature temperature = this.temperature;
517 return Objects.nonNull(temperature) ? temperature.getTemperatureState() : UnDefType.NULL;
520 public State getTemperatureValidState() {
521 Temperature temperature = this.temperature;
522 return Objects.nonNull(temperature) ? temperature.getTemperatureValidState() : UnDefType.NULL;
525 public @Nullable Effects getTimedEffects() {
529 public ResourceType getType() {
530 return ResourceType.of(type);
533 public State getZigbeeState() {
534 ZigbeeStatus zigbeeStatus = getZigbeeStatus();
535 return Objects.nonNull(zigbeeStatus) ? new StringType(zigbeeStatus.toString()) : UnDefType.NULL;
538 public @Nullable ZigbeeStatus getZigbeeStatus() {
539 JsonElement status = this.status;
540 if (Objects.nonNull(status) && status.isJsonPrimitive()) {
541 return ZigbeeStatus.of(status.getAsString());
546 public boolean hasFullState() {
547 return !hasSparseData;
551 * Mark that the resource has sparse data.
553 * @return this instance.
555 public Resource markAsSparse() {
556 hasSparseData = true;
560 public Resource setAlerts(Alerts alert) {
565 public Resource setColorTemperature(ColorTemperature colorTemperature) {
566 this.colorTemperature = colorTemperature;
570 public Resource setColorXy(ColorXy color) {
575 public Resource setDimming(Dimming dimming) {
576 this.dimming = dimming;
580 public Resource setDynamicsDuration(Duration duration) {
581 dynamics = new Dynamics().setDuration(duration);
585 public Resource setEffects(Effects effect) {
586 this.effects = effect;
590 public Resource setEnabled(Command command) {
591 if (command instanceof OnOffType) {
592 this.enabled = ((OnOffType) command) == OnOffType.ON;
597 public Resource setId(String id) {
602 public Resource setMetadata(MetaData metadata) {
603 this.metadata = metadata;
607 public Resource setMirekSchema(@Nullable MirekSchema schema) {
608 ColorTemperature colorTemperature = this.colorTemperature;
609 if (Objects.nonNull(colorTemperature)) {
610 colorTemperature.setMirekSchema(schema);
616 * Set the on/off JSON element (only).
618 * @param command an OnOffTypee command value.
619 * @return this resource instance.
621 public Resource setOnOff(Command command) {
622 if (command instanceof OnOffType) {
623 OnOffType onOff = (OnOffType) command;
624 OnState on = this.on;
625 on = Objects.nonNull(on) ? on : new OnState();
626 on.setOn(OnOffType.ON.equals(onOff));
632 public void setOnState(OnState on) {
636 public Resource setRecallAction(RecallAction recallAction) {
637 Recall recall = this.recall;
638 this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setAction(recallAction);
642 public Resource setRecallDuration(Duration recallDuration) {
643 Recall recall = this.recall;
644 this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setDuration(recallDuration);
648 public Resource setType(ResourceType resourceType) {
649 this.type = resourceType.name().toLowerCase();
654 public String toString() {
656 return String.format("id:%s, type:%s", Objects.nonNull(id) ? id : "?" + " ".repeat(35),
657 getType().name().toLowerCase());