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.*;
17 import java.io.IOException;
18 import java.time.LocalDateTime;
19 import java.util.HashMap;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ScheduledExecutorService;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.ScheduledThreadPoolExecutor;
25 import java.util.concurrent.TimeUnit;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.miio.internal.Message;
30 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
31 import org.openhab.binding.miio.internal.MiIoCommand;
32 import org.openhab.binding.miio.internal.MiIoCrypto;
33 import org.openhab.binding.miio.internal.MiIoCryptoException;
34 import org.openhab.binding.miio.internal.MiIoDevices;
35 import org.openhab.binding.miio.internal.MiIoInfoDTO;
36 import org.openhab.binding.miio.internal.MiIoMessageListener;
37 import org.openhab.binding.miio.internal.MiIoSendCommand;
38 import org.openhab.binding.miio.internal.Utils;
39 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
40 import org.openhab.binding.miio.internal.cloud.CloudConnector;
41 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
42 import org.openhab.core.cache.ExpiringCache;
43 import org.openhab.core.common.NamedThreadFactory;
44 import org.openhab.core.config.core.Configuration;
45 import org.openhab.core.library.types.DecimalType;
46 import org.openhab.core.library.types.StringType;
47 import org.openhab.core.thing.ChannelUID;
48 import org.openhab.core.thing.Thing;
49 import org.openhab.core.thing.ThingStatus;
50 import org.openhab.core.thing.ThingStatusDetail;
51 import org.openhab.core.thing.ThingTypeUID;
52 import org.openhab.core.thing.binding.BaseThingHandler;
53 import org.openhab.core.thing.binding.builder.ThingBuilder;
54 import org.openhab.core.types.Command;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 import com.google.gson.Gson;
59 import com.google.gson.GsonBuilder;
60 import com.google.gson.JsonObject;
61 import com.google.gson.JsonParser;
64 * The {@link MiIoAbstractHandler} is responsible for handling commands, which are
65 * sent to one of the channels.
67 * @author Marcel Verpaalen - Initial contribution
70 public abstract class MiIoAbstractHandler extends BaseThingHandler implements MiIoMessageListener {
71 protected static final int MAX_QUEUE = 5;
72 protected static final Gson GSON = new GsonBuilder().create();
74 protected ScheduledExecutorService miIoScheduler = scheduler;
75 protected @Nullable ScheduledFuture<?> pollingJob;
76 protected MiIoDevices miDevice = MiIoDevices.UNKNOWN;
77 protected boolean isIdentified;
79 protected final JsonParser parser = new JsonParser();
80 protected byte[] token = new byte[0];
82 protected @Nullable MiIoBindingConfiguration configuration;
83 protected @Nullable MiIoAsyncCommunication miioCom;
84 protected CloudConnector cloudConnector;
85 protected String cloudServer = "";
88 protected Map<Integer, String> cmds = new ConcurrentHashMap<>();
89 protected Map<String, Object> deviceVariables = new HashMap<>();
90 protected final ExpiringCache<String> network = new ExpiringCache<>(CACHE_EXPIRY_NETWORK, () -> {
91 int ret = sendCommand(MiIoCommand.MIIO_INFO);
97 protected static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(5);
98 protected static final long CACHE_EXPIRY_NETWORK = TimeUnit.SECONDS.toMillis(60);
100 private final Logger logger = LoggerFactory.getLogger(MiIoAbstractHandler.class);
101 protected MiIoDatabaseWatchService miIoDatabaseWatchService;
103 public MiIoAbstractHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
104 CloudConnector cloudConnector) {
106 this.miIoDatabaseWatchService = miIoDatabaseWatchService;
107 this.cloudConnector = cloudConnector;
111 public abstract void handleCommand(ChannelUID channelUID, Command command);
113 protected boolean handleCommandsChannels(ChannelUID channelUID, Command command) {
114 if (channelUID.getId().equals(CHANNEL_COMMAND)) {
115 cmds.put(sendCommand(command.toString(), ""), command.toString());
118 if (channelUID.getId().equals(CHANNEL_RPC)) {
119 cmds.put(sendCommand(command.toString(), cloudServer), command.toString());
126 public void initialize() {
127 logger.debug("Initializing Mi IO device handler '{}' with thingType {}", getThing().getUID(),
128 getThing().getThingTypeUID());
130 ScheduledThreadPoolExecutor miIoScheduler = new ScheduledThreadPoolExecutor(3,
131 new NamedThreadFactory(getThing().getUID().getAsString(), true));
132 miIoScheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
133 miIoScheduler.setRemoveOnCancelPolicy(true);
134 this.miIoScheduler = miIoScheduler;
136 final MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
137 this.configuration = configuration;
138 if (configuration.host == null || configuration.host.isEmpty()) {
139 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
140 "IP address required. Configure IP address");
143 if (!tokenCheckPass(configuration.token)) {
144 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Token required. Configure token");
147 cloudServer = (configuration.cloudServer != null) ? configuration.cloudServer : "";
148 isIdentified = false;
149 miIoScheduler.schedule(this::initializeData, 1, TimeUnit.SECONDS);
150 int pollingPeriod = configuration.refreshInterval;
151 if (pollingPeriod > 0) {
152 pollingJob = miIoScheduler.scheduleWithFixedDelay(() -> {
155 } catch (Exception e) {
156 logger.debug("Unexpected error during refresh.", e);
158 }, 10, pollingPeriod, TimeUnit.SECONDS);
159 logger.debug("Polling job scheduled to run every {} sec. for '{}'", pollingPeriod, getThing().getUID());
161 logger.debug("Polling job disabled. for '{}'", getThing().getUID());
162 miIoScheduler.schedule(this::updateData, 10, TimeUnit.SECONDS);
164 updateStatus(ThingStatus.OFFLINE);
167 private boolean tokenCheckPass(@Nullable String tokenSting) {
168 if (tokenSting == null) {
171 switch (tokenSting.length()) {
173 token = tokenSting.getBytes();
176 if (!IGNORED_TOKENS.contains(tokenSting)) {
177 token = Utils.hexStringToByteArray(tokenSting);
183 token = Utils.hexStringToByteArray(MiIoCrypto.decryptToken(Utils.hexStringToByteArray(tokenSting)));
184 logger.debug("IOS token decrypted to {}", Utils.getHex(token));
185 } catch (MiIoCryptoException e) {
186 logger.warn("Could not decrypt token {}{}", tokenSting, e.getMessage());
196 public void dispose() {
197 logger.debug("Disposing Xiaomi Mi IO handler '{}'", getThing().getUID());
198 miIoScheduler.shutdown();
199 final ScheduledFuture<?> pollingJob = this.pollingJob;
200 if (pollingJob != null) {
201 pollingJob.cancel(true);
202 this.pollingJob = null;
204 final @Nullable MiIoAsyncCommunication miioCom = this.miioCom;
205 if (miioCom != null) {
206 lastId = miioCom.getId();
207 miioCom.unregisterListener(this);
211 miIoScheduler.shutdownNow();
214 protected int sendCommand(MiIoCommand command) {
215 return sendCommand(command, "[]");
218 protected int sendCommand(MiIoCommand command, String params) {
220 final MiIoAsyncCommunication connection = getConnection();
221 return (connection != null) ? connection.queueCommand(command, params, getCloudServer()) : 0;
222 } catch (MiIoCryptoException | IOException e) {
223 logger.debug("Command {} for {} failed (type: {}): {}", command.toString(), getThing().getUID(),
224 getThing().getThingTypeUID(), e.getLocalizedMessage());
229 protected int sendCommand(String commandString) {
230 return sendCommand(commandString, getCloudServer());
234 * This is used to execute arbitrary commands by sending to the commands channel. Command parameters to be added
236 * [] brackets. This to allow for unimplemented commands to be executed (e.g. get detailed historical cleaning
239 * @param commandString command to be executed
240 * @param cloud server to be used or empty string for direct sending to the device
241 * @return vacuum response
243 protected int sendCommand(String commandString, String cloudServer) {
244 final MiIoAsyncCommunication connection = getConnection();
246 String command = commandString.trim();
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 (connection != null) ? connection.queueCommand(command, param, cloudServer) : 0;
256 } catch (MiIoCryptoException | IOException e) {
257 disconnected(e.getMessage());
262 String getCloudServer() {
263 // This can be improved in the future with additional / more advanced options like e.g. directFirst which would
264 // use direct communications and in case of failures fall back to cloud communication. For now we keep it
265 // simple and only have the option for cloud or direct.
266 final MiIoBindingConfiguration configuration = this.configuration;
267 if (configuration != null && configuration.communication != null) {
268 return configuration.communication.equals("cloud") ? cloudServer : "";
273 protected boolean skipUpdate() {
274 final MiIoAsyncCommunication miioCom = this.miioCom;
275 if (!hasConnection() || miioCom == null) {
276 logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
279 if (getThing().getStatusInfo().getStatusDetail().equals(ThingStatusDetail.CONFIGURATION_ERROR)) {
280 logger.debug("Skipping periodic update for '{}'. Thing Status {}", getThing().getUID().toString(),
281 getThing().getStatusInfo().getStatusDetail());
282 sendCommand(MiIoCommand.MIIO_INFO);
285 if (miioCom.getQueueLength() > MAX_QUEUE) {
286 logger.debug("Skipping periodic update for '{}'. {} elements in queue.", getThing().getUID().toString(),
287 miioCom.getQueueLength());
293 protected abstract void updateData();
295 protected boolean updateNetwork(JsonObject networkData) {
297 updateState(CHANNEL_SSID, new StringType(networkData.getAsJsonObject("ap").get("ssid").getAsString()));
298 updateState(CHANNEL_BSSID, new StringType(networkData.getAsJsonObject("ap").get("bssid").getAsString()));
299 if (networkData.getAsJsonObject("ap").get("rssi") != null) {
300 updateState(CHANNEL_RSSI, new DecimalType(networkData.getAsJsonObject("ap").get("rssi").getAsLong()));
301 } else if (networkData.getAsJsonObject("ap").get("wifi_rssi") != null) {
302 updateState(CHANNEL_RSSI,
303 new DecimalType(networkData.getAsJsonObject("ap").get("wifi_rssi").getAsLong()));
305 logger.debug("No RSSI info in response");
307 updateState(CHANNEL_LIFE, new DecimalType(networkData.get("life").getAsLong()));
309 } catch (Exception e) {
310 logger.debug("Could not parse network response: {}", networkData, e);
315 protected boolean hasConnection() {
316 return getConnection() != null;
319 protected void disconnectedNoResponse() {
320 disconnected("No Response from device");
323 protected void disconnected(@Nullable String message) {
324 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
325 message != null ? message : "");
326 final MiIoAsyncCommunication miioCom = this.miioCom;
327 if (miioCom != null) {
328 lastId = miioCom.getId();
333 protected synchronized @Nullable MiIoAsyncCommunication getConnection() {
334 if (miioCom != null) {
337 final MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
338 if (configuration.host == null || configuration.host.isEmpty()) {
342 String deviceId = configuration.deviceId;
344 if (deviceId != null && deviceId.length() == 8 && tokenCheckPass(configuration.token)) {
345 final MiIoAsyncCommunication miioCom = new MiIoAsyncCommunication(configuration.host, token,
346 Utils.hexStringToByteArray(deviceId), lastId, configuration.timeout, cloudConnector);
347 if (getCloudServer().isBlank()) {
348 logger.debug("Ping Mi device {} at {}", deviceId, configuration.host);
349 Message miIoResponse = miioCom.sendPing(configuration.host);
350 if (miIoResponse != null) {
351 logger.debug("Ping response from device {} at {}. Time stamp: {}, OH time {}, delta {}",
352 Utils.getHex(miIoResponse.getDeviceId()), configuration.host,
353 miIoResponse.getTimestamp(), LocalDateTime.now(), miioCom.getTimeDelta());
354 miioCom.registerListener(this);
355 this.miioCom = miioCom;
361 miioCom.registerListener(this);
362 this.miioCom = miioCom;
366 logger.debug("No device ID defined. Retrieving Mi device ID");
367 final MiIoAsyncCommunication miioCom = new MiIoAsyncCommunication(configuration.host, token,
368 new byte[0], lastId, configuration.timeout, cloudConnector);
369 Message miIoResponse = miioCom.sendPing(configuration.host);
370 if (miIoResponse != null) {
371 logger.debug("Ping response from device {} at {}. Time stamp: {}, OH time {}, delta {}",
372 Utils.getHex(miIoResponse.getDeviceId()), configuration.host, miIoResponse.getTimestamp(),
373 LocalDateTime.now(), miioCom.getTimeDelta());
374 deviceId = Utils.getHex(miIoResponse.getDeviceId());
375 logger.debug("Ping response from device {} at {}. Time stamp: {}, OH time {}, delta {}", deviceId,
376 configuration.host, miIoResponse.getTimestamp(), LocalDateTime.now(),
377 miioCom.getTimeDelta());
378 miioCom.setDeviceId(miIoResponse.getDeviceId());
379 logger.debug("Using retrieved Mi device ID: {}", deviceId);
380 updateDeviceIdConfig(deviceId);
381 miioCom.registerListener(this);
382 this.miioCom = miioCom;
388 logger.debug("Ping response from device {} at {} FAILED", configuration.deviceId, configuration.host);
389 disconnectedNoResponse();
391 } catch (IOException e) {
392 logger.debug("Could not connect to {} at {}", getThing().getUID().toString(), configuration.host);
393 disconnected(e.getMessage());
398 private void updateDeviceIdConfig(String deviceId) {
399 if (!deviceId.isEmpty()) {
400 updateProperty(Thing.PROPERTY_SERIAL_NUMBER, deviceId);
401 Configuration config = editConfiguration();
402 config.put(PROPERTY_DID, deviceId);
403 updateConfiguration(config);
405 logger.debug("Could not update config with device ID: {}", deviceId);
409 protected boolean initializeData() {
410 this.miioCom = getConnection();
414 protected void refreshNetwork() {
418 protected void defineDeviceType(JsonObject miioInfo) {
419 updateProperties(miioInfo);
420 isIdentified = updateThingType(miioInfo);
423 private void updateProperties(JsonObject miioInfo) {
424 final MiIoInfoDTO info = GSON.fromJson(miioInfo, MiIoInfoDTO.class);
425 Map<String, String> properties = editProperties();
426 if (info.model != null) {
427 properties.put(Thing.PROPERTY_MODEL_ID, info.model);
429 if (info.fwVer != null) {
430 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, info.fwVer);
432 if (info.hwVer != null) {
433 properties.put(Thing.PROPERTY_HARDWARE_VERSION, info.hwVer);
435 if (info.wifiFwVer != null) {
436 properties.put("wifiFirmware", info.wifiFwVer);
438 if (info.mcuFwVer != null) {
439 properties.put("mcuFirmware", info.mcuFwVer);
441 deviceVariables.putAll(properties);
442 updateProperties(properties);
445 protected boolean updateThingType(JsonObject miioInfo) {
446 MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
447 String model = miioInfo.get("model").getAsString();
448 miDevice = MiIoDevices.getType(model);
449 if (configuration.model == null || configuration.model.isEmpty()) {
450 Configuration config = editConfiguration();
451 config.put(PROPERTY_MODEL, model);
452 updateConfiguration(config);
453 configuration = getConfigAs(MiIoBindingConfiguration.class);
455 if (!configuration.model.equals(model)) {
456 logger.info("Mi Device model {} has model config: {}. Unexpected unless manual override", model,
457 configuration.model);
459 if (miDevice.getThingType().equals(getThing().getThingTypeUID())
460 && !(miDevice.getThingType().equals(THING_TYPE_UNSUPPORTED)
461 && miIoDatabaseWatchService.getDatabaseUrl(model) != null)) {
462 logger.debug("Mi Device model {} identified as: {}. Matches thingtype {}", model, miDevice.toString(),
463 miDevice.getThingType().toString());
466 if (getThing().getThingTypeUID().equals(THING_TYPE_MIIO)
467 || getThing().getThingTypeUID().equals(THING_TYPE_UNSUPPORTED)) {
471 "Mi Device model {} identified as: {}, thingtype {}. Does not matches thingtype {}. Unexpected, unless manual override.",
472 miDevice.toString(), miDevice.getThingType(), getThing().getThingTypeUID().toString(),
473 miDevice.getThingType().toString());
481 * Changes the {@link org.openhab.core.thing.type.ThingType} to the right type once it is retrieved from
484 * @param modelId String with the model id
486 private void changeType(final String modelId) {
487 final ScheduledFuture<?> pollingJob = this.pollingJob;
488 if (pollingJob != null) {
489 pollingJob.cancel(true);
490 this.pollingJob = null;
492 miIoScheduler.schedule(() -> {
493 String label = getThing().getLabel();
494 if (label == null || label.startsWith("Xiaomi Mi Device")) {
495 ThingBuilder thingBuilder = editThing();
496 thingBuilder.withLabel(miDevice.getDescription());
497 updateThing(thingBuilder.build());
499 logger.info("Mi Device model {} identified as: {}. Does not match thingtype {}. Changing thingtype to {}",
500 modelId, miDevice.toString(), getThing().getThingTypeUID().toString(),
501 miDevice.getThingType().toString());
502 ThingTypeUID thingTypeUID = MiIoDevices.getType(modelId).getThingType();
503 if (thingTypeUID.equals(THING_TYPE_UNSUPPORTED)
504 && miIoDatabaseWatchService.getDatabaseUrl(modelId) != null) {
505 thingTypeUID = THING_TYPE_BASIC;
507 changeThingType(thingTypeUID, getConfig());
508 }, 10, TimeUnit.SECONDS);
512 public void onStatusUpdated(ThingStatus status, ThingStatusDetail statusDetail) {
513 updateStatus(status, statusDetail);
517 public void onMessageReceived(MiIoSendCommand response) {
518 logger.debug("Received response for {} type: {}, result: {}, fullresponse: {}", getThing().getUID().getId(),
519 response.getCommand(), response.getResult(), response.getResponse());
520 if (response.isError()) {
521 logger.debug("Error received: {}", response.getResponse().get("error"));
522 if (MiIoCommand.MIIO_INFO.equals(response.getCommand())) {
523 network.invalidateValue();
528 switch (response.getCommand()) {
531 defineDeviceType(response.getResult().getAsJsonObject());
533 updateNetwork(response.getResult().getAsJsonObject());
538 if (cmds.containsKey(response.getId())) {
539 if (response.getCloudServer().isBlank()) {
540 updateState(CHANNEL_COMMAND, new StringType(response.getResponse().toString()));
542 updateState(CHANNEL_RPC, new StringType(response.getResponse().toString()));
544 cmds.remove(response.getId());
546 } catch (Exception e) {
547 logger.debug("Error while handing message {}", response.getResponse(), e);