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