]> git.basschouten.com Git - openhab-addons.git/blob
f8fadf3b56d50b30f70c8d667eeea5c2c2adafc6
[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.MiIoCryptoException;
34 import org.openhab.binding.miio.internal.MiIoQuantiyTypes;
35 import org.openhab.binding.miio.internal.MiIoSendCommand;
36 import org.openhab.binding.miio.internal.Utils;
37 import org.openhab.binding.miio.internal.basic.ActionConditions;
38 import org.openhab.binding.miio.internal.basic.CommandParameterType;
39 import org.openhab.binding.miio.internal.basic.Conversions;
40 import org.openhab.binding.miio.internal.basic.MiIoBasicChannel;
41 import org.openhab.binding.miio.internal.basic.MiIoBasicDevice;
42 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
43 import org.openhab.binding.miio.internal.basic.MiIoDeviceAction;
44 import org.openhab.binding.miio.internal.basic.MiIoDeviceActionCondition;
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         scheduler.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             ChannelTypeRegistry channelTypeRegistry) {
101         super(thing, miIoDatabaseWatchService);
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                     cmd = cmd + parameters.toString();
231                     if (value != null) {
232                         logger.debug("Sending command {}", cmd);
233                         sendCommand(cmd);
234                     } else {
235                         if (miIoDeviceActionCondition != null) {
236                             logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
237                                     miIoDeviceActionCondition.getName());
238                         } else {
239                             logger.debug("Command not send. Value null");
240                         }
241                     }
242                 }
243             } else {
244                 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
245                 if (logger.isTraceEnabled()) {
246                     for (ChannelUID a : actions.keySet()) {
247                         logger.trace("Available entries: {} : {}", a, actions.get(a).getFriendlyName());
248                     }
249                 }
250             }
251             updateDataCache.invalidateValue();
252             scheduler.schedule(() -> {
253                 updateData();
254             }, 3000, TimeUnit.MILLISECONDS);
255         } else {
256             logger.debug("Actions not loaded yet");
257         }
258     }
259
260     private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
261         JsonObject json = new JsonObject();
262         json.addProperty("did", miIoBasicChannel.getChannel());
263         json.addProperty("siid", miIoBasicChannel.getSiid());
264         json.addProperty("piid", miIoBasicChannel.getPiid());
265         json.add("value", value);
266         return json;
267     }
268
269     private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
270             @Nullable JsonElement value) {
271         JsonObject json = new JsonObject();
272         json.addProperty("did", miIoBasicChannel.getChannel());
273         json.addProperty("siid", action.getSiid());
274         json.addProperty("aiid", action.getAiid());
275         if (value != null) {
276             json.add("in", value);
277         }
278         return json;
279     }
280
281     @Override
282     protected synchronized void updateData() {
283         logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
284         final MiIoAsyncCommunication miioCom = getConnection();
285         try {
286             if (!hasConnection() || skipUpdate() || miioCom == null) {
287                 return;
288             }
289             checkChannelStructure();
290             if (!isIdentified) {
291                 miioCom.queueCommand(MiIoCommand.MIIO_INFO);
292             }
293             final MiIoBasicDevice midevice = miioDevice;
294             if (midevice != null) {
295                 refreshProperties(midevice);
296                 refreshCustomProperties(midevice);
297                 refreshNetwork();
298             }
299         } catch (Exception e) {
300             logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
301         }
302     }
303
304     private void refreshCustomProperties(MiIoBasicDevice midevice) {
305         for (MiIoBasicChannel miChannel : refreshListCustomCommands.values()) {
306             sendCommand(miChannel.getChannelCustomRefreshCommand());
307         }
308     }
309
310     private boolean refreshProperties(MiIoBasicDevice device) {
311         MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
312         int maxProperties = device.getDevice().getMaxProperties();
313         JsonArray getPropString = new JsonArray();
314         for (MiIoBasicChannel miChannel : refreshList) {
315             JsonElement property;
316             if (miChannel.isMiOt()) {
317                 JsonObject json = new JsonObject();
318                 json.addProperty("did", miChannel.getProperty());
319                 json.addProperty("siid", miChannel.getSiid());
320                 json.addProperty("piid", miChannel.getPiid());
321                 property = json;
322             } else {
323                 property = new JsonPrimitive(miChannel.getProperty());
324             }
325             getPropString.add(property);
326             if (getPropString.size() >= maxProperties) {
327                 sendRefreshProperties(command, getPropString);
328                 getPropString = new JsonArray();
329             }
330         }
331         if (getPropString.size() > 0) {
332             sendRefreshProperties(command, getPropString);
333         }
334         return true;
335     }
336
337     private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
338         try {
339             final MiIoAsyncCommunication miioCom = this.miioCom;
340             if (miioCom != null) {
341                 miioCom.queueCommand(command, getPropString.toString());
342             }
343         } catch (MiIoCryptoException | IOException e) {
344             logger.debug("Send refresh failed {}", e.getMessage(), e);
345         }
346     }
347
348     /**
349      * Checks if the channel structure has been build already based on the model data. If not build it.
350      */
351     private void checkChannelStructure() {
352         final MiIoBindingConfiguration configuration = this.configuration;
353         if (configuration == null) {
354             return;
355         }
356         if (!hasChannelStructure) {
357             if (configuration.model == null || configuration.model.isEmpty()) {
358                 logger.debug("Model needs to be determined");
359                 isIdentified = false;
360             } else {
361                 hasChannelStructure = buildChannelStructure(configuration.model);
362             }
363         }
364         if (hasChannelStructure) {
365             refreshList = new ArrayList<>();
366             final MiIoBasicDevice miioDevice = this.miioDevice;
367             if (miioDevice != null) {
368                 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
369                     if (miChannel.getRefresh()) {
370                         if (miChannel.getChannelCustomRefreshCommand().isBlank()) {
371                             refreshList.add(miChannel);
372                         } else {
373                             String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
374                             refreshListCustomCommands.put(i.trim(), miChannel);
375                         }
376                     }
377                 }
378             }
379
380         }
381     }
382
383     private boolean buildChannelStructure(String deviceName) {
384         logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
385         URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
386         if (fn == null) {
387             logger.warn("Database entry for model '{}' cannot be found.", deviceName);
388             return false;
389         }
390         try {
391             JsonObject deviceMapping = Utils.convertFileToJSON(fn);
392             logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
393             Gson gson = new GsonBuilder().serializeNulls().create();
394             miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
395             for (Channel ch : getThing().getChannels()) {
396                 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
397             }
398             ThingBuilder thingBuilder = editThing();
399             int channelsAdded = 0;
400
401             // make a map of the actions
402             actions = new HashMap<>();
403             final MiIoBasicDevice device = this.miioDevice;
404             if (device != null) {
405                 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
406                     logger.debug("properties {}", miChannel);
407                     if (!miChannel.getType().isEmpty()) {
408                         ChannelUID channelUID = addChannel(thingBuilder, miChannel.getChannel(),
409                                 miChannel.getChannelType(), miChannel.getType(), miChannel.getFriendlyName());
410                         if (channelUID != null) {
411                             actions.put(channelUID, miChannel);
412                             channelsAdded++;
413                         } else {
414                             logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
415                                     miChannel.getFriendlyName());
416                         }
417                     } else {
418                         logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
419                                 miChannel.getFriendlyName());
420                     }
421                 }
422             }
423             // only update if channels were added/removed
424             if (channelsAdded > 0) {
425                 logger.debug("Current thing channels added: {}", channelsAdded);
426                 updateThing(thingBuilder.build());
427             }
428             return true;
429         } catch (JsonIOException | JsonSyntaxException e) {
430             logger.warn("Error parsing database Json", e);
431         } catch (IOException e) {
432             logger.warn("Error reading database file", e);
433         } catch (Exception e) {
434             logger.warn("Error creating channel structure", e);
435         }
436         return false;
437     }
438
439     private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, @Nullable String channel, String channelType,
440             @Nullable String datatype, String friendlyName) {
441         if (channel == null || channel.isEmpty() || datatype == null || datatype.isEmpty()) {
442             logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
443                     getThing().getUID());
444             return null;
445         }
446         ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
447
448         // TODO: Need to understand if this harms anything. If yes, channel only to be added when not there already.
449         // current way allows to have no issues when channels are changing.
450         if (getThing().getChannel(channel) != null) {
451             logger.info("Channel '{}' for thing {} already exist... removing", channel, getThing().getUID());
452             thingBuilder.withoutChannel(new ChannelUID(getThing().getUID(), channel));
453         }
454         ChannelBuilder newChannel = ChannelBuilder.create(channelUID, datatype).withLabel(friendlyName);
455         boolean useGenericChannelType = false;
456         if (!channelType.isBlank()) {
457             ChannelTypeUID channelTypeUID = new ChannelTypeUID(channelType);
458             if (channelTypeRegistry.getChannelType(channelTypeUID) != null) {
459                 newChannel = newChannel.withType(channelTypeUID);
460             } else {
461                 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID,
462                         getThing().getUID());
463                 useGenericChannelType = true;
464             }
465         } else {
466             useGenericChannelType = true;
467         }
468         if (useGenericChannelType) {
469             newChannel = newChannel.withType(new ChannelTypeUID(BINDING_ID, datatype.toLowerCase()));
470         }
471         thingBuilder.withChannel(newChannel.build());
472         return channelUID;
473     }
474
475     private @Nullable MiIoBasicChannel getChannel(String parameter) {
476         for (MiIoBasicChannel refreshEntry : refreshList) {
477             if (refreshEntry.getProperty().equals(parameter)) {
478                 return refreshEntry;
479             }
480         }
481         logger.trace("Did not find channel for {} in {}", parameter, refreshList);
482         return null;
483     }
484
485     private void updatePropsFromJsonArray(MiIoSendCommand response) {
486         JsonArray res = response.getResult().getAsJsonArray();
487         JsonArray para = parser.parse(response.getCommandString()).getAsJsonObject().get("params").getAsJsonArray();
488         if (res.size() != para.size()) {
489             logger.debug("Unexpected size different. Request size {},  response size {}. (Req: {}, Resp:{})",
490                     para.size(), res.size(), para, res);
491             return;
492         }
493         for (int i = 0; i < para.size(); i++) {
494             // This is a miot parameter
495             String param;
496             final JsonElement paraElement = para.get(i);
497             if (paraElement.isJsonObject()) { // miot channel
498                 param = paraElement.getAsJsonObject().get("did").getAsString();
499             } else {
500                 param = paraElement.getAsString();
501             }
502             JsonElement val = res.get(i);
503             if (val.isJsonNull()) {
504                 logger.debug("Property '{}' returned null (is it supported?).", param);
505                 continue;
506             } else if (val.isJsonObject()) { // miot channel
507                 val = val.getAsJsonObject().get("value");
508             }
509             MiIoBasicChannel basicChannel = getChannel(param);
510             updateChannel(basicChannel, param, val);
511         }
512     }
513
514     private void updatePropsFromJsonObject(MiIoSendCommand response) {
515         JsonObject res = response.getResult().getAsJsonObject();
516         for (Object k : res.keySet()) {
517             String param = (String) k;
518             JsonElement val = res.get(param);
519             if (val.isJsonNull()) {
520                 logger.debug("Property '{}' returned null (is it supported?).", param);
521                 continue;
522             }
523             MiIoBasicChannel basicChannel = getChannel(param);
524             updateChannel(basicChannel, param, val);
525         }
526     }
527
528     private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
529         JsonElement val = value;
530         if (basicChannel == null) {
531             logger.debug("Channel not found for {}", param);
532             return;
533         }
534         final String transformation = basicChannel.getTransfortmation();
535         if (transformation != null) {
536             JsonElement transformed = Conversions.execute(transformation, val);
537             logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
538                     transformed);
539             val = transformed;
540         }
541         try {
542             String[] chType = basicChannel.getType().toLowerCase().split(":");
543             switch (chType[0]) {
544                 case "number":
545                     quantityTypeUpdate(basicChannel, val, chType.length > 1 ? chType[1] : "");
546                     break;
547                 case "dimmer":
548                     updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
549                     break;
550                 case "string":
551                     updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
552                     break;
553                 case "switch":
554                     updateState(basicChannel.getChannel(), val.getAsString().toLowerCase().equals("on")
555                             || val.getAsString().toLowerCase().equals("true") ? OnOffType.ON : OnOffType.OFF);
556                     break;
557                 case "color":
558                     Color rgb = new Color(val.getAsInt());
559                     HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
560                     updateState(basicChannel.getChannel(), hsb);
561                     break;
562                 default:
563                     logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
564             }
565         } catch (Exception e) {
566             logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
567                     basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
568             logger.trace("Property update error detail:", e);
569         }
570     }
571
572     private void quantityTypeUpdate(MiIoBasicChannel basicChannel, JsonElement val, String type) {
573         if (!basicChannel.getUnit().isBlank()) {
574             Unit<?> unit = MiIoQuantiyTypes.get(basicChannel.getUnit());
575             if (unit != null) {
576                 logger.debug("'{}' channel '{}' has unit '{}' with symbol '{}'.", getThing().getUID(),
577                         basicChannel.getChannel(), basicChannel.getUnit(), unit);
578                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), unit));
579             } else {
580                 logger.debug("Unit '{}' used by '{}' channel '{}' is not found.. using default unit.",
581                         getThing().getUID(), basicChannel.getUnit(), basicChannel.getChannel());
582             }
583         }
584         // if no unit is provided or unit not found use default units, these units have so far been seen for miio
585         // devices
586         switch (type.toLowerCase()) {
587             case "temperature":
588                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SIUnits.CELSIUS));
589                 break;
590             case "electriccurrent":
591                 updateState(basicChannel.getChannel(),
592                         new QuantityType<>(val.getAsBigDecimal(), SmartHomeUnits.AMPERE));
593                 break;
594             case "energy":
595                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SmartHomeUnits.WATT));
596                 break;
597             case "time":
598                 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SmartHomeUnits.HOUR));
599                 break;
600             default:
601                 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
602         }
603     }
604
605     @Override
606     public void onMessageReceived(MiIoSendCommand response) {
607         super.onMessageReceived(response);
608         if (response.isError()) {
609             return;
610         }
611         try {
612             switch (response.getCommand()) {
613                 case MIIO_INFO:
614                     break;
615                 case GET_VALUE:
616                 case GET_PROPERTIES:
617                 case GET_PROPERTY:
618                     if (response.getResult().isJsonArray()) {
619                         updatePropsFromJsonArray(response);
620                     } else if (response.getResult().isJsonObject()) {
621                         updatePropsFromJsonObject(response);
622                     }
623                     break;
624                 default:
625                     if (refreshListCustomCommands.containsKey(response.getMethod())) {
626                         logger.debug("Processing custom refresh command response for !{}", response.getMethod());
627                         MiIoBasicChannel ch = refreshListCustomCommands.get(response.getMethod());
628                         if (response.getResult().isJsonArray()) {
629                             JsonArray cmdResponse = response.getResult().getAsJsonArray();
630                             final String transformation = ch.getTransfortmation();
631                             if (transformation == null || transformation.isBlank()) {
632                                 updateChannel(ch, ch.getChannel(),
633                                         cmdResponse.get(0).isJsonPrimitive() ? cmdResponse.get(0)
634                                                 : new JsonPrimitive(cmdResponse.get(0).toString()));
635                             } else {
636                                 updateChannel(ch, ch.getChannel(), cmdResponse);
637                             }
638                         } else {
639                             updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
640                         }
641                     }
642                     break;
643             }
644         } catch (Exception e) {
645             logger.debug("Error while handing message {}", response.getResponse(), e);
646         }
647     }
648 }