]> git.basschouten.com Git - openhab-addons.git/blob
47b36c45002add59aff77517d69b938e648dc09f
[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.miio.internal.handler;
14
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.CHANNEL_COMMAND;
16
17 import java.awt.Color;
18 import java.io.IOException;
19 import java.net.URL;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.concurrent.TimeUnit;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
29 import org.openhab.binding.miio.internal.MiIoCommand;
30 import org.openhab.binding.miio.internal.MiIoCryptoException;
31 import org.openhab.binding.miio.internal.MiIoSendCommand;
32 import org.openhab.binding.miio.internal.Utils;
33 import org.openhab.binding.miio.internal.basic.ActionConditions;
34 import org.openhab.binding.miio.internal.basic.CommandParameterType;
35 import org.openhab.binding.miio.internal.basic.Conversions;
36 import org.openhab.binding.miio.internal.basic.MiIoBasicChannel;
37 import org.openhab.binding.miio.internal.basic.MiIoBasicDevice;
38 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
39 import org.openhab.binding.miio.internal.basic.MiIoDeviceAction;
40 import org.openhab.binding.miio.internal.basic.MiIoDeviceActionCondition;
41 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
42 import org.openhab.core.cache.ExpiringCache;
43 import org.openhab.core.library.types.DecimalType;
44 import org.openhab.core.library.types.HSBType;
45 import org.openhab.core.library.types.OnOffType;
46 import org.openhab.core.library.types.PercentType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.thing.Channel;
49 import org.openhab.core.thing.ChannelUID;
50 import org.openhab.core.thing.Thing;
51 import org.openhab.core.thing.binding.builder.ChannelBuilder;
52 import org.openhab.core.thing.binding.builder.ThingBuilder;
53 import org.openhab.core.thing.type.ChannelTypeUID;
54 import org.openhab.core.types.Command;
55 import org.openhab.core.types.RefreshType;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import com.google.gson.Gson;
60 import com.google.gson.GsonBuilder;
61 import com.google.gson.JsonArray;
62 import com.google.gson.JsonElement;
63 import com.google.gson.JsonIOException;
64 import com.google.gson.JsonObject;
65 import com.google.gson.JsonPrimitive;
66 import com.google.gson.JsonSyntaxException;
67
68 /**
69  * The {@link MiIoBasicHandler} is responsible for handling commands, which are
70  * sent to one of the channels.
71  *
72  * @author Marcel Verpaalen - Initial contribution
73  */
74 @NonNullByDefault
75 public class MiIoBasicHandler extends MiIoAbstractHandler {
76
77     private final Logger logger = LoggerFactory.getLogger(MiIoBasicHandler.class);
78     private boolean hasChannelStructure;
79
80     private final ExpiringCache<Boolean> updateDataCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
81         scheduler.schedule(this::updateData, 0, TimeUnit.SECONDS);
82         return true;
83     });
84
85     List<MiIoBasicChannel> refreshList = new ArrayList<>();
86
87     private @Nullable MiIoBasicDevice miioDevice;
88     private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
89
90     public MiIoBasicHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService) {
91         super(thing, miIoDatabaseWatchService);
92     }
93
94     @Override
95     public void initialize() {
96         super.initialize();
97         hasChannelStructure = false;
98         isIdentified = false;
99         refreshList = new ArrayList<>();
100     }
101
102     @Override
103     public void handleCommand(ChannelUID channelUID, Command command) {
104         if (command == RefreshType.REFRESH) {
105             if (updateDataCache.isExpired()) {
106                 logger.debug("Refreshing {}", channelUID);
107                 updateDataCache.getValue();
108             } else {
109                 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
110             }
111             return;
112         }
113         if (channelUID.getId().equals(CHANNEL_COMMAND)) {
114             cmds.put(sendCommand(command.toString()), command.toString());
115             return;
116         }
117         logger.debug("Locating action for channel '{}': '{}'", channelUID.getId(), command);
118         if (!actions.isEmpty()) {
119             if (actions.containsKey(channelUID)) {
120                 int valuePos = 0;
121                 MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
122                 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
123                     @Nullable
124                     JsonElement value = null;
125                     JsonArray parameters = action.getParameters().deepCopy();
126                     for (int i = 0; i < action.getParameters().size(); i++) {
127                         JsonElement p = action.getParameters().get(i);
128                         if (p.isJsonPrimitive() && p.getAsString().toLowerCase().contains("$value$")) {
129                             valuePos = i;
130                             break;
131                         }
132                     }
133                     String cmd = action.getCommand();
134                     CommandParameterType paramType = action.getparameterType();
135                     if (paramType == CommandParameterType.COLOR) {
136                         if (command instanceof HSBType) {
137                             HSBType hsb = (HSBType) command;
138                             Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360,
139                                     hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100);
140                             value = new JsonPrimitive(
141                                     (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue());
142                         } else if (command instanceof DecimalType) {
143                             // actually brightness is being set instead of a color
144                             value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
145                         } else if (command instanceof OnOffType) {
146                             value = new JsonPrimitive(command == OnOffType.ON ? 100 : 0);
147                         } else {
148                             logger.debug("Unsupported command for COLOR: {}", command);
149                         }
150                     } else if (command instanceof OnOffType) {
151                         if (paramType == CommandParameterType.ONOFF) {
152                             value = new JsonPrimitive(command == OnOffType.ON ? "on" : "off");
153                         } else if (paramType == CommandParameterType.ONOFFPARA) {
154                             cmd = cmd.replace("*", command == OnOffType.ON ? "on" : "off");
155                         } else if (paramType == CommandParameterType.ONOFFBOOL) {
156                             boolean boolCommand = command == OnOffType.ON;
157                             value = new JsonPrimitive(boolCommand);
158                         } else if (paramType == CommandParameterType.ONOFFBOOLSTRING) {
159                             value = new JsonPrimitive(command == OnOffType.ON ? "true" : "false");
160                         }
161                     } else if (command instanceof DecimalType) {
162                         value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
163                     } else if (command instanceof StringType) {
164                         if (paramType == CommandParameterType.STRING) {
165                             value = new JsonPrimitive(command.toString().toLowerCase());
166                         } else if (paramType == CommandParameterType.CUSTOMSTRING) {
167                             value = new JsonPrimitive(parameters.get(valuePos).getAsString().replace("$value",
168                                     command.toString().toLowerCase()));
169                         }
170                     } else {
171                         value = new JsonPrimitive(command.toString().toLowerCase());
172                     }
173                     if (paramType == CommandParameterType.EMPTY) {
174                         value = new JsonArray();
175                     }
176                     final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
177                     if (miIoDeviceActionCondition != null) {
178                         value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
179                                 command);
180                     }
181                     // Check for miot channel
182                     if (value != null) {
183                         if (action.isMiOtAction()) {
184                             value = miotActionTransform(action, miIoBasicChannel, value);
185                         } else if (miIoBasicChannel.isMiOt()) {
186                             value = miotTransform(miIoBasicChannel, value);
187                         }
188                     }
189                     if (paramType != CommandParameterType.NONE && value != null) {
190                         if (parameters.size() > 0) {
191                             parameters.set(valuePos, value);
192                         } else {
193                             parameters.add(value);
194                         }
195                     }
196                     cmd = cmd + parameters.toString();
197                     if (value != null) {
198                         logger.debug("Sending command {}", cmd);
199                         sendCommand(cmd);
200                     } else {
201                         if (miIoDeviceActionCondition != null) {
202                             logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
203                                     miIoDeviceActionCondition.getName());
204                         } else {
205                             logger.debug("Command not send. Value null");
206                         }
207                     }
208                 }
209             } else {
210                 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
211                 if (logger.isTraceEnabled()) {
212                     for (ChannelUID a : actions.keySet()) {
213                         logger.trace("Available entries: {} : {}", a, actions.get(a).getFriendlyName());
214                     }
215                 }
216             }
217             updateDataCache.invalidateValue();
218             updateData();
219         } else {
220             logger.debug("Actions not loaded yet");
221         }
222     }
223
224     private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
225         JsonObject json = new JsonObject();
226         json.addProperty("did", miIoBasicChannel.getChannel());
227         json.addProperty("siid", miIoBasicChannel.getSiid());
228         json.addProperty("piid", miIoBasicChannel.getPiid());
229         json.add("value", value);
230         return json;
231     }
232
233     private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
234             @Nullable JsonElement value) {
235         JsonObject json = new JsonObject();
236         json.addProperty("did", miIoBasicChannel.getChannel());
237         json.addProperty("siid", action.getSiid());
238         json.addProperty("aiid", action.getAiid());
239         if (value != null) {
240             json.add("in", value);
241         }
242         return json;
243     }
244
245     @Override
246     protected synchronized void updateData() {
247         logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
248         final MiIoAsyncCommunication miioCom = getConnection();
249         try {
250             if (!hasConnection() || skipUpdate() || miioCom == null) {
251                 return;
252             }
253             checkChannelStructure();
254             if (!isIdentified) {
255                 miioCom.queueCommand(MiIoCommand.MIIO_INFO);
256             }
257             final MiIoBasicDevice midevice = miioDevice;
258             if (midevice != null) {
259                 refreshProperties(midevice);
260                 refreshNetwork();
261             }
262         } catch (Exception e) {
263             logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
264         }
265     }
266
267     private boolean refreshProperties(MiIoBasicDevice device) {
268         MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
269         int maxProperties = device.getDevice().getMaxProperties();
270         JsonArray getPropString = new JsonArray();
271         for (MiIoBasicChannel miChannel : refreshList) {
272             JsonElement property;
273             if (miChannel.isMiOt()) {
274                 JsonObject json = new JsonObject();
275                 json.addProperty("did", miChannel.getProperty());
276                 json.addProperty("siid", miChannel.getSiid());
277                 json.addProperty("piid", miChannel.getPiid());
278                 property = json;
279             } else {
280                 property = new JsonPrimitive(miChannel.getProperty());
281             }
282             getPropString.add(property);
283             if (getPropString.size() >= maxProperties) {
284                 sendRefreshProperties(command, getPropString);
285                 getPropString = new JsonArray();
286             }
287         }
288         if (getPropString.size() > 0) {
289             sendRefreshProperties(command, getPropString);
290         }
291         return true;
292     }
293
294     private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
295         try {
296             final MiIoAsyncCommunication miioCom = this.miioCom;
297             if (miioCom != null) {
298                 miioCom.queueCommand(command, getPropString.toString());
299             }
300         } catch (MiIoCryptoException | IOException e) {
301             logger.debug("Send refresh failed {}", e.getMessage(), e);
302         }
303     }
304
305     /**
306      * Checks if the channel structure has been build already based on the model data. If not build it.
307      */
308     private void checkChannelStructure() {
309         final MiIoBindingConfiguration configuration = this.configuration;
310         if (configuration == null) {
311             return;
312         }
313         if (!hasChannelStructure) {
314             if (configuration.model == null || configuration.model.isEmpty()) {
315                 logger.debug("Model needs to be determined");
316                 isIdentified = false;
317             } else {
318                 hasChannelStructure = buildChannelStructure(configuration.model);
319             }
320         }
321         if (hasChannelStructure) {
322             refreshList = new ArrayList<>();
323             final MiIoBasicDevice miioDevice = this.miioDevice;
324             if (miioDevice != null) {
325                 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
326                     if (miChannel.getRefresh()) {
327                         refreshList.add(miChannel);
328                     }
329                 }
330             }
331
332         }
333     }
334
335     private boolean buildChannelStructure(String deviceName) {
336         logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
337         URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
338         if (fn == null) {
339             logger.warn("Database entry for model '{}' cannot be found.", deviceName);
340             return false;
341         }
342         try {
343             JsonObject deviceMapping = Utils.convertFileToJSON(fn);
344             logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
345             Gson gson = new GsonBuilder().serializeNulls().create();
346             miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
347             for (Channel ch : getThing().getChannels()) {
348                 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
349             }
350             ThingBuilder thingBuilder = editThing();
351             int channelsAdded = 0;
352
353             // make a map of the actions
354             actions = new HashMap<>();
355             final MiIoBasicDevice device = this.miioDevice;
356             if (device != null) {
357                 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
358                     logger.debug("properties {}", miChannel);
359                     if (!miChannel.getType().isEmpty()) {
360                         ChannelUID channelUID = addChannel(thingBuilder, miChannel.getChannel(),
361                                 miChannel.getChannelType(), miChannel.getType(), miChannel.getFriendlyName());
362                         if (channelUID != null) {
363                             actions.put(channelUID, miChannel);
364                             channelsAdded++;
365                         } else {
366                             logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
367                                     miChannel.getFriendlyName());
368                         }
369                     } else {
370                         logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
371                                 miChannel.getFriendlyName());
372                     }
373                 }
374             }
375             // only update if channels were added/removed
376             if (channelsAdded > 0) {
377                 logger.debug("Current thing channels added: {}", channelsAdded);
378                 updateThing(thingBuilder.build());
379             }
380             return true;
381         } catch (JsonIOException | JsonSyntaxException e) {
382             logger.warn("Error parsing database Json", e);
383         } catch (IOException e) {
384             logger.warn("Error reading database file", e);
385         } catch (Exception e) {
386             logger.warn("Error creating channel structure", e);
387         }
388         return false;
389     }
390
391     private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, @Nullable String channel, String channelType,
392             @Nullable String datatype, String friendlyName) {
393         if (channel == null || channel.isEmpty() || datatype == null || datatype.isEmpty()) {
394             logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
395                     getThing().getUID());
396             return null;
397         }
398         ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
399         ChannelTypeUID channelTypeUID = new ChannelTypeUID(channelType);
400
401         // TODO: Need to understand if this harms anything. If yes, channel only to be added when not there already.
402         // current way allows to have no issues when channels are changing.
403         if (getThing().getChannel(channel) != null) {
404             logger.info("Channel '{}' for thing {} already exist... removing", channel, getThing().getUID());
405             thingBuilder.withoutChannel(new ChannelUID(getThing().getUID(), channel));
406         }
407         Channel newChannel = ChannelBuilder.create(channelUID, datatype).withType(channelTypeUID)
408                 .withLabel(friendlyName).build();
409         thingBuilder.withChannel(newChannel);
410         return channelUID;
411     }
412
413     private @Nullable MiIoBasicChannel getChannel(String parameter) {
414         for (MiIoBasicChannel refreshEntry : refreshList) {
415             if (refreshEntry.getProperty().equals(parameter)) {
416                 return refreshEntry;
417             }
418         }
419         logger.trace("Did not find channel for {} in {}", parameter, refreshList);
420         return null;
421     }
422
423     private void updatePropsFromJsonArray(MiIoSendCommand response) {
424         JsonArray res = response.getResult().getAsJsonArray();
425         JsonArray para = parser.parse(response.getCommandString()).getAsJsonObject().get("params").getAsJsonArray();
426         if (res.size() != para.size()) {
427             logger.debug("Unexpected size different. Request size {},  response size {}. (Req: {}, Resp:{})",
428                     para.size(), res.size(), para, res);
429         }
430         for (int i = 0; i < para.size(); i++) {
431             // This is a miot parameter
432             String param;
433             final JsonElement paraElement = para.get(i);
434             if (paraElement.isJsonObject()) { // miot channel
435                 param = paraElement.getAsJsonObject().get("did").getAsString();
436             } else {
437                 param = paraElement.getAsString();
438             }
439             JsonElement val = res.get(i);
440             if (val.isJsonNull()) {
441                 logger.debug("Property '{}' returned null (is it supported?).", param);
442                 continue;
443             } else if (val.isJsonObject()) { // miot channel
444                 val = val.getAsJsonObject().get("value");
445             }
446             MiIoBasicChannel basicChannel = getChannel(param);
447             updateChannel(basicChannel, param, val);
448         }
449     }
450
451     private void updatePropsFromJsonObject(MiIoSendCommand response) {
452         JsonObject res = response.getResult().getAsJsonObject();
453         for (Object k : res.keySet()) {
454             String param = (String) k;
455             JsonElement val = res.get(param);
456             if (val.isJsonNull()) {
457                 logger.debug("Property '{}' returned null (is it supported?).", param);
458                 continue;
459             }
460             MiIoBasicChannel basicChannel = getChannel(param);
461             updateChannel(basicChannel, param, val);
462         }
463     }
464
465     private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
466         JsonElement val = value;
467         if (basicChannel == null) {
468             logger.debug("Channel not found for {}", param);
469             return;
470         }
471         final String transformation = basicChannel.getTransfortmation();
472         if (transformation != null) {
473             JsonElement transformed = Conversions.execute(transformation, val);
474             logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
475                     transformed);
476             val = transformed;
477         }
478         try {
479             switch (basicChannel.getType().toLowerCase()) {
480                 case "number":
481                     updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
482                     break;
483                 case "dimmer":
484                     updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
485                     break;
486                 case "string":
487                     updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
488                     break;
489                 case "switch":
490                     updateState(basicChannel.getChannel(), val.getAsString().toLowerCase().equals("on")
491                             || val.getAsString().toLowerCase().equals("true") ? OnOffType.ON : OnOffType.OFF);
492                     break;
493                 case "color":
494                     Color rgb = new Color(val.getAsInt());
495                     HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
496                     updateState(basicChannel.getChannel(), hsb);
497                     break;
498                 default:
499                     logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
500             }
501         } catch (Exception e) {
502             logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
503                     basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
504             logger.trace("Property update error detail:", e);
505         }
506     }
507
508     @Override
509     public void onMessageReceived(MiIoSendCommand response) {
510         super.onMessageReceived(response);
511         if (response.isError()) {
512             return;
513         }
514         try {
515             switch (response.getCommand()) {
516                 case MIIO_INFO:
517                     break;
518                 case GET_VALUE:
519                 case GET_PROPERTIES:
520                 case GET_PROPERTY:
521                     if (response.getResult().isJsonArray()) {
522                         updatePropsFromJsonArray(response);
523                     } else if (response.getResult().isJsonObject()) {
524                         updatePropsFromJsonObject(response);
525                     }
526                     break;
527                 default:
528                     break;
529             }
530         } catch (Exception e) {
531             logger.debug("Error while handing message {}", response.getResponse(), e);
532         }
533     }
534 }