]> git.basschouten.com Git - openhab-addons.git/blob
63a75a4d55dd97f356c85aef9eec4b10f3fa1bbb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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         startReceiver();
97     }
98
99     protected List<MiIoMessageListener> getListeners() {
100         return listeners;
101     }
102
103     /**
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.
106      *
107      * @param listener {@link MiIoMessageListener} to be called back
108      */
109     public synchronized void registerListener(MiIoMessageListener listener) {
110         needPing = true;
111         startReceiver();
112         if (!getListeners().contains(listener)) {
113             logger.trace("Adding socket listener {}", listener);
114             getListeners().add(listener);
115         }
116     }
117
118     /**
119      * Unregisters a {@link MiIoMessageListener}. If there are no listeners left,
120      * the {@link MessageSenderThread} is being closed.
121      *
122      * @param listener {@link MiIoMessageListener} to be unregistered
123      */
124     public synchronized void unregisterListener(MiIoMessageListener listener) {
125         getListeners().remove(listener);
126         if (getListeners().isEmpty()) {
127             concurrentLinkedQueue.clear();
128             close();
129         }
130     }
131
132     public int queueCommand(String command, String params, String cloudServer, String sender)
133             throws MiIoCryptoException, IOException, JsonSyntaxException {
134         try {
135             JsonObject fullCommand = new JsonObject();
136             int cmdId = id.incrementAndGet();
137             if (cmdId > MAX_ID) {
138                 id.set(0);
139             }
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));
145                 }
146             } else {
147                 fullCommand.addProperty("id", cmdId);
148                 fullCommand.addProperty("method", command);
149                 fullCommand.add("params", JsonParser.parseString(params));
150             }
151             MiIoSendCommand sendCmd = new MiIoSendCommand(cmdId, MiIoCommand.getCommand(command), fullCommand,
152                     cloudServer);
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);
160             }
161             if (needPing && cloudServer.isBlank()) {
162                 sendPing(ip);
163             }
164             return cmdId;
165         } catch (JsonSyntaxException | IllegalStateException e) {
166             logger.warn("Send command '{}' with parameters {} -> {} (Device: {}) gave error {}", command, params, ip,
167                     deviceId, e.getMessage());
168             throw e;
169         }
170     }
171
172     MiIoSendCommand sendMiIoSendCommand(MiIoSendCommand miIoSendCommand) {
173         String errorMsg = "Unknown Error while sending command";
174         String decryptedResponse = "";
175         try {
176             if (miIoSendCommand.getCloudServer().isBlank()) {
177                 decryptedResponse = sendCommand(miIoSendCommand.getCommandString(), token, ip, deviceId);
178             } else {
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);
185                 } else {
186                     String data = miIoSendCommand.getParams().isJsonArray()
187                             && miIoSendCommand.getParams().getAsJsonArray().size() > 0
188                                     ? miIoSendCommand.getParams().getAsJsonArray().get(0).toString()
189                                     : "";
190                     logger.debug("Custom cloud request send to url '{}' with data '{}'", miIoSendCommand.getMethod(),
191                             data);
192                     decryptedResponse = cloudConnector.sendCloudCommand(miIoSendCommand.getMethod(),
193                             miIoSendCommand.getCloudServer(), data);
194                     miIoSendCommand.setResponse(JsonParser.parseString(decryptedResponse).getAsJsonObject());
195                     return miIoSendCommand;
196                 }
197             }
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 ";
204             } else {
205                 needPing = false;
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;
213                     } else {
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);
218                         } else {
219                             errorMsg = String.format("Received message out of sync. Expected id: %d, received id: %d",
220                                     miIoSendCommand.getId(), id);
221                         }
222                     }
223                 } else {
224                     errorMsg = "Received message is without id";
225                 }
226
227             }
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);
242         }
243         JsonObject erroResp = new JsonObject();
244         erroResp.addProperty("error", errorMsg);
245         miIoSendCommand.setResponse(erroResp);
246         return miIoSendCommand;
247     }
248
249     public synchronized void startReceiver() {
250         MessageSenderThread senderThread = this.senderThread;
251         if (senderThread == null || !senderThread.isAlive()) {
252             senderThread = new MessageSenderThread();
253             senderThread.start();
254             this.senderThread = senderThread;
255         }
256     }
257
258     /**
259      * The {@link MessageSenderThread} is responsible for consuming messages from the queue and sending these to the
260      * device
261      *
262      */
263     private class MessageSenderThread extends Thread {
264         public MessageSenderThread() {
265             super("Mi IO MessageSenderThread");
266             setDaemon(true);
267         }
268
269         @Override
270         public void run() {
271             logger.debug("Starting Mi IO MessageSenderThread");
272             while (!interrupted()) {
273                 try {
274                     if (concurrentLinkedQueue.isEmpty()) {
275                         Thread.sleep(100);
276                         continue;
277                     }
278                     MiIoSendCommand queuedMessage = concurrentLinkedQueue.remove();
279                     MiIoSendCommand miIoSendCommand = sendMiIoSendCommand(queuedMessage);
280                     for (MiIoMessageListener listener : listeners) {
281                         logger.trace("inform listener {}, data {} from {}", listener, queuedMessage, miIoSendCommand);
282                         try {
283                             listener.onMessageReceived(miIoSendCommand);
284                         } catch (Exception e) {
285                             logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
286                         }
287                     }
288                 } catch (NoSuchElementException e) {
289                     // ignore
290                 } catch (InterruptedException e) {
291                     // That's our signal to stop
292                     break;
293                 } catch (Exception e) {
294                     logger.warn("Error while polling/sending message", e);
295                 }
296             }
297             closeSocket();
298             logger.debug("Finished Mi IO MessageSenderThread");
299         }
300     }
301
302     private String sendCommand(String command, byte[] token, String ip, String deviceId)
303             throws MiIoCryptoException, IOException {
304         byte[] sendMsg = new byte[0];
305         if (!command.isBlank()) {
306             byte[] encr;
307             encr = MiIoCrypto.encrypt(command.getBytes(StandardCharsets.UTF_8), token);
308             timeStamp = (int) Instant.now().getEpochSecond();
309             sendMsg = Message.createMsgData(encr, token, Utils.hexStringToByteArray(Utils.getHexId(deviceId)),
310                     timeStamp + timeDelta);
311         }
312         Message miIoResponseMsg = sendData(sendMsg, ip);
313         if (miIoResponseMsg == null) {
314             if (logger.isTraceEnabled()) {
315                 logger.trace("No response from device {} at {} for command {}.\r\n{}", deviceId, ip, command,
316                         (new Message(sendMsg)).toSting());
317             } else {
318                 logger.debug("No response from device {} at {} for command {}.", deviceId, ip, command);
319             }
320             errorCounter++;
321             if (errorCounter > MAX_ERRORS) {
322                 status = ThingStatusDetail.CONFIGURATION_ERROR;
323                 sendPing(ip);
324             }
325             return "{\"error\":\"No Response\"}";
326         }
327         if (!miIoResponseMsg.isChecksumValid()) {
328             return "{\"error\":\"Message has invalid checksum\"}";
329         }
330         if (errorCounter > 0) {
331             errorCounter = 0;
332             status = ThingStatusDetail.NONE;
333             updateStatus(ThingStatus.ONLINE, status);
334         }
335         if (!connected) {
336             pingSuccess();
337         }
338         String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
339         logger.trace("Received response from {}: {}", ip, decryptedResponse);
340         return decryptedResponse;
341     }
342
343     public @Nullable Message sendPing(String ip) throws IOException {
344         for (int i = 0; i < 3; i++) {
345             logger.debug("Sending Ping to device '{}' ({})", deviceId, ip);
346             Message resp = sendData(MiIoBindingConstants.DISCOVER_STRING, ip);
347             if (resp != null) {
348                 pingSuccess();
349                 return resp;
350             }
351         }
352         pingFail();
353         return null;
354     }
355
356     private void pingFail() {
357         logger.debug("Ping to device '{}' ({}) failed", deviceId, ip);
358         connected = false;
359         status = ThingStatusDetail.COMMUNICATION_ERROR;
360         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
361     }
362
363     private void pingSuccess() {
364         logger.debug("Ping to device '{}' ({}) success", deviceId, ip);
365         if (!connected) {
366             connected = true;
367             status = ThingStatusDetail.NONE;
368             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
369         } else {
370             if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
371                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
372             } else {
373                 status = ThingStatusDetail.NONE;
374                 updateStatus(ThingStatus.ONLINE, status);
375             }
376         }
377     }
378
379     private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
380         for (MiIoMessageListener listener : listeners) {
381             logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
382             try {
383                 listener.onStatusUpdated(status, statusDetail);
384             } catch (Exception e) {
385                 logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
386             }
387         }
388     }
389
390     private @Nullable Message sendData(byte[] sendMsg, String ip) throws IOException {
391         byte[] response = comms(sendMsg, ip);
392         if (response.length >= 32) {
393             Message miIoResponse = new Message(response);
394             timeStamp = (int) TimeUnit.MILLISECONDS.toSeconds(Calendar.getInstance().getTime().getTime());
395             timeDelta = miIoResponse.getTimestampAsInt() - timeStamp;
396             logger.trace("Message Details:{} ", miIoResponse.toSting());
397             return miIoResponse;
398         } else {
399             logger.trace("Reponse length <32 : {}", response.length);
400             return null;
401         }
402     }
403
404     private synchronized byte[] comms(byte[] message, String ip) throws IOException {
405         InetAddress ipAddress = InetAddress.getByName(ip);
406         DatagramSocket clientSocket = getSocket();
407         DatagramPacket receivePacket = new DatagramPacket(new byte[MSG_BUFFER_SIZE], MSG_BUFFER_SIZE);
408         try {
409             logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
410             if (message.length > 0) {
411                 byte[] sendData = new byte[MSG_BUFFER_SIZE];
412                 sendData = message;
413                 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
414                         MiIoBindingConstants.PORT);
415                 clientSocket.send(sendPacket);
416                 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
417             }
418             clientSocket.receive(receivePacket);
419             byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
420                     receivePacket.getOffset() + receivePacket.getLength());
421             return response;
422         } catch (SocketTimeoutException e) {
423             logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
424             needPing = true;
425             return new byte[0];
426         }
427     }
428
429     private DatagramSocket getSocket() throws SocketException {
430         @Nullable
431         DatagramSocket socket = this.socket;
432         if (socket == null || socket.isClosed()) {
433             socket = new DatagramSocket();
434             socket.setSoTimeout(timeout);
435             logger.debug("Opening socket on port: {} ", socket.getLocalPort());
436             this.socket = socket;
437             return socket;
438         } else {
439             return socket;
440         }
441     }
442
443     public void close() {
444         try {
445             final MessageSenderThread senderThread = this.senderThread;
446             if (senderThread != null) {
447                 senderThread.interrupt();
448             }
449         } catch (SecurityException e) {
450             logger.debug("Error while closing: {} ", e.getMessage());
451         }
452         closeSocket();
453     }
454
455     public void closeSocket() {
456         try {
457             final DatagramSocket socket = this.socket;
458             if (socket != null) {
459                 logger.debug("Closing socket for port: {} ", socket.getLocalPort());
460                 socket.close();
461                 this.socket = null;
462             }
463         } catch (SecurityException e) {
464             logger.debug("Error while closing: {} ", e.getMessage());
465         }
466     }
467
468     /**
469      * @return the id
470      */
471     public int getId() {
472         return id.incrementAndGet();
473     }
474
475     /**
476      * @param id the id to set
477      */
478     public void setId(int id) {
479         this.id.set(id);
480     }
481
482     /**
483      * Time delta between device time and server time
484      *
485      * @return delta
486      */
487     public int getTimeDelta() {
488         return timeDelta;
489     }
490
491     public String getDeviceId() {
492         return deviceId;
493     }
494
495     public void setDeviceId(String deviceId) {
496         this.deviceId = deviceId;
497     }
498
499     public int getQueueLength() {
500         return concurrentLinkedQueue.size();
501     }
502 }