2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.miio.internal.handler;
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.*;
17 import java.awt.Color;
18 import java.io.IOException;
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;
26 import java.util.Map.Entry;
28 import java.util.concurrent.TimeUnit;
30 import javax.measure.Unit;
31 import javax.measure.format.MeasurementParseException;
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.library.types.DecimalType;
53 import org.openhab.core.library.types.HSBType;
54 import org.openhab.core.library.types.OnOffType;
55 import org.openhab.core.library.types.OpenClosedType;
56 import org.openhab.core.library.types.PercentType;
57 import org.openhab.core.library.types.QuantityType;
58 import org.openhab.core.library.types.StringType;
59 import org.openhab.core.library.unit.SIUnits;
60 import org.openhab.core.library.unit.Units;
61 import org.openhab.core.thing.Channel;
62 import org.openhab.core.thing.ChannelUID;
63 import org.openhab.core.thing.Thing;
64 import org.openhab.core.thing.binding.builder.ChannelBuilder;
65 import org.openhab.core.thing.binding.builder.ThingBuilder;
66 import org.openhab.core.thing.type.ChannelTypeRegistry;
67 import org.openhab.core.thing.type.ChannelTypeUID;
68 import org.openhab.core.types.Command;
69 import org.openhab.core.types.RefreshType;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
73 import com.google.gson.Gson;
74 import com.google.gson.GsonBuilder;
75 import com.google.gson.JsonArray;
76 import com.google.gson.JsonElement;
77 import com.google.gson.JsonIOException;
78 import com.google.gson.JsonObject;
79 import com.google.gson.JsonParser;
80 import com.google.gson.JsonPrimitive;
81 import com.google.gson.JsonSyntaxException;
84 * The {@link MiIoBasicHandler} is responsible for handling commands, which are
85 * sent to one of the channels.
87 * @author Marcel Verpaalen - Initial contribution
90 public class MiIoBasicHandler extends MiIoAbstractHandler {
91 private final Logger logger = LoggerFactory.getLogger(MiIoBasicHandler.class);
92 private boolean hasChannelStructure;
94 private final ExpiringCache<Boolean> updateDataCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
95 miIoScheduler.schedule(this::updateData, 0, TimeUnit.SECONDS);
99 List<MiIoBasicChannel> refreshList = new ArrayList<>();
100 private Map<String, MiIoBasicChannel> refreshListCustomCommands = new HashMap<>();
102 private @Nullable MiIoBasicDevice miioDevice;
103 private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
104 private ChannelTypeRegistry channelTypeRegistry;
105 private BasicChannelTypeProvider basicChannelTypeProvider;
107 public MiIoBasicHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
108 CloudConnector cloudConnector, ChannelTypeRegistry channelTypeRegistry,
109 BasicChannelTypeProvider basicChannelTypeProvider) {
110 super(thing, miIoDatabaseWatchService, cloudConnector);
111 this.channelTypeRegistry = channelTypeRegistry;
112 this.basicChannelTypeProvider = basicChannelTypeProvider;
116 public void initialize() {
118 hasChannelStructure = false;
119 isIdentified = false;
120 refreshList = new ArrayList<>();
121 refreshListCustomCommands = new HashMap<>();
125 public void handleCommand(ChannelUID channelUID, Command receivedCommand) {
126 Command command = receivedCommand;
127 deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
128 if (command == RefreshType.REFRESH) {
129 if (updateDataCache.isExpired()) {
130 logger.debug("Refreshing {}", channelUID);
131 updateDataCache.getValue();
133 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
137 if (handleCommandsChannels(channelUID, command)) {
141 logger.debug("Locating action for {} channel '{}': '{}'", getThing().getUID(), channelUID.getId(), command);
142 if (!actions.isEmpty()) {
143 final MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
144 if (miIoBasicChannel != null) {
146 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
148 JsonElement value = null;
149 JsonArray parameters = action.getParameters().deepCopy();
150 for (int i = 0; i < action.getParameters().size(); i++) {
151 JsonElement p = action.getParameters().get(i);
152 if (p.isJsonPrimitive() && p.getAsString().toLowerCase().contains("$value$")) {
157 String cmd = action.getCommand();
158 CommandParameterType paramType = action.getparameterType();
159 if (command instanceof QuantityType) {
160 QuantityType<?> qtc = null;
162 if (!miIoBasicChannel.getUnit().isBlank()) {
163 Unit<?> unit = MiIoQuantiyTypes.get(miIoBasicChannel.getUnit());
165 qtc = ((QuantityType<?>) command).toUnit(unit);
168 } catch (MeasurementParseException e) {
172 command = new DecimalType(qtc.toBigDecimal());
174 logger.debug("Could not convert QuantityType to '{}'", miIoBasicChannel.getUnit());
175 command = new DecimalType(((QuantityType<?>) command).toBigDecimal());
178 if (paramType == CommandParameterType.COLOR) {
179 if (command instanceof HSBType) {
180 HSBType hsb = (HSBType) command;
181 Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360,
182 hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100);
183 value = new JsonPrimitive(
184 (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue());
185 } else if (command instanceof DecimalType) {
186 // actually brightness is being set instead of a color
187 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
188 } else if (command instanceof OnOffType) {
189 value = new JsonPrimitive(command == OnOffType.ON ? 100 : 0);
191 logger.debug("Unsupported command for COLOR: {}", command);
193 } else if (command instanceof OnOffType) {
194 if (paramType == CommandParameterType.ONOFF) {
195 value = new JsonPrimitive(command == OnOffType.ON ? "on" : "off");
196 } else if (paramType == CommandParameterType.ONOFFPARA) {
197 cmd = cmd.replace("*", command == OnOffType.ON ? "on" : "off");
198 value = new JsonArray();
199 } else if (paramType == CommandParameterType.ONOFFBOOL) {
200 boolean boolCommand = command == OnOffType.ON;
201 value = new JsonPrimitive(boolCommand);
202 } else if (paramType == CommandParameterType.ONOFFBOOLSTRING) {
203 value = new JsonPrimitive(command == OnOffType.ON ? "true" : "false");
204 } else if (paramType == CommandParameterType.ONOFFNUMBER) {
205 value = new JsonPrimitive(command == OnOffType.ON ? 1 : 0);
207 } else if (command instanceof DecimalType) {
208 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
209 } else if (command instanceof StringType) {
210 if (paramType == CommandParameterType.STRING) {
211 value = new JsonPrimitive(command.toString().toLowerCase());
212 } else if (paramType == CommandParameterType.CUSTOMSTRING) {
213 value = new JsonPrimitive(parameters.get(valuePos).getAsString().replace("$value",
214 command.toString().toLowerCase()));
217 value = new JsonPrimitive(command.toString().toLowerCase());
219 if (paramType == CommandParameterType.EMPTY) {
220 value = new JsonArray();
222 final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
223 if (miIoDeviceActionCondition != null) {
224 value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
227 // Check for miot channel
229 if (action.isMiOtAction()) {
230 value = miotActionTransform(action, miIoBasicChannel, value);
231 } else if (miIoBasicChannel.isMiOt()) {
232 value = miotTransform(miIoBasicChannel, value);
235 if (paramType != CommandParameterType.NONE && paramType != CommandParameterType.ONOFFPARA
237 if (parameters.size() > 0) {
238 parameters.set(valuePos, value);
240 parameters.add(value);
243 if (action.isMiOtAction() && parameters.size() > 0 && parameters.get(0).isJsonObject()) {
244 // hack as unlike any other commands miot actions parameters appear to be send as a json object
245 // instead of a json array
246 cmd = cmd + parameters.get(0).getAsJsonObject().toString();
248 cmd = cmd + parameters.toString();
251 logger.debug("Sending command {}", cmd);
254 if (miIoDeviceActionCondition != null) {
255 logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
256 miIoDeviceActionCondition.getName());
258 logger.debug("Command not send. Value null");
263 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
264 if (logger.isTraceEnabled()) {
265 for (Entry<ChannelUID, MiIoBasicChannel> a : actions.entrySet()) {
266 logger.trace("Available entries: {} : {}", a.getKey(), a.getValue().getFriendlyName());
272 logger.debug("Actions not loaded yet, or none available");
276 private void forceStatusUpdate() {
277 updateDataCache.invalidateValue();
278 miIoScheduler.schedule(() -> {
280 }, 3000, TimeUnit.MILLISECONDS);
283 private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
284 JsonObject json = new JsonObject();
285 json.addProperty("did", miIoBasicChannel.getChannel());
286 json.addProperty("siid", miIoBasicChannel.getSiid());
287 json.addProperty("piid", miIoBasicChannel.getPiid());
288 json.add("value", value);
292 private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
293 @Nullable JsonElement value) {
294 JsonObject json = new JsonObject();
295 json.addProperty("did", miIoBasicChannel.getChannel());
296 json.addProperty("siid", action.getSiid());
297 json.addProperty("aiid", action.getAiid());
299 json.add("in", value);
305 protected synchronized void updateData() {
306 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
307 final MiIoAsyncCommunication miioCom = getConnection();
309 if (!hasConnection() || skipUpdate() || miioCom == null) {
312 checkChannelStructure();
314 sendCommand(MiIoCommand.MIIO_INFO);
316 final MiIoBasicDevice midevice = miioDevice;
317 if (midevice != null) {
318 deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
319 refreshProperties(midevice);
320 refreshCustomProperties(midevice);
323 } catch (Exception e) {
324 logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
328 private void refreshCustomProperties(MiIoBasicDevice midevice) {
329 for (MiIoBasicChannel miChannel : refreshListCustomCommands.values()) {
330 if (!isLinked(miChannel.getChannel())) {
331 logger.debug("Skip refresh of channel {} for {} as it is not linked", miChannel.getChannel(),
332 getThing().getUID());
335 String cmd = miChannel.getChannelCustomRefreshCommand();
336 if (!cmd.startsWith("/")) {
337 cmds.put(sendCommand(miChannel.getChannelCustomRefreshCommand()), miChannel.getChannel());
339 if (cloudServer.isBlank()) {
340 logger.debug("Cloudserver empty. Skipping refresh for {} channel '{}'", getThing().getUID(),
341 miChannel.getChannel());
343 cmds.put(sendCommand(cmd, cloudServer), miChannel.getChannel());
349 private boolean refreshProperties(MiIoBasicDevice device) {
350 MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
351 int maxProperties = device.getDevice().getMaxProperties();
352 JsonArray getPropString = new JsonArray();
353 for (MiIoBasicChannel miChannel : refreshList) {
354 if (!isLinked(miChannel.getChannel())) {
355 logger.debug("Skip refresh of channel {} for {} as it is not linked", miChannel.getChannel(),
356 getThing().getUID());
359 JsonElement property;
360 if (miChannel.isMiOt()) {
361 JsonObject json = new JsonObject();
362 json.addProperty("did", miChannel.getProperty());
363 json.addProperty("siid", miChannel.getSiid());
364 json.addProperty("piid", miChannel.getPiid());
367 property = new JsonPrimitive(miChannel.getProperty());
369 getPropString.add(property);
370 if (getPropString.size() >= maxProperties) {
371 sendRefreshProperties(command, getPropString);
372 getPropString = new JsonArray();
375 if (getPropString.size() > 0) {
376 sendRefreshProperties(command, getPropString);
381 private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
382 sendCommand(command, getPropString.toString());
386 * Checks if the channel structure has been build already based on the model data. If not build it.
388 private void checkChannelStructure() {
389 final MiIoBindingConfiguration configuration = this.configuration;
390 if (configuration == null) {
393 if (!hasChannelStructure) {
394 if (configuration.model.isEmpty()) {
395 logger.debug("Model needs to be determined");
396 isIdentified = false;
398 hasChannelStructure = buildChannelStructure(configuration.model);
401 if (hasChannelStructure) {
402 refreshList = new ArrayList<>();
403 refreshListCustomCommands = new HashMap<>();
404 final MiIoBasicDevice miioDevice = this.miioDevice;
405 if (miioDevice != null) {
406 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
407 if (miChannel.getRefresh()) {
408 if (miChannel.getChannelCustomRefreshCommand().isBlank()) {
409 refreshList.add(miChannel);
411 String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
412 refreshListCustomCommands.put(i.trim(), miChannel);
421 private boolean buildChannelStructure(String deviceName) {
422 logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
423 URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
425 logger.warn("Database entry for model '{}' cannot be found.", deviceName);
429 JsonObject deviceMapping = Utils.convertFileToJSON(fn);
430 logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
431 Gson gson = new GsonBuilder().serializeNulls().create();
432 miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
433 for (Channel ch : getThing().getChannels()) {
434 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
436 ThingBuilder thingBuilder = editThing();
437 int channelsAdded = 0;
439 // make a map of the actions
440 actions = new HashMap<>();
441 final MiIoBasicDevice device = this.miioDevice;
442 if (device != null) {
443 for (Channel cn : getThing().getChannels()) {
444 logger.trace("Channel '{}' for thing {} already exist... removing", cn.getUID(),
445 getThing().getUID());
446 if (!PERSISTENT_CHANNELS.contains(cn.getUID().getId().toString())) {
447 thingBuilder.withoutChannels(cn);
450 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
451 logger.debug("properties {}", miChannel);
452 if (!miChannel.getType().isEmpty()) {
453 basicChannelTypeProvider.addChannelType(miChannel, deviceName);
454 ChannelUID channelUID = addChannel(thingBuilder, miChannel, deviceName);
455 if (channelUID != null) {
456 actions.put(channelUID, miChannel);
459 logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
460 miChannel.getFriendlyName());
463 logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
464 miChannel.getFriendlyName());
468 // only update if channels were added/removed
469 if (channelsAdded > 0) {
470 logger.debug("Current thing channels added: {}", channelsAdded);
471 updateThing(thingBuilder.build());
474 } catch (JsonIOException | JsonSyntaxException e) {
475 logger.warn("Error parsing database Json", e);
476 } catch (IOException e) {
477 logger.warn("Error reading database file", e);
478 } catch (Exception e) {
479 logger.warn("Error creating channel structure", e);
484 private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, MiIoBasicChannel miChannel, String model) {
485 String channel = miChannel.getChannel();
486 String dataType = miChannel.getType();
487 if (channel.isEmpty() || dataType.isEmpty()) {
488 logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
489 getThing().getUID());
492 ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
493 ChannelBuilder newChannel = ChannelBuilder.create(channelUID, dataType).withLabel(miChannel.getFriendlyName());
494 boolean useGeneratedChannelType = false;
495 if (!miChannel.getChannelType().isBlank()) {
496 ChannelTypeUID channelTypeUID = new ChannelTypeUID(miChannel.getChannelType());
497 if (channelTypeRegistry.getChannelType(channelTypeUID) != null) {
498 newChannel = newChannel.withType(channelTypeUID);
499 final LinkedHashSet<String> tags = miChannel.getTags();
500 if (tags != null && !tags.isEmpty()) {
501 newChannel.withDefaultTags(tags);
504 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID, model);
505 useGeneratedChannelType = true;
508 useGeneratedChannelType = true;
510 if (useGeneratedChannelType) {
511 newChannel = newChannel
512 .withType(new ChannelTypeUID(BINDING_ID, model.toUpperCase().replace(".", "_") + "_" + channel));
513 final Set<String> tags = miChannel.getTags();
514 if (tags != null && !tags.isEmpty()) {
515 newChannel.withDefaultTags(tags);
518 thingBuilder.withChannel(newChannel.build());
522 private @Nullable MiIoBasicChannel getChannel(String parameter) {
523 for (MiIoBasicChannel refreshEntry : refreshList) {
524 if (refreshEntry.getProperty().equals(parameter)) {
528 logger.trace("Did not find channel for {} in {}", parameter, refreshList);
532 private @Nullable MiIoBasicChannel getCustomRefreshChannel(String channelName) {
533 for (MiIoBasicChannel refreshEntry : refreshListCustomCommands.values()) {
534 if (refreshEntry.getChannel().equals(channelName)) {
538 logger.trace("Did not find channel for {} in {}", channelName, refreshList);
542 private void updatePropsFromJsonArray(MiIoSendCommand response) {
543 JsonArray res = response.getResult().getAsJsonArray();
544 JsonArray para = JsonParser.parseString(response.getCommandString()).getAsJsonObject().get("params")
546 if (res.size() != para.size()) {
547 logger.debug("Unexpected size different. Request size {}, response size {}. (Req: {}, Resp:{})",
548 para.size(), res.size(), para, res);
551 for (int i = 0; i < para.size(); i++) {
552 // This is a miot parameter
554 final JsonElement paraElement = para.get(i);
555 if (paraElement.isJsonObject()) { // miot channel
556 param = paraElement.getAsJsonObject().get("did").getAsString();
558 param = paraElement.getAsString();
560 JsonElement val = res.get(i);
561 if (val.isJsonNull()) {
562 logger.debug("Property '{}' returned null (is it supported?).", param);
564 } else if (val.isJsonObject()) { // miot channel
565 val = val.getAsJsonObject().get("value");
567 MiIoBasicChannel basicChannel = getChannel(param);
568 updateChannel(basicChannel, param, val);
572 private void updatePropsFromJsonObject(MiIoSendCommand response) {
573 JsonObject res = response.getResult().getAsJsonObject();
574 for (Object k : res.keySet()) {
575 String param = (String) k;
576 JsonElement val = res.get(param);
577 if (val.isJsonNull()) {
578 logger.debug("Property '{}' returned null (is it supported?).", param);
581 MiIoBasicChannel basicChannel = getChannel(param);
582 updateChannel(basicChannel, param, val);
586 private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
587 JsonElement val = value;
588 deviceVariables.put(param, val);
589 if (basicChannel == null) {
590 logger.debug("Channel not found for {}", param);
593 final String transformation = basicChannel.getTransformation();
594 if (transformation != null) {
595 JsonElement transformed = Conversions.execute(transformation, val, deviceVariables);
596 logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
601 String[] chType = basicChannel.getType().toLowerCase().split(":");
604 quantityTypeUpdate(basicChannel, val, chType.length > 1 ? chType[1] : "");
607 updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
610 if (val.isJsonPrimitive()) {
611 updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
613 updateState(basicChannel.getChannel(), new StringType(val.toString()));
617 if (val.getAsJsonPrimitive().isNumber()) {
618 updateState(basicChannel.getChannel(), val.getAsInt() > 0 ? OnOffType.ON : OnOffType.OFF);
620 String strVal = val.getAsString().toLowerCase();
621 updateState(basicChannel.getChannel(),
622 "on".equals(strVal) || "true".equals(strVal) || "1".equals(strVal) ? OnOffType.ON
627 if (val.getAsJsonPrimitive().isNumber()) {
628 updateState(basicChannel.getChannel(),
629 val.getAsInt() > 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
631 String strVal = val.getAsString().toLowerCase();
632 updateState(basicChannel.getChannel(),
633 "on".equals(strVal) || "true".equals(strVal) || "1".equals(strVal) ? OpenClosedType.OPEN
634 : OpenClosedType.CLOSED);
638 if (val.isJsonPrimitive()
639 && (val.getAsJsonPrimitive().isNumber() || val.getAsString().matches("^[0-9]+$"))) {
640 Color rgb = new Color(val.getAsInt());
641 HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
642 updateState(basicChannel.getChannel(), hsb);
645 HSBType hsb = HSBType.valueOf(val.getAsString().replace("[", "").replace("]", ""));
646 updateState(basicChannel.getChannel(), hsb);
647 } catch (IllegalArgumentException e) {
648 logger.debug("Failed updating channel '{}'. Could not convert '{}' to color",
649 basicChannel.getChannel(), val.getAsString());
654 logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
656 } catch (Exception e) {
657 logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
658 basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
659 logger.trace("Property update error detail:", e);
663 private void quantityTypeUpdate(MiIoBasicChannel basicChannel, JsonElement val, String type) {
664 if (!basicChannel.getUnit().isBlank()) {
665 Unit<?> unit = MiIoQuantiyTypes.get(basicChannel.getUnit());
667 logger.debug("'{}' channel '{}' has unit '{}' with symbol '{}'.", getThing().getUID(),
668 basicChannel.getChannel(), basicChannel.getUnit(), unit);
669 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), unit));
672 "Unit '{}' used by '{}' channel '{}' is not found in conversion table... Trying anyway to submit as the update.",
673 basicChannel.getUnit(), getThing().getUID(), basicChannel.getChannel());
674 updateState(basicChannel.getChannel(),
675 new QuantityType<>(val.getAsBigDecimal().toPlainString() + " " + basicChannel.getUnit()));
679 // if no unit is provided or unit not found use default units, these units have so far been seen for miio
681 switch (type.toLowerCase()) {
683 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SIUnits.CELSIUS));
685 case "electriccurrent":
686 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.AMPERE));
689 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.WATT));
692 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.HOUR));
695 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
700 public void onMessageReceived(MiIoSendCommand response) {
701 super.onMessageReceived(response);
702 if (response.isError()) {
706 switch (response.getCommand()) {
712 if (response.getResult().isJsonArray()) {
713 updatePropsFromJsonArray(response);
714 } else if (response.getResult().isJsonObject()) {
715 updatePropsFromJsonObject(response);
719 String channel = cmds.get(response.getId());
720 if (channel != null) {
721 logger.debug("Processing custom refresh command response for '{}' - {}", response.getMethod(),
722 response.getResult());
723 final MiIoBasicChannel ch = getCustomRefreshChannel(channel);
725 if (response.getResult().isJsonArray()) {
726 JsonArray cmdResponse = response.getResult().getAsJsonArray();
727 final String transformation = ch.getTransformation();
728 if (transformation == null || transformation.isBlank()) {
729 JsonElement response0 = cmdResponse.get(0);
730 updateChannel(ch, ch.getChannel(), response0.isJsonPrimitive() ? response0
731 : new JsonPrimitive(response0.toString()));
733 updateChannel(ch, ch.getChannel(), cmdResponse);
736 updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
739 cmds.remove(response.getId());
743 } catch (Exception e) {
744 logger.debug("Error while handing message {}", response.getResponse(), e);