]> git.basschouten.com Git - openhab-addons.git/blob
20b391a757c51f3954130dfd38110a6d4c0e917c
[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                 && (command.toString().equalsIgnoreCase(NAN) || command.toString().equalsIgnoreCase(NEGATIVE_NAN))) {
126             return UnDefType.UNDEF;
127         }
128         return parseCommand(command);
129     }
130
131     private BigDecimal getOldValue() {
132         BigDecimal val = BigDecimal.ZERO;
133         if (state instanceof DecimalType decimalCommand) {
134             val = decimalCommand.toBigDecimal();
135         } else if (state instanceof QuantityType<?> quantityCommand) {
136             val = quantityCommand.toBigDecimal();
137         }
138         return val;
139     }
140
141     private BigDecimal getQuantityTypeAsDecimal(QuantityType<?> qType) {
142         BigDecimal val = qType.toBigDecimal();
143         if (!qType.getUnit().isCompatible(Units.ONE)) {
144             QuantityType<?> convertedType = qType.toInvertibleUnit(unit);
145             if (convertedType != null) {
146                 val = convertedType.toBigDecimal();
147             }
148         }
149         return val;
150     }
151
152     @Override
153     public StateDescriptionFragmentBuilder createStateDescription(boolean readOnly) {
154         StateDescriptionFragmentBuilder builder = super.createStateDescription(readOnly);
155         BigDecimal max = this.max;
156         if (max != null) {
157             builder = builder.withMaximum(max);
158         }
159         BigDecimal min = this.min;
160         if (min != null) {
161             builder = builder.withMinimum(min);
162         }
163         if (!unit.equals(Units.ONE)) {
164             builder.withPattern("%s " + unit);
165         } else {
166             builder.withPattern("%s %unit%");
167         }
168         return builder.withStep(step);
169     }
170 }