• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.usbManager.serial (Serial Port 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
10This module provides the serial port management functions, including enabling and disabling the serial port of the device, writing and reading data, setting and obtaining the configuration parameters of the serial port, and managing permissions.
11
12> **NOTE**
13>
14> The initial APIs of this module are supported since API version 19. Newly added APIs will be marked with a superscript to indicate their earliest API version.
15
16## Modules to Import
17
18```ts
19import { serialManager } from '@kit.BasicServicesKit';
20```
21
22## serialManager.getPortList
23
24getPortList(): Readonly&lt;SerialPort&gt;[]
25
26Obtains the serial port device list, including the device name and port number.
27
28**System capability**: SystemCapability.USB.USBManager.Serial
29
30**Returns**
31
32| Type                                       | Description         |
33|-------------------------------------------|-------------|
34| Readonly&lt;[SerialPort](#serialport)&gt;[] | Serial port information list.|
35
36**Example**
37
38> **NOTE**
39>
40> The following sample code shows the basic process for calling the **getPortList** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
41
42<!--code_no_check-->
43```ts
44import { JSON } from '@kit.ArkTS';
45import { serialManager } from '@kit.BasicServicesKit';
46
47// Obtain the serial port device list.
48let portList: serialManager.SerialPort[] = serialManager.getPortList();
49console.info('usbSerial portList: ' + JSON.stringify(portList));
50if (portList === undefined || portList.length === 0) {
51  console.info('usbSerial portList is empty');
52  return;
53}
54let portId: number = portList[0].portId;
55```
56
57## serialManager.hasSerialRight
58
59hasSerialRight(portId: number): boolean
60
61Checks whether the application has the permission to access the serial port device. When an application is restarted after exits, you need to request the permission from the user again.
62
63**System capability**: SystemCapability.USB.USBManager.Serial
64
65**Parameters**
66
67| Name   | Type    | Mandatory| Description                                 |
68|--------|--------|----|-------------------------------------|
69| portId | number | Yes | Port number.|
70
71**Returns**
72
73| Type     | Description              |
74|---------|------------------|
75| boolean | The value **true** indicates that the permission is authorized, and **false** indicates the opposite.|
76
77**Error codes**
78
79For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
80
81| ID| Error Message                                                    |
82| -------- | ------------------------------------------------------------ |
83| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
84| 14400005 | Database operation exception. |
85| 31400001 | Serial port management exception. |
86| 31400003 | PortId does not exist. |
87
88**Example**
89
90> **NOTE**
91>
92> The following sample code shows the basic process for calling the **hasSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
93
94<!--code_no_check-->
95```ts
96import { JSON } from '@kit.ArkTS';
97import { serialManager } from '@kit.BasicServicesKit';
98
99// Obtain the serial port list.
100let portList: serialManager.SerialPort[] = serialManager.getPortList();
101console.info('portList: ', JSON.stringify(portList));
102if (portList === undefined || portList.length === 0) {
103  console.info('portList is empty');
104  return;
105}
106let portId: number = portList[0].portId;
107
108// Check whether the device can be accessed by the application.
109if (serialManager.hasSerialRight(portId)) {
110  console.info('The serial port is accessible');
111} else {
112  console.info('No permission to access the serial port');
113}
114```
115
116## serialManager.requestSerialRight
117
118requestSerialRight(portId: number): Promise&lt;boolean&gt;
119
120Requests the permission for the application to access the serial port device. After the application exits, the access permission on the serial port device is automatically removed. After the application is restarted, you need to request the permission again.
121
122**System capability**: SystemCapability.USB.USBManager.Serial
123
124**Parameters**
125
126| Name   | Type    | Mandatory| Description                                 |
127|--------|--------|----|-------------------------------------|
128| portId | number | Yes | Port number.|
129
130**Returns**
131
132| Type                    | Description           |
133|------------------------|---------------|
134| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the permission is successfully requested, and **false** indicates the opposite.|
135
136**Error codes**
137
138For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
139
140| ID| Error Message                                                    |
141| -------- | ------------------------------------------------------------ |
142| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
143| 14400005 | Database operation exception. |
144| 31400001 | Serial port management exception. |
145| 31400003 | PortId does not exist. |
146
147**Example**
148
149> **NOTE**
150>
151> The following sample code shows the basic process for calling the **requestSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
152
153<!--code_no_check-->
154```ts
155import { JSON } from '@kit.ArkTS';
156import { serialManager } from '@kit.BasicServicesKit';
157
158// Obtain the serial port list.
159let portList: serialManager.SerialPort[] = serialManager.getPortList();
160console.info('usbSerial portList: ' + JSON.stringify(portList));
161if (portList === undefined || portList.length === 0) {
162  console.info('usbSerial portList is empty');
163  return;
164}
165let portId: number = portList[0].portId;
166
167// Check whether the device can be accessed by the application.
168if (!serialManager.hasSerialRight(portId)) {
169  serialManager.requestSerialRight(portId).then(result => {
170    if (!result) {
171      // If the application does not have the access permission and is not granted by the user, the application exits.
172      console.info('user is not granted the operation permission');
173      return;
174    } else {
175      console.info('grant permission successfully');
176    }
177  });
178}
179```
180
181## serialManager.open
182
183open(portId: number): void
184
185Opens a serial port device.
186
187**System capability**: SystemCapability.USB.USBManager.Serial
188
189**Parameters**
190
191| Name   | Type    | Mandatory| Description         |
192|--------|--------|----|-------------|
193| portId | number | Yes | Port number.|
194
195**Error codes**
196
197For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
198
199| ID| Error Message                                                    |
200| -------- | ------------------------------------------------------------ |
201| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
202| 31400001 | Serial port management exception. |
203| 31400002 | Access denied. Call requestSerialRight to request user authorization first. |
204| 31400003 | PortId does not exist. |
205| 31400004 | The serial port device is occupied. |
206
207**Example**
208
209> **NOTE**
210>
211> The following sample code shows the basic process for calling the **open** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
212
213<!--code_no_check-->
214```ts
215import { JSON } from '@kit.ArkTS';
216import { serialManager } from '@kit.BasicServicesKit';
217
218// Obtain the serial port list.
219let portList: serialManager.SerialPort[] = serialManager.getPortList();
220console.info('usbSerial portList: ' + JSON.stringify(portList));
221if (portList === undefined || portList.length === 0) {
222  console.info('usbSerial portList is empty');
223  return;
224}
225let portId: number = portList[0].portId;
226
227// Check whether the device can be accessed by the application.
228if (!serialManager.hasSerialRight(portId)) {
229  serialManager.requestSerialRight(portId).then(result => {
230    if (!result) {
231      // If the application does not have the access permission and is not granted by the user, the application exits.
232      console.info('user is not granted the operation  permission');
233      return;
234    } else {
235      console.info('grant permission successfully');
236    }
237  });
238}
239
240// Open a serial port device.
241try {
242  serialManager.open(portId)
243  console.info('open usbSerial success, portId: ' + portId);
244} catch (error) {
245  console.error('open usbSerial error, ' + JSON.stringify(error));
246}
247```
248
249## serialManager.getAttribute
250
251getAttribute(portId: number): Readonly&lt;[SerialAttribute](#serialattribute)&gt;
252
253Obtains the configuration parameters of a specified serial port.
254
255**System capability**: SystemCapability.USB.USBManager.Serial
256
257**Parameters**
258
259| Name   | Type    | Mandatory| Description         |
260|--------|--------|----|-------------|
261| portId | number | Yes | Port number.|
262
263**Returns**
264
265| Type    | Description         |
266|--------|-------------|
267| Readonly&lt;[SerialAttribute](#serialattribute)&gt; | Configuration parameters of the serial port.|
268
269**Error codes**
270
271For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
272
273| ID| Error Message                                                    |
274| -------- | ------------------------------------------------------------ |
275| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
276| 31400001 | Serial port management exception. |
277| 31400003 | PortId does not exist. |
278| 31400005 | The serial port device is not opened. Call the open API first. |
279
280**Example**
281
282> **NOTE**
283>
284> The following sample code shows the basic process for calling the **getAttribute** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
285
286<!--code_no_check-->
287```ts
288import { JSON } from '@kit.ArkTS';
289import { serialManager } from '@kit.BasicServicesKit';
290
291// Obtain the serial port list.
292let portList: serialManager.SerialPort[] = serialManager.getPortList();
293console.info('usbSerial portList: ' + JSON.stringify(portList));
294if (portList === undefined || portList.length === 0) {
295  console.info('usbSerial portList is empty');
296  return;
297}
298let portId: number = portList[0].portId;
299
300// Check whether the device can be accessed by the application.
301if (!serialManager.hasSerialRight(portId)) {
302  serialManager.requestSerialRight(portId).then(result => {
303    if (!result) {
304      // If the application does not have the access permission and is not granted by the user, the application exits.
305      console.info('user is not granted the operation  permission');
306      return;
307    } else {
308      console.info('grant permission successfully');
309    }
310  });
311}
312
313// Open a serial port device.
314try {
315  serialManager.open(portId)
316  console.info('open usbSerial success, portId: ' + portId);
317} catch (error) {
318  console.error('open usbSerial error, ' + JSON.stringify(error));
319  return;
320}
321
322// Obtain the serial port configuration.
323try {
324  let attribute: serialManager.SerialAttribute = serialManager.getAttribute(portId);
325  if (attribute === undefined) {
326    console.error('getAttribute usbSerial error, attribute is undefined');
327  } else {
328    console.info('getAttribute usbSerial success, attribute: ' + JSON.stringify(attribute));
329  }
330} catch (error) {
331  console.error('getAttribute usbSerial error, ' + JSON.stringify(error));
332}
333```
334
335## serialManager.setAttribute
336
337setAttribute(portId: number, attribute: [SerialAttribute](#serialattribute)): void
338
339Sets the parameters of the serial port. If this method is not called, the default configuration parameters are used (baud rate: 9600 bit/s; data bit: 8; parity bit: 0; stop bit: 1).
340
341**System capability**: SystemCapability.USB.USBManager.Serial
342
343**Parameters**
344
345| Name      | Type                                 | Mandatory| Description         |
346|-----------|-------------------------------------|----|-------------|
347| portId    | number                              | Yes | Port number.|
348| attribute | [SerialAttribute](#serialattribute) | Yes | Configuration parameters of the serial port.    |
349
350**Error codes**
351
352For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
353
354| ID| Error Message                                                    |
355| -------- | ------------------------------------------------------------ |
356| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
357| 31400001 | Serial port management exception. |
358| 31400003 | PortId does not exist. |
359| 31400005 | The serial port device is not opened. Call the open API first. |
360
361**Example**
362
363> **NOTE**
364>
365> The following sample code shows the basic process for calling the **setAttribute** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
366
367<!--code_no_check-->
368```ts
369import { JSON } from '@kit.ArkTS';
370import { serialManager } from '@kit.BasicServicesKit';
371
372// Obtain the serial port list.
373let portList: serialManager.SerialPort[] = serialManager.getPortList();
374console.info('usbSerial portList: ' + JSON.stringify(portList));
375if (portList === undefined || portList.length === 0) {
376  console.info('usbSerial portList is empty');
377  return;
378}
379let portId: number = portList[0].portId;
380
381// Check whether the device can be accessed by the application.
382if (!serialManager.hasSerialRight(portId)) {
383  serialManager.requestSerialRight(portId).then(result => {
384    if (!result) {
385      // If the application does not have the access permission and is not granted by the user, the application exits.
386      console.info('user is not granted the operation  permission');
387      return;
388    } else {
389      console.info('grant permission successfully');
390    }
391  });
392}
393
394// Open a serial port device.
395try {
396  serialManager.open(portId)
397  console.info('open usbSerial success, portId: ' + portId);
398} catch (error) {
399  console.error('open usbSerial error, ' + JSON.stringify(error));
400  return;
401}
402
403// Set the serial port configuration.
404try {
405  let attribute: serialManager.SerialAttribute = {
406    baudRate: serialManager.BaudRates.BAUDRATE_9600,
407    dataBits: serialManager.DataBits.DATABIT_8,
408    parity: serialManager.Parity.PARITY_NONE,
409    stopBits: serialManager.StopBits.STOPBIT_1
410  }
411  serialManager.setAttribute(portId, attribute);
412  console.info('setAttribute usbSerial success, attribute: ' + JSON.stringify(attribute));
413} catch (error) {
414  console.error('setAttribute usbSerial error, ' + JSON.stringify(error));
415}
416```
417
418## serialManager.read
419
420read(portId: number, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt;
421
422Reads data from the serial port device asynchronously.
423
424**System capability**: SystemCapability.USB.USBManager.Serial
425
426**Parameters**
427
428| Name    | Type        | Mandatory| Description              |
429|---------|------------|----|------------------|
430| portId  | number     | Yes | Port number.     |
431| buffer  | Uint8Array | Yes | Buffer for reading data.|
432| timeout | number     | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.|
433
434**Returns**
435
436| Type                   | Description            |
437|-----------------------|----------------|
438| Promise&lt;number&gt; | Promise used to return the length of the data read.|
439
440**Error codes**
441
442For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
443
444| ID| Error Message                                                    |
445| -------- | ------------------------------------------------------------ |
446| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
447| 31400001 | Serial port management exception. |
448| 31400003 | PortId does not exist. |
449| 31400005 | The serial port device is not opened. Call the open API first. |
450| 31400006 | Data transfer timed out. |
451| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. |
452
453**Example**
454
455> **NOTE**
456>
457> The following sample code shows the basic process for calling the **read** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
458
459<!--code_no_check-->
460```ts
461import { JSON } from '@kit.ArkTS';
462import { serialManager } from '@kit.BasicServicesKit';
463
464// Obtain the serial port list.
465let portList: serialManager.SerialPort[] = serialManager.getPortList();
466console.info('usbSerial portList: ' + JSON.stringify(portList));
467if (portList === undefined || portList.length === 0) {
468  console.info('usbSerial portList is empty');
469  return;
470}
471let portId: number = portList[0].portId;
472
473// Check whether the device can be accessed by the application.
474if (!serialManager.hasSerialRight(portId)) {
475  serialManager.requestSerialRight(portId).then(result => {
476    if (!result) {
477      // If the application does not have the access permission and is not granted by the user, the application exits.
478      console.info('user is not granted the operation  permission');
479      return;
480    } else {
481      console.info('grant permission successfully');
482    }
483  });
484}
485
486// Open a serial port device.
487try {
488  serialManager.open(portId)
489  console.info('open usbSerial success, portId: ' + portId);
490} catch (error) {
491  console.error('open usbSerial error, ' + JSON.stringify(error));
492}
493
494// Read data asynchronously.
495let readBuffer: Uint8Array = new Uint8Array(64);
496serialManager.read(portId, readBuffer, 2000).then((size: number) => {
497  console.info('read usbSerial success, readBuffer: ' + readBuffer.toString());
498}).catch((error: Error) => {
499  console.error('read usbSerial error, ' + JSON.stringify(error));
500})
501```
502
503## serialManager.readSync
504
505readSync(portId: number, buffer: Uint8Array, timeout?: number): number
506
507Reads data from the serial port device synchronously.
508
509**System capability**: SystemCapability.USB.USBManager.Serial
510
511**Parameters**
512
513| Name    | Type        | Mandatory| Description              |
514|---------|------------|----|------------------|
515| portId  | number     | Yes | Port number.|
516| buffer  | Uint8Array | Yes | Buffer for reading data.|
517| timeout | number     | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.|
518
519**Returns**
520
521| Type    | Description         |
522|--------|-------------|
523| number | Length of the data read.|
524
525**Error codes**
526
527For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
528
529| ID| Error Message                                                    |
530| -------- | ------------------------------------------------------------ |
531| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
532| 31400001 | Serial port management exception. |
533| 31400003 | PortId does not exist. |
534| 31400005 | The serial port device is not opened. Call the open API first. |
535| 31400006 | Data transfer timed out. |
536| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. |
537
538**Example**
539
540> **NOTE**
541>
542> The following sample code shows the basic process for calling the **readSync** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
543
544<!--code_no_check-->
545```ts
546import { JSON } from '@kit.ArkTS';
547import { serialManager } from '@kit.BasicServicesKit';
548
549// Obtain the serial port list.
550let portList: serialManager.SerialPort[] = serialManager.getPortList();
551console.info('usbSerial portList: ' + JSON.stringify(portList));
552if (portList === undefined || portList.length === 0) {
553  console.info('usbSerial portList is empty');
554  return;
555}
556let portId: number = portList[0].portId;
557
558// Check whether the device can be accessed by the application.
559if (!serialManager.hasSerialRight(portId)) {
560  serialManager.requestSerialRight(portId).then(result => {
561    if (!result) {
562      // If the application does not have the access permission and is not granted by the user, the application exits.
563      console.info('user is not granted the operation  permission');
564      return;
565    } else {
566      console.info('grant permission successfully');
567    }
568  });
569}
570
571// Open a serial port device.
572try {
573  serialManager.open(portId)
574  console.info('open usbSerial success, portId: ' + portId);
575} catch (error) {
576  console.error('open usbSerial error, ' + JSON.stringify(error));
577}
578
579// Read data synchronously.
580let readSyncBuffer: Uint8Array = new Uint8Array(64);
581try {
582  serialManager.readSync(portId, readSyncBuffer, 2000);
583  console.info('readSync usbSerial success, readSyncBuffer: ' + readSyncBuffer.toString());
584} catch (error) {
585  console.error('readSync usbSerial error, ' + JSON.stringify(error));
586}
587```
588
589## serialManager.write
590
591write(portId: number, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt;
592
593Writes data to the serial port device asynchronously.
594
595**System capability**: SystemCapability.USB.USBManager.Serial
596
597**Parameters**
598
599| Name    | Type        | Mandatory| Description              |
600|---------|------------|----|------------------|
601| portId  | number     | Yes | Port number.     |
602| buffer  | Uint8Array | Yes | Buffer for writing data.|
603| timeout | number     | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.|
604
605**Returns**
606
607| Type                   | Description         |
608|-----------------------|-------------|
609| Promise&lt;number&gt; | Promise used to return the length of the data written.|
610
611**Error codes**
612
613For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
614
615| ID| Error Message                                                    |
616| -------- | ------------------------------------------------------------ |
617| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
618| 31400001 | Serial port management exception. |
619| 31400003 | PortId does not exist. |
620| 31400005 | The serial port device is not opened. Call the open API first. |
621| 31400006 | Data transfer timed out. |
622| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. |
623
624**Example**
625
626> **NOTE**
627>
628> The following sample code shows the basic process for calling the **addSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
629
630<!--code_no_check-->
631```ts
632import { JSON } from '@kit.ArkTS';
633import { serialManager } from '@kit.BasicServicesKit';
634
635// Obtain the serial port list.
636let portList: serialManager.SerialPort[] = serialManager.getPortList();
637console.info('usbSerial portList: ' + JSON.stringify(portList));
638if (portList === undefined || portList.length === 0) {
639  console.info('usbSerial portList is empty');
640  return;
641}
642let portId: number = portList[0].portId;
643
644// Check whether the device can be accessed by the application.
645if (!serialManager.hasSerialRight(portId)) {
646  serialManager.requestSerialRight(portId).then(result => {
647    if (!result) {
648      // If the application does not have the access permission and is not granted by the user, the application exits.
649      console.info('user is not granted the operation  permission');
650      return;
651    } else {
652      console.info('grant permission successfully');
653    }
654  });
655}
656
657// Open a serial port device.
658try {
659  serialManager.open(portId)
660  console.info('open usbSerial success, portId: ' + portId);
661} catch (error) {
662  console.error('open usbSerial error, ' + JSON.stringify(error));
663}
664
665// Write data asynchronously.
666let writeBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer)
667serialManager.write(portId, writeBuffer, 2000).then((size: number) => {
668  console.info('write usbSerial success, writeBuffer: ' + writeBuffer.toString());
669}).catch((error: Error) => {
670  console.error('write usbSerial error, ' + JSON.stringify(error));
671})
672```
673
674## serialManager.writeSync
675
676writeSync(portId: number, buffer: Uint8Array, timeout?: number): number
677
678Writes data to the serial port device synchronously.
679
680**System capability**: SystemCapability.USB.USBManager.Serial
681
682**Parameters**
683
684| Name    | Type        | Mandatory| Description              |
685|---------|------------|----|------------------|
686| portId  | number     | Yes | Port number.    |
687| buffer  | Uint8Array | Yes | Destination buffer for writing data.|
688| timeout | number     | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.|
689
690**Returns**
691
692| Type    | Description         |
693|--------|-------------|
694| number | Length of the data written.|
695
696**Error codes**
697
698For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
699
700| ID| Error Message                                                    |
701| -------- | ------------------------------------------------------------ |
702| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
703| 31400001 | Serial port management exception. |
704| 31400003 | PortId does not exist. |
705| 31400005 | The serial port device is not opened. Call the open API first. |
706| 31400006 | Data transfer timed out. |
707| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. |
708
709**Example**
710
711> **NOTE**
712>
713> The following sample code shows the basic process for calling the **writeSync** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
714
715<!--code_no_check-->
716```ts
717import { JSON } from '@kit.ArkTS';
718import { serialManager } from '@kit.BasicServicesKit';
719
720// Obtain the serial port list.
721let portList: serialManager.SerialPort[] = serialManager.getPortList();
722console.info('usbSerial portList: ' + JSON.stringify(portList));
723if (portList === undefined || portList.length === 0) {
724  console.info('usbSerial portList is empty');
725  return;
726}
727let portId: number = portList[0].portId;
728
729// Check whether the device can be accessed by the application.
730if (!serialManager.hasSerialRight(portId)) {
731  serialManager.requestSerialRight(portId).then(result => {
732    if (!result) {
733      // If the application does not have the access permission and is not granted by the user, the application exits.
734      console.info('user is not granted the operation  permission');
735      return;
736    } else {
737      console.info('grant permission successfully');
738    }
739  });
740}
741
742// Open a serial port device.
743try {
744  serialManager.open(portId)
745  console.info('open usbSerial success, portId: ' + portId);
746} catch (error) {
747  console.error('open usbSerial error, ' + JSON.stringify(error));
748}
749
750// Write data synchronously.
751let writeSyncBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer)
752try {
753  serialManager.writeSync(portId, writeSyncBuffer, 2000);
754  console.info('writeSync usbSerial success, writeSyncBuffer: ' + writeSyncBuffer.toString());
755} catch (error) {
756  console.error('writeSync usbSerial error, ' + JSON.stringify(error));
757}
758```
759
760## serialManager.close
761
762close(portId: number): void
763
764Closes the serial port device.
765
766**System capability**: SystemCapability.USB.USBManager.Serial
767
768**Parameters**
769
770| Name   | Type    | Mandatory| Description         |
771|--------|--------|----|-------------|
772| portId | number | Yes | Port number.|
773
774**Error codes**
775
776For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
777
778| ID| Error Message                                                    |
779| -------- | ------------------------------------------------------------ |
780| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
781| 31400001 | Serial port management exception. |
782| 31400003 | PortId does not exist. |
783| 31400005 | The serial port device is not opened. Call the open API first. |
784
785**Example**
786
787> **NOTE**
788>
789> The following sample code shows the basic process for calling the **close** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
790
791<!--code_no_check-->
792```ts
793import { JSON } from '@kit.ArkTS';
794import { serialManager } from '@kit.BasicServicesKit';
795
796// Obtain the serial port list.
797let portList: serialManager.SerialPort[] = serialManager.getPortList();
798console.info('usbSerial portList: ' + JSON.stringify(portList));
799if (portList === undefined || portList.length === 0) {
800  console.info('usbSerial portList is empty');
801  return;
802}
803let portId: number = portList[0].portId;
804
805// Check whether the device can be accessed by the application.
806if (!serialManager.hasSerialRight(portId)) {
807  serialManager.requestSerialRight(portId).then(result => {
808    if (!result) {
809      // If the application does not have the access permission and is not granted by the user, the application exits.
810      console.info('user is not granted the operation  permission');
811      return;
812    } else {
813      console.info('grant permission successfully');
814    }
815  });
816}
817
818// Open a serial port device.
819try {
820  serialManager.open(portId)
821  console.info('open usbSerial success, portId: ' + portId);
822} catch (error) {
823  console.error('open usbSerial error, ' + JSON.stringify(error));
824  return;
825}
826
827// Close the serial port device.
828try {
829  serialManager.close(portId);
830  console.info('close usbSerial success, portId: ' + portId);
831} catch (error) {
832  console.error('close usbSerial error, ' + JSON.stringify(error));
833}
834```
835
836## serialManager.cancelSerialRight
837
838cancelSerialRight(portId: number): void
839
840Cancels the permission to access the serial port device when the application is running. This API is used to close the enabled serial port device.
841
842**System capability**: SystemCapability.USB.USBManager.Serial
843
844**Parameters**
845
846| Name   | Type    | Mandatory| Description                                 |
847|--------|--------|----|-------------------------------------|
848| portId | number | Yes | Port number.|
849
850**Error codes**
851
852For details about the error codes, see [USB Service Error Codes](errorcode-usb.md).
853
854| ID| Error Message                                                    |
855| -------- | ------------------------------------------------------------ |
856| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
857| 14400005 | Database operation exception.                                |
858| 31400001 | Serial port management exception. |
859| 31400002 | Access denied. Call requestSerialRight to request user authorization first. |
860| 31400003 | PortId does not exist. |
861
862**Example**
863
864> **NOTE**
865>
866> The following sample code shows the basic process for calling the **cancelSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols.
867
868<!--code_no_check-->
869```ts
870import { JSON } from '@kit.ArkTS';
871import { serialManager } from '@kit.BasicServicesKit';
872
873// Obtain the serial port list.
874let portList: serialManager.SerialPort[] = serialManager.getPortList();
875console.info('usbSerial portList: ' + JSON.stringify(portList));
876if (portList === undefined || portList.length === 0) {
877  console.info('usbSerial portList is empty');
878  return;
879}
880let portId: number = portList[0].portId;
881
882// Check whether the device can be accessed by the application.
883if (!serialManager.hasSerialRight(portId)) {
884  serialManager.requestSerialRight(portId).then(result => {
885    if (!result) {
886      // If the application does not have the access permission and is not granted by the user, the application exits.
887      console.info('user is not granted the operation  permission');
888      return;
889    } else {
890      console.info('grant permission successfully');
891    }
892  });
893}
894
895// Cancel the granted permission.
896try {
897  serialManager.cancelSerialRight(portId);
898  console.info('cancelSerialRight success, portId: ', portId);
899} catch (error) {
900  console.error('cancelSerialRight error, ', JSON.stringify(error));
901}
902```
903
904## SerialAttribute
905
906Represents the configuration parameters of a serial port.
907
908**System capability**: SystemCapability.USB.USBManager.Serial
909
910| Name      |          Type       |  Read-Only  |  Optional| Description       |
911|----------|--------|----------|-----------|----------------------|
912| baudRate | [BaudRates](#baudrates) |   No  | No | Baud rate. |
913| dataBits | [DataBits](#databits)   |   No  | Yes | Data bits. The default value is **8**. |
914| parity   | [Parity](#parity)       |   No  | Yes | Parity check. The default value is **None**, indicating that no parity check is performed.|
915| stopBits | [StopBits](#stopbits)   |   No  | Yes | Stop bits. The default value is **1**. |
916
917## SerialPort
918
919Represents the parameters of a serial port.
920
921**System capability**: SystemCapability.USB.USBManager.Serial
922
923| Name    | Type |  Read-Only| Optional| Description   |
924|--------|--------|------|-------|--------|
925| portId | number | No |  No| Port number.|
926| deviceName | string | No |  No| Serial port device name.|
927
928## BaudRates
929
930Enumerates the baud rates.
931
932**System capability**: SystemCapability.USB.USBManager.Serial
933
934| Name    | Value    | Description   |
935|-----------|-----------|-----------|
936| BAUDRATE_50  | 50  | The baud rate is 50 bit/s. |
937| BAUDRATE_75  | 75  | The baud rate is 75 bit/s. |
938| BAUDRATE_110  | 110  | The baud rate is 110 bit/s. |
939| BAUDRATE_134  | 134  | The baud rate is 134 bit/s. |
940| BAUDRATE_150  | 150  | The baud rate is 150 bit/s. |
941| BAUDRATE_200  | 200  | The baud rate is 200 bit/s. |
942| BAUDRATE_300  | 300  | The baud rate is 300 bit/s. |
943| BAUDRATE_600  | 600  | The baud rate is 600 bit/s. |
944| BAUDRATE_1200  | 1200  | The baud rate is 1200 bit/s. |
945| BAUDRATE_1800  | 1800  | The baud rate is 1800 bit/s. |
946| BAUDRATE_2400  | 2400  | The baud rate is 2400 bit/s. |
947| BAUDRATE_4800  | 4800  | The baud rate is 4800 bit/s. |
948| BAUDRATE_9600  | 9600  | The baud rate is 9600 bit/s. |
949| BAUDRATE_19200  | 19200  | The baud rate is 19200 bit/s. |
950| BAUDRATE_38400  | 38400  | The baud rate is 38400 bit/s. |
951| BAUDRATE_57600  | 57600  | The baud rate is 57600 bit/s. |
952| BAUDRATE_115200  | 115200  | The baud rate is 115200 bit/s. |
953| BAUDRATE_230400  | 230400  | The baud rate is 230400 bit/s. |
954| BAUDRATE_460800  | 460800  | The baud rate is 460800 bit/s. |
955| BAUDRATE_500000  | 500000  | The baud rate is 500000 bit/s. |
956| BAUDRATE_576000  | 576000  | The baud rate is 576000 bit/s. |
957| BAUDRATE_921600  | 921600  | The baud rate is 921600 bit/s. |
958| BAUDRATE_1000000  | 1000000  | The baud rate is 1000000 bit/s. |
959| BAUDRATE_1152000  | 1152000  | The baud rate is 1152000 bit/s. |
960| BAUDRATE_1500000  | 1500000  | The baud rate is 1500000 bit/s. |
961| BAUDRATE_2000000  | 2000000  | The baud rate is 2000000 bit/s. |
962| BAUDRATE_2500000  | 2500000  | The baud rate is 2500000 bit/s. |
963| BAUDRATE_3000000  | 3000000  | The baud rate is 3000000 bit/s. |
964| BAUDRATE_3500000  | 3500000  | The baud rate is 3500000 bit/s. |
965| BAUDRATE_4000000  | 4000000  | The baud rate is 4000000 bit/s. |
966
967## DataBits
968
969Enumerates the number of data bits.
970
971**System capability**: SystemCapability.USB.USBManager.Serial
972
973| Name    | Value    | Description   |
974|-----------|-----------|-----------|
975| DATABIT_8 | 8 | The number of data bits is 8.|
976| DATABIT_7 | 7 | The number of data bits is 7.|
977| DATABIT_6 | 6 | The number of data bits is 6.|
978| DATABIT_5 | 5 | The number of data bits is 5.|
979
980## Parity
981
982Enumerates the parity check modes.
983
984**System capability**: SystemCapability.USB.USBManager.Serial
985
986| Name    | Value    | Description   |
987|-----------|-----------|-----------|
988| PARITY_NONE | 0 | No parity.|
989| PARITY_ODD | 1 | Odd parity.|
990| PARITY_EVEN | 2 | Even parity.|
991| PARITY_MARK | 3 | Mark parity, whose parity bit is fixed at **1**.|
992| PARITY_SPACE | 4 | Space parity, whose parity bit is fixed at **0**.|
993
994## StopBits
995
996Enumerates of the number of stop bits.
997
998**System capability**: SystemCapability.USB.USBManager.Serial
999
1000| Name    | Value    | Description   |
1001|-----------|-----------|-----------|
1002| STOPBIT_1 | 0 | The number of stop bits is 1.|
1003| STOPBIT_2 | 1 | The number of stop bits is 2.|
1004