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 sendCommand(miChannel.getChannelCustomRefreshCommand());
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());
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());
353 property = new JsonPrimitive(miChannel.getProperty());
355 getPropString.add(property);
356 if (getPropString.size() >= maxProperties) {
357 sendRefreshProperties(command, getPropString);
358 getPropString = new JsonArray();
361 if (getPropString.size() > 0) {
362 sendRefreshProperties(command, getPropString);
367 private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
368 sendCommand(command, getPropString.toString());
372 * Checks if the channel structure has been build already based on the model data. If not build it.
374 private void checkChannelStructure() {
375 final MiIoBindingConfiguration configuration = this.configuration;
376 if (configuration == null) {
379 if (!hasChannelStructure) {
380 if (configuration.model.isEmpty()) {
381 logger.debug("Model needs to be determined");
382 isIdentified = false;
384 hasChannelStructure = buildChannelStructure(configuration.model);
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);
397 String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
398 refreshListCustomCommands.put(i.trim(), miChannel);
407 private boolean buildChannelStructure(String deviceName) {
408 logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
409 URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
411 logger.warn("Database entry for model '{}' cannot be found.", deviceName);
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());
422 ThingBuilder thingBuilder = editThing();
423 int channelsAdded = 0;
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);
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);
445 logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
446 miChannel.getFriendlyName());
449 logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
450 miChannel.getFriendlyName());
454 // only update if channels were added/removed
455 if (channelsAdded > 0) {
456 logger.debug("Current thing channels added: {}", channelsAdded);
457 updateThing(thingBuilder.build());
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);
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());
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);
490 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID, model);
491 useGeneratedChannelType = true;
494 useGeneratedChannelType = true;
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);
504 thingBuilder.withChannel(newChannel.build());
508 private @Nullable MiIoBasicChannel getChannel(String parameter) {
509 for (MiIoBasicChannel refreshEntry : refreshList) {
510 if (refreshEntry.getProperty().equals(parameter)) {
514 logger.trace("Did not find channel for {} in {}", parameter, refreshList);
518 private void updatePropsFromJsonArray(MiIoSendCommand response) {
519 JsonArray res = response.getResult().getAsJsonArray();
520 JsonArray para = JsonParser.parseString(response.getCommandString()).getAsJsonObject().get("params")
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);
527 for (int i = 0; i < para.size(); i++) {
528 // This is a miot parameter
530 final JsonElement paraElement = para.get(i);
531 if (paraElement.isJsonObject()) { // miot channel
532 param = paraElement.getAsJsonObject().get("did").getAsString();
534 param = paraElement.getAsString();
536 JsonElement val = res.get(i);
537 if (val.isJsonNull()) {
538 logger.debug("Property '{}' returned null (is it supported?).", param);
540 } else if (val.isJsonObject()) { // miot channel
541 val = val.getAsJsonObject().get("value");
543 MiIoBasicChannel basicChannel = getChannel(param);
544 updateChannel(basicChannel, param, val);
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);
557 MiIoBasicChannel basicChannel = getChannel(param);
558 updateChannel(basicChannel, param, val);
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);
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,
576 String[] chType = basicChannel.getType().toLowerCase().split(":");
579 quantityTypeUpdate(basicChannel, val, chType.length > 1 ? chType[1] : "");
582 updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
585 if (val.isJsonPrimitive()) {
586 updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
588 updateState(basicChannel.getChannel(), new StringType(val.toString()));
592 if (val.getAsJsonPrimitive().isNumber()) {
593 updateState(basicChannel.getChannel(), val.getAsInt() > 0 ? OnOffType.ON : OnOffType.OFF);
595 String strVal = val.getAsString().toLowerCase();
596 updateState(basicChannel.getChannel(),
597 "on".equals(strVal) || "true".equals(strVal) ? OnOffType.ON : OnOffType.OFF);
601 if (val.isJsonPrimitive() && val.getAsJsonPrimitive().isNumber()) {
602 Color rgb = new Color(val.getAsInt());
603 HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
604 updateState(basicChannel.getChannel(), hsb);
607 HSBType hsb = HSBType.valueOf(val.getAsString().replace("[", "").replace("]", ""));
608 updateState(basicChannel.getChannel(), hsb);
609 } catch (IllegalArgumentException e) {
610 logger.debug("Failed updating channel '{}'. Could not convert '{}' to color",
611 basicChannel.getChannel(), val.getAsString());
616 logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
618 } catch (Exception e) {
619 logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
620 basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
621 logger.trace("Property update error detail:", e);
625 private void quantityTypeUpdate(MiIoBasicChannel basicChannel, JsonElement val, String type) {
626 if (!basicChannel.getUnit().isBlank()) {
627 Unit<?> unit = MiIoQuantiyTypes.get(basicChannel.getUnit());
629 logger.debug("'{}' channel '{}' has unit '{}' with symbol '{}'.", getThing().getUID(),
630 basicChannel.getChannel(), basicChannel.getUnit(), unit);
631 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), unit));
634 "Unit '{}' used by '{}' channel '{}' is not found in conversion table... Trying anyway to submit as the update.",
635 basicChannel.getUnit(), getThing().getUID(), basicChannel.getChannel());
636 updateState(basicChannel.getChannel(),
637 new QuantityType<>(val.getAsBigDecimal().toPlainString() + " " + basicChannel.getUnit()));
641 // if no unit is provided or unit not found use default units, these units have so far been seen for miio
643 switch (type.toLowerCase()) {
645 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SIUnits.CELSIUS));
647 case "electriccurrent":
648 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.AMPERE));
651 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.WATT));
654 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.HOUR));
657 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
662 public void onMessageReceived(MiIoSendCommand response) {
663 super.onMessageReceived(response);
664 if (response.isError()) {
668 switch (response.getCommand()) {
674 if (response.getResult().isJsonArray()) {
675 updatePropsFromJsonArray(response);
676 } else if (response.getResult().isJsonObject()) {
677 updatePropsFromJsonObject(response);
681 if (refreshListCustomCommands.containsKey(response.getMethod())) {
682 logger.debug("Processing custom refresh command response for '{}' - {}", response.getMethod(),
683 response.getResult());
684 final MiIoBasicChannel ch = refreshListCustomCommands.get(response.getMethod());
686 if (response.getResult().isJsonArray()) {
687 JsonArray cmdResponse = response.getResult().getAsJsonArray();
688 final String transformation = ch.getTransformation();
689 if (transformation == null || transformation.isBlank()) {
690 JsonElement response0 = cmdResponse.get(0);
691 updateChannel(ch, ch.getChannel(), response0.isJsonPrimitive() ? response0
692 : new JsonPrimitive(response0.toString()));
694 updateChannel(ch, ch.getChannel(), cmdResponse);
697 updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
703 } catch (Exception e) {
704 logger.debug("Error while handing message {}", response.getResponse(), e);