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 String 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, String 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(String command, String params, String cloudServer, String sender)
133 throws MiIoCryptoException, IOException, JsonSyntaxException {
135 JsonObject fullCommand = new JsonObject();
136 int cmdId = id.incrementAndGet();
137 if (cmdId > MAX_ID) {
140 if (command.startsWith("{") && command.endsWith("}")) {
141 fullCommand = JsonParser.parseString(command).getAsJsonObject();
142 fullCommand.addProperty("id", cmdId);
143 if (!fullCommand.has("params") && !params.isBlank()) {
144 fullCommand.add("params", JsonParser.parseString(params));
147 fullCommand.addProperty("id", cmdId);
148 fullCommand.addProperty("method", command);
149 fullCommand.add("params", JsonParser.parseString(params));
151 MiIoSendCommand sendCmd = new MiIoSendCommand(cmdId, MiIoCommand.getCommand(command), fullCommand,
153 concurrentLinkedQueue.add(sendCmd);
154 if (logger.isDebugEnabled()) {
155 // Obfuscate part of the token to allow sharing of the logfiles
156 String tokenText = Utils.obfuscateToken(Utils.getHex(token));
157 logger.debug("Command added to Queue {} -> {} (Device: {} token: {} Queue: {}).{}{}",
158 fullCommand.toString(), ip, deviceId, tokenText, concurrentLinkedQueue.size(),
159 cloudServer.isBlank() ? "" : " Send via cloudserver: ", cloudServer);
161 if (needPing && cloudServer.isBlank()) {
165 } catch (JsonSyntaxException | IllegalStateException e) {
166 logger.warn("Send command '{}' with parameters {} -> {} (Device: {}) gave error {}", command, params, ip,
167 deviceId, e.getMessage());
172 MiIoSendCommand sendMiIoSendCommand(MiIoSendCommand miIoSendCommand) {
173 String errorMsg = "Unknown Error while sending command";
174 String decryptedResponse = "";
176 if (miIoSendCommand.getCloudServer().isBlank()) {
177 decryptedResponse = sendCommand(miIoSendCommand.getCommandString(), token, ip, deviceId);
179 if (!miIoSendCommand.getMethod().startsWith("/")) {
180 decryptedResponse = cloudConnector.sendRPCCommand(Utils.getHexId(deviceId),
181 miIoSendCommand.getCloudServer(), miIoSendCommand);
182 logger.debug("Command {} send via cloudserver {}", miIoSendCommand.getCommandString(),
183 miIoSendCommand.getCloudServer());
184 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
186 String data = miIoSendCommand.getParams().isJsonArray()
187 && miIoSendCommand.getParams().getAsJsonArray().size() > 0
188 ? miIoSendCommand.getParams().getAsJsonArray().get(0).toString()
190 logger.debug("Custom cloud request send to url '{}' with data '{}'", miIoSendCommand.getMethod(),
192 decryptedResponse = cloudConnector.sendCloudCommand(miIoSendCommand.getMethod(),
193 miIoSendCommand.getCloudServer(), data);
194 miIoSendCommand.setResponse(JsonParser.parseString(decryptedResponse).getAsJsonObject());
195 return miIoSendCommand;
198 // hack due to avoid invalid json errors from some misbehaving device firmwares
199 decryptedResponse = decryptedResponse.replace(",,", ",");
200 JsonElement response;
201 response = JsonParser.parseString(decryptedResponse);
202 if (!response.isJsonObject()) {
203 errorMsg = "Received message is not a JSON object ";
206 logger.trace("Received JSON message {}", response.toString());
207 JsonObject resJson = response.getAsJsonObject();
208 if (resJson.has("id")) {
209 int id = resJson.get("id").getAsInt();
210 if (id == miIoSendCommand.getId()) {
211 miIoSendCommand.setResponse(response.getAsJsonObject());
212 return miIoSendCommand;
214 if (id < miIoSendCommand.getId()) {
215 errorMsg = String.format(
216 "Received message out of sync, extend timeout time. Expected id: %d, received id: %d",
217 miIoSendCommand.getId(), id);
219 errorMsg = String.format("Received message out of sync. Expected id: %d, received id: %d",
220 miIoSendCommand.getId(), id);
224 errorMsg = "Received message is without id";
228 logger.debug("{}: {}", errorMsg, decryptedResponse);
229 } catch (MiIoCryptoException | IOException e) {
230 logger.debug("Send command '{}' -> {} (Device: {}) gave error {}", miIoSendCommand.getCommandString(), ip,
231 deviceId, e.getMessage());
232 errorMsg = e.getMessage();
233 } catch (JsonSyntaxException e) {
234 logger.warn("Could not parse '{}' <- {} (Device: {}) gave error {}", decryptedResponse,
235 miIoSendCommand.getCommandString(), deviceId, e.getMessage());
236 errorMsg = "Received message is invalid JSON";
237 } catch (MiCloudException e) {
238 logger.debug("Send command '{}' -> cloudserver '{}' (Device: {}) gave error {}",
239 miIoSendCommand.getCommandString(), miIoSendCommand.getCloudServer(), deviceId, e.getMessage());
240 errorMsg = e.getMessage();
241 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
243 JsonObject erroResp = new JsonObject();
244 erroResp.addProperty("error", errorMsg);
245 miIoSendCommand.setResponse(erroResp);
246 return miIoSendCommand;
249 public synchronized void startReceiver() {
250 MessageSenderThread senderThread = this.senderThread;
251 if (senderThread == null || !senderThread.isAlive()) {
252 senderThread = new MessageSenderThread(deviceId);
253 senderThread.start();
254 this.senderThread = senderThread;
259 * The {@link MessageSenderThread} is responsible for consuming messages from the queue and sending these to the
263 private class MessageSenderThread extends Thread {
264 private final String deviceId;
266 public MessageSenderThread(String deviceId) {
267 super("OH-binding-miio-MessageSenderThread-" + deviceId);
269 this.deviceId = deviceId;
274 logger.debug("Starting Mi IO MessageSenderThread {}", deviceId);
275 while (!interrupted()) {
277 if (concurrentLinkedQueue.isEmpty()) {
281 MiIoSendCommand queuedMessage = concurrentLinkedQueue.remove();
282 MiIoSendCommand miIoSendCommand = sendMiIoSendCommand(queuedMessage);
283 for (MiIoMessageListener listener : listeners) {
284 logger.trace("inform listener {}, data {} from {}", listener, queuedMessage, miIoSendCommand);
286 listener.onMessageReceived(miIoSendCommand);
287 } catch (Exception e) {
288 logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
291 } catch (NoSuchElementException e) {
293 } catch (InterruptedException e) {
294 // That's our signal to stop
296 } catch (Exception e) {
297 logger.warn("Error while polling/sending message for {}", deviceId, e);
301 logger.debug("Finished Mi IO MessageSenderThread {}", deviceId);
305 private String sendCommand(String command, byte[] token, String ip, String deviceId)
306 throws MiIoCryptoException, IOException {
307 byte[] sendMsg = new byte[0];
308 if (!command.isBlank()) {
310 encr = MiIoCrypto.encrypt(command.getBytes(StandardCharsets.UTF_8), token);
311 timeStamp = (int) Instant.now().getEpochSecond();
312 sendMsg = Message.createMsgData(encr, token, Utils.hexStringToByteArray(Utils.getHexId(deviceId)),
313 timeStamp + timeDelta);
315 Message miIoResponseMsg = sendData(sendMsg, ip);
316 if (miIoResponseMsg == null) {
317 if (logger.isTraceEnabled()) {
318 logger.trace("No response from device {} at {} for command {}.\r\n{}", deviceId, ip, command,
319 (new Message(sendMsg)).toSting());
321 logger.debug("No response from device {} at {} for command {}.", deviceId, ip, command);
324 if (errorCounter > MAX_ERRORS) {
325 status = ThingStatusDetail.CONFIGURATION_ERROR;
328 return "{\"error\":\"No Response\"}";
330 if (!miIoResponseMsg.isChecksumValid()) {
331 return "{\"error\":\"Message has invalid checksum\"}";
333 if (errorCounter > 0) {
335 status = ThingStatusDetail.NONE;
336 updateStatus(ThingStatus.ONLINE, status);
341 String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
342 logger.trace("Received response from {}: {}", ip, decryptedResponse);
343 return decryptedResponse;
346 public @Nullable Message sendPing(String ip) throws IOException {
347 for (int i = 0; i < 3; i++) {
348 logger.debug("Sending Ping to device '{}' ({})", deviceId, ip);
349 Message resp = sendData(MiIoBindingConstants.DISCOVER_STRING, ip);
359 private void pingFail() {
360 logger.debug("Ping to device '{}' ({}) failed", deviceId, ip);
362 status = ThingStatusDetail.COMMUNICATION_ERROR;
363 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
366 private void pingSuccess() {
367 logger.debug("Ping to device '{}' ({}) success", deviceId, ip);
370 status = ThingStatusDetail.NONE;
371 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
373 if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
374 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
376 status = ThingStatusDetail.NONE;
377 updateStatus(ThingStatus.ONLINE, status);
382 private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
383 for (MiIoMessageListener listener : listeners) {
384 logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
386 listener.onStatusUpdated(status, statusDetail);
387 } catch (Exception e) {
388 logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
393 private @Nullable Message sendData(byte[] sendMsg, String ip) throws IOException {
394 byte[] response = comms(sendMsg, ip);
395 if (response.length >= 32) {
396 Message miIoResponse = new Message(response);
397 timeStamp = (int) TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().getTime().getTime());
398 timeDelta = miIoResponse.getTimestampAsInt() - timeStamp;
399 logger.trace("Message Details:{} ", miIoResponse.toSting());
402 logger.trace("Reponse length <32 : {}", response.length);
407 private synchronized byte[] comms(byte[] message, String ip) throws IOException {
408 InetAddress ipAddress = InetAddress.getByName(ip);
409 DatagramSocket clientSocket = getSocket();
410 DatagramPacket receivePacket = new DatagramPacket(new byte[MSG_BUFFER_SIZE], MSG_BUFFER_SIZE);
412 logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
413 if (message.length > 0) {
414 byte[] sendData = new byte[MSG_BUFFER_SIZE];
416 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
417 MiIoBindingConstants.PORT);
418 clientSocket.send(sendPacket);
419 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
421 clientSocket.receive(receivePacket);
422 byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
423 receivePacket.getOffset() + receivePacket.getLength());
425 } catch (SocketTimeoutException e) {
426 logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
432 private DatagramSocket getSocket() throws SocketException {
434 DatagramSocket socket = this.socket;
435 if (socket == null || socket.isClosed()) {
436 socket = new DatagramSocket();
437 socket.setSoTimeout(timeout);
438 logger.debug("Opening socket on port: {} ", socket.getLocalPort());
439 this.socket = socket;
446 public void close() {
448 final MessageSenderThread senderThread = this.senderThread;
449 if (senderThread != null) {
450 senderThread.interrupt();
452 } catch (SecurityException e) {
453 logger.debug("Error while closing: {} ", e.getMessage());
458 public void closeSocket() {
460 final DatagramSocket socket = this.socket;
461 if (socket != null) {
462 logger.debug("Closing socket for port: {} ", socket.getLocalPort());
466 } catch (SecurityException e) {
467 logger.debug("Error while closing: {} ", e.getMessage());
475 return id.incrementAndGet();
479 * @param id the id to set
481 public void setId(int id) {
486 * Time delta between device time and server time
490 public int getTimeDelta() {
494 public String getDeviceId() {
498 public void setDeviceId(String deviceId) {
499 this.deviceId = deviceId;
502 public int getQueueLength() {
503 return concurrentLinkedQueue.size();