]> git.basschouten.com Git - openhab-addons.git/blob
4895e6cdccc58b729a54cc9a18eaa29bcb0d08e1
[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.homeassistant.internal.component;
14
15 import java.math.BigDecimal;
16 import java.math.MathContext;
17 import java.util.List;
18 import java.util.Objects;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
23 import org.openhab.binding.mqtt.generic.values.TextValue;
24 import org.openhab.binding.mqtt.homeassistant.internal.ComponentChannelType;
25 import org.openhab.core.library.types.DecimalType;
26 import org.openhab.core.library.types.HSBType;
27 import org.openhab.core.library.types.OnOffType;
28 import org.openhab.core.library.types.PercentType;
29 import org.openhab.core.library.types.QuantityType;
30 import org.openhab.core.library.types.StringType;
31 import org.openhab.core.library.unit.Units;
32 import org.openhab.core.thing.ChannelUID;
33 import org.openhab.core.types.Command;
34 import org.openhab.core.types.State;
35 import org.openhab.core.types.UnDefType;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.gson.JsonSyntaxException;
40 import com.google.gson.annotations.SerializedName;
41
42 /**
43  * A MQTT light, following the https://www.home-assistant.io/components/light.mqtt/ specification.
44  *
45  * Specifically, the JSON schema. All channels are synthetic, and wrap the single internal raw
46  * state.
47  *
48  * @author Cody Cutrer - Initial contribution
49  */
50 @NonNullByDefault
51 public class JSONSchemaLight extends AbstractRawSchemaLight {
52     private static final BigDecimal SCALE_FACTOR = new BigDecimal("2.55"); // string to not lose precision
53     private static final BigDecimal BIG_DECIMAL_HUNDRED = new BigDecimal(100);
54
55     private final Logger logger = LoggerFactory.getLogger(JSONSchemaLight.class);
56
57     private static class JSONState {
58         protected static class Color {
59             protected @Nullable Integer r, g, b, c, w;
60             protected @Nullable BigDecimal x, y, h, s;
61         }
62
63         protected @Nullable String state;
64         protected @Nullable Integer brightness;
65         @SerializedName("color_mode")
66         protected @Nullable LightColorMode colorMode;
67         @SerializedName("color_temp")
68         protected @Nullable Integer colorTemp;
69         protected @Nullable Color color;
70         protected @Nullable String effect;
71         protected @Nullable Integer transition;
72     }
73
74     TextValue colorModeValue;
75
76     public JSONSchemaLight(ComponentFactory.ComponentConfiguration builder, boolean newStyleChannels) {
77         super(builder, newStyleChannels);
78         colorModeValue = new TextValue();
79     }
80
81     @Override
82     protected void buildChannels() {
83         List<LightColorMode> supportedColorModes = channelConfiguration.supportedColorModes;
84         if (supportedColorModes != null) {
85             if (LightColorMode.hasColorChannel(supportedColorModes)) {
86                 hasColorChannel = true;
87             }
88
89             if (supportedColorModes.contains(LightColorMode.COLOR_MODE_COLOR_TEMP)) {
90                 buildChannel(COLOR_TEMP_CHANNEL_ID, ComponentChannelType.NUMBER, colorTempValue, "Color Temperature",
91                         this).commandTopic(DUMMY_TOPIC, true, 1)
92                         .commandFilter(command -> handleColorTempCommand(command)).build();
93
94                 if (hasColorChannel) {
95                     colorModeValue = new TextValue(
96                             supportedColorModes.stream().map(LightColorMode::serializedName).toArray(String[]::new));
97                     buildChannel(COLOR_MODE_CHANNEL_ID, ComponentChannelType.STRING, colorModeValue, "Color Mode", this)
98                             .isAdvanced(true).build();
99
100                 }
101             }
102         }
103
104         if (hasColorChannel) {
105             buildChannel(COLOR_CHANNEL_ID, ComponentChannelType.COLOR, colorValue, "Color", this)
106                     .commandTopic(DUMMY_TOPIC, true, 1).commandFilter(this::handleCommand).build();
107         } else if (channelConfiguration.brightness) {
108             brightnessChannel = buildChannel(BRIGHTNESS_CHANNEL_ID, ComponentChannelType.DIMMER, brightnessValue,
109                     "Brightness", this).commandTopic(DUMMY_TOPIC, true, 1).commandFilter(this::handleCommand).build();
110         } else {
111             onOffChannel = buildChannel(ON_OFF_CHANNEL_ID, ComponentChannelType.SWITCH, onOffValue, "On/Off State",
112                     this).commandTopic(DUMMY_TOPIC, true, 1).commandFilter(this::handleCommand).build();
113         }
114
115         if (effectValue != null) {
116             buildChannel(EFFECT_CHANNEL_ID, ComponentChannelType.STRING, Objects.requireNonNull(effectValue),
117                     "Lighting Effect", this).commandTopic(DUMMY_TOPIC, true, 1)
118                     .commandFilter(command -> handleEffectCommand(command)).build();
119
120         }
121     }
122
123     private boolean handleEffectCommand(Command command) {
124         if (command instanceof StringType) {
125             JSONState json = new JSONState();
126             json.state = "ON";
127             json.effect = command.toString();
128             publishState(json);
129         }
130         return false;
131     }
132
133     @Override
134     protected void publishState(HSBType state) {
135         JSONState json = new JSONState();
136
137         logger.trace("Publishing new state {} of light {} to MQTT.", state, getName());
138         if (state.getBrightness().equals(PercentType.ZERO)) {
139             json.state = "OFF";
140         } else {
141             json.state = "ON";
142             if (channelConfiguration.brightness || (channelConfiguration.supportedColorModes != null
143                     && (channelConfiguration.supportedColorModes.contains(LightColorMode.COLOR_MODE_HS)
144                             || channelConfiguration.supportedColorModes.contains(LightColorMode.COLOR_MODE_XY)))) {
145                 json.brightness = state.getBrightness().toBigDecimal()
146                         .multiply(new BigDecimal(channelConfiguration.brightnessScale))
147                         .divide(new BigDecimal(100), MathContext.DECIMAL128).intValue();
148             }
149
150             if (hasColorChannel) {
151                 json.color = new JSONState.Color();
152                 if (channelConfiguration.supportedColorModes.contains(LightColorMode.COLOR_MODE_HS)) {
153                     json.color.h = state.getHue().toBigDecimal();
154                     json.color.s = state.getSaturation().toBigDecimal().divide(BIG_DECIMAL_HUNDRED);
155                 } else if (LightColorMode.hasRGB(Objects.requireNonNull(channelConfiguration.supportedColorModes))) {
156                     var rgb = state.toRGB();
157                     json.color.r = rgb[0].toBigDecimal().multiply(SCALE_FACTOR).intValue();
158                     json.color.g = rgb[1].toBigDecimal().multiply(SCALE_FACTOR).intValue();
159                     json.color.b = rgb[2].toBigDecimal().multiply(SCALE_FACTOR).intValue();
160                 } else { // if (channelConfiguration.supportedColorModes.contains(COLOR_MODE_XY))
161                     var xy = state.toXY();
162                     json.color.x = xy[0].toBigDecimal().divide(BIG_DECIMAL_HUNDRED);
163                     json.color.y = xy[1].toBigDecimal().divide(BIG_DECIMAL_HUNDRED);
164                 }
165             }
166         }
167
168         publishState(json);
169     }
170
171     private void publishState(JSONState json) {
172         String command = getGson().toJson(json);
173         logger.debug("Publishing new state '{}' of light {} to MQTT.", command, getName());
174         rawChannel.getState().publishValue(new StringType(command));
175     }
176
177     @Override
178     protected boolean handleCommand(Command command) {
179         JSONState json = new JSONState();
180         if (command.getClass().equals(OnOffType.class)) {
181             json.state = command.toString();
182         } else if (command.getClass().equals(PercentType.class)) {
183             if (command.equals(PercentType.ZERO)) {
184                 json.state = "OFF";
185             } else {
186                 json.state = "ON";
187                 if (channelConfiguration.brightness) {
188                     json.brightness = ((PercentType) command).toBigDecimal()
189                             .multiply(new BigDecimal(channelConfiguration.brightnessScale))
190                             .divide(new BigDecimal(100), MathContext.DECIMAL128).intValue();
191                 }
192             }
193         } else {
194             return super.handleCommand(command);
195         }
196
197         String jsonCommand = getGson().toJson(json);
198         logger.debug("Publishing new state '{}' of light {} to MQTT.", jsonCommand, getName());
199         rawChannel.getState().publishValue(new StringType(jsonCommand));
200         return false;
201     }
202
203     private boolean handleColorTempCommand(Command command) {
204         JSONState json = new JSONState();
205
206         if (command instanceof DecimalType) {
207             command = new QuantityType<>(((DecimalType) command).toBigDecimal(), Units.MIRED);
208         }
209         if (command instanceof QuantityType) {
210             QuantityType<?> mireds = ((QuantityType<?>) command).toInvertibleUnit(Units.MIRED);
211             if (mireds == null) {
212                 logger.warn("Unable to convert {} to mireds", command);
213                 return false;
214             }
215             json.state = "ON";
216             json.colorTemp = mireds.toBigDecimal().intValue();
217         } else {
218             return false;
219         }
220
221         String jsonCommand = getGson().toJson(json);
222         logger.debug("Publishing new state '{}' of light {} to MQTT.", jsonCommand, getName());
223         rawChannel.getState().publishValue(new StringType(jsonCommand));
224         return false;
225     }
226
227     @Override
228     public void updateChannelState(ChannelUID channel, State state) {
229         ChannelStateUpdateListener listener = this.channelStateUpdateListener;
230
231         @Nullable
232         JSONState jsonState;
233         try {
234             jsonState = getGson().fromJson(state.toString(), JSONState.class);
235
236             if (jsonState == null) {
237                 logger.warn("JSON light state for '{}' is empty.", getHaID());
238                 return;
239             }
240         } catch (JsonSyntaxException e) {
241             logger.warn("Cannot parse JSON light state '{}' for '{}'.", state, getHaID());
242             return;
243         }
244
245         if (effectValue != null) {
246             if (jsonState.effect != null) {
247                 effectValue.update(new StringType(jsonState.effect));
248                 listener.updateChannelState(buildChannelUID(EFFECT_CHANNEL_ID), effectValue.getChannelState());
249             } else {
250                 listener.updateChannelState(buildChannelUID(EFFECT_CHANNEL_ID), UnDefType.NULL);
251             }
252         }
253
254         boolean off = false;
255         if (jsonState.state != null) {
256             onOffValue.update((State) onOffValue.parseMessage(new StringType(jsonState.state)));
257             off = onOffValue.getChannelState().equals(OnOffType.OFF);
258             if (onOffValue.getChannelState() instanceof OnOffType onOffState) {
259                 if (brightnessValue.getChannelState() instanceof UnDefType) {
260                     brightnessValue.update(Objects.requireNonNull(onOffState.as(PercentType.class)));
261                 }
262                 if (colorValue.getChannelState() instanceof UnDefType) {
263                     colorValue.update(Objects.requireNonNull(onOffState.as(PercentType.class)));
264                 }
265             }
266         }
267
268         PercentType brightness;
269         if (off) {
270             brightness = PercentType.ZERO;
271         } else if (brightnessValue.getChannelState() instanceof PercentType percentValue) {
272             brightness = percentValue;
273         } else {
274             brightness = PercentType.HUNDRED;
275         }
276
277         if (jsonState.brightness != null) {
278             if (!off) {
279                 brightness = (PercentType) brightnessValue
280                         .parseMessage(new DecimalType(Objects.requireNonNull(jsonState.brightness)));
281             }
282             brightnessValue.update(brightness);
283             if (colorValue.getChannelState() instanceof HSBType) {
284                 HSBType color = (HSBType) colorValue.getChannelState();
285                 colorValue.update(new HSBType(color.getHue(), color.getSaturation(), brightness));
286             } else {
287                 colorValue.update(new HSBType(DecimalType.ZERO, PercentType.ZERO, brightness));
288             }
289         }
290
291         if (jsonState.colorTemp != null) {
292             colorTempValue.update(new QuantityType(Objects.requireNonNull(jsonState.colorTemp), Units.MIRED));
293             listener.updateChannelState(buildChannelUID(COLOR_TEMP_CHANNEL_ID), colorTempValue.getChannelState());
294
295             colorModeValue.update(new StringType(LightColorMode.COLOR_MODE_COLOR_TEMP.serializedName()));
296         }
297
298         if (jsonState.color != null) {
299             // This corresponds to "deprecated" color mode handling, since we're not checking which color
300             // mode is currently active.
301             // HS is highest priority, then XY, then RGB
302             // See
303             // https://github.com/home-assistant/core/blob/4f965f0eca09f0d12ae1c98c6786054063a36b44/homeassistant/components/mqtt/light/schema_json.py#L258
304             if (jsonState.color.h != null && jsonState.color.s != null) {
305                 colorValue.update(new HSBType(new DecimalType(Objects.requireNonNull(jsonState.color.h)),
306                         new PercentType(Objects.requireNonNull(jsonState.color.s)), brightness));
307                 colorModeValue.update(new StringType(LightColorMode.COLOR_MODE_HS.serializedName()));
308             } else if (jsonState.color.x != null && jsonState.color.y != null) {
309                 HSBType newColor = HSBType.fromXY(jsonState.color.x.floatValue(), jsonState.color.y.floatValue());
310                 colorValue.update(new HSBType(newColor.getHue(), newColor.getSaturation(), brightness));
311                 colorModeValue.update(new StringType(LightColorMode.COLOR_MODE_XY.serializedName()));
312             } else if (jsonState.color.r != null && jsonState.color.g != null && jsonState.color.b != null) {
313                 colorValue.update(HSBType.fromRGB(jsonState.color.r, jsonState.color.g, jsonState.color.b));
314                 colorModeValue.update(new StringType(LightColorMode.COLOR_MODE_RGB.serializedName()));
315             }
316         }
317
318         if (jsonState.colorMode != null) {
319             colorModeValue.update(new StringType(jsonState.colorMode.serializedName()));
320         }
321
322         listener.updateChannelState(buildChannelUID(COLOR_MODE_CHANNEL_ID), colorModeValue.getChannelState());
323
324         if (hasColorChannel) {
325             listener.updateChannelState(buildChannelUID(COLOR_CHANNEL_ID), colorValue.getChannelState());
326         } else if (brightnessChannel != null) {
327             listener.updateChannelState(buildChannelUID(BRIGHTNESS_CHANNEL_ID), brightnessValue.getChannelState());
328         } else {
329             listener.updateChannelState(buildChannelUID(ON_OFF_CHANNEL_ID), onOffValue.getChannelState());
330         }
331     }
332 }