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 List<ResourceReference> getChildren() {
200 List<ResourceReference> children = this.children;
201 return Objects.nonNull(children) ? children : List.of();
205 * Get the color as an HSBType. This returns an HSB that is based on an amalgamation of the color xy, dimming, and
206 * on/off JSON elements. It takes its 'H' and 'S' parts from the 'ColorXy' JSON element, and its 'B' part from the
207 * on/off resp. dimming JSON elements. If off the B part is 0, otherwise it is the dimming element value. Note: this
208 * method is only to be used on cached state DTOs which already have a defined color gamut.
210 * @return an HSBType containing the current color and brightness level, or UNDEF or NULL.
212 public State getColorState() {
213 ColorXy color = this.color;
214 if (Objects.nonNull(color)) {
216 Gamut gamut = color.getGamut();
217 gamut = Objects.nonNull(gamut) ? gamut : ColorUtil.DEFAULT_GAMUT;
218 HSBType hsb = ColorUtil.xyToHsb(color.getXY(), gamut);
219 OnState on = this.on;
220 Dimming dimming = this.dimming;
221 double brightness = Objects.nonNull(on) && !on.isOn() ? 0
222 : Objects.nonNull(dimming) ? Math.max(0, Math.min(100, dimming.getBrightness())) : 50;
223 return new HSBType(hsb.getHue(), hsb.getSaturation(),
224 new PercentType(new BigDecimal(brightness, PERCENT_MATH_CONTEXT)));
225 } catch (DTOPresentButEmptyException e) {
226 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
229 return UnDefType.NULL;
232 public @Nullable ColorTemperature getColorTemperature() {
233 return colorTemperature;
236 public State getColorTemperatureAbsoluteState() {
237 ColorTemperature colorTemp = colorTemperature;
238 if (Objects.nonNull(colorTemp)) {
240 QuantityType<?> colorTemperature = colorTemp.getAbsolute();
241 if (Objects.nonNull(colorTemperature)) {
242 return colorTemperature;
244 } catch (DTOPresentButEmptyException e) {
245 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
248 return UnDefType.NULL;
252 * Get the colour temperature in percent. Note: this method is only to be used on cached state DTOs which already
253 * have a defined mirek schema.
255 * @return a PercentType with the colour temperature percentage.
257 public State getColorTemperaturePercentState() {
258 ColorTemperature colorTemperature = this.colorTemperature;
259 if (Objects.nonNull(colorTemperature)) {
261 Double percent = colorTemperature.getPercent();
262 if (Objects.nonNull(percent)) {
263 return new PercentType(new BigDecimal(percent, PERCENT_MATH_CONTEXT));
265 } catch (DTOPresentButEmptyException e) {
266 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
269 return UnDefType.NULL;
272 public @Nullable ColorXy getColorXy() {
277 * Return an HSB where the HS part is derived from the color xy JSON element (only), so the B part is 100%
279 * @return an HSBType.
281 public State getColorXyState() {
282 ColorXy color = this.color;
283 if (Objects.nonNull(color)) {
285 Gamut gamut = color.getGamut();
286 gamut = Objects.nonNull(gamut) ? gamut : ColorUtil.DEFAULT_GAMUT;
287 HSBType hsb = ColorUtil.xyToHsb(color.getXY(), gamut);
288 return new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.HUNDRED);
289 } catch (DTOPresentButEmptyException e) {
290 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
293 return UnDefType.NULL;
296 public int getControlId() {
297 MetaData metadata = this.metadata;
298 return Objects.nonNull(metadata) ? metadata.getControlId() : 0;
301 public @Nullable Dimming getDimming() {
306 * Return a PercentType which is derived from the dimming JSON element (only).
308 * @return a PercentType.
310 public State getDimmingState() {
311 Dimming dimming = this.dimming;
312 if (Objects.nonNull(dimming)) {
314 double dimmingValue = Math.max(0f, Math.min(100f, dimming.getBrightness()));
315 return new PercentType(new BigDecimal(dimmingValue, PERCENT_MATH_CONTEXT));
316 } catch (DTOPresentButEmptyException e) {
317 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
320 return UnDefType.NULL;
323 public @Nullable Effects getEffects() {
327 public State getEffectState() {
328 Effects effects = this.effects;
329 return Objects.nonNull(effects) ? new StringType(effects.getStatus().name()) : UnDefType.NULL;
332 public @Nullable Boolean getEnabled() {
336 public State getEnabledState() {
337 Boolean enabled = this.enabled;
338 return Objects.nonNull(enabled) ? OnOffType.from(enabled.booleanValue()) : UnDefType.NULL;
341 public @Nullable Gamut getGamut() {
342 ColorXy color = this.color;
343 return Objects.nonNull(color) ? color.getGamut() : null;
346 public @Nullable ResourceReference getGroup() {
350 public String getId() {
352 return Objects.nonNull(id) ? id : "";
355 public String getIdV1() {
356 String idV1 = this.idV1;
357 return Objects.nonNull(idV1) ? idV1 : "";
360 public @Nullable LightLevel getLightLevel() {
364 public State getLightLevelState() {
365 LightLevel light = this.light;
366 return Objects.nonNull(light) ? light.getLightLevelState() : UnDefType.NULL;
369 public @Nullable MetaData getMetaData() {
373 public @Nullable Double getMinimumDimmingLevel() {
374 Dimming dimming = this.dimming;
375 return Objects.nonNull(dimming) ? dimming.getMinimumDimmingLevel() : null;
378 public @Nullable MirekSchema getMirekSchema() {
379 ColorTemperature colorTemp = this.colorTemperature;
380 return Objects.nonNull(colorTemp) ? colorTemp.getMirekSchema() : null;
383 public @Nullable Motion getMotion() {
387 public State getMotionState() {
388 Motion motion = this.motion;
389 return Objects.nonNull(motion) ? motion.getMotionState() : UnDefType.NULL;
392 public State getMotionValidState() {
393 Motion motion = this.motion;
394 return Objects.nonNull(motion) ? motion.getMotionValidState() : UnDefType.NULL;
397 public String getName() {
398 MetaData metaData = getMetaData();
399 if (Objects.nonNull(metaData)) {
400 String name = metaData.getName();
401 if (Objects.nonNull(name)) {
405 return getType().toString();
409 * Return the state of the On/Off element (only).
411 public State getOnOffState() {
413 OnState on = this.on;
414 return Objects.nonNull(on) ? OnOffType.from(on.isOn()) : UnDefType.NULL;
415 } catch (DTOPresentButEmptyException e) {
416 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
420 public @Nullable OnState getOnState() {
424 public @Nullable ResourceReference getOwner() {
428 public @Nullable Power getPowerState() {
432 public @Nullable ProductData getProductData() {
436 public String getProductName() {
437 ProductData productData = getProductData();
438 if (Objects.nonNull(productData)) {
439 return productData.getProductName();
441 return getType().toString();
444 public @Nullable Recall getRecall() {
448 public @Nullable RelativeRotary getRelativeRotary() {
449 return relativeRotary;
452 public State getRelativeRotaryActionState() {
453 RelativeRotary relativeRotary = this.relativeRotary;
454 return Objects.nonNull(relativeRotary) ? relativeRotary.getActionState() : UnDefType.NULL;
457 public State getRotaryStepsState() {
458 RelativeRotary relativeRotary = this.relativeRotary;
459 return Objects.nonNull(relativeRotary) ? relativeRotary.getStepsState() : UnDefType.NULL;
463 * Check if the scene resource contains a 'status.active' element. If such an element is present, returns a Boolean
464 * Optional whose value depends on the value of that element, or an empty Optional if it is not.
466 * @return true, false, or empty.
468 public Optional<Boolean> getSceneActive() {
469 if (ResourceType.SCENE == getType()) {
470 JsonElement status = this.status;
471 if (Objects.nonNull(status) && status.isJsonObject()) {
472 JsonElement active = ((JsonObject) status).get("active");
473 if (Objects.nonNull(active) && active.isJsonPrimitive()) {
474 return Optional.of(!"inactive".equalsIgnoreCase(active.getAsString()));
478 return Optional.empty();
482 * If the getSceneActive() optional result is empty return 'UnDefType.NULL'. Otherwise if the optional result is
483 * present and 'true' (i.e. the scene is active) return the scene name. Or finally (the optional result is present
484 * and 'false') return 'UnDefType.UNDEF'.
486 * @return either 'UnDefType.NULL', a StringType containing the (active) scene name, or 'UnDefType.UNDEF'.
488 public State getSceneState() {
489 Optional<Boolean> active = getSceneActive();
490 return active.isEmpty() ? UnDefType.NULL : active.get() ? new StringType(getName()) : UnDefType.UNDEF;
493 public List<ResourceReference> getServiceReferences() {
494 List<ResourceReference> services = this.services;
495 return Objects.nonNull(services) ? services : List.of();
498 public JsonObject getStatus() {
499 JsonElement status = this.status;
500 if (Objects.nonNull(status) && status.isJsonObject()) {
501 return status.getAsJsonObject();
503 return new JsonObject();
506 public @Nullable Temperature getTemperature() {
510 public State getTemperatureState() {
511 Temperature temperature = this.temperature;
512 return Objects.nonNull(temperature) ? temperature.getTemperatureState() : UnDefType.NULL;
515 public State getTemperatureValidState() {
516 Temperature temperature = this.temperature;
517 return Objects.nonNull(temperature) ? temperature.getTemperatureValidState() : UnDefType.NULL;
520 public @Nullable Effects getTimedEffects() {
524 public ResourceType getType() {
525 return ResourceType.of(type);
528 public State getZigbeeState() {
529 ZigbeeStatus zigbeeStatus = getZigbeeStatus();
530 return Objects.nonNull(zigbeeStatus) ? new StringType(zigbeeStatus.toString()) : UnDefType.NULL;
533 public @Nullable ZigbeeStatus getZigbeeStatus() {
534 JsonElement status = this.status;
535 if (Objects.nonNull(status) && status.isJsonPrimitive()) {
536 return ZigbeeStatus.of(status.getAsString());
541 public boolean hasFullState() {
542 return !hasSparseData;
546 * Mark that the resource has sparse data.
548 * @return this instance.
550 public Resource markAsSparse() {
551 hasSparseData = true;
555 public Resource setAlerts(Alerts alert) {
560 public Resource setColorTemperature(ColorTemperature colorTemperature) {
561 this.colorTemperature = colorTemperature;
565 public Resource setColorXy(ColorXy color) {
570 public Resource setDimming(Dimming dimming) {
571 this.dimming = dimming;
575 public Resource setDynamicsDuration(Duration duration) {
576 dynamics = new Dynamics().setDuration(duration);
580 public Resource setEffects(Effects effect) {
581 this.effects = effect;
585 public Resource setEnabled(Command command) {
586 if (command instanceof OnOffType) {
587 this.enabled = ((OnOffType) command) == OnOffType.ON;
592 public Resource setId(String id) {
597 public Resource setMetadata(MetaData metadata) {
598 this.metadata = metadata;
602 public Resource setMirekSchema(@Nullable MirekSchema schema) {
603 ColorTemperature colorTemperature = this.colorTemperature;
604 if (Objects.nonNull(colorTemperature)) {
605 colorTemperature.setMirekSchema(schema);
611 * Set the on/off JSON element (only).
613 * @param command an OnOffTypee command value.
614 * @return this resource instance.
616 public Resource setOnOff(Command command) {
617 if (command instanceof OnOffType) {
618 OnOffType onOff = (OnOffType) command;
619 OnState on = this.on;
620 on = Objects.nonNull(on) ? on : new OnState();
621 on.setOn(OnOffType.ON.equals(onOff));
627 public void setOnState(OnState on) {
631 public Resource setRecallAction(RecallAction recallAction) {
632 Recall recall = this.recall;
633 this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setAction(recallAction);
637 public Resource setRecallDuration(Duration recallDuration) {
638 Recall recall = this.recall;
639 this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setDuration(recallDuration);
643 public Resource setType(ResourceType resourceType) {
644 this.type = resourceType.name().toLowerCase();
649 public String toString() {
651 return String.format("id:%s, type:%s", Objects.nonNull(id) ? id : "?" + " ".repeat(35),
652 getType().name().toLowerCase());