]> git.basschouten.com Git - openhab-addons.git/blob
44ef31e889ed1099b09ce544d07269fc6dbf23a8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.hue.internal.dto.clip2;
14
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;
20 import java.util.Map;
21 import java.util.Objects;
22 import java.util.Optional;
23
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;
42
43 import com.google.gson.JsonElement;
44 import com.google.gson.JsonObject;
45 import com.google.gson.annotations.SerializedName;
46
47 /**
48  * Complete Resource information DTO for CLIP 2.
49  *
50  * Note: all fields are @Nullable because some cases do not (must not) use them.
51  *
52  * @author Andrew Fiddian-Green - Initial contribution
53  */
54 @NonNullByDefault
55 public class Resource {
56
57     public static final double PERCENT_DELTA = 30f;
58     public static final MathContext PERCENT_MATH_CONTEXT = new MathContext(4, RoundingMode.HALF_UP);
59
60     /**
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.
65      */
66     private transient boolean hasSparseData;
67
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;
96
97     /**
98      * Constructor
99      *
100      * @param resourceType
101      */
102     public Resource(@Nullable ResourceType resourceType) {
103         if (Objects.nonNull(resourceType)) {
104             setType(resourceType);
105         }
106     }
107
108     public @Nullable List<ActionEntry> getActions() {
109         return actions;
110     }
111
112     public @Nullable Alerts getAlerts() {
113         return alert;
114     }
115
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());
123                 }
124                 return new StringType(ActionType.NO_ACTION.name());
125             }
126         }
127         return UnDefType.NULL;
128     }
129
130     public String getArchetype() {
131         MetaData metaData = getMetaData();
132         if (Objects.nonNull(metaData)) {
133             return metaData.getArchetype().toString();
134         }
135         return getType().toString();
136     }
137
138     public State getBatteryLevelState() {
139         Power powerState = this.powerState;
140         return Objects.nonNull(powerState) ? powerState.getBatteryLevelState() : UnDefType.NULL;
141     }
142
143     public State getBatteryLowState() {
144         Power powerState = this.powerState;
145         return Objects.nonNull(powerState) ? powerState.getBatteryLowState() : UnDefType.NULL;
146     }
147
148     public @Nullable String getBridgeId() {
149         String bridgeId = this.bridgeId;
150         return Objects.isNull(bridgeId) || bridgeId.isBlank() ? null : bridgeId;
151     }
152
153     /**
154      * Get the brightness as a PercentType. If off the brightness is 0, otherwise use dimming value.
155      *
156      * @return a PercentType with the dimming state, or UNDEF, or NULL
157      */
158     public State getBrightnessState() {
159         Dimming dimming = this.dimming;
160         if (Objects.nonNull(dimming)) {
161             try {
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
169             }
170         }
171         return UnDefType.NULL;
172     }
173
174     public @Nullable Button getButton() {
175         return button;
176     }
177
178     /**
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.
182      *
183      * @param controlIds the map of control ids to be referenced.
184      * @return the state.
185      */
186     public State getButtonEventState(Map<String, Integer> controlIds) {
187         Button button = this.button;
188         if (Objects.nonNull(button)) {
189             try {
190                 return new DecimalType(
191                         (controlIds.getOrDefault(getId(), 0).intValue() * 1000) + button.getLastEvent().ordinal());
192             } catch (IllegalArgumentException e) {
193                 // fall through
194             }
195         }
196         return UnDefType.NULL;
197     }
198
199     public List<ResourceReference> getChildren() {
200         List<ResourceReference> children = this.children;
201         return Objects.nonNull(children) ? children : List.of();
202     }
203
204     /**
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' & '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.
209      *
210      * @return an HSBType containing the current color and brightness level, or UNDEF or NULL.
211      */
212     public State getColorState() {
213         ColorXy color = this.color;
214         if (Objects.nonNull(color)) {
215             try {
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
227             }
228         }
229         return UnDefType.NULL;
230     }
231
232     public @Nullable ColorTemperature getColorTemperature() {
233         return colorTemperature;
234     }
235
236     public State getColorTemperatureAbsoluteState() {
237         ColorTemperature colorTemp = colorTemperature;
238         if (Objects.nonNull(colorTemp)) {
239             try {
240                 QuantityType<?> colorTemperature = colorTemp.getAbsolute();
241                 if (Objects.nonNull(colorTemperature)) {
242                     return colorTemperature;
243                 }
244             } catch (DTOPresentButEmptyException e) {
245                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
246             }
247         }
248         return UnDefType.NULL;
249     }
250
251     /**
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.
254      *
255      * @return a PercentType with the colour temperature percentage.
256      */
257     public State getColorTemperaturePercentState() {
258         ColorTemperature colorTemperature = this.colorTemperature;
259         if (Objects.nonNull(colorTemperature)) {
260             try {
261                 Double percent = colorTemperature.getPercent();
262                 if (Objects.nonNull(percent)) {
263                     return new PercentType(new BigDecimal(percent, PERCENT_MATH_CONTEXT));
264                 }
265             } catch (DTOPresentButEmptyException e) {
266                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
267             }
268         }
269         return UnDefType.NULL;
270     }
271
272     public @Nullable ColorXy getColorXy() {
273         return color;
274     }
275
276     /**
277      * Return an HSB where the HS part is derived from the color xy JSON element (only), so the B part is 100%
278      *
279      * @return an HSBType.
280      */
281     public State getColorXyState() {
282         ColorXy color = this.color;
283         if (Objects.nonNull(color)) {
284             try {
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
291             }
292         }
293         return UnDefType.NULL;
294     }
295
296     public int getControlId() {
297         MetaData metadata = this.metadata;
298         return Objects.nonNull(metadata) ? metadata.getControlId() : 0;
299     }
300
301     public @Nullable Dimming getDimming() {
302         return dimming;
303     }
304
305     /**
306      * Return a PercentType which is derived from the dimming JSON element (only).
307      *
308      * @return a PercentType.
309      */
310     public State getDimmingState() {
311         Dimming dimming = this.dimming;
312         if (Objects.nonNull(dimming)) {
313             try {
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
318             }
319         }
320         return UnDefType.NULL;
321     }
322
323     public @Nullable Effects getEffects() {
324         return effects;
325     }
326
327     public State getEffectState() {
328         Effects effects = this.effects;
329         return Objects.nonNull(effects) ? new StringType(effects.getStatus().name()) : UnDefType.NULL;
330     }
331
332     public @Nullable Boolean getEnabled() {
333         return enabled;
334     }
335
336     public State getEnabledState() {
337         Boolean enabled = this.enabled;
338         return Objects.nonNull(enabled) ? OnOffType.from(enabled.booleanValue()) : UnDefType.NULL;
339     }
340
341     public @Nullable Gamut getGamut() {
342         ColorXy color = this.color;
343         return Objects.nonNull(color) ? color.getGamut() : null;
344     }
345
346     public @Nullable ResourceReference getGroup() {
347         return group;
348     }
349
350     public String getId() {
351         String id = this.id;
352         return Objects.nonNull(id) ? id : "";
353     }
354
355     public String getIdV1() {
356         String idV1 = this.idV1;
357         return Objects.nonNull(idV1) ? idV1 : "";
358     }
359
360     public @Nullable LightLevel getLightLevel() {
361         return light;
362     }
363
364     public State getLightLevelState() {
365         LightLevel light = this.light;
366         return Objects.nonNull(light) ? light.getLightLevelState() : UnDefType.NULL;
367     }
368
369     public @Nullable MetaData getMetaData() {
370         return metadata;
371     }
372
373     public @Nullable Double getMinimumDimmingLevel() {
374         Dimming dimming = this.dimming;
375         return Objects.nonNull(dimming) ? dimming.getMinimumDimmingLevel() : null;
376     }
377
378     public @Nullable MirekSchema getMirekSchema() {
379         ColorTemperature colorTemp = this.colorTemperature;
380         return Objects.nonNull(colorTemp) ? colorTemp.getMirekSchema() : null;
381     }
382
383     public @Nullable Motion getMotion() {
384         return motion;
385     }
386
387     public State getMotionState() {
388         Motion motion = this.motion;
389         return Objects.nonNull(motion) ? motion.getMotionState() : UnDefType.NULL;
390     }
391
392     public State getMotionValidState() {
393         Motion motion = this.motion;
394         return Objects.nonNull(motion) ? motion.getMotionValidState() : UnDefType.NULL;
395     }
396
397     public String getName() {
398         MetaData metaData = getMetaData();
399         if (Objects.nonNull(metaData)) {
400             String name = metaData.getName();
401             if (Objects.nonNull(name)) {
402                 return name;
403             }
404         }
405         return getType().toString();
406     }
407
408     /**
409      * Return the state of the On/Off element (only).
410      */
411     public State getOnOffState() {
412         try {
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
417         }
418     }
419
420     public @Nullable OnState getOnState() {
421         return on;
422     }
423
424     public @Nullable ResourceReference getOwner() {
425         return owner;
426     }
427
428     public @Nullable Power getPowerState() {
429         return powerState;
430     }
431
432     public @Nullable ProductData getProductData() {
433         return productData;
434     }
435
436     public String getProductName() {
437         ProductData productData = getProductData();
438         if (Objects.nonNull(productData)) {
439             return productData.getProductName();
440         }
441         return getType().toString();
442     }
443
444     public @Nullable Recall getRecall() {
445         return recall;
446     }
447
448     public @Nullable RelativeRotary getRelativeRotary() {
449         return relativeRotary;
450     }
451
452     public State getRelativeRotaryActionState() {
453         RelativeRotary relativeRotary = this.relativeRotary;
454         return Objects.nonNull(relativeRotary) ? relativeRotary.getActionState() : UnDefType.NULL;
455     }
456
457     public State getRotaryStepsState() {
458         RelativeRotary relativeRotary = this.relativeRotary;
459         return Objects.nonNull(relativeRotary) ? relativeRotary.getStepsState() : UnDefType.NULL;
460     }
461
462     /**
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.
465      *
466      * @return true, false, or empty.
467      */
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()));
475                 }
476             }
477         }
478         return Optional.empty();
479     }
480
481     /**
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'.
485      *
486      * @return either 'UnDefType.NULL', a StringType containing the (active) scene name, or 'UnDefType.UNDEF'.
487      */
488     public State getSceneState() {
489         Optional<Boolean> active = getSceneActive();
490         return active.isEmpty() ? UnDefType.NULL : active.get() ? new StringType(getName()) : UnDefType.UNDEF;
491     }
492
493     public List<ResourceReference> getServiceReferences() {
494         List<ResourceReference> services = this.services;
495         return Objects.nonNull(services) ? services : List.of();
496     }
497
498     public JsonObject getStatus() {
499         JsonElement status = this.status;
500         if (Objects.nonNull(status) && status.isJsonObject()) {
501             return status.getAsJsonObject();
502         }
503         return new JsonObject();
504     }
505
506     public @Nullable Temperature getTemperature() {
507         return temperature;
508     }
509
510     public State getTemperatureState() {
511         Temperature temperature = this.temperature;
512         return Objects.nonNull(temperature) ? temperature.getTemperatureState() : UnDefType.NULL;
513     }
514
515     public State getTemperatureValidState() {
516         Temperature temperature = this.temperature;
517         return Objects.nonNull(temperature) ? temperature.getTemperatureValidState() : UnDefType.NULL;
518     }
519
520     public @Nullable Effects getTimedEffects() {
521         return timedEffects;
522     }
523
524     public ResourceType getType() {
525         return ResourceType.of(type);
526     }
527
528     public State getZigbeeState() {
529         ZigbeeStatus zigbeeStatus = getZigbeeStatus();
530         return Objects.nonNull(zigbeeStatus) ? new StringType(zigbeeStatus.toString()) : UnDefType.NULL;
531     }
532
533     public @Nullable ZigbeeStatus getZigbeeStatus() {
534         JsonElement status = this.status;
535         if (Objects.nonNull(status) && status.isJsonPrimitive()) {
536             return ZigbeeStatus.of(status.getAsString());
537         }
538         return null;
539     }
540
541     public boolean hasFullState() {
542         return !hasSparseData;
543     }
544
545     /**
546      * Mark that the resource has sparse data.
547      *
548      * @return this instance.
549      */
550     public Resource markAsSparse() {
551         hasSparseData = true;
552         return this;
553     }
554
555     public Resource setAlerts(Alerts alert) {
556         this.alert = alert;
557         return this;
558     }
559
560     public Resource setColorTemperature(ColorTemperature colorTemperature) {
561         this.colorTemperature = colorTemperature;
562         return this;
563     }
564
565     public Resource setColorXy(ColorXy color) {
566         this.color = color;
567         return this;
568     }
569
570     public Resource setDimming(Dimming dimming) {
571         this.dimming = dimming;
572         return this;
573     }
574
575     public Resource setDynamicsDuration(Duration duration) {
576         dynamics = new Dynamics().setDuration(duration);
577         return this;
578     }
579
580     public Resource setEffects(Effects effect) {
581         this.effects = effect;
582         return this;
583     }
584
585     public Resource setEnabled(Command command) {
586         if (command instanceof OnOffType) {
587             this.enabled = ((OnOffType) command) == OnOffType.ON;
588         }
589         return this;
590     }
591
592     public Resource setId(String id) {
593         this.id = id;
594         return this;
595     }
596
597     public Resource setMetadata(MetaData metadata) {
598         this.metadata = metadata;
599         return this;
600     }
601
602     public Resource setMirekSchema(@Nullable MirekSchema schema) {
603         ColorTemperature colorTemperature = this.colorTemperature;
604         if (Objects.nonNull(colorTemperature)) {
605             colorTemperature.setMirekSchema(schema);
606         }
607         return this;
608     }
609
610     /**
611      * Set the on/off JSON element (only).
612      *
613      * @param command an OnOffTypee command value.
614      * @return this resource instance.
615      */
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));
622             this.on = on;
623         }
624         return this;
625     }
626
627     public void setOnState(OnState on) {
628         this.on = on;
629     }
630
631     public Resource setRecallAction(RecallAction recallAction) {
632         Recall recall = this.recall;
633         this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setAction(recallAction);
634         return this;
635     }
636
637     public Resource setRecallDuration(Duration recallDuration) {
638         Recall recall = this.recall;
639         this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setDuration(recallDuration);
640         return this;
641     }
642
643     public Resource setType(ResourceType resourceType) {
644         this.type = resourceType.name().toLowerCase();
645         return this;
646     }
647
648     @Override
649     public String toString() {
650         String id = this.id;
651         return String.format("id:%s, type:%s", Objects.nonNull(id) ? id : "?" + " ".repeat(35),
652                 getType().name().toLowerCase());
653     }
654 }