]> git.basschouten.com Git - openhab-addons.git/blob
8778fcfbbec420ec4a8c937707ca4fad60fe2e23
[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.androiddebugbridge.internal;
14
15 import java.io.*;
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;
28
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;
34
35 import com.tananaev.adblib.AdbBase64;
36 import com.tananaev.adblib.AdbConnection;
37 import com.tananaev.adblib.AdbCrypto;
38 import com.tananaev.adblib.AdbStream;
39
40 /**
41  * The {@link AndroidDebugBridgeConfiguration} class encapsulates adb device connection logic.
42  *
43  * @author Miguel Álvarez - Initial contribution
44  */
45 @NonNullByDefault
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.*)]");
52
53     private static @Nullable AdbCrypto adbCrypto;
54
55     static {
56         var logger = LoggerFactory.getLogger(AndroidDebugBridgeDevice.class);
57         try {
58             File directory = new File(ADB_FOLDER);
59             if (!directory.exists()) {
60                 directory.mkdir();
61             }
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());
66         }
67     }
68
69     private final ScheduledExecutorService scheduler;
70
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;
77
78     AndroidDebugBridgeDevice(ScheduledExecutorService scheduler) {
79         this.scheduler = scheduler;
80     }
81
82     public void configure(String ip, int port, int timeout) {
83         this.ip = ip;
84         this.port = port;
85         this.timeoutSec = timeout;
86     }
87
88     public void sendKeyEvent(String eventCode)
89             throws InterruptedException, AndroidDebugBridgeDeviceException, TimeoutException, ExecutionException {
90         runAdbShell("input", "keyevent", eventCode);
91     }
92
93     public void sendText(String text)
94             throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
95         runAdbShell("input", "text", URLEncoder.encode(text, StandardCharsets.UTF_8));
96     }
97
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");
103     }
104
105     public void stopPackage(String packageName)
106             throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
107         runAdbShell("am", "force-stop", packageName);
108     }
109
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];
119         }
120         throw new AndroidDebugBridgeDeviceReadException("can read package name");
121     }
122
123     public boolean isScreenOn() throws InterruptedException, AndroidDebugBridgeDeviceException,
124             AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
125         String devicesResp = runAdbShell("dumpsys", "power", "|", "grep", "'Display Power'");
126         if (devicesResp.contains("=")) {
127             try {
128                 return devicesResp.split("=")[1].equals("ON");
129             } catch (NumberFormatException e) {
130                 logger.debug("Unable to parse device wake lock: {}", e.getMessage());
131             }
132         }
133         throw new AndroidDebugBridgeDeviceReadException("can read screen state");
134     }
135
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
143             return false;
144         }
145         boolean isPlaying = mediaSessions[0].contains("PlaybackState {state=3");
146         logger.debug("device media state playing {}", isPlaying);
147         return isPlaying;
148     }
149
150     public boolean isPlayingAudio()
151             throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
152         String audioDump = runAdbShell("dumpsys", "audio", "|", "grep", "ID:");
153         return audioDump.contains("state:started");
154     }
155
156     public VolumeInfo getMediaVolume() throws AndroidDebugBridgeDeviceException, InterruptedException,
157             AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
158         return getVolume(ANDROID_MEDIA_STREAM);
159     }
160
161     public void setMediaVolume(int volume)
162             throws AndroidDebugBridgeDeviceException, InterruptedException, TimeoutException, ExecutionException {
163         setVolume(ANDROID_MEDIA_STREAM, volume);
164     }
165
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("=")) {
170             try {
171                 return Integer.parseInt(lockResp.replace("\n", "").split("=")[1]);
172             } catch (NumberFormatException e) {
173                 logger.debug("Unable to parse device wake lock: {}", e.getMessage());
174             }
175         }
176         throw new AndroidDebugBridgeDeviceReadException("can read wake lock");
177     }
178
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));
182     }
183
184     public String getModel() throws AndroidDebugBridgeDeviceException, InterruptedException,
185             AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
186         return getDeviceProp("ro.product.model");
187     }
188
189     public String getAndroidVersion() throws AndroidDebugBridgeDeviceException, InterruptedException,
190             AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
191         return getDeviceProp("ro.build.version.release");
192     }
193
194     public String getBrand() throws AndroidDebugBridgeDeviceException, InterruptedException,
195             AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
196         return getDeviceProp("ro.product.brand");
197     }
198
199     public String getSerialNo() throws AndroidDebugBridgeDeviceException, InterruptedException,
200             AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
201         return getDeviceProp("ro.serialno");
202     }
203
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");
209         }
210         return propValue;
211     }
212
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", "|",
216                 "grep", "volume");
217         Matcher matcher = VOLUME_PATTERN.matcher(volumeResp);
218         if (!matcher.find())
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);
224         return volumeInfo;
225     }
226
227     public boolean isConnected() {
228         var currentSocket = socket;
229         return currentSocket != null && currentSocket.isConnected();
230     }
231
232     public void connect() throws AndroidDebugBridgeDeviceException, InterruptedException {
233         this.disconnect();
234         AdbConnection adbConnection;
235         Socket sock;
236         AdbCrypto crypto = adbCrypto;
237         if (crypto == null) {
238             throw new AndroidDebugBridgeDeviceException("Device not connected");
239         }
240         try {
241             sock = new Socket();
242             socket = sock;
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();
249             }
250             throw new AndroidDebugBridgeDeviceException("Can not open socket " + ip + ":" + port);
251         }
252         try {
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);
259         }
260     }
261
262     private String runAdbShell(String... args)
263             throws InterruptedException, AndroidDebugBridgeDeviceException, TimeoutException, ExecutionException {
264         var adb = connection;
265         if (adb == null) {
266             throw new AndroidDebugBridgeDeviceException("Device not connected");
267         }
268         var commandFuture = scheduler.submit(() -> {
269             var byteArrayOutputStream = new ByteArrayOutputStream();
270             String cmd = String.join(" ", args);
271             logger.debug("{} - shell:{}", ip, cmd);
272             try {
273                 AdbStream stream = adb.open("shell:" + cmd);
274                 do {
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")) {
280                     throw e;
281                 }
282             }
283             return byteArrayOutputStream.toString(StandardCharsets.US_ASCII);
284         });
285         this.commandFuture = commandFuture;
286         return commandFuture.get(timeoutSec, TimeUnit.SECONDS);
287     }
288
289     private static AdbBase64 getBase64Impl() {
290         Charset asciiCharset = Charset.forName("ASCII");
291         return bytes -> new String(Base64.getEncoder().encode(bytes), asciiCharset);
292     }
293
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);
298         AdbCrypto c = null;
299         // load key pair
300         if (pub.exists() && priv.exists()) {
301             try {
302                 c = AdbCrypto.loadAdbKeyPair(getBase64Impl(), priv, pub);
303             } catch (IOException ignored) {
304                 // Keys don't exits
305             }
306         }
307         if (c == null) {
308             // generate key pair
309             c = AdbCrypto.generateAdbKeyPair(getBase64Impl());
310             c.saveAdbKeyPair(priv, pub);
311         }
312         return c;
313     }
314
315     public void disconnect() {
316         var commandFuture = this.commandFuture;
317         if (commandFuture != null && !commandFuture.isDone()) {
318             commandFuture.cancel(true);
319         }
320         var adb = connection;
321         var sock = socket;
322         if (adb != null) {
323             try {
324                 adb.close();
325             } catch (IOException ignored) {
326             }
327             connection = null;
328         }
329         if (sock != null) {
330             try {
331                 sock.close();
332             } catch (IOException ignored) {
333             }
334             socket = null;
335         }
336     }
337
338     public static class VolumeInfo {
339         public int current;
340         public int min;
341         public int max;
342
343         VolumeInfo(int current, int min, int max) {
344             this.current = current;
345             this.min = min;
346             this.max = max;
347         }
348     }
349 }