• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# USB Serial Communication Management
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## Overview
11
12In the USB serial communication service, the USB port of the host is connected to the serial port of the serial port device for serial data transmission. The core objective of communication management is to implement efficient and stable data transmission and collaborative control between devices. It is mainly used in scenarios such as industrial automation and remote management, IoT device interconnection, and medical device management.
13
14## Preparing the Environment
15
16For details, see [Preparing the Environment](usbSerial-overview.md#preparing-the-environment) in *USB Serial Communication Development Overview*.
17
18## How to Develop
19
20### Available APIs
21
22| API                                                                         | Description                      |
23|------------------------------------------------------------------------------|--------------------------|
24| getPortList(): Readonly&lt;SerialPort&gt;[]                                        | Obtains the serial port device list.               |
25| hasSerialRight(portId: number): boolean                                      | Checks whether the application has the permission to access the serial port device.    |
26| requestSerialRight(portId: number): Promise&lt;boolean&gt;                         | Requests the permission to access the serial port device.           |
27| open(portId: number): void                                                   | Opens a serial port device.                 |
28| close(portId: number): void                                                  | Closes a serial port device.                 |
29| read(portId: number, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt;  | Reads data from a serial port device. This API uses a promise to return the result.|
30| readSync(portId: number, buffer: Uint8Array, timeout?: number): number       | Reads data from a serial port device in a synchronous manner.         |
31| write(portId: number, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt; | Writes data to a serial port device. This API uses a promise to return the result.|
32| writeSync(portId: number, buffer: Uint8Array, timeout?: number): number      | Writes data to a serial port device in a synchronous manner.         |
33
34
35### Development Procedure
36
37You can read and write data as follows:
38
39> **NOTE**
40>
41> The following sample code shows only a basic process. You should execute the code in a specific method.
42
431. Import the **usbManager** module.
44
45    ```ts
46    // Import the usbManager module.
47    import serial from '@ohos.usbManager.serial';
48    import { buffer } from '@kit.ArkTS';
49    ```
50
512. Obtain the USB device list.
52
53    ```ts
54    // Obtain the list of USB devices connected to the host.
55    let portList: serial.SerialPort[] = serial.getPortList();
56    console.info(`usbSerial portList: ${portList}`);
57    if (portList === undefined || portList.length === 0) {
58      console.error('usbSerial portList is empty');
59      return;
60    }
61    ```
62
633. Obtain the device operation permissions.
64
65    ```ts
66    // Check whether the first USB device in the list has the access permission.
67    // Name the function based on the specific service.
68    async function serialDefault() {
69      let portId: number = portList[0].portId;
70      if (!serial.hasSerialRight(portId)) {
71        await serial.requestSerialRight(portId).then(result => {
72          if(!result) {
73            // If the device does not have the access permission and is not granted by the user, the device exits.
74            console.error('The user does not have permission to perform this operation');
75            return;
76          }
77        });
78      }
79    }
80    ```
81
824. Open the device based on the serial port.
83
84    ```ts
85    try {
86      serial.open(portId)
87      console.info(`open usbSerial success, portId: ${portId}`);
88    } catch (error) {
89      console.error(`open usbSerial error: ${error}`);
90    }
91    ```
92
935. Read data through the serial port.
94
95    ```ts
96    // Read data asynchronously.
97    let readBuffer: Uint8Array = new Uint8Array(64);
98    serial.read(portId, readBuffer, 2000).then((size: number) => {
99      console.info(`read usbSerial success, readBuffer: ${readBuffer}`);
100    }).catch((error: Error) => {
101      console.error(`read usbSerial error: ${error}`);
102    })
103
104    // Read data synchronously.
105    let readSyncBuffer: Uint8Array = new Uint8Array(64);
106    try {
107      serial.readSync(portId, readSyncBuffer, 2000);
108      console.info(`readSync usbSerial success, readSyncBuffer: ${readSyncBuffer}`);
109    } catch (error) {
110      console.error(`readSync usbSerial error: ${error}`);
111    }
112    ```
113
1146. Write data through the serial port.
115
116    ```ts
117    // Write data asynchronously.
118    let writeBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer)
119    serial.write(portId, writeBuffer, 2000).then((size: number) => {
120      console.info(`write usbSerial success, writeBuffer: ${writeBuffer}`);
121    }).catch((error: Error) => {
122      console.error(`write usbSerial error: ${error}`);
123    })
124
125    // Write data synchronously.
126    let writeSyncBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer)
127    try {
128      serial.writeSync(portId, writeSyncBuffer, 2000);
129      console.info(`writeSync usbSerial success, writeSyncBuffer: ${writeSyncBuffer}`);
130    } catch (error) {
131      console.error(`writeSync usbSerial error: ${error}`);
132    }
133    ```
134
1357. Close a serial port device.
136
137    ```ts
138    try {
139      serial.close(portId);
140      console.info(`close usbSerial success, portId: ${portId}`);
141    } catch (error) {
142      console.error(`close usbSerial error: ${error}`);
143    }
144    ```
145
146### Debugging and Verification
147
1481. Prepare a USB-to-serial cable. Connect the USB port and the serial port of the cable to that of the OpenHarmony device.
1492. Execute the preceding sample code on the OpenHarmony device.
1503. Return **usbSerial success** if the related API is successfully called and the serial port communication of the device runs properly; return **usbSerial error** otherwise.
151