]> git.basschouten.com Git - openhab-addons.git/blob
cfece9d67bf815a1e257be3d0ea312935113425d
[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.mqtt.generic.values;
14
15 import java.math.BigDecimal;
16 import java.util.List;
17
18 import javax.measure.Unit;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.library.CoreItemFactory;
23 import org.openhab.core.library.types.DecimalType;
24 import org.openhab.core.library.types.IncreaseDecreaseType;
25 import org.openhab.core.library.types.QuantityType;
26 import org.openhab.core.library.types.StringType;
27 import org.openhab.core.library.types.UpDownType;
28 import org.openhab.core.library.unit.Units;
29 import org.openhab.core.types.Command;
30 import org.openhab.core.types.StateDescriptionFragmentBuilder;
31 import org.openhab.core.types.Type;
32 import org.openhab.core.types.UnDefType;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * Implements a number value.
38  *
39  * If min / max limits are set, values below / above are (almost) silently ignored.
40  *
41  * <p>
42  * Accepts user updates and MQTT state updates from a DecimalType, IncreaseDecreaseType and UpDownType.
43  * </p>
44  *
45  * @author David Graeff - Initial contribution
46  */
47 @NonNullByDefault
48 public class NumberValue extends Value {
49     private static final String NAN = "NaN";
50     private static final String NEGATIVE_NAN = "-NaN";
51
52     private final Logger logger = LoggerFactory.getLogger(NumberValue.class);
53     private final @Nullable BigDecimal min;
54     private final @Nullable BigDecimal max;
55     private final BigDecimal step;
56     private final Unit<?> unit;
57
58     public NumberValue(@Nullable BigDecimal min, @Nullable BigDecimal max, @Nullable BigDecimal step,
59             @Nullable Unit<?> unit) {
60         super(CoreItemFactory.NUMBER,
61                 List.of(QuantityType.class, IncreaseDecreaseType.class, UpDownType.class, StringType.class));
62         this.min = min;
63         this.max = max;
64         this.step = step == null ? BigDecimal.ONE : step;
65         this.unit = unit != null ? unit : Units.ONE;
66     }
67
68     protected boolean checkConditions(BigDecimal newValue) {
69         BigDecimal min = this.min;
70         if (min != null && newValue.compareTo(min) == -1) {
71             logger.trace("Number not accepted as it is below the configured minimum");
72             return false;
73         }
74         BigDecimal max = this.max;
75         if (max != null && newValue.compareTo(max) == 1) {
76             logger.trace("Number not accepted as it is above the configured maximum");
77             return false;
78         }
79
80         return true;
81     }
82
83     @Override
84     public String getMQTTpublishValue(Command command, @Nullable String pattern) {
85         String formatPattern = pattern;
86         if (formatPattern == null) {
87             formatPattern = "%s";
88         }
89
90         return command.format(formatPattern);
91     }
92
93     @Override
94     public Command parseCommand(Command command) throws IllegalArgumentException {
95         BigDecimal newValue = null;
96         if (command instanceof DecimalType decimalCommand) {
97             newValue = decimalCommand.toBigDecimal();
98         } else if (command instanceof IncreaseDecreaseType || command instanceof UpDownType) {
99             BigDecimal oldValue = getOldValue();
100             if (command == IncreaseDecreaseType.INCREASE || command == UpDownType.UP) {
101                 newValue = oldValue.add(step);
102             } else {
103                 newValue = oldValue.subtract(step);
104             }
105         } else if (command instanceof QuantityType<?> quantityCommand) {
106             newValue = getQuantityTypeAsDecimal(quantityCommand);
107         } else {
108             newValue = new BigDecimal(command.toString());
109         }
110         if (!checkConditions(newValue)) {
111             throw new IllegalArgumentException(newValue + " is out of range");
112         }
113         // items with units specified in the label in the UI but no unit on mqtt are stored as
114         // DecimalType to avoid conversions (e.g. % expects 0-1 rather than 0-100)
115         if (!Units.ONE.equals(unit)) {
116             return new QuantityType<>(newValue, unit);
117         } else {
118             return new DecimalType(newValue);
119         }
120     }
121
122     @Override
123     public Type parseMessage(Command command) throws IllegalArgumentException {
124         if (command instanceof StringType) {
125             if (command.toString().equalsIgnoreCase(NAN) || command.toString().equalsIgnoreCase(NEGATIVE_NAN)) {
126                 return UnDefType.UNDEF;
127             } else if (command.toString().isEmpty()) {
128                 return UnDefType.NULL;
129             }
130         }
131         return parseCommand(command);
132     }
133
134     private BigDecimal getOldValue() {
135         BigDecimal val = BigDecimal.ZERO;
136         if (state instanceof DecimalType decimalCommand) {
137             val = decimalCommand.toBigDecimal();
138         } else if (state instanceof QuantityType<?> quantityCommand) {
139             val = quantityCommand.toBigDecimal();
140         }
141         return val;
142     }
143
144     private BigDecimal getQuantityTypeAsDecimal(QuantityType<?> qType) {
145         BigDecimal val = qType.toBigDecimal();
146         if (!qType.getUnit().isCompatible(Units.ONE)) {
147             QuantityType<?> convertedType = qType.toInvertibleUnit(unit);
148             if (convertedType != null) {
149                 val = convertedType.toBigDecimal();
150             }
151         }
152         return val;
153     }
154
155     @Override
156     public StateDescriptionFragmentBuilder createStateDescription(boolean readOnly) {
157         StateDescriptionFragmentBuilder builder = super.createStateDescription(readOnly);
158         BigDecimal max = this.max;
159         if (max != null) {
160             builder = builder.withMaximum(max);
161         }
162         BigDecimal min = this.min;
163         if (min != null) {
164             builder = builder.withMinimum(min);
165         }
166         if (!unit.equals(Units.ONE)) {
167             builder.withPattern("%s " + unit);
168         } else {
169             builder.withPattern("%s %unit%");
170         }
171         return builder.withStep(step);
172     }
173 }