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.i18n.LocaleProvider;
53 import org.openhab.core.i18n.TranslationProvider;
54 import org.openhab.core.library.types.DecimalType;
55 import org.openhab.core.library.types.HSBType;
56 import org.openhab.core.library.types.OnOffType;
57 import org.openhab.core.library.types.OpenClosedType;
58 import org.openhab.core.library.types.PercentType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.library.types.StringType;
61 import org.openhab.core.library.unit.SIUnits;
62 import org.openhab.core.library.unit.Units;
63 import org.openhab.core.thing.Channel;
64 import org.openhab.core.thing.ChannelUID;
65 import org.openhab.core.thing.Thing;
66 import org.openhab.core.thing.binding.builder.ChannelBuilder;
67 import org.openhab.core.thing.binding.builder.ThingBuilder;
68 import org.openhab.core.thing.type.ChannelTypeRegistry;
69 import org.openhab.core.thing.type.ChannelTypeUID;
70 import org.openhab.core.types.Command;
71 import org.openhab.core.types.RefreshType;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 import com.google.gson.Gson;
76 import com.google.gson.GsonBuilder;
77 import com.google.gson.JsonArray;
78 import com.google.gson.JsonElement;
79 import com.google.gson.JsonIOException;
80 import com.google.gson.JsonObject;
81 import com.google.gson.JsonParser;
82 import com.google.gson.JsonPrimitive;
83 import com.google.gson.JsonSyntaxException;
86 * The {@link MiIoBasicHandler} is responsible for handling commands, which are
87 * sent to one of the channels.
89 * @author Marcel Verpaalen - Initial contribution
92 public class MiIoBasicHandler extends MiIoAbstractHandler {
93 private final Logger logger = LoggerFactory.getLogger(MiIoBasicHandler.class);
94 private boolean hasChannelStructure;
96 private final ExpiringCache<Boolean> updateDataCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
97 miIoScheduler.schedule(this::updateData, 0, TimeUnit.SECONDS);
101 List<MiIoBasicChannel> refreshList = new ArrayList<>();
102 private Map<String, MiIoBasicChannel> refreshListCustomCommands = new HashMap<>();
104 private @Nullable MiIoBasicDevice miioDevice;
105 private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
106 private ChannelTypeRegistry channelTypeRegistry;
107 private BasicChannelTypeProvider basicChannelTypeProvider;
108 private Map<String, Integer> customRefreshInterval = new HashMap<>();
110 public MiIoBasicHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
111 CloudConnector cloudConnector, ChannelTypeRegistry channelTypeRegistry,
112 BasicChannelTypeProvider basicChannelTypeProvider, TranslationProvider i18nProvider,
113 LocaleProvider localeProvider) {
114 super(thing, miIoDatabaseWatchService, cloudConnector, i18nProvider, localeProvider);
115 this.channelTypeRegistry = channelTypeRegistry;
116 this.basicChannelTypeProvider = basicChannelTypeProvider;
120 public void initialize() {
122 hasChannelStructure = false;
123 isIdentified = false;
124 refreshList = new ArrayList<>();
125 refreshListCustomCommands = new HashMap<>();
129 public void handleCommand(ChannelUID channelUID, Command receivedCommand) {
130 Command command = receivedCommand;
131 deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
132 if (command == RefreshType.REFRESH) {
133 if (updateDataCache.isExpired()) {
134 logger.debug("Refreshing {}", channelUID);
135 updateDataCache.getValue();
137 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
141 if (handleCommandsChannels(channelUID, command)) {
145 logger.debug("Locating action for {} channel '{}': '{}'", getThing().getUID(), channelUID.getId(), command);
146 if (!actions.isEmpty()) {
147 final MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
148 if (miIoBasicChannel != null) {
150 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
152 JsonElement value = null;
153 JsonArray parameters = action.getParameters().deepCopy();
154 for (int i = 0; i < action.getParameters().size(); i++) {
155 JsonElement p = action.getParameters().get(i);
156 if (p.isJsonPrimitive() && p.getAsString().toLowerCase().contains("$value$")) {
161 String cmd = action.getCommand();
162 CommandParameterType paramType = action.getparameterType();
163 if (command instanceof QuantityType) {
164 QuantityType<?> qtc = null;
166 if (!miIoBasicChannel.getUnit().isBlank()) {
167 Unit<?> unit = MiIoQuantiyTypes.get(miIoBasicChannel.getUnit());
169 qtc = ((QuantityType<?>) command).toUnit(unit);
172 } catch (MeasurementParseException e) {
176 command = new DecimalType(qtc.toBigDecimal());
178 logger.debug("Could not convert QuantityType to '{}'", miIoBasicChannel.getUnit());
179 command = new DecimalType(((QuantityType<?>) command).toBigDecimal());
182 if (paramType == CommandParameterType.OPENCLOSE) {
183 if (command instanceof OpenClosedType) {
184 value = new JsonPrimitive(command == OpenClosedType.OPEN ? "open" : "close");
186 value = new JsonPrimitive(("ON".contentEquals(command.toString().toUpperCase())
187 || "1".contentEquals(command.toString())) ? "open" : "close");
190 if (paramType == CommandParameterType.OPENCLOSENUMBER) {
191 if (command instanceof OpenClosedType) {
192 value = new JsonPrimitive(command == OpenClosedType.OPEN ? 1 : 0);
194 value = new JsonPrimitive(("ON".contentEquals(command.toString().toUpperCase())
195 || "1".contentEquals(command.toString())) ? 1 : 0);
198 if (paramType == CommandParameterType.OPENCLOSESWITCH) {
199 if (command instanceof OpenClosedType) {
200 value = new JsonPrimitive(command == OpenClosedType.OPEN ? "on" : "off");
202 value = new JsonPrimitive(("ON".contentEquals(command.toString().toUpperCase())
203 || "1".contentEquals(command.toString())) ? "on" : "off");
206 if (paramType == CommandParameterType.COLOR) {
207 if (command instanceof HSBType) {
208 HSBType hsb = (HSBType) command;
209 Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360,
210 hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100);
211 value = new JsonPrimitive(
212 (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue());
213 } else if (command instanceof DecimalType) {
214 // actually brightness is being set instead of a color
215 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
216 } else if (command instanceof OnOffType) {
217 value = new JsonPrimitive(command == OnOffType.ON ? 100 : 0);
219 logger.debug("Unsupported command for COLOR: {}", command);
221 } else if (command instanceof OnOffType) {
222 if (paramType == CommandParameterType.ONOFF) {
223 value = new JsonPrimitive(command == OnOffType.ON ? "on" : "off");
224 } else if (paramType == CommandParameterType.ONOFFPARA) {
225 cmd = cmd.replace("*", command == OnOffType.ON ? "on" : "off");
226 value = new JsonArray();
227 } else if (paramType == CommandParameterType.ONOFFBOOL) {
228 boolean boolCommand = command == OnOffType.ON;
229 value = new JsonPrimitive(boolCommand);
230 } else if (paramType == CommandParameterType.ONOFFBOOLSTRING) {
231 value = new JsonPrimitive(command == OnOffType.ON ? "true" : "false");
232 } else if (paramType == CommandParameterType.ONOFFNUMBER) {
233 value = new JsonPrimitive(command == OnOffType.ON ? 1 : 0);
235 } else if (command instanceof DecimalType) {
236 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
237 } else if (command instanceof StringType) {
238 if (paramType == CommandParameterType.STRING) {
239 value = new JsonPrimitive(command.toString().toLowerCase());
240 } else if (paramType == CommandParameterType.CUSTOMSTRING) {
241 value = new JsonPrimitive(parameters.get(valuePos).getAsString().replace("$value",
242 command.toString().toLowerCase()));
245 value = new JsonPrimitive(command.toString().toLowerCase());
247 if (paramType == CommandParameterType.EMPTY) {
248 value = parameters.deepCopy();
250 final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
251 if (miIoDeviceActionCondition != null) {
252 value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
255 // Check for miot channel
257 if (action.isMiOtAction()) {
258 value = miotActionTransform(action, miIoBasicChannel, value);
259 } else if (miIoBasicChannel.isMiOt()) {
260 value = miotTransform(miIoBasicChannel, value);
263 if (paramType != CommandParameterType.NONE && paramType != CommandParameterType.ONOFFPARA
265 if (parameters.size() > 0) {
266 parameters.set(valuePos, value);
268 parameters.add(value);
271 if (action.isMiOtAction() && parameters.size() > 0 && parameters.get(0).isJsonObject()) {
272 // hack as unlike any other commands miot actions parameters appear to be send as a json object
273 // instead of a json array
274 cmd = cmd + parameters.get(0).getAsJsonObject().toString();
276 cmd = cmd + parameters.toString();
279 logger.debug("Sending command {}", cmd);
282 if (miIoDeviceActionCondition != null) {
283 logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
284 miIoDeviceActionCondition.getName());
286 logger.debug("Command not send. Value null");
291 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
292 if (logger.isTraceEnabled()) {
293 for (Entry<ChannelUID, MiIoBasicChannel> a : actions.entrySet()) {
294 logger.trace("Available entries: {} : {}", a.getKey(), a.getValue().getFriendlyName());
300 logger.debug("Actions not loaded yet, or none available");
304 private void forceStatusUpdate() {
305 updateDataCache.invalidateValue();
306 miIoScheduler.schedule(() -> {
308 }, 3000, TimeUnit.MILLISECONDS);
311 private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
312 JsonObject json = new JsonObject();
313 json.addProperty("did", miIoBasicChannel.getChannel());
314 json.addProperty("siid", miIoBasicChannel.getSiid());
315 json.addProperty("piid", miIoBasicChannel.getPiid());
316 json.add("value", value);
320 private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
321 @Nullable JsonElement value) {
322 JsonObject json = new JsonObject();
323 json.addProperty("did", miIoBasicChannel.getChannel());
324 json.addProperty("siid", action.getSiid());
325 json.addProperty("aiid", action.getAiid());
327 json.add("in", value);
333 protected synchronized void updateData() {
334 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
335 final MiIoAsyncCommunication miioCom = getConnection();
337 if (!hasConnection() || skipUpdate() || miioCom == null) {
340 checkChannelStructure();
342 sendCommand(MiIoCommand.MIIO_INFO);
344 final MiIoBasicDevice midevice = miioDevice;
345 if (midevice != null) {
346 deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
347 refreshProperties(midevice);
348 refreshCustomProperties(midevice);
351 } catch (Exception e) {
352 logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
356 private boolean customRefreshIntervalCheck(MiIoBasicChannel miChannel) {
357 if (miChannel.getRefreshInterval() > 1) {
358 int iteration = customRefreshInterval.getOrDefault(miChannel.getChannel(), 0);
360 customRefreshInterval.put(miChannel.getChannel(), miChannel.getRefreshInterval() - 1);
362 logger.debug("Skip refresh of channel {} for {}. Next refresh in {} cycles.", miChannel.getChannel(),
363 getThing().getUID(), iteration);
364 customRefreshInterval.put(miChannel.getChannel(), iteration - 1);
371 private boolean linkedChannelCheck(MiIoBasicChannel miChannel) {
372 if (!isLinked(miChannel.getChannel())) {
373 logger.debug("Skip refresh of channel {} for {} as it is not linked", miChannel.getChannel(),
374 getThing().getUID());
380 private void refreshCustomProperties(MiIoBasicDevice midevice) {
381 for (MiIoBasicChannel miChannel : refreshListCustomCommands.values()) {
382 if (customRefreshIntervalCheck(miChannel) || !linkedChannelCheck(miChannel)) {
385 final JsonElement para = miChannel.getCustomRefreshParameters();
386 String cmd = miChannel.getChannelCustomRefreshCommand() + (para != null ? para.toString() : "");
387 if (!cmd.startsWith("/")) {
388 cmds.put(sendCommand(cmd), miChannel.getChannel());
390 if (cloudServer.isBlank()) {
391 logger.debug("Cloudserver empty. Skipping refresh for {} channel '{}'", getThing().getUID(),
392 miChannel.getChannel());
394 cmds.put(sendCommand(cmd, cloudServer), miChannel.getChannel());
400 private boolean refreshProperties(MiIoBasicDevice device) {
401 MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
402 int maxProperties = device.getDevice().getMaxProperties();
403 JsonArray getPropString = new JsonArray();
404 for (MiIoBasicChannel miChannel : refreshList) {
405 if (customRefreshIntervalCheck(miChannel) || !linkedChannelCheck(miChannel)) {
408 JsonElement property;
409 if (miChannel.isMiOt()) {
410 JsonObject json = new JsonObject();
411 json.addProperty("did", miChannel.getProperty());
412 json.addProperty("siid", miChannel.getSiid());
413 json.addProperty("piid", miChannel.getPiid());
416 property = new JsonPrimitive(miChannel.getProperty());
418 getPropString.add(property);
419 if (getPropString.size() >= maxProperties) {
420 sendRefreshProperties(command, getPropString);
421 getPropString = new JsonArray();
424 if (getPropString.size() > 0) {
425 sendRefreshProperties(command, getPropString);
430 private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
431 sendCommand(command, getPropString.toString());
435 * Checks if the channel structure has been build already based on the model data. If not build it.
437 private void checkChannelStructure() {
438 final MiIoBindingConfiguration configuration = this.configuration;
439 if (configuration == null) {
442 if (!hasChannelStructure) {
443 if (configuration.model.isEmpty()) {
444 logger.debug("Model needs to be determined");
445 isIdentified = false;
447 hasChannelStructure = buildChannelStructure(configuration.model);
450 if (hasChannelStructure) {
451 refreshList = new ArrayList<>();
452 refreshListCustomCommands = new HashMap<>();
453 final MiIoBasicDevice miioDevice = this.miioDevice;
454 if (miioDevice != null) {
455 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
456 if (miChannel.getRefresh()) {
457 if (miChannel.getChannelCustomRefreshCommand().isBlank()) {
458 refreshList.add(miChannel);
460 String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
461 refreshListCustomCommands.put(i.trim(), miChannel);
470 private boolean buildChannelStructure(String deviceName) {
471 logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
472 URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
474 logger.warn("Database entry for model '{}' cannot be found.", deviceName);
478 JsonObject deviceMapping = Utils.convertFileToJSON(fn);
479 logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
480 String key = fn.getFile().replaceFirst("/database/", "").split("json")[0];
481 Gson gson = new GsonBuilder().serializeNulls().create();
482 miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
483 for (Channel ch : getThing().getChannels()) {
484 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
486 ThingBuilder thingBuilder = editThing();
487 int channelsAdded = 0;
489 // make a map of the actions
490 actions = new HashMap<>();
491 final MiIoBasicDevice device = this.miioDevice;
492 if (device != null) {
493 for (Channel cn : getThing().getChannels()) {
494 logger.trace("Channel '{}' for thing {} already exist... removing", cn.getUID(),
495 getThing().getUID());
496 if (!PERSISTENT_CHANNELS.contains(cn.getUID().getId().toString())) {
497 thingBuilder.withoutChannels(cn);
500 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
501 logger.debug("properties {}", miChannel);
502 if (!miChannel.getType().isEmpty()) {
503 basicChannelTypeProvider.addChannelType(miChannel, deviceName);
504 ChannelUID channelUID = addChannel(thingBuilder, miChannel, deviceName, key);
505 if (channelUID != null) {
506 actions.put(channelUID, miChannel);
509 logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
510 miChannel.getFriendlyName());
513 logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
514 miChannel.getFriendlyName());
518 // only update if channels were added/removed
519 if (channelsAdded > 0) {
520 logger.debug("Current thing channels added: {}", channelsAdded);
521 updateThing(thingBuilder.build());
524 } catch (JsonIOException | JsonSyntaxException e) {
525 logger.warn("Error parsing database Json", e);
526 } catch (IOException e) {
527 logger.warn("Error reading database file", e);
528 } catch (Exception e) {
529 logger.warn("Error creating channel structure", e);
534 private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, MiIoBasicChannel miChannel, String model,
536 String channel = miChannel.getChannel();
537 String dataType = miChannel.getType();
538 if (channel.isEmpty() || dataType.isEmpty()) {
539 logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
540 getThing().getUID());
543 ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
544 String label = getLocalText(I18N_CHANNEL_PREFIX + key + channel, miChannel.getFriendlyName());
545 ChannelBuilder newChannel = ChannelBuilder.create(channelUID, dataType).withLabel(label);
546 boolean useGeneratedChannelType = false;
547 if (!miChannel.getChannelType().isBlank()) {
548 ChannelTypeUID channelTypeUID = new ChannelTypeUID(miChannel.getChannelType());
549 if (channelTypeRegistry.getChannelType(channelTypeUID) != null) {
550 newChannel = newChannel.withType(channelTypeUID);
551 final LinkedHashSet<String> tags = miChannel.getTags();
552 if (tags != null && !tags.isEmpty()) {
553 newChannel.withDefaultTags(tags);
556 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID, model);
557 useGeneratedChannelType = true;
560 useGeneratedChannelType = true;
562 if (useGeneratedChannelType) {
563 newChannel = newChannel
564 .withType(new ChannelTypeUID(BINDING_ID, model.toUpperCase().replace(".", "_") + "_" + channel));
565 final Set<String> tags = miChannel.getTags();
566 if (tags != null && !tags.isEmpty()) {
567 newChannel.withDefaultTags(tags);
570 thingBuilder.withChannel(newChannel.build());
574 private @Nullable MiIoBasicChannel getChannel(String parameter) {
575 for (MiIoBasicChannel refreshEntry : refreshList) {
576 if (refreshEntry.getProperty().equals(parameter)) {
580 logger.trace("Did not find channel for {} in {}", parameter, refreshList);
584 private @Nullable MiIoBasicChannel getCustomRefreshChannel(String channelName) {
585 for (MiIoBasicChannel refreshEntry : refreshListCustomCommands.values()) {
586 if (refreshEntry.getChannel().equals(channelName)) {
590 logger.trace("Did not find channel for {} in {}", channelName, refreshList);
594 private void updatePropsFromJsonArray(MiIoSendCommand response) {
595 JsonArray res = response.getResult().getAsJsonArray();
596 JsonArray para = JsonParser.parseString(response.getCommandString()).getAsJsonObject().get("params")
598 if (res.size() != para.size()) {
599 logger.debug("Unexpected size different. Request size {}, response size {}. (Req: {}, Resp:{})",
600 para.size(), res.size(), para, res);
603 for (int i = 0; i < para.size(); i++) {
604 // This is a miot parameter
606 final JsonElement paraElement = para.get(i);
607 if (paraElement.isJsonObject()) { // miot channel
608 param = paraElement.getAsJsonObject().get("did").getAsString();
610 param = paraElement.getAsString();
612 JsonElement val = res.get(i);
613 if (val.isJsonNull()) {
614 logger.debug("Property '{}' returned null (is it supported?).", param);
616 } else if (val.isJsonObject()) { // miot channel
617 val = val.getAsJsonObject().get("value");
619 MiIoBasicChannel basicChannel = getChannel(param);
620 updateChannel(basicChannel, param, val);
624 private void updatePropsFromJsonObject(MiIoSendCommand response) {
625 JsonObject res = response.getResult().getAsJsonObject();
626 for (Object k : res.keySet()) {
627 String param = (String) k;
628 JsonElement val = res.get(param);
629 if (val.isJsonNull()) {
630 logger.debug("Property '{}' returned null (is it supported?).", param);
633 MiIoBasicChannel basicChannel = getChannel(param);
634 updateChannel(basicChannel, param, val);
638 private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
639 JsonElement val = value;
640 deviceVariables.put(param, val);
641 if (basicChannel == null) {
642 logger.debug("Channel not found for {}", param);
645 final String transformation = basicChannel.getTransformation();
646 if (transformation != null) {
647 JsonElement transformed = Conversions.execute(transformation, val, deviceVariables);
648 logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
653 String[] chType = basicChannel.getType().toLowerCase().split(":");
656 quantityTypeUpdate(basicChannel, val, chType.length > 1 ? chType[1] : "");
659 updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
662 if (val.isJsonPrimitive()) {
663 updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
665 updateState(basicChannel.getChannel(), new StringType(val.toString()));
669 if (val.getAsJsonPrimitive().isNumber()) {
670 updateState(basicChannel.getChannel(), val.getAsInt() > 0 ? OnOffType.ON : OnOffType.OFF);
672 String strVal = val.getAsString().toLowerCase();
673 updateState(basicChannel.getChannel(),
674 "on".equals(strVal) || "true".equals(strVal) || "1".equals(strVal) ? OnOffType.ON
679 if (val.getAsJsonPrimitive().isNumber()) {
680 updateState(basicChannel.getChannel(),
681 val.getAsInt() > 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
683 String strVal = val.getAsString().toLowerCase();
684 updateState(basicChannel.getChannel(),
685 "open".equals(strVal) || "on".equals(strVal) || "true".equals(strVal)
686 || "1".equals(strVal) ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
690 if (val.isJsonPrimitive()
691 && (val.getAsJsonPrimitive().isNumber() || val.getAsString().matches("^[0-9]+$"))) {
692 Color rgb = new Color(val.getAsInt());
693 HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
694 updateState(basicChannel.getChannel(), hsb);
697 HSBType hsb = HSBType.valueOf(val.getAsString().replace("[", "").replace("]", ""));
698 updateState(basicChannel.getChannel(), hsb);
699 } catch (IllegalArgumentException e) {
700 logger.debug("Failed updating channel '{}'. Could not convert '{}' to color",
701 basicChannel.getChannel(), val.getAsString());
706 logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
708 } catch (Exception e) {
709 logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
710 basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
711 logger.trace("Property update error detail:", e);
715 private void quantityTypeUpdate(MiIoBasicChannel basicChannel, JsonElement val, String type) {
716 if (!basicChannel.getUnit().isBlank()) {
717 Unit<?> unit = MiIoQuantiyTypes.get(basicChannel.getUnit());
719 logger.debug("'{}' channel '{}' has unit '{}' with symbol '{}'.", getThing().getUID(),
720 basicChannel.getChannel(), basicChannel.getUnit(), unit);
721 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), unit));
724 "Unit '{}' used by '{}' channel '{}' is not found in conversion table... Trying anyway to submit as the update.",
725 basicChannel.getUnit(), getThing().getUID(), basicChannel.getChannel());
726 updateState(basicChannel.getChannel(),
727 new QuantityType<>(val.getAsBigDecimal().toPlainString() + " " + basicChannel.getUnit()));
731 // if no unit is provided or unit not found use default units, these units have so far been seen for miio
733 switch (type.toLowerCase()) {
735 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), SIUnits.CELSIUS));
737 case "electriccurrent":
738 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.AMPERE));
741 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.WATT));
744 updateState(basicChannel.getChannel(), new QuantityType<>(val.getAsBigDecimal(), Units.HOUR));
747 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
752 public void onMessageReceived(MiIoSendCommand response) {
753 super.onMessageReceived(response);
754 if (response.isError()) {
758 switch (response.getCommand()) {
761 case GET_DEVICE_PROPERTY_EXP:
765 if (response.getResult().isJsonArray()) {
766 updatePropsFromJsonArray(response);
767 } else if (response.getResult().isJsonObject()) {
768 updatePropsFromJsonObject(response);
772 String channel = cmds.get(response.getId());
773 if (channel != null) {
774 logger.debug("Processing custom refresh command response for '{}' - {}", response.getMethod(),
775 response.getResult());
776 final MiIoBasicChannel ch = getCustomRefreshChannel(channel);
778 if (response.getResult().isJsonArray()) {
779 JsonArray cmdResponse = response.getResult().getAsJsonArray();
780 final String transformation = ch.getTransformation();
781 if (transformation == null || transformation.isBlank()) {
782 JsonElement response0 = cmdResponse.get(0);
783 updateChannel(ch, ch.getChannel(), response0.isJsonPrimitive() ? response0
784 : new JsonPrimitive(response0.toString()));
786 updateChannel(ch, ch.getChannel(), cmdResponse);
789 updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
792 cmds.remove(response.getId());
796 } catch (Exception e) {
797 logger.debug("Error while handing message {}", response.getResponse(), e);