• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# USB Bulk Transfer
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
12Bulk transfer is used to transfer and receive a large amount of data without bandwidth or interval requirements, for example, file or image transfer. Devices such as printers and scanners support this type of transfer.
13
14## Preparing the Environment
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 a device to the PC.
38
39## How to Develop
40
41### Available APIs
42
43| API                                                                                                              | Description                   |
44|-------------------------------------------------------------------------------------------------------------------|-----------------------|
45| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise&lt;number&gt;  | Performs bulk transfer.                |
46
47For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md).
48
49### Development Procedure
50
51Connect a host to a device and use the **bulkTransfer** API to transfer data. The following steps describe how to implement a bulk transfer:
52
53> **NOTE**
54>
55> The following sample code shows only a basic process. You should execute the code in a specific method. When calling this method, you must comply with device protocols to ensure proper data transfer and device compatibility.
56
571. Import modules.
58
59   ```ts
60   // Import the usbManager module.
61   import { usbManager } from '@kit.BasicServicesKit';
62   import { BusinessError } from '@kit.BasicServicesKit';
63   ```
64
652. Obtain the USB device list.
66
67> **NOTE**
68>
69> Bulk transfer can be performed only on the endpoint whose [transfer type](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md#usbendpointtransfertype18) is **2**. If an incorrect endpoint type is used, an I/O error is returned.
70
71   ```ts
72   // Obtain the USB device list.
73   let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices();
74   console.info(`deviceList: ${deviceList}`);
75   if(deviceList.length === 0) {
76     console.error('deviceList is empty');
77     return;
78   }
79   /*
80   Example deviceList structure:
81   [
82     {
83       name: "1-1",
84       serial: "",
85       manufacturerName: "",
86       productName: "",
87       version: "",
88       vendorId: 7531,
89       productId: 2,
90       clazz: 9,
91       subClass: 0,
92       protocol: 1,
93       devAddress: 1,
94       busNum: 1,
95       configs: [
96         {
97           id: 1,
98           attributes: 224,
99           isRemoteWakeup: true,
100           isSelfPowered: true,
101           maxPower: 0,
102           name: "1-1",
103           interfaces: [
104             {
105               id: 0,
106               protocol: 0,
107               clazz: 9,
108               subClass: 0,
109               alternateSetting: 0,
110               name: "1-1",
111               endpoints: [
112                 {
113                   address: 129,
114                   attributes: 3,
115                   interval: 12,
116                   maxPacketSize: 4,
117                   direction: 128,
118                   number: 1,
119                   type: 2, // Determine the transfer type.
120                   interfaceId: 0,
121                 }
122               ]
123             }
124           ]
125         }
126       ]
127     }
128   ]
129   */
130   ```
131
1323. Obtain the device operation permissions.
133
134   ```ts
135   let deviceName : string = deviceList[0].name;
136   // Request the permissions to operate a specified device.
137   usbManager.requestRight(deviceName).then((hasRight : boolean) => {
138     console.info(`usb device request right result: ${hasRight}`);
139   }).catch((error : BusinessError)=> {
140     console.error(`usb device request right failed : ${error}`);
141   });
142   ```
143
1444. Open the device.
145
146   ```ts
147   // Open the device, and obtain the USB device pipe for data transfer.
148   let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]);
149   let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0];
150   /*
151    Claim the corresponding interface from deviceList.
152   interface1 must be one present in the device configuration.
153   */
154   usbManager.claimInterface(pipe, interface1, true);
155   ```
156
1575. Perform data transfer.
158
159**NOTE**
160
161> Before data transfer, you are advised to obtain the **type** of the **endpoint** to which the **interface** belongs and determine whether the **interface** supports the required transfer type.
162>
163> If the transfer API fails to be called, check whether the device interface supports [alternateSetting](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md#usbinterface). If it is supported, you can call [usbManager.setInterface](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md#usbmanagersetinterface) to reset the **interface** before data transfer to match the endpoint with the transfer type, ensuring normal communications.
164
165    ```ts
166    /*
167      Read data. Select the corresponding RX endpoint from deviceList for data transfer.
168    (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array.
169    */
170    let inEndpoint : usbManager.USBEndpoint = interface1.endpoints[2];
171    let outEndpoint : usbManager.USBEndpoint = interface1.endpoints[1];
172    let dataUint8Array : Uint8Array = new Uint8Array(1024);
173    usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => {
174    if (dataLength >= 0) {
175      console.info(`usb readData result Length : ${dataLength}`);
176    } else {
177      console.error("usb readData failed");
178    }
179    }).catch((error : BusinessError) => {
180    console.error(`usb readData error : ${error}`);
181    });
182    // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0)
183    usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => {
184      if (dataLength >= 0) {
185        console.info(`usb writeData result write length : ${dataLength}`);
186      } else {
187        console.error("usb writeData failed");
188      }
189    }).catch((error : BusinessError) => {
190      console.error(`usb writeData error : ${error}`);
191    });
192    ```
193
1946. Release the USB interface, and close the USB device pipe.
195
196   ```ts
197   usbManager.releaseInterface(pipe, interface1);
198   usbManager.closePipe(pipe);
199   ```
200