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