]> git.basschouten.com Git - openhab-addons.git/blob
c6c7c5905723f395799df5a0c20ffb957b00e147
[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.miio.internal.handler;
14
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.*;
16
17 import java.awt.Color;
18 import java.io.IOException;
19 import java.net.URL;
20 import java.time.Instant;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.LinkedHashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Set;
28 import java.util.concurrent.TimeUnit;
29
30 import javax.measure.Unit;
31 import javax.measure.format.MeasurementParseException;
32
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
36 import org.openhab.binding.miio.internal.MiIoCommand;
37 import org.openhab.binding.miio.internal.MiIoQuantiyTypes;
38 import org.openhab.binding.miio.internal.MiIoSendCommand;
39 import org.openhab.binding.miio.internal.Utils;
40 import org.openhab.binding.miio.internal.basic.ActionConditions;
41 import org.openhab.binding.miio.internal.basic.BasicChannelTypeProvider;
42 import org.openhab.binding.miio.internal.basic.CommandParameterType;
43 import org.openhab.binding.miio.internal.basic.Conversions;
44 import org.openhab.binding.miio.internal.basic.MiIoBasicChannel;
45 import org.openhab.binding.miio.internal.basic.MiIoBasicDevice;
46 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
47 import org.openhab.binding.miio.internal.basic.MiIoDeviceAction;
48 import org.openhab.binding.miio.internal.basic.MiIoDeviceActionCondition;
49 import org.openhab.binding.miio.internal.cloud.CloudConnector;
50 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
51 import org.openhab.core.cache.ExpiringCache;
52 import org.openhab.core.library.types.DecimalType;
53 import org.openhab.core.library.types.HSBType;
54 import org.openhab.core.library.types.OnOffType;
55 import org.openhab.core.library.types.OpenClosedType;
56 import org.openhab.core.library.types.PercentType;
57 import org.openhab.core.library.types.QuantityType;
58 import org.openhab.core.library.types.StringType;
59 import org.openhab.core.library.unit.SIUnits;
60 import org.openhab.core.library.unit.Units;
61 import org.openhab.core.thing.Channel;
62 import org.openhab.core.thing.ChannelUID;
63 import org.openhab.core.thing.Thing;
64 import org.openhab.core.thing.binding.builder.ChannelBuilder;
65 import org.openhab.core.thing.binding.builder.ThingBuilder;
66 import org.openhab.core.thing.type.ChannelTypeRegistry;
67 import org.openhab.core.thing.type.ChannelTypeUID;
68 import org.openhab.core.types.Command;
69 import org.openhab.core.types.RefreshType;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 import com.google.gson.Gson;
74 import com.google.gson.GsonBuilder;
75 import com.google.gson.JsonArray;
76 import com.google.gson.JsonElement;
77 import com.google.gson.JsonIOException;
78 import com.google.gson.JsonObject;
79 import com.google.gson.JsonParser;
80 import com.google.gson.JsonPrimitive;
81 import com.google.gson.JsonSyntaxException;
82
83 /**
84  * The {@link MiIoBasicHandler} is responsible for handling commands, which are
85  * sent to one of the channels.
86  *
87  * @author Marcel Verpaalen - Initial contribution
88  */
89 @NonNullByDefault
90 public class MiIoBasicHandler extends MiIoAbstractHandler {
91     private final Logger logger = LoggerFactory.getLogger(MiIoBasicHandler.class);
92     private boolean hasChannelStructure;
93
94     private final ExpiringCache<Boolean> updateDataCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
95         miIoScheduler.schedule(this::updateData, 0, TimeUnit.SECONDS);
96         return true;
97     });
98
99     List<MiIoBasicChannel> refreshList = new ArrayList<>();
100     private Map<String, MiIoBasicChannel> refreshListCustomCommands = new HashMap<>();
101
102     private @Nullable MiIoBasicDevice miioDevice;
103     private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
104     private ChannelTypeRegistry channelTypeRegistry;
105     private BasicChannelTypeProvider basicChannelTypeProvider;
106
107     public MiIoBasicHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
108             CloudConnector cloudConnector, ChannelTypeRegistry channelTypeRegistry,
109             BasicChannelTypeProvider basicChannelTypeProvider) {
110         super(thing, miIoDatabaseWatchService, cloudConnector);
111         this.channelTypeRegistry = channelTypeRegistry;
112         this.basicChannelTypeProvider = basicChannelTypeProvider;
113     }
114
115     @Override
116     public void initialize() {
117         super.initialize();
118         hasChannelStructure = false;
119         isIdentified = false;
120         refreshList = new ArrayList<>();
121         refreshListCustomCommands = new HashMap<>();
122     }
123
124     @Override
125     public void handleCommand(ChannelUID channelUID, Command receivedCommand) {
126         Command command = receivedCommand;
127         deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
128         if (command == RefreshType.REFRESH) {
129             if (updateDataCache.isExpired()) {
130                 logger.debug("Refreshing {}", channelUID);
131                 updateDataCache.getValue();
132             } else {
133                 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
134             }
135             return;
136         }
137         if (handleCommandsChannels(channelUID, command)) {
138             forceStatusUpdate();
139             return;
140         }
141         logger.debug("Locating action for {} channel '{}': '{}'", getThing().getUID(), channelUID.getId(), command);
142         if (!actions.isEmpty()) {
143             final MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
144             if (miIoBasicChannel != null) {
145                 int valuePos = 0;
146                 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
147                     @Nullable
148                     JsonElement value = null;
149                     JsonArray parameters = action.getParameters().deepCopy();
150                     for (int i = 0; i < action.getParameters().size(); i++) {
151                         JsonElement p = action.getParameters().get(i);
152                         if (p.isJsonPrimitive() && p.getAsString().toLowerCase().contains("$value$")) {
153                             valuePos = i;
154                             break;
155                         }
156                     }
157                     String cmd = action.getCommand();
158                     CommandParameterType paramType = action.getparameterType();
159                     if (command instanceof QuantityType) {
160                         QuantityType<?> qtc = null;
161                         try {
162                             if (!miIoBasicChannel.getUnit().isBlank()) {
163                                 Unit<?> unit = MiIoQuantiyTypes.get(miIoBasicChannel.getUnit());
164                                 if (unit != null) {
165                                     qtc = ((QuantityType<?>) command).toUnit(unit);
166                                 }
167                             }
168                         } catch (MeasurementParseException e) {
169                             // swallow
170                         }
171                         if (qtc != null) {
172                             command = new DecimalType(qtc.toBigDecimal());
173                         } else {
174                             logger.debug("Could not convert QuantityType to '{}'", miIoBasicChannel.getUnit());
175                             command = new DecimalType(((QuantityType<?>) command).toBigDecimal());
176                         }
177                     }
178                     if (paramType == CommandParameterType.COLOR) {
179                         if (command instanceof HSBType) {
180                             HSBType hsb = (HSBType) command;
181                             Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360,
182                                     hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100);
183                             value = new JsonPrimitive(
184                                     (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue());
185                         } else if (command instanceof DecimalType) {
186                             // actually brightness is being set instead of a color
187                             value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
188                         } else if (command instanceof OnOffType) {
189                             value = new JsonPrimitive(command == OnOffType.ON ? 100 : 0);
190                         } else {
191                             logger.debug("Unsupported command for COLOR: {}", command);
192                         }
193                     } else if (command instanceof OnOffType) {
194                         if (paramType == CommandParameterType.ONOFF) {
195                             value = new JsonPrimitive(command == OnOffType.ON ? "on" : "off");
196                         } else if (paramType == CommandParameterType.ONOFFPARA) {
197                             cmd = cmd.replace("*", command == OnOffType.ON ? "on" : "off");
198                             value = new JsonArray();
199                         } else if (paramType == CommandParameterType.ONOFFBOOL) {
200                             boolean boolCommand = command == OnOffType.ON;
201                             value = new JsonPrimitive(boolCommand);
202                         } else if (paramType == CommandParameterType.ONOFFBOOLSTRING) {
203                             value = new JsonPrimitive(command == OnOffType.ON ? "true" : "false");
204                         } else if (paramType == CommandParameterType.ONOFFNUMBER) {
205                             value = new JsonPrimitive(command == OnOffType.ON ? 1 : 0);
206                         }
207                     } else if (command instanceof DecimalType) {
208                         value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
209                     } else if (command instanceof StringType) {
210                         if (paramType == CommandParameterType.STRING) {
211                             value = new JsonPrimitive(command.toString().toLowerCase());
212                         } else if (paramType == CommandParameterType.CUSTOMSTRING) {
213                             value = new JsonPrimitive(parameters.get(valuePos).getAsString().replace("$value",
214                                     command.toString().toLowerCase()));
215                         }
216                     } else {
217                         value = new JsonPrimitive(command.toString().toLowerCase());
218                     }
219                     if (paramType == CommandParameterType.EMPTY) {
220                         value = new JsonArray();
221                     }
222                     final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
223                     if (miIoDeviceActionCondition != null) {
224                         value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
225                                 command);
226                     }
227                     // Check for miot channel
228                     if (value != null) {
229                         if (action.isMiOtAction()) {
230                             value = miotActionTransform(action, miIoBasicChannel, value);
231                         } else if (miIoBasicChannel.isMiOt()) {
232                             value = miotTransform(miIoBasicChannel, value);
233                         }
234                     }
235                     if (paramType != CommandParameterType.NONE && paramType != CommandParameterType.ONOFFPARA
236                             && value != null) {
237                         if (parameters.size() > 0) {
238                             parameters.set(valuePos, value);
239                         } else {
240                             parameters.add(value);
241                         }
242                     }
243                     if (action.isMiOtAction() && parameters.size() > 0 && parameters.get(0).isJsonObject()) {
244                         // hack as unlike any other commands miot actions parameters appear to be send as a json object
245                         // instead of a json array
246                         cmd = cmd + parameters.get(0).getAsJsonObject().toString();
247                     } else {
248                         cmd = cmd + parameters.toString();
249                     }
250                     if (value != null) {
251                         logger.debug("Sending command {}", cmd);
252                         sendCommand(cmd);
253                     } else {
254                         if (miIoDeviceActionCondition != null) {
255                             logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
256                                     miIoDeviceActionCondition.getName());
257                         } else {
258                             logger.debug("Command not send. Value null");
259                         }
260                     }
261                 }
262             } else {
263                 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
264                 if (logger.isTraceEnabled()) {
265                     for (Entry<ChannelUID, MiIoBasicChannel> a : actions.entrySet()) {
266                         logger.trace("Available entries: {} : {}", a.getKey(), a.getValue().getFriendlyName());
267                     }
268                 }
269             }
270             forceStatusUpdate();
271         } else {
272             logger.debug("Actions not loaded yet, or none available");
273         }
274     }
275
276     private void forceStatusUpdate() {
277         updateDataCache.invalidateValue();
278         miIoScheduler.schedule(() -> {
279             updateData();
280         }, 3000, TimeUnit.MILLISECONDS);
281     }
282
283     private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
284         JsonObject json = new JsonObject();
285         json.addProperty("did", miIoBasicChannel.getChannel());
286         json.addProperty("siid", miIoBasicChannel.getSiid());
287         json.addProperty("piid", miIoBasicChannel.getPiid());
288         json.add("value", value);
289         return json;
290     }
291
292     private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
293             @Nullable JsonElement value) {
294         JsonObject json = new JsonObject();
295         json.addProperty("did", miIoBasicChannel.getChannel());
296         json.addProperty("siid", action.getSiid());
297         json.addProperty("aiid", action.getAiid());
298         if (value != null) {
299             json.add("in", value);
300         }
301         return json;
302     }
303
304     @Override
305     protected synchronized void updateData() {
306         logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
307         final MiIoAsyncCommunication miioCom = getConnection();
308         try {
309             if (!hasConnection() || skipUpdate() || miioCom == null) {
310                 return;
311             }
312             checkChannelStructure();
313             if (!isIdentified) {
314                 sendCommand(MiIoCommand.MIIO_INFO);
315             }
316             final MiIoBasicDevice midevice = miioDevice;
317             if (midevice != null) {
318                 deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
319                 refreshProperties(midevice);
320                 refreshCustomProperties(midevice);
321                 refreshNetwork();
322             }
323         } catch (Exception e) {
324             logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
325         }
326     }
327
328     private void refreshCustomProperties(MiIoBasicDevice midevice) {
329         for (MiIoBasicChannel miChannel : refreshListCustomCommands.values()) {
330             if (!isLinked(miChannel.getChannel())) {
331                 logger.debug("Skip refresh of channel {} for {} as it is not linked", miChannel.getChannel(),
332                         getThing().getUID());
333                 continue;
334             }
335             String cmd = miChannel.getChannelCustomRefreshCommand();
336             if (!cmd.startsWith("/")) {
337                 cmds.put(sendCommand(miChannel.getChannelCustomRefreshCommand()), miChannel.getChannel());
338             } else {
339                 if (cloudServer.isBlank()) {
340                     logger.debug("Cloudserver empty. Skipping refresh for {} channel '{}'", getThing().getUID(),
341                             miChannel.getChannel());
342                 } else {
343                     cmds.put(sendCommand(cmd, cloudServer), miChannel.getChannel());
344                 }
345             }
346         }
347     }
348
349     private boolean refreshProperties(MiIoBasicDevice device) {
350         MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
351         int maxProperties = device.getDevice().getMaxProperties();
352         JsonArray getPropString = new JsonArray();
353         for (MiIoBasicChannel miChannel : refreshList) {
354             if (!isLinked(miChannel.getChannel())) {
355                 logger.debug("Skip refresh of channel {} for {} as it is not linked", miChannel.getChannel(),
356                         getThing().getUID());
357                 continue;
358             }
359             JsonElement property;
360             if (miChannel.isMiOt()) {
361                 JsonObject json = new JsonObject();
362                 json.addProperty("did", miChannel.getProperty());
363                 json.addProperty("siid", miChannel.getSiid());
364                 json.addProperty("piid", miChannel.getPiid());
365                 property = json;
366             } else {
367                 property = new JsonPrimitive(miChannel.getProperty());
368             }
369             getPropString.add(property);
370             if (getPropString.size() >= maxProperties) {
371                 sendRefreshProperties(command, getPropString);
372                 getPropString = new JsonArray();
373             }
374         }
375         if (getPropString.size() > 0) {
376             sendRefreshProperties(command, getPropString);
377         }
378         return true;
379     }
380
381     private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
382         sendCommand(command, getPropString.toString());
383     }
384
385     /**
386      * Checks if the channel structure has been build already based on the model data. If not build it.
387      */
388     private void checkChannelStructure() {
389         final MiIoBindingConfiguration configuration = this.configuration;
390         if (configuration == null) {
391             return;
392         }
393         if (!hasChannelStructure) {
394             if (configuration.model.isEmpty()) {
395                 logger.debug("Model needs to be determined");
396                 isIdentified = false;
397             } else {
398                 hasChannelStructure = buildChannelStructure(configuration.model);
399             }
400         }
401         if (hasChannelStructure) {
402             refreshList = new ArrayList<>();
403             refreshListCustomCommands = new HashMap<>();
404             final MiIoBasicDevice miioDevice = this.miioDevice;
405             if (miioDevice != null) {
406                 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
407                     if (miChannel.getRefresh()) {
408                         if (miChannel.getChannelCustomRefreshCommand().isBlank()) {
409                             refreshList.add(miChannel);
410                         } else {
411                             String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
412                             refreshListCustomCommands.put(i.trim(), miChannel);
413                         }
414                     }
415                 }
416             }
417
418         }
419     }
420
421     private boolean buildChannelStructure(String deviceName) {
422         logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
423         URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
424         if (fn == null) {
425             logger.warn("Database entry for model '{}' cannot be found.", deviceName);
426             return false;
427         }
428         try {
429             JsonObject deviceMapping = Utils.convertFileToJSON(fn);
430             logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
431             Gson gson = new GsonBuilder().serializeNulls().create();
432             miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
433             for (Channel ch : getThing().getChannels()) {
434                 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
435             }
436             ThingBuilder thingBuilder = editThing();
437             int channelsAdded = 0;
438
439             // make a map of the actions
440             actions = new HashMap<>();
441             final MiIoBasicDevice device = this.miioDevice;
442             if (device != null) {
443                 for (Channel cn : getThing().getChannels()) {
444                     logger.trace("Channel '{}' for thing {} already exist... removing", cn.getUID(),
445                             getThing().getUID());
446                     if (!PERSISTENT_CHANNELS.contains(cn.getUID().getId().toString())) {
447                         thingBuilder.withoutChannels(cn);
448                     }
449                 }
450                 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
451                     logger.debug("properties {}", miChannel);
452                     if (!miChannel.getType().isEmpty()) {
453                         basicChannelTypeProvider.addChannelType(miChannel, deviceName);
454                         ChannelUID channelUID = addChannel(thingBuilder, miChannel, deviceName);
455                         if (channelUID != null) {
456                             actions.put(channelUID, miChannel);
457                             channelsAdded++;
458                         } else {
459                             logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
460                                     miChannel.getFriendlyName());
461                         }
462                     } else {
463                         logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
464                                 miChannel.getFriendlyName());
465                     }
466                 }
467             }
468             // only update if channels were added/removed
469             if (channelsAdded > 0) {
470                 logger.debug("Current thing channels added: {}", channelsAdded);
471                 updateThing(thingBuilder.build());
472             }
473             return true;
474         } catch (JsonIOException | JsonSyntaxException e) {
475             logger.warn("Error parsing database Json", e);
476         } catch (IOException e) {
477             logger.warn("Error reading database file", e);
478         } catch (Exception e) {
479             logger.warn("Error creating channel structure", e);
480         }
481         return false;
482     }
483
484     private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, MiIoBasicChannel miChannel, String model) {
485         String channel = miChannel.getChannel();
486         String dataType = miChannel.getType();
487         if (channel.isEmpty() || dataType.isEmpty()) {
488             logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
489                     getThing().getUID());
490             return null;
491         }
492         ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
493         ChannelBuilder newChannel = ChannelBuilder.create(channelUID, dataType).withLabel(miChannel.getFriendlyName());
494         boolean useGeneratedChannelType = false;
495         if (!miChannel.getChannelType().isBlank()) {
496             ChannelTypeUID channelTypeUID = new ChannelTypeUID(miChannel.getChannelType());
497             if (channelTypeRegistry.getChannelType(channelTypeUID) != null) {
498                 newChannel = newChannel.withType(channelTypeUID);
499                 final LinkedHashSet<String> tags = miChannel.getTags();
500                 if (tags != null && !tags.isEmpty()) {
501                     newChannel.withDefaultTags(tags);
502                 }
503             } else {
504                 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID, model);
505                 useGeneratedChannelType = true;
506             }
507         } else {
508             useGeneratedChannelType = true;
509         }
510         if (useGeneratedChannelType) {
511             newChannel = newChannel
512                     .withType(new ChannelTypeUID(BINDING_ID, model.toUpperCase().replace(".", "_") + "_" + channel));
513             final Set<String> tags = miChannel.getTags();
514             if (tags != null && !tags.isEmpty()) {
515                 newChannel.withDefaultTags(tags);
516             }
517         }
518         thingBuilder.withChannel(newChannel.build());
519         return channelUID;
520     }
521
522     private @Nullable MiIoBasicChannel getChannel(String parameter) {
523         for (MiIoBasicChannel refreshEntry : refreshList) {
524             if (refreshEntry.getProperty().equals(parameter)) {
525                 return refreshEntry;
526             }
527         }
528         logger.trace("Did not find channel for {} in {}", parameter, refreshList);
529         return null;
530     }
531
532     private @Nullable MiIoBasicChannel getCustomRefreshChannel(String channelName) {
533         for (MiIoBasicChannel refreshEntry : refreshListCustomCommands.values()) {
534             if (refreshEntry.getChannel().equals(channelName)) {
535                 return refreshEntry;
536             }
537         }
538         logger.trace("Did not find channel for {} in {}", channelName, refreshList);
539         return null;
540     }
541
542     private void updatePropsFromJsonArray(MiIoSendCommand response) {
543         JsonArray res = response.getResult().getAsJsonArray();
544         JsonArray para = JsonParser.parseString(response.getCommandString()).getAsJsonObject().get("params")
545                 .getAsJsonArray();
546         if (res.size() != para.size()) {
547             logger.debug("Unexpected size different. Request size {},  response size {}. (Req: {}, Resp:{})",
548                     para.size(), res.size(), para, res);
549             return;
550         }
551         for (int i = 0; i < para.size(); i++) {
552             // This is a miot parameter
553             String param;
554             final JsonElement paraElement = para.get(i);
555             if (paraElement.isJsonObject()) { // miot channel
556                 param = paraElement.getAsJsonObject().get("did").getAsString();
557             } else {
558                 param = paraElement.getAsString();
559             }
560             JsonElement val = res.get(i);
561             if (val.isJsonNull()) {
562                 logger.debug("Property '{}' returned null (is it supported?).", param);
563                 continue;
564             } else if (val.isJsonObject()) { // miot channel
565                 val = val.getAsJsonObject().get("value");
566             }
567             MiIoBasicChannel basicChannel = getChannel(param);
568             updateChannel(basicChannel, param, val);
569         }
570     }
571
572     private void updatePropsFromJsonObject(MiIoSendCommand response) {
573         JsonObject res = response.getResult().getAsJsonObject();
574         for (Object k : res.keySet()) {
575             String param = (String) k;
576             JsonElement val = res.get(param);
577             if (val.isJsonNull()) {
578                 logger.debug("Property '{}' returned null (is it supported?).", param);
579                 continue;
580             }
581             MiIoBasicChannel basicChannel = getChannel(param);
582             updateChannel(basicChannel, param, val);
583         }
584     }
585
586     private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
587         JsonElement val = value;
588         deviceVariables.put(param, val);
589         if (basicChannel == null) {
590             logger.debug("Channel not found for {}", param);
591             return;
592         }
593         final String transformation = basicChannel.getTransformation();
594         if (transformation != null) {
595             JsonElement transformed = Conversions.execute(transformation, val, deviceVariables);
596             logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
597                     transformed);
598             val = transformed;
599         }
600         try {
601             String[] chType = basicChannel.getType().toLowerCase().split(":");
602             switch (chType[0]) {
603                 case "number":
604                     quantityTypeUpdate(basicChannel, val, chType.length > 1 ? chType[1] : "");
605                     break;
606                 case "dimmer":
607                     updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
608                     break;
609                 case "string":
610                     if (val.isJsonPrimitive()) {
611                         updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
612                     } else {
613                         updateState(basicChannel.getChannel(), new StringType(val.toString()));
614                     }
615                     break;
616                 case "switch":
617                     if (val.getAsJsonPrimitive().isNumber()) {
618                         updateState(basicChannel.getChannel(), val.getAsInt() > 0 ? OnOffType.ON : OnOffType.OFF);
619                     } else {
620                         String strVal = val.getAsString().toLowerCase();
621                         updateState(basicChannel.getChannel(),
622                                 "on".equals(strVal) || "true".equals(strVal) || "1".equals(strVal) ? OnOffType.ON
623                                         : OnOffType.OFF);
624                     }
625                     break;
626                 case "contact":
627                     if (val.getAsJsonPrimitive().isNumber()) {
628                         updateState(basicChannel.getChannel(),
629                                 val.getAsInt() > 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
630                     } else {
631                         String strVal = val.getAsString().toLowerCase();
632                         updateState(basicChannel.getChannel(),
633                                 "on".equals(strVal) || "true".equals(strVal) || "1".equals(strVal) ? OpenClosedType.OPEN
634                                         : OpenClosedType.CLOSED);
635                     }
636                     break;
637                 case "color":
638                     if (val.isJsonPrimitive()
639                             && (val.getAsJsonPrimitive().isNumber() || val.getAsString().matches("^[0-9]+$"))) {
640                         Color rgb = new Color(val.getAsInt());
641                         HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
642                         updateState(basicChannel.getChannel(), hsb);
643                     } else {
644                         try {
645                             HSBType hsb = HSBType.valueOf(val.getAsString().replace("[", "").replace("]", ""));
646                             updateState(basicChannel.getChannel(), hsb);
647                         } catch (IllegalArgumentException e) {
648                             logger.debug("Failed updating channel '{}'. Could not convert '{}' to color",
649                                     basicChannel.getChannel(), val.getAsString());
650                         }
651                     }
652                     break;
653                 default:
654                     logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
655             }
656         } catch (Exception e) {
657             logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
658                     basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
659             logger.trace("Property update error detail:", e);
660         }
661     }
662
663     private void quantityTypeUpdate(MiIoBasicChannel basicChannel, JsonElement val, String type) {
664         if (!basicChannel.getUnit().isBlank()) {
665             Unit<?> unit = MiIoQuantiyTypes.get(basicChannel.getUnit());
666             if (unit != null) {
667                 logger.debug("'{}' channel '{}' has unit '{}' with symbol '{}'.", getThing().getUID(),
668                         basicChannel.getChannel(), basicChannel.getUnit(), unit);
669                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), unit));
670             } else {
671                 logger.debug(
672                         "Unit '{}' used by '{}' channel '{}' is not found in conversion table... Trying anyway to submit as the update.",
673                         basicChannel.getUnit(), getThing().getUID(), basicChannel.getChannel());
674                 updateState(basicChannel.getChannel(),
675                         new QuantityType<>(val.getAsBigDecimal().toPlainString() + " " + basicChannel.getUnit()));
676             }
677             return;
678         }
679         // if no unit is provided or unit not found use default units, these units have so far been seen for miio
680         // devices
681         switch (type.toLowerCase()) {
682             case "temperature":
683                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SIUnits.CELSIUS));
684                 break;
685             case "electriccurrent":
686                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.AMPERE));
687                 break;
688             case "energy":
689                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.WATT));
690                 break;
691             case "time":
692                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.HOUR));
693                 break;
694             default:
695                 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
696         }
697     }
698
699     @Override
700     public void onMessageReceived(MiIoSendCommand response) {
701         super.onMessageReceived(response);
702         if (response.isError()) {
703             return;
704         }
705         try {
706             switch (response.getCommand()) {
707                 case MIIO_INFO:
708                     break;
709                 case GET_VALUE:
710                 case GET_PROPERTIES:
711                 case GET_PROPERTY:
712                     if (response.getResult().isJsonArray()) {
713                         updatePropsFromJsonArray(response);
714                     } else if (response.getResult().isJsonObject()) {
715                         updatePropsFromJsonObject(response);
716                     }
717                     break;
718                 default:
719                     String channel = cmds.get(response.getId());
720                     if (channel != null) {
721                         logger.debug("Processing custom refresh command response for '{}' - {}", response.getMethod(),
722                                 response.getResult());
723                         final MiIoBasicChannel ch = getCustomRefreshChannel(channel);
724                         if (ch != null) {
725                             if (response.getResult().isJsonArray()) {
726                                 JsonArray cmdResponse = response.getResult().getAsJsonArray();
727                                 final String transformation = ch.getTransformation();
728                                 if (transformation == null || transformation.isBlank()) {
729                                     JsonElement response0 = cmdResponse.get(0);
730                                     updateChannel(ch, ch.getChannel(), response0.isJsonPrimitive() ? response0
731                                             : new JsonPrimitive(response0.toString()));
732                                 } else {
733                                     updateChannel(ch, ch.getChannel(), cmdResponse);
734                                 }
735                             } else {
736                                 updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
737                             }
738                         }
739                         cmds.remove(response.getId());
740                     }
741                     break;
742             }
743         } catch (Exception e) {
744             logger.debug("Error while handing message {}", response.getResponse(), e);
745         }
746     }
747 }