未验证 提交 7e4282ca 编写于 作者: O openharmony_ci 提交者: Gitee

!20683 翻译已完成19337

Merge pull request !20683 from shawn_he/19184-d
因为 它太大了无法显示 source diff 。你可以改为 查看blob
...@@ -455,3 +455,4 @@ Represents a screen hopping message notification. ...@@ -455,3 +455,4 @@ Represents a screen hopping message notification.
| COOPERATE_ACTIVATE_FAIL | 4 | Starting screen hopping fails.| | COOPERATE_ACTIVATE_FAIL | 4 | Starting screen hopping fails.|
| COOPERATE_DEACTIVATE_SUCCESS | 5 | Stopping screen hopping succeeds.| | COOPERATE_DEACTIVATE_SUCCESS | 5 | Stopping screen hopping succeeds.|
| COOPERATE_DEACTIVATE_FAIL | 6 | Stopping screen hopping fails.| | COOPERATE_DEACTIVATE_FAIL | 6 | Stopping screen hopping fails.|
| COOPERATE_SESSION_DISCONNECTED | 7 | The screen hopping session is disconnected.|
# @ohos.hilog (HiLog) # @ohos.hilog (HiLog)
The **hilog** module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -23,7 +24,7 @@ Checks whether logs are printable based on the specified service domain, log tag ...@@ -23,7 +24,7 @@ Checks whether logs are printable based on the specified service domain, log tag
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | --------------------- | ---- | ------------------------------------------------------------ | | ------ | --------------------- | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| level | [LogLevel](#loglevel) | Yes | Log level. | | level | [LogLevel](#loglevel) | Yes | Log level. |
...@@ -41,11 +42,11 @@ hilog.isLoggable(0x0001, "testTag", hilog.LogLevel.INFO); ...@@ -41,11 +42,11 @@ hilog.isLoggable(0x0001, "testTag", hilog.LogLevel.INFO);
## LogLevel ## LogLevel
Enumerates the log levels. Log level.
**System capability**: SystemCapability.HiviewDFX.HiLog **System capability**: SystemCapability.HiviewDFX.HiLog
| Name | Value| Description | | Name | Value | Description |
| ----- | ------ | ------------------------------------------------------------ | | ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| | INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
...@@ -67,9 +68,9 @@ DEBUG logs are not recorded in official versions by default. They are available ...@@ -67,9 +68,9 @@ DEBUG logs are not recorded in official versions by default. They are available
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several elements, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example** **Example**
...@@ -98,9 +99,9 @@ Prints INFO logs. ...@@ -98,9 +99,9 @@ Prints INFO logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several elements, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example** **Example**
...@@ -129,9 +130,9 @@ Prints WARN logs. ...@@ -129,9 +130,9 @@ Prints WARN logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several elements, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example** **Example**
...@@ -160,9 +161,9 @@ Prints ERROR logs. ...@@ -160,9 +161,9 @@ Prints ERROR logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several elements, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example** **Example**
...@@ -191,9 +192,9 @@ Prints FATAL logs. ...@@ -191,9 +192,9 @@ Prints FATAL logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several elements, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example** **Example**
...@@ -209,3 +210,43 @@ If `"hello"` is filled in `%{public}s` and `3` in `%{private}d`, the output log ...@@ -209,3 +210,43 @@ If `"hello"` is filled in `%{public}s` and `3` in `%{private}d`, the output log
``` ```
08-05 12:21:47.579 2695-2703/com.example.myapplication F 00001/testTag: hello World <private> 08-05 12:21:47.579 2695-2703/com.example.myapplication F 00001/testTag: hello World <private>
``` ```
## Parameter Format
Parameters in the log are printed in the following format:
%[private flag]specifier
| Privacy Flag| Description|
| ------------ | ---- |
| Unspecified | The default value is **private**, indicating that parameters in plaintext are not printed.|
| private | Prints private parameters.|
| public | Prints parameters in plaintext.|
| Specifier| Description| Example|
| ------------ | ---- | ---- |
| d/i | Prints logs of the **number** and **bigint** types.| 123 |
| s | Prints logs of the **string undefined bool** and **null** types.| "123" |
**Example**
```js
let obj2 = new Object({name:"Jack", age:22});
let isBol = true;
let bigNum = BigInt(1234567890123456789);
hilog.info(0x0001, "jsHilogTest", "print object: %{public}s", JSON.stringify(obj2));
hilog.info(0x0001, "jsHilogTest", "private flag: %{private}s %s, print null: %{public}s", "hello", "world", null);
hilog.info(0x0001, "jsHilogTest", "print undefined: %{public}s", undefined);
hilog.info(0x0001, "jsHilogTest", "print number: %{public}d %{public}i", 123, 456);
hilog.info(0x0001, "jsHilogTest", "print bigNum: %{public}d %{public}i", bigNum, bigNum);
hilog.info(0x0001, "jsHilogTest", "print boolean: %{public}s", isBol);
```
Log printing result:
```
08-09 13:26:29.094 2266 2266 I A00001/jsHilogTest: print object: {"name":"Jack","age":22}
08-09 13:26:29.094 2266 2266 I A00001/jsHilogTest: private flag: <private> <private>, print null: null
08-09 13:26:29.094 2266 2266 I A00001/jsHilogTest: print undefined: undefined
08-09 13:26:29.094 2266 2266 I A00001/jsHilogTest: print number: 123 456
08-09 13:26:29.095 2266 2266 I A00001/jsHilogTest: print bigNum: 1234567890123456768 1234567890123456768
08-09 13:26:29.095 2266 2266 I A00001/jsHilogTest: print boolean: true
```
...@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object. ...@@ -1059,7 +1059,7 @@ Creates a **PhoneNumberFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------- | | ------- | ---------------------------------------- | ---- | ---------------- |
| country | string | Yes | Country or region to which the phone number to be formatted belongs.| | country | string | Yes | Country or region to which the phone number to be formatted belongs.|
| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. | | options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. |
**Example** **Example**
```js ```js
...@@ -1149,7 +1149,7 @@ Obtains the home location of a phone number. ...@@ -1149,7 +1149,7 @@ Obtains the home location of a phone number.
``` ```
## PhoneNumberFormatOptions<sup>9+</sup> ## PhoneNumberFormatOptions<sup>8+</sup>
Defines the options for this PhoneNumberFormat object. Defines the options for this PhoneNumberFormat object.
...@@ -1157,7 +1157,7 @@ Defines the options for this PhoneNumberFormat object. ...@@ -1157,7 +1157,7 @@ Defines the options for this PhoneNumberFormat object.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| ---- | ------ | ---- | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---- | ---------------------------------------- |
| type | string | Yes | Yes | Format type of a phone number. The available options are as follows: E164,&nbsp;INTERNATIONAL,&nbsp;NATIONAL, and&nbsp;RFC3966.| | type | string | Yes | Yes | Format type of a phone number. The available options are as follows: E164,&nbsp;INTERNATIONAL,&nbsp;NATIONAL, and&nbsp;RFC3966.<br>- In API version 8, **type** is mandatory.<br>- In API version 9 or later, **type** is optional.|
## UnitInfo<sup>8+</sup> ## UnitInfo<sup>8+</sup>
...@@ -1786,8 +1786,8 @@ Obtains a list of IDs supported by the **Transliterator** object. ...@@ -1786,8 +1786,8 @@ Obtains a list of IDs supported by the **Transliterator** object.
**Example** **Example**
```ts ```ts
// ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...], 671 IDs supported in total // A total of 671 IDs are supported. One ID is comprised of two parts separated by a hyphen (-) in the format of source-destination. For example, in **ids = ["Han-Latin","Latin-ASCII", "Amharic-Latin/BGN","Accents-Any", ...]**, **Han-Latin** indicates conversion from Chinese to Latin, and **Amharic-Latin** indicates conversion from Amharic to Latin.
// Each ID consists of two parts separated by a hyphen (-). The format is source-destination. // For more information, see ISO-15924.
let ids = I18n.Transliterator.getAvailableIDs(); let ids = I18n.Transliterator.getAvailableIDs();
``` ```
...@@ -2210,6 +2210,157 @@ Enumerates text normalization modes. ...@@ -2210,6 +2210,157 @@ Enumerates text normalization modes.
| NFKD | 4 | NFKD.| | NFKD | 4 | NFKD.|
## SystemLocaleManager<sup>10+</sup>
### constructor<sup>10+</sup>
constructor()
Creates a **SystemLocaleManager** object.
**System API**: This is a system API.
**System capability**: SystemCapability.Global.I18n
**Example**
```js
let systemLocaleManager= new I18n.SystemLocaleManager();
```
### getLanguageInfoArray<sup>10+</sup>
getLanguageInfoArray(languages: Array&lt;string&gt;, options?: SortOptions): Array&lt;LocaleItem&gt;
Obtains the language sorting array.
**System API**: This is a system API.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------- | ---- | ------------- |
| languages | Array&lt;string&gt; | Yes | List of languages to be sorted.|
| options | [SortOptions](#sortoptions10) | No | Language sorting option.|
**Return value**
| Type | Description |
| ----------------- | -------------------- |
| Array&lt;[LocaleItem](#localeitem10)&gt; | Language list after sorting.|
**Error codes**
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
| 890001 | param value not valid |
**Example**
```js
// Assume that the system language is zh-Hans, the system region is CN, and the system locale is zh-Hans-CN.
let systemLocaleManager = new I18n.SystemLocaleManager();
var languages = ["zh-Hans", "en-US", "pt", "ar"];
var sortOptions = {locale: "zh-Hans-CN", isUseLocalName: true, isSuggestedFirst: true};
try {
// The language list after sorting is [zh-Hans, en-US, pt, ar].
let sortedLanguages = systemLocaleManager.getLanguageInfoArray(languages, sortOptions);
} catch(error) {
console.error(`call systemLocaleManager.getLanguageInfoArray failed, error code: ${error.code}, message: ${error.message}.`);
}
```
### getRegionInfoArray<sup>10+</sup>
getRegionInfoArray(regions: Array&lt;string&gt;, options?: SortOptions): Array&lt;LocaleItem&gt;
Obtains the country/region sorting array.
**System API**: This is a system API.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------- | ---- | ------------- |
| regions | Array&lt;string&gt; | Yes | List of countries/regions to be sorted.|
| options | [SortOptions](#sortoptions10) | No | Country/region sorting option.|
**Return value**
| Type | Description |
| ----------------- | -------------------- |
| Array&lt;[LocaleItem](#localeitem10)&gt; | Country/region list after sorting.|
**Error codes**
For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md).
| ID | Error Message |
| ------ | ---------------------- |
| 890001 | param value not valid |
**Example**
```js
// Assume that the system language is zh-Hans, the system region is CN, and the system locale is zh-Hans-CN.
let systemLocaleManager = new I18n.SystemLocaleManager();
var regions = ["CN", "US", "PT", "EG"];
var sortOptions = {locale: "zh-Hans-CN", isUseLocalName: false, isSuggestedFirst: true};
try {
// The country/region list after sorting is [CN, EG, US, PT].
let sortedRegions = systemLocaleManager.getRegionInfoArray(regions, sortOptions);
} catch(error) {
console.error(`call systemLocaleManager.getRegionInfoArray failed, error code: ${error.code}, message: ${error.message}.`);
}
```
## LocaleItem<sup>10+</sup>
Represents the list of languages or countries/regions sorted by **SystemLocaleManager**.
**System capability**: SystemCapability.Global.I18n
| Name | Type | Mandatory | Description |
| --------------- | --------------- | ------ | --------------------------------------- |
| id | string | Yes | Language code or country/region code, for example, **zh** or **CN**. |
| suggestionType | [SuggestionType](#suggestiontype10) | Yes | Language or country/region suggestion type. |
| displayName | string | Yes | Displayed name of the ID in the locale of **SystemLocaleManager**.|
| localName | string | No | Local name of the ID. |
## SuggestionType<sup>10+</sup>
Represents the language or country/region suggestion type.
**System capability**: SystemCapability.Global.I18n
| Name | Value | Description |
| ---------------------- | ---- | ---- |
| SUGGESTION_TYPE_NONE | 0x00 | Not a recommended language or country/region.|
| SUGGESTION_TYPE_RELATED| 0x01 | Country/region recommended by the system language or language recommended by the system country/region.|
| SUGGESTION_TYPE_SIM | 0x02 | Language recommended by the country/region of the SIM card.|
## SortOptions<sup>10+<sup>
Represents the language or country/region sorting option.
**System capability**: SystemCapability.Global.I18n
| Name | Type | Mandatory| Description |
| --------------- | --------------- | ---- | --------------------------------------- |
| locale | string | No | System locale, for example, **zh-Hans-CN**. |
| isUseLocalName | boolean | No | Whether to use the local name for sorting. |
| isSuggestedFirst | boolean | No | Whether to move the recommended language or country/region to the top in the sorting result. |
## I18n.getDisplayCountry<sup>(deprecated)</sup> ## I18n.getDisplayCountry<sup>(deprecated)</sup>
getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string
......
# @ohos.multimodalInput.inputDevice (Input Device) # @ohos.multimodalInput.inputDevice (Input Device)
The **inputDevice** module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse.
> **NOTE**<br> The **inputDevice** module allows you to listen for hot swap events of input devices and query information about input devices.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```js ```js
import inputDevice from '@ohos.multimodalInput.inputDevice'; import inputDevice from '@ohos.multimodalInput.inputDevice';
``` ```
## inputDevice.getDeviceList<sup>9+</sup> ## inputDevice.getDeviceList<sup>9+</sup>
getDeviceList(callback: AsyncCallback&lt;Array&lt;number&gt;&gt;): void getDeviceList(callback: AsyncCallback&lt;Array&lt;number&gt;&gt;): void
...@@ -20,25 +26,23 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to ...@@ -20,25 +26,23 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ---------- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| callback | AsyncCallback&lt;Array&lt;number&gt;&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;Array&lt;number&gt;&gt; | Yes | Callback used to return the result.|
**Example** **Example**
```js ```js
try { try {
inputDevice.getDeviceIds((error, ids) => { inputDevice.getDeviceList((error, ids) => {
if (error) { if (error) {
console.log(`Failed to get device list. console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`);
error code=${err.code} msg=${err.message}`);
return; return;
} }
this.data = ids; console.log(`Device id list: ${JSON.stringify(ids)}`);
console.log("The device ID list is: " + ids);
}); });
} catch (error) { } catch (error) {
console.info("getDeviceList " + error.code + " " + error.message); console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -52,19 +56,19 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu ...@@ -52,19 +56,19 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu
**Return value** **Return value**
| Name | Description | | Parameters | Description |
| ---------------------------------- | ------------------------------- | | ---------------------------------- | ------------------------------------------- |
| Promise&lt;Array&lt;number&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;number&gt;&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
try { try {
inputDevice.getDeviceIds().then((ids) => { inputDevice.getDeviceList().then((ids) => {
console.log("The device ID list is: " + ids); console.log(`Device id list: ${JSON.stringify(ids)}`);
}); });
} catch (error) { } catch (error) {
console.info("getDeviceList " + error.code + " " + error.message); console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -88,16 +92,15 @@ Obtains information about an input device. This API uses an asynchronous callbac ...@@ -88,16 +92,15 @@ Obtains information about an input device. This API uses an asynchronous callbac
```js ```js
// Obtain the name of the device whose ID is 1. // Obtain the name of the device whose ID is 1.
try { try {
inputDevice.getDeviceInfo(1, (error, inputDevice) => { inputDevice.getDeviceInfo(1, (error, deviceData) => {
if (error) { if (error) {
console.log(`Failed to get device information. console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`);
error code=${err.code} msg=${err.message}`);
return; return;
} }
console.log("The device name is: " + inputDevice.name); console.log(`Device info: ${JSON.stringify(deviceData)}`);
}); });
} catch (error) { } catch (error) {
console.info("getDeviceInfo " + error.code + " " + error.message); console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -117,7 +120,7 @@ Obtains information about an input device. This API uses a promise to return the ...@@ -117,7 +120,7 @@ Obtains information about an input device. This API uses a promise to return the
**Return value** **Return value**
| Name | Description | | Parameters | Description |
| -------------------------------------------------- | ------------------------------- | | -------------------------------------------------- | ------------------------------- |
| Promise&lt;[InputDeviceData](#inputdevicedata)&gt; | Promise used to return the result.| | Promise&lt;[InputDeviceData](#inputdevicedata)&gt; | Promise used to return the result.|
...@@ -126,20 +129,19 @@ Obtains information about an input device. This API uses a promise to return the ...@@ -126,20 +129,19 @@ Obtains information about an input device. This API uses a promise to return the
```js ```js
// Obtain the name of the device whose ID is 1. // Obtain the name of the device whose ID is 1.
try { try {
inputDevice.getDeviceInfo(id).then((inputDevice) => { inputDevice.getDeviceInfo(1).then((deviceData) => {
console.log("The device name is: " + inputDevice.name); console.log(`Device info: ${JSON.stringify(deviceData)}`);
}); });
} catch (error) { } catch (error) {
console.info("getDeviceInfo " + error.code + " " + error.message); console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
## inputDevice.on<sup>9+</sup> ## inputDevice.on<sup>9+</sup>
on(type: "change", listener: Callback&lt;DeviceListener&gt;): void on(type: "change", listener: Callback&lt;DeviceListener&gt;): void
Enables listening for hot swap events of an input device. Enables listening for device hot swap events.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice **System capability**: SystemCapability.MultimodalInput.Input.InputDevice
...@@ -156,13 +158,13 @@ Enables listening for hot swap events of an input device. ...@@ -156,13 +158,13 @@ Enables listening for hot swap events of an input device.
let isPhysicalKeyboardExist = true; let isPhysicalKeyboardExist = true;
try { try {
inputDevice.on("change", (data) => { inputDevice.on("change", (data) => {
console.log("type: " + data.type + ", deviceId: " + data.deviceId); console.log(`Device event info: ${JSON.stringify(data)}`);
inputDevice.getKeyboardType(data.deviceId, (err, ret) => { inputDevice.getKeyboardType(data.deviceId, (err, type) => {
console.log("The keyboard type of the device is: " + ret); console.log("The keyboard type is: " + type);
if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is connected. // The physical keyboard is connected.
isPhysicalKeyboardExist = true; isPhysicalKeyboardExist = true;
} else if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { } else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') {
// The physical keyboard is disconnected. // The physical keyboard is disconnected.
isPhysicalKeyboardExist = false; isPhysicalKeyboardExist = false;
} }
...@@ -170,7 +172,7 @@ try { ...@@ -170,7 +172,7 @@ try {
}); });
// Check whether the soft keyboard is open based on the value of isPhysicalKeyboardExist. // Check whether the soft keyboard is open based on the value of isPhysicalKeyboardExist.
} catch (error) { } catch (error) {
console.info("oninputdevcie " + error.code + " " + error.message); console.log(`Get device info failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -178,7 +180,7 @@ try { ...@@ -178,7 +180,7 @@ try {
off(type: "change", listener?: Callback&lt;DeviceListener&gt;): void off(type: "change", listener?: Callback&lt;DeviceListener&gt;): void
Disables listening for hot swap events of an input device. Disables listening for device hot swap events. This API is called before the application exits.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice **System capability**: SystemCapability.MultimodalInput.Input.InputDevice
...@@ -192,33 +194,29 @@ Disables listening for hot swap events of an input device. ...@@ -192,33 +194,29 @@ Disables listening for hot swap events of an input device.
**Example** **Example**
```js ```js
callback: function(data) { function callback(data) {
console.log("type: " + data.type + ", deviceId: " + data.deviceId); console.log(`Report device event info: ${JSON.stringify(data, [`type`, `deviceId`])}`);
} };
try { try {
inputDevice.on("change", this.callback); inputDevice.on("change", callback);
} catch (error) { } catch (error) {
console.info("oninputdevcie " + error.code + " " + error.message) console.log(`Listen device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
// Enable listening for hot swap events of an input device.
inputDevice.on("change", listener);
// Disable this listener. // Disable this listener.
try { try {
inputDevice.off("change", this.callback); inputDevice.off("change", callback);
} catch (error) { } catch (error) {
console.info("offinputdevcie " + error.code + " " + error.message) console.log(`Cancel listening device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
// Disable all listeners. // Disable all listeners.
try { try {
inputDevice.off("change"); inputDevice.off("change");
} catch (error) { } catch (error) {
console.info("offinputdevcie " + error.code + " " + error.message); console.log(`Cancel all listening device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
// By default, the soft keyboard is closed when listening is disabled.
``` ```
## inputDevice.getDeviceIds<sup>(deprecated)</sup> ## inputDevice.getDeviceIds<sup>(deprecated)</sup>
...@@ -233,9 +231,9 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ...@@ -233,9 +231,9 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ----- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| callback | AsyncCallback&lt;Array&lt;number&gt;&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;Array&lt;number&gt;&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -248,7 +246,6 @@ inputDevice.getDeviceIds((error, ids) => { ...@@ -248,7 +246,6 @@ inputDevice.getDeviceIds((error, ids) => {
console.log(`Device id list: ${JSON.stringify(ids)}`); console.log(`Device id list: ${JSON.stringify(ids)}`);
}); });
``` ```
```
## inputDevice.getDeviceIds<sup>(deprecated)</sup> ## inputDevice.getDeviceIds<sup>(deprecated)</sup>
...@@ -262,8 +259,8 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ...@@ -262,8 +259,8 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
**Return value** **Return value**
| Parameter | Description | | Parameters | Description |
| ---------------------------------- | ------------------- | | ---------------------------------- | ------------------------------------------- |
| Promise&lt;Array&lt;number&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;number&gt;&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -286,10 +283,10 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ...@@ -286,10 +283,10 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | --------------------------- | | -------- | -------------------------------------------------------- | ---- | -------------------------------- |
| deviceId | number | Yes | ID of the input device. | | deviceId | number | Yes | ID of the input device. |
| callback | AsyncCallback&lt;[InputDeviceData](#inputdevicedata)&gt; | Yes | Callback used to return the result, which is an **InputDeviceData** object.| | callback | AsyncCallback&lt;[InputDeviceData](#inputdevicedata)&gt; | Yes | Callback used to return the result, which is an **InputDeviceData** object.|
**Example** **Example**
...@@ -316,14 +313,14 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ...@@ -316,14 +313,14 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------ | | -------- | ------ | ---- | ------------ |
| deviceId | number | Yes | ID of the input device.| | deviceId | number | Yes | ID of the input device.|
**Return value** **Return value**
| Parameter | Description | | Parameters | Description |
| ---------------------------------------- | ------------------- | | -------------------------------------------------- | ----------------------------------- |
| Promise&lt;[InputDeviceData](#inputdevicedata)&gt; | Promise used to return the result.| | Promise&lt;[InputDeviceData](#inputdevicedata)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -345,22 +342,22 @@ Obtains the key codes supported by the input device. This API uses an asynchrono ...@@ -345,22 +342,22 @@ Obtains the key codes supported by the input device. This API uses an asynchrono
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | --------------------------------- | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------ |
| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
| keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. | | keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. |
| callback | AsyncCallback&lt;Array&lt;boolean&gt;&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;Array&lt;boolean&gt;&gt; | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
// Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055. // Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055.
try { try {
inputDevice.supportKeys(1, [17, 22, 2055], (error, ret) => { inputDevice.supportKeys(1, [17, 22, 2055], (error, supportResult) => {
console.log("The query result is as follows: " + ret); console.log(`Query result: ${JSON.stringify(supportResult)}`);
}); });
} catch (error) { } catch (error) {
console.info("supportKeys " + error.code + " " + error.message); console.log(`Query failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -374,15 +371,15 @@ Obtains the key codes supported by the input device. This API uses a promise to ...@@ -374,15 +371,15 @@ Obtains the key codes supported by the input device. This API uses a promise to
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | --------------------------------- | | -------- | -------------------- | ---- | ------------------------------------------------------ |
| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
| keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. | | keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. |
**Return value** **Return value**
| Parameter | Description | | Parameters | Description |
| ----------------------------------- | ------------------- | | ----------------------------------- | ------------------------------- |
| Promise&lt;Array&lt;boolean&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;boolean&gt;&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -390,11 +387,11 @@ Obtains the key codes supported by the input device. This API uses a promise to ...@@ -390,11 +387,11 @@ Obtains the key codes supported by the input device. This API uses a promise to
```js ```js
// Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055. // Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055.
try { try {
inputDevice.supportKeys(1, [17, 22, 2055]).then((ret) => { inputDevice.supportKeys(1, [17, 22, 2055]).then((supportResult) => {
console.log("The query result is as follows: " + ret); console.log(`Query result: ${JSON.stringify(supportResult)}`);
}); });
} catch (error) { } catch (error) {
console.info("supportKeys " + error.code + " " + error.message); console.log(`Query failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -408,41 +405,46 @@ Obtains the keyboard type of an input device. This API uses an asynchronous call ...@@ -408,41 +405,46 @@ Obtains the keyboard type of an input device. This API uses an asynchronous call
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | --------------------------------- | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
| callback | AsyncCallback&lt;[KeyboardType](#keyboardtype9)&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;[KeyboardType](#keyboardtype9)&gt; | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
// Query the keyboard type of the input device whose ID is 1. // Query the keyboard type of the input device whose ID is 1.
try { try {
inputDevice.getKeyboardType(1, (error, number) => { inputDevice.getKeyboardType(1, (error, type) => {
if (error) { if (error) {
console.log(`Failed to get keyboardtype. console.log(`Failed to get keyboard type, error: ${JSON.stringify(error, [`code`, `message`])}`);
error code=${err.code} msg=${err.message}`);
return; return;
} }
console.log("The keyboard type of the device is: " + number); console.log(`Keyboard type: ${JSON.stringify(type)}`);
}); });
} catch (error) { } catch (error) {
console.info("getKeyboardType " + error.code + " " + error.message); console.log(`Failed to get keyboard type, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
## inputDevice.getKeyboardType<sup>9+</sup> ## inputDevice.getKeyboardType<sup>9+</sup>
getKeyboardType(deviceId: number,): Promise&lt;KeyboardType&gt; getKeyboardType(deviceId: number): Promise&lt;KeyboardType&gt;
Obtains the keyboard type of an input device. This API uses a promise to return the result. Obtains the keyboard type of an input device. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice **System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
**Return value** **Return value**
| Parameter | Description | | Parameters | Description |
| ---------------------------------------- | ------------------- | | --------------------------------------------- | ------------------------------- |
| Promise&lt;[KeyboardType](#keyboardtype9)&gt; | Promise used to return the result.| | Promise&lt;[KeyboardType](#keyboardtype9)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -450,11 +452,137 @@ Obtains the keyboard type of an input device. This API uses a promise to return ...@@ -450,11 +452,137 @@ Obtains the keyboard type of an input device. This API uses a promise to return
```js ```js
// Query the keyboard type of the input device whose ID is 1. // Query the keyboard type of the input device whose ID is 1.
try { try {
inputDevice.getKeyboardType(1).then((number) => { inputDevice.getKeyboardType(1).then((type) => {
console.log("The keyboard type of the device is: " + number); console.log(`Keyboard type: ${JSON.stringify(type)}`);
});
} catch (error) {
console.log(`Failed to get keyboard type, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDevice.setKeyboardRepeatDelay<sup>10+</sup>
setKeyboardRepeatDelay(delay: number, callback: AsyncCallback&lt;void&gt;): void
Sets the keyboard repeat delay. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| delay | number | Yes | Keyboard repeat delay, in ms. The value range is [300 ms, 1000 ms] and the default value is **500**.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
try {
inputDevice.setKeyboardRepeatDelay(350, (error) => {
if (error) {
console.log(`Set keyboard repeat delay failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Set keyboard repeat delay success`);
});
} catch (error) {
console.log(`Set keyboard repeat delay failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDevice.setKeyboardRepeatDelay<sup>10+</sup>
setKeyboardRepeatDelay(delay: number): Promise&lt;void&gt;
Sets the keyboard repeat delay. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------------------------- |
| delay | number | Yes | Keyboard repeat delay, in ms. The value range is [300, 1000] and the default value is **500**.|
**Return value**
| Parameters | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
try {
inputDevice.setKeyboardRepeatDelay(350).then(() => {
console.log(`Set keyboard repeat delay success`);
});
} catch (error) {
console.log(`Set keyboard repeat delay failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDevice.setKeyboardRepeatRate<sup>10+</sup>
setKeyboardRepeatRate(rate: number, callback: AsyncCallback&lt;void&gt;): void
Sets the keyboard repeat rate. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| rate | number | Yes | Keyboard repeat rate, in ms/time. The value range is [36, 100] and the default value is 50.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
try {
inputDevice.setKeyboardRepeatRate(60, (error) => {
if (error) {
console.log(`Set keyboard repeat rate failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Set keyboard repeat rate success`);
});
} catch (error) {
console.log(`Set keyboard repeat rate failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDevice.setKeyboardRepeatRate<sup>10+</sup>
setKeyboardRepeatRate(rate: number): Promise&lt;void&gt;
Sets the keyboard repeat rate. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------------------------- |
| rate | number | Yes | Keyboard repeat rate, in ms/time. The value range is [36, 100] and the default value is 50.|
**Return value**
| Parameters | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
try {
inputDevice.setKeyboardRepeatRate(60).then(() => {
console.log(`Set keyboard repeat rate success`);
}); });
} catch (error) { } catch (error) {
console.info("getKeyboardType " + error.code + " " + error.message); console.log(`Set keyboard repeat rate failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -496,15 +624,15 @@ Defines the axis type of an input device. ...@@ -496,15 +624,15 @@ Defines the axis type of an input device.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| --------- | ------ | ---- | ---- | ------- | | --------- | ------ | ---- | ---- | ------- |
| touchmajor | string | Yes| No| touchmajor axis. | | touchmajor | string | Yes| No| **touchmajor** axis. |
| touchminor | string | Yes| No| touchminor axis. | | touchminor | string | Yes| No| **touchminor** axis. |
| toolminor | string | Yes| No| toolminor axis. | | toolminor | string | Yes| No| **toolminor** axis. |
| toolmajor | string | Yes| No| toolmajor axis. | | toolmajor | string | Yes| No| **toolmajor** axis. |
| orientation | string | Yes| No| Orientation axis.| | orientation | string | Yes| No| Orientation axis.|
| pressure | string | Yes| No| Pressure axis. | | pressure | string | Yes| No| Pressure axis. |
| x | string | Yes| No| X axis. | | x | string | Yes| No| X axis. |
| y | string | Yes| No| Y axis. | | y | string | Yes| No| Y axis. |
| NULL | string | Yes| No| None. | | null | string | Yes| No| None. |
## AxisRange ## AxisRange
...@@ -524,7 +652,7 @@ Defines the axis range of an input device. ...@@ -524,7 +652,7 @@ Defines the axis range of an input device.
## SourceType<sup>9+</sup> ## SourceType<sup>9+</sup>
Enumerates the input source types. For example, if a mouse reports an x-axis event, the source of the x-axis is the mouse. Input source type of the axis. For example, if a mouse reports an x-axis event, the input source of the x-axis is the mouse.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice **System capability**: SystemCapability.MultimodalInput.Input.InputDevice
......
# @ohos.ai.mindSporeLite (Inference)
The **mindSporeLite** module provides APIs for the MindSpore Lite inference engine to implment model inference.
MindSpore Lite is an AI engine that implements AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. Unless otherwise stated, the MindSpore model is used in the sample code.
>
## Modules to Import
```js
import mindSporeLite from '@ohos.ai.mindSporeLite';
```
## Context
Defines the configuration information of the running environment.
### Attributes
**System capability**: SystemCapability.AI.MindSporeLite
| Name | Type | Readable| Writable| Description |
| ------ | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| target | string[] | Yes | Yes | Target backend. The value can be **cpu** or **nnrt**. The default value is **cpu**. |
| cpu | [CpuDevice](#cpudevice) | Yes | Yes | CPU backend device option. Set this parameter set only when **target** is set to **cpu**. The default value is the combination of the default value of each **CpuDevice** option.|
| nnrt | [NNRTDevice](#nnrtdevice) | Yes | Yes | NNRt backend device option. Set this parameter set only when **target** is set to **nnrt**. Currently, this parameter is empty.|
**Example**
```js
let context: mindSporeLite.Context = {};
context.target = ['cpu','nnrt'];
```
## CpuDevice
Defines the CPU backend device option.
### Attributes
**System capability**: SystemCapability.AI.MindSporeLite
| Name | Type | Readable| Writable| Description |
| ---------------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| threadNum | number | Yes | Yes | Number of runtime threads. The default value is **2**. |
| threadAffinityMode | [ThreadAffinityMode](#threadaffinitymode) | Yes | Yes | Affinity mode for binding runtime threads to CPU cores. The default value is **mindSporeLite.ThreadAffinityMode.NO_AFFINITIES**.|
| threadAffinityCoreList | number[] | Yes | Yes | List of CPU cores bound to runtime threads. Set this parameter only when **threadAffinityMode** is set. If **threadAffinityMode** is set to **mindSporeLite.ThreadAffinityMode.NO_AFFINITIES**, this parameter is empty. The number in the list indicates the SN of the CPU core. The default value is **[]**.|
| precisionMode | string | Yes | Yes | Whether to enable the Float16 inference mode. The value **preferred_fp16** means to enable half-precision inference and the default value **force_fp32** means to disable half-precision inference. Other settings are not supported.|
**Float16 inference mode**: a mode that uses half-precision inference. Float16 uses 16 bits to represent a number and therefore it is also called half-precision.
**Example**
```js
let context: mindSporeLite.Context = {};
context.cpu = {};
context.target = ['cpu'];
context.cpu.threadAffinityMode = 0;
context.cpu.precisionMode = 'preferred_fp16';
context.cpu.threadAffinityCoreList = [0, 1, 2];
```
## NNRTDevice
Represents an NNRt device. Neural Network Runtime (NNRt) is a bridge that connects the upper-layer AI inference framework to the bottom-layer acceleration chip to implement cross-chip inference and computing of AI models. An NNRt backend can be configured for MindSpore Lite. Currently, this API is not supported.
**System capability**: SystemCapability.AI.MindSporeLite
## ThreadAffinityMode
Specifies the affinity mode for binding runtime threads to CPU cores.
**System capability**: SystemCapability.AI.MindSporeLite
| Name | Value | Description |
| ------------------ | ---- | ------------ |
| NO_AFFINITIES | 0 | No affinities. |
| BIG_CORES_FIRST | 1 | Big cores first.|
| LITTLE_CORES_FIRST | 2 | Medium cores first.|
## mindSporeLite.loadModelFromFile
loadModelFromFile(model: string, callback: Callback&lt;Model&gt;): void
Loads the input model from the full path for model inference. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------ |
| model | string | Yes | Complete path of the input model. |
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
let model_file = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(model_file, (result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromFile
loadModelFromFile(model: string, context: Context, callback: Callback&lt;Model&gt;): void
Loads the input model from the full path for model inference. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| model | string | Yes | Complete path of the input model. |
| context | [Context](#context) | Yes| Configuration information of the running environment.|
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
let context: mindSporeLite.Context = {};
let context = {'target': ['cpu']};
let model_file = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(model_file, context, (result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromFile
loadModelFromFile(model: string, context?: Context): Promise&lt;Model&gt;
Loads the input model from the full path for model inference. This API uses a promise to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | -------------------- |
| model | string | Yes | Complete path of the input model.|
| context | [Context](#context) | No | Configuration information of the running environment.|
**Return value**
| Type | Description |
| ------------------------- | ---------------------------- |
| Promise<[Model](#model)> | Promise used to return the result, which is a **Model** object.|
**Example**
```js
let model_file = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(model_file).then((result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromBuffer
loadModelFromBuffer(model: ArrayBuffer, callback: Callback&lt;Model&gt;): void
Loads the input model from the memory for inference. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------ |
| model | ArrayBuffer | Yes | Memory that contains the input model. |
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State modelName: string = 'xxx.ms';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.modelName).then((buffer) => {
this.modelBuffer = buffer;
}).catch(error => {
console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.');
})
mindSporeLite.loadModelFromBuffer(this.modelBuffer.buffer, (result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromBuffer
loadModelFromBuffer(model: ArrayBuffer, context: Context, callback: Callback&lt;Model&gt;): void
Loads the input model from the memory for inference. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| model | ArrayBuffer | Yes | Memory that contains the input model.|
| context | [Context](#context) | Yes | Configuration information of the running environment.|
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State modelName: string = 'xxx.ms';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.modelName).then((error,buffer) => {
this.modelBuffer = buffer;
}).catch(error => {
console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.');
})
let context: mindSporeLite.Context = {};
context = {'target': ['cpu']};
mindSporeLite.loadModelFromBuffer(this.modelBuffer.buffer, context, (result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromBuffer
loadModelFromBuffer(model: ArrayBuffer, context?: Context): Promise&lt;Model&gt;
Loads the input model from the memory for inference. This API uses a promise to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | -------------------- |
| model | ArrayBuffer | Yes | Memory that contains the input model. |
| context | [Context](#context) | No | Configuration information of the running environment.|
**Return value**
| Type | Description |
| ------------------------------- | ---------------------------- |
| Promise<[Model](#model)> | Promise used to return the result, which is a **Model** object.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State modelName: string = 'xxx.ms';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.modelName).then((buffer) => {
this.modelBuffer = buffer;
}).catch(error => {
console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.');
})
mindSporeLite.loadModelFromBuffer(model_file).then((result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromFd
loadModelFromFd(model: number, callback: Callback&lt;Model&gt;): void
Loads the input model based on the specified file descriptor for inference. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| model | number | Yes | File descriptor of the input model.|
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
import fs from '@ohos.file.fs';
let model_file = '/path/to/xxx.ms';
let file = await fs.open(model_file, 0);
mindSporeLite.loadModelFromFd(file.fd, (result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromFd
loadModelFromFd(model: number, context: Context, callback: Callback&lt;Model&gt;): void
Loads the input model based on the specified file descriptor for inference. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ---------------------- |
| model | number | Yes | File descriptor of the input model.|
| context | [Context](#context) | Yes | Configuration information of the running environment.|
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
import fs from '@ohos.file.fs';
let model_file = '/path/to/xxx.ms';
let context : mindSporeLite.Context = {};
context = {'target': ['cpu']};
let file = await fs.open(model_file, 0);
mindSporeLite.loadModelFromFd(file.fd, context, (result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## mindSporeLite.loadModelFromFd
loadModelFromFd(model: number, context?: Context): Promise&lt; Model&gt;
Loads the input model based on the specified file descriptor for inference. This API uses a promise to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | -------------------- |
| model | number | Yes | File descriptor of the input model. |
| context | [Context](#context) | No | Configuration information of the running environment.|
**Return value**
| Type | Description |
| ------------------------- | ---------------------------- |
| Promise<[Model](#model)> | Promise used to return the result, which is a **Model** object.|
**Example**
```js
import fs from '@ohos.file.fs';
let model_file = '/path/to/xxx.ms';
let file = await fs.open(model_file, 0);
let mindSporeLiteModel = await mindSporeLite.loadModelFromFd(file.fd);
mindSporeLite.loadModelFromFd(file.fd).then((result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
## Model
Represents a **Model** instance, with properties and APIs defined.
In the following sample code, you first need to use [loadModelFromFile()](#mindsporeliteloadmodelfromfile), [loadModelFromBuffer()](#mindsporeliteloadmodelfrombuffer), or [loadModelFromFd()](#mindsporeliteloadmodelfromfd) to obtain a **Model** instance before calling related APIs.
### getInputs
getInputs(): MSTensor[]
Obtains the model input for inference.
**System capability**: SystemCapability.AI.MindSporeLite
**Return value**
| Type | Description |
| ----------------------- | ------------------ |
| [MSTensor](#mstensor)[] | **MSTensor** object.|
**Example**
```js
let model_file = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(model_file).then((result) => {
const modelInputs = result.getInputs();
console.log(modelInputs[0].name);
})
```
### predict
predict(inputs: MSTensor[], callback: Callback&lt;Model&gt;): void
Executes the inference model. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------- | ---- | -------------------------- |
| inputs | [MSTensor](#mstensor)[] | Yes | Model input, which is an **MSTensor** object.|
| callback | Callback<[Model](#model)> | Yes | Callback used to return the result, which is a **Model** object.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State inputName: string = 'input_data.bin';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => {
this.inputBuffer = buffer;
let model_file = '/path/to/xxx.ms';
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(this.inputBuffer.buffer);
result.predict(modelInputs, (result) => {
let output = new Float32Array(result[0].getData());
for (let i = 0; i < output.length; i++) {
console.log(output[i].toString());
}
})
})
```
### predict
predict(inputs: MSTensor[]): Promise&lt;MSTensor[]&gt;
Executes the inference model. This API uses a promise to return the result.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------- | ---- | -------------------------- |
| inputs | [MSTensor](#mstensor)[] | Yes | Model input, which is an **MSTensor** object.|
**Return value**
| Type | Description |
| ----------------------- | ------------------ |
| [MSTensor](#mstensor)[] | **MSTensor** object.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State inputName: string = 'input_data.bin';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => {
this.inputBuffer = buffer;
let model_file = '/path/to/xxx.ms';
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(this.inputBuffer.buffer);
result.predict(modelInputs).then((result) => {
let output = new Float32Array(result[0].getData());
for (let i = 0; i < output.length; i++) {
console.log(output[i].toString());
}
})
})
```
### resize
resize(inputs: MSTensor[], dims: Array&lt;Array&lt;number&gt;&gt;): boolean
Resets the tensor size.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | --------------------- | ---- | ----------------------------- |
| inputs | [MSTensor](#mstensor)[] | Yes | Model input, which is an **MSTensor** object. |
| dims | Array&lt;Array&lt;number&gt;&gt; | Yes | Target tensor size.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Result indicating whether the setting is successful. The value **true** indicates that the tensor size is successfully reset, and the value **false** indicates the opposite.|
**Example**
```js
let model_file = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(model_file).then((mindSporeLiteModel) => {
const modelInputs = mindSporeLiteModel.getInputs();
let new_dim = new Array([1,32,32,1]);
mindSporeLiteModel.resize(modelInputs, new_dim);
})
```
## MSTensor
Represents an **MSTensor** instance, with properties and APIs defined. It is a special data structure similar to arrays and matrices. It is the basic data structure used in MindSpore Lite network operations.
In the following sample code, you first need to use [getInputs()](#getinputs) to obtain an **MSTensor** instance before calling related APIs.
### Attributes
**System capability**: SystemCapability.AI.MindSporeLite
| Name | Type | Readable| Writable| Description |
| ---------- | --------------------- | ---- | ---- | ---------------------------------------------------- |
| name | string | Yes | Yes | Tensor name. The default value is **null**. |
| shape | number[] | Yes | Yes | Tensor dimension array. The default value is **0**. |
| elementNum | number | Yes | Yes | Length of the tensor dimension array. The default value is **0**. |
| dataSize | number | Yes | Yes | Length of tensor data. The default value is **0**. |
| dtype | [DataType](#datatype) | Yes | Yes | Tensor data type. The default value is **0**, indicating **TYPE_UNKNOWN**. |
| format | [Format](#format) | Yes | Yes | Tensor data format. The default value is **-1**, indicating **DEFAULT_FORMAT**.|
**Example**
```js
let model_file = '/path/to/xxx.ms';
mindSporeLite.loadModelFromFile(model_file).then((mindSporeLiteModel) => {
const modelInputs = mindSporeLiteModel.getInputs();
console.log(modelInputs[0].name);
console.log(modelInputs[0].shape.toString());
console.log(modelInputs[0].elementNum.toString());
console.log(modelInputs[0].dtype.toString());
console.log(modelInputs[0].format.toString());
console.log(modelInputs[0].dataSize.toString());
})
```
### getData
getData(): ArrayBuffer
Obtains tensor data.
**System capability**: SystemCapability.AI.MindSporeLite
**Return value**
| Type | Description |
| ----------- | -------------------- |
| ArrayBuffer | Pointer to the tensor data.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State inputName: string = 'input_data.bin';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => {
this.inputBuffer = buffer;
let model_file = '/path/to/xxx.ms';
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(this.inputBuffer.buffer);
result.predict(modelInputs).then((result) => {
let output = new Float32Array(result[0].getData());
for (let i = 0; i < output.length; i++) {
console.log(output[i].toString());
}
})
})
```
### setData
setData(inputArray: ArrayBuffer): void
Sets the tensor data.
**System capability**: SystemCapability.AI.MindSporeLite
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ----------- | ---- | ---------------------- |
| inputArray | ArrayBuffer | Yes | Input data buffer of the tensor.|
**Example**
```js
import resourceManager from '@ohos.resourceManager'
@State inputName: string = 'input_data.bin';
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => {
this.inputBuffer = buffer;
})
let model_file = '/path/to/xxx.ms';
let mindSporeLiteModel = await mindSporeLite.loadModelFromFile(model_file);
const modelInputs = mindSporeLiteModel.getInputs();
modelInputs[0].setData(this.inputBuffer.buffer);
```
## DataType
Tensor data type.
**System capability**: SystemCapability.AI.MindSporeLite
| Name | Value | Description |
| ------------------- | ---- | ------------------- |
| TYPE_UNKNOWN | 0 | Unknown type. |
| NUMBER_TYPE_INT8 | 32 | Int8 type. |
| NUMBER_TYPE_INT16 | 33 | Int16 type. |
| NUMBER_TYPE_INT32 | 34 | Int32 type. |
| NUMBER_TYPE_INT64 | 35 | Int64 type. |
| NUMBER_TYPE_UINT8 | 37 | UInt8 type. |
| NUMBER_TYPE_UINT16 | 38 | UInt16 type. |
| NUMBER_TYPE_UINT32 | 39 | UInt32 type. |
| NUMBER_TYPE_UINT64 | 40 | UInt64 type. |
| NUMBER_TYPE_FLOAT16 | 42 | Float16 type.|
| NUMBER_TYPE_FLOAT32 | 43 | Float32 type.|
| NUMBER_TYPE_FLOAT64 | 44 | Float64 type.|
## Format
Enumerates tensor data formats.
**System capability**: SystemCapability.AI.MindSporeLite
| Name | Value | Description |
| -------------- | ---- | --------------------- |
| DEFAULT_FORMAT | -1 | Unknown data format. |
| NCHW | 0 | NCHW format. |
| NHWC | 1 | NHWC format. |
| NHWC4 | 2 | NHWC4 format.|
| HWKC | 3 | HWKC format. |
| HWCK | 4 | HWCK format. |
| KCHW | 5 | KCHW format. |
...@@ -58,9 +58,9 @@ Obtains the default active data network. This API uses an asynchronous callback ...@@ -58,9 +58,9 @@ Obtains the default active data network. This API uses an asynchronous callback
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If the default activated data network is obtained successfully, err is undefined and data is the default activated data network. Otherwise, err is an error object.| | callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If the default activated data network is obtained successfully, **error** is **undefined** and **data** is the default activated data network. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -156,9 +156,9 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy ...@@ -156,9 +156,9 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **err** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **err** is an error object.| | callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -227,10 +227,10 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch ...@@ -227,10 +227,10 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.| | httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -310,6 +310,71 @@ connection.setGlobalHttpProxy(httpProxy).then(() => { ...@@ -310,6 +310,71 @@ connection.setGlobalHttpProxy(httpProxy).then(() => {
}) })
``` ```
## connection.getDefaultHttpProxy<sup>10+</sup>
getDefaultHttpProxy(callback: AsyncCallback\<HttpProxy>): void
Obtains the default HTTP proxy configuration of the network.
If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
| ID| Error Message |
| -------- | -------------------------------------------- |
| 2100002 | Operation failed. Cannot connect to service. |
| 2100003 | System internal error. |
**Example**
```js
connection.getDefaultHttpProxy((error, data) => {
console.info(JSON.stringify(error));
console.info(JSON.stringify(data));
})
```
## connection.getDefaultHttpProxy<sup>10+</sup>
getDefaultHttpProxy(): Promise\<HttpProxy>;
Obtains the default proxy configuration of the network.
If the global proxy is set, the global proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| -------------------------------- | ----------------------------------------- |
| Promise<[HttpProxy](#httpproxy)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | -------------------------------------------- |
| 2100002 | Operation failed. Cannot connect to service. |
| 2100003 | System internal error. |
**Example**
```js
connection.getDefaultHttpProxy().then((data) => {
console.info(JSON.stringify(data));
}).catch(error => {
console.info(JSON.stringify(error));
})
```
## connection.getAppNet<sup>9+</sup> ## connection.getAppNet<sup>9+</sup>
getAppNet(callback: AsyncCallback\<NetHandle>): void getAppNet(callback: AsyncCallback\<NetHandle>): void
...@@ -320,9 +385,9 @@ Obtains information about the network bound to an application. This API uses an ...@@ -320,9 +385,9 @@ Obtains information about the network bound to an application. This API uses an
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, **err** is **undefined** and **data** is the obtained network information. Otherwise, **err** is an error object.| | callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, **error** is **undefined** and **data** is the obtained network information. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -385,10 +450,10 @@ Binds an application to the specified network, so that the application can acces ...@@ -385,10 +450,10 @@ Binds an application to the specified network, so that the application can acces
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the application is successfully bound to the specified network, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the application is successfully bound to the specified network, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -469,7 +534,7 @@ Obtains the list of all connected networks. This API uses an asynchronous callba ...@@ -469,7 +534,7 @@ Obtains the list of all connected networks. This API uses an asynchronous callba
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result. If the list of all connected networks is obtained successfully, **err** is **undefined** and **data** is the list of activated data networks. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result. If the list of all connected networks is obtained successfully, **error** is **undefined** and **data** is the list of activated data networks. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -534,10 +599,10 @@ Obtains connection properties of the network corresponding to the **netHandle**. ...@@ -534,10 +599,10 @@ Obtains connection properties of the network corresponding to the **netHandle**.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. |
| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. If the connection properties of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network connection information. Otherwise, **err** is an error object.| | callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. If the connection properties of the network corresponding to the **netHandle** is obtained successfully, **error** is **undefined** and **data** is the obtained network connection information. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -614,10 +679,10 @@ Obtains capability information of the network corresponding to the **netHandle** ...@@ -614,10 +679,10 @@ Obtains capability information of the network corresponding to the **netHandle**
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------------------------- | ---- | ---------------- | | --------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. |
| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. If the capability information of the network corresponding to the **netHandle** is obtained successfully, **err** is **undefined** and **data** is the obtained network capability information. Otherwise, **err** is an error object. | | callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. If the capability information of the network corresponding to the **netHandle** is obtained successfully, **error** is **undefined** and **data** is the obtained network capability information. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -904,7 +969,7 @@ Disables the airplane mode. This API uses an asynchronous callback to return the ...@@ -904,7 +969,7 @@ Disables the airplane mode. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the airplane mode is disabled successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the airplane mode is disabled successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -975,7 +1040,7 @@ Reports connection of the data network to the network management module. This AP ...@@ -975,7 +1040,7 @@ Reports connection of the data network to the network management module. This AP
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the network status is reported successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1053,7 +1118,7 @@ Reports disconnection of the data network to the network management module. This ...@@ -1053,7 +1118,7 @@ Reports disconnection of the data network to the network management module. This
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the network status is reported successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the network status is reported successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1128,10 +1193,10 @@ Resolves the host name by using the default network to obtain all IP addresses. ...@@ -1128,10 +1193,10 @@ Resolves the host name by using the default network to obtain all IP addresses.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| host | string | Yes | Host name to resolve.| | host | string | Yes | Host name to resolve. |
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.| | callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **error** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1215,9 +1280,9 @@ Registers a listener for network status changes. ...@@ -1215,9 +1280,9 @@ Registers a listener for network status changes.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- | | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1248,9 +1313,9 @@ Unregisters the listener for network status changes. ...@@ -1248,9 +1313,9 @@ Unregisters the listener for network status changes.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------- | | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1532,7 +1597,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -1532,7 +1597,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ------------------------ | ---- | -------------------------------| | ----------- | ------------------------ | ---- | -------------------------------|
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| | socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the **TCPSocket** or **UDPSocket** object is successfully bound to the current network, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the **TCPSocket** or **UDPSocket** object is successfully bound to the current network, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1684,10 +1749,10 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -1684,10 +1749,10 @@ Resolves the host name by using the corresponding network to obtain all IP addre
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------ | | -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| host | string | Yes | Host name to resolve.| | host | string | Yes | Host name to resolve. |
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **err** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **err** is an error object.| | callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **error** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1766,10 +1831,10 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -1766,10 +1831,10 @@ Resolves the host name by using the corresponding network to obtain the first IP
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| host | string | Yes | Host name to resolve.| | host | string | Yes | Host name to resolve. |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **err** is **undefined**, and **data** is the first obtained IP address. Otherwise, **err** is an error object. | | callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **error** is **undefined**, and **data** is the first obtained IP address. Otherwise, **error** is an error object.|
**Error codes** **Error codes**
...@@ -1864,7 +1929,7 @@ Enumerates network types. ...@@ -1864,7 +1929,7 @@ Enumerates network types.
## HttpProxy<sup>10+</sup> ## HttpProxy<sup>10+</sup>
Defines the global HTTP proxy configuration of the network. Represents the HTTP proxy configuration.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -1872,7 +1937,7 @@ Defines the global HTTP proxy configuration of the network. ...@@ -1872,7 +1937,7 @@ Defines the global HTTP proxy configuration of the network.
| ------ | ------ | --- |------------------------- | | ------ | ------ | --- |------------------------- |
| host | string | No | Host name of the proxy server.| | host | string | No | Host name of the proxy server.|
| port | number | No | Host port.| | port | number | No | Host port.|
| exclusionList | Array<string> | No | Exclusion list of hosts that do not use the proxy server. The length of the combined elements in the list cannot exceed 96 bytes.<br>For example, the length of **baidu.com,zhihu.com** is 20 bytes.| | exclusionList | Array<string> | No | List of the names of hosts that do not use a proxy. Host names can be domain names, IP addresses, or wildcards. The detailed matching rules are as follows:<br>- Domain name matching:<br> - Exact match: The host name of the proxy server exactly matches any host name in the list.<br> - Partial match: The host name of the proxy server contains any host name in the list.<br>For example, if **ample.com** is set in the host name list, **ample.com**, **www.ample.com**, and **ample.com:80** are matched, and **www.example.com** and **ample.com.org** are not matched.<br>- IP address matching: The host name of the proxy server exactly matches any IP address in the list.<br>- Both the domain name and IP address are added to the list for matching.<br>- A single asterisk (*) is the only valid wildcard. If the list contains only wildcards, the wildcards match all host names; that is, the HTTP proxy is disabled. A wildcard can only be added independently. It cannot be added to the list together with other domain names or IP addresses. Otherwise, the wildcard does not take effect.<br>- Host names are case insensitive.<br>- Protocol prefixes such as **http** and **https** are ignored during matching.|
## NetSpecifier<sup>8+</sup> ## NetSpecifier<sup>8+</sup>
......
...@@ -472,7 +472,7 @@ Enables listening for message receiving events of the UDPSocket connection. This ...@@ -472,7 +472,7 @@ Enables listening for message receiving events of the UDPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result. | | callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -506,7 +506,7 @@ Disables listening for message receiving events of the UDPSocket connection. Thi ...@@ -506,7 +506,7 @@ Disables listening for message receiving events of the UDPSocket connection. Thi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example** **Example**
...@@ -541,7 +541,7 @@ Enables listening for data packet message events or close events of the UDPSocke ...@@ -541,7 +541,7 @@ Enables listening for data packet message events or close events of the UDPSocke
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **listening**: data packet message event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -606,7 +606,7 @@ Enables listening for error events of the UDPSocket connection. This API uses an ...@@ -606,7 +606,7 @@ Enables listening for error events of the UDPSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -633,7 +633,7 @@ Disables listening for error events of the UDPSocket connection. This API uses a ...@@ -633,7 +633,7 @@ Disables listening for error events of the UDPSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
...@@ -1358,7 +1358,7 @@ Enables listening for message receiving events of the TCPSocket connection. This ...@@ -1358,7 +1358,7 @@ Enables listening for message receiving events of the TCPSocket connection. This
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -1392,7 +1392,7 @@ Disables listening for message receiving events of the TCPSocket connection. Thi ...@@ -1392,7 +1392,7 @@ Disables listening for message receiving events of the TCPSocket connection. Thi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. |
**Example** **Example**
...@@ -1427,7 +1427,7 @@ Enables listening for connection or close events of the TCPSocket connection. Th ...@@ -1427,7 +1427,7 @@ Enables listening for connection or close events of the TCPSocket connection. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -1457,7 +1457,7 @@ Disables listening for connection or close events of the TCPSocket connection. T ...@@ -1457,7 +1457,7 @@ Disables listening for connection or close events of the TCPSocket connection. T
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. | | callback | Callback\<void\> | No | Callback used to return the result. |
**Example** **Example**
...@@ -1492,7 +1492,7 @@ Enables listening for error events of the TCPSocket connection. This API uses an ...@@ -1492,7 +1492,7 @@ Enables listening for error events of the TCPSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -1519,7 +1519,7 @@ Disables listening for error events of the TCPSocket connection. This API uses a ...@@ -1519,7 +1519,7 @@ Disables listening for error events of the TCPSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
...@@ -1572,7 +1572,960 @@ Defines other properties of the TCPSocket connection. ...@@ -1572,7 +1572,960 @@ Defines other properties of the TCPSocket connection.
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. The default value is **0**. | | receiveBufferSize | number | No | Size of the receive buffer, in bytes. The default value is **0**. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. The default value is **0**. | | sendBufferSize | number | No | Size of the send buffer, in bytes. The default value is **0**. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. The default value is **0**. | | socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. The default value is **0**. |
## socket.constructTCPSocketServerInstance<sup>10+</sup>
constructTCPSocketServerInstance(): TCPSocketServer
Creates a **TCPSocketServer** object.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :---------------------------------- | :---------------------------- |
| [TCPSocketServer](#tcpsocketserver10) | **TCPSocketServer** object.|
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
```
## TCPSocketServer<sup>10+</sup>
Defines a TCPSocketServer connection. Before invoking TCPSocketServer APIs, you need to call [socket.constructTCPSocketServerInstance](#socketconstructtcpsocketserverinstance10) to create a **TCPSocketServer** object.
### listen<sup>10+</sup>
listen(address: NetAddress, callback: AsyncCallback\<void\>): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCPSocket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result.
> **NOTE**
> The server uses this API to perform the bind, listen, and accept operations.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | --------------------------------------------- |
| address | [NetAddress](#netaddress7) | Yes | Destination address.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.listen({ address: "192.168.xx.xxx", port: xxxx, family: 1 }, err => {
if (err) {
console.log("listen fail");
return;
}
console.log("listen success");
})
```
### listen<sup>10+</sup>
listen(address: NetAddress): Promise\<void\>
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCPSocket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result.
> **NOTE**
> The server uses this API to perform the bind, listen, and accept operations.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------- | ---- | --------------------------------------------- |
| address | [NetAddress](#netaddress7) | Yes | Destination address.|
**Return value**
| Type | Description |
| :-------------- | :----------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303109 | Bad file number. |
| 2303111 | Resource temporarily unavailable try again. |
| 2303198 | Address already in use. |
| 2303199 | Cannot assign requested address. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
let promise = tcpServer.listen({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
promise.then(() => {
console.log('listen success');
}).catch(err => {
console.log('listen fail');
});
```
### getState<sup>10+</sup>
getState(callback: AsyncCallback\<SocketStateBase\>): void
Obtains the status of the TCPSocketServer connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API can be called only after **listen** is successfully called.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[SocketStateBase](#socketstatebase7)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303188 | Socket operation on non-socket. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.listen({ address: "192.168.xx.xxx", port: xxxx, family: 1 }, err => {
if (err) {
console.log("listen fail");
return;
}
console.log("listen success");
})
tcpServer.getState((err, data) => {
if (err) {
console.log('getState fail');
return;
}
console.log('getState success:' + JSON.stringify(data));
})
```
### getState<sup>10+</sup>
getState(): Promise\<SocketStateBase\>
Obtains the status of the TCPSocketServer connection. This API uses a promise to return the result.
> **NOTE**
> This API can be called only after **listen** is successfully called.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :------------------------------------------- | :----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase7)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------- |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303188 | Socket operation on non-socket. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
let promiseListen = tcpServer.listen({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
promiseListen.then(() => {
console.log('listen success');
}).catch(err => {
console.log('listen fail');
});
let promise = tcpServer.getState();
promise.then(() => {
console.log('getState success');
}).catch(err => {
console.log('getState fail');
});
```
### setExtraOptions<sup>10+</sup>
setExtraOptions(options: TCPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other properties of the TCPSocketServer connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API can be called only after **listen** is successfully called.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions7) | Yes | Other properties of the TCPSocketServer connection.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ------------------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303188 | Socket operation on non-socket. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.listen({ address: "192.168.xx.xxx", port: xxxx, family: 1 }, err => {
if (err) {
console.log("listen fail");
return;
}
console.log("listen success");
})
tcpServer.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on: true, linger: 10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
}, err => {
if (err) {
console.log('setExtraOptions fail');
return;
}
console.log('setExtraOptions success');
});
```
### setExtraOptions<sup>10+</sup>
setExtraOptions(options: TCPExtraOptions): Promise\<void\>
Sets other properties of the TCPSocketServer connection. This API uses a promise to return the result.
> **NOTE**
> This API can be called only after **listen** is successfully called.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPExtraOptions](#tcpextraoptions7) | Yes | Other properties of the TCPSocketServer connection.|
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303188 | Socket operation on non-socket. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
let promiseListen = tcpServer.listen({ address: '192.168.xx.xxx', port: xxxx, family: 1 });
promiseListen.then(() => {
console.log('listen success');
}).catch(err => {
console.log('listen fail');
});
let promise = tcpServer.setExtraOptions({
keepAlive: true,
OOBInline: true,
TCPNoDelay: true,
socketLinger: { on: true, linger: 10 },
receiveBufferSize: 1000,
sendBufferSize: 1000,
reuseAddress: true,
socketTimeout: 3000,
});
promise.then(() => {
console.log('setExtraOptions success');
}).catch(err => {
console.log('setExtraOptions fail');
});
```
### on('connect')<sup>10+</sup>
on(type: 'connect', callback: Callback\<TCPSocketConnection\>): void
Enables listening for TCPSocketServer connection events. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br/> **connect**: connection event|
| callback | Callback<[TCPSocketConnection](#tcpsocketconnection10)> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(data) {
console.log(JSON.stringify(data))
});
```
### off('connect')<sup>10+</sup>
off(type: 'connect', callback?: Callback\<TCPSocketConnection\>): void
Disables listening for TCPSocketServer connection events. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br/> **connect**: connection event|
| callback | Callback<[TCPSocketConnection](#tcpsocketconnection10)> | No | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
let callback = data => {
console.log('on connect message: ' + JSON.stringify(data));
}
tcpServer.on('connect', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcpServer.off('connect', callback);
tcpServer.off('connect');
```
### on('error')<sup>10+</sup>
on(type: 'error', callback: ErrorCallback): void
Enables listening for error events of the TCPSocketServer connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
```
### off('error')<sup>10+</sup>
off(type: 'error', callback?: ErrorCallback): void
Disables listening for error events of the TCPSocketServer connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
let callback = err => {
console.log("on error, err:" + JSON.stringify(err));
}
tcpServer.on('error', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcpServer.off('error', callback);
tcpServer.off('error');
```
## TCPSocketConnection<sup>10+</sup>
Defines a **TCPSocketConnection** object, that is, the connection between the TCPSocket client and the server. Before invoking TCPSocketConnection APIs, you need to obtain a **TCPSocketConnection** object.
**System capability**: SystemCapability.Communication.NetStack
### Attributes
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ----------------------------------------- |
| clientId | number | Yes | ID of the connection between the client and TCPSocketServer.|
### send<sup>10+</sup>
send(options: TCPSendOptions, callback: AsyncCallback\<void\>): void
Sends data over a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API can be called only after a connection with the client is set up.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions7) | Yes | Defines the parameters for sending data over the **TCPSocketConnection** object.|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.send({data: 'Hello, client!'}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
});
});
```
### send<sup>10+</sup>
send(options: TCPSendOptions): Promise\<void\>
Sends data over a **TCPSocketConnection** object. This API uses a promise to return the result.
> **NOTE**
> This API can be called only after a connection with the client is set up.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
| options | [TCPSendOptions](#tcpsendoptions7) | Yes | Defines the parameters for sending data over the **TCPSocketConnection** object.|
**Return value**
| Type | Description |
| :-------------- | :----------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
let promise = client.send({data: 'Hello, client!'});
promise.then(() => {
console.log('send success');
}).catch(err => {
console.log('send fail');
});
});
```
### close<sup>10+</sup>
close(callback: AsyncCallback\<void\>): void
Closes a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.close(err => {
if (err) {
console.log('close fail');
return;
}
console.log('close success');
});
});
```
### close<sup>10+</sup>
close(): Promise\<void\>
Closes a **TCPSocketConnection** object. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :-------------- | :------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| -------- | ---------------------- |
| 201 | Permission denied. |
| 2300002 | System internal error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
let promise = client.close();
promise.then(() => {
console.log('close success');
}).catch(err => {
console.log('close fail');
});
});
```
### getRemoteAddress<sup>10+</sup>
getRemoteAddress(callback: AsyncCallback\<NetAddress\>): void
Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API can be called only after a connection with the client is set up.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ---------- |
| callback | AsyncCallback<[NetAddress](#netaddress7)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------- |
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303188 | Socket operation on non-socket. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.getRemoteAddress((err, data) => {
if (err) {
console.log('getRemoteAddress fail');
return;
}
console.log('getRemoteAddress success:' + JSON.stringify(data));
});
});
```
### getRemoteAddress<sup>10+</sup>
getRemoteAddress(): Promise\<NetAddress\>
Obtains the remote address of a socket connection. This API uses a promise to return the result.
> **NOTE**
> This API can be called only after a connection with the client is set up.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :--------------------------------- | :------------------------------------------ |
| Promise<[NetAddress](#netaddress7)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------- |
| 201 | Permission denied. |
| 2300002 | System internal error. |
| 2303188 | Socket operation on non-socket. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
let promise = client.getRemoteAddress();
promise.then(() => {
console.log('getRemoteAddress success');
}).catch(err => {
console.log('getRemoteAddress fail');
});
});
```
### on('message')<sup>10+</sup>
on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Enables listening for **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | Yes | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.on('message', value => {
let messageView = '';
for (var i = 0; i < value.message.length; i++) {
let messages = value.message[i];
let message = String.fromCharCode(messages);
messageView += item;
}
console.log('on message message: ' + JSON.stringify(messageView));
console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
});
});
```
### off('message')<sup>10+</sup>
off(type: 'message', callback?: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Disables listening for **message** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo7)}> | No | Callback used to return the result. **message**: received message.<br>**remoteInfo**: socket connection information. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let callback = value => {
let messageView = '';
for (var i = 0; i < value.message.length; i++) {
let messages = value.message[i];
let message = String.fromCharCode(messages);
messageView += item;
}
console.log('on message message: ' + JSON.stringify(messageView));
console.log('remoteInfo: ' + JSON.stringify(value.remoteInfo));
}
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.on('message', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
client.off('message', callback);
client.off('message');
});
```
### on('close')<sup>10+</sup>
on(type: 'close', callback: Callback\<void\>): void
Enables listening for **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ----------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br/> **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.on('close', () => {
console.log("on close success")
});
});
```
### off('close')<sup>10+</sup>
on(type: 'close', callback: Callback\<void\>): void
Disables listening for **close** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ----------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br/> **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let callback = () => {
console.log("on close success");
}
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.on('close', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
client.off('close', callback);
client.off('close');
});
```
### on('error')<sup>10+</sup>
on(type: 'error', callback: ErrorCallback): void
Enables listening for **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.on('error', err => {
console.log("on error, err:" + JSON.stringify(err))
});
});
```
### off('error')<sup>10+</sup>
off(type: 'error', callback?: ErrorCallback): void
Disables listening for **error** events of a **TCPSocketConnection** object. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. |
**Error codes**
| ID| Error Message |
| -------- | ---------------- |
| 401 | Parameter error. |
**Example**
```js
let callback = err => {
console.log("on error, err:" + JSON.stringify(err));
}
let tcpServer = socket.constructTCPSocketServerInstance();
tcpServer.on('connect', function(client) {
client.on('error', callback);
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
client.off('error', callback);
client.off('error');
});
```
## Description of TCP Error Codes ## Description of TCP Error Codes
...@@ -1873,7 +2826,7 @@ promise.then(() => { ...@@ -1873,7 +2826,7 @@ promise.then(() => {
on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void; on(type: 'message', callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void;
Subscribes to **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result. Enables listening for **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -1881,7 +2834,7 @@ Subscribes to **message** events of the TLSSocket connection. This API uses an a ...@@ -1881,7 +2834,7 @@ Subscribes to **message** events of the TLSSocket connection. This API uses an a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.| | callback | Callback\<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}\> | Yes | Callback used to return the result.<br> **message**: received message.<br>**remoteInfo**: socket connection information.|
**Example** **Example**
...@@ -1904,7 +2857,7 @@ tls.on('message', value => { ...@@ -1904,7 +2857,7 @@ tls.on('message', value => {
off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void off(type: 'message', callback?: Callback\<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}\>): void
Unsubscribes from **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result. Disables listening for **message** events of the TLSSocket connection. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. > You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
...@@ -1915,7 +2868,7 @@ Unsubscribes from **message** events of the TLSSocket connection. This API uses ...@@ -1915,7 +2868,7 @@ Unsubscribes from **message** events of the TLSSocket connection. This API uses
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- |
| type | string | Yes | Type of the event to subscribe to.<br /> **message**: message receiving event| | type | string | Yes | Type of the event to subscribe to.<br/> **message**: message receiving event|
| callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. **message**: received message.<br>**remoteInfo**: socket connection information.| | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. **message**: received message.<br>**remoteInfo**: socket connection information.|
**Example** **Example**
...@@ -1948,7 +2901,7 @@ Enables listening for connection or close events of the TLSSocket connection. Th ...@@ -1948,7 +2901,7 @@ Enables listening for connection or close events of the TLSSocket connection. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | Yes | Callback used to return the result. | | callback | Callback\<void\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -1978,7 +2931,7 @@ Disables listening for connection or close events of the TLSSocket connection. T ...@@ -1978,7 +2931,7 @@ Disables listening for connection or close events of the TLSSocket connection. T
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /><br>- **connect**: connection event<br>- **close**: close event| | type | string | Yes | Type of the event to subscribe to.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. | | callback | Callback\<void\> | No | Callback used to return the result. |
**Example** **Example**
...@@ -2012,7 +2965,7 @@ Enables listening for error events of the TLSSocket connection. This API uses an ...@@ -2012,7 +2965,7 @@ Enables listening for error events of the TLSSocket connection. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | Yes | Callback used to return the result. | | callback | ErrorCallback | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -2039,7 +2992,7 @@ Disables listening for error events of the TLSSocket connection. This API uses a ...@@ -2039,7 +2992,7 @@ Disables listening for error events of the TLSSocket connection. This API uses a
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------ | | -------- | ------------- | ---- | ------------------------------------ |
| type | string | Yes | Type of the event to subscribe to.<br /> **error**: error event| | type | string | Yes | Type of the event to subscribe to.<br/> **error**: error event|
| callback | ErrorCallback | No | Callback used to return the result. | | callback | ErrorCallback | No | Callback used to return the result. |
**Example** **Example**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册