2 * Copyright (c) 2010-2021 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.androiddebugbridge.internal;
16 import java.net.InetSocketAddress;
17 import java.net.Socket;
18 import java.net.URLEncoder;
19 import java.nio.charset.Charset;
20 import java.nio.charset.StandardCharsets;
21 import java.security.NoSuchAlgorithmException;
22 import java.security.spec.InvalidKeySpecException;
23 import java.util.Arrays;
24 import java.util.Base64;
25 import java.util.concurrent.*;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.core.OpenHAB;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
35 import com.tananaev.adblib.AdbBase64;
36 import com.tananaev.adblib.AdbConnection;
37 import com.tananaev.adblib.AdbCrypto;
38 import com.tananaev.adblib.AdbStream;
41 * The {@link AndroidDebugBridgeConfiguration} class encapsulates adb device connection logic.
43 * @author Miguel Álvarez - Initial contribution
46 public class AndroidDebugBridgeDevice {
47 public static final int ANDROID_MEDIA_STREAM = 3;
48 private static final String ADB_FOLDER = OpenHAB.getUserDataFolder() + File.separator + ".adb";
49 private final Logger logger = LoggerFactory.getLogger(AndroidDebugBridgeDevice.class);
50 private static final Pattern VOLUME_PATTERN = Pattern
51 .compile("volume is (?<current>\\d.*) in range \\[(?<min>\\d.*)\\.\\.(?<max>\\d.*)]");
53 private static @Nullable AdbCrypto adbCrypto;
56 var logger = LoggerFactory.getLogger(AndroidDebugBridgeDevice.class);
58 File directory = new File(ADB_FOLDER);
59 if (!directory.exists()) {
62 adbCrypto = loadKeyPair(ADB_FOLDER + File.separator + "adb_pub.key",
63 ADB_FOLDER + File.separator + "adb.key");
64 } catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
65 logger.warn("Unable to setup adb keys: {}", e.getMessage());
69 private final ScheduledExecutorService scheduler;
71 private String ip = "127.0.0.1";
72 private int port = 5555;
73 private int timeoutSec = 5;
74 private @Nullable Socket socket;
75 private @Nullable AdbConnection connection;
76 private @Nullable Future<String> commandFuture;
78 AndroidDebugBridgeDevice(ScheduledExecutorService scheduler) {
79 this.scheduler = scheduler;
82 public void configure(String ip, int port, int timeout) {
85 this.timeoutSec = timeout;
88 public void sendKeyEvent(String eventCode)
89 throws InterruptedException, AndroidDebugBridgeDeviceException, TimeoutException, ExecutionException {
90 runAdbShell("input", "keyevent", eventCode);
93 public void sendText(String text)
94 throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
95 runAdbShell("input", "text", URLEncoder.encode(text, StandardCharsets.UTF_8));
98 public void startPackage(String packageName)
99 throws InterruptedException, AndroidDebugBridgeDeviceException, TimeoutException, ExecutionException {
100 var out = runAdbShell("monkey", "--pct-syskeys", "0", "-p", packageName, "-v", "1");
101 if (out.contains("monkey aborted"))
102 throw new AndroidDebugBridgeDeviceException("Unable to open package");
105 public void stopPackage(String packageName)
106 throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
107 runAdbShell("am", "force-stop", packageName);
110 public String getCurrentPackage() throws AndroidDebugBridgeDeviceException, InterruptedException,
111 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
112 var out = runAdbShell("dumpsys", "window", "windows", "|", "grep", "mFocusedApp");
113 var targetLine = Arrays.stream(out.split("\n")).findFirst().orElse("");
114 var lineParts = targetLine.split(" ");
115 if (lineParts.length >= 2) {
116 var packageActivityName = lineParts[lineParts.length - 2];
117 if (packageActivityName.contains("/"))
118 return packageActivityName.split("/")[0];
120 throw new AndroidDebugBridgeDeviceReadException("can read package name");
123 public boolean isScreenOn() throws InterruptedException, AndroidDebugBridgeDeviceException,
124 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
125 String devicesResp = runAdbShell("dumpsys", "power", "|", "grep", "'Display Power'");
126 if (devicesResp.contains("=")) {
128 return devicesResp.split("=")[1].equals("ON");
129 } catch (NumberFormatException e) {
130 logger.debug("Unable to parse device wake lock: {}", e.getMessage());
133 throw new AndroidDebugBridgeDeviceReadException("can read screen state");
136 public boolean isPlayingMedia(String currentApp)
137 throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
138 String devicesResp = runAdbShell("dumpsys", "media_session", "|", "grep", "-A", "100", "'Sessions Stack'", "|",
139 "grep", "-A", "50", currentApp);
140 String[] mediaSessions = devicesResp.split("\n\n");
141 if (mediaSessions.length == 0) {
142 // no media session found for current app
145 boolean isPlaying = mediaSessions[0].contains("PlaybackState {state=3");
146 logger.debug("device media state playing {}", isPlaying);
150 public boolean isPlayingAudio()
151 throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
152 String audioDump = runAdbShell("dumpsys", "audio", "|", "grep", "ID:");
153 return audioDump.contains("state:started");
156 public VolumeInfo getMediaVolume() throws AndroidDebugBridgeDeviceException, InterruptedException,
157 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
158 return getVolume(ANDROID_MEDIA_STREAM);
161 public void setMediaVolume(int volume)
162 throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
163 setVolume(ANDROID_MEDIA_STREAM, volume);
166 public int getPowerWakeLock() throws InterruptedException, AndroidDebugBridgeDeviceException,
167 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
168 String lockResp = runAdbShell("dumpsys", "power", "|", "grep", "Locks", "|", "grep", "'size='");
169 if (lockResp.contains("=")) {
171 return Integer.parseInt(lockResp.replace("\n", "").split("=")[1]);
172 } catch (NumberFormatException e) {
173 logger.debug("Unable to parse device wake lock: {}", e.getMessage());
176 throw new AndroidDebugBridgeDeviceReadException("can read wake lock");
179 private void setVolume(int stream, int volume)
180 throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
181 runAdbShell("media", "volume", "--show", "--stream", String.valueOf(stream), "--set", String.valueOf(volume));
184 public String getModel() throws AndroidDebugBridgeDeviceException, InterruptedException,
185 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
186 return getDeviceProp("ro.product.model");
189 public String getAndroidVersion() throws AndroidDebugBridgeDeviceException, InterruptedException,
190 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
191 return getDeviceProp("ro.build.version.release");
194 public String getBrand() throws AndroidDebugBridgeDeviceException, InterruptedException,
195 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
196 return getDeviceProp("ro.product.brand");
199 public String getSerialNo() throws AndroidDebugBridgeDeviceException, InterruptedException,
200 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
201 return getDeviceProp("ro.serialno");
204 private String getDeviceProp(String name) throws AndroidDebugBridgeDeviceException, InterruptedException,
205 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
206 var propValue = runAdbShell("getprop", name, "&&", "sleep", "0.3").replace("\n", "").replace("\r", "");
207 if (propValue.length() == 0) {
208 throw new AndroidDebugBridgeDeviceReadException("Unable to get device property");
213 private VolumeInfo getVolume(int stream) throws AndroidDebugBridgeDeviceException, InterruptedException,
214 AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
215 String volumeResp = runAdbShell("media", "volume", "--show", "--stream", String.valueOf(stream), "--get", "|",
217 Matcher matcher = VOLUME_PATTERN.matcher(volumeResp);
219 throw new AndroidDebugBridgeDeviceReadException("Unable to get volume info");
220 var volumeInfo = new VolumeInfo(Integer.parseInt(matcher.group("current")),
221 Integer.parseInt(matcher.group("min")), Integer.parseInt(matcher.group("max")));
222 logger.debug("Device {}:{} VolumeInfo: current {}, min {}, max {}", this.ip, this.port, volumeInfo.current,
223 volumeInfo.min, volumeInfo.max);
227 public boolean isConnected() {
228 var currentSocket = socket;
229 return currentSocket != null && currentSocket.isConnected();
232 public void connect() throws AndroidDebugBridgeDeviceException, InterruptedException {
234 AdbConnection adbConnection;
236 AdbCrypto crypto = adbCrypto;
237 if (crypto == null) {
238 throw new AndroidDebugBridgeDeviceException("Device not connected");
243 sock.connect(new InetSocketAddress(ip, port), (int) TimeUnit.SECONDS.toMillis(15));
244 } catch (IOException e) {
245 logger.debug("Error connecting to {}: [{}] {}", ip, e.getClass().getName(), e.getMessage());
246 if (e.getMessage().equals("Socket closed")) {
247 // Connection aborted by us
248 throw new InterruptedException();
250 throw new AndroidDebugBridgeDeviceException("Can not open socket " + ip + ":" + port);
253 adbConnection = AdbConnection.create(sock, crypto);
254 connection = adbConnection;
255 adbConnection.connect(15, TimeUnit.SECONDS, false);
256 } catch (IOException e) {
257 logger.debug("Error connecting to {}: {}", ip, e.getMessage());
258 throw new AndroidDebugBridgeDeviceException("Can not open adb connection " + ip + ":" + port);
262 private String runAdbShell(String... args)
263 throws InterruptedException, AndroidDebugBridgeDeviceException, TimeoutException, ExecutionException {
264 var adb = connection;
266 throw new AndroidDebugBridgeDeviceException("Device not connected");
268 var commandFuture = scheduler.submit(() -> {
269 var byteArrayOutputStream = new ByteArrayOutputStream();
270 String cmd = String.join(" ", args);
271 logger.debug("{} - shell:{}", ip, cmd);
273 AdbStream stream = adb.open("shell:" + cmd);
275 byteArrayOutputStream.writeBytes(stream.read());
276 } while (!stream.isClosed());
277 } catch (IOException e) {
278 String message = e.getMessage();
279 if (message != null && !message.equals("Stream closed")) {
283 return byteArrayOutputStream.toString(StandardCharsets.US_ASCII);
285 this.commandFuture = commandFuture;
286 return commandFuture.get(timeoutSec, TimeUnit.SECONDS);
289 private static AdbBase64 getBase64Impl() {
290 Charset asciiCharset = Charset.forName("ASCII");
291 return bytes -> new String(Base64.getEncoder().encode(bytes), asciiCharset);
294 private static AdbCrypto loadKeyPair(String pubKeyFile, String privKeyFile)
295 throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
296 File pub = new File(pubKeyFile);
297 File priv = new File(privKeyFile);
300 if (pub.exists() && priv.exists()) {
302 c = AdbCrypto.loadAdbKeyPair(getBase64Impl(), priv, pub);
303 } catch (IOException ignored) {
309 c = AdbCrypto.generateAdbKeyPair(getBase64Impl());
310 c.saveAdbKeyPair(priv, pub);
315 public void disconnect() {
316 var commandFuture = this.commandFuture;
317 if (commandFuture != null && !commandFuture.isDone()) {
318 commandFuture.cancel(true);
320 var adb = connection;
325 } catch (IOException ignored) {
332 } catch (IOException ignored) {
338 public static class VolumeInfo {
343 VolumeInfo(int current, int min, int max) {
344 this.current = current;