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