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