• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# USB Device Management
2
3<!--Kit: Basic Services Kit-->
4<!--Subsystem: USB-->
5<!--Owner: @hwymlgitcode-->
6<!--Designer: @w00373942-->
7<!--Tester: @dong-dongzhen-->
8<!--Adviser: @w_Machine_cc-->
9
10## When to Use
11
12When a USB device is inserted, you can use **usbManager** to obtain basic information about the USB device, such as the device type and supported functions. The host communicates with the USB device through the encapsulated pipe. In OpenHarmony, the USB management service is the core component that manages the connection and communication with USB devices. With the USB management service, applications can detect the USB connection and disconnection, manage permission requests and device configurations of USB devices, and perform data transfer and device control.
13
14## Environment Preparation
15
16### Environment Requirements
17
18- Development tool and configuration:
19
20  DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview).
21
22
23- SDK version configuration:
24
25  The ArkTs APIs for peripheral management can be used only when the SDK is of API version 16 or later.
26
27
28- HDC configuration:
29
30  HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulator on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc).
31
32### Environment Setup
33
34- Install [DevEco Studio](https://developer.huawei.com/consumer/en/download/) 4.1 or later on the PC.
35- Update the public SDK to API version 16 or later.<!--Del--> For details, see [Switching to Full SDK](../../../../faqs/full-sdk-switch-guide.md).<!--DelEnd-->
36- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS.
37- Use a USB cable to connect an OpenHarmony device to the PC.
38
39## How to Develop
40
41### Available APIs
42
43USB device management provides the following functions: querying the USB device list, controlling USB device permissions, and setting USB device configurations.
44
45The following table lists the USB APIs currently available. For details, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md).
46
47**Table 1** Open USB APIs
48
49| API                                                      | Description                                                        |
50| ------------------------------------------------------------ | ------------------------------------------------------------ |
51| hasRight(deviceName: string): boolean                         | Checks whether the USB has the device access permissions.|
52| requestRight(deviceName: string): Promise&lt;boolean&gt;       | Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result.                       |
53| removeRight(deviceName: string): boolean | Removes the device access permissions of the application.|
54| connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt; | Connects to the USB device based on the device information returned by **getDevices()**.               |
55| getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt;          | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned.                                           |
56| setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration.                                            |
57| setInterface(pipe: USBDevicePipe, iface: USBInterface): number   | Sets a USB interface.                                            |
58| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface.                                                  |
59| closePipe(pipe: USBDevicePipe): number                         | Closes a USB device pipe.                                      |
60| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface.                                                  |
61| getFileDescriptor(pipe: USBDevicePipe): number                 | Obtains the file descriptor of a USB device.                                            |
62| getRawDescriptor(pipe: USBDevicePipe): Uint8Array              | Obtains the raw USB descriptor.                                       |
63
64### How to Develop
65
66A USB device can be used as a host to connect to a device for management. The procedure is as follows:
67
68
691. Import modules.
70
71   ```ts
72   // Import the usbManager module.
73   import { usbManager } from '@kit.BasicServicesKit';
74   import { BusinessError } from '@kit.BasicServicesKit';
75   ```
76
772. Obtain the USB device list.
78
79   ```ts
80   // Obtain the USB device list.
81   let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices();
82   console.info(`deviceList: ${deviceList}`);
83   if(deviceList.length === 0) {
84     console.error('deviceList is empty');
85     return;
86   }
87   /*
88   Example deviceList structure:
89   [
90     {
91       name: "1-1",
92       serial: "",
93       manufacturerName: "",
94       productName: "",
95       version: "",
96       vendorId: 7531,
97       productId: 2,
98       clazz: 9,
99       subClass: 0,
100       protocol: 1,
101       devAddress: 1,
102       busNum: 1,
103       configs: [
104         {
105           id: 1,
106           attributes: 224,
107           isRemoteWakeup: true,
108           isSelfPowered: true,
109           maxPower: 0,
110           name: "1-1",
111           interfaces: [
112             {
113               id: 0,
114               protocol: 0,
115               clazz: 9,
116               subClass: 0,
117               alternateSetting: 0,
118               name: "1-1",
119               endpoints: [
120                 {
121                   address: 129,
122                   attributes: 3,
123                   interval: 12,
124                   maxPacketSize: 4,
125                   direction: 128,
126                   number: 1,
127                   type: 3,
128                   interfaceId: 0,
129                 }
130               ]
131             }
132           ]
133         }
134       ]
135     }
136   ]
137   */
138   ```
139
1403. Obtain the device operation permissions.
141
142   ```ts
143   let deviceName : string = deviceList[0].name;
144   // Request the permissions to operate a specified device.
145   usbManager.requestRight(deviceName).then((hasRight : boolean) => {
146     console.info("usb device request right result: " + hasRight);
147   }).catch((error : BusinessError)=> {
148     console.error(`usb device request right failed : ${error}`);
149   });
150   ```
151
1524. Open the device.
153
154   ```ts
155   // Open the device, and obtain the USB device pipe for data transfer.
156   let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]);
157   let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0];
158   /*
159    Claim the corresponding interface from **deviceList**.
160   interface1 must be one present in the device configuration.
161   */
162   usbManager.claimInterface(pipe, interface1, true);
163   ```
164
1655. Release the USB interface, and close the USB device.
166
167   ```ts
168   usbManager.releaseInterface(pipe, interface1);
169   usbManager.closePipe(pipe);
170   ```