]> git.basschouten.com Git - openhab-addons.git/blob
95be2fba35aa850531c57396d174f13361523310
[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(deviceId);
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         private final String deviceId;
265
266         public MessageSenderThread(String deviceId) {
267             super("OH-binding-miio-MessageSenderThread-" + deviceId);
268             setDaemon(true);
269             this.deviceId = deviceId;
270         }
271
272         @Override
273         public void run() {
274             logger.debug("Starting Mi IO MessageSenderThread {}", deviceId);
275             while (!interrupted()) {
276                 try {
277                     if (concurrentLinkedQueue.isEmpty()) {
278                         Thread.sleep(100);
279                         continue;
280                     }
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);
285                         try {
286                             listener.onMessageReceived(miIoSendCommand);
287                         } catch (Exception e) {
288                             logger.debug("Could not inform listener {}: {}: ", listener, e.getMessage(), e);
289                         }
290                     }
291                 } catch (NoSuchElementException e) {
292                     // ignore
293                 } catch (InterruptedException e) {
294                     // That's our signal to stop
295                     break;
296                 } catch (Exception e) {
297                     logger.warn("Error while polling/sending message for {}", deviceId, e);
298                 }
299             }
300             closeSocket();
301             logger.debug("Finished Mi IO MessageSenderThread {}", deviceId);
302         }
303     }
304
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()) {
309             byte[] encr;
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);
314         }
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());
320             } else {
321                 logger.debug("No response from device {} at {} for command {}.", deviceId, ip, command);
322             }
323             errorCounter++;
324             if (errorCounter > MAX_ERRORS) {
325                 status = ThingStatusDetail.CONFIGURATION_ERROR;
326                 sendPing(ip);
327             }
328             return "{\"error\":\"No Response\"}";
329         }
330         if (!miIoResponseMsg.isChecksumValid()) {
331             return "{\"error\":\"Message has invalid checksum\"}";
332         }
333         if (errorCounter > 0) {
334             errorCounter = 0;
335             status = ThingStatusDetail.NONE;
336             updateStatus(ThingStatus.ONLINE, status);
337         }
338         if (!connected) {
339             pingSuccess();
340         }
341         String decryptedResponse = new String(MiIoCrypto.decrypt(miIoResponseMsg.getData(), token), "UTF-8").trim();
342         logger.trace("Received response from {}: {}", ip, decryptedResponse);
343         return decryptedResponse;
344     }
345
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);
350             if (resp != null) {
351                 pingSuccess();
352                 return resp;
353             }
354         }
355         pingFail();
356         return null;
357     }
358
359     private void pingFail() {
360         logger.debug("Ping to device '{}' ({}) failed", deviceId, ip);
361         connected = false;
362         status = ThingStatusDetail.COMMUNICATION_ERROR;
363         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
364     }
365
366     private void pingSuccess() {
367         logger.debug("Ping to device '{}' ({}) success", deviceId, ip);
368         if (!connected) {
369             connected = true;
370             status = ThingStatusDetail.NONE;
371             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE);
372         } else {
373             if (ThingStatusDetail.CONFIGURATION_ERROR.equals(status)) {
374                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
375             } else {
376                 status = ThingStatusDetail.NONE;
377                 updateStatus(ThingStatus.ONLINE, status);
378             }
379         }
380     }
381
382     private void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
383         for (MiIoMessageListener listener : listeners) {
384             logger.trace("inform listener {}, data {} from {}", listener, status, statusDetail);
385             try {
386                 listener.onStatusUpdated(status, statusDetail);
387             } catch (Exception e) {
388                 logger.debug("Could not inform listener {}: {}", listener, e.getMessage(), e);
389             }
390         }
391     }
392
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());
400             return miIoResponse;
401         } else {
402             logger.trace("Reponse length <32 : {}", response.length);
403             return null;
404         }
405     }
406
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);
411         try {
412             logger.trace("Connection {}:{}", ip, clientSocket.getLocalPort());
413             if (message.length > 0) {
414                 byte[] sendData = new byte[MSG_BUFFER_SIZE];
415                 sendData = message;
416                 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress,
417                         MiIoBindingConstants.PORT);
418                 clientSocket.send(sendPacket);
419                 sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
420             }
421             clientSocket.receive(receivePacket);
422             byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
423                     receivePacket.getOffset() + receivePacket.getLength());
424             return response;
425         } catch (SocketTimeoutException e) {
426             logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
427             needPing = true;
428             return new byte[0];
429         }
430     }
431
432     private DatagramSocket getSocket() throws SocketException {
433         @Nullable
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;
440             return socket;
441         } else {
442             return socket;
443         }
444     }
445
446     public void close() {
447         try {
448             final MessageSenderThread senderThread = this.senderThread;
449             if (senderThread != null) {
450                 senderThread.interrupt();
451             }
452         } catch (SecurityException e) {
453             logger.debug("Error while closing: {} ", e.getMessage());
454         }
455         closeSocket();
456     }
457
458     public void closeSocket() {
459         try {
460             final DatagramSocket socket = this.socket;
461             if (socket != null) {
462                 logger.debug("Closing socket for port: {} ", socket.getLocalPort());
463                 socket.close();
464                 this.socket = null;
465             }
466         } catch (SecurityException e) {
467             logger.debug("Error while closing: {} ", e.getMessage());
468         }
469     }
470
471     /**
472      * @return the id
473      */
474     public int getId() {
475         return id.incrementAndGet();
476     }
477
478     /**
479      * @param id the id to set
480      */
481     public void setId(int id) {
482         this.id.set(id);
483     }
484
485     /**
486      * Time delta between device time and server time
487      *
488      * @return delta
489      */
490     public int getTimeDelta() {
491         return timeDelta;
492     }
493
494     public String getDeviceId() {
495         return deviceId;
496     }
497
498     public void setDeviceId(String deviceId) {
499         this.deviceId = deviceId;
500     }
501
502     public int getQueueLength() {
503         return concurrentLinkedQueue.size();
504     }
505 }