2 * Copyright (c) 2010-2023 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;
98 protected List<MiIoMessageListener> getListeners() {
103 * Registers a {@link MiIoMessageListener} to be called back, when data is received.
104 * If no {@link MessageSenderThread} exists, when the method is called, it is being set up.
106 * @param listener {@link MiIoMessageListener} to be called back
108 public synchronized void registerListener(MiIoMessageListener listener) {
111 if (!getListeners().contains(listener)) {
112 logger.trace("Adding socket listener {}", listener);
113 getListeners().add(listener);
118 * Unregisters a {@link MiIoMessageListener}. If there are no listeners left,
119 * the {@link MessageSenderThread} is being closed.
121 * @param listener {@link MiIoMessageListener} to be unregistered
123 public synchronized void unregisterListener(MiIoMessageListener listener) {
124 getListeners().remove(listener);
125 if (getListeners().isEmpty()) {
126 concurrentLinkedQueue.clear();
131 public int queueCommand(String command, String params, String cloudServer, String sender)
132 throws MiIoCryptoException, IOException, JsonSyntaxException {
134 JsonObject fullCommand = new JsonObject();
135 int cmdId = id.incrementAndGet();
136 if (cmdId > MAX_ID) {
139 if (command.startsWith("{") && command.endsWith("}")) {
140 fullCommand = JsonParser.parseString(command).getAsJsonObject();
141 fullCommand.addProperty("id", cmdId);
142 if (!fullCommand.has("params") && !params.isBlank()) {
143 fullCommand.add("params", JsonParser.parseString(params));
146 fullCommand.addProperty("id", cmdId);
147 fullCommand.addProperty("method", command);
148 fullCommand.add("params", JsonParser.parseString(params));
150 MiIoSendCommand sendCmd = new MiIoSendCommand(cmdId, MiIoCommand.getCommand(command), fullCommand,
151 cloudServer, sender);
152 concurrentLinkedQueue.add(sendCmd);
153 if (logger.isDebugEnabled()) {
154 // Obfuscate part of the token to allow sharing of the logfiles
155 String tokenText = Utils.obfuscateToken(Utils.getHex(token));
156 logger.debug("Command added to Queue {} -> {} (Device: {} token: {} Queue: {}).{}{}",
157 fullCommand.toString(), ip, deviceId, tokenText, concurrentLinkedQueue.size(),
158 cloudServer.isBlank() ? "" : " Send via cloudserver: ", cloudServer);
160 if (needPing && cloudServer.isBlank()) {
164 } catch (JsonSyntaxException | IllegalStateException e) {
165 logger.warn("Send command '{}' with parameters {} -> {} (Device: {}) gave error {}", command, params, ip,
166 deviceId, e.getMessage());
171 MiIoSendCommand sendMiIoSendCommand(MiIoSendCommand miIoSendCommand) {
172 String errorMsg = "Unknown Error while sending command";
173 String decryptedResponse = "";
175 if (miIoSendCommand.getCloudServer().isBlank()) {
176 decryptedResponse = sendCommand(miIoSendCommand.getCommandString(), token, ip, deviceId);
178 if (!miIoSendCommand.getMethod().startsWith("/")) {
179 decryptedResponse = cloudConnector.sendRPCCommand(Utils.getHexId(deviceId),
180 miIoSendCommand.getCloudServer(), miIoSendCommand);
181 logger.debug("Command {} send via cloudserver {}", miIoSendCommand.getCommandString(),
182 miIoSendCommand.getCloudServer());
183 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
185 String data = miIoSendCommand.getParams().toString();
186 logger.debug("Custom cloud request send to url '{}' with data '{}'", miIoSendCommand.getMethod(),
188 decryptedResponse = cloudConnector.sendCloudCommand(miIoSendCommand.getMethod(),
189 miIoSendCommand.getCloudServer(), data);
190 miIoSendCommand.setResponse(JsonParser.parseString(decryptedResponse).getAsJsonObject());
191 return miIoSendCommand;
194 // hack due to avoid invalid json errors from some misbehaving device firmwares
195 decryptedResponse = decryptedResponse.replace(",,", ",");
196 JsonElement response;
197 response = JsonParser.parseString(decryptedResponse);
198 if (!response.isJsonObject()) {
199 errorMsg = "Received message is not a JSON object ";
202 logger.trace("Received JSON message {}", response.toString());
203 JsonObject resJson = response.getAsJsonObject();
204 if (resJson.has("id")) {
205 int id = resJson.get("id").getAsInt();
206 if (id == miIoSendCommand.getId()) {
207 miIoSendCommand.setResponse(response.getAsJsonObject());
208 return miIoSendCommand;
210 if (id < miIoSendCommand.getId()) {
211 errorMsg = String.format(
212 "Received message out of sync, extend timeout time. Expected id: %d, received id: %d",
213 miIoSendCommand.getId(), id);
215 errorMsg = String.format("Received message out of sync. Expected id: %d, received id: %d",
216 miIoSendCommand.getId(), id);
220 errorMsg = "Received message is without id";
224 logger.debug("{}: {}", errorMsg, decryptedResponse);
225 } catch (MiIoCryptoException | IOException e) {
226 logger.debug("Send command '{}' -> {} (Device: {}) gave error {}", miIoSendCommand.getCommandString(), ip,
227 deviceId, e.getMessage());
228 errorMsg = e.getMessage();
229 } catch (JsonSyntaxException e) {
230 logger.warn("Could not parse '{}' <- {} (Device: {}) gave error {}", decryptedResponse,
231 miIoSendCommand.getCommandString(), deviceId, e.getMessage());
232 errorMsg = "Received message is invalid JSON";
233 } catch (MiCloudException e) {
234 logger.debug("Send command '{}' -> cloudserver '{}' (Device: {}) gave error {}",
235 miIoSendCommand.getCommandString(), miIoSendCommand.getCloudServer(), deviceId, e.getMessage());
236 errorMsg = e.getMessage();
237 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
239 JsonObject erroResp = new JsonObject();
240 erroResp.addProperty("error", errorMsg);
241 miIoSendCommand.setResponse(erroResp);
242 return miIoSendCommand;
245 public synchronized void startReceiver() {
246 MessageSenderThread senderThread = this.senderThread;
247 if (senderThread == null || !senderThread.isAlive()) {
248 senderThread = new MessageSenderThread(deviceId.isBlank() ? "?" + ip : deviceId);
249 senderThread.start();
250 this.senderThread = senderThread;
255 * The {@link MessageSenderThread} is responsible for consuming messages from the queue and sending these to the
259 private class MessageSenderThread extends Thread {
260 private final String deviceId;
262 public MessageSenderThread(String deviceId) {
263 super("OH-binding-miio-MessageSenderThread-" + deviceId);
265 this.deviceId = deviceId;
270 logger.debug("Starting Mi IO MessageSenderThread {}", deviceId);
271 while (!interrupted()) {
273 if (concurrentLinkedQueue.isEmpty()) {
277 MiIoSendCommand queuedMessage = concurrentLinkedQueue.remove();
278 MiIoSendCommand miIoSendCommand = sendMiIoSendCommand(queuedMessage);
279 for (MiIoMessageListener listener : listeners) {
280 logger.trace("inform listener {}, data {} from {}", listener, queuedMessage, miIoSendCommand);
282 listener.onMessageReceived(miIoSendCommand);
283 } catch (Exception e) {
284 logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
287 } catch (NoSuchElementException e) {
289 } catch (InterruptedException e) {
290 // That's our signal to stop
292 } catch (Exception e) {
293 logger.warn("Error while polling/sending message for {}", deviceId, e);
297 logger.debug("Finished Mi IO MessageSenderThread {}", deviceId);
301 private String sendCommand(String command, byte[] token, String ip, String deviceId)
302 throws MiIoCryptoException, IOException {
303 byte[] sendMsg = new byte[0];
304 if (!command.isBlank()) {
306 encr = MiIoCrypto.encrypt(command.getBytes(StandardCharsets.UTF_8), token);
307 timeStamp = (int) Instant.now().getEpochSecond();
308 sendMsg = Message.createMsgData(encr, token, Utils.hexStringToByteArray(Utils.getHexId(deviceId)),
309 timeStamp + timeDelta);
311 Message miIoResponseMsg = sendData(sendMsg, ip);
312 if (miIoResponseMsg == null) {
313 if (logger.isTraceEnabled()) {
314 logger.trace("No response from device {} at {} for command {}.\r\n{}", deviceId, ip, command,
315 (new Message(sendMsg)).toSting());
317 logger.debug("No response from device {} at {} for command {}.", deviceId, ip, command);
320 if (errorCounter > MAX_ERRORS) {
321 status = ThingStatusDetail.CONFIGURATION_ERROR;
324 return "{\"error\":\"No Response\"}";
326 if (!miIoResponseMsg.isChecksumValid()) {
327 return "{\"error\":\"Message has invalid checksum\"}";
329 if (errorCounter > 0) {
331 status = ThingStatusDetail.NONE;
332 updateStatus(ThingStatus.ONLINE, status);
337 String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
338 logger.trace("Received response from {}: {}", ip, decryptedResponse);
339 return decryptedResponse;
342 public @Nullable Message sendPing(String ip) throws IOException {
343 for (int i = 0; i < 3; i++) {
344 logger.debug("Sending Ping to device '{}' ({})", deviceId, ip);
345 Message resp = sendData(MiIoBindingConstants.DISCOVER_STRING, ip);
355 private void pingFail() {
356 logger.debug("Ping to device '{}' ({}) failed", deviceId, ip);
358 status = ThingStatusDetail.COMMUNICATION_ERROR;
359 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
362 private void pingSuccess() {
363 logger.debug("Ping to device '{}' ({}) success", deviceId, ip);
366 status = ThingStatusDetail.NONE;
367 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
369 if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
370 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
372 status = ThingStatusDetail.NONE;
373 updateStatus(ThingStatus.ONLINE, status);
378 private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
379 for (MiIoMessageListener listener : listeners) {
380 logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
382 listener.onStatusUpdated(status, statusDetail);
383 } catch (Exception e) {
384 logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
389 private @Nullable Message sendData(byte[] sendMsg, String ip) throws IOException {
390 byte[] response = comms(sendMsg, ip);
391 if (response.length >= 32) {
392 Message miIoResponse = new Message(response);
393 timeStamp = (int) TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().getTime().getTime());
394 timeDelta = miIoResponse.getTimestampAsInt() - timeStamp;
395 logger.trace("Message Details:{} ", miIoResponse.toSting());
398 logger.trace("Reponse length <32 : {}", response.length);
403 private synchronized byte[] comms(byte[] message, String ip) throws IOException {
404 InetAddress ipAddress = InetAddress.getByName(ip);
405 DatagramSocket clientSocket = getSocket();
406 DatagramPacket receivePacket = new DatagramPacket(new byte[MSG_BUFFER_SIZE], MSG_BUFFER_SIZE);
408 logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
409 if (message.length > 0) {
410 byte[] sendData = new byte[MSG_BUFFER_SIZE];
412 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
413 MiIoBindingConstants.PORT);
414 clientSocket.send(sendPacket);
415 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
417 clientSocket.receive(receivePacket);
418 return Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
419 receivePacket.getOffset() + receivePacket.getLength());
420 } catch (SocketTimeoutException e) {
421 logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
427 private DatagramSocket getSocket() throws SocketException {
429 DatagramSocket socket = this.socket;
430 if (socket == null || socket.isClosed()) {
431 socket = new DatagramSocket();
432 socket.setSoTimeout(timeout);
433 logger.debug("Opening socket on port: {} ({} {})", socket.getLocalPort(), deviceId, ip);
434 this.socket = socket;
441 public void close() {
443 final MessageSenderThread senderThread = this.senderThread;
444 if (senderThread != null) {
445 senderThread.interrupt();
447 } catch (SecurityException e) {
448 logger.debug("Error while closing: {} ", e.getMessage());
453 public void closeSocket() {
455 final DatagramSocket socket = this.socket;
456 if (socket != null) {
457 logger.debug("Closing socket for port: {} ", socket.getLocalPort());
461 } catch (SecurityException e) {
462 logger.debug("Error while closing: {} ", e.getMessage());
470 return id.incrementAndGet();
474 * @param id the id to set
476 public void setId(int id) {
481 * Time delta between device time and server time
485 public int getTimeDelta() {
489 public String getDeviceId() {
493 public void setDeviceId(String deviceId) {
494 this.deviceId = deviceId;
495 MessageSenderThread senderThread = this.senderThread;
496 if (senderThread != null) {
497 senderThread.setName("OH-binding-miio-MessageSenderThread-" + deviceId);
501 public int getQueueLength() {
502 return concurrentLinkedQueue.size();