2 * Copyright (c) 2010-2020 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.discovery;
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.*;
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;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
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;
54 * The {@link MiIoDiscovery} is responsible for discovering new Xiaomi Mi IO devices
57 * @author Marcel Verpaalen - Initial contribution
61 @Component(service = DiscoveryService.class, configurationPid = "discovery.miio")
62 public class MiIoDiscovery extends AbstractDiscoveryService {
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";
72 private @Nullable ScheduledFuture<?> miIoDiscoveryJob;
73 protected @Nullable DatagramSocket clientSocket;
74 private @Nullable Thread socketReceiveThread;
75 private Set<String> responseIps = new HashSet<>();
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;
83 public MiIoDiscovery(@Reference CloudConnector cloudConnector, @Reference ConfigurationAdmin configAdmin)
84 throws IllegalArgumentException {
85 super(DISCOVERY_TIME);
86 this.cloudConnector = cloudConnector;
88 miioConfig = configAdmin.getConfiguration("binding.miio");
89 } catch (IOException | SecurityException e) {
90 logger.debug("Error getting configuration: {}", e.getMessage());
94 private String getCloudDiscoveryMode() {
95 if (miioConfig != null) {
97 Dictionary<String, @Nullable Object> properties = miioConfig.getProperties();
98 String cloudDiscoveryModeConfig = (String) properties.get("cloudDiscoveryMode");
99 if (cloudDiscoveryModeConfig == null) {
100 cloudDiscoveryModeConfig = DISABLED;
102 cloudDiscoveryModeConfig = cloudDiscoveryModeConfig.toLowerCase();
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());
113 public Set<ThingTypeUID> getSupportedThingTypes() {
114 return SUPPORTED_THING_TYPES_UIDS;
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,
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;
138 protected void deactivate() {
139 stopReceiverThreat();
140 final DatagramSocket clientSocket = this.clientSocket;
141 if (clientSocket != null) {
142 clientSocket.close();
144 this.clientSocket = null;
149 protected void startScan() {
150 String cloudDiscoveryMode = getCloudDiscoveryMode();
151 logger.debug("Start Xiaomi Mi IO discovery with cloudDiscoveryMode: {}", cloudDiscoveryMode);
152 if (!cloudDiscoveryMode.contentEquals(DISABLED)) {
155 final DatagramSocket clientSocket = getSocket();
156 if (clientSocket != null) {
157 logger.debug("Discovery using socket on port {}", clientSocket.getLocalPort());
160 logger.debug("Discovery not started. Client DatagramSocket null");
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);
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);
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);
198 logger.debug("Discovered from cloud, but ignored because not online: {} {}", id, device);
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) + ")";
211 boolean isOnline = false;
212 if (ip.equals(cloudDevices.get(id))) {
213 logger.debug("Skipped adding local found {}. Already discovered by cloud.", label);
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();
227 submitDiscovery(ip, token, id, label, country, isOnline);
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);
237 "No token discovered for device {}. For options how to get the token, check the binding readme.",
239 dr = dr.withRepresentationProperty(PROPERTY_DID).withLabel(label);
241 logger.debug("Discovered Mi Device {} ({}) at {} as {} with token {}", id, Utils.fromHEX(id), ip, uid,
243 dr = dr.withProperty(PROPERTY_TOKEN, token).withRepresentationProperty(PROPERTY_DID)
244 .withLabel(label + " with token");
246 if (!country.isEmpty() && isOnline) {
247 dr = dr.withProperty(PROPERTY_CLOUDSERVER, country);
249 thingDiscovered(dr.build());
252 synchronized @Nullable DatagramSocket getSocket() {
253 DatagramSocket clientSocket = this.clientSocket;
254 if (clientSocket != null && clientSocket.isBound()) {
258 logger.debug("Getting new socket for discovery");
259 clientSocket = new DatagramSocket();
260 clientSocket.setReuseAddress(true);
261 clientSocket.setBroadcast(true);
262 this.clientSocket = clientSocket;
264 } catch (SocketException | SecurityException e) {
265 logger.debug("Error getting socket for discovery: {}", e.getMessage());
270 private void closeSocket() {
271 final @Nullable DatagramSocket clientSocket = this.clientSocket;
272 if (clientSocket != null) {
273 clientSocket.close();
277 this.clientSocket = null;
280 private void sendDiscoveryRequest(String ipAddress) {
281 final @Nullable DatagramSocket socket = getSocket();
282 if (socket != null) {
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);
292 } catch (IOException e) {
293 logger.trace("Discovery on {} error: {}", ipAddress, e.getMessage());
299 * starts the {@link ReceiverThread} thread
301 private synchronized void startReceiverThreat() {
302 final Thread srt = socketReceiveThread;
304 if (srt.isAlive() && !srt.isInterrupted()) {
308 stopReceiverThreat();
309 Thread socketReceiveThread = new ReceiverThread();
310 socketReceiveThread.start();
311 this.socketReceiveThread = socketReceiveThread;
315 * Stops the {@link ReceiverThread} thread
317 private synchronized void stopReceiverThreat() {
318 if (socketReceiveThread != null) {
319 socketReceiveThread.interrupt();
320 socketReceiveThread = null;
326 * The thread, which waits for data and submits the unique results addresses to the discovery results
329 private class ReceiverThread extends Thread {
332 DatagramSocket socket = getSocket();
333 if (socket != null) {
334 logger.debug("Starting discovery receiver thread for socket on port {}", socket.getLocalPort());
340 * This method waits for data and submits the unique results addresses to the discovery results
342 * @param socket - The multicast socket to (re)use
344 private void receiveData(DatagramSocket socket) {
345 DatagramPacket receivePacket = new DatagramPacket(new byte[BUFFER_LENGTH], BUFFER_LENGTH);
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());
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());
361 if (!responseIps.contains(hostAddress)) {
362 scheduler.schedule(() -> {
364 discovered(hostAddress, messageBuf);
365 } catch (Exception e) {
366 logger.debug("Error submitting discovered Mi IO device at {}", hostAddress, e);
368 }, 0, TimeUnit.SECONDS);
370 responseIps.add(hostAddress);
372 } catch (SocketException e) {
373 logger.debug("Receiver thread received SocketException: {}", e.getMessage());
374 } catch (IOException e) {
375 logger.trace("Receiver thread was interrupted");
377 logger.debug("Receiver thread ended");