Skip to main content

Create connection

As explained before, each USB device can have multiple interfaces for different functions, and each interface needs to be exclusively claimed by programs.

Requesting permission to access a device doesn't automatically claim its interfaces. The connect method does that, but not only that. It includes three steps to simplify the usage:

  1. Call WebUSB USBDevice#open method to open the device
  2. Call WebUSB USBDevice#claimInterface method to claim the ADB interface
  3. Find the endpoints for the ADB interface and create streams for them

It returns a pair of streams, one for sending and one for receiving ADB packets.

import type { AdbPacketData, AdbPacketInit } from "@yume-chan/adb";
import type { Consumable, ReadableWritablePair } from "@yume-chan/stream-extra";

const connection: ReadableWritablePair<
AdbPacketData,
Consumable<AdbPacketInit>
> = await device.connect();

If the interface is already claimed by another program (or another USBDevice instance), connect will throw an NetworkError. You can catch it and show a message to the user to ask them to close the conflicting program.

function connect(device: AdbDaemonWebUsbDevice) {
try {
return await device.connect();
} catch (error) {
// `usb` package for Node.js doesn't throw a real `DOMException`
// This check is compatible with both Chrome and `usb` package
if (
typeof error === "object" &&
error !== null &&
"name" in error &&
error.name === "NetworkError"
) {
alert(
"The device is already in use by another program. Please close the program and try again.",
);
}
throw error;
}
}