]> git.basschouten.com Git - openhab-addons.git/blob
ab5d494e8dabdf0cb945d487afb4bbda93d7b0c3
[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.mqtt.ruuvigateway.internal;
14
15 import java.util.Optional;
16
17 import javax.measure.Quantity;
18 import javax.measure.Unit;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.openhab.binding.mqtt.generic.ChannelConfig;
22 import org.openhab.binding.mqtt.generic.ChannelState;
23 import org.openhab.binding.mqtt.generic.values.NumberValue;
24 import org.openhab.core.library.types.DecimalType;
25 import org.openhab.core.library.types.QuantityType;
26 import org.openhab.core.thing.ChannelUID;
27
28 /**
29  * Simplified state cache for purposes of caching QuantityType and DecimalType values
30  *
31  * Unlike parent class {@link ChannelState}, this class by definition is not interacting with MQTT subscriptions nor
32  * does it update any channels
33  *
34  * @author Sami Salonen - Initial contribution
35  */
36 @NonNullByDefault
37 public class RuuviCachedNumberState<T extends Quantity<T>> extends ChannelState {
38
39     private final Optional<Unit<T>> unit;
40
41     /**
42      * Construct cache for numbers with unit
43      *
44      * @param channelUID associated channel UID
45      * @param unit unit associated with updated numbers
46      *
47      */
48     public RuuviCachedNumberState(ChannelUID channelUID, Unit<T> unit) {
49         super(new ChannelConfig(), channelUID, new NumberValue(null, null, null, unit), null);
50         this.unit = Optional.of(unit);
51     }
52
53     /**
54      * Construct cache for numbers without unit
55      *
56      * @param channelUID associated channeld UID
57      */
58     public RuuviCachedNumberState(ChannelUID channelUID) {
59         super(new ChannelConfig(), channelUID, new NumberValue(null, null, null, null), null);
60         this.unit = Optional.empty();
61     }
62
63     /**
64      * Update cached state with given value
65      *
66      * @param value value. Specified as plain number with unit given in constructor
67      */
68     public void update(Number value) {
69         unit.ifPresentOrElse(unit -> cachedValue.update(new QuantityType<>(value, unit)),
70                 () -> cachedValue.update(new DecimalType(value)));
71     }
72
73     /**
74      * Get associated unit with this cache
75      *
76      * @return unit associated with this (if applicable)
77      */
78     public Optional<Unit<T>> getUnit() {
79         return unit;
80     }
81 }