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.io.IOException;
18 import java.math.BigDecimal;
19 import java.time.Instant;
20 import java.time.LocalDateTime;
21 import java.util.HashMap;
23 import java.util.Map.Entry;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.ScheduledThreadPoolExecutor;
28 import java.util.concurrent.TimeUnit;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.miio.internal.Message;
33 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
34 import org.openhab.binding.miio.internal.MiIoCommand;
35 import org.openhab.binding.miio.internal.MiIoCrypto;
36 import org.openhab.binding.miio.internal.MiIoCryptoException;
37 import org.openhab.binding.miio.internal.MiIoDevices;
38 import org.openhab.binding.miio.internal.MiIoInfoApDTO;
39 import org.openhab.binding.miio.internal.MiIoInfoDTO;
40 import org.openhab.binding.miio.internal.MiIoMessageListener;
41 import org.openhab.binding.miio.internal.MiIoSendCommand;
42 import org.openhab.binding.miio.internal.Utils;
43 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
44 import org.openhab.binding.miio.internal.cloud.CloudConnector;
45 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
46 import org.openhab.core.cache.ExpiringCache;
47 import org.openhab.core.common.NamedThreadFactory;
48 import org.openhab.core.config.core.Configuration;
49 import org.openhab.core.library.types.DecimalType;
50 import org.openhab.core.library.types.StringType;
51 import org.openhab.core.thing.ChannelUID;
52 import org.openhab.core.thing.Thing;
53 import org.openhab.core.thing.ThingStatus;
54 import org.openhab.core.thing.ThingStatusDetail;
55 import org.openhab.core.thing.ThingTypeUID;
56 import org.openhab.core.thing.binding.BaseThingHandler;
57 import org.openhab.core.thing.binding.builder.ThingBuilder;
58 import org.openhab.core.types.Command;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import com.google.gson.Gson;
63 import com.google.gson.GsonBuilder;
64 import com.google.gson.JsonObject;
65 import com.google.gson.JsonPrimitive;
66 import com.google.gson.JsonSyntaxException;
69 * The {@link MiIoAbstractHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * @author Marcel Verpaalen - Initial contribution
75 public abstract class MiIoAbstractHandler extends BaseThingHandler implements MiIoMessageListener {
76 protected static final int MAX_QUEUE = 5;
77 protected static final Gson GSON = new GsonBuilder().create();
78 protected static final String TIMESTAMP = "timestamp";
80 protected ScheduledExecutorService miIoScheduler = scheduler;
81 protected @Nullable ScheduledFuture<?> pollingJob;
82 protected MiIoDevices miDevice = MiIoDevices.UNKNOWN;
83 protected boolean isIdentified;
85 protected byte[] token = new byte[0];
87 protected @Nullable MiIoBindingConfiguration configuration;
88 protected @Nullable MiIoAsyncCommunication miioCom;
89 protected CloudConnector cloudConnector;
90 protected String cloudServer = "";
93 protected Map<Integer, String> cmds = new ConcurrentHashMap<>();
94 protected Map<String, Object> deviceVariables = new HashMap<>();
95 protected final ExpiringCache<String> network = new ExpiringCache<>(CACHE_EXPIRY_NETWORK, () -> {
96 int ret = sendCommand(MiIoCommand.MIIO_INFO);
102 protected static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(5);
103 protected static final long CACHE_EXPIRY_NETWORK = TimeUnit.SECONDS.toMillis(60);
105 private final Logger logger = LoggerFactory.getLogger(MiIoAbstractHandler.class);
106 protected MiIoDatabaseWatchService miIoDatabaseWatchService;
108 public MiIoAbstractHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
109 CloudConnector cloudConnector) {
111 this.miIoDatabaseWatchService = miIoDatabaseWatchService;
112 this.cloudConnector = cloudConnector;
116 public abstract void handleCommand(ChannelUID channelUID, Command command);
118 protected boolean handleCommandsChannels(ChannelUID channelUID, Command command) {
119 String cmd = processSubstitutions(command.toString(), deviceVariables);
120 if (channelUID.getId().equals(CHANNEL_COMMAND)) {
121 cmds.put(sendCommand(cmd), channelUID.getId());
124 if (channelUID.getId().equals(CHANNEL_RPC)) {
125 cmds.put(sendCommand(cmd, cloudServer), channelUID.getId());
132 public void initialize() {
133 logger.debug("Initializing Mi IO device handler '{}' with thingType {}", getThing().getUID(),
134 getThing().getThingTypeUID());
136 ScheduledThreadPoolExecutor miIoScheduler = new ScheduledThreadPoolExecutor(3,
137 new NamedThreadFactory(getThing().getUID().getAsString(), true));
138 miIoScheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
139 miIoScheduler.setRemoveOnCancelPolicy(true);
140 this.miIoScheduler = miIoScheduler;
142 final MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
143 this.configuration = configuration;
144 if (configuration.host.isEmpty()) {
145 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
146 "IP address required. Configure IP address");
149 if (!tokenCheckPass(configuration.token)) {
150 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Token required. Configure token");
153 this.cloudServer = configuration.cloudServer;
154 isIdentified = false;
155 deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
156 deviceVariables.put(PROPERTY_DID, configuration.deviceId);
157 miIoScheduler.schedule(this::initializeData, 1, TimeUnit.SECONDS);
158 int pollingPeriod = configuration.refreshInterval;
159 if (pollingPeriod > 0) {
160 pollingJob = miIoScheduler.scheduleWithFixedDelay(() -> {
163 } catch (Exception e) {
164 logger.debug("Unexpected error during refresh.", e);
166 }, 10, pollingPeriod, TimeUnit.SECONDS);
167 logger.debug("Polling job scheduled to run every {} sec. for '{}'", pollingPeriod, getThing().getUID());
169 logger.debug("Polling job disabled. for '{}'", getThing().getUID());
170 miIoScheduler.schedule(this::updateData, 10, TimeUnit.SECONDS);
172 updateStatus(ThingStatus.OFFLINE);
175 private boolean tokenCheckPass(@Nullable String tokenSting) {
176 if (tokenSting == null) {
179 switch (tokenSting.length()) {
181 token = tokenSting.getBytes();
184 if (!IGNORED_TOKENS.contains(tokenSting)) {
185 token = Utils.hexStringToByteArray(tokenSting);
191 token = Utils.hexStringToByteArray(MiIoCrypto.decryptToken(Utils.hexStringToByteArray(tokenSting)));
192 logger.debug("IOS token decrypted to {}", Utils.getHex(token));
193 } catch (MiIoCryptoException e) {
194 logger.warn("Could not decrypt token {}{}", tokenSting, e.getMessage());
204 public void dispose() {
205 logger.debug("Disposing Xiaomi Mi IO handler '{}'", getThing().getUID());
206 miIoScheduler.shutdown();
207 final ScheduledFuture<?> pollingJob = this.pollingJob;
208 if (pollingJob != null) {
209 pollingJob.cancel(true);
210 this.pollingJob = null;
212 final @Nullable MiIoAsyncCommunication miioCom = this.miioCom;
213 if (miioCom != null) {
214 lastId = miioCom.getId();
215 miioCom.unregisterListener(this);
219 miIoScheduler.shutdownNow();
222 protected int sendCommand(MiIoCommand command) {
223 return sendCommand(command, "[]");
226 protected int sendCommand(MiIoCommand command, String params) {
227 return sendCommand(command.getCommand(), processSubstitutions(params, deviceVariables), getCloudServer(), "");
230 protected int sendCommand(String commandString) {
231 return sendCommand(commandString, getCloudServer());
235 * This is used to execute arbitrary commands by sending to the commands channel. Command parameters to be added
237 * [] brackets. This to allow for unimplemented commands to be executed (e.g. get detailed historical cleaning
240 * @param commandString command to be executed
241 * @param cloud server to be used or empty string for direct sending to the device
242 * @return vacuum response
244 protected int sendCommand(String commandString, String cloudServer) {
245 String command = commandString.trim();
246 command = processSubstitutions(commandString.trim(), deviceVariables);
248 int sb = command.indexOf("[");
249 int cb = command.indexOf("{");
250 if (Math.max(sb, cb) > 0) {
251 int loc = (Math.min(sb, cb) > 0 ? Math.min(sb, cb) : Math.max(sb, cb));
252 param = command.substring(loc).trim();
253 command = command.substring(0, loc).trim();
255 return sendCommand(command, param, cloudServer, "");
258 protected int sendCommand(String command, String params, String cloudServer) {
259 return sendCommand(command, processSubstitutions(params, deviceVariables), cloudServer, "");
263 * Sends commands to the {@link MiIoAsyncCommunication} for transmission to the Mi devices or cloud
265 * @param command (method) to be queued for execution
266 * @param parameters to be send with the command
267 * @param cloud server to be used or empty string for direct sending to the device
268 * @param sending subdevice or empty string for regular device
271 protected int sendCommand(String command, String params, String cloudServer, String sender) {
273 final MiIoAsyncCommunication connection = getConnection();
274 return (connection != null) ? connection.queueCommand(command, params, cloudServer, sender) : 0;
275 } catch (MiIoCryptoException | IOException e) {
276 logger.debug("Command {} for {} failed (type: {}): {}", command.toString(), getThing().getUID(),
277 getThing().getThingTypeUID(), e.getLocalizedMessage());
278 disconnected(e.getMessage());
283 String getCloudServer() {
284 // This can be improved in the future with additional / more advanced options like e.g. directFirst which would
285 // use direct communications and in case of failures fall back to cloud communication. For now we keep it
286 // simple and only have the option for cloud or direct.
287 final MiIoBindingConfiguration configuration = this.configuration;
288 if (configuration != null) {
289 return configuration.communication.equals("cloud") ? cloudServer : "";
294 protected boolean skipUpdate() {
295 final MiIoAsyncCommunication miioCom = this.miioCom;
296 if (!hasConnection() || miioCom == null) {
297 logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
300 if (getThing().getStatusInfo().getStatusDetail().equals(ThingStatusDetail.CONFIGURATION_ERROR)) {
301 logger.debug("Skipping periodic update for '{}'. Thing Status {}", getThing().getUID().toString(),
302 getThing().getStatusInfo().getStatusDetail());
303 sendCommand(MiIoCommand.MIIO_INFO);
306 if (miioCom.getQueueLength() > MAX_QUEUE) {
307 logger.debug("Skipping periodic update for '{}'. {} elements in queue.", getThing().getUID().toString(),
308 miioCom.getQueueLength());
314 protected abstract void updateData();
316 protected boolean updateNetwork(JsonObject networkData) {
318 final MiIoInfoDTO miioInfo = GSON.fromJson(networkData, MiIoInfoDTO.class);
319 final MiIoInfoApDTO ap = miioInfo != null ? miioInfo.ap : null;
320 if (miioInfo != null && ap != null) {
321 if (ap.getSsid() != null) {
322 updateState(CHANNEL_SSID, new StringType(ap.getSsid()));
324 if (ap.getBssid() != null) {
325 updateState(CHANNEL_BSSID, new StringType(ap.getBssid()));
327 if (ap.getRssi() != null) {
328 updateState(CHANNEL_RSSI, new DecimalType(ap.getRssi()));
329 } else if (ap.getWifiRssi() != null) {
330 updateState(CHANNEL_RSSI, new DecimalType(ap.getWifiRssi()));
332 logger.debug("No RSSI info in response");
334 if (miioInfo.life != null) {
335 updateState(CHANNEL_LIFE, new DecimalType(miioInfo.life));
339 } catch (NumberFormatException e) {
340 logger.debug("Could not parse number in network response: {}", networkData);
341 } catch (JsonSyntaxException e) {
342 logger.debug("Could not parse network response: {}", networkData, e);
347 protected boolean hasConnection() {
348 return getConnection() != null;
351 protected void disconnectedNoResponse() {
352 disconnected("No Response from device");
355 protected void disconnected(@Nullable String message) {
356 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
357 message != null ? message : "");
358 final MiIoAsyncCommunication miioCom = this.miioCom;
359 if (miioCom != null) {
360 lastId = miioCom.getId();
365 protected synchronized @Nullable MiIoAsyncCommunication getConnection() {
366 if (miioCom != null) {
369 final MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
370 if (configuration.host.isBlank()) {
374 String deviceId = configuration.deviceId;
375 if (deviceId.length() == 8 && deviceId.matches("^.*[a-zA-Z]+.*$")) {
377 "As per openHAB version 3.2 the deviceId is no longer a string with hexadecimals, instead it is a string with the numeric respresentation of the deviceId. If you continue seeing this message, update deviceId in your thing configuration");
381 if (!deviceId.isBlank() && tokenCheckPass(configuration.token)) {
382 final MiIoAsyncCommunication miioCom = new MiIoAsyncCommunication(configuration.host, token, deviceId,
383 lastId, configuration.timeout, cloudConnector);
384 if (getCloudServer().isBlank()) {
385 logger.debug("Ping Mi deviceId '{}' at {}", deviceId, configuration.host);
386 Message miIoResponse = miioCom.sendPing(configuration.host);
387 if (miIoResponse != null) {
388 logger.debug("Ping response from deviceId '{}' at {}. Time stamp: {}, OH time {}, delta {}",
389 Utils.fromHEX(Utils.getHex(miIoResponse.getDeviceId())), configuration.host,
390 miIoResponse.getTimestamp(), LocalDateTime.now(), miioCom.getTimeDelta());
391 miioCom.registerListener(this);
392 this.miioCom = miioCom;
398 miioCom.registerListener(this);
399 this.miioCom = miioCom;
403 logger.debug("No deviceId defined. Retrieving Mi deviceId");
404 final MiIoAsyncCommunication miioCom = new MiIoAsyncCommunication(configuration.host, token, "", lastId,
405 configuration.timeout, cloudConnector);
406 Message miIoResponse = miioCom.sendPing(configuration.host);
407 if (miIoResponse != null) {
408 deviceId = Utils.fromHEX(Utils.getHex(miIoResponse.getDeviceId()));
409 logger.debug("Ping response from deviceId '{}' at {}. Time stamp: {}, OH time {}, delta {}",
410 deviceId, configuration.host, miIoResponse.getTimestamp(), LocalDateTime.now(),
411 miioCom.getTimeDelta());
412 miioCom.setDeviceId(deviceId);
413 logger.debug("Using retrieved Mi deviceId: {}", deviceId);
414 updateDeviceIdConfig(deviceId);
415 miioCom.registerListener(this);
416 this.miioCom = miioCom;
422 logger.debug("Ping response from deviceId '{}' at {} FAILED", configuration.deviceId, configuration.host);
423 disconnectedNoResponse();
425 } catch (IOException e) {
426 logger.debug("Could not connect to {} at {}", getThing().getUID().toString(), configuration.host);
427 disconnected(e.getMessage());
432 private void updateDeviceIdConfig(String deviceId) {
433 if (!deviceId.isEmpty()) {
434 updateProperty(Thing.PROPERTY_SERIAL_NUMBER, deviceId);
435 Configuration config = editConfiguration();
436 config.put(PROPERTY_DID, deviceId);
437 updateConfiguration(config);
438 deviceVariables.put(PROPERTY_DID, deviceId);
440 logger.debug("Could not update config with deviceId: {}", deviceId);
444 protected boolean initializeData() {
445 this.miioCom = getConnection();
449 protected void refreshNetwork() {
453 protected void defineDeviceType(JsonObject miioInfo) {
454 updateProperties(miioInfo);
455 isIdentified = updateThingType(miioInfo);
458 private void updateProperties(JsonObject miioInfo) {
459 final MiIoInfoDTO info = GSON.fromJson(miioInfo, MiIoInfoDTO.class);
463 Map<String, String> properties = editProperties();
464 if (info.model != null) {
465 properties.put(Thing.PROPERTY_MODEL_ID, info.model);
467 if (info.fwVer != null) {
468 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, info.fwVer);
470 if (info.hwVer != null) {
471 properties.put(Thing.PROPERTY_HARDWARE_VERSION, info.hwVer);
473 if (info.wifiFwVer != null) {
474 properties.put("wifiFirmware", info.wifiFwVer);
476 if (info.mcuFwVer != null) {
477 properties.put("mcuFirmware", info.mcuFwVer);
479 deviceVariables.putAll(properties);
480 updateProperties(properties);
483 protected String processSubstitutions(String cmd, Map<String, Object> deviceVariables) {
484 if (!cmd.contains("$")) {
487 String returnCmd = cmd.replace("\"$", "$").replace("$\"", "$");
488 String cmdParts[] = cmd.split("\\$");
489 if (logger.isTraceEnabled()) {
490 logger.debug("processSubstitutions {} ", cmd);
491 for (Entry<String, Object> e : deviceVariables.entrySet()) {
492 logger.debug("key, value: {} -> {}", e.getKey(), e.getValue());
495 for (String substitute : cmdParts) {
496 if (deviceVariables.containsKey(substitute)) {
497 String replacementString = "";
498 Object replacement = deviceVariables.get(substitute);
499 if (replacement == null) {
500 logger.debug("Replacement for '{}' is null. skipping replacement", substitute);
503 if (replacement instanceof Integer || replacement instanceof Long || replacement instanceof Double
504 || replacement instanceof BigDecimal || replacement instanceof Boolean) {
505 replacementString = replacement.toString();
506 } else if (replacement instanceof JsonPrimitive) {
507 replacementString = ((JsonPrimitive) replacement).getAsString();
508 } else if (replacement instanceof String) {
509 replacementString = "\"" + (String) replacement + "\"";
511 replacementString = String.valueOf(replacement);
513 returnCmd = returnCmd.replace("$" + substitute + "$", replacementString);
519 protected boolean updateThingType(JsonObject miioInfo) {
520 MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
521 String model = miioInfo.get("model").getAsString();
522 miDevice = MiIoDevices.getType(model);
523 if (configuration.model.isEmpty()) {
524 Configuration config = editConfiguration();
525 config.put(PROPERTY_MODEL, model);
526 updateConfiguration(config);
527 configuration = getConfigAs(MiIoBindingConfiguration.class);
529 if (!configuration.model.equals(model)) {
530 logger.info("Mi Device model {} has model config: {}. Unexpected unless manual override", model,
531 configuration.model);
533 if (miDevice.getThingType().equals(getThing().getThingTypeUID())
534 && !(miDevice.getThingType().equals(THING_TYPE_UNSUPPORTED)
535 && miIoDatabaseWatchService.getDatabaseUrl(model) != null)) {
536 logger.debug("Mi Device model {} identified as: {}. Matches thingtype {}", model, miDevice.toString(),
537 miDevice.getThingType().toString());
540 if (getThing().getThingTypeUID().equals(THING_TYPE_MIIO)
541 || getThing().getThingTypeUID().equals(THING_TYPE_UNSUPPORTED)) {
545 "Mi Device model {} identified as: {}, thingtype {}. Does not matches thingtype {}. Unexpected, unless manual override.",
546 miDevice.toString(), miDevice.getThingType(), getThing().getThingTypeUID().toString(),
547 miDevice.getThingType().toString());
555 * Changes the {@link org.openhab.core.thing.type.ThingType} to the right type once it is retrieved from
558 * @param modelId String with the model id
560 private void changeType(final String modelId) {
561 final ScheduledFuture<?> pollingJob = this.pollingJob;
562 if (pollingJob != null) {
563 pollingJob.cancel(true);
564 this.pollingJob = null;
566 miIoScheduler.schedule(() -> {
567 String label = getThing().getLabel();
568 if (label == null || label.startsWith("Xiaomi Mi Device")) {
569 ThingBuilder thingBuilder = editThing();
570 thingBuilder.withLabel(miDevice.getDescription());
571 updateThing(thingBuilder.build());
573 logger.info("Mi Device model {} identified as: {}. Does not match thingtype {}. Changing thingtype to {}",
574 modelId, miDevice.toString(), getThing().getThingTypeUID().toString(),
575 miDevice.getThingType().toString());
576 ThingTypeUID thingTypeUID = MiIoDevices.getType(modelId).getThingType();
577 if (thingTypeUID.equals(THING_TYPE_UNSUPPORTED)
578 && miIoDatabaseWatchService.getDatabaseUrl(modelId) != null) {
579 thingTypeUID = THING_TYPE_BASIC;
581 changeThingType(thingTypeUID, getConfig());
582 }, 10, TimeUnit.SECONDS);
586 public void onStatusUpdated(ThingStatus status, ThingStatusDetail statusDetail) {
587 updateStatus(status, statusDetail);
591 public void onMessageReceived(MiIoSendCommand response) {
592 logger.debug("Received response for device {} type: {}, result: {}, fullresponse: {}",
593 getThing().getUID().getId(), response.getCommand(), response.getResult(), response.getResponse());
594 if (response.isError()) {
595 logger.debug("Error received for command '{}': {}.", response.getCommandString(),
596 response.getResponse().get("error"));
597 if (MiIoCommand.MIIO_INFO.equals(response.getCommand())) {
598 network.invalidateValue();
603 switch (response.getCommand()) {
606 defineDeviceType(response.getResult().getAsJsonObject());
608 updateNetwork(response.getResult().getAsJsonObject());
613 if (cmds.containsKey(response.getId())) {
614 String channel = cmds.get(response.getId());
615 if (channel != null && (CHANNEL_COMMAND.contentEquals(channel) || CHANNEL_RPC.contentEquals(channel))) {
616 updateState(channel, new StringType(response.getResponse().toString()));
617 cmds.remove(response.getId());
620 } catch (Exception e) {
621 logger.debug("Error while handing message {}", response.getResponse(), e);