]> git.basschouten.com Git - openhab-addons.git/blob
b2ddce8c7c88d778311d40dcd023fa8ebdcd00bd
[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.util.List;
17 import java.util.Locale;
18
19 import javax.ws.rs.NotSupportedException;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.mqtt.generic.mapping.ColorMode;
24 import org.openhab.core.library.CoreItemFactory;
25 import org.openhab.core.library.types.HSBType;
26 import org.openhab.core.library.types.OnOffType;
27 import org.openhab.core.library.types.PercentType;
28 import org.openhab.core.library.types.StringType;
29 import org.openhab.core.types.Command;
30 import org.openhab.core.types.UnDefType;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Implements a color value.
36  *
37  * <p>
38  * Accepts user updates from a HSBType, OnOffType and StringType.
39  * </p>
40  * Accepts MQTT state updates as OnOffType and a
41  * StringType with comma separated HSB ("h,s,b"), RGB ("r,g,b"), CIE xyY ("x,y,Y") and on, off strings.
42  * On, Off strings can be customized.
43  *
44  * @author David Graeff - Initial contribution
45  * @author Aitor Iturrioz - Add CIE xyY colors support
46  */
47 @NonNullByDefault
48 public class ColorValue extends Value {
49     private static BigDecimal factor = new BigDecimal("2.55"); // string to not lose precision
50
51     private final Logger logger = LoggerFactory.getLogger(ColorValue.class);
52
53     private final ColorMode colorMode;
54     private final String onValue;
55     private final String offValue;
56     private final int onBrightness;
57
58     /**
59      * Creates a non initialized color value.
60      *
61      * @param colorMode The color mode: HSB, RGB or XYY.
62      * @param onValue The ON value string. This will be compared to MQTT messages.
63      * @param offValue The OFF value string. This will be compared to MQTT messages.
64      * @param onBrightness When receiving an ON command, the brightness percentage is set to this value
65      */
66     public ColorValue(ColorMode colorMode, @Nullable String onValue, @Nullable String offValue, int onBrightness) {
67         super(CoreItemFactory.COLOR, List.of(OnOffType.class, PercentType.class, StringType.class));
68
69         if (onBrightness > 100) {
70             throw new IllegalArgumentException("Brightness parameter must be <= 100");
71         }
72
73         this.colorMode = colorMode;
74         this.onValue = onValue == null ? "ON" : onValue;
75         this.offValue = offValue == null ? "OFF" : offValue;
76         this.onBrightness = onBrightness;
77     }
78
79     /**
80      * Updates the color state.
81      */
82     @Override
83     public void update(Command command) throws IllegalArgumentException {
84         HSBType oldvalue = (state == UnDefType.UNDEF) ? new HSBType() : (HSBType) state;
85         if (command instanceof HSBType) {
86             state = (HSBType) command;
87         } else if (command instanceof OnOffType) {
88             OnOffType boolValue = ((OnOffType) command);
89             PercentType minOn = new PercentType(Math.max(oldvalue.getBrightness().intValue(), onBrightness));
90             state = new HSBType(oldvalue.getHue(), oldvalue.getSaturation(),
91                     boolValue == OnOffType.ON ? minOn : new PercentType(0));
92         } else if (command instanceof PercentType) {
93             state = new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), (PercentType) command);
94         } else {
95             final String updatedValue = command.toString();
96             if (onValue.equals(updatedValue)) {
97                 PercentType minOn = new PercentType(Math.max(oldvalue.getBrightness().intValue(), onBrightness));
98                 state = new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), minOn);
99             } else if (offValue.equals(updatedValue)) {
100                 state = new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), new PercentType(0));
101             } else {
102                 String[] split = updatedValue.split(",");
103                 if (split.length != 3) {
104                     throw new IllegalArgumentException(updatedValue + " is not a valid string syntax");
105                 }
106                 switch (this.colorMode) {
107                     case HSB:
108                         state = new HSBType(updatedValue);
109                         break;
110                     case RGB:
111                         state = HSBType.fromRGB(Integer.parseInt(split[0]), Integer.parseInt(split[1]),
112                                 Integer.parseInt(split[2]));
113                         break;
114                     case XYY:
115                         HSBType tempState = HSBType.fromXY(Float.parseFloat(split[0]), Float.parseFloat(split[1]));
116                         state = new HSBType(tempState.getHue(), tempState.getSaturation(), new PercentType(split[2]));
117                         break;
118                     default:
119                         logger.warn("Non supported color mode");
120                 }
121             }
122         }
123     }
124
125     /**
126      * Converts the color state to a string.
127      *
128      * @return Returns the color value depending on the color mode: as a HSB/HSV string (hue,saturation,brightness ->
129      *         "60,100,100"), as an RGB string (red,green,blue -> "255,255,0") or as a xyY string
130      *         ("0.419321,0.505255,100.00").
131      */
132     @Override
133     public String getMQTTpublishValue(@Nullable String pattern) {
134         if (state == UnDefType.UNDEF) {
135             return "";
136         }
137
138         String formatPattern = pattern;
139         if (formatPattern == null || "%s".equals(formatPattern)) {
140             if (this.colorMode == ColorMode.XYY) {
141                 formatPattern = "%1$f,%2$f,%3$.2f";
142             } else {
143                 formatPattern = "%1$d,%2$d,%3$d";
144             }
145         }
146
147         HSBType hsbState = (HSBType) state;
148
149         switch (this.colorMode) {
150             case HSB:
151                 return String.format(formatPattern, hsbState.getHue().intValue(), hsbState.getSaturation().intValue(),
152                         hsbState.getBrightness().intValue());
153             case RGB:
154                 PercentType[] rgb = hsbState.toRGB();
155                 return String.format(formatPattern, rgb[0].toBigDecimal().multiply(factor).intValue(),
156                         rgb[1].toBigDecimal().multiply(factor).intValue(),
157                         rgb[2].toBigDecimal().multiply(factor).intValue());
158             case XYY:
159                 PercentType[] xyY = hsbState.toXY();
160                 return String.format(Locale.ROOT, formatPattern, xyY[0].floatValue() / 100.0f,
161                         xyY[1].floatValue() / 100.0f, hsbState.getBrightness().floatValue());
162             default:
163                 throw new NotSupportedException(String.format("Non supported color mode: {}", this.colorMode));
164         }
165     }
166 }