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.transport;
15 import java.io.IOException;
16 import java.net.DatagramPacket;
17 import java.net.DatagramSocket;
18 import java.net.InetAddress;
19 import java.net.SocketException;
20 import java.net.SocketTimeoutException;
21 import java.nio.charset.StandardCharsets;
22 import java.time.Instant;
23 import java.util.Arrays;
24 import java.util.Calendar;
25 import java.util.List;
26 import java.util.NoSuchElementException;
27 import java.util.concurrent.ConcurrentLinkedQueue;
28 import java.util.concurrent.CopyOnWriteArrayList;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicInteger;
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.openhab.binding.miio.internal.Message;
35 import org.openhab.binding.miio.internal.MiIoBindingConstants;
36 import org.openhab.binding.miio.internal.MiIoCommand;
37 import org.openhab.binding.miio.internal.MiIoCrypto;
38 import org.openhab.binding.miio.internal.MiIoCryptoException;
39 import org.openhab.binding.miio.internal.MiIoMessageListener;
40 import org.openhab.binding.miio.internal.MiIoSendCommand;
41 import org.openhab.binding.miio.internal.Utils;
42 import org.openhab.binding.miio.internal.cloud.CloudConnector;
43 import org.openhab.binding.miio.internal.cloud.MiCloudException;
44 import org.openhab.core.thing.ThingStatus;
45 import org.openhab.core.thing.ThingStatusDetail;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import com.google.gson.JsonElement;
50 import com.google.gson.JsonObject;
51 import com.google.gson.JsonParser;
52 import com.google.gson.JsonSyntaxException;
55 * The {@link MiIoAsyncCommunication} is responsible for communications with the Mi IO devices
57 * @author Marcel Verpaalen - Initial contribution
60 public class MiIoAsyncCommunication {
62 private static final int MSG_BUFFER_SIZE = 2048;
64 private final Logger logger = LoggerFactory.getLogger(MiIoAsyncCommunication.class);
66 private final String ip;
67 private final byte[] token;
68 private byte[] deviceId;
69 private @Nullable DatagramSocket socket;
71 private List<MiIoMessageListener> listeners = new CopyOnWriteArrayList<>();
73 private AtomicInteger id = new AtomicInteger(-1);
74 private int timeDelta;
75 private int timeStamp;
76 private @Nullable MessageSenderThread senderThread;
77 private boolean connected;
78 private ThingStatusDetail status = ThingStatusDetail.NONE;
79 private int errorCounter;
81 private boolean needPing = true;
82 private static final int MAX_ERRORS = 3;
83 private static final int MAX_ID = 15000;
84 private final CloudConnector cloudConnector;
86 private ConcurrentLinkedQueue<MiIoSendCommand> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
88 public MiIoAsyncCommunication(String ip, byte[] token, byte[] did, int id, int timeout,
89 CloudConnector cloudConnector) {
93 this.timeout = timeout;
94 this.cloudConnector = cloudConnector;
99 protected List<MiIoMessageListener> getListeners() {
104 * Registers a {@link MiIoMessageListener} to be called back, when data is received.
105 * If no {@link MessageSenderThread} exists, when the method is called, it is being set up.
107 * @param listener {@link MiIoMessageListener} to be called back
109 public synchronized void registerListener(MiIoMessageListener listener) {
112 if (!getListeners().contains(listener)) {
113 logger.trace("Adding socket listener {}", listener);
114 getListeners().add(listener);
119 * Unregisters a {@link MiIoMessageListener}. If there are no listeners left,
120 * the {@link MessageSenderThread} is being closed.
122 * @param listener {@link MiIoMessageListener} to be unregistered
124 public synchronized void unregisterListener(MiIoMessageListener listener) {
125 getListeners().remove(listener);
126 if (getListeners().isEmpty()) {
127 concurrentLinkedQueue.clear();
132 public int queueCommand(MiIoCommand command, String cloudServer) throws MiIoCryptoException, IOException {
133 return queueCommand(command, "[]", cloudServer);
136 public int queueCommand(MiIoCommand command, String params, String cloudServer)
137 throws MiIoCryptoException, IOException {
138 return queueCommand(command.getCommand(), params, cloudServer);
141 public int queueCommand(String command, String params, String cloudServer)
142 throws MiIoCryptoException, IOException, JsonSyntaxException {
144 JsonObject fullCommand = new JsonObject();
145 int cmdId = id.incrementAndGet();
146 if (cmdId > MAX_ID) {
149 fullCommand.addProperty("id", cmdId);
150 fullCommand.addProperty("method", command);
151 fullCommand.add("params", JsonParser.parseString(params));
152 MiIoSendCommand sendCmd = new MiIoSendCommand(cmdId, MiIoCommand.getCommand(command), fullCommand,
154 concurrentLinkedQueue.add(sendCmd);
155 if (logger.isDebugEnabled()) {
156 // Obfuscate part of the token to allow sharing of the logfiles
157 String tokenText = Utils.obfuscateToken(Utils.getHex(token));
158 logger.debug("Command added to Queue {} -> {} (Device: {} token: {} Queue: {}).{}{}",
159 fullCommand.toString(), ip, Utils.getHex(deviceId), tokenText, concurrentLinkedQueue.size(),
160 cloudServer.isBlank() ? "" : " Send via cloudserver: ", cloudServer);
162 if (needPing && cloudServer.isBlank()) {
166 } catch (JsonSyntaxException e) {
167 logger.warn("Send command '{}' with parameters {} -> {} (Device: {}) gave error {}", command, params, ip,
168 Utils.getHex(deviceId), e.getMessage());
173 MiIoSendCommand sendMiIoSendCommand(MiIoSendCommand miIoSendCommand) {
174 String errorMsg = "Unknown Error while sending command";
175 String decryptedResponse = "";
177 if (miIoSendCommand.getCloudServer().isBlank()) {
178 decryptedResponse = sendCommand(miIoSendCommand.getCommandString(), token, ip, deviceId);
180 decryptedResponse = cloudConnector.sendRPCCommand(Utils.getHex(deviceId),
181 miIoSendCommand.getCloudServer(), miIoSendCommand);
182 logger.debug("Command {} send via cloudserver {}", miIoSendCommand.getCommandString(),
183 miIoSendCommand.getCloudServer());
184 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
186 // hack due to avoid invalid json errors from some misbehaving device firmwares
187 decryptedResponse = decryptedResponse.replace(",,", ",");
188 JsonElement response;
189 response = JsonParser.parseString(decryptedResponse);
190 if (!response.isJsonObject()) {
191 errorMsg = "Received message is not a JSON object ";
194 logger.trace("Received JSON message {}", response.toString());
195 JsonObject resJson = response.getAsJsonObject();
196 if (resJson.has("id")) {
197 int id = resJson.get("id").getAsInt();
198 if (id == miIoSendCommand.getId()) {
199 miIoSendCommand.setResponse(response.getAsJsonObject());
200 return miIoSendCommand;
202 if (id < miIoSendCommand.getId()) {
203 errorMsg = String.format(
204 "Received message out of sync, extend timeout time. Expected id: %d, received id: %d",
205 miIoSendCommand.getId(), id);
207 errorMsg = String.format("Received message out of sync. Expected id: %d, received id: %d",
208 miIoSendCommand.getId(), id);
212 errorMsg = "Received message is without id";
216 logger.debug("{}: {}", errorMsg, decryptedResponse);
217 } catch (MiIoCryptoException | IOException e) {
218 logger.debug("Send command '{}' -> {} (Device: {}) gave error {}", miIoSendCommand.getCommandString(), ip,
219 Utils.getHex(deviceId), e.getMessage());
220 errorMsg = e.getMessage();
221 } catch (JsonSyntaxException e) {
222 logger.warn("Could not parse '{}' <- {} (Device: {}) gave error {}", decryptedResponse,
223 miIoSendCommand.getCommandString(), Utils.getHex(deviceId), e.getMessage());
224 errorMsg = "Received message is invalid JSON";
225 } catch (MiCloudException e) {
226 logger.debug("Send command '{}' -> cloudserver '{}' (Device: {}) gave error {}",
227 miIoSendCommand.getCommandString(), miIoSendCommand.getCloudServer(), Utils.getHex(deviceId),
229 errorMsg = e.getMessage();
230 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
232 JsonObject erroResp = new JsonObject();
233 erroResp.addProperty("error", errorMsg);
234 miIoSendCommand.setResponse(erroResp);
235 return miIoSendCommand;
238 public synchronized void startReceiver() {
239 MessageSenderThread senderThread = this.senderThread;
240 if (senderThread == null || !senderThread.isAlive()) {
241 senderThread = new MessageSenderThread();
242 senderThread.start();
243 this.senderThread = senderThread;
248 * The {@link MessageSenderThread} is responsible for consuming messages from the queue and sending these to the
252 private class MessageSenderThread extends Thread {
253 public MessageSenderThread() {
254 super("Mi IO MessageSenderThread");
260 logger.debug("Starting Mi IO MessageSenderThread");
261 while (!interrupted()) {
263 if (concurrentLinkedQueue.isEmpty()) {
267 MiIoSendCommand queuedMessage = concurrentLinkedQueue.remove();
268 MiIoSendCommand miIoSendCommand = sendMiIoSendCommand(queuedMessage);
269 for (MiIoMessageListener listener : listeners) {
270 logger.trace("inform listener {}, data {} from {}", listener, queuedMessage, miIoSendCommand);
272 listener.onMessageReceived(miIoSendCommand);
273 } catch (Exception e) {
274 logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
277 } catch (NoSuchElementException e) {
279 } catch (InterruptedException e) {
280 // That's our signal to stop
282 } catch (Exception e) {
283 logger.warn("Error while polling/sending message", e);
287 logger.debug("Finished Mi IO MessageSenderThread");
291 private String sendCommand(String command, byte[] token, String ip, byte[] deviceId)
292 throws MiIoCryptoException, IOException {
293 byte[] sendMsg = new byte[0];
294 if (!command.isBlank()) {
296 encr = MiIoCrypto.encrypt(command.getBytes(StandardCharsets.UTF_8), token);
297 timeStamp = (int) Instant.now().getEpochSecond();
298 sendMsg = Message.createMsgData(encr, token, deviceId, timeStamp + timeDelta);
300 Message miIoResponseMsg = sendData(sendMsg, ip);
301 if (miIoResponseMsg == null) {
302 if (logger.isTraceEnabled()) {
303 logger.trace("No response from device {} at {} for command {}.\r\n{}", Utils.getHex(deviceId), ip,
304 command, (new Message(sendMsg)).toSting());
306 logger.debug("No response from device {} at {} for command {}.", Utils.getHex(deviceId), ip, command);
309 if (errorCounter > MAX_ERRORS) {
310 status = ThingStatusDetail.CONFIGURATION_ERROR;
313 return "{\"error\":\"No Response\"}";
315 if (!miIoResponseMsg.isChecksumValid()) {
316 return "{\"error\":\"Message has invalid checksum\"}";
318 if (errorCounter > 0) {
320 status = ThingStatusDetail.NONE;
321 updateStatus(ThingStatus.ONLINE, status);
326 String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
327 logger.trace("Received response from {}: {}", ip, decryptedResponse);
328 return decryptedResponse;
331 public @Nullable Message sendPing(String ip) throws IOException {
332 for (int i = 0; i < 3; i++) {
333 logger.debug("Sending Ping {} ({})", Utils.getHex(deviceId), ip);
334 Message resp = sendData(MiIoBindingConstants.DISCOVER_STRING, ip);
344 private void pingFail() {
345 logger.debug("Ping {} ({}) failed", Utils.getHex(deviceId), ip);
347 status = ThingStatusDetail.COMMUNICATION_ERROR;
348 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
351 private void pingSuccess() {
352 logger.debug("Ping {} ({}) success", Utils.getHex(deviceId), ip);
355 status = ThingStatusDetail.NONE;
356 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
358 if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
359 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
361 status = ThingStatusDetail.NONE;
362 updateStatus(ThingStatus.ONLINE, status);
367 private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
368 for (MiIoMessageListener listener : listeners) {
369 logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
371 listener.onStatusUpdated(status, statusDetail);
372 } catch (Exception e) {
373 logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
378 private @Nullable Message sendData(byte[] sendMsg, String ip) throws IOException {
379 byte[] response = comms(sendMsg, ip);
380 if (response.length >= 32) {
381 Message miIoResponse = new Message(response);
382 timeStamp = (int) TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().getTime().getTime());
383 timeDelta = miIoResponse.getTimestampAsInt() - timeStamp;
384 logger.trace("Message Details:{} ", miIoResponse.toSting());
387 logger.trace("Reponse length <32 : {}", response.length);
392 private synchronized byte[] comms(byte[] message, String ip) throws IOException {
393 InetAddress ipAddress = InetAddress.getByName(ip);
394 DatagramSocket clientSocket = getSocket();
395 DatagramPacket receivePacket = new DatagramPacket(new byte[MSG_BUFFER_SIZE], MSG_BUFFER_SIZE);
397 logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
398 if (message.length > 0) {
399 byte[] sendData = new byte[MSG_BUFFER_SIZE];
401 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
402 MiIoBindingConstants.PORT);
403 clientSocket.send(sendPacket);
404 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
406 clientSocket.receive(receivePacket);
407 byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
408 receivePacket.getOffset() + receivePacket.getLength());
410 } catch (SocketTimeoutException e) {
411 logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
417 private DatagramSocket getSocket() throws SocketException {
419 DatagramSocket socket = this.socket;
420 if (socket == null || socket.isClosed()) {
421 socket = new DatagramSocket();
422 socket.setSoTimeout(timeout);
423 logger.debug("Opening socket on port: {} ", socket.getLocalPort());
424 this.socket = socket;
431 public void close() {
433 final MessageSenderThread senderThread = this.senderThread;
434 if (senderThread != null) {
435 senderThread.interrupt();
437 } catch (SecurityException e) {
438 logger.debug("Error while closing: {} ", e.getMessage());
443 public void closeSocket() {
445 final DatagramSocket socket = this.socket;
446 if (socket != null) {
447 logger.debug("Closing socket for port: {} ", socket.getLocalPort());
451 } catch (SecurityException e) {
452 logger.debug("Error while closing: {} ", e.getMessage());
460 return id.incrementAndGet();
464 * @param id the id to set
466 public void setId(int id) {
471 * Time delta between device time and server time
475 public int getTimeDelta() {
479 public byte[] getDeviceId() {
483 public void setDeviceId(byte[] deviceId) {
484 this.deviceId = deviceId;
487 public int getQueueLength() {
488 return concurrentLinkedQueue.size();