]> git.basschouten.com Git - openhab-addons.git/blob
1a2cc0f0a0bf6f64d736590b365d6c627013c927
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.miio.internal.transport;
14
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;
31
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;
48
49 import com.google.gson.JsonElement;
50 import com.google.gson.JsonObject;
51 import com.google.gson.JsonParser;
52 import com.google.gson.JsonSyntaxException;
53
54 /**
55  * The {@link MiIoAsyncCommunication} is responsible for communications with the Mi IO devices
56  *
57  * @author Marcel Verpaalen - Initial contribution
58  */
59 @NonNullByDefault
60 public class MiIoAsyncCommunication {
61
62     private static final int MSG_BUFFER_SIZE = 2048;
63
64     private final Logger logger = LoggerFactory.getLogger(MiIoAsyncCommunication.class);
65
66     private final String ip;
67     private final byte[] token;
68     private String deviceId;
69     private @Nullable DatagramSocket socket;
70
71     private List<MiIoMessageListener> listeners = new CopyOnWriteArrayList<>();
72
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;
80     private int timeout;
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;
85
86     private ConcurrentLinkedQueue<MiIoSendCommand> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
87
88     public MiIoAsyncCommunication(String ip, byte[] token, String did, int id, int timeout,
89             CloudConnector cloudConnector) {
90         this.ip = ip;
91         this.token = token;
92         this.deviceId = did;
93         this.timeout = timeout;
94         this.cloudConnector = cloudConnector;
95         setId(id);
96     }
97
98     protected List<MiIoMessageListener> getListeners() {
99         return listeners;
100     }
101
102     /**
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.
105      *
106      * @param listener {@link MiIoMessageListener} to be called back
107      */
108     public synchronized void registerListener(MiIoMessageListener listener) {
109         needPing = true;
110         startReceiver();
111         if (!getListeners().contains(listener)) {
112             logger.trace("Adding socket listener {}", listener);
113             getListeners().add(listener);
114         }
115     }
116
117     /**
118      * Unregisters a {@link MiIoMessageListener}. If there are no listeners left,
119      * the {@link MessageSenderThread} is being closed.
120      *
121      * @param listener {@link MiIoMessageListener} to be unregistered
122      */
123     public synchronized void unregisterListener(MiIoMessageListener listener) {
124         getListeners().remove(listener);
125         if (getListeners().isEmpty()) {
126             concurrentLinkedQueue.clear();
127             close();
128         }
129     }
130
131     public int queueCommand(String command, String params, String cloudServer, String sender)
132             throws MiIoCryptoException, IOException, JsonSyntaxException {
133         try {
134             JsonObject fullCommand = new JsonObject();
135             int cmdId = id.incrementAndGet();
136             if (cmdId > MAX_ID) {
137                 id.set(0);
138             }
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));
144                 }
145             } else {
146                 fullCommand.addProperty("id", cmdId);
147                 fullCommand.addProperty("method", command);
148                 fullCommand.add("params", JsonParser.parseString(params));
149             }
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);
159             }
160             if (needPing && cloudServer.isBlank()) {
161                 sendPing(ip);
162             }
163             return cmdId;
164         } catch (JsonSyntaxException | IllegalStateException e) {
165             logger.warn("Send command '{}' with parameters {} -> {} (Device: {}) gave error {}", command, params, ip,
166                     deviceId, e.getMessage());
167             throw e;
168         }
169     }
170
171     MiIoSendCommand sendMiIoSendCommand(MiIoSendCommand miIoSendCommand) {
172         String errorMsg = "Unknown Error while sending command";
173         String decryptedResponse = "";
174         try {
175             if (miIoSendCommand.getCloudServer().isBlank()) {
176                 decryptedResponse = sendCommand(miIoSendCommand.getCommandString(), token, ip, deviceId);
177             } else {
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);
184                 } else {
185                     String data = miIoSendCommand.getParams().toString();
186                     logger.debug("Custom cloud request send to url '{}' with data '{}'", miIoSendCommand.getMethod(),
187                             data);
188                     decryptedResponse = cloudConnector.sendCloudCommand(miIoSendCommand.getMethod(),
189                             miIoSendCommand.getCloudServer(), data);
190                     miIoSendCommand.setResponse(JsonParser.parseString(decryptedResponse).getAsJsonObject());
191                     return miIoSendCommand;
192                 }
193             }
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 ";
200             } else {
201                 needPing = false;
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;
209                     } else {
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);
214                         } else {
215                             errorMsg = String.format("Received message out of sync. Expected id: %d, received id: %d",
216                                     miIoSendCommand.getId(), id);
217                         }
218                     }
219                 } else {
220                     errorMsg = "Received message is without id";
221                 }
222
223             }
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);
238         }
239         JsonObject erroResp = new JsonObject();
240         erroResp.addProperty("error", errorMsg);
241         miIoSendCommand.setResponse(erroResp);
242         return miIoSendCommand;
243     }
244
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;
251         }
252     }
253
254     /**
255      * The {@link MessageSenderThread} is responsible for consuming messages from the queue and sending these to the
256      * device
257      *
258      */
259     private class MessageSenderThread extends Thread {
260         private final String deviceId;
261
262         public MessageSenderThread(String deviceId) {
263             super("OH-binding-miio-MessageSenderThread-" + deviceId);
264             setDaemon(true);
265             this.deviceId = deviceId;
266         }
267
268         @Override
269         public void run() {
270             logger.debug("Starting Mi IO MessageSenderThread {}", deviceId);
271             while (!interrupted()) {
272                 try {
273                     if (concurrentLinkedQueue.isEmpty()) {
274                         Thread.sleep(100);
275                         continue;
276                     }
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);
281                         try {
282                             listener.onMessageReceived(miIoSendCommand);
283                         } catch (Exception e) {
284                             logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
285                         }
286                     }
287                 } catch (NoSuchElementException e) {
288                     // ignore
289                 } catch (InterruptedException e) {
290                     // That's our signal to stop
291                     break;
292                 } catch (Exception e) {
293                     logger.warn("Error while polling/sending message for {}", deviceId, e);
294                 }
295             }
296             closeSocket();
297             logger.debug("Finished Mi IO MessageSenderThread {}", deviceId);
298         }
299     }
300
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()) {
305             byte[] encr;
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);
310         }
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());
316             } else {
317                 logger.debug("No response from device {} at {} for command {}.", deviceId, ip, command);
318             }
319             errorCounter++;
320             if (errorCounter > MAX_ERRORS) {
321                 status = ThingStatusDetail.CONFIGURATION_ERROR;
322                 sendPing(ip);
323             }
324             return "{\"error\":\"No Response\"}";
325         }
326         if (!miIoResponseMsg.isChecksumValid()) {
327             return "{\"error\":\"Message has invalid checksum\"}";
328         }
329         if (errorCounter > 0) {
330             errorCounter = 0;
331             status = ThingStatusDetail.NONE;
332             updateStatus(ThingStatus.ONLINE, status);
333         }
334         if (!connected) {
335             pingSuccess();
336         }
337         String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
338         logger.trace("Received response from {}: {}", ip, decryptedResponse);
339         return decryptedResponse;
340     }
341
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);
346             if (resp != null) {
347                 pingSuccess();
348                 return resp;
349             }
350         }
351         pingFail();
352         return null;
353     }
354
355     private void pingFail() {
356         logger.debug("Ping to device '{}' ({}) failed", deviceId, ip);
357         connected = false;
358         status = ThingStatusDetail.COMMUNICATION_ERROR;
359         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
360     }
361
362     private void pingSuccess() {
363         logger.debug("Ping to device '{}' ({}) success", deviceId, ip);
364         if (!connected) {
365             connected = true;
366             status = ThingStatusDetail.NONE;
367             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
368         } else {
369             if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
370                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
371             } else {
372                 status = ThingStatusDetail.NONE;
373                 updateStatus(ThingStatus.ONLINE, status);
374             }
375         }
376     }
377
378     private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
379         for (MiIoMessageListener listener : listeners) {
380             logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
381             try {
382                 listener.onStatusUpdated(status, statusDetail);
383             } catch (Exception e) {
384                 logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
385             }
386         }
387     }
388
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());
396             return miIoResponse;
397         } else {
398             logger.trace("Reponse length <32 : {}", response.length);
399             return null;
400         }
401     }
402
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);
407         try {
408             logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
409             if (message.length > 0) {
410                 byte[] sendData = new byte[MSG_BUFFER_SIZE];
411                 sendData = message;
412                 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
413                         MiIoBindingConstants.PORT);
414                 clientSocket.send(sendPacket);
415                 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
416             }
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());
422             needPing = true;
423             return new byte[0];
424         }
425     }
426
427     private DatagramSocket getSocket() throws SocketException {
428         @Nullable
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;
435             return socket;
436         } else {
437             return socket;
438         }
439     }
440
441     public void close() {
442         try {
443             final MessageSenderThread senderThread = this.senderThread;
444             if (senderThread != null) {
445                 senderThread.interrupt();
446             }
447         } catch (SecurityException e) {
448             logger.debug("Error while closing: {} ", e.getMessage());
449         }
450         closeSocket();
451     }
452
453     public void closeSocket() {
454         try {
455             final DatagramSocket socket = this.socket;
456             if (socket != null) {
457                 logger.debug("Closing socket for port: {} ", socket.getLocalPort());
458                 socket.close();
459                 this.socket = null;
460             }
461         } catch (SecurityException e) {
462             logger.debug("Error while closing: {} ", e.getMessage());
463         }
464     }
465
466     /**
467      * @return the id
468      */
469     public int getId() {
470         return id.incrementAndGet();
471     }
472
473     /**
474      * @param id the id to set
475      */
476     public void setId(int id) {
477         this.id.set(id);
478     }
479
480     /**
481      * Time delta between device time and server time
482      *
483      * @return delta
484      */
485     public int getTimeDelta() {
486         return timeDelta;
487     }
488
489     public String getDeviceId() {
490         return deviceId;
491     }
492
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);
498         }
499     }
500
501     public int getQueueLength() {
502         return concurrentLinkedQueue.size();
503     }
504 }