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.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.LinkedHashSet;
23 import java.util.List;
25 import java.util.Map.Entry;
27 import java.util.concurrent.TimeUnit;
29 import javax.measure.Unit;
30 import javax.measure.format.MeasurementParseException;
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;
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;
82 * The {@link MiIoBasicHandler} is responsible for handling commands, which are
83 * sent to one of the channels.
85 * @author Marcel Verpaalen - Initial contribution
88 public class MiIoBasicHandler extends MiIoAbstractHandler {
89 private final Logger logger = LoggerFactory.getLogger(MiIoBasicHandler.class);
90 private boolean hasChannelStructure;
92 private final ExpiringCache<Boolean> updateDataCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
93 miIoScheduler.schedule(this::updateData, 0, TimeUnit.SECONDS);
97 List<MiIoBasicChannel> refreshList = new ArrayList<>();
98 private Map<String, MiIoBasicChannel> refreshListCustomCommands = new HashMap<>();
100 private @Nullable MiIoBasicDevice miioDevice;
101 private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
102 private ChannelTypeRegistry channelTypeRegistry;
103 private BasicChannelTypeProvider basicChannelTypeProvider;
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;
114 public void initialize() {
116 hasChannelStructure = false;
117 isIdentified = false;
118 refreshList = new ArrayList<>();
119 refreshListCustomCommands = new HashMap<>();
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();
130 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
134 if (handleCommandsChannels(channelUID, command)) {
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) {
143 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
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$")) {
154 String cmd = action.getCommand();
155 CommandParameterType paramType = action.getparameterType();
156 if (command instanceof QuantityType) {
157 QuantityType<?> qtc = null;
159 if (!miIoBasicChannel.getUnit().isBlank()) {
160 Unit<?> unit = MiIoQuantiyTypes.get(miIoBasicChannel.getUnit());
162 qtc = ((QuantityType<?>) command).toUnit(unit);
165 } catch (MeasurementParseException e) {
169 command = new DecimalType(qtc.toBigDecimal());
171 logger.debug("Could not convert QuantityType to '{}'", miIoBasicChannel.getUnit());
172 command = new DecimalType(((QuantityType<?>) command).toBigDecimal());
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);
188 logger.debug("Unsupported command for COLOR: {}", command);
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);
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()));
214 value = new JsonPrimitive(command.toString().toLowerCase());
216 if (paramType == CommandParameterType.EMPTY) {
217 value = new JsonArray();
219 final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
220 if (miIoDeviceActionCondition != null) {
221 value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
224 // Check for miot channel
226 if (action.isMiOtAction()) {
227 value = miotActionTransform(action, miIoBasicChannel, value);
228 } else if (miIoBasicChannel.isMiOt()) {
229 value = miotTransform(miIoBasicChannel, value);
232 if (paramType != CommandParameterType.NONE && paramType != CommandParameterType.ONOFFPARA
234 if (parameters.size() > 0) {
235 parameters.set(valuePos, value);
237 parameters.add(value);
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();
245 cmd = cmd + parameters.toString();
248 logger.debug("Sending command {}", cmd);
251 if (miIoDeviceActionCondition != null) {
252 logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
253 miIoDeviceActionCondition.getName());
255 logger.debug("Command not send. Value null");
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());
269 logger.debug("Actions not loaded yet, or none available");
273 private void forceStatusUpdate() {
274 updateDataCache.invalidateValue();
275 miIoScheduler.schedule(() -> {
277 }, 3000, TimeUnit.MILLISECONDS);
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);
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());
296 json.add("in", value);
302 protected synchronized void updateData() {
303 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
304 final MiIoAsyncCommunication miioCom = getConnection();
306 if (!hasConnection() || skipUpdate() || miioCom == null) {
309 checkChannelStructure();
311 sendCommand(MiIoCommand.MIIO_INFO);
313 final MiIoBasicDevice midevice = miioDevice;
314 if (midevice != null) {
315 refreshProperties(midevice);
316 refreshCustomProperties(midevice);
319 } catch (Exception e) {
320 logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
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());
331 String cmd = miChannel.getChannelCustomRefreshCommand();
332 if (!cmd.startsWith("/")) {
333 cmds.put(sendCommand(miChannel.getChannelCustomRefreshCommand()), miChannel.getChannel());
335 if (cloudServer.isBlank()) {
336 logger.debug("Cloudserver empty. Skipping refresh for {} channel '{}'", getThing().getUID(),
337 miChannel.getChannel());
339 cmds.put(sendCommand(cmd, cloudServer), miChannel.getChannel());
345 private boolean refreshProperties(MiIoBasicDevice device) {
346 MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
347 int maxProperties = device.getDevice().getMaxProperties();
348 JsonArray getPropString = new JsonArray();
349 for (MiIoBasicChannel miChannel : refreshList) {
350 if (!isLinked(miChannel.getChannel())) {
351 logger.debug("Skip refresh of channel {} for {} as it is not linked", miChannel.getChannel(),
352 getThing().getUID());
355 JsonElement property;
356 if (miChannel.isMiOt()) {
357 JsonObject json = new JsonObject();
358 json.addProperty("did", miChannel.getProperty());
359 json.addProperty("siid", miChannel.getSiid());
360 json.addProperty("piid", miChannel.getPiid());
363 property = new JsonPrimitive(miChannel.getProperty());
365 getPropString.add(property);
366 if (getPropString.size() >= maxProperties) {
367 sendRefreshProperties(command, getPropString);
368 getPropString = new JsonArray();
371 if (getPropString.size() > 0) {
372 sendRefreshProperties(command, getPropString);
377 private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
378 sendCommand(command, getPropString.toString());
382 * Checks if the channel structure has been build already based on the model data. If not build it.
384 private void checkChannelStructure() {
385 final MiIoBindingConfiguration configuration = this.configuration;
386 if (configuration == null) {
389 if (!hasChannelStructure) {
390 if (configuration.model.isEmpty()) {
391 logger.debug("Model needs to be determined");
392 isIdentified = false;
394 hasChannelStructure = buildChannelStructure(configuration.model);
397 if (hasChannelStructure) {
398 refreshList = new ArrayList<>();
399 refreshListCustomCommands = new HashMap<>();
400 final MiIoBasicDevice miioDevice = this.miioDevice;
401 if (miioDevice != null) {
402 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
403 if (miChannel.getRefresh()) {
404 if (miChannel.getChannelCustomRefreshCommand().isBlank()) {
405 refreshList.add(miChannel);
407 String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
408 refreshListCustomCommands.put(i.trim(), miChannel);
417 private boolean buildChannelStructure(String deviceName) {
418 logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
419 URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
421 logger.warn("Database entry for model '{}' cannot be found.", deviceName);
425 JsonObject deviceMapping = Utils.convertFileToJSON(fn);
426 logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
427 Gson gson = new GsonBuilder().serializeNulls().create();
428 miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
429 for (Channel ch : getThing().getChannels()) {
430 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
432 ThingBuilder thingBuilder = editThing();
433 int channelsAdded = 0;
435 // make a map of the actions
436 actions = new HashMap<>();
437 final MiIoBasicDevice device = this.miioDevice;
438 if (device != null) {
439 for (Channel cn : getThing().getChannels()) {
440 logger.trace("Channel '{}' for thing {} already exist... removing", cn.getUID(),
441 getThing().getUID());
442 if (!PERSISTENT_CHANNELS.contains(cn.getUID().getId().toString())) {
443 thingBuilder.withoutChannels(cn);
446 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
447 logger.debug("properties {}", miChannel);
448 if (!miChannel.getType().isEmpty()) {
449 basicChannelTypeProvider.addChannelType(miChannel, deviceName);
450 ChannelUID channelUID = addChannel(thingBuilder, miChannel, deviceName);
451 if (channelUID != null) {
452 actions.put(channelUID, miChannel);
455 logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
456 miChannel.getFriendlyName());
459 logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
460 miChannel.getFriendlyName());
464 // only update if channels were added/removed
465 if (channelsAdded > 0) {
466 logger.debug("Current thing channels added: {}", channelsAdded);
467 updateThing(thingBuilder.build());
470 } catch (JsonIOException | JsonSyntaxException e) {
471 logger.warn("Error parsing database Json", e);
472 } catch (IOException e) {
473 logger.warn("Error reading database file", e);
474 } catch (Exception e) {
475 logger.warn("Error creating channel structure", e);
480 private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, MiIoBasicChannel miChannel, String model) {
481 String channel = miChannel.getChannel();
482 String dataType = miChannel.getType();
483 if (channel.isEmpty() || dataType.isEmpty()) {
484 logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
485 getThing().getUID());
488 ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
489 ChannelBuilder newChannel = ChannelBuilder.create(channelUID, dataType).withLabel(miChannel.getFriendlyName());
490 boolean useGeneratedChannelType = false;
491 if (!miChannel.getChannelType().isBlank()) {
492 ChannelTypeUID channelTypeUID = new ChannelTypeUID(miChannel.getChannelType());
493 if (channelTypeRegistry.getChannelType(channelTypeUID) != null) {
494 newChannel = newChannel.withType(channelTypeUID);
495 final LinkedHashSet<String> tags = miChannel.getTags();
496 if (tags != null && !tags.isEmpty()) {
497 newChannel.withDefaultTags(tags);
500 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID, model);
501 useGeneratedChannelType = true;
504 useGeneratedChannelType = true;
506 if (useGeneratedChannelType) {
507 newChannel = newChannel
508 .withType(new ChannelTypeUID(BINDING_ID, model.toUpperCase().replace(".", "_") + "_" + channel));
509 final Set<String> tags = miChannel.getTags();
510 if (tags != null && !tags.isEmpty()) {
511 newChannel.withDefaultTags(tags);
514 thingBuilder.withChannel(newChannel.build());
518 private @Nullable MiIoBasicChannel getChannel(String parameter) {
519 for (MiIoBasicChannel refreshEntry : refreshList) {
520 if (refreshEntry.getProperty().equals(parameter)) {
524 logger.trace("Did not find channel for {} in {}", parameter, refreshList);
528 private @Nullable MiIoBasicChannel getCustomRefreshChannel(String channelName) {
529 for (MiIoBasicChannel refreshEntry : refreshListCustomCommands.values()) {
530 if (refreshEntry.getChannel().equals(channelName)) {
534 logger.trace("Did not find channel for {} in {}", channelName, refreshList);
538 private void updatePropsFromJsonArray(MiIoSendCommand response) {
539 JsonArray res = response.getResult().getAsJsonArray();
540 JsonArray para = JsonParser.parseString(response.getCommandString()).getAsJsonObject().get("params")
542 if (res.size() != para.size()) {
543 logger.debug("Unexpected size different. Request size {}, response size {}. (Req: {}, Resp:{})",
544 para.size(), res.size(), para, res);
547 for (int i = 0; i < para.size(); i++) {
548 // This is a miot parameter
550 final JsonElement paraElement = para.get(i);
551 if (paraElement.isJsonObject()) { // miot channel
552 param = paraElement.getAsJsonObject().get("did").getAsString();
554 param = paraElement.getAsString();
556 JsonElement val = res.get(i);
557 if (val.isJsonNull()) {
558 logger.debug("Property '{}' returned null (is it supported?).", param);
560 } else if (val.isJsonObject()) { // miot channel
561 val = val.getAsJsonObject().get("value");
563 MiIoBasicChannel basicChannel = getChannel(param);
564 updateChannel(basicChannel, param, val);
568 private void updatePropsFromJsonObject(MiIoSendCommand response) {
569 JsonObject res = response.getResult().getAsJsonObject();
570 for (Object k : res.keySet()) {
571 String param = (String) k;
572 JsonElement val = res.get(param);
573 if (val.isJsonNull()) {
574 logger.debug("Property '{}' returned null (is it supported?).", param);
577 MiIoBasicChannel basicChannel = getChannel(param);
578 updateChannel(basicChannel, param, val);
582 private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
583 JsonElement val = value;
584 if (basicChannel == null) {
585 logger.debug("Channel not found for {}", param);
588 final String transformation = basicChannel.getTransformation();
589 if (transformation != null) {
590 JsonElement transformed = Conversions.execute(transformation, val);
591 logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
596 String[] chType = basicChannel.getType().toLowerCase().split(":");
599 quantityTypeUpdate(basicChannel, val, chType.length > 1 ? chType[1] : "");
602 updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
605 if (val.isJsonPrimitive()) {
606 updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
608 updateState(basicChannel.getChannel(), new StringType(val.toString()));
612 if (val.getAsJsonPrimitive().isNumber()) {
613 updateState(basicChannel.getChannel(), val.getAsInt() > 0 ? OnOffType.ON : OnOffType.OFF);
615 String strVal = val.getAsString().toLowerCase();
616 updateState(basicChannel.getChannel(),
617 "on".equals(strVal) || "true".equals(strVal) ? OnOffType.ON : OnOffType.OFF);
621 if (val.isJsonPrimitive()
622 && (val.getAsJsonPrimitive().isNumber() || val.getAsString().matches("^[0-9]+$"))) {
623 Color rgb = new Color(val.getAsInt());
624 HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
625 updateState(basicChannel.getChannel(), hsb);
628 HSBType hsb = HSBType.valueOf(val.getAsString().replace("[", "").replace("]", ""));
629 updateState(basicChannel.getChannel(), hsb);
630 } catch (IllegalArgumentException e) {
631 logger.debug("Failed updating channel '{}'. Could not convert '{}' to color",
632 basicChannel.getChannel(), val.getAsString());
637 logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
639 } catch (Exception e) {
640 logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
641 basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
642 logger.trace("Property update error detail:", e);
646 private void quantityTypeUpdate(MiIoBasicChannel basicChannel, JsonElement val, String type) {
647 if (!basicChannel.getUnit().isBlank()) {
648 Unit<?> unit = MiIoQuantiyTypes.get(basicChannel.getUnit());
650 logger.debug("'{}' channel '{}' has unit '{}' with symbol '{}'.", getThing().getUID(),
651 basicChannel.getChannel(), basicChannel.getUnit(), unit);
652 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), unit));
655 "Unit '{}' used by '{}' channel '{}' is not found in conversion table... Trying anyway to submit as the update.",
656 basicChannel.getUnit(), getThing().getUID(), basicChannel.getChannel());
657 updateState(basicChannel.getChannel(),
658 new QuantityType<>(val.getAsBigDecimal().toPlainString() + " " + basicChannel.getUnit()));
662 // if no unit is provided or unit not found use default units, these units have so far been seen for miio
664 switch (type.toLowerCase()) {
666 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SIUnits.CELSIUS));
668 case "electriccurrent":
669 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.AMPERE));
672 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.WATT));
675 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.HOUR));
678 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
683 public void onMessageReceived(MiIoSendCommand response) {
684 super.onMessageReceived(response);
685 if (response.isError()) {
689 switch (response.getCommand()) {
695 if (response.getResult().isJsonArray()) {
696 updatePropsFromJsonArray(response);
697 } else if (response.getResult().isJsonObject()) {
698 updatePropsFromJsonObject(response);
702 String channel = cmds.get(response.getId());
703 if (channel != null) {
704 logger.debug("Processing custom refresh command response for '{}' - {}", response.getMethod(),
705 response.getResult());
706 final MiIoBasicChannel ch = getCustomRefreshChannel(channel);
708 if (response.getResult().isJsonArray()) {
709 JsonArray cmdResponse = response.getResult().getAsJsonArray();
710 final String transformation = ch.getTransformation();
711 if (transformation == null || transformation.isBlank()) {
712 JsonElement response0 = cmdResponse.get(0);
713 updateChannel(ch, ch.getChannel(), response0.isJsonPrimitive() ? response0
714 : new JsonPrimitive(response0.toString()));
716 updateChannel(ch, ch.getChannel(), cmdResponse);
719 updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
722 cmds.remove(response.getId());
726 } catch (Exception e) {
727 logger.debug("Error while handing message {}", response.getResponse(), e);