]> git.basschouten.com Git - openhab-addons.git/blob
8dfe010cab2c8347d25dc4ceafdf1ccfc19c59e5
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.deconz.internal.handler;
14
15 import static org.openhab.binding.deconz.internal.BindingConstants.*;
16 import static org.openhab.binding.deconz.internal.Util.*;
17
18 import java.math.BigDecimal;
19 import java.util.*;
20 import java.util.stream.Collectors;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.deconz.internal.CommandDescriptionProvider;
25 import org.openhab.binding.deconz.internal.StateDescriptionProvider;
26 import org.openhab.binding.deconz.internal.Util;
27 import org.openhab.binding.deconz.internal.dto.DeconzBaseMessage;
28 import org.openhab.binding.deconz.internal.dto.LightMessage;
29 import org.openhab.binding.deconz.internal.dto.LightState;
30 import org.openhab.binding.deconz.internal.types.ResourceType;
31 import org.openhab.core.library.types.*;
32 import org.openhab.core.thing.ChannelUID;
33 import org.openhab.core.thing.Thing;
34 import org.openhab.core.thing.ThingStatus;
35 import org.openhab.core.thing.ThingStatusDetail;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.thing.binding.builder.ChannelBuilder;
38 import org.openhab.core.thing.binding.builder.ThingBuilder;
39 import org.openhab.core.types.*;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import com.google.gson.Gson;
44
45 /**
46  * This light thing doesn't establish any connections, that is done by the bridge Thing.
47  *
48  * It waits for the bridge to come online, grab the websocket connection and bridge configuration
49  * and registers to the websocket connection as a listener.
50  *
51  * A REST API call is made to get the initial light/rollershutter state.
52  *
53  * Every light and rollershutter is supported by this Thing, because a unified state is kept
54  * in {@link #lightStateCache}. Every field that got received by the REST API for this specific
55  * sensor is published to the framework.
56  *
57  * @author Jan N. Klug - Initial contribution
58  */
59 @NonNullByDefault
60 public class LightThingHandler extends DeconzBaseThingHandler {
61     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Set.of(THING_TYPE_COLOR_TEMPERATURE_LIGHT,
62             THING_TYPE_DIMMABLE_LIGHT, THING_TYPE_COLOR_LIGHT, THING_TYPE_EXTENDED_COLOR_LIGHT, THING_TYPE_ONOFF_LIGHT,
63             THING_TYPE_WINDOW_COVERING, THING_TYPE_WARNING_DEVICE, THING_TYPE_DOORLOCK);
64
65     private static final long DEFAULT_COMMAND_EXPIRY_TIME = 250; // in ms
66     private static final int BRIGHTNESS_DIM_STEP = 26; // ~ 10%
67
68     private final Logger logger = LoggerFactory.getLogger(LightThingHandler.class);
69
70     private final StateDescriptionProvider stateDescriptionProvider;
71     private final CommandDescriptionProvider commandDescriptionProvider;
72
73     private long lastCommandExpireTimestamp = 0;
74     private boolean needsPropertyUpdate = false;
75
76     /**
77      * The light state. Contains all possible fields for all supported lights
78      */
79     private LightState lightStateCache = new LightState();
80     private LightState lastCommand = new LightState();
81
82     // set defaults, we can override them later if we receive better values
83     private int ctMax = ZCL_CT_MAX;
84     private int ctMin = ZCL_CT_MIN;
85
86     public LightThingHandler(Thing thing, Gson gson, StateDescriptionProvider stateDescriptionProvider,
87             CommandDescriptionProvider commandDescriptionProvider) {
88         super(thing, gson, ResourceType.LIGHTS);
89         this.stateDescriptionProvider = stateDescriptionProvider;
90         this.commandDescriptionProvider = commandDescriptionProvider;
91     }
92
93     @Override
94     public void initialize() {
95         if (thing.getThingTypeUID().equals(THING_TYPE_COLOR_TEMPERATURE_LIGHT)
96                 || thing.getThingTypeUID().equals(THING_TYPE_EXTENDED_COLOR_LIGHT)) {
97             try {
98                 Map<String, String> properties = thing.getProperties();
99                 String ctMaxString = properties.get(PROPERTY_CT_MAX);
100                 ctMax = ctMaxString == null ? ZCL_CT_MAX : Integer.parseInt(ctMaxString);
101                 String ctMinString = properties.get(PROPERTY_CT_MIN);
102                 ctMin = ctMinString == null ? ZCL_CT_MIN : Integer.parseInt(ctMinString);
103
104                 // minimum and maximum are inverted due to mired/kelvin conversion!
105                 StateDescription stateDescription = StateDescriptionFragmentBuilder.create()
106                         .withMinimum(new BigDecimal(miredToKelvin(ctMax)))
107                         .withMaximum(new BigDecimal(miredToKelvin(ctMin))).build().toStateDescription();
108                 if (stateDescription != null) {
109                     stateDescriptionProvider.setDescription(new ChannelUID(thing.getUID(), CHANNEL_COLOR_TEMPERATURE),
110                             stateDescription);
111                 } else {
112                     logger.warn("Failed to create state description in thing {}", thing.getUID());
113                 }
114             } catch (NumberFormatException e) {
115                 needsPropertyUpdate = true;
116             }
117         }
118         super.initialize();
119     }
120
121     @Override
122     public void handleCommand(ChannelUID channelUID, Command command) {
123         if (command instanceof RefreshType) {
124             valueUpdated(channelUID.getId(), lightStateCache);
125             return;
126         }
127
128         LightState newLightState = new LightState();
129         Boolean currentOn = lightStateCache.on;
130         Integer currentBri = lightStateCache.bri;
131
132         switch (channelUID.getId()) {
133             case CHANNEL_ALERT:
134                 if (command instanceof OnOffType) {
135                     newLightState.alert = command == OnOffType.ON ? "alert" : "none";
136                 } else {
137                     return;
138                 }
139                 break;
140             case CHANNEL_EFFECT:
141                 if (command instanceof StringType) {
142                     // effect command only allowed for lights that are turned on
143                     newLightState.on = true;
144                     newLightState.effect = command.toString();
145                 } else {
146                     return;
147                 }
148                 break;
149             case CHANNEL_EFFECT_SPEED:
150                 if (command instanceof DecimalType) {
151                     newLightState.on = true;
152                     newLightState.effectSpeed = Util.constrainToRange(((DecimalType) command).intValue(), 0, 10);
153                 } else {
154                     return;
155                 }
156                 break;
157             case CHANNEL_SWITCH:
158             case CHANNEL_LOCK:
159                 if (command instanceof OnOffType) {
160                     newLightState.on = (command == OnOffType.ON);
161                 } else {
162                     return;
163                 }
164                 break;
165             case CHANNEL_BRIGHTNESS:
166             case CHANNEL_COLOR:
167                 if (command instanceof OnOffType) {
168                     newLightState.on = (command == OnOffType.ON);
169                 } else if (command instanceof IncreaseDecreaseType) {
170                     // try to get best value for current brightness
171                     int oldBri = currentBri != null ? currentBri
172                             : (Boolean.TRUE.equals(currentOn) ? BRIGHTNESS_MAX : BRIGHTNESS_MIN);
173                     if (command.equals(IncreaseDecreaseType.INCREASE)) {
174                         newLightState.bri = Util.constrainToRange(oldBri + BRIGHTNESS_DIM_STEP, BRIGHTNESS_MIN,
175                                 BRIGHTNESS_MAX);
176                     } else {
177                         newLightState.bri = Util.constrainToRange(oldBri - BRIGHTNESS_DIM_STEP, BRIGHTNESS_MIN,
178                                 BRIGHTNESS_MAX);
179                     }
180                 } else if (command instanceof HSBType) {
181                     HSBType hsbCommand = (HSBType) command;
182                     if ("xy".equals(lightStateCache.colormode)) {
183                         PercentType[] xy = hsbCommand.toXY();
184                         if (xy.length < 2) {
185                             logger.warn("Failed to convert {} to xy-values", command);
186                         }
187                         newLightState.xy = new double[] { xy[0].doubleValue() / 100.0, xy[1].doubleValue() / 100.0 };
188                         newLightState.bri = Util.fromPercentType(hsbCommand.getBrightness());
189                     } else {
190                         // default is colormode "hs" (used when colormode "hs" is set or colormode is unknown)
191                         newLightState.bri = Util.fromPercentType(hsbCommand.getBrightness());
192                         newLightState.hue = (int) (hsbCommand.getHue().doubleValue() * HUE_FACTOR);
193                         newLightState.sat = Util.fromPercentType(hsbCommand.getSaturation());
194                     }
195                 } else if (command instanceof PercentType) {
196                     newLightState.bri = Util.fromPercentType((PercentType) command);
197                 } else if (command instanceof DecimalType) {
198                     newLightState.bri = ((DecimalType) command).intValue();
199                 } else {
200                     return;
201                 }
202
203                 // send on/off state together with brightness if not already set or unknown
204                 Integer newBri = newLightState.bri;
205                 if (newBri != null) {
206                     newLightState.on = (newBri > 0);
207                 }
208
209                 // fix sending bri=0 when light is already off
210                 if (newBri != null && newBri == 0 && currentOn != null && !currentOn) {
211                     return;
212                 }
213
214                 Double transitiontime = config.transitiontime;
215                 if (transitiontime != null) {
216                     // value is in 1/10 seconds
217                     newLightState.transitiontime = (int) Math.round(10 * transitiontime);
218                 }
219                 break;
220             case CHANNEL_COLOR_TEMPERATURE:
221                 if (command instanceof DecimalType) {
222                     int miredValue = kelvinToMired(((DecimalType) command).intValue());
223                     newLightState.ct = constrainToRange(miredValue, ctMin, ctMax);
224                     newLightState.on = true;
225                 }
226                 break;
227             case CHANNEL_POSITION:
228                 if (command instanceof UpDownType) {
229                     newLightState.on = (command == UpDownType.DOWN);
230                 } else if (command == StopMoveType.STOP) {
231                     if (currentOn != null && currentOn && currentBri != null && currentBri <= BRIGHTNESS_MAX) {
232                         // going down or currently stop (254 because of rounding error)
233                         newLightState.on = true;
234                     } else if (currentOn != null && !currentOn && currentBri != null && currentBri > BRIGHTNESS_MIN) {
235                         // going up or currently stopped
236                         newLightState.on = false;
237                     }
238                 } else if (command instanceof PercentType) {
239                     newLightState.bri = fromPercentType((PercentType) command);
240                 } else {
241                     return;
242                 }
243                 break;
244             default:
245                 // no supported command
246                 return;
247         }
248
249         Boolean newOn = newLightState.on;
250         if (newOn != null && !newOn) {
251             // if light shall be off, no other commands are allowed, so reset the new light state
252             newLightState.clear();
253             newLightState.on = false;
254         }
255
256         sendCommand(newLightState, command, channelUID, () -> {
257             Integer transitionTime = newLightState.transitiontime;
258             lastCommandExpireTimestamp = System.currentTimeMillis()
259                     + (transitionTime != null ? transitionTime : DEFAULT_COMMAND_EXPIRY_TIME);
260             lastCommand = newLightState;
261         });
262     }
263
264     @Override
265     protected void processStateResponse(DeconzBaseMessage stateResponse) {
266         if (!(stateResponse instanceof LightMessage)) {
267             return;
268         }
269
270         LightMessage lightMessage = (LightMessage) stateResponse;
271         if (needsPropertyUpdate) {
272             // if we did not receive an ctmin/ctmax, then we probably don't need it
273             needsPropertyUpdate = false;
274
275             Integer ctmax = lightMessage.ctmax;
276             Integer ctmin = lightMessage.ctmin;
277             if (ctmin != null && ctmax != null) {
278                 Map<String, String> properties = new HashMap<>(thing.getProperties());
279                 properties.put(PROPERTY_CT_MAX, Integer.toString(Util.constrainToRange(ctmax, ZCL_CT_MIN, ZCL_CT_MAX)));
280                 properties.put(PROPERTY_CT_MIN, Integer.toString(Util.constrainToRange(ctmin, ZCL_CT_MIN, ZCL_CT_MAX)));
281                 updateProperties(properties);
282             }
283         }
284
285         LightState lightState = lightMessage.state;
286         if (lightState != null && lightState.effect != null) {
287             checkAndUpdateEffectChannels(lightMessage);
288         }
289
290         messageReceived(config.id, lightMessage);
291     }
292
293     private enum EffectLightModel {
294         LIDL_MELINARA,
295         TINT_MUELLER,
296         UNKNOWN;
297     }
298
299     private void checkAndUpdateEffectChannels(LightMessage lightMessage) {
300         EffectLightModel model = EffectLightModel.UNKNOWN;
301         // try to determine which model we have
302         if (lightMessage.manufacturername.equals("_TZE200_s8gkrkxk")) {
303             // the LIDL Melinara string does not report a proper model name
304             model = EffectLightModel.LIDL_MELINARA;
305         } else if (lightMessage.manufacturername.equals("MLI")) {
306             model = EffectLightModel.TINT_MUELLER;
307         } else {
308             logger.info("Could not determine effect light type for thing {}, please request adding support on GitHub.",
309                     thing.getUID());
310         }
311
312         ChannelUID effectChannelUID = new ChannelUID(thing.getUID(), CHANNEL_EFFECT);
313         ChannelUID effectSpeedChannelUID = new ChannelUID(thing.getUID(), CHANNEL_EFFECT_SPEED);
314
315         if (thing.getChannel(CHANNEL_EFFECT) == null) {
316             ThingBuilder thingBuilder = editThing();
317             thingBuilder.withChannel(
318                     ChannelBuilder.create(effectChannelUID, "String").withType(CHANNEL_EFFECT_TYPE_UID).build());
319             if (model == EffectLightModel.LIDL_MELINARA) {
320                 // additional channels
321                 thingBuilder.withChannel(ChannelBuilder.create(effectSpeedChannelUID, "Number")
322                         .withType(CHANNEL_EFFECT_SPEED_TYPE_UID).build());
323             }
324             updateThing(thingBuilder.build());
325         }
326
327         switch (model) {
328             case LIDL_MELINARA:
329                 List<String> options = List.of("none", "steady", "snow", "rainbow", "snake", "tinkle", "fireworks",
330                         "flag", "waves", "updown", "vintage", "fading", "collide", "strobe", "sparkles", "carnival",
331                         "glow");
332                 commandDescriptionProvider.setDescription(effectChannelUID,
333                         CommandDescriptionBuilder.create().withCommandOptions(toCommandOptionList(options)).build());
334                 break;
335             case TINT_MUELLER:
336                 options = List.of("none", "colorloop", "sunset", "party", "worklight", "campfire", "romance",
337                         "nightlight");
338                 commandDescriptionProvider.setDescription(effectChannelUID,
339                         CommandDescriptionBuilder.create().withCommandOptions(toCommandOptionList(options)).build());
340                 break;
341             default:
342                 options = List.of("none", "colorloop");
343                 commandDescriptionProvider.setDescription(effectChannelUID,
344                         CommandDescriptionBuilder.create().withCommandOptions(toCommandOptionList(options)).build());
345
346         }
347     }
348
349     private List<CommandOption> toCommandOptionList(List<String> options) {
350         return options.stream().map(c -> new CommandOption(c, c)).collect(Collectors.toList());
351     }
352
353     private void valueUpdated(String channelId, LightState newState) {
354         Integer bri = newState.bri;
355         Integer hue = newState.hue;
356         Integer sat = newState.sat;
357         Boolean on = newState.on;
358
359         switch (channelId) {
360             case CHANNEL_ALERT:
361                 updateState(channelId, "alert".equals(newState.alert) ? OnOffType.ON : OnOffType.OFF);
362                 break;
363             case CHANNEL_SWITCH:
364             case CHANNEL_LOCK:
365                 if (on != null) {
366                     updateState(channelId, OnOffType.from(on));
367                 }
368                 break;
369             case CHANNEL_COLOR:
370                 if (on != null && on == false) {
371                     updateState(channelId, OnOffType.OFF);
372                 } else if (bri != null && "xy".equals(newState.colormode)) {
373                     final double @Nullable [] xy = newState.xy;
374                     if (xy != null && xy.length == 2) {
375                         HSBType color = HSBType.fromXY((float) xy[0], (float) xy[1]);
376                         updateState(channelId, new HSBType(color.getHue(), color.getSaturation(), toPercentType(bri)));
377                     }
378                 } else if (bri != null && hue != null && sat != null) {
379                     updateState(channelId,
380                             new HSBType(new DecimalType(hue / HUE_FACTOR), toPercentType(sat), toPercentType(bri)));
381                 }
382                 break;
383             case CHANNEL_BRIGHTNESS:
384                 if (bri != null && on != null && on) {
385                     updateState(channelId, toPercentType(bri));
386                 } else {
387                     updateState(channelId, OnOffType.OFF);
388                 }
389                 break;
390             case CHANNEL_COLOR_TEMPERATURE:
391                 Integer ct = newState.ct;
392                 if (ct != null && ct >= ctMin && ct <= ctMax) {
393                     updateState(channelId, new DecimalType(miredToKelvin(ct)));
394                 }
395                 break;
396             case CHANNEL_POSITION:
397                 if (bri != null) {
398                     updateState(channelId, toPercentType(bri));
399                 }
400                 break;
401             case CHANNEL_EFFECT:
402                 String effect = newState.effect;
403                 if (effect != null) {
404                     updateState(channelId, new StringType(effect));
405                 }
406                 break;
407             case CHANNEL_EFFECT_SPEED:
408                 Integer effectSpeed = newState.effectSpeed;
409                 if (effectSpeed != null) {
410                     updateState(channelId, new DecimalType(effectSpeed));
411                 }
412                 break;
413             default:
414         }
415     }
416
417     @Override
418     public void messageReceived(String sensorID, DeconzBaseMessage message) {
419         if (message instanceof LightMessage) {
420             LightMessage lightMessage = (LightMessage) message;
421             logger.trace("{} received {}", thing.getUID(), lightMessage);
422             LightState lightState = lightMessage.state;
423             if (lightState != null) {
424                 if (lastCommandExpireTimestamp > System.currentTimeMillis()
425                         && !lightState.equalsIgnoreNull(lastCommand)) {
426                     // skip for SKIP_UPDATE_TIMESPAN after last command if lightState is different from command
427                     logger.trace("Ignoring differing update after last command until {}", lastCommandExpireTimestamp);
428                     return;
429                 }
430                 lightStateCache = lightState;
431                 if (Boolean.TRUE.equals(lightState.reachable)) {
432                     updateStatus(ThingStatus.ONLINE);
433                     thing.getChannels().stream().map(c -> c.getUID().getId()).forEach(c -> valueUpdated(c, lightState));
434                 } else {
435                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Not reachable");
436                     thing.getChannels().stream().map(c -> c.getUID()).forEach(c -> updateState(c, UnDefType.UNDEF));
437                 }
438             }
439         }
440     }
441 }