Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Unverified Commit fc9af953 authored by Simon Chan's avatar Simon Chan
Browse files

feat(adb): add AdbServerClient.trackDevices

parent 1f162ad3
Loading
Loading
Loading
Loading
+75 −47
Original line number Diff line number Diff line
@@ -27,7 +27,7 @@ import {
import type { AdbIncomingSocketHandler, AdbSocket, Closeable } from "../adb.js";
import { AdbBanner } from "../banner.js";
import type { AdbFeature } from "../features.js";
import { NOOP, hexToNumber, numberToHex } from "../utils/index.js";
import { NOOP, hexToNumber, numberToHex, unreachable } from "../utils/index.js";

import { AdbServerTransport } from "./transport.js";

@@ -214,13 +214,9 @@ export class AdbServerClient {
        }
    }

    async getDevices(): Promise<AdbServerDevice[]> {
        const connection = await this.connect("host:devices-l");
        const readable = new BufferedReadableStream(connection.readable);
        try {
    parseDeviceList(value: string): AdbServerDevice[] {
        const devices: AdbServerDevice[] = [];
            const response = await AdbServerClient.readString(readable);
            for (const line of response.split("\n")) {
        for (const line of value.split("\n")) {
            if (!line) {
                continue;
            }
@@ -265,12 +261,44 @@ export class AdbServerClient {
            });
        }
        return devices;
    }

    async getDevices(): Promise<AdbServerDevice[]> {
        const connection = await this.connect("host:devices-l");
        const readable = new BufferedReadableStream(connection.readable);
        try {
            const response = await AdbServerClient.readString(readable);
            return this.parseDeviceList(response);
        } finally {
            connection.writable.close().catch(NOOP);
            readable.cancel().catch(NOOP);
        }
    }

    async trackDevices(
        callback: (devices: AdbServerDevice[]) => void,
    ): Promise<() => void> {
        const connection = await this.connect("host:track-devices-l");
        const readable = new BufferedReadableStream(connection.readable);
        let running = true;
        (async () => {
            try {
                while (running) {
                    const response = await AdbServerClient.readString(readable);
                    const devices = this.parseDeviceList(response);
                    callback(devices);
                }
            } catch {
                // ignore
            }
        })().catch(unreachable);
        return () => {
            running = false;
            readable.cancel().catch(NOOP);
            Promise.resolve(connection.close()).catch(NOOP);
        };
    }

    formatDeviceService(device: AdbServerDeviceSelector, command: string) {
        if (!device) {
            return `host:${command}`;