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 NetworkError
. You can catch it and show a message to the user to ask them to close the conflicting program.
- JavaScript
- TypeScript
function connect(device) {
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;
}
}
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;
}
}
Next Step