# WebUSBBridge **Repository Path**: mini-tiger/webusb_bridge ## Basic Information - **Project Name**: WebUSBBridge - **Description**: 鸿蒙系统webusb功能的本地化桥接实现 - **Primary Language**: TypeScript - **License**: GPL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-07-13 - **Last Updated**: 2025-07-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # WebUSBBridge for OpenHarmony ## Overview WebUSBBridge is a bridge library that implements the WebUSB API on OpenHarmony systems, allowing web applications to interact with local USB devices through the WebUSB API. ## Features 1. **Complete WebUSB API Implementation**: - Device enumeration and selection - Device connect/disconnect event monitoring - Interface claiming and releasing - Bulk and control transfers - Endpoint halt clearing 2. **Device Management**: - Device permission requests - Configuration selection - Alternate interface setting selection - Device forgetting functionality 3. **Data Transfer Optimization**: - Large file chunked transfer - Transfer buffer management - Asynchronous message queue 4. **UI Integration**: - Device selection dialog - Permission prompts - Error handling ## Installation 1. Prerequisites - OphenHarmony SDK 5.0.5+ API Level 17+ - DevEco Studio(Latest version recommended) - ohpm package manager(Bundled with DevEco Studio) 2. Install via ohpm ```Bash ohpm install webusb_bridge ``` 3. Manual Installation(Optional) - If ohpm is not not available, download the .har package and add it to your project's libs folder, then configure in oh-package.json5: ``` "dependencies": { "webusb_bridge": "file:./libs/webusb_bridge.har" } ``` ## Integration ### 1. Include in OpenHarmony Application ```arkts import { webview } from '@kit.ArkWeb'; import { WebUSBBridge } from "webusb_bridge" const HOMEPAGE = "https://your-web-app.com"; @Entry @Component struct Index { private controller: WebviewController = new webview.WebviewController(); private bridge: WebUSBBridge = new WebUSBBridge(this.controller, this.getUIContext()); aboutToAppear(): void { webview.WebviewController.setWebDebuggingAccess(true); } aboutToDisappear() { this.bridge.destroy(); } build() { Stack() { Web({ src: HOMEPAGE, controller: this.controller }) .onControllerAttached(async () => { this.bridge.attachToWebview(); }) .runJavaScriptOnDocumentStart(this.bridge.getScripts()) .onPageBegin(_ => this.bridge.cleanup()) .width("100%") .height("100%"); } } } ``` ### 2. Usage in Web Application ```javascript // Request USB device const device = await navigator.usb.requestDevice({ filters: [{ vendorId: 0x1234 }] }); // Open device await device.open(); // Claim interface await device.claimInterface(0); // Transfer data const result = await device.transferIn(1, 64); console.log(new Uint8Array(result.data.buffer)); ``` ## API Reference ### Core Methods | Method | Description | |--------|-------------| | `attachToWebview()` | Attaches WebUSB functionality to Webview | | `getScripts()` | Gets WebUSB JavaScript scripts to inject | | `cleanup()` | Cleans up USB device resources | | `destroy()` | Completely destroys bridge instance | ### WebUSB API | API | Description | |--------|-------------| | `open()` | Opens the USB device | | `close()` | Closes the USB device | | `selectConfiguration(configurationValue)` | Selects a device configuration | | `claimInterface(interfaceNumber)` | Claims a USB interface | | `releaseInterface(interfaceNumber)` | Releases a claimed USB interface | | `selectAlternateInterface(interfaceNumber, alternateSetting)` | Selects an alternate interface setting | | `controlTransferIn(setup, length)` | Performs a control transfer from the device | | `controlTransferOut(setup, data)` | Performs a control transfer to the device | | `transferIn(endpointNumber, length)` | Performs a bulk or interrupt transfer from the device | | `transferOut(endpointNumber, data)` | Performs a bulk or interrupt transfer to the device | | `clearHalt(direction, endpointNumber)` | Clears a halt/stall condition on an endpoint | | `forget()` | Releases the device and forgets permission | #### USB Object Additional Methods | Method | Description | |--------|-------------| | `setTransferThreshold(size)` | Sets the threshold for using message ports for large transfers | ## Examples ### Read Device Descriptor ```javascript async function readDeviceDescriptor(device) { await device.open(); const result = await device.controlTransferIn({ requestType: 'standard', recipient: 'device', request: 0x06, value: 0x0100, index: 0x00 }, 18); const data = new DataView(result.data.buffer); console.log('Device descriptor:', data); } ``` ### Bulk Data Transfer ```javascript async function bulkTransferExample(device) { await device.open(); await device.selectConfiguration(1); await device.claimInterface(0); // Send data const data = new Uint8Array([0x01, 0x02, 0x03]); await device.transferOut(1, data); // Receive data const result = await device.transferIn(2, 64); console.log('Received data:', new Uint8Array(result.data.buffer)); } ``` ## Notes 1. **Data Transfer Limits**: - Default transfer threshold: 64 bytes - Adjustable via `setTransferThreshold()` 2. **Device Compatibility**: - Supports standard USB device classes - Special devices may require additional configuration 3. **Error Handling**: - All operations may throw USBError - Includes detailed error codes and messages ## Development Guide ### Project Structure ``` webusb_bridge/ ├── src/ │ ├── main/ │ │ ├── ets/ │ │ │ ├── USBDevice.ets // USB device implementation │ │ │ ├── WebUSBBridge.ets // Main bridge class │ │ │ └── errors.ets // Error type definitions │ │ └── resources/ │ │ └── rawfile/ │ │ └── _webusb_bridge_WebUSBClient.js // Web-side script └── README.md ``` ### Build & Test 1. Add module to your OpenHarmony app 2. Initialize WebUSBBridge in pages needing WebUSB 3. Load WebUSB-enabled pages using Web component 4. Test functionality with USB devices ## License Apache License 2.0 - See LICENSE file for details. ## Contributing Issues and Pull Requests are welcome for code improvements and suggestions.