]> git.basschouten.com Git - openhab-addons.git/blob
6cae9c1e5904ba175a2d72e767f7e5c62f54840c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.api.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.time.Instant;
20 import java.time.ZoneId;
21 import java.time.ZonedDateTime;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ActionType;
30 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ButtonEventType;
31 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ContactStateType;
32 import org.openhab.binding.hue.internal.api.dto.clip2.enums.EffectType;
33 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ResourceType;
34 import org.openhab.binding.hue.internal.api.dto.clip2.enums.SceneRecallAction;
35 import org.openhab.binding.hue.internal.api.dto.clip2.enums.SmartSceneRecallAction;
36 import org.openhab.binding.hue.internal.api.dto.clip2.enums.SmartSceneState;
37 import org.openhab.binding.hue.internal.api.dto.clip2.enums.TamperStateType;
38 import org.openhab.binding.hue.internal.api.dto.clip2.enums.ZigbeeStatus;
39 import org.openhab.binding.hue.internal.exceptions.DTOPresentButEmptyException;
40 import org.openhab.core.library.types.DateTimeType;
41 import org.openhab.core.library.types.DecimalType;
42 import org.openhab.core.library.types.HSBType;
43 import org.openhab.core.library.types.OnOffType;
44 import org.openhab.core.library.types.OpenClosedType;
45 import org.openhab.core.library.types.PercentType;
46 import org.openhab.core.library.types.QuantityType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.library.unit.SIUnits;
49 import org.openhab.core.library.unit.Units;
50 import org.openhab.core.types.Command;
51 import org.openhab.core.types.State;
52 import org.openhab.core.types.UnDefType;
53 import org.openhab.core.util.ColorUtil;
54 import org.openhab.core.util.ColorUtil.Gamut;
55
56 import com.google.gson.JsonElement;
57 import com.google.gson.JsonObject;
58 import com.google.gson.annotations.SerializedName;
59
60 /**
61  * Complete Resource information DTO for CLIP 2.
62  *
63  * Note: all fields are @Nullable because some cases do not (must not) use them.
64  *
65  * @author Andrew Fiddian-Green - Initial contribution
66  */
67 @NonNullByDefault
68 public class Resource {
69
70     public static final MathContext PERCENT_MATH_CONTEXT = new MathContext(4, RoundingMode.HALF_UP);
71
72     /**
73      * The SSE event mechanism sends resources in a sparse (skeleton) format that only includes state fields whose
74      * values have changed. A sparse resource does not contain the full state of the resource. And the absence of any
75      * field from such a resource does not indicate that the field value is UNDEF, but rather that the value is the same
76      * as what it was previously set to by the last non-sparse resource.
77      */
78     private transient boolean hasSparseData;
79
80     private @Nullable String type;
81     private @Nullable String id;
82     private @Nullable @SerializedName("bridge_id") String bridgeId;
83     private @Nullable @SerializedName("id_v1") String idV1;
84     private @Nullable ResourceReference owner;
85     private @Nullable MetaData metadata;
86     private @Nullable @SerializedName("product_data") ProductData productData;
87     private @Nullable List<ResourceReference> services;
88     private @Nullable OnState on;
89     private @Nullable Dimming dimming;
90     private @Nullable @SerializedName("color_temperature") ColorTemperature colorTemperature;
91     private @Nullable ColorXy color;
92     private @Nullable Alerts alert;
93     private @Nullable Effects effects;
94     private @Nullable @SerializedName("timed_effects") TimedEffects timedEffects;
95     private @Nullable ResourceReference group;
96     private @Nullable List<ActionEntry> actions;
97     private @Nullable Recall recall;
98     private @Nullable Boolean enabled;
99     private @Nullable LightLevel light;
100     private @Nullable Button button;
101     private @Nullable Temperature temperature;
102     private @Nullable Motion motion;
103     private @Nullable @SerializedName("power_state") Power powerState;
104     private @Nullable @SerializedName("relative_rotary") RelativeRotary relativeRotary;
105     private @Nullable List<ResourceReference> children;
106     private @Nullable JsonElement status;
107     private @Nullable Dynamics dynamics;
108     private @Nullable @SerializedName("contact_report") ContactReport contactReport;
109     private @Nullable @SerializedName("tamper_reports") List<TamperReport> tamperReports;
110     private @Nullable String state;
111
112     /**
113      * Constructor
114      *
115      * @param resourceType
116      */
117     public Resource(@Nullable ResourceType resourceType) {
118         if (Objects.nonNull(resourceType)) {
119             setType(resourceType);
120         }
121     }
122
123     /**
124      * Check if <code>light</code> or <code>grouped_light</code> resource contains any
125      * relevant fields to process according to its type.
126      *
127      * As an example, {@link #colorTemperature} is relevant for a <code>light</code>
128      * resource because it's needed for updating the color-temperature channels.
129      *
130      * @return true is resource contains any relevant field
131      */
132     public boolean hasAnyRelevantField() {
133         return switch (getType()) {
134             // https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_light_get
135             case LIGHT -> hasHSBField() || colorTemperature != null || dynamics != null || effects != null
136                     || timedEffects != null;
137             // https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_grouped_light_get
138             case GROUPED_LIGHT -> on != null || dimming != null || alert != null;
139             default -> throw new IllegalStateException(type + " is not supported by hasAnyRelevantField()");
140         };
141     }
142
143     /**
144      * Check if resource contains any field which is needed to represent an HSB value
145      * (<code>on</code>, <code>dimming</code> or <code>color</code>).
146      *
147      * @return true if resource has any HSB field
148      */
149     public boolean hasHSBField() {
150         return on != null || dimming != null || color != null;
151     }
152
153     public @Nullable List<ActionEntry> getActions() {
154         return actions;
155     }
156
157     public @Nullable Alerts getAlerts() {
158         return alert;
159     }
160
161     public State getAlertState() {
162         Alerts alerts = this.alert;
163         if (Objects.nonNull(alerts)) {
164             if (!alerts.getActionValues().isEmpty()) {
165                 ActionType alertType = alerts.getAction();
166                 if (Objects.nonNull(alertType)) {
167                     return new StringType(alertType.name());
168                 }
169                 return new StringType(ActionType.NO_ACTION.name());
170             }
171         }
172         return UnDefType.NULL;
173     }
174
175     public String getArchetype() {
176         MetaData metaData = getMetaData();
177         if (Objects.nonNull(metaData)) {
178             return metaData.getArchetype().toString();
179         }
180         return getType().toString();
181     }
182
183     public State getBatteryLevelState() {
184         Power powerState = this.powerState;
185         return Objects.nonNull(powerState) ? powerState.getBatteryLevelState() : UnDefType.NULL;
186     }
187
188     public State getBatteryLowState() {
189         Power powerState = this.powerState;
190         return Objects.nonNull(powerState) ? powerState.getBatteryLowState() : UnDefType.NULL;
191     }
192
193     public @Nullable String getBridgeId() {
194         String bridgeId = this.bridgeId;
195         return Objects.isNull(bridgeId) || bridgeId.isBlank() ? null : bridgeId;
196     }
197
198     /**
199      * Get the brightness as a PercentType. If off the brightness is 0, otherwise use dimming value.
200      *
201      * @return a PercentType with the dimming state, or UNDEF, or NULL
202      */
203     public State getBrightnessState() {
204         Dimming dimming = this.dimming;
205         if (Objects.nonNull(dimming)) {
206             try {
207                 // if off the brightness is 0, otherwise it is the larger of dimming value or minimum dimming level
208                 OnState on = this.on;
209                 double brightness;
210                 if (Objects.nonNull(on) && !on.isOn()) {
211                     brightness = 0f;
212                 } else {
213                     Double minimumDimmingLevel = dimming.getMinimumDimmingLevel();
214                     brightness = Math.max(Objects.nonNull(minimumDimmingLevel) ? minimumDimmingLevel
215                             : Dimming.DEFAULT_MINIMUM_DIMMIMG_LEVEL, Math.min(100f, dimming.getBrightness()));
216                 }
217                 return new PercentType(new BigDecimal(brightness, PERCENT_MATH_CONTEXT));
218             } catch (DTOPresentButEmptyException e) {
219                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
220             }
221         }
222         return UnDefType.NULL;
223     }
224
225     public @Nullable Button getButton() {
226         return button;
227     }
228
229     /**
230      * Get the state corresponding to a button's last event value multiplied by the controlId found for it in the given
231      * controlIds map. States are decimal values formatted like '1002' where the first digit is the button's controlId
232      * and the last digit is the ordinal value of the button's last event.
233      *
234      * @param controlIds the map of control ids to be referenced.
235      * @return the state.
236      */
237     public State getButtonEventState(Map<String, Integer> controlIds) {
238         Button button = this.button;
239         if (button == null) {
240             return UnDefType.NULL;
241         }
242         ButtonEventType event;
243         ButtonReport buttonReport = button.getButtonReport();
244         if (buttonReport == null) {
245             event = button.getLastEvent();
246         } else {
247             event = buttonReport.getLastEvent();
248         }
249         if (event == null) {
250             return UnDefType.NULL;
251         }
252         return new DecimalType((controlIds.getOrDefault(getId(), 0).intValue() * 1000) + event.ordinal());
253     }
254
255     public State getButtonLastUpdatedState(ZoneId zoneId) {
256         Button button = this.button;
257         if (button == null) {
258             return UnDefType.NULL;
259         }
260         ButtonReport buttonReport = button.getButtonReport();
261         if (buttonReport == null) {
262             return UnDefType.UNDEF;
263         }
264         Instant lastChanged = buttonReport.getLastChanged();
265         if (Instant.EPOCH.equals(lastChanged)) {
266             return UnDefType.UNDEF;
267         }
268         return new DateTimeType(ZonedDateTime.ofInstant(lastChanged, zoneId));
269     }
270
271     public List<ResourceReference> getChildren() {
272         List<ResourceReference> children = this.children;
273         return Objects.nonNull(children) ? children : List.of();
274     }
275
276     /**
277      * Get the color as an HSBType. This returns an HSB that is based on an amalgamation of the color xy, dimming, and
278      * on/off JSON elements. It takes its 'H' and 'S' parts from the 'ColorXy' JSON element, and its 'B' part from the
279      * on/off resp. dimming JSON elements. If off the B part is 0, otherwise it is the dimming element value. Note: this
280      * method is only to be used on cached state DTOs which already have a defined color gamut.
281      *
282      * @return an HSBType containing the current color and brightness level, or UNDEF or NULL.
283      */
284     public State getColorState() {
285         ColorXy color = this.color;
286         if (Objects.nonNull(color)) {
287             try {
288                 HSBType hsb = ColorUtil.xyToHsb(color.getXY());
289                 OnState on = this.on;
290                 Dimming dimming = this.dimming;
291                 double brightness = Objects.nonNull(on) && !on.isOn() ? 0
292                         : Objects.nonNull(dimming) ? Math.max(0, Math.min(100, dimming.getBrightness())) : 50;
293                 return new HSBType(hsb.getHue(), hsb.getSaturation(),
294                         new PercentType(new BigDecimal(brightness, PERCENT_MATH_CONTEXT)));
295             } catch (DTOPresentButEmptyException e) {
296                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
297             }
298         }
299         return UnDefType.NULL;
300     }
301
302     public @Nullable ColorTemperature getColorTemperature() {
303         return colorTemperature;
304     }
305
306     public State getColorTemperatureAbsoluteState() {
307         ColorTemperature colorTemp = colorTemperature;
308         if (Objects.nonNull(colorTemp)) {
309             try {
310                 QuantityType<?> colorTemperature = colorTemp.getAbsolute();
311                 if (Objects.nonNull(colorTemperature)) {
312                     return colorTemperature;
313                 }
314             } catch (DTOPresentButEmptyException e) {
315                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
316             }
317         }
318         return UnDefType.NULL;
319     }
320
321     /**
322      * Get the colour temperature in percent. Note: this method is only to be used on cached state DTOs which already
323      * have a defined mirek schema.
324      *
325      * @return a PercentType with the colour temperature percentage.
326      */
327     public State getColorTemperaturePercentState() {
328         ColorTemperature colorTemperature = this.colorTemperature;
329         if (Objects.nonNull(colorTemperature)) {
330             try {
331                 Double percent = colorTemperature.getPercent();
332                 if (Objects.nonNull(percent)) {
333                     return new PercentType(new BigDecimal(percent, PERCENT_MATH_CONTEXT));
334                 }
335             } catch (DTOPresentButEmptyException e) {
336                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
337             }
338         }
339         return UnDefType.NULL;
340     }
341
342     public @Nullable ColorXy getColorXy() {
343         return color;
344     }
345
346     /**
347      * Return an HSB where the HS part is derived from the color xy JSON element (only), so the B part is 100%
348      *
349      * @return an HSBType.
350      */
351     public State getColorXyState() {
352         ColorXy color = this.color;
353         if (Objects.nonNull(color)) {
354             try {
355                 HSBType hsb = ColorUtil.xyToHsb(color.getXY());
356                 return new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.HUNDRED);
357             } catch (DTOPresentButEmptyException e) {
358                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
359             }
360         }
361         return UnDefType.NULL;
362     }
363
364     public State getContactLastUpdatedState(ZoneId zoneId) {
365         ContactReport contactReport = this.contactReport;
366         return Objects.nonNull(contactReport)
367                 ? new DateTimeType(ZonedDateTime.ofInstant(contactReport.getLastChanged(), zoneId))
368                 : UnDefType.NULL;
369     }
370
371     public State getContactState() {
372         ContactReport contactReport = this.contactReport;
373         return Objects.isNull(contactReport) ? UnDefType.NULL
374                 : ContactStateType.CONTACT == contactReport.getContactState() ? OpenClosedType.CLOSED
375                         : OpenClosedType.OPEN;
376     }
377
378     public int getControlId() {
379         MetaData metadata = this.metadata;
380         return Objects.nonNull(metadata) ? metadata.getControlId() : 0;
381     }
382
383     public @Nullable Dimming getDimming() {
384         return dimming;
385     }
386
387     /**
388      * Return a PercentType which is derived from the dimming JSON element (only).
389      *
390      * @return a PercentType.
391      */
392     public State getDimmingState() {
393         Dimming dimming = this.dimming;
394         if (Objects.nonNull(dimming)) {
395             try {
396                 double dimmingValue = Math.max(0f, Math.min(100f, dimming.getBrightness()));
397                 return new PercentType(new BigDecimal(dimmingValue, PERCENT_MATH_CONTEXT));
398             } catch (DTOPresentButEmptyException e) {
399                 return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
400             }
401         }
402         return UnDefType.NULL;
403     }
404
405     public @Nullable Effects getFixedEffects() {
406         return effects;
407     }
408
409     /**
410      * Get the amalgamated effect state. The result may be either from an 'effects' field or from a 'timedEffects'
411      * field. If both fields are missing it returns UnDefType.NULL, otherwise if either field is present and has an
412      * active value (other than EffectType.NO_EFFECT) it returns a StringType of the name of the respective active
413      * effect; and if none of the above apply, it returns a StringType of 'NO_EFFECT'.
414      *
415      * @return either a StringType value or UnDefType.NULL
416      */
417     public State getEffectState() {
418         Effects effects = this.effects;
419         TimedEffects timedEffects = this.timedEffects;
420         if (Objects.isNull(effects) && Objects.isNull(timedEffects)) {
421             return UnDefType.NULL;
422         }
423         EffectType effect = Objects.nonNull(effects) ? effects.getStatus() : null;
424         if (Objects.nonNull(effect) && effect != EffectType.NO_EFFECT) {
425             return new StringType(effect.name());
426         }
427         EffectType timedEffect = Objects.nonNull(timedEffects) ? timedEffects.getStatus() : null;
428         if (Objects.nonNull(timedEffect) && timedEffect != EffectType.NO_EFFECT) {
429             return new StringType(timedEffect.name());
430         }
431         return new StringType(EffectType.NO_EFFECT.name());
432     }
433
434     public @Nullable Boolean getEnabled() {
435         return enabled;
436     }
437
438     public State getEnabledState() {
439         Boolean enabled = this.enabled;
440         return Objects.nonNull(enabled) ? OnOffType.from(enabled.booleanValue()) : UnDefType.NULL;
441     }
442
443     public @Nullable Gamut getGamut() {
444         ColorXy color = this.color;
445         return Objects.nonNull(color) ? color.getGamut() : null;
446     }
447
448     public @Nullable ResourceReference getGroup() {
449         return group;
450     }
451
452     public String getId() {
453         String id = this.id;
454         return Objects.nonNull(id) ? id : "";
455     }
456
457     public String getIdV1() {
458         String idV1 = this.idV1;
459         return Objects.nonNull(idV1) ? idV1 : "";
460     }
461
462     public @Nullable LightLevel getLightLevel() {
463         return light;
464     }
465
466     public State getLightLevelState() {
467         LightLevel lightLevel = this.light;
468         if (lightLevel == null) {
469             return UnDefType.NULL;
470         }
471         LightLevelReport lightLevelReport = lightLevel.getLightLevelReport();
472         if (lightLevelReport == null) {
473             return lightLevel.getLightLevelState();
474         }
475         return new QuantityType<>(Math.pow(10f, (double) lightLevelReport.getLightLevel() / 10000f) - 1f, Units.LUX);
476     }
477
478     public State getLightLevelLastUpdatedState(ZoneId zoneId) {
479         LightLevel lightLevel = this.light;
480         if (lightLevel == null) {
481             return UnDefType.NULL;
482         }
483         LightLevelReport lightLevelReport = lightLevel.getLightLevelReport();
484         if (lightLevelReport == null) {
485             return UnDefType.UNDEF;
486         }
487         Instant lastChanged = lightLevelReport.getLastChanged();
488         if (Instant.EPOCH.equals(lastChanged)) {
489             return UnDefType.UNDEF;
490         }
491         return new DateTimeType(ZonedDateTime.ofInstant(lastChanged, zoneId));
492     }
493
494     public @Nullable MetaData getMetaData() {
495         return metadata;
496     }
497
498     public @Nullable Double getMinimumDimmingLevel() {
499         Dimming dimming = this.dimming;
500         return Objects.nonNull(dimming) ? dimming.getMinimumDimmingLevel() : null;
501     }
502
503     public @Nullable MirekSchema getMirekSchema() {
504         ColorTemperature colorTemp = this.colorTemperature;
505         return Objects.nonNull(colorTemp) ? colorTemp.getMirekSchema() : null;
506     }
507
508     public @Nullable Motion getMotion() {
509         return motion;
510     }
511
512     public State getMotionState() {
513         Motion motion = this.motion;
514         if (motion == null) {
515             return UnDefType.NULL;
516         }
517         MotionReport motionReport = motion.getMotionReport();
518         if (motionReport == null) {
519             return motion.getMotionState();
520         }
521         return OnOffType.from(motionReport.isMotion());
522     }
523
524     public State getMotionLastUpdatedState(ZoneId zoneId) {
525         Motion motion = this.motion;
526         if (motion == null) {
527             return UnDefType.NULL;
528         }
529         MotionReport motionReport = motion.getMotionReport();
530         if (motionReport == null) {
531             return UnDefType.UNDEF;
532         }
533         Instant lastChanged = motionReport.getLastChanged();
534         if (Instant.EPOCH.equals(lastChanged)) {
535             return UnDefType.UNDEF;
536         }
537         return new DateTimeType(ZonedDateTime.ofInstant(lastChanged, zoneId));
538     }
539
540     public State getMotionValidState() {
541         Motion motion = this.motion;
542         return Objects.nonNull(motion) ? motion.getMotionValidState() : UnDefType.NULL;
543     }
544
545     public String getName() {
546         MetaData metaData = getMetaData();
547         if (Objects.nonNull(metaData)) {
548             String name = metaData.getName();
549             if (Objects.nonNull(name)) {
550                 return name;
551             }
552         }
553         return getType().toString();
554     }
555
556     /**
557      * Return the state of the On/Off element (only).
558      */
559     public State getOnOffState() {
560         try {
561             OnState on = this.on;
562             return Objects.nonNull(on) ? OnOffType.from(on.isOn()) : UnDefType.NULL;
563         } catch (DTOPresentButEmptyException e) {
564             return UnDefType.UNDEF; // indicates the DTO is present but its inner fields are missing
565         }
566     }
567
568     public @Nullable OnState getOnState() {
569         return on;
570     }
571
572     public @Nullable ResourceReference getOwner() {
573         return owner;
574     }
575
576     public @Nullable Power getPowerState() {
577         return powerState;
578     }
579
580     public @Nullable ProductData getProductData() {
581         return productData;
582     }
583
584     public String getProductName() {
585         ProductData productData = getProductData();
586         if (Objects.nonNull(productData)) {
587             return productData.getProductName();
588         }
589         return getType().toString();
590     }
591
592     public @Nullable Recall getRecall() {
593         return recall;
594     }
595
596     public @Nullable RelativeRotary getRelativeRotary() {
597         return relativeRotary;
598     }
599
600     public State getRotaryStepsState() {
601         RelativeRotary relativeRotary = this.relativeRotary;
602         if (relativeRotary == null) {
603             return UnDefType.NULL;
604         }
605         RotaryReport rotaryReport = relativeRotary.getRotaryReport();
606         if (rotaryReport == null) {
607             return relativeRotary.getStepsState();
608         }
609         Rotation rotation = rotaryReport.getRotation();
610         if (rotation == null) {
611             return UnDefType.NULL;
612         }
613         return rotation.getStepsState();
614     }
615
616     public State getRotaryStepsLastUpdatedState(ZoneId zoneId) {
617         RelativeRotary relativeRotary = this.relativeRotary;
618         if (relativeRotary == null) {
619             return UnDefType.NULL;
620         }
621         RotaryReport rotaryReport = relativeRotary.getRotaryReport();
622         if (rotaryReport == null) {
623             return UnDefType.UNDEF;
624         }
625         Instant lastChanged = rotaryReport.getLastChanged();
626         if (Instant.EPOCH.equals(lastChanged)) {
627             return UnDefType.UNDEF;
628         }
629         return new DateTimeType(ZonedDateTime.ofInstant(lastChanged, zoneId));
630     }
631
632     /**
633      * Check if the scene resource contains a 'status.active' element. If such an element is present, returns a Boolean
634      * Optional whose value depends on the value of that element, or an empty Optional if it is not.
635      *
636      * @return true, false, or empty.
637      */
638     public Optional<Boolean> getSceneActive() {
639         if (ResourceType.SCENE == getType()) {
640             JsonElement status = this.status;
641             if (Objects.nonNull(status) && status.isJsonObject()) {
642                 JsonElement active = ((JsonObject) status).get("active");
643                 if (Objects.nonNull(active) && active.isJsonPrimitive()) {
644                     return Optional.of(!"inactive".equalsIgnoreCase(active.getAsString()));
645                 }
646             }
647         }
648         return Optional.empty();
649     }
650
651     /**
652      * If the getSceneActive() optional result is empty return 'UnDefType.NULL'. Otherwise if the optional result is
653      * present and 'true' (i.e. the scene is active) return the scene name. Or finally (the optional result is present
654      * and 'false') return 'UnDefType.UNDEF'.
655      *
656      * @return either 'UnDefType.NULL', a StringType containing the (active) scene name, or 'UnDefType.UNDEF'.
657      */
658     public State getSceneState() {
659         return getSceneActive().map(a -> a ? new StringType(getName()) : UnDefType.UNDEF).orElse(UnDefType.NULL);
660     }
661
662     /**
663      * Check if the smart scene resource contains a 'state' element. If such an element is present, returns a Boolean
664      * Optional whose value depends on the value of that element, or an empty Optional if it is not.
665      *
666      * @return true, false, or empty.
667      */
668     public Optional<Boolean> getSmartSceneActive() {
669         if (ResourceType.SMART_SCENE == getType()) {
670             String state = this.state;
671             if (Objects.nonNull(state)) {
672                 return Optional.of(SmartSceneState.ACTIVE == SmartSceneState.of(state));
673             }
674         }
675         return Optional.empty();
676     }
677
678     /**
679      * If the getSmartSceneActive() optional result is empty return 'UnDefType.NULL'. Otherwise if the optional result
680      * is present and 'true' (i.e. the scene is active) return the smart scene name. Or finally (the optional result is
681      * present and 'false') return 'UnDefType.UNDEF'.
682      *
683      * @return either 'UnDefType.NULL', a StringType containing the (active) scene name, or 'UnDefType.UNDEF'.
684      */
685     public State getSmartSceneState() {
686         return getSmartSceneActive().map(a -> a ? new StringType(getName()) : UnDefType.UNDEF).orElse(UnDefType.NULL);
687     }
688
689     public List<ResourceReference> getServiceReferences() {
690         List<ResourceReference> services = this.services;
691         return Objects.nonNull(services) ? services : List.of();
692     }
693
694     public JsonObject getStatus() {
695         JsonElement status = this.status;
696         if (Objects.nonNull(status) && status.isJsonObject()) {
697             return status.getAsJsonObject();
698         }
699         return new JsonObject();
700     }
701
702     public State getTamperLastUpdatedState(ZoneId zoneId) {
703         TamperReport report = getTamperReportsLatest();
704         return Objects.nonNull(report) ? new DateTimeType(ZonedDateTime.ofInstant(report.getLastChanged(), zoneId))
705                 : UnDefType.NULL;
706     }
707
708     /**
709      * The the Hue bridge could return its raw list of tamper reports in any order, so sort the list (latest entry
710      * first) according to the respective 'changed' instant and return the first entry i.e. the latest changed entry.
711      *
712      * @return the latest changed tamper report
713      */
714     private @Nullable TamperReport getTamperReportsLatest() {
715         List<TamperReport> reports = this.tamperReports;
716         return Objects.nonNull(reports)
717                 ? reports.stream().sorted((e1, e2) -> e2.getLastChanged().compareTo(e1.getLastChanged())).findFirst()
718                         .orElse(null)
719                 : null;
720     }
721
722     public State getTamperState() {
723         TamperReport report = getTamperReportsLatest();
724         return Objects.nonNull(report)
725                 ? TamperStateType.TAMPERED == report.getTamperState() ? OpenClosedType.OPEN : OpenClosedType.CLOSED
726                 : UnDefType.NULL;
727     }
728
729     public @Nullable Temperature getTemperature() {
730         return temperature;
731     }
732
733     public State getTemperatureState() {
734         Temperature temperature = this.temperature;
735         if (temperature == null) {
736             return UnDefType.NULL;
737         }
738         TemperatureReport temperatureReport = temperature.getTemperatureReport();
739         if (temperatureReport == null) {
740             return temperature.getTemperatureState();
741         }
742         return new QuantityType<>(temperatureReport.getTemperature(), SIUnits.CELSIUS);
743     }
744
745     public State getTemperatureLastUpdatedState(ZoneId zoneId) {
746         Temperature temperature = this.temperature;
747         if (temperature == null) {
748             return UnDefType.NULL;
749         }
750         TemperatureReport temperatureReport = temperature.getTemperatureReport();
751         if (temperatureReport == null) {
752             return UnDefType.UNDEF;
753         }
754         Instant lastChanged = temperatureReport.getLastChanged();
755         if (Instant.EPOCH.equals(lastChanged)) {
756             return UnDefType.UNDEF;
757         }
758         return new DateTimeType(ZonedDateTime.ofInstant(lastChanged, zoneId));
759     }
760
761     public State getTemperatureValidState() {
762         Temperature temperature = this.temperature;
763         return Objects.nonNull(temperature) ? temperature.getTemperatureValidState() : UnDefType.NULL;
764     }
765
766     public @Nullable TimedEffects getTimedEffects() {
767         return timedEffects;
768     }
769
770     public ResourceType getType() {
771         return ResourceType.of(type);
772     }
773
774     public State getZigbeeState() {
775         ZigbeeStatus zigbeeStatus = getZigbeeStatus();
776         return Objects.nonNull(zigbeeStatus) ? new StringType(zigbeeStatus.toString()) : UnDefType.NULL;
777     }
778
779     public @Nullable ZigbeeStatus getZigbeeStatus() {
780         JsonElement status = this.status;
781         if (Objects.nonNull(status) && status.isJsonPrimitive()) {
782             return ZigbeeStatus.of(status.getAsString());
783         }
784         return null;
785     }
786
787     public boolean hasFullState() {
788         return !hasSparseData;
789     }
790
791     /**
792      * Mark that the resource has sparse data.
793      *
794      * @return this instance.
795      */
796     public Resource markAsSparse() {
797         hasSparseData = true;
798         return this;
799     }
800
801     public Resource setAlerts(Alerts alert) {
802         this.alert = alert;
803         return this;
804     }
805
806     public Resource setColorTemperature(ColorTemperature colorTemperature) {
807         this.colorTemperature = colorTemperature;
808         return this;
809     }
810
811     public Resource setColorXy(@Nullable ColorXy color) {
812         this.color = color;
813         return this;
814     }
815
816     public Resource setContactReport(ContactReport contactReport) {
817         this.contactReport = contactReport;
818         return this;
819     }
820
821     public Resource setDimming(@Nullable Dimming dimming) {
822         this.dimming = dimming;
823         return this;
824     }
825
826     public Resource setDynamicsDuration(Duration duration) {
827         dynamics = new Dynamics().setDuration(duration);
828         return this;
829     }
830
831     public Resource setFixedEffects(Effects effect) {
832         this.effects = effect;
833         return this;
834     }
835
836     public Resource setEnabled(Command command) {
837         if (command instanceof OnOffType) {
838             this.enabled = ((OnOffType) command) == OnOffType.ON;
839         }
840         return this;
841     }
842
843     public Resource setId(String id) {
844         this.id = id;
845         return this;
846     }
847
848     public Resource setMetadata(MetaData metadata) {
849         this.metadata = metadata;
850         return this;
851     }
852
853     public Resource setMirekSchema(@Nullable MirekSchema schema) {
854         ColorTemperature colorTemperature = this.colorTemperature;
855         if (Objects.nonNull(colorTemperature)) {
856             colorTemperature.setMirekSchema(schema);
857         }
858         return this;
859     }
860
861     /**
862      * Set the on/off JSON element (only).
863      *
864      * @param command an OnOffTypee command value.
865      * @return this resource instance.
866      */
867     public Resource setOnOff(Command command) {
868         if (command instanceof OnOffType) {
869             OnOffType onOff = (OnOffType) command;
870             OnState on = this.on;
871             on = Objects.nonNull(on) ? on : new OnState();
872             on.setOn(OnOffType.ON.equals(onOff));
873             this.on = on;
874         }
875         return this;
876     }
877
878     public Resource setOnState(@Nullable OnState on) {
879         this.on = on;
880         return this;
881     }
882
883     public Resource setRecallAction(SceneRecallAction recallAction) {
884         Recall recall = this.recall;
885         this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setAction(recallAction);
886         return this;
887     }
888
889     public Resource setRecallAction(SmartSceneRecallAction recallAction) {
890         Recall recall = this.recall;
891         this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setAction(recallAction);
892         return this;
893     }
894
895     public Resource setRecallDuration(Duration recallDuration) {
896         Recall recall = this.recall;
897         this.recall = ((Objects.nonNull(recall) ? recall : new Recall())).setDuration(recallDuration);
898         return this;
899     }
900
901     public Resource setTamperReports(List<TamperReport> tamperReports) {
902         this.tamperReports = tamperReports;
903         return this;
904     }
905
906     public Resource setTimedEffects(TimedEffects timedEffects) {
907         this.timedEffects = timedEffects;
908         return this;
909     }
910
911     public Resource setTimedEffectsDuration(Duration dynamicsDuration) {
912         TimedEffects timedEffects = this.timedEffects;
913         if (Objects.nonNull(timedEffects)) {
914             timedEffects.setDuration(dynamicsDuration);
915         }
916         return this;
917     }
918
919     public Resource setType(ResourceType resourceType) {
920         this.type = resourceType.name().toLowerCase();
921         return this;
922     }
923
924     @Override
925     public String toString() {
926         String id = this.id;
927         return String.format("id:%s, type:%s", Objects.nonNull(id) ? id : "?" + " ".repeat(35),
928                 getType().name().toLowerCase());
929     }
930 }