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.ChannelTypeUID;
54 import org.openhab.core.types.Command;
55 import org.openhab.core.types.RefreshType;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import com.google.gson.Gson;
60 import com.google.gson.GsonBuilder;
61 import com.google.gson.JsonArray;
62 import com.google.gson.JsonElement;
63 import com.google.gson.JsonIOException;
64 import com.google.gson.JsonObject;
65 import com.google.gson.JsonPrimitive;
66 import com.google.gson.JsonSyntaxException;
69 * The {@link MiIoBasicHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * @author Marcel Verpaalen - Initial contribution
75 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<>();
87 private @Nullable MiIoBasicDevice miioDevice;
88 private Map<ChannelUID, MiIoBasicChannel> actions = new HashMap<>();
90 public MiIoBasicHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService) {
91 super(thing, miIoDatabaseWatchService);
95 public void initialize() {
97 hasChannelStructure = false;
99 refreshList = new ArrayList<>();
103 public void handleCommand(ChannelUID channelUID, Command command) {
104 if (command == RefreshType.REFRESH) {
105 if (updateDataCache.isExpired()) {
106 logger.debug("Refreshing {}", channelUID);
107 updateDataCache.getValue();
109 logger.debug("Refresh {} skipped. Already refreshing", channelUID);
113 if (channelUID.getId().equals(CHANNEL_COMMAND)) {
114 cmds.put(sendCommand(command.toString()), command.toString());
117 logger.debug("Locating action for channel '{}': '{}'", channelUID.getId(), command);
118 if (!actions.isEmpty()) {
119 if (actions.containsKey(channelUID)) {
121 MiIoBasicChannel miIoBasicChannel = actions.get(channelUID);
122 for (MiIoDeviceAction action : miIoBasicChannel.getActions()) {
124 JsonElement value = null;
125 JsonArray parameters = action.getParameters().deepCopy();
126 for (int i = 0; i < action.getParameters().size(); i++) {
127 JsonElement p = action.getParameters().get(i);
128 if (p.isJsonPrimitive() && p.getAsString().toLowerCase().contains("$value$")) {
133 String cmd = action.getCommand();
134 CommandParameterType paramType = action.getparameterType();
135 if (paramType == CommandParameterType.COLOR) {
136 if (command instanceof HSBType) {
137 HSBType hsb = (HSBType) command;
138 Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360,
139 hsb.getSaturation().floatValue() / 100, hsb.getBrightness().floatValue() / 100);
140 value = new JsonPrimitive(
141 (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue());
142 } else if (command instanceof DecimalType) {
143 // actually brightness is being set instead of a color
144 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
145 } else if (command instanceof OnOffType) {
146 value = new JsonPrimitive(command == OnOffType.ON ? 100 : 0);
148 logger.debug("Unsupported command for COLOR: {}", command);
150 } else if (command instanceof OnOffType) {
151 if (paramType == CommandParameterType.ONOFF) {
152 value = new JsonPrimitive(command == OnOffType.ON ? "on" : "off");
153 } else if (paramType == CommandParameterType.ONOFFPARA) {
154 cmd = cmd.replace("*", command == OnOffType.ON ? "on" : "off");
155 } else if (paramType == CommandParameterType.ONOFFBOOL) {
156 boolean boolCommand = command == OnOffType.ON;
157 value = new JsonPrimitive(boolCommand);
158 } else if (paramType == CommandParameterType.ONOFFBOOLSTRING) {
159 value = new JsonPrimitive(command == OnOffType.ON ? "true" : "false");
161 } else if (command instanceof DecimalType) {
162 value = new JsonPrimitive(((DecimalType) command).toBigDecimal());
163 } else if (command instanceof StringType) {
164 if (paramType == CommandParameterType.STRING) {
165 value = new JsonPrimitive(command.toString().toLowerCase());
166 } else if (paramType == CommandParameterType.CUSTOMSTRING) {
167 value = new JsonPrimitive(parameters.get(valuePos).getAsString().replace("$value",
168 command.toString().toLowerCase()));
171 value = new JsonPrimitive(command.toString().toLowerCase());
173 if (paramType == CommandParameterType.EMPTY) {
174 value = new JsonArray();
176 final MiIoDeviceActionCondition miIoDeviceActionCondition = action.getCondition();
177 if (miIoDeviceActionCondition != null) {
178 value = ActionConditions.executeAction(miIoDeviceActionCondition, deviceVariables, value,
181 // Check for miot channel
183 if (action.isMiOtAction()) {
184 value = miotActionTransform(action, miIoBasicChannel, value);
185 } else if (miIoBasicChannel.isMiOt()) {
186 value = miotTransform(miIoBasicChannel, value);
189 if (paramType != CommandParameterType.NONE && value != null) {
190 if (parameters.size() > 0) {
191 parameters.set(valuePos, value);
193 parameters.add(value);
196 cmd = cmd + parameters.toString();
198 logger.debug("Sending command {}", cmd);
201 if (miIoDeviceActionCondition != null) {
202 logger.debug("Conditional command {} not send, condition '{}' not met", cmd,
203 miIoDeviceActionCondition.getName());
205 logger.debug("Command not send. Value null");
210 logger.debug("Channel Id {} not in mapping.", channelUID.getId());
211 if (logger.isTraceEnabled()) {
212 for (ChannelUID a : actions.keySet()) {
213 logger.trace("Available entries: {} : {}", a, actions.get(a).getFriendlyName());
217 updateDataCache.invalidateValue();
220 logger.debug("Actions not loaded yet");
224 private @Nullable JsonElement miotTransform(MiIoBasicChannel miIoBasicChannel, @Nullable JsonElement value) {
225 JsonObject json = new JsonObject();
226 json.addProperty("did", miIoBasicChannel.getChannel());
227 json.addProperty("siid", miIoBasicChannel.getSiid());
228 json.addProperty("piid", miIoBasicChannel.getPiid());
229 json.add("value", value);
233 private @Nullable JsonElement miotActionTransform(MiIoDeviceAction action, MiIoBasicChannel miIoBasicChannel,
234 @Nullable JsonElement value) {
235 JsonObject json = new JsonObject();
236 json.addProperty("did", miIoBasicChannel.getChannel());
237 json.addProperty("siid", action.getSiid());
238 json.addProperty("aiid", action.getAiid());
240 json.add("in", value);
246 protected synchronized void updateData() {
247 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
248 final MiIoAsyncCommunication miioCom = getConnection();
250 if (!hasConnection() || skipUpdate() || miioCom == null) {
253 checkChannelStructure();
255 miioCom.queueCommand(MiIoCommand.MIIO_INFO);
257 final MiIoBasicDevice midevice = miioDevice;
258 if (midevice != null) {
259 refreshProperties(midevice);
262 } catch (Exception e) {
263 logger.debug("Error while updating '{}': ", getThing().getUID().toString(), e);
267 private boolean refreshProperties(MiIoBasicDevice device) {
268 MiIoCommand command = MiIoCommand.getCommand(device.getDevice().getPropertyMethod());
269 int maxProperties = device.getDevice().getMaxProperties();
270 JsonArray getPropString = new JsonArray();
271 for (MiIoBasicChannel miChannel : refreshList) {
272 JsonElement property;
273 if (miChannel.isMiOt()) {
274 JsonObject json = new JsonObject();
275 json.addProperty("did", miChannel.getProperty());
276 json.addProperty("siid", miChannel.getSiid());
277 json.addProperty("piid", miChannel.getPiid());
280 property = new JsonPrimitive(miChannel.getProperty());
282 getPropString.add(property);
283 if (getPropString.size() >= maxProperties) {
284 sendRefreshProperties(command, getPropString);
285 getPropString = new JsonArray();
288 if (getPropString.size() > 0) {
289 sendRefreshProperties(command, getPropString);
294 private void sendRefreshProperties(MiIoCommand command, JsonArray getPropString) {
296 final MiIoAsyncCommunication miioCom = this.miioCom;
297 if (miioCom != null) {
298 miioCom.queueCommand(command, getPropString.toString());
300 } catch (MiIoCryptoException | IOException e) {
301 logger.debug("Send refresh failed {}", e.getMessage(), e);
306 * Checks if the channel structure has been build already based on the model data. If not build it.
308 private void checkChannelStructure() {
309 final MiIoBindingConfiguration configuration = this.configuration;
310 if (configuration == null) {
313 if (!hasChannelStructure) {
314 if (configuration.model == null || configuration.model.isEmpty()) {
315 logger.debug("Model needs to be determined");
316 isIdentified = false;
318 hasChannelStructure = buildChannelStructure(configuration.model);
321 if (hasChannelStructure) {
322 refreshList = new ArrayList<>();
323 final MiIoBasicDevice miioDevice = this.miioDevice;
324 if (miioDevice != null) {
325 for (MiIoBasicChannel miChannel : miioDevice.getDevice().getChannels()) {
326 if (miChannel.getRefresh()) {
327 refreshList.add(miChannel);
335 private boolean buildChannelStructure(String deviceName) {
336 logger.debug("Building Channel Structure for {} - Model: {}", getThing().getUID().toString(), deviceName);
337 URL fn = miIoDatabaseWatchService.getDatabaseUrl(deviceName);
339 logger.warn("Database entry for model '{}' cannot be found.", deviceName);
343 JsonObject deviceMapping = Utils.convertFileToJSON(fn);
344 logger.debug("Using device database: {} for device {}", fn.getFile(), deviceName);
345 Gson gson = new GsonBuilder().serializeNulls().create();
346 miioDevice = gson.fromJson(deviceMapping, MiIoBasicDevice.class);
347 for (Channel ch : getThing().getChannels()) {
348 logger.debug("Current thing channels {}, type: {}", ch.getUID(), ch.getChannelTypeUID());
350 ThingBuilder thingBuilder = editThing();
351 int channelsAdded = 0;
353 // make a map of the actions
354 actions = new HashMap<>();
355 final MiIoBasicDevice device = this.miioDevice;
356 if (device != null) {
357 for (MiIoBasicChannel miChannel : device.getDevice().getChannels()) {
358 logger.debug("properties {}", miChannel);
359 if (!miChannel.getType().isEmpty()) {
360 ChannelUID channelUID = addChannel(thingBuilder, miChannel.getChannel(),
361 miChannel.getChannelType(), miChannel.getType(), miChannel.getFriendlyName());
362 if (channelUID != null) {
363 actions.put(channelUID, miChannel);
366 logger.debug("Channel for {} ({}) not loaded", miChannel.getChannel(),
367 miChannel.getFriendlyName());
370 logger.debug("Channel {} ({}), not loaded, missing type", miChannel.getChannel(),
371 miChannel.getFriendlyName());
375 // only update if channels were added/removed
376 if (channelsAdded > 0) {
377 logger.debug("Current thing channels added: {}", channelsAdded);
378 updateThing(thingBuilder.build());
381 } catch (JsonIOException | JsonSyntaxException e) {
382 logger.warn("Error parsing database Json", e);
383 } catch (IOException e) {
384 logger.warn("Error reading database file", e);
385 } catch (Exception e) {
386 logger.warn("Error creating channel structure", e);
391 private @Nullable ChannelUID addChannel(ThingBuilder thingBuilder, @Nullable String channel, String channelType,
392 @Nullable String datatype, String friendlyName) {
393 if (channel == null || channel.isEmpty() || datatype == null || datatype.isEmpty()) {
394 logger.info("Channel '{}', UID '{}' cannot be added incorrectly configured database. ", channel,
395 getThing().getUID());
398 ChannelUID channelUID = new ChannelUID(getThing().getUID(), channel);
399 ChannelTypeUID channelTypeUID = new ChannelTypeUID(channelType);
401 // TODO: Need to understand if this harms anything. If yes, channel only to be added when not there already.
402 // current way allows to have no issues when channels are changing.
403 if (getThing().getChannel(channel) != null) {
404 logger.info("Channel '{}' for thing {} already exist... removing", channel, getThing().getUID());
405 thingBuilder.withoutChannel(new ChannelUID(getThing().getUID(), channel));
407 Channel newChannel = ChannelBuilder.create(channelUID, datatype).withType(channelTypeUID)
408 .withLabel(friendlyName).build();
409 thingBuilder.withChannel(newChannel);
413 private @Nullable MiIoBasicChannel getChannel(String parameter) {
414 for (MiIoBasicChannel refreshEntry : refreshList) {
415 if (refreshEntry.getProperty().equals(parameter)) {
419 logger.trace("Did not find channel for {} in {}", parameter, refreshList);
423 private void updatePropsFromJsonArray(MiIoSendCommand response) {
424 JsonArray res = response.getResult().getAsJsonArray();
425 JsonArray para = parser.parse(response.getCommandString()).getAsJsonObject().get("params").getAsJsonArray();
426 if (res.size() != para.size()) {
427 logger.debug("Unexpected size different. Request size {}, response size {}. (Req: {}, Resp:{})",
428 para.size(), res.size(), para, res);
430 for (int i = 0; i < para.size(); i++) {
431 // This is a miot parameter
433 final JsonElement paraElement = para.get(i);
434 if (paraElement.isJsonObject()) { // miot channel
435 param = paraElement.getAsJsonObject().get("did").getAsString();
437 param = paraElement.getAsString();
439 JsonElement val = res.get(i);
440 if (val.isJsonNull()) {
441 logger.debug("Property '{}' returned null (is it supported?).", param);
443 } else if (val.isJsonObject()) { // miot channel
444 val = val.getAsJsonObject().get("value");
446 MiIoBasicChannel basicChannel = getChannel(param);
447 updateChannel(basicChannel, param, val);
451 private void updatePropsFromJsonObject(MiIoSendCommand response) {
452 JsonObject res = response.getResult().getAsJsonObject();
453 for (Object k : res.keySet()) {
454 String param = (String) k;
455 JsonElement val = res.get(param);
456 if (val.isJsonNull()) {
457 logger.debug("Property '{}' returned null (is it supported?).", param);
460 MiIoBasicChannel basicChannel = getChannel(param);
461 updateChannel(basicChannel, param, val);
465 private void updateChannel(@Nullable MiIoBasicChannel basicChannel, String param, JsonElement value) {
466 JsonElement val = value;
467 if (basicChannel == null) {
468 logger.debug("Channel not found for {}", param);
471 final String transformation = basicChannel.getTransfortmation();
472 if (transformation != null) {
473 JsonElement transformed = Conversions.execute(transformation, val);
474 logger.debug("Transformed with '{}': {} {} -> {} ", transformation, basicChannel.getFriendlyName(), val,
479 switch (basicChannel.getType().toLowerCase()) {
481 updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
484 updateState(basicChannel.getChannel(), new PercentType(val.getAsBigDecimal()));
487 updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
490 updateState(basicChannel.getChannel(), val.getAsString().toLowerCase().equals("on")
491 || val.getAsString().toLowerCase().equals("true") ? OnOffType.ON : OnOffType.OFF);
494 Color rgb = new Color(val.getAsInt());
495 HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
496 updateState(basicChannel.getChannel(), hsb);
499 logger.debug("No update logic for channeltype '{}' ", basicChannel.getType());
501 } catch (Exception e) {
502 logger.debug("Error updating {} property {} with '{}' : {}: {}", getThing().getUID(),
503 basicChannel.getChannel(), val, e.getClass().getCanonicalName(), e.getMessage());
504 logger.trace("Property update error detail:", e);
509 public void onMessageReceived(MiIoSendCommand response) {
510 super.onMessageReceived(response);
511 if (response.isError()) {
515 switch (response.getCommand()) {
521 if (response.getResult().isJsonArray()) {
522 updatePropsFromJsonArray(response);
523 } else if (response.getResult().isJsonObject()) {
524 updatePropsFromJsonObject(response);
530 } catch (Exception e) {
531 logger.debug("Error while handing message {}", response.getResponse(), e);