• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# USB Service Development
2
3
4
5## When to Use
6
7In Host mode, you can obtain the list of connected USB devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
8
9
10## Available APIs
11
12The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
13
14The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usbManager.md).
15
16**Table 1** Open USB APIs
17
18| Name                                                      | Description                                                        |
19| ------------------------------------------------------------ | ------------------------------------------------------------ |
20| hasRight(deviceName: string): boolean                         | Checks whether the user has the device access permissions.|
21| requestRight(deviceName: string): Promise<boolean>       | Requests the device access permissions for the application. This API uses a promise to return the result.                       |
22| removeRight(deviceName: string): boolean | Revokes the device access permissions of the application.|
23| connectDevice(device: USBDevice): Readonly<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`.               |
24| getDevices(): Array<Readonly<USBDevice>>          | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned.                                           |
25| setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration.                                            |
26| setInterface(pipe: USBDevicePipe, iface: USBInterface): number   | Sets a USB interface.                                            |
27| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface.                                                  |
28| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> | Performs bulk transfer.                                                  |
29| closePipe(pipe: USBDevicePipe): number                         | Closes a USB device pipe.                                      |
30| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface.                                                  |
31| getFileDescriptor(pipe: USBDevicePipe): number                 | Obtains the file descriptor.                                              |
32| getRawDescriptor(pipe: USBDevicePipe): Uint8Array              | Obtains the raw USB descriptor.                                       |
33| controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise<number> | Performs control transfer.                                                  |
34
35
36## How to Develop
37
38You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows:
39
40
411. Obtain the USB device list.
42
43   ```ts
44   // Import the USB API package.
45   import usb from '@ohos.usbManager';
46   // Obtain the USB device list.
47   let deviceList : Array<usb.USBDevice> = usb.getDevices();
48   /*
49   Example deviceList structure:
50   [
51     {
52       name: "1-1",
53       serial: "",
54       manufacturerName: "",
55       productName: "",
56       version: "",
57       vendorId: 7531,
58       productId: 2,
59       clazz: 9,
60       subClass: 0,
61       protocol: 1,
62       devAddress: 1,
63       busNum: 1,
64       configs: [
65         {
66           id: 1,
67           attributes: 224,
68           isRemoteWakeup: true,
69           isSelfPowered: true,
70           maxPower: 0,
71           name: "1-1",
72           interfaces: [
73             {
74               id: 0,
75               protocol: 0,
76               clazz: 9,
77               subClass: 0,
78               alternateSetting: 0,
79               name: "1-1",
80               endpoints: [
81                 {
82                   address: 129,
83                   attributes: 3,
84                   interval: 12,
85                   maxPacketSize: 4,
86                   direction: 128,
87                   number: 1,
88                   type: 3,
89                   interfaceId: 0,
90                 }
91               ]
92             }
93           ]
94         }
95       ]
96     }
97   ]
98   */
99   ```
100
1012. Obtain the device operation permissions.
102
103   ```ts
104   import usb from '@ohos.usbManager';
105   import { BusinessError } from '@ohos.base';
106
107   let deviceName : string = deviceList[0].name;
108   // Request the permissions to operate a specified device.
109   usb.requestRight(deviceName).then((hasRight : boolean) => {
110     console.info("usb device request right result: " + hasRight);
111   }).catch((error : BusinessError)=> {
112     console.info("usb device request right failed : " + error);
113   });
114   ```
115
1163. Open the device.
117
118   ```ts
119   // Open the device, and obtain the USB device pipe for data transfer.
120   let pipe : usb.USBDevicePipe = usb.connectDevice(deviceList[0]);
121   let interface1 : usb.USBInterface = deviceList[0].configs[0].interfaces[0];
122   /*
123    Claim the corresponding interface from **deviceList**.
124   interface1 must be one present in the device configuration.
125   */
126   usb.claimInterface(pipe, interface1, true);
127   ```
128
1294. Perform data transfer.
130
131   ```ts
132   import usb from '@ohos.usbManager';
133   import { BusinessError } from '@ohos.base';
134   /*
135    Read data. Select the corresponding RX endpoint from deviceList for data transfer.
136   (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array.
137   */
138   let inEndpoint : usb.USBEndpoint = interface1.endpoints[2];
139   let outEndpoint : usb.USBEndpoint = interface1.endpoints[1];
140   let dataUint8Array : Uint8Array = new Uint8Array(1024);
141   usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => {
142   if (dataLength >= 0) {
143     console.info("usb readData result Length : " + dataLength);
144   } else {
145     console.info("usb readData failed : " + dataLength);
146   }
147   }).catch((error : BusinessError) => {
148   console.info("usb readData error : " + JSON.stringify(error));
149   });
150   // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0)
151   usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => {
152     if (dataLength >= 0) {
153       console.info("usb writeData result write length : " + dataLength);
154     } else {
155       console.info("writeData failed");
156     }
157   }).catch((error : BusinessError) => {
158     console.info("usb writeData error : " + JSON.stringify(error));
159   });
160   ```
161
1625. Release the USB interface, and close the USB device.
163
164   ```ts
165   usb.releaseInterface(pipe, interface1);
166   usb.closePipe(pipe);
167   ```
168