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:
- Call WebUSB
USBDevice#open
method to open the device - Call WebUSB
USBDevice#claimInterface
method to claim the ADB interface - 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.
- JavaScript
- TypeScript
const connection = await device.connect();
export {};
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 DeviceBusyError
. You can catch it and show a message to the user to ask them to close the conflicting program.
- JavaScript
- TypeScript
import { AdbDaemonWebUsbDevice } from "@yume-chan/adb-daemon-webusb";
function connect(device) {
try {
return await device.connect();
} catch (error) {
if (error instanceof AdbDaemonWebUsbDevice.DeviceBusyError) {
alert(
"The device is already in use by another program. Please close the program and try again.",
);
}
// It might also throw other errors
throw error;
}
}
import { AdbDaemonWebUsbDevice } from "@yume-chan/adb-daemon-webusb";
function connect(device: AdbDaemonWebUsbDevice) {
try {
return await device.connect();
} catch (error) {
if (error instanceof AdbDaemonWebUsbDevice.DeviceBusyError) {
alert(
"The device is already in use by another program. Please close the program and try again.",
);
}
// It might also throw other errors
throw error;
}
}
Next Step