]> git.basschouten.com Git - openhab-addons.git/blob
3ae6ee2e427e9f403c007c950ef6dbf74316d6ea
[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             if (command instanceof DecimalType || command instanceof QuantityType<?>) {
88                 formatPattern = "%.0f";
89             } else {
90                 formatPattern = "%s";
91             }
92         }
93
94         return command.format(formatPattern);
95     }
96
97     @Override
98     public Command parseCommand(Command command) throws IllegalArgumentException {
99         BigDecimal newValue = null;
100         if (command instanceof DecimalType decimalCommand) {
101             newValue = decimalCommand.toBigDecimal();
102         } else if (command instanceof IncreaseDecreaseType || command instanceof UpDownType) {
103             BigDecimal oldValue = getOldValue();
104             if (command == IncreaseDecreaseType.INCREASE || command == UpDownType.UP) {
105                 newValue = oldValue.add(step);
106             } else {
107                 newValue = oldValue.subtract(step);
108             }
109         } else if (command instanceof QuantityType<?> quantityCommand) {
110             newValue = getQuantityTypeAsDecimal(quantityCommand);
111         } else {
112             newValue = new BigDecimal(command.toString());
113         }
114         if (!checkConditions(newValue)) {
115             throw new IllegalArgumentException(newValue + " is out of range");
116         }
117         // items with units specified in the label in the UI but no unit on mqtt are stored as
118         // DecimalType to avoid conversions (e.g. % expects 0-1 rather than 0-100)
119         if (!Units.ONE.equals(unit)) {
120             return new QuantityType<>(newValue, unit);
121         } else {
122             return new DecimalType(newValue);
123         }
124     }
125
126     @Override
127     public Type parseMessage(Command command) throws IllegalArgumentException {
128         if (command instanceof StringType) {
129             if (command.toString().equalsIgnoreCase(NAN) || command.toString().equalsIgnoreCase(NEGATIVE_NAN)) {
130                 return UnDefType.UNDEF;
131             } else if (command.toString().isEmpty()) {
132                 return UnDefType.NULL;
133             }
134         }
135         return parseCommand(command);
136     }
137
138     private BigDecimal getOldValue() {
139         BigDecimal val = BigDecimal.ZERO;
140         if (state instanceof DecimalType decimalCommand) {
141             val = decimalCommand.toBigDecimal();
142         } else if (state instanceof QuantityType<?> quantityCommand) {
143             val = quantityCommand.toBigDecimal();
144         }
145         return val;
146     }
147
148     private BigDecimal getQuantityTypeAsDecimal(QuantityType<?> qType) {
149         BigDecimal val = qType.toBigDecimal();
150         if (!qType.getUnit().isCompatible(Units.ONE)) {
151             QuantityType<?> convertedType = qType.toInvertibleUnit(unit);
152             if (convertedType != null) {
153                 val = convertedType.toBigDecimal();
154             }
155         }
156         return val;
157     }
158
159     @Override
160     public StateDescriptionFragmentBuilder createStateDescription(boolean readOnly) {
161         StateDescriptionFragmentBuilder builder = super.createStateDescription(readOnly);
162         BigDecimal max = this.max;
163         if (max != null) {
164             builder = builder.withMaximum(max);
165         }
166         BigDecimal min = this.min;
167         if (min != null) {
168             builder = builder.withMinimum(min);
169         }
170         if (!unit.equals(Units.ONE)) {
171             builder.withPattern("%s " + unit);
172         } else {
173             builder.withPattern("%s %unit%");
174         }
175         return builder.withStep(step);
176     }
177 }