• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.usbManager (USB Manager)
2
3The **usbManager** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as USB interface management, and function switch and query on the device side.
4
5>  **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9## Modules to Import
10
11```ts
12import { usbManager } from '@kit.BasicServicesKit';
13```
14
15## usbManager.getDevices
16
17getDevices(): Array<Readonly<USBDevice>>
18
19Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. When the developer mode is disabled, **undefined** may be returned if no device is connected. Check whether the return value of the API is empty.
20
21**System capability**: SystemCapability.USB.USBManager
22
23**Error codes**
24
25For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
26
27| ID| Error Message                 |
28| -------- | ------------------------- |
29| 801      | Capability not supported. |
30
31**Return value**
32
33| Type                                                  | Description     |
34| ---------------------------------------------------- | ------- |
35| Array<Readonly<[USBDevice](#usbdevice)>> | USB device list.|
36
37**Example**
38
39```ts
40let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
41console.log(`devicesList = ${devicesList}`);
42/*
43The following is a simple example of the data structure for devicesList:
44[
45  {
46    name: "1-1",
47    serial: "",
48    manufacturerName: "",
49    productName: "",
50    version: "",
51    vendorId: 7531,
52    productId: 2,
53    clazz: 9,
54    subClass: 0,
55    protocol: 1,
56    devAddress: 1,
57    busNum: 1,
58    configs: [
59      {
60        id: 1,
61        attributes: 224,
62        isRemoteWakeup: true,
63        isSelfPowered: true,
64        maxPower: 0,
65        name: "1-1",
66        interfaces: [
67          {
68            id: 0,
69            protocol: 0,
70            clazz: 9,
71            subClass: 0,
72            alternateSetting: 0,
73            name: "1-1",
74            endpoints: [
75              {
76                address: 129,
77                attributes: 3,
78                interval: 12,
79                maxPacketSize: 4,
80                direction: 128,
81                number: 1,
82                type: 3,
83                interfaceId: 0,
84              },
85            ],
86          },
87        ],
88      },
89    ],
90  },
91]
92*/
93```
94
95## usbManager.connectDevice
96
97connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
98
99Connects to the USB device based on the device information returned by **getDevices()**. If the USB service is abnormal, **undefined** may be returned. Check whether the return value of the API is empty.
100
1011. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list.
1022. Call [usbManager.requestRight](#usbmanagerrequestright) to request the permission to use the device.
103
104**System capability**: SystemCapability.USB.USBManager
105
106**Parameters**
107
108| Name| Type| Mandatory| Description|
109| -------- | -------- | -------- | ---------------- |
110| device | [USBDevice](#usbdevice) | Yes| USB device. The **busNum** and **devAddress** parameters obtained by **getDevices** are used to determine a USB device. Other parameters are passed transparently.|
111
112**Return value**
113
114| Type| Description|
115| -------- | -------- |
116| Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.|
117
118**Error codes**
119
120For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
121
122| ID| Error Message                                                    |
123| -------- | ------------------------------------------------------------ |
124| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
125| 801      | Capability not supported.                                    |
126| 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first.|
127
128**Example**
129
130```ts
131let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
132if (devicesList.length == 0) {
133  console.log(`device list is empty`);
134}
135
136let device: usbManager.USBDevice = devicesList[0];
137usbManager.requestRight(device.name);
138let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
139console.log(`devicepipe = ${devicepipe}`);
140```
141
142## usbManager.hasRight
143
144hasRight(deviceName: string): boolean
145
146Checks whether the application has the permission to access the device.
147
148Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise.
149
150**System capability**: SystemCapability.USB.USBManager
151
152**Parameters**
153
154| Name| Type| Mandatory| Description|
155| -------- | -------- | -------- | -------- |
156| deviceName | string | Yes| Device name, which can be obtained from the device list returned by **getDevices**.|
157
158**Error codes**
159
160For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
161
162| ID| Error Message                                                    |
163| -------- | ------------------------------------------------------------ |
164| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
165| 801      | Capability not supported.                                    |
166
167**Return value**
168
169| Type| Description|
170| -------- | -------- |
171| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise. If this API fails to be called, the following error codes are returned:<br>- 88080385: This API is not initialized.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.|
172
173**Example**
174
175```ts
176let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
177if (devicesList.length == 0) {
178  console.log(`device list is empty`);
179}
180
181let device: usbManager.USBDevice = devicesList[0];
182usbManager.requestRight(device.name);
183let right: boolean = usbManager.hasRight(device.name);
184console.log(`${right}`);
185```
186
187## usbManager.requestRight
188
189requestRight(deviceName: string): Promise&lt;boolean&gt;
190
191Requests the temporary device access permission for the application. This API uses a promise to return the result. System applications are granted the device access permission by default, and you do not need to apply for the permission separately.
192
193**System capability**: SystemCapability.USB.USBManager
194
195**Parameters**
196
197| Name| Type| Mandatory| Description|
198| -------- | -------- | -------- | -------- |
199| deviceName | string | Yes| Device name, which can be obtained from the device list returned by **getDevices**.|
200
201**Error codes**
202
203For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
204
205| ID| Error Message                                                    |
206| -------- | ------------------------------------------------------------ |
207| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
208| 801      | Capability not supported.                                    |
209
210**Return value**
211
212| Type| Description|
213| -------- | -------- |
214| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite. If this API fails to be called, the following error codes are returned:<br>- 88080385: This API is not initialized.<br>- 88080392: An error occurs when the API data packet is written.<br>- 88080393: An error occurs when the API data packet is read.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.|
215
216**Example**
217
218```ts
219let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
220if (devicesList.length == 0) {
221  console.log(`device list is empty`);
222}
223
224let device: usbManager.USBDevice = devicesList[0];
225usbManager.requestRight(device.name).then(ret => {
226  console.log(`requestRight = ${ret}`);
227});
228```
229
230## usbManager.removeRight
231
232removeRight(deviceName: string): boolean
233
234Removes the device access permission for the application. System applications are granted the device access permission by default, and calling this API will not revoke the permission.
235
236**System capability**: SystemCapability.USB.USBManager
237
238**Parameters**
239
240| Name| Type| Mandatory| Description|
241| -------- | -------- | -------- | -------- |
242| deviceName | string | Yes| Device name, which can be obtained from the device list returned by **getDevices**.|
243
244**Error codes**
245
246For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
247
248| ID| Error Message                                                    |
249| -------- | ------------------------------------------------------------ |
250| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
251| 801      | Capability not supported.                                    |
252
253**Return value**
254
255| Type| Description|
256| -------- | -------- |
257| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite. If this API fails to be called, the following error codes are returned:<br>- 88080382: An invalid value or parameter occurs during the API operation.<br>- 88080385: This API is not initialized.<br>- 88080392: An error occurs when the API data packet is written.<br>- 88080393: An error occurs when the API data packet is read.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.|
258
259**Example**
260
261```ts
262let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
263if (devicesList.length == 0) {
264  console.log(`device list is empty`);
265}
266
267let device: usbManager.USBDevice = devicesList[0];
268if (usbManager.removeRight(device.name)) {
269  console.log(`Succeed in removing right`);
270}
271```
272
273## usbManager.claimInterface
274
275claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number
276
277Claims a USB interface.
278
2791. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list and interfaces.
2802. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
2813. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
282
283**System capability**: SystemCapability.USB.USBManager
284
285**Parameters**
286
287| Name| Type| Mandatory| Description|
288| -------- | -------- | -------- | -------- |
289| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
290| iface | [USBInterface](#usbinterface) | Yes| USB interface. You can use **getDevices** to obtain device information and identify the USB interface based on its ID.|
291| force | boolean | No| Whether to forcibly claim a USB interface. The default value is **false**, which means not to forcibly claim a USB interface. You can set the value as required.|
292
293**Error codes**
294
295For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
296
297| ID| Error Message                                                    |
298| -------- | ------------------------------------------------------------ |
299| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
300| 801      | Capability not supported.                                    |
301
302**Return value**
303
304| Type| Description|
305| -------- | -------- |
306| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise. The error codes are as follows:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
307
308**Example**
309
310```ts
311let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
312if (devicesList.length == 0) {
313  console.log(`device list is empty`);
314}
315
316let device: usbManager.USBDevice = devicesList[0];
317usbManager.requestRight(device.name);
318let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
319let interfaces: usbManager.USBInterface = device.configs[0].interfaces[0];
320let ret: number= usbManager.claimInterface(devicepipe, interfaces);
321console.log(`claimInterface = ${ret}`);
322```
323
324## usbManager.releaseInterface
325
326releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number
327
328Releases a USB interface.
329
330Before you do this, ensure that you have claimed the interface by calling [usbManager.claimInterface](#usbmanagerclaiminterface).
331
332**System capability**: SystemCapability.USB.USBManager
333
334**Parameters**
335
336| Name| Type| Mandatory| Description|
337| -------- | -------- | -------- | -------- |
338| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
339| iface | [USBInterface](#usbinterface) | Yes| USB interface. You can use **getDevices** to obtain device information and identify the USB interface based on its ID.|
340
341**Error codes**
342
343For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
344
345| ID| Error Message                                                    |
346| -------- | ------------------------------------------------------------ |
347| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types. |
348| 801      | Capability not supported.                                    |
349
350**Return value**
351
352| Type| Description|
353| -------- | -------- |
354| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise. The error codes are as follows:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080381: Invalid interface operation.<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
355
356**Example**
357
358```ts
359let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
360if (devicesList.length == 0) {
361  console.log(`device list is empty`);
362}
363
364let device: usbManager.USBDevice = devicesList[0];
365usbManager.requestRight(device.name);
366let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
367let interfaces: usbManager.USBInterface = device.configs[0].interfaces[0];
368let ret: number = usbManager.claimInterface(devicepipe, interfaces);
369ret = usbManager.releaseInterface(devicepipe, interfaces);
370console.log(`releaseInterface = ${ret}`);
371```
372
373## usbManager.setConfiguration
374
375setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number
376
377Sets the device configuration.
378
3791. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list and device configuration.
3802. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
3813. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
382
383**System capability**: SystemCapability.USB.USBManager
384
385**Parameters**
386
387| Name| Type| Mandatory| Description|
388| -------- | -------- | -------- | -------- |
389| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
390| config | [USBConfiguration](#usbconfiguration) | Yes| USB configuration. You can use **getDevices** to obtain device information and identify the USB configuration based on the ID.|
391
392**Error codes**
393
394For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
395
396| ID| Error Message                                                    |
397| -------- | ------------------------------------------------------------ |
398| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
399| 801      | Capability not supported.                                    |
400
401**Return value**
402
403| Type| Description|
404| -------- | -------- |
405| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise. The error codes are as follows:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.<br>- -17: I/O failure.|
406
407**Example**
408
409```ts
410let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
411if (devicesList.length == 0) {
412  console.log(`device list is empty`);
413}
414
415let device: usbManager.USBDevice = devicesList[0];
416usbManager.requestRight(device.name);
417let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
418let config: usbManager.USBConfiguration = device.configs[0];
419let ret: number= usbManager.setConfiguration(devicepipe, config);
420console.log(`setConfiguration = ${ret}`);
421```
422
423## usbManager.setInterface
424
425setInterface(pipe: USBDevicePipe, iface: USBInterface): number
426
427Sets a USB interface.
428
4291. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the device list and interfaces.
4302. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
4313. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
4324. Call [usbManager.claimInterface](#usbmanagerclaiminterface) to register a communication interface.
433
434**System capability**: SystemCapability.USB.USBManager
435
436**Parameters**
437
438| Name| Type| Mandatory| Description|
439| -------- | -------- | -------- | -------- |
440| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
441| iface | [USBInterface](#usbinterface)   | Yes| USB interface. You can use **getDevices** to obtain device information and identify the USB interface based on its **id** and **alternateSetting**.|
442
443**Error codes**
444
445For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
446
447| ID| Error Message                                                    |
448| -------- | ------------------------------------------------------------ |
449| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
450| 801      | Capability not supported.                                    |
451
452**Return value**
453
454| Type| Description|
455| -------- | -------- |
456| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise. The error codes are as follows:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
457
458**Example**
459
460```ts
461let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
462if (devicesList.length == 0) {
463  console.log(`device list is empty`);
464}
465
466let device: usbManager.USBDevice = devicesList[0];
467usbManager.requestRight(device.name);
468let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
469let interfaces: usbManager.USBInterface = device.configs[0].interfaces[0];
470let ret: number = usbManager.claimInterface(devicepipe, interfaces);
471ret = usbManager.setInterface(devicepipe, interfaces);
472console.log(`setInterface = ${ret}`);
473```
474
475## usbManager.getRawDescriptor
476
477getRawDescriptor(pipe: USBDevicePipe): Uint8Array
478
479Obtains the raw USB descriptor. If the USB service is abnormal, **undefined** may be returned. Check whether the return value of the API is empty.
480
4811. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list.
4822. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
4833. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
484
485**System capability**: SystemCapability.USB.USBManager
486
487**Parameters**
488
489| Name| Type| Mandatory| Description|
490| -------- | -------- | -------- | -------- |
491| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
492
493**Error codes**
494
495For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
496
497| ID| Error Message                                                    |
498| -------- | ------------------------------------------------------------ |
499| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
500| 801      | Capability not supported.                                    |
501
502**Return value**
503
504| Type| Description|
505| -------- | -------- |
506| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.|
507
508**Example**
509
510```ts
511let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
512if (devicesList.length == 0) {
513  console.log(`device list is empty`);
514}
515
516usbManager.requestRight(devicesList[0].name);
517let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]);
518let ret: Uint8Array = usbManager.getRawDescriptor(devicepipe);
519```
520
521## usbManager.getFileDescriptor
522
523getFileDescriptor(pipe: USBDevicePipe): number
524
525Obtains the file descriptor.
526
5271. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list.
5282. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
5293. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
530
531**System capability**: SystemCapability.USB.USBManager
532
533**Parameters**
534
535| Name| Type| Mandatory| Description|
536| -------- | -------- | -------- | -------- |
537| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
538
539**Error codes**
540
541For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
542
543| ID| Error Message                                                    |
544| -------- | ------------------------------------------------------------ |
545| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
546| 801      | Capability not supported.                                    |
547
548**Return value**
549
550| Type    | Description                  |
551| ------ | -------------------- |
552| number | Returns the file descriptor corresponding to the device if this API is successful called; returns an error code otherwise. The error codes are as follows:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
553
554**Example**
555
556```ts
557let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
558if (devicesList.length == 0) {
559  console.log(`device list is empty`);
560}
561
562usbManager.requestRight(devicesList[0].name);
563let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]);
564let ret: number = usbManager.getFileDescriptor(devicepipe);
565```
566
567## usbManager.controlTransfer<sup>(deprecated)</sup>
568
569controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise&lt;number&gt;
570
571Performs control transfer.
572
5731. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list.
5742. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
5753. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
576
577**NOTE**
578
579> This API is supported since API version 9 and deprecated since API version 12. You are advised to use [usbControlTransfer](#usbmanagerusbcontroltransfer12).
580
581**System capability**: SystemCapability.USB.USBManager
582
583**Parameters**
584
585| Name| Type| Mandatory| Description|
586| -------- | -------- | -------- | -------- |
587| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe. You need to call **connectDevice** to obtain its value.|
588| controlparam | [USBControlParams](#usbcontrolparamsdeprecated) | Yes| Control transfer parameters. Set the parameters as required. For details, see the USB protocol.|
589| timeout | number | No| (Optional) Timeout duration, in ms. The default value is **0**. You can set this parameter as required.|
590
591**Error codes**
592
593For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
594
595| ID| Error Message                                                    |
596| -------- | ------------------------------------------------------------ |
597| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
598
599**Return value**
600
601| Type| Description|
602| -------- | -------- |
603| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
604
605**Example**
606
607```ts
608class PARA {
609  request: number = 0
610  reqType: usbManager.USBControlRequestType = 0
611  target: usbManager.USBRequestTargetType = 0
612  value: number = 0
613  index: number = 0
614  data: Uint8Array = new Uint8Array()
615}
616
617let param: PARA = {
618  request: 0x06,
619  reqType: 0x80,
620  target:0,
621  value: 0x01 << 8 | 0,
622  index: 0,
623  data: new Uint8Array(18)
624};
625
626let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
627if (devicesList.length == 0) {
628  console.log(`device list is empty`);
629}
630
631usbManager.requestRight(devicesList[0].name);
632let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]);
633usbManager.controlTransfer(devicepipe, param).then((ret: number) => {
634console.log(`controlTransfer = ${ret}`);
635})
636```
637
638## usbManager.usbControlTransfer<sup>12+</sup>
639
640usbControlTransfer(pipe: USBDevicePipe, requestparam: USBDeviceRequestParams, timeout ?: number): Promise&lt;number&gt;
641
642Performs control transfer.
643
6441. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list.
6452. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
6463. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
647
648**System capability**: SystemCapability.USB.USBManager
649
650**Parameters**
651
652| Name| Type| Mandatory| Description|
653| -------- | -------- | -------- | -------- |
654| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
655| requestparam | [USBDeviceRequestParams](#usbdevicerequestparams12) | Yes| Control transfer parameters. Set the parameters as required. For details, see the USB protocol.|
656| timeout | number | No| (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout.|
657
658**Error codes**
659
660For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
661
662| ID| Error Message                                                    |
663| -------- | ------------------------------------------------------------ |
664| 401      | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types. |
665| 801      | Capability not supported.                                    |
666
667**Return value**
668
669| Type| Description|
670| -------- | -------- |
671| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
672
673**Example**
674
675```ts
676class PARA {
677  bmRequestType: number = 0
678  bRequest: number = 0
679  wValue: number = 0
680  wIndex: number = 0
681  wLength: number = 0
682  data: Uint8Array = new Uint8Array()
683}
684
685let param: PARA = {
686  bmRequestType: 0x80,
687  bRequest: 0x06,
688
689  wValue:0x01 << 8 | 0,
690  wIndex: 0,
691  wLength: 18,
692  data: new Uint8Array(18)
693};
694
695let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
696if (devicesList.length == 0) {
697  console.log(`device list is empty`);
698}
699
700usbManager.requestRight(devicesList[0].name);
701let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]);
702usbManager.usbControlTransfer(devicepipe, param).then((ret: number) => {
703console.log(`usbControlTransfer = ${ret}`);
704})
705```
706
707## usbManager.bulkTransfer
708
709bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise&lt;number&gt;
710
711Performs bulk transfer.
712
7131. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list and endpoints.
7142. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
7153. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain the returned **devicepipe**.
7164. Obtain the [usbManager.claimInterface](#usbmanagerclaiminterface) API.
7175. Call the **usbManager.bulkTransfer** API.
718
719> **NOTE**
720>
721> The total amount of data (including **pipe**, **endpoint**, **buffer**, and **timeout**) transferred in bulk must be less than 200 KB.
722
723**System capability**: SystemCapability.USB.USBManager
724
725**Parameters**
726
727| Name| Type| Mandatory| Description|
728| -------- | -------- | -------- | -------- |
729| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe. You need to call **connectDevice** to obtain its value.|
730| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB interface for data transfer. You need to call **getDevices** to obtain the device information list and endpoint. Wherein, **address** is used to determine the endpoint address, **direction** is used to determine the endpoint direction, and **interfaceId** is used to determine the USB interface to which the endpoint belongs. Other parameters are passed transparently.|
731| buffer | Uint8Array | Yes| Buffer used to write or read data.|
732| timeout | number | No| (Optional) Timeout duration, in ms. The default value is **0**. You can set this parameter as required.|
733
734**Error codes**
735
736For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
737
738| ID| Error Message                                                    |
739| -------- | ------------------------------------------------------------ |
740| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
741| 801      | Capability not supported.                                    |
742
743**Return value**
744
745| Type| Description|
746| -------- | -------- |
747| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080385: This API is not initialized.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080492: An error occurs when the service data packet is written.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.<br>- -3: The parameter is invalid.<br>- -202: The device is not found.|
748
749**Example**
750
751> **NOTE**
752>
753> The following sample code is only a basic process for calling the **bulkTransfer** API. In actual calling, you must comply with the device-related protocols to ensure correct data transfer and device compatibility.
754
755```ts
756// Call usbManager.getDevices to obtain a data set. Then, obtain a USB device and its access permission.
757// Pass the obtained USB device as a parameter to usbManager.connectDevice. Then, call usbManager.connectDevice to connect the USB device.
758// Call usbManager.claimInterface to claim a USB interface. After that, call usbManager.bulkTransfer to start bulk transfer.
759let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
760if (devicesList.length == 0) {
761  console.log(`device list is empty`);
762}
763
764let device: usbManager.USBDevice = devicesList[0];
765usbManager.requestRight(device.name);
766
767let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
768for (let i = 0; i < device.configs[0].interfaces.length; i++) {
769  if (device.configs[0].interfaces[i].endpoints[0].attributes == 2) {
770    let endpoint: usbManager.USBEndpoint = device.configs[0].interfaces[i].endpoints[0];
771    let interfaces: usbManager.USBInterface = device.configs[0].interfaces[i];
772    let ret: number = usbManager.claimInterface(devicepipe, interfaces);
773    let buffer =  new Uint8Array(128);
774    usbManager.bulkTransfer(devicepipe, endpoint, buffer).then((ret: number) => {
775      console.log(`bulkTransfer = ${ret}`);
776    });
777  }
778}
779```
780
781## usbManager.usbSubmitTransfer<sup>18+</sup>
782
783usbSubmitTransfer(transfer: UsbDataTransferParams): void
784
785Requests a USB data transfer.
786
787This API uses an asynchronous callback to return the result.
788
7891. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list and endpoints.
7902. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
7913. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain the returned **devicepipe**.
7924. Obtain the [usbManager.claimInterface](#usbmanagerclaiminterface) API.
7935. Call the **usbManager.usbSubmitTransfer** API.
794
795**System capability**: SystemCapability.USB.USBManager
796
797**Parameters**
798
799| Name| Type| Mandatory| Description|
800| -------- | -------- | -------- | -------- |
801| transfer | [UsbDataTransferParams](#usbdatatransferparams18) | Yes| As a USB data transfer interface, it is required for a client to initiate a transfer request.|
802
803**Error codes**
804
805For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
806
807| ID| Error Message                                                    |
808| -------- | ------------------------------------------------------------ |
809| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
810| 801 | Capability not supported. |
811| 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first. |
812| 14400007 | Resource busy. |
813| 14400008 | No such device (it may have been disconnected). |
814| 14400009 | Insufficient memory. |
815| 14400012 | Transmission I/O error. |
816
817**Example**
818
819> **NOTE**
820>
821> The following sample code shows the basic process for calling the **usbSubmitTransfer** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols to ensure correct data transfer and device compatibility.
822
823```ts
824// Call usbManager.getDevices to obtain a data set. Then, obtain a USB device and its access permission.
825// Pass the obtained USB device as a parameter to usbManager.connectDevice. Then, call usbManager.connectDevice to connect the USB device.
826// Call usbManager.claimInterface to claim a USB interface. After that, call usbManager.bulkTransfer to start bulk transfer.
827let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
828if (devicesList.length == 0) {
829  console.log(`device list is empty`);
830  return;
831}
832let device: usbManager.USBDevice = devicesList[0];
833usbManager.requestRight(device.name);
834let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
835// Obtain the endpoint address.
836let endpoint = device.configs[0].interfaces[0]?.endpoints.find((value) => {
837  return value.direction === 0 && value.type === 2
838})
839// Obtain the first ID of the device.
840let ret: number = usbManager.claimInterface(devicepipe, device.configs[0].interfaces[0], true);
841
842let transferParams: usbManager.UsbDataTransferParams = {
843  devPipe: devicepipe,
844  flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK,
845  endpoint: 1,
846  type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_BULK,
847  timeout: 2000,
848  length: 10,
849  callback: () => {},
850  userData: new Uint8Array(10),
851  buffer: new Uint8Array(10),
852  isoPacketCount: 0,
853};
854try {
855  transferParams.endpoint=endpoint?.address as number;
856  transferParams.callback=(err, callBackData: usbManager.SubmitTransferCallback)=>{
857    console.info('callBackData =' +JSON.stringify(callBackData));
858  }
859  usbManager.usbSubmitTransfer(transferParams);
860  console.info('USB transfer request submitted.');
861} catch (error) {
862  console.error('USB transfer failed:', error);
863}
864```
865
866## usbManager.usbCancelTransfer<sup>18+</sup>
867
868usbCancelTransfer(transfer: UsbDataTransferParams): void
869
870Cancels an asynchronous USB data transfer request.
871
8721. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list and endpoints.
8732. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
8743. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain the returned **devicepipe**.
8754. Obtain the [usbManager.claimInterface](#usbmanagerclaiminterface) API.
8765. Call the **usbManager.usbCancelTransfer** API.
877
878**System capability**: SystemCapability.USB.USBManager
879
880**Parameters**
881
882| Name| Type| Mandatory| Description|
883| -------- | -------- | -------- | -------- |
884| transfer | [UsbDataTransferParams](#usbdatatransferparams18) | Yes| Only **USBDevicePipe** and **endpoint** are required for canceling the transfer.|
885
886**Error codes**
887
888For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
889
890| ID| Error Message                                                    |
891| -------- | ------------------------------------------------------------ |
892| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
893| 801 | Capability not supported. |
894| 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first. |
895| 14400008 | No such device (it may have been disconnected). |
896| 14400010 | Other USB error. Possible causes:<br>1.Unrecognized discard error code. |
897| 14400011 | The transfer is not in progress, or is already complete or cancelled.|
898
899**Return value**
900
901| Type| Description|
902| -------- | -------- |
903| &lt;void&gt; | None.|
904
905**Example**
906
907> **NOTE**
908>
909> The following sample code shows the basic process for calling the **usbCancelTransfer** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols to ensure correct data transfer and device compatibility.
910
911```ts
912// Call usbManager.getDevices to obtain a data set. Then, obtain a USB device and its access permission.
913// Pass the obtained USB device as a parameter to usbManager.connectDevice. Then, call usbManager.connectDevice to connect the USB device.
914// Call usbManager.claimInterface to claim a USB interface. After that, call usbManager.bulkTransfer to start bulk transfer.
915let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
916if (devicesList.length == 0) {
917  console.log(`device list is empty`);
918  return;
919}
920let device: usbManager.USBDevice = devicesList[0];
921usbManager.requestRight(device.name);
922let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(device);
923// Obtain the endpoint address.
924let endpoint = device.configs[0].interfaces[0]?.endpoints.find((value) => {
925  return value.direction === 0 && value.type === 2
926})
927// Obtain the first ID of the device.
928let ret: number = usbManager.claimInterface(devicepipe, device.configs[0].interfaces[0], true);
929let transferParams: usbManager.UsbDataTransferParams = {
930  devPipe: devicepipe,
931  flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK,
932  endpoint: 1,
933  type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_BULK,
934  timeout: 2000,
935  length: 10,
936  callback: () => {},
937  userData: new Uint8Array(10),
938  buffer: new Uint8Array(10),
939  isoPacketCount: 0,
940};
941try {
942  transferParams.endpoint=endpoint?.address as number;
943  transferParams.callback=(err, callBackData: usbManager.SubmitTransferCallback)=>{
944    console.info('callBackData =' +JSON.stringify(callBackData));
945  }
946  usbManager.usbSubmitTransfer(transferParams);
947  usbManager.usbCancelTransfer(transferParams);
948  console.info('USB transfer request submitted.');
949} catch (error) {
950  console.error('USB transfer failed:', error);
951}
952```
953
954## usbManager.closePipe
955
956closePipe(pipe: USBDevicePipe): number
957
958Closes a USB device pipe.
959
9601. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the USB device list.
9612. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission.
9623. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as an input parameter.
963
964**System capability**: SystemCapability.USB.USBManager
965
966**Parameters**
967
968| Name| Type| Mandatory| Description|
969| -------- | -------- | -------- | -------- |
970| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the message control channel. You need to call **connectDevice** to obtain its value.|
971
972**Error codes**
973
974For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
975
976| ID| Error Message                                                    |
977| -------- | ------------------------------------------------------------ |
978| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
979| 801      | Capability not supported.                                    |
980
981**Return value**
982
983| Type| Description|
984| -------- | -------- |
985| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise. The error codes are as follows:<br>- 63: The data exceeds the expected maximum volume.<br>- 88080393: An error occurs when the API data packet is read.<br>- 88080482: An invalid value or parameter occurs during the service.<br>- 88080484: No permission.<br>- 88080493: An error occurs when the service data packet is read.<br>- 88080497: An error occurs when the internal logic of the service is executed.<br>- -1: The underlying interface fails to be called.|
986
987**Example**
988
989```ts
990let devicesList: Array<usbManager.USBDevice> = usbManager.getDevices();
991if (devicesList.length == 0) {
992  console.log(`device list is empty`);
993}
994
995usbManager.requestRight(devicesList[0].name);
996let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]);
997let ret: number = usbManager.closePipe(devicepipe);
998console.log(`closePipe = ${ret}`);
999```
1000
1001## usbManager.hasAccessoryRight<sup>14+</sup>
1002
1003hasAccessoryRight(accessory: USBAccessory): boolean
1004
1005Checks whether the application has the permission to access the USB accessory.
1006
1007You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to obtain the accessory list and use [USBAccessory](#usbaccessory14) as a parameter.
1008
1009**System capability**: SystemCapability.USB.USBManager
1010
1011**Parameters**
1012
1013| Name   | Type        | Mandatory| Description                                 |
1014| --------- | ------------ | ---- | ------------------------------------- |
1015| accessory | [USBAccessory](#usbaccessory14) | Yes  | USB accessory.|
1016
1017**Error codes**
1018
1019For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
1020
1021| ID| Error Message                                                    |
1022| -------- | ------------------------------------------------------------ |
1023| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
1024| 801      | Capability not supported.                                    |
1025| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. |
1026| 14400005 | Database operation exception.                                |
1027| 14401001 | The target USBAccessory not matched.                         |
1028
1029**Return value**
1030
1031| Type   | Description                         |
1032| ------- | ----------------------------- |
1033| boolean | The value **true** indicates that the application has the permission to access the USB accessory; **false** indicates the opposite.|
1034
1035**Example**
1036
1037```ts
1038import { hilog } from '@kit.PerformanceAnalysisKit';
1039try {
1040  let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList()
1041  let flag = usbManager.hasAccessoryRight(accList[0])
1042  hilog.info(0, 'testTag ui', `hasAccessoryRight success, ret:${flag}`)
1043} catch (error) {
1044  hilog.info(0, 'testTag ui', `hasAccessoryRight error ${error.code}, message is ${error.message}`)
1045}
1046```
1047
1048## usbManager.requestAccessoryRight<sup>14+</sup>
1049
1050requestAccessoryRight(accessory: USBAccessory): Promise&lt;boolean&gt;
1051
1052Requests the permission to access a USB accessory for a specified application.
1053
1054You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to obtain the accessory list and use [USBAccessory](#usbaccessory14) as a parameter.
1055
1056**System capability**: SystemCapability.USB.USBManager
1057
1058**Parameters**
1059
1060| Name   | Type        | Mandatory| Description                                 |
1061| --------- | ------------ | ---- | ------------------------------------- |
1062| accessory | [USBAccessory](#usbaccessory14) | Yes  | USB accessory.|
1063
1064**Error codes**
1065
1066For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
1067
1068| ID| Error Message                                                    |
1069| -------- | ------------------------------------------------------------ |
1070| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
1071| 801      | Capability not supported.                                    |
1072| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. |
1073| 14400005 | Database operation exception.                                |
1074| 14401001 | The target USBAccessory not matched.                         |
1075
1076**Return value**
1077
1078| Type            | Description                         |
1079| ---------------- | ----------------------------- |
1080| Promise&lt;boolean&gt; | Promise used to return the application result. The value **true** indicates that the device access permissions are granted; **false** indicates the opposite.|
1081
1082**Example**
1083
1084```ts
1085import { hilog } from '@kit.PerformanceAnalysisKit';
1086try {
1087  let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList()
1088  let flag = usbManager.requestAccessoryRight(accList[0])
1089  hilog.info(0, 'testTag ui', `requestAccessoryRight success, ret:${flag}`)
1090} catch (error) {
1091  hilog.info(0, 'testTag ui', `requestAccessoryRight error ${error.code}, message is ${error.message}`)
1092}
1093```
1094
1095## usbManager.cancelAccessoryRight<sup>14+</sup>
1096
1097cancelAccessoryRight(accessory: USBAccessory): void
1098
1099Cancels the permission of the current application to access USB accessories.
1100
1101You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to obtain the accessory list and use [USBAccessory](#usbaccessory14) as a parameter.
1102
1103**System capability**: SystemCapability.USB.USBManager
1104
1105**Parameters**
1106
1107| Name   | Type        | Mandatory| Description                                 |
1108| --------- | ------------ | ---- | ------------------------------------- |
1109| accessory | [USBAccessory](#usbaccessory14) | Yes  | USB accessory.|
1110
1111**Error codes**
1112
1113For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
1114
1115| ID| Error Message                                                    |
1116| -------- | ------------------------------------------------------------ |
1117| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
1118| 801      | Capability not supported.                                    |
1119| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. |
1120| 14400005 | Database operation exception.                                |
1121| 14401001 | The target USBAccessory not matched.                         |
1122
1123**Example**
1124
1125```ts
1126import { hilog } from '@kit.PerformanceAnalysisKit';
1127try {
1128  let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList()
1129  let flag = usbManager.requestAccessoryRight(accList[0])
1130  usbManager.cancelAccessoryRight(accList[0])
1131  hilog.info(0, 'testTag ui', `cancelAccessoryRight success`)
1132} catch (error) {
1133  hilog.info(0, 'testTag ui', `cancelAccessoryRight error ${error.code}, message is ${error.message}`)
1134}
1135```
1136
1137## usbManager.getAccessoryList<sup>14+</sup>
1138
1139getAccessoryList(): Array<Readonly&lt;USBAccessory&gt;>
1140
1141Obtains the list of USB accessories connected to the host.
1142
1143**System capability**: SystemCapability.USB.USBManager
1144
1145**Error codes**
1146
1147For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
1148
1149| ID| Error Message                                                    |
1150| -------- | ------------------------------------------------------------ |
1151| 801      | Capability not supported.                                    |
1152| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. |
1153
1154**Return value**
1155
1156| Type                         | Description                                              |
1157| ----------------------------- | -------------------------------------------------- |
1158| Array<Readonly&lt;USBAccessory&gt;> | List of USB accessories (read-only). Currently, only one USB accessory is contained in the list.|
1159
1160**Example**
1161
1162```ts
1163import { hilog } from '@kit.PerformanceAnalysisKit';
1164try {
1165  let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList()
1166  hilog.info(0, 'testTag ui', `getAccessoryList success, accList: ${JSON.stringify(accList)}`)
1167} catch (error) {
1168  hilog.info(0, 'testTag ui', `getAccessoryList error ${error.code}, message is ${error.message}`)
1169}
1170```
1171
1172## usbManager.openAccessory<sup>14+</sup>
1173
1174openAccessory(accessory: USBAccessory): USBAccessoryHandle
1175
1176Obtains the accessory handle and opens the accessory file descriptor.
1177
1178You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to obtain the accessory list and use [USBAccessory](#usbaccessory14) as a parameter.
1179
1180**System capability**: SystemCapability.USB.USBManager
1181
1182**Parameters**
1183
1184| Name   | Type        | Mandatory| Description                                 |
1185| --------- | ------------ | ---- | ------------------------------------- |
1186| accessory | [USBAccessory](#usbaccessory14) | Yes  | USB accessory.|
1187
1188**Error codes**
1189
1190For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
1191
1192| ID| Error Message                                                    |
1193| -------- | ------------------------------------------------------------ |
1194| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
1195| 801      | Capability not supported.                                    |
1196| 14400001 | Permission denied. Call requestAccessoryRight to get the right first. |
1197| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. |
1198| 14401001 | The target USBAccessory not matched.                         |
1199| 14401002 | Failed to open the native accessory node.                    |
1200| 14401003 | Cannot reopen the accessory.                                 |
1201
1202**Return value**
1203
1204| Type              | Description       |
1205| ------------------ | ----------- |
1206| [USBAccessoryHandle](#usbaccessoryhandle14) | USB accessory handle.|
1207
1208**Example**
1209
1210```ts
1211import { hilog } from '@kit.PerformanceAnalysisKit';
1212try {
1213  let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList()
1214  let flag = usbManager.requestAccessoryRight(accList[0])
1215  let handle = usbManager.openAccessory(accList[0])
1216  hilog.info(0, 'testTag ui', `openAccessory success`)
1217} catch (error) {
1218  hilog.info(0, 'testTag ui', `openAccessory error ${error.code}, message is ${error.message}`)
1219}
1220```
1221
1222## usbManager.closeAccessory<sup>14+</sup>
1223
1224closeAccessory(accessoryHandle: USBAccessoryHandle): void
1225
1226Closes the accessory file descriptor.
1227
1228You need to call [usbManager.openAccessory](#usbmanageropenaccessory14) to obtain the accessory list and use [USBAccessoryHandle](#usbaccessoryhandle14) as a parameter.
1229
1230**System capability**: SystemCapability.USB.USBManager
1231
1232**Parameters**
1233
1234| Name         | Type              | Mandatory| Description                                  |
1235| --------------- | ------------------ | ---- | -------------------------------------- |
1236| accessoryHandle | [USBAccessoryHandle](#usbaccessoryhandle14) | Yes  | USB accessory handle, obtained through [openAccessory](#usbmanageropenaccessory14).|
1237
1238**Error codes**
1239
1240For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
1241
1242| ID| Error Message                                                    |
1243| -------- | ------------------------------------------------------------ |
1244| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
1245| 801      | Capability not supported.                                    |
1246| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. |
1247
1248**Example**
1249
1250```ts
1251import { hilog } from '@kit.PerformanceAnalysisKit';
1252try {
1253  let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList()
1254  let flag = usbManager.requestAccessoryRight(accList[0])
1255  let handle = usbManager.openAccessory(accList[0])
1256  usbManager.closeAccessory(handle)
1257  hilog.info(0, 'testTag ui', `closeAccessory success`)
1258} catch (error) {
1259  hilog.info(0, 'testTag ui', `closeAccessory error ${error.code}, message is ${error.message}`)
1260}
1261```
1262
1263## USBEndpoint
1264
1265Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface).
1266
1267**System capability**: SystemCapability.USB.USBManager
1268
1269| Name           | Type                                       | Mandatory           |Description           |
1270| ------------- | ------------------------------------------- | ------------- |------------- |
1271| address       | number                                      | Yes|Endpoint address.        |
1272| attributes    | number                                      | Yes|Endpoint attributes.        |
1273| interval      | number                                      | Yes|Endpoint interval.        |
1274| maxPacketSize | number                                      | Yes|Maximum size of data packets on the endpoint.   |
1275| direction     | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction.       |
1276| number        | number                                      | Yes|Endpoint number.         |
1277| type          | number                                      | Yes|Endpoint type.        |
1278| interfaceId   | number                                      | Yes|Unique ID of the interface to which the endpoint belongs.|
1279
1280## USBInterface
1281
1282Represents a USB interface. One [USBConfiguration](#usbconfiguration) object can contain multiple **USBInterface** instances, each providing a specific function.
1283
1284**System capability**: SystemCapability.USB.USBManager
1285
1286| Name              | Type                                    | Mandatory           |Description                   |
1287| ---------------- | ---------------------------------------- | ------------- |--------------------- |
1288| id               | number                                   | Yes|Unique ID of the USB interface.             |
1289| protocol         | number                                   | Yes|Interface protocol.               |
1290| clazz            | number                                   | Yes|Device type.                |
1291| subClass         | number                                   | Yes|Device subclass.                |
1292| alternateSetting | number                                   | Yes|Settings for alternating between descriptors of the same USB interface.|
1293| name             | string                                   | Yes|Interface name.                |
1294| endpoints        | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface.          |
1295
1296## USBConfiguration
1297
1298Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances.
1299
1300**System capability**: SystemCapability.USB.USBManager
1301
1302| Name            | Type                                            | Mandatory |Description             |
1303| -------------- | ------------------------------------------------ | --------------- |--------------- |
1304| id             | number                                           | Yes|Unique ID of the USB configuration.       |
1305| attributes     | number                                           | Yes|Configuration attributes.         |
1306| maxPower       | number                                           | Yes|Maximum power consumption, in mA.   |
1307| name           | string                                           | Yes|Configuration name, which can be left empty.    |
1308| isRemoteWakeup | boolean                                          | Yes|Support for remote wakeup.|
1309| isSelfPowered  | boolean                                          | Yes| Support for independent power supplies.|
1310| interfaces     | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes.     |
1311
1312## USBDevice
1313
1314Represents the USB device information.
1315
1316**System capability**: SystemCapability.USB.USBManager
1317
1318| Name              | Type                                | Mandatory        |Description        |
1319| ---------------- | ------------------------------------ | ---------- |---------- |
1320| busNum           | number                               | Yes|Bus address.     |
1321| devAddress       | number                               | Yes|Device address.     |
1322| serial           | string                               | Yes|Sequence number.      |
1323| name             | string                               | Yes|Device name.     |
1324| manufacturerName | string                               | Yes| Device manufacturer.     |
1325| productName      | string                               | Yes|Product name.     |
1326| version          | string                               | Yes|Version number.       |
1327| vendorId         | number                               | Yes|Vendor ID.     |
1328| productId        | number                               | Yes|Product ID.     |
1329| clazz            | number                               | Yes|Device class.      |
1330| subClass         | number                               | Yes|Device subclass.     |
1331| protocol         | number                               | Yes|Device protocol code.    |
1332| configs          | Array&lt;[USBConfiguration](#usbconfiguration)&gt; | Yes|Device configuration descriptor information.|
1333
1334## USBDevicePipe
1335
1336Represents a USB device pipe, which is used to determine a USB device.
1337
1338**System capability**: SystemCapability.USB.USBManager
1339
1340| Name        | Type  | Mandatory   |Description   |
1341| ---------- | ------ | ----- |----- |
1342| busNum     | number |Yes| Bus address.|
1343| devAddress | number |Yes| Device address.|
1344
1345## USBControlParams<sup>(deprecated)</sup>
1346
1347Represents control transfer parameters.
1348
1349**NOTE**
1350
1351> This API is supported since API version 9 and deprecated since API version 18. You are advised to use [USBDeviceRequestParams](#usbdevicerequestparams12) instead.
1352
1353**System capability**: SystemCapability.USB.USBManager
1354
1355| Name     | Type                                           | Mandatory              |Description              |
1356| ------- | ----------------------------------------------- | ---------------- |---------------- |
1357| request | number                                          | Yes  |Request type.           |
1358| target  | [USBRequestTargetType](#usbrequesttargettype)   | Yes  |Request target type.         |
1359| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes  |Control request type.         |
1360| value   | number                                          | Yes  |Request parameter.           |
1361| index   | number                                          | Yes  |Index of the request parameter.|
1362| data    | Uint8Array                                      | Yes  |Buffer for writing or reading data.    |
1363
1364## USBDeviceRequestParams<sup>12+</sup>
1365
1366Represents control transfer parameters.
1367
1368**System capability**: SystemCapability.USB.USBManager
1369
1370| Name     | Type                                           | Mandatory              |Description              |
1371| ------- | ----------------------------------------------- | ---------------- |---------------- |
1372| bmRequestType | number                                    | Yes  |Control request type.           |
1373| bRequest  | number                                        | Yes  |Request type.         |
1374| wValue | number                                           | Yes  |Request parameter.         |
1375| wIndex   | number                                         | Yes  |Index of the request parameter.           |
1376| wLength   | number                                        | Yes  |Length of the requested data.|
1377| data    | Uint8Array                                      | Yes  |Buffer for writing or reading data.    |
1378
1379## USBRequestTargetType
1380
1381Enumerates request target types.
1382
1383**System capability**: SystemCapability.USB.USBManager
1384
1385| Name                        | Value  | Description  |
1386| ---------------------------- | ---- | ------ |
1387| USB_REQUEST_TARGET_DEVICE    | 0    | Device.|
1388| USB_REQUEST_TARGET_INTERFACE | 1    | Interface.|
1389| USB_REQUEST_TARGET_ENDPOINT  | 2    | Endpoint.|
1390| USB_REQUEST_TARGET_OTHER     | 3    | Other.|
1391
1392## USBControlRequestType
1393
1394Enumerates control request types.
1395
1396**System capability**: SystemCapability.USB.USBManager
1397
1398| Name                     | Value  | Description  |
1399| ------------------------- | ---- | ------ |
1400| USB_REQUEST_TYPE_STANDARD | 0    | Standard.|
1401| USB_REQUEST_TYPE_CLASS    | 1    | Class.  |
1402| USB_REQUEST_TYPE_VENDOR   | 2    | Vendor.|
1403
1404## USBRequestDirection
1405
1406Enumerates request directions.
1407
1408**System capability**: SystemCapability.USB.USBManager
1409
1410| Name                       | Value  | Description                    |
1411| --------------------------- | ---- | ------------------------ |
1412| USB_REQUEST_DIR_TO_DEVICE   | 0    | Request for writing data from the host to the device.|
1413| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.|
1414
1415## USBAccessory<sup>14+</sup>
1416
1417Describes the USB accessory information.
1418
1419**System capability**: SystemCapability.USB.USBManager
1420
1421| Name        | Type  | Mandatory| Description            |
1422| ------------ | ------ | ---- | ---------------- |
1423| manufacturer | string | Yes  | Manufacturer of an accessory.|
1424| product      | string | Yes  | Product type of an accessory.|
1425| description  | string | Yes  | Description of an accessory.    |
1426| version      | string | Yes  | Version of an accessory.    |
1427| serialNumber | string | Yes  | SN of an accessory.    |
1428
1429## USBAccessoryHandle<sup>14+</sup>
1430
1431Describes the USB accessory handle.
1432
1433**System capability**: SystemCapability.USB.USBManager
1434
1435| Name       | Type  | Mandatory| Description                                     |
1436| ----------- | ------ | ---- | ----------------------------------------- |
1437| accessoryFd | number | Yes  | Accessory file descriptor. A valid **accessoryFd** is a positive integer.|
1438
1439## UsbDataTransferParams<sup>18+</sup>
1440
1441As a USB data transfer interface, it is required for a client to initiate a transfer request.
1442
1443**System capability**: SystemCapability.USB.USBManager
1444
1445| Name        | Type  | Mandatory   |Description   |
1446| ---------- | ------ | ----- |----- |
1447| devPipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.|
1448| flags | [UsbTransferFlags](#usbtransferflags18) |Yes| USB transfer flag.|
1449| endpoint | number | Yes| Endpoint address, which is a positive integer.|
1450| type | [UsbEndpointTransferType](#usbendpointtransfertype18) |Yes| Transfer type.|
1451| timeout | number | Yes| Timeout duration, in ms.|
1452| length | number |Yes| Length of the data buffer, in bytes. The value must be a non-negative number (expected length).|
1453| callback | AsyncCallback<[SubmitTransferCallback](#submittransfercallback18)> |Yes| Information returned by the callback.|
1454| userData | Uint8Array | Yes| User data.|
1455| buffer | Uint8Array | Yes| Buffer, which is used to store data for read or write requests.|
1456| isoPacketCount | number | Yes| Number of data packets during real-time transfer, used only for I/Os with real-time transfer endpoints. The value must be a non-negative number.|
1457
1458## UsbTransferFlags<sup>18+</sup>
1459
1460Enumerates USB transfer flags.
1461
1462**System capability**: SystemCapability.USB.USBManager
1463
1464| Name                        | Value  | Description  |
1465| ---------------------------- | ---- | ------ |
1466| USB_TRANSFER_SHORT_NOT_OK    | 0    | Reports short frames as errors.|
1467| USB_TRANSFER_FREE_BUFFER | 1    | Automatically releases the transfer buffer.|
1468| USB_TRANSFER_FREE_TRANSFER  | 2    | Automatically transfers after the callback is complete.|
1469| USB_TRANSFER_ADD_ZERO_PACKET     | 3    | Adds an additional data packet to the transfer.|
1470
1471## UsbEndpointTransferType<sup>18+</sup>
1472
1473Enumerates USB transfer types.
1474
1475**System capability**: SystemCapability.USB.USBManager
1476
1477| Name                        | Value  | Description  |
1478| ---------------------------- | ---- | ------ |
1479| TRANSFER_TYPE_ISOCHRONOUS | 0x1    | Real-time transfer.|
1480| TRANSFER_TYPE_BULK  | 0x2    | Performs bulk transfer.|
1481| TRANSFER_TYPE_INTERRUPT     | 0x3    | Interrupt transfer.|
1482
1483## SubmitTransferCallback<sup>18+</sup>
1484
1485Transfers USB data packets in an asynchronous manner.
1486
1487**System capability**: SystemCapability.USB.USBManager
1488
1489| Name       | Type| Mandatory  | Description   |
1490| ---------- | ------ | ----- | ------ |
1491| actualLength | number |  Yes|Actual length of the read or written data, in bytes.|
1492| status | [UsbTransferStatus](#usbtransferstatus18) | Yes|Status after reading or writing is complete.|
1493| isoPacketDescs | Array<Readonly<[UsbIsoPacketDescriptor](#usbisopacketdescriptor18)>> | Yes|Packet information transferred in real time.|
1494
1495## UsbTransferStatus<sup>18+</sup>
1496
1497Enumerates the statuses returned by **libusb** through callback after the actual processing is complete.
1498
1499**System capability**: SystemCapability.USB.USBManager
1500
1501| Name                        | Value  | Description  |
1502| ---------------------------- | ---- | ------ |
1503| TRANSFER_COMPLETED    | 0    | Transfer completed.|
1504| TRANSFER_ERROR | 1    | Transfer failed.|
1505| TRANSFER_TIMED_OUT  | 2    | Transfer timeout.|
1506| TRANSFER_CANCELED     | 3    |Transfer canceled.|
1507| TRANSFER_STALL  | 4    | Transfer stalled (at bulk/interrupt endpoint).|
1508| TRANSFER_NO_DEVICE     | 5    | Device disconnected.|
1509| TRANSFER_OVERFLOW     | 6    | Data overflow.|
1510
1511## UsbIsoPacketDescriptor<sup>18+</sup>
1512
1513Describes packet information returned in real time by the transfer callback.
1514
1515**System capability**: SystemCapability.USB.USBManager
1516
1517| Name        | Type| Mandatory| Description   |
1518| ---------- | ------ | ----- | ------ |
1519| length | number | Yes|Expected length of the read or written data, in bytes.|
1520| actualLength | number| Yes|Actual length of the read or written data, in bytes.|
1521| status | [UsbTransferStatus](#usbtransferstatus18) | Yes|Status returned by callback.|
1522