2 * Copyright (c) 2010-2020 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.CHANNEL_COMMAND;
17 import java.awt.Color;
18 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
29 import org.openhab.binding.miio.internal.MiIoCommand;
30 import org.openhab.binding.miio.internal.MiIoCryptoException;
31 import org.openhab.binding.miio.internal.MiIoSendCommand;
32 import org.openhab.binding.miio.internal.Utils;
33 import org.openhab.binding.miio.internal.basic.ActionConditions;
34 import org.openhab.binding.miio.internal.basic.CommandParameterType;
35 import org.openhab.binding.miio.internal.basic.Conversions;
36 import org.openhab.binding.miio.internal.basic.MiIoBasicChannel;
37 import org.openhab.binding.miio.internal.basic.MiIoBasicDevice;
38 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
39 import org.openhab.binding.miio.internal.basic.MiIoDeviceAction;
40 import org.openhab.binding.miio.internal.basic.MiIoDeviceActionCondition;
41 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
42 import org.openhab.core.cache.ExpiringCache;
43 import org.openhab.core.library.types.DecimalType;
44 import org.openhab.core.library.types.HSBType;
45 import org.openhab.core.library.types.OnOffType;
46 import org.openhab.core.library.types.PercentType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.thing.Channel;
49 import org.openhab.core.thing.ChannelUID;
50 import org.openhab.core.thing.Thing;
51 import org.openhab.core.thing.binding.builder.ChannelBuilder;
52 import org.openhab.core.thing.binding.builder.ThingBuilder;
53 import org.openhab.core.thing.type.ChannelTypeRegistry;
54 import org.openhab.core.thing.type.ChannelTypeUID;
55 import org.openhab.core.types.Command;
56 import org.openhab.core.types.RefreshType;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 import com.google.gson.Gson;
61 import com.google.gson.GsonBuilder;
62 import com.google.gson.JsonArray;
63 import com.google.gson.JsonElement;
64 import com.google.gson.JsonIOException;
65 import com.google.gson.JsonObject;
66 import com.google.gson.JsonPrimitive;
67 import com.google.gson.JsonSyntaxException;
70 * The {@link MiIoBasicHandler} is responsible for handling commands, which are
71 * sent to one of the channels.
73 * @author Marcel Verpaalen - Initial contribution
76 public class MiIoBasicHandler extends MiIoAbstractHandler {
77 private final Logger logger = LoggerFactory.getLogger(MiIoBasicHandler.class);
78 private boolean hasChannelStructure;
80 private final ExpiringCache<Boolean> updateDataCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
81 scheduler.schedule(this::updateData, 0, TimeUnit.SECONDS);
85 List<MiIoBasicChannel> refreshList = new ArrayList<>();
86 private Map<String, MiIoBasicChannel> refreshListCustomCommands = new HashMap<>();
88 private @Nullable MiIoBasicDevice miioDevice;
89 private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
90 private ChannelTypeRegistry channelTypeRegistry;
92 public MiIoBasicHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
93 ChannelTypeRegistry channelTypeRegistry) {
94 super(thing, miIoDatabaseWatchService);
95 this.channelTypeRegistry = channelTypeRegistry;
99 public void initialize() {
101 hasChannelStructure = false;
102 isIdentified = false;
103 refreshList = new ArrayList<>();
104 refreshListCustomCommands = new HashMap<>();
108 public void handleCommand(ChannelUID channelUID, Command command) {
109 if (command == RefreshType.REFRESH) {
110 if (updateDataCache.isExpired()) {
111 logger.debug("Refreshing {}", channelUID);
112 updateDataCache.getValue();
114 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
118 if (channelUID.getId().equals(CHANNEL_COMMAND)) {
119 cmds.put(sendCommand(command.toString()), command.toString());
122 logger.debug("Locating action for channel '{}': '{}'", channelUID.getId(), command);
123 if (!actions.isEmpty()) {
124 if (actions.containsKey(channelUID)) {
126 MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
127 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
129 JsonElement value = null;
130 JsonArray parameters = action.getParameters().deepCopy();
131 for (int i = 0; i < action.getParameters().size(); i++) {
132 JsonElement p = action.getParameters().get(i);
133 if (p.isJsonPrimitive() && p.getAsString().toLowerCase().contains("$value$")) {
138 String cmd = action.getCommand();
139 CommandParameterType paramType = action.getparameterType();
140 if (paramType == CommandParameterType.COLOR) {
141 if (command instanceof HSBType) {
142 HSBType hsb = (HSBType) command;
143 Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360,
144 hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100);
145 value = new JsonPrimitive(
146 (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue());
147 } else if (command instanceof DecimalType) {
148 // actually brightness is being set instead of a color
149 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
150 } else if (command instanceof OnOffType) {
151 value = new JsonPrimitive(command == OnOffType.ON ? 100 : 0);
153 logger.debug("Unsupported command for COLOR: {}", command);
155 } else if (command instanceof OnOffType) {
156 if (paramType == CommandParameterType.ONOFF) {
157 value = new JsonPrimitive(command == OnOffType.ON ? "on" : "off");
158 } else if (paramType == CommandParameterType.ONOFFPARA) {
159 cmd = cmd.replace("*", command == OnOffType.ON ? "on" : "off");
160 value = new JsonArray();
161 } else if (paramType == CommandParameterType.ONOFFBOOL) {
162 boolean boolCommand = command == OnOffType.ON;
163 value = new JsonPrimitive(boolCommand);
164 } else if (paramType == CommandParameterType.ONOFFBOOLSTRING) {
165 value = new JsonPrimitive(command == OnOffType.ON ? "true" : "false");
167 } else if (command instanceof DecimalType) {
168 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
169 } else if (command instanceof StringType) {
170 if (paramType == CommandParameterType.STRING) {
171 value = new JsonPrimitive(command.toString().toLowerCase());
172 } else if (paramType == CommandParameterType.CUSTOMSTRING) {
173 value = new JsonPrimitive(parameters.get(valuePos).getAsString().replace("$value",
174 command.toString().toLowerCase()));
177 value = new JsonPrimitive(command.toString().toLowerCase());
179 if (paramType == CommandParameterType.EMPTY) {
180 value = new JsonArray();
182 final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
183 if (miIoDeviceActionCondition != null) {
184 value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
187 // Check for miot channel
189 if (action.isMiOtAction()) {
190 value = miotActionTransform(action, miIoBasicChannel, value);
191 } else if (miIoBasicChannel.isMiOt()) {
192 value = miotTransform(miIoBasicChannel, value);
195 if (paramType != CommandParameterType.NONE && paramType != CommandParameterType.ONOFFPARA
197 if (parameters.size() > 0) {
198 parameters.set(valuePos, value);
200 parameters.add(value);
203 cmd = cmd + parameters.toString();
205 logger.debug("Sending command {}", cmd);
208 if (miIoDeviceActionCondition != null) {
209 logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
210 miIoDeviceActionCondition.getName());
212 logger.debug("Command not send. Value null");
217 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
218 if (logger.isTraceEnabled()) {
219 for (ChannelUID a : actions.keySet()) {
220 logger.trace("Available entries: {} : {}", a, actions.get(a).getFriendlyName());
224 updateDataCache.invalidateValue();
227 logger.debug("Actions not loaded yet");
231 private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
232 JsonObject json = new JsonObject();
233 json.addProperty("did", miIoBasicChannel.getChannel());
234 json.addProperty("siid", miIoBasicChannel.getSiid());
235 json.addProperty("piid", miIoBasicChannel.getPiid());
236 json.add("value", value);
240 private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
241 @Nullable JsonElement value) {
242 JsonObject json = new JsonObject();
243 json.addProperty("did", miIoBasicChannel.getChannel());
244 json.addProperty("siid", action.getSiid());
245 json.addProperty("aiid", action.getAiid());
247 json.add("in", value);
253 protected synchronized void updateData() {
254 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
255 final MiIoAsyncCommunication miioCom = getConnection();
257 if (!hasConnection() || skipUpdate() || miioCom == null) {
260 checkChannelStructure();
262 miioCom.queueCommand(MiIoCommand.MIIO_INFO);
264 final MiIoBasicDevice midevice = miioDevice;
265 if (midevice != null) {
266 refreshProperties(midevice);
267 refreshCustomProperties(midevice);
270 } catch (Exception e) {
271 logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
275 private void refreshCustomProperties(MiIoBasicDevice midevice) {
276 for (MiIoBasicChannel miChannel : refreshListCustomCommands.values()) {
277 sendCommand(miChannel.getChannelCustomRefreshCommand());
281 private boolean refreshProperties(MiIoBasicDevice device) {
282 MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
283 int maxProperties = device.getDevice().getMaxProperties();
284 JsonArray getPropString = new JsonArray();
285 for (MiIoBasicChannel miChannel : refreshList) {
286 JsonElement property;
287 if (miChannel.isMiOt()) {
288 JsonObject json = new JsonObject();
289 json.addProperty("did", miChannel.getProperty());
290 json.addProperty("siid", miChannel.getSiid());
291 json.addProperty("piid", miChannel.getPiid());
294 property = new JsonPrimitive(miChannel.getProperty());
296 getPropString.add(property);
297 if (getPropString.size() >= maxProperties) {
298 sendRefreshProperties(command, getPropString);
299 getPropString = new JsonArray();
302 if (getPropString.size() > 0) {
303 sendRefreshProperties(command, getPropString);
308 private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
310 final MiIoAsyncCommunication miioCom = this.miioCom;
311 if (miioCom != null) {
312 miioCom.queueCommand(command, getPropString.toString());
314 } catch (MiIoCryptoException | IOException e) {
315 logger.debug("Send refresh failed {}", e.getMessage(), e);
320 * Checks if the channel structure has been build already based on the model data. If not build it.
322 private void checkChannelStructure() {
323 final MiIoBindingConfiguration configuration = this.configuration;
324 if (configuration == null) {
327 if (!hasChannelStructure) {
328 if (configuration.model == null || configuration.model.isEmpty()) {
329 logger.debug("Model needs to be determined");
330 isIdentified = false;
332 hasChannelStructure = buildChannelStructure(configuration.model);
335 if (hasChannelStructure) {
336 refreshList = new ArrayList<>();
337 final MiIoBasicDevice miioDevice = this.miioDevice;
338 if (miioDevice != null) {
339 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
340 if (miChannel.getRefresh()) {
341 if (miChannel.getChannelCustomRefreshCommand().isBlank()) {
342 refreshList.add(miChannel);
344 String i = miChannel.getChannelCustomRefreshCommand().split("\\[")[0];
345 refreshListCustomCommands.put(i.trim(), miChannel);
354 private boolean buildChannelStructure(String deviceName) {
355 logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
356 URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
358 logger.warn("Database entry for model '{}' cannot be found.", deviceName);
362 JsonObject deviceMapping = Utils.convertFileToJSON(fn);
363 logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
364 Gson gson = new GsonBuilder().serializeNulls().create();
365 miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
366 for (Channel ch : getThing().getChannels()) {
367 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
369 ThingBuilder thingBuilder = editThing();
370 int channelsAdded = 0;
372 // make a map of the actions
373 actions = new HashMap<>();
374 final MiIoBasicDevice device = this.miioDevice;
375 if (device != null) {
376 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
377 logger.debug("properties {}", miChannel);
378 if (!miChannel.getType().isEmpty()) {
379 ChannelUID channelUID = addChannel(thingBuilder, miChannel.getChannel(),
380 miChannel.getChannelType(), miChannel.getType(), miChannel.getFriendlyName());
381 if (channelUID != null) {
382 actions.put(channelUID, miChannel);
385 logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
386 miChannel.getFriendlyName());
389 logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
390 miChannel.getFriendlyName());
394 // only update if channels were added/removed
395 if (channelsAdded > 0) {
396 logger.debug("Current thing channels added: {}", channelsAdded);
397 updateThing(thingBuilder.build());
400 } catch (JsonIOException | JsonSyntaxException e) {
401 logger.warn("Error parsing database Json", e);
402 } catch (IOException e) {
403 logger.warn("Error reading database file", e);
404 } catch (Exception e) {
405 logger.warn("Error creating channel structure", e);
410 private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, @Nullable String channel, String channelType,
411 @Nullable String datatype, String friendlyName) {
412 if (channel == null || channel.isEmpty() || datatype == null || datatype.isEmpty()) {
413 logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
414 getThing().getUID());
417 ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
419 // TODO: Need to understand if this harms anything. If yes, channel only to be added when not there already.
420 // current way allows to have no issues when channels are changing.
421 if (getThing().getChannel(channel) != null) {
422 logger.info("Channel '{}' for thing {} already exist... removing", channel, getThing().getUID());
423 thingBuilder.withoutChannel(new ChannelUID(getThing().getUID(), channel));
425 ChannelBuilder newChannel = ChannelBuilder.create(channelUID, datatype).withLabel(friendlyName);
426 if (!channelType.isBlank()) {
427 ChannelTypeUID channelTypeUID = new ChannelTypeUID(channelType);
428 if (channelTypeRegistry.getChannelType(channelTypeUID) != null) {
429 newChannel = newChannel.withType(channelTypeUID);
431 logger.debug("ChannelType '{}' is not available. Check the Json file for {}", channelTypeUID,
432 getThing().getUID());
435 thingBuilder.withChannel(newChannel.build());
439 private @Nullable MiIoBasicChannel getChannel(String parameter) {
440 for (MiIoBasicChannel refreshEntry : refreshList) {
441 if (refreshEntry.getProperty().equals(parameter)) {
445 logger.trace("Did not find channel for {} in {}", parameter, refreshList);
449 private void updatePropsFromJsonArray(MiIoSendCommand response) {
450 JsonArray res = response.getResult().getAsJsonArray();
451 JsonArray para = parser.parse(response.getCommandString()).getAsJsonObject().get("params").getAsJsonArray();
452 if (res.size() != para.size()) {
453 logger.debug("Unexpected size different. Request size {}, response size {}. (Req: {}, Resp:{})",
454 para.size(), res.size(), para, res);
457 for (int i = 0; i < para.size(); i++) {
458 // This is a miot parameter
460 final JsonElement paraElement = para.get(i);
461 if (paraElement.isJsonObject()) { // miot channel
462 param = paraElement.getAsJsonObject().get("did").getAsString();
464 param = paraElement.getAsString();
466 JsonElement val = res.get(i);
467 if (val.isJsonNull()) {
468 logger.debug("Property '{}' returned null (is it supported?).", param);
470 } else if (val.isJsonObject()) { // miot channel
471 val = val.getAsJsonObject().get("value");
473 MiIoBasicChannel basicChannel = getChannel(param);
474 updateChannel(basicChannel, param, val);
478 private void updatePropsFromJsonObject(MiIoSendCommand response) {
479 JsonObject res = response.getResult().getAsJsonObject();
480 for (Object k : res.keySet()) {
481 String param = (String) k;
482 JsonElement val = res.get(param);
483 if (val.isJsonNull()) {
484 logger.debug("Property '{}' returned null (is it supported?).", param);
487 MiIoBasicChannel basicChannel = getChannel(param);
488 updateChannel(basicChannel, param, val);
492 private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
493 JsonElement val = value;
494 if (basicChannel == null) {
495 logger.debug("Channel not found for {}", param);
498 final String transformation = basicChannel.getTransfortmation();
499 if (transformation != null) {
500 JsonElement transformed = Conversions.execute(transformation, val);
501 logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
506 switch (basicChannel.getType().toLowerCase()) {
508 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
511 updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
514 updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
517 updateState(basicChannel.getChannel(), val.getAsString().toLowerCase().equals("on")
518 || val.getAsString().toLowerCase().equals("true") ? OnOffType.ON : OnOffType.OFF);
521 Color rgb = new Color(val.getAsInt());
522 HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
523 updateState(basicChannel.getChannel(), hsb);
526 logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
528 } catch (Exception e) {
529 logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
530 basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
531 logger.trace("Property update error detail:", e);
536 public void onMessageReceived(MiIoSendCommand response) {
537 super.onMessageReceived(response);
538 if (response.isError()) {
542 switch (response.getCommand()) {
548 if (response.getResult().isJsonArray()) {
549 updatePropsFromJsonArray(response);
550 } else if (response.getResult().isJsonObject()) {
551 updatePropsFromJsonObject(response);
555 if (refreshListCustomCommands.containsKey(response.getMethod())) {
556 logger.debug("Processing custom refresh command response for !{}", response.getMethod());
557 MiIoBasicChannel ch = refreshListCustomCommands.get(response.getMethod());
558 if (response.getResult().isJsonArray()) {
559 JsonArray cmdResponse = response.getResult().getAsJsonArray();
560 final String transformation = ch.getTransfortmation();
561 if (transformation == null || transformation.isBlank()) {
562 updateChannel(ch, ch.getChannel(),
563 cmdResponse.get(0).isJsonPrimitive() ? cmdResponse.get(0)
564 : new JsonPrimitive(cmdResponse.get(0).toString()));
566 updateChannel(ch, ch.getChannel(), cmdResponse);
569 updateChannel(ch, ch.getChannel(), new JsonPrimitive(response.getResult().toString()));
574 } catch (Exception e) {
575 logger.debug("Error while handing message {}", response.getResponse(), e);