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