]> git.basschouten.com Git - openhab-addons.git/blob
c9ad3703e8e0a2e49dbc732eec62f4c5c35a6b9a
[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.generic.values;
14
15 import java.math.BigDecimal;
16 import java.math.MathContext;
17 import java.util.List;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.library.CoreItemFactory;
22 import org.openhab.core.library.types.DecimalType;
23 import org.openhab.core.library.types.IncreaseDecreaseType;
24 import org.openhab.core.library.types.OnOffType;
25 import org.openhab.core.library.types.PercentType;
26 import org.openhab.core.library.types.QuantityType;
27 import org.openhab.core.library.types.StringType;
28 import org.openhab.core.library.types.UpDownType;
29 import org.openhab.core.library.unit.Units;
30 import org.openhab.core.types.Command;
31 import org.openhab.core.types.StateDescriptionFragmentBuilder;
32 import org.openhab.core.types.UnDefType;
33
34 /**
35  * Implements a percentage value. Minimum and maximum are definable.
36  *
37  * <p>
38  * Accepts user updates from a DecimalType, IncreaseDecreaseType and UpDownType.
39  * If this is a percent value, PercentType
40  * </p>
41  * Accepts MQTT state updates as DecimalType, IncreaseDecreaseType and UpDownType
42  * StringType with comma separated HSB ("h,s,b"), RGB ("r,g,b") and on, off strings.
43  * On, Off strings can be customized.
44  *
45  * @author David Graeff - Initial contribution
46  */
47 @NonNullByDefault
48 public class PercentageValue extends Value {
49     private static final BigDecimal HUNDRED = BigDecimal.valueOf(100);
50     private final BigDecimal min;
51     private final BigDecimal max;
52     private final BigDecimal span;
53     private final BigDecimal step;
54     private final BigDecimal stepPercent;
55     private final @Nullable String onValue;
56     private final @Nullable String offValue;
57
58     public PercentageValue(@Nullable BigDecimal min, @Nullable BigDecimal max, @Nullable BigDecimal step,
59             @Nullable String onValue, @Nullable String offValue) {
60         super(CoreItemFactory.DIMMER, List.of(DecimalType.class, QuantityType.class, IncreaseDecreaseType.class,
61                 OnOffType.class, UpDownType.class, StringType.class));
62         this.onValue = onValue;
63         this.offValue = offValue;
64         this.min = min == null ? BigDecimal.ZERO : min;
65         this.max = max == null ? HUNDRED : max;
66         if (this.min.compareTo(this.max) >= 0) {
67             throw new IllegalArgumentException("Min need to be smaller than max!");
68         }
69         this.span = this.max.subtract(this.min);
70         this.step = step == null ? BigDecimal.ONE : step;
71         this.stepPercent = this.step.multiply(HUNDRED).divide(this.span, MathContext.DECIMAL128);
72     }
73
74     @Override
75     public void update(Command command) throws IllegalArgumentException {
76         PercentType oldvalue = (state == UnDefType.UNDEF) ? new PercentType() : (PercentType) state;
77         // Nothing do to -> We have received a percentage
78         if (command instanceof PercentType) {
79             state = (PercentType) command;
80         } else //
81                // A decimal type need to be converted according to the current min/max values
82         if (command instanceof DecimalType) {
83             BigDecimal v = ((DecimalType) command).toBigDecimal();
84             v = v.subtract(min).multiply(HUNDRED).divide(max.subtract(min), MathContext.DECIMAL128);
85             state = new PercentType(v);
86         } else //
87                // A quantity type need to be converted according to the current min/max values
88         if (command instanceof QuantityType) {
89             QuantityType<?> qty = ((QuantityType<?>) command).toUnit(Units.PERCENT);
90             if (qty != null) {
91                 BigDecimal v = qty.toBigDecimal();
92                 v = v.subtract(min).multiply(HUNDRED).divide(max.subtract(min), MathContext.DECIMAL128);
93                 state = new PercentType(v);
94             }
95         } else //
96                // Increase or decrease by "step"
97         if (command instanceof IncreaseDecreaseType) {
98             if (((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE) {
99                 final BigDecimal v = oldvalue.toBigDecimal().add(stepPercent);
100                 state = v.compareTo(HUNDRED) <= 0 ? new PercentType(v) : PercentType.HUNDRED;
101             } else {
102                 final BigDecimal v = oldvalue.toBigDecimal().subtract(stepPercent);
103                 state = v.compareTo(BigDecimal.ZERO) >= 0 ? new PercentType(v) : PercentType.ZERO;
104             }
105         } else //
106                // On/Off equals 100 or 0 percent
107         if (command instanceof OnOffType) {
108             state = ((OnOffType) command) == OnOffType.ON ? PercentType.HUNDRED : PercentType.ZERO;
109         } else//
110               // Increase or decrease by "step"
111         if (command instanceof UpDownType) {
112             if (((UpDownType) command) == UpDownType.UP) {
113                 final BigDecimal v = oldvalue.toBigDecimal().add(stepPercent);
114                 state = v.compareTo(HUNDRED) <= 0 ? new PercentType(v) : PercentType.HUNDRED;
115             } else {
116                 final BigDecimal v = oldvalue.toBigDecimal().subtract(stepPercent);
117                 state = v.compareTo(BigDecimal.ZERO) >= 0 ? new PercentType(v) : PercentType.ZERO;
118             }
119         } else //
120                // Check against custom on/off values
121         if (command instanceof StringType) {
122             if (onValue != null && command.toString().equals(onValue)) {
123                 state = new PercentType(max);
124             } else if (offValue != null && command.toString().equals(offValue)) {
125                 state = new PercentType(min);
126             } else {
127                 throw new IllegalStateException("Unknown String!");
128             }
129         } else {
130             // We are desperate -> Try to parse the command as number value
131             state = PercentType.valueOf(command.toString());
132         }
133     }
134
135     @Override
136     public String getMQTTpublishValue(@Nullable String pattern) {
137         if (state == UnDefType.UNDEF) {
138             return "";
139         }
140         // Formula: From percentage to custom min/max: value*span/100+min
141         // Calculation need to happen with big decimals to either return a straight integer or a decimal depending on
142         // the value.
143         BigDecimal value = ((PercentType) state).toBigDecimal().multiply(span).divide(HUNDRED, MathContext.DECIMAL128)
144                 .add(min).stripTrailingZeros();
145
146         String formatPattern = pattern;
147         if (formatPattern == null) {
148             formatPattern = "%s";
149         }
150
151         return new DecimalType(value).format(formatPattern);
152     }
153
154     @Override
155     public StateDescriptionFragmentBuilder createStateDescription(boolean readOnly) {
156         return super.createStateDescription(readOnly).withMaximum(HUNDRED).withMinimum(BigDecimal.ZERO).withStep(step)
157                 .withPattern("%s %%");
158     }
159 }