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