]> git.basschouten.com Git - openhab-addons.git/blob
a4ff9e13d4e7440a6ede702df5c2f9f3042e9869
[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.androiddebugbridge.internal.discovery;
14
15 import static org.openhab.binding.androiddebugbridge.internal.AndroidDebugBridgeBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.Inet4Address;
19 import java.net.InetAddress;
20 import java.net.NetworkInterface;
21 import java.net.SocketException;
22 import java.util.Collections;
23 import java.util.Dictionary;
24 import java.util.Enumeration;
25 import java.util.Map;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.TimeoutException;
28 import java.util.function.Function;
29 import java.util.stream.Collectors;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.androiddebugbridge.internal.AndroidDebugBridgeBindingConfiguration;
34 import org.openhab.binding.androiddebugbridge.internal.AndroidDebugBridgeDevice;
35 import org.openhab.binding.androiddebugbridge.internal.AndroidDebugBridgeDeviceException;
36 import org.openhab.binding.androiddebugbridge.internal.AndroidDebugBridgeDeviceReadException;
37 import org.openhab.core.config.discovery.AbstractDiscoveryService;
38 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
39 import org.openhab.core.config.discovery.DiscoveryService;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingUID;
42 import org.osgi.service.cm.Configuration;
43 import org.osgi.service.cm.ConfigurationAdmin;
44 import org.osgi.service.component.annotations.Activate;
45 import org.osgi.service.component.annotations.Component;
46 import org.osgi.service.component.annotations.Reference;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * The {@link AndroidDebugBridgeDiscoveryService} discover Android ADB Instances in the network.
52  *
53  * @author Miguel Alvarez - Initial contribution
54  */
55 @NonNullByDefault
56 @Component(service = DiscoveryService.class, configurationPid = "discovery.androiddebugbridge")
57 public class AndroidDebugBridgeDiscoveryService extends AbstractDiscoveryService {
58
59     static final int TIMEOUT_MS = 60000;
60     private static final long DISCOVERY_RESULT_TTL_SEC = 300;
61     public static final String LOCAL_INTERFACE_IP = "127.0.0.1";
62     public static final int MAX_RETRIES = 2;
63     private final Logger logger = LoggerFactory.getLogger(AndroidDebugBridgeDiscoveryService.class);
64     private final ConfigurationAdmin admin;
65     private boolean discoveryRunning = false;
66
67     @Activate
68     public AndroidDebugBridgeDiscoveryService(final @Reference ConfigurationAdmin admin) {
69         super(SUPPORTED_THING_TYPES, TIMEOUT_MS, false);
70         this.admin = admin;
71     }
72
73     @Override
74     protected void startScan() {
75         logger.debug("scan started: searching android devices");
76         discoveryRunning = true;
77         Enumeration<NetworkInterface> nets;
78         AndroidDebugBridgeBindingConfiguration configuration = getConfig();
79         if (configuration == null) {
80             return;
81         }
82         try {
83             nets = NetworkInterface.getNetworkInterfaces();
84             for (NetworkInterface netint : Collections.list(nets)) {
85                 Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
86                 for (InetAddress inetAddress : Collections.list(inetAddresses)) {
87                     if (!discoveryRunning) {
88                         break;
89                     }
90                     if (!(inetAddress instanceof Inet4Address)
91                             || inetAddress.getHostAddress().equals(LOCAL_INTERFACE_IP)) {
92                         continue;
93                     }
94                     String[] ipParts = inetAddress.getHostAddress().split("\\.");
95                     for (int i = configuration.discoveryIpRangeMin; i <= configuration.discoveryIpRangeMax; i++) {
96                         if (!discoveryRunning) {
97                             break;
98                         }
99                         ipParts[3] = Integer.toString(i);
100                         String currentIp = String.join(".", ipParts);
101                         try {
102                             var currentAddress = InetAddress.getByName(currentIp);
103                             logger.debug("address: {}", currentIp);
104                             if (currentAddress.isReachable(configuration.discoveryReachableMs)) {
105                                 logger.debug("Reachable ip: {}", currentIp);
106                                 int retries = 0;
107                                 while (retries < MAX_RETRIES) {
108                                     try {
109                                         discoverWithADB(currentIp, configuration.discoveryPort,
110                                                 new String(netint.getHardwareAddress()).toLowerCase());
111                                     } catch (AndroidDebugBridgeDeviceReadException | TimeoutException e) {
112                                         retries++;
113                                         if (retries < MAX_RETRIES) {
114                                             logger.debug("retrying - pending {}", MAX_RETRIES - retries);
115                                             continue;
116                                         }
117                                         throw e;
118                                     }
119                                     break;
120                                 }
121                             }
122                         } catch (IOException | AndroidDebugBridgeDeviceException | AndroidDebugBridgeDeviceReadException
123                                 | TimeoutException | ExecutionException e) {
124                             logger.debug("Error connecting to device at {}: {}", currentIp, e.getMessage());
125                         }
126                     }
127                 }
128             }
129         } catch (SocketException | InterruptedException e) {
130             logger.warn("Error while discovering: {}", e.getMessage());
131         }
132     }
133
134     private void discoverWithADB(String ip, int port, String macAddress)
135             throws InterruptedException, AndroidDebugBridgeDeviceException, AndroidDebugBridgeDeviceReadException,
136             TimeoutException, ExecutionException {
137         var device = new AndroidDebugBridgeDevice(scheduler);
138         device.configureConnection(ip, port, 10);
139         try {
140             device.connect();
141             logger.debug("connected adb at {}:{}", ip, port);
142             String serialNo = device.getSerialNo();
143             String model = device.getModel();
144             String androidVersion = device.getAndroidVersion();
145             String brand = device.getBrand();
146             logger.debug("discovered: {} - {} - {} - {} - {}", model, serialNo, androidVersion, brand, macAddress);
147             onDiscoverResult(serialNo, ip, port, model, androidVersion, brand, macAddress);
148         } finally {
149             device.disconnect();
150         }
151     }
152
153     @Override
154     protected void stopScan() {
155         super.stopScan();
156         discoveryRunning = false;
157         logger.debug("scan stopped");
158     }
159
160     private void onDiscoverResult(String serialNo, String ip, int port, String model, String androidVersion,
161             String brand, String macAddress) {
162         String friendlyName = String.format("%s (%s)", model, ip);
163         thingDiscovered(
164                 DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replace(":", ""))) //
165                         .withProperties(Map.of( //
166                                 PARAMETER_IP, ip, //
167                                 PARAMETER_PORT, port, //
168                                 Thing.PROPERTY_MAC_ADDRESS, macAddress, //
169                                 Thing.PROPERTY_SERIAL_NUMBER, serialNo, //
170                                 Thing.PROPERTY_MODEL_ID, model, //
171                                 Thing.PROPERTY_VENDOR, brand, //
172                                 Thing.PROPERTY_FIRMWARE_VERSION, androidVersion //
173                         )) //
174                         .withLabel(friendlyName) //
175                         .withRepresentationProperty(Thing.PROPERTY_MAC_ADDRESS) //
176                         .withTTL(DISCOVERY_RESULT_TTL_SEC) //
177                         .build());
178     }
179
180     private @Nullable AndroidDebugBridgeBindingConfiguration getConfig() {
181         try {
182             Configuration configOnline = admin.getConfiguration(BINDING_CONFIGURATION_PID, null);
183             if (configOnline != null) {
184                 Dictionary<String, Object> props = configOnline.getProperties();
185                 if (props != null) {
186                     Map<String, Object> propMap = Collections.list(props.keys()).stream()
187                             .collect(Collectors.toMap(Function.identity(), props::get));
188                     return new org.openhab.core.config.core.Configuration(propMap)
189                             .as(AndroidDebugBridgeBindingConfiguration.class);
190                 }
191             }
192         } catch (IOException e) {
193             logger.warn("Unable to read configuration: {}", e.getMessage());
194         }
195         return null;
196     }
197 }