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.mqtt.ruuvigateway.internal;
15 import java.util.Optional;
17 import javax.measure.Quantity;
18 import javax.measure.Unit;
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;
29 * Simplified state cache for purposes of caching QuantityType and DecimalType values
31 * Unlike parent class {@link ChannelState}, this class by definition is not interacting with MQTT subscriptions nor
32 * does it update any channels
34 * @author Sami Salonen - Initial contribution
37 public class RuuviCachedNumberState<T extends Quantity<T>> extends ChannelState {
39 private final Optional<Unit<T>> unit;
42 * Construct cache for numbers with unit
44 * @param channelUID associated channel UID
45 * @param unit unit associated with updated numbers
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);
54 * Construct cache for numbers without unit
56 * @param channelUID associated channeld UID
58 public RuuviCachedNumberState(ChannelUID channelUID) {
59 super(new ChannelConfig(), channelUID, new NumberValue(null, null, null, null), null);
60 this.unit = Optional.empty();
64 * Update cached state with given value
66 * @param value value. Specified as plain number with unit given in constructor
68 public void update(Number value) {
69 unit.ifPresentOrElse(unit -> cachedValue.update(new QuantityType<>(value, unit)),
70 () -> cachedValue.update(new DecimalType(value)));
74 * Get associated unit with this cache
76 * @return unit associated with this (if applicable)
78 public Optional<Unit<T>> getUnit() {