]> git.basschouten.com Git - openhab-addons.git/blob
7715de5649ddd6145b6d0577ac952d44023ca627
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.discovery;
14
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.DatagramPacket;
19 import java.net.DatagramSocket;
20 import java.net.InetAddress;
21 import java.net.SocketException;
22 import java.util.Arrays;
23 import java.util.Dictionary;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
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.MiIoDevices;
36 import org.openhab.binding.miio.internal.Utils;
37 import org.openhab.binding.miio.internal.cloud.CloudConnector;
38 import org.openhab.binding.miio.internal.cloud.CloudDeviceDTO;
39 import org.openhab.core.config.discovery.AbstractDiscoveryService;
40 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
41 import org.openhab.core.config.discovery.DiscoveryService;
42 import org.openhab.core.net.NetUtil;
43 import org.openhab.core.thing.ThingTypeUID;
44 import org.openhab.core.thing.ThingUID;
45 import org.osgi.service.cm.Configuration;
46 import org.osgi.service.cm.ConfigurationAdmin;
47 import org.osgi.service.component.annotations.Activate;
48 import org.osgi.service.component.annotations.Component;
49 import org.osgi.service.component.annotations.Reference;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * The {@link MiIoDiscovery} is responsible for discovering new Xiaomi Mi IO devices
55  * and their token
56  *
57  * @author Marcel Verpaalen - Initial contribution
58  *
59  */
60 @NonNullByDefault
61 @Component(service = DiscoveryService.class, configurationPid = "discovery.miio")
62 public class MiIoDiscovery extends AbstractDiscoveryService {
63
64     /** The refresh interval for background discovery */
65     private static final long SEARCH_INTERVAL = 600;
66     private static final int BUFFER_LENGTH = 1024;
67     private static final int DISCOVERY_TIME = 10;
68     private static final String DISABLED = "disabled";
69     private static final String SUPPORTED = "supportedonly";
70     private static final String ALL = "all";
71
72     private @Nullable ScheduledFuture<?> miIoDiscoveryJob;
73     protected @Nullable DatagramSocket clientSocket;
74     private @Nullable Thread socketReceiveThread;
75     private Set<String> responseIps = new HashSet<>();
76
77     private final Logger logger = LoggerFactory.getLogger(MiIoDiscovery.class);
78     private final CloudConnector cloudConnector;
79     private Map<String, String> cloudDevices = new ConcurrentHashMap<>();
80     private @Nullable Configuration miioConfig;
81
82     @Activate
83     public MiIoDiscovery(@Reference CloudConnector cloudConnector, @Reference ConfigurationAdmin configAdmin)
84             throws IllegalArgumentException {
85         super(DISCOVERY_TIME);
86         this.cloudConnector = cloudConnector;
87         try {
88             miioConfig = configAdmin.getConfiguration("binding.miio");
89         } catch (IOException | SecurityException e) {
90             logger.debug("Error getting configuration: {}", e.getMessage());
91         }
92     }
93
94     private String getCloudDiscoveryMode() {
95         if (miioConfig != null) {
96             try {
97                 Dictionary<String, @Nullable Object> properties = miioConfig.getProperties();
98                 String cloudDiscoveryModeConfig = (String) properties.get("cloudDiscoveryMode");
99                 if (cloudDiscoveryModeConfig == null) {
100                     cloudDiscoveryModeConfig = DISABLED;
101                 } else {
102                     cloudDiscoveryModeConfig = cloudDiscoveryModeConfig.toLowerCase();
103                 }
104                 return Set.of(SUPPORTED, ALL).contains(cloudDiscoveryModeConfig) ? cloudDiscoveryModeConfig : DISABLED;
105             } catch (ClassCastException | SecurityException e) {
106                 logger.debug("Error getting cloud discovery configuration: {}", e.getMessage());
107             }
108         }
109         return DISABLED;
110     }
111
112     @Override
113     public Set<ThingTypeUID> getSupportedThingTypes() {
114         return SUPPORTED_THING_TYPES_UIDS;
115     }
116
117     @Override
118     protected void startBackgroundDiscovery() {
119         logger.debug("Start Xiaomi Mi IO background discovery with cloudDiscoveryMode: {}", getCloudDiscoveryMode());
120         final @Nullable ScheduledFuture<?> miIoDiscoveryJob = this.miIoDiscoveryJob;
121         if (miIoDiscoveryJob == null || miIoDiscoveryJob.isCancelled()) {
122             this.miIoDiscoveryJob = scheduler.scheduleWithFixedDelay(this::discover, 0, SEARCH_INTERVAL,
123                     TimeUnit.SECONDS);
124         }
125     }
126
127     @Override
128     protected void stopBackgroundDiscovery() {
129         logger.debug("Stop Xiaomi  Mi IO background discovery");
130         final @Nullable ScheduledFuture<?> miIoDiscoveryJob = this.miIoDiscoveryJob;
131         if (miIoDiscoveryJob != null) {
132             miIoDiscoveryJob.cancel(true);
133             this.miIoDiscoveryJob = null;
134         }
135     }
136
137     @Override
138     protected void deactivate() {
139         stopReceiverThreat();
140         final DatagramSocket clientSocket = this.clientSocket;
141         if (clientSocket != null) {
142             clientSocket.close();
143         }
144         this.clientSocket = null;
145         super.deactivate();
146     }
147
148     @Override
149     protected void startScan() {
150         String cloudDiscoveryMode = getCloudDiscoveryMode();
151         logger.debug("Start Xiaomi Mi IO discovery with cloudDiscoveryMode: {}", cloudDiscoveryMode);
152         if (!cloudDiscoveryMode.contentEquals(DISABLED)) {
153             cloudDiscovery();
154         }
155         final DatagramSocket clientSocket = getSocket();
156         if (clientSocket != null) {
157             logger.debug("Discovery using socket on port {}", clientSocket.getLocalPort());
158             discover();
159         } else {
160             logger.debug("Discovery not started. Client DatagramSocket null");
161         }
162     }
163
164     private void discover() {
165         startReceiverThreat();
166         responseIps = new HashSet<>();
167         HashSet<String> broadcastAddresses = new HashSet<>();
168         broadcastAddresses.add("224.0.0.1");
169         broadcastAddresses.add("224.0.0.50");
170         broadcastAddresses.addAll(NetUtil.getAllBroadcastAddresses());
171         for (String broadcastAdress : broadcastAddresses) {
172             sendDiscoveryRequest(broadcastAdress);
173         }
174     }
175
176     private void cloudDiscovery() {
177         String cloudDiscoveryMode = getCloudDiscoveryMode();
178         cloudDevices.clear();
179         if (cloudConnector.isConnected()) {
180             List<CloudDeviceDTO> dv = cloudConnector.getDevicesList();
181             for (CloudDeviceDTO device : dv) {
182                 String id = Utils.toHEX(device.getDid());
183                 if (cloudDiscoveryMode.contentEquals(SUPPORTED)) {
184                     if (MiIoDevices.getType(device.getModel()).getThingType().equals(THING_TYPE_UNSUPPORTED)) {
185                         logger.warn("Discovered from cloud, but ignored because not supported: {} {}", id, device);
186                     }
187                 }
188                 if (device.getIsOnline()) {
189                     logger.debug("Discovered from cloud: {} {}", id, device);
190                     cloudDevices.put(id, device.getLocalip());
191                     String token = device.getToken();
192                     String label = device.getName() + " " + id + " (" + device.getDid() + ")";
193                     String country = device.getServer();
194                     boolean isOnline = device.getIsOnline();
195                     String ip = device.getLocalip();
196                     submitDiscovery(ip, token, id, label, country, isOnline);
197                 } else {
198                     logger.debug("Discovered from cloud, but ignored because not online: {} {}", id, device);
199                 }
200             }
201         }
202     }
203
204     private void discovered(String ip, byte[] response) {
205         logger.trace("Discovery responses from : {}:{}", ip, Utils.getSpacedHex(response));
206         Message msg = new Message(response);
207         String token = Utils.getHex(msg.getChecksum());
208         String id = Utils.getHex(msg.getDeviceId());
209         String label = "Xiaomi Mi Device " + id + " (" + Utils.fromHEX(id) + ")";
210         String country = "";
211         boolean isOnline = false;
212         if (ip.equals(cloudDevices.get(id))) {
213             logger.debug("Skipped adding local found {}. Already discovered by cloud.", label);
214             return;
215         }
216         if (cloudConnector.isConnected()) {
217             cloudConnector.getDevicesList();
218             CloudDeviceDTO cloudInfo = cloudConnector.getDeviceInfo(id);
219             if (cloudInfo != null) {
220                 logger.debug("Cloud Info: {}", cloudInfo);
221                 token = cloudInfo.getToken();
222                 label = cloudInfo.getName() + " " + id + " (" + Utils.fromHEX(id) + ")";
223                 country = cloudInfo.getServer();
224                 isOnline = cloudInfo.getIsOnline();
225             }
226         }
227         submitDiscovery(ip, token, id, label, country, isOnline);
228     }
229
230     private void submitDiscovery(String ip, String token, String id, String label, String country, boolean isOnline) {
231         ThingUID uid = new ThingUID(THING_TYPE_MIIO, id);
232         DiscoveryResultBuilder dr = DiscoveryResultBuilder.create(uid).withProperty(PROPERTY_HOST_IP, ip)
233                 .withProperty(PROPERTY_DID, id);
234         if (IGNORED_TOKENS.contains(token)) {
235             logger.debug("Discovered Mi Device {} ({}) at {} as {}", id, Utils.fromHEX(id), ip, uid);
236             logger.debug(
237                     "No token discovered for device {}. For options how to get the token, check the binding readme.",
238                     id);
239             dr = dr.withRepresentationProperty(PROPERTY_DID).withLabel(label);
240         } else {
241             logger.debug("Discovered Mi Device {} ({}) at {} as {} with token {}", id, Utils.fromHEX(id), ip, uid,
242                     token);
243             dr = dr.withProperty(PROPERTY_TOKEN, token).withRepresentationProperty(PROPERTY_DID)
244                     .withLabel(label + " with token");
245         }
246         if (!country.isEmpty() && isOnline) {
247             dr = dr.withProperty(PROPERTY_CLOUDSERVER, country);
248         }
249         thingDiscovered(dr.build());
250     }
251
252     synchronized @Nullable DatagramSocket getSocket() {
253         DatagramSocket clientSocket = this.clientSocket;
254         if (clientSocket != null && clientSocket.isBound()) {
255             return clientSocket;
256         }
257         try {
258             logger.debug("Getting new socket for discovery");
259             clientSocket = new DatagramSocket();
260             clientSocket.setReuseAddress(true);
261             clientSocket.setBroadcast(true);
262             this.clientSocket = clientSocket;
263             return clientSocket;
264         } catch (SocketException | SecurityException e) {
265             logger.debug("Error getting socket for discovery: {}", e.getMessage());
266         }
267         return null;
268     }
269
270     private void closeSocket() {
271         final @Nullable DatagramSocket clientSocket = this.clientSocket;
272         if (clientSocket != null) {
273             clientSocket.close();
274         } else {
275             return;
276         }
277         this.clientSocket = null;
278     }
279
280     private void sendDiscoveryRequest(String ipAddress) {
281         final @Nullable DatagramSocket socket = getSocket();
282         if (socket != null) {
283             try {
284                 byte[] sendData = DISCOVER_STRING;
285                 logger.trace("Discovery sending ping to {} from {}:{}", ipAddress, socket.getLocalAddress(),
286                         socket.getLocalPort());
287                 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
288                         InetAddress.getByName(ipAddress), PORT);
289                 for (int i = 1; i <= 1; i++) {
290                     socket.send(sendPacket);
291                 }
292             } catch (IOException e) {
293                 logger.trace("Discovery on {} error: {}", ipAddress, e.getMessage());
294             }
295         }
296     }
297
298     /**
299      * starts the {@link ReceiverThread} thread
300      */
301     private synchronized void startReceiverThreat() {
302         final Thread srt = socketReceiveThread;
303         if (srt != null) {
304             if (srt.isAlive() && !srt.isInterrupted()) {
305                 return;
306             }
307         }
308         stopReceiverThreat();
309         Thread socketReceiveThread = new ReceiverThread();
310         socketReceiveThread.start();
311         this.socketReceiveThread = socketReceiveThread;
312     }
313
314     /**
315      * Stops the {@link ReceiverThread} thread
316      */
317     private synchronized void stopReceiverThreat() {
318         if (socketReceiveThread != null) {
319             socketReceiveThread.interrupt();
320             socketReceiveThread = null;
321         }
322         closeSocket();
323     }
324
325     /**
326      * The thread, which waits for data and submits the unique results addresses to the discovery results
327      *
328      */
329     private class ReceiverThread extends Thread {
330         @Override
331         public void run() {
332             DatagramSocket socket = getSocket();
333             if (socket != null) {
334                 logger.debug("Starting discovery receiver thread for socket on port {}", socket.getLocalPort());
335                 receiveData(socket);
336             }
337         }
338
339         /**
340          * This method waits for data and submits the unique results addresses to the discovery results
341          *
342          * @param socket - The multicast socket to (re)use
343          */
344         private void receiveData(DatagramSocket socket) {
345             DatagramPacket receivePacket = new DatagramPacket(new byte[BUFFER_LENGTH], BUFFER_LENGTH);
346             try {
347                 while (!interrupted()) {
348                     logger.trace("Thread {} waiting for data on port {}", this, socket.getLocalPort());
349                     socket.receive(receivePacket);
350                     String hostAddress = receivePacket.getAddress().getHostAddress();
351                     logger.trace("Received {} bytes response from {}:{} on Port {}", receivePacket.getLength(),
352                             hostAddress, receivePacket.getPort(), socket.getLocalPort());
353
354                     byte[] messageBuf = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
355                             receivePacket.getOffset() + receivePacket.getLength());
356                     if (logger.isTraceEnabled()) {
357                         Message miIoResponse = new Message(messageBuf);
358                         logger.trace("Discovery response received from {} DeviceID: {}\r\n{}", hostAddress,
359                                 Utils.getHex(miIoResponse.getDeviceId()), miIoResponse.toSting());
360                     }
361                     if (!responseIps.contains(hostAddress)) {
362                         scheduler.schedule(() -> {
363                             try {
364                                 discovered(hostAddress, messageBuf);
365                             } catch (Exception e) {
366                                 logger.debug("Error submitting discovered Mi IO device at {}", hostAddress, e);
367                             }
368                         }, 0, TimeUnit.SECONDS);
369                     }
370                     responseIps.add(hostAddress);
371                 }
372             } catch (SocketException e) {
373                 logger.debug("Receiver thread received SocketException: {}", e.getMessage());
374             } catch (IOException e) {
375                 logger.trace("Receiver thread was interrupted");
376             }
377             logger.debug("Receiver thread ended");
378         }
379     }
380 }