• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# USB Isochronous Transfer
2
3## When to Use
4
5Isochronous transfer is a transfer mode in which data is transferred in a fixed time window through the USB protocol. This ensures the timing stability and low latency of data streams, but allows a small amount of data loss (such as video frame loss and audio noise). This transfer mode is applicable to scenarios that have high requirements on continuity and fault tolerance, such as USB headsets, USB speakers, and video conferencing devices.
6
7## Preparing the Environment
8
9### Environment Requirements
10
11- Development tool and configuration:
12
13  DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14).
14
15
16- SDK version configuration:
17
18  The ArkTs APIs for peripheral management can be used only when the SDK is of API version 16 or later.
19
20
21- HDC configuration:
22
23  HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5).
24
25### Environment Setup
26
27- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC.
28- Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md).
29- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5).
30- Use a USB cable to connect an OpenHarmony device to the PC.
31
32## How to Develop
33
34### Available APIs
35
36| API                                                                                                             | Description                                                     |
37|------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------|
38| usbSubmitTransfer(transfer: UsbDataTransferParams): void                                                         | Submits isochronous, bulk, or interrupt transfer in an asynchronous manner.                                  |
39| usbCancelTransfer(transfer: UsbDataTransferParams): void                                                         | Cancels the submitted asynchronous transfer.                                            |
40
41For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md).
42
43### How to Develop
44
45Connect a host to a device and use the **usbSubmitTransfer** API to transfer data. The following steps describe how to implement an interrupt transfer:
46
471. Import modules.
48
49    ```ts
50    // Import the usbManager module.
51    import { usbManager } from '@kit.BasicServicesKit';
52    ```
53
542. Obtain the USB device list.
55
56    ```ts
57    // Obtain the list of USB devices connected to the host.
58    let usbDevices: Array<usbManager.USBDevice> = usbManager.getDevices();
59    console.info('usbDevices: ', JSON.stringify(usbDevices));
60    if(usbDevices.length === 0) {
61      console.info('usbDevices is empty');
62      return;
63    }
64    ```
65
663. Obtain the device operation permissions.
67
68    ```ts
69    // Check whether the first USB device in the list has the access permission.
70    let usbDevice: usbManager.USBDevice = usbDevices[0];
71    if(!usbManager.hasRight(usbDevice.name)) {
72      await usbManager.requestRight(usbDevice.name).then(result => {
73        if(!result) {
74          // If the USB device does not have the access permission and is not granted by the user, the device exits.
75          console.info('user is not granted the operation permission');
76          return;
77        }
78      });
79    }
80    ```
81
824. Obtain the endpoint for reading data through interrupt transfer.
83
84   ```ts
85   let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(usbDevice);
86   let usbConfigs: usbManager.USBConfiguration[] = usbDevice.configs;
87   let usbInterfaces: usbManager.USBInterface[] = [];
88   let usbInterface: usbManager.USBInterface | undefined = undefined
89   let usbEndpoints: usbManager.USBEndpoint[] = [];
90   let usbEndprint: usbManager.USBEndpoint | undefined = undefined
91   for (let i = 0; i < usbConfigs.length; i++) {
92     usbInterfaces = usbConfigs[i].interfaces;
93     for (let i = 0; i < usbInterfaces.length; i++) {
94       usbEndpoints = usbInterfaces[i].endpoints;
95       usbEndprint = usbEndpoints.find((value) => {
96         // direction indicates the request direction. The value 0 indicates the written data, and the value 128 indicates the read data.
97         return value.direction === 128 && value.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS;
98       })
99       if (usbEndprint !== undefined) {
100         usbInterface = usbInterfaces[i];
101         break;
102       }
103     }
104   }
105   if (usbEndprint === undefined) {
106     console.error(`get usbEndprint error`)
107     return;
108   }
109   ```
110
1115. Connect to the device and register the communication interface.
112
113    ```ts
114    // Register a communication interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned.
115    let claimInterfaceResult: number = usbManager.claimInterface(devicePipe, usbInterface, true);
116    if (claimInterfaceResult !== 0) {
117      console.error(`claimInterface error = ${claimInterfaceResult}`)
118      return;
119    }
120
121    // When the transfer is of the isochronous type, you need to register a device interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned.
122    if (this.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS) {
123      let setInterfaceResult = usbManager.setInterface(devicePipe, usbInterface);
124      if (setInterfaceResult !== 0) {
125        console.info(`setInterfaceResult error = ${setInterfaceResult}`)
126        return;
127      }
128    }
129    ```
130
1316. Perform data transfer.
132
133   ```ts
134   try {
135     // The communication interface is successfully registered and performs data transfer.
136     let transferParams: usbManager.UsbDataTransferParams = {
137       devPipe: devicePipe,
138       flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK,
139       endpoint: usbEndprint.address,
140       type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS,
141       timeout: 2000,
142       length: 10,
143       callback: () => {},
144       userData: new Uint8Array(10),
145       buffer: new Uint8Array(10),
146       isoPacketCount: 2,
147     };
148
149     transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => {
150       console.info('callBackData = ' + JSON.stringify(callBackData));
151       console.info('transfer success, result = ' + transferParams.buffer.toString());
152     }
153     usbManager.usbSubmitTransfer(transferParams);
154     console.info('USB transfer request submitted.');
155   } catch (error) {
156     console.error('USB transfer failed:', error);
157   }
158   ```
159
1607. Cancels the data transfer, releases the interface, and closes the USB device pipe.
161
162    ```ts
163    usbManager.usbCancelTransfer(transferParams);
164    usbManager.releaseInterface(devicePipe, usbInterface);
165    usbManager.closePipe(devicePipe);
166    ```
167
168### Verification
169
1701. Connect the host to a device (such as a USB headset) that supports isochronous transfer through a USB interface.
1712. Execute the preceding code.
1723. Search for the keyword **transfer success** in the log. If the keyword is found, the isochronous transfer interface is successfully called.
173