提交 a6b57c4f 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 aef3a217
# HTTP Data Request
## Use Cases
## When to Use
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
......@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description |
| ----------------------------------------- | --------------------------------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| destroy() | Destroys an HTTP request. |
| API | Description |
| ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop
1. Import the required HTTP module.
2. Create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events.
4. Initiate an HTTP request to a given URL.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js
// Import the http namespace.
import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
......@@ -55,21 +64,33 @@ httpRequest.request(
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // Optional. The default value is 60000, in ms.
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => {
if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements.
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Call the destroy() method to destroy the request if it is no longer needed.
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`HTTP`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
......@@ -18,7 +18,7 @@ import batteryStats from '@ohos.batteryStatistics';
getBatteryStats(): Promise<Array&lt;BatteryStatsInfo&gt;>
Obtains the power consumption information list, using a promise to return the result.
Obtains the power consumption information list. This API uses a promise to return the result.
**System API**: This is a system API.
......@@ -34,9 +34,9 @@ Obtains the power consumption information list, using a promise to return the re
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
......@@ -64,15 +64,15 @@ Obtains the power consumption information list. This API uses an asynchronous ca
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.|
| callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained (that is, **Array<[BatteryStatsInfo](#batterystatsinfo)>>**). If the operation failed, **err** is an error object.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
......@@ -112,9 +112,9 @@ Obtains the power consumption of an application.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
......@@ -153,9 +153,9 @@ Obtains the proportion of the power consumption of an application.
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
......@@ -194,16 +194,16 @@ Obtains the power consumption of a hardware unit according to the consumption ty
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
console.info('battery statistics value of hardware is: ' + value);
} catch(err) {
console.error('get battery statistics percent of hardware failed, err: ' + err);
}
......@@ -235,15 +235,15 @@ Obtains the proportion of the power consumption of a hardware unit according to
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
| Code | Error Message |
|---------|---------|
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
var percent = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) {
console.error('get battery statistics percent of hardware failed, err: ' + err);
......
......@@ -114,9 +114,9 @@ ethernet.setIfaceConfig("eth0", {
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
}).then(() => {
console.log("setIfaceConfig promiss ok ");
console.log("setIfaceConfig promise ok ");
}).catch(error => {
console.log("setIfaceConfig promiss error = " + JSON.stringify(error));
console.log("setIfaceConfig promise error = " + JSON.stringify(error));
});
```
......@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret
```js
ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain));
console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => {
console.log("getIfaceConfig promiss error = " + JSON.stringify(error));
console.log("getIfaceConfig promise error = " + JSON.stringify(error));
});
```
......@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return
```js
ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promiss = " + JSON.stringify(data));
console.log("isIfaceActive promise = " + JSON.stringify(data));
}).catch(error => {
console.log("isIfaceActive promiss error = " + JSON.stringify(error));
console.log("isIfaceActive promise error = " + JSON.stringify(error));
});
```
......@@ -377,12 +377,12 @@ Obtains the list of all active network interfaces. This API uses a promise to re
```js
ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length));
console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i]));
console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
}
}).catch(error => {
console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error));
console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
});
```
......
......@@ -46,6 +46,8 @@ battery.getStatus({
Object that contains the API calling result.
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
| success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.|
......@@ -56,7 +58,9 @@ Object that contains the API calling result.
Defines a response that returns the charging status and remaining power of the device.
| Name| Type| Description|
| -------- | -------- | -------- |
| charging | boolean | Whether the battery is being charged.|
| level | number | Current battery level, which ranges from **0.00** to **1.00**.|
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| charging | boolean | Yes| No| Whether the battery is being charged.|
| level | number | Yes| No| Current battery level, which ranges from **0.00** to **1.00**.|
......@@ -45,7 +45,7 @@ Obtains the current screen brightness.
## brightness.setValue
etValue(options?: SetBrightnessOptions): void
setValue(options?: SetBrightnessOptions): void
Sets the screen brightness.
......@@ -74,7 +74,7 @@ Sets the screen brightness.
## brightness.getMode
getMode(options?: GetBrightnessModeOptions: void
getMode(options?: GetBrightnessModeOptions): void
Obtains the screen brightness adjustment mode.
......@@ -161,67 +161,81 @@ Sets whether to always keep the screen on. Call this API in **onShow()**.
Defines the options for obtaining the screen brightness.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| success | (data: [BrightnessResponse](#brightnessresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessResponse](#brightnessresponse) type.|
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. |
| complete | () => void | No | Called when the API call is complete. |
## SetBrightnessOptions
Defines the options for setting the screen brightness.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| value | number | Yes | Screen brightness. The value is an integer ranging from **1** to **255**.<br>-&nbsp;If the value is less than or equal to **0**, value **1** will be used.<br>-&nbsp;If the value is greater than **255**, value **255** will be used.<br>-&nbsp;If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.|
| success | () => void | No | Called when API call is successful. |
| success | () => void | No | Callback upon a successful API call. |
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. |
| complete | () => void | No | Called when the API call is complete. |
## BrightnessResponse
Defines a response that returns the screen brightness.
| Parameter| Type | Description|
| -------- | -------- | -------- |
| value | number | Screen brightness. The value ranges from 1 to 255.|
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes| No| Screen brightness. The value ranges from **1** to **255**.|
## GetBrightnessModeOptions
Defines the options for obtaining the screen brightness mode.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessModeResponse](#brightnessmoderesponse) type.|
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. |
| complete | () => void | No | Called when the API call is complete. |
## SetBrightnessModeOptions
Defines the options for setting the screen brightness mode.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------------------------------ |
| mode | number | Yes | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.|
| success | () => void | No | Called when API call is successful. |
| success | () => void | No | Callback upon a successful API call. |
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.|
| complete | () => void | No | Called when API call is complete. |
| complete | () => void | No | Called when the API call is complete. |
## BrightnessModeResponse
Defines a response that returns the screen brightness mode.
| Name| Type | Description|
| -------- | -------- | -------- |
| mode | number | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.|
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| mode | number | Yes| No| The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.|
## SetKeepScreenOnOptions
Defines the options for setting the screen to be steady on.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------ | ---- | ------------------------------------------------------ |
| keepScreenOn | boolean | Yes | The value **true** means to keep the screen steady on, and the value **false** indicates the opposite. |
| success | () => void | No | Called when API call is successful. |
| success | () => void | No | Callback upon a successful API call. |
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.|
| complete | () => void | No | Called when API call is complete. |
| complete | () => void | No | Called when the API call is complete. |
# @system.fetch (Data Request)
> **NOTE**
>
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead.
>
>
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -15,7 +14,7 @@ import fetch from '@system.fetch';
```
## fetch.fetch
## fetch.fetch<sup>3+</sup>
fetch(Object): void
......@@ -31,9 +30,9 @@ Obtains data through a network.
| header | Object | No| Request header.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| success | Function | No| Called when data is obtained successfully. The return value is [FetchResponse](#fetchresponse). |
| fail | Function | No| Called when data failed to be obtained.|
| complete | Function | No| Called when the execution is complete.|
| success | Function | No| Called when the API call is successful. The return value is defined by [FetchResponse](#fetchresponse).|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the API call is complete.|
**Table 1** Mapping between data and Content-Type
......@@ -46,11 +45,11 @@ Obtains data through a network.
## FetchResponse
| Name| Type| Description|
| -------- | -------- | -------- |
| code | number | Server status code.|
| data | string \| Object | The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | All headers in the response from the server.|
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| code | number | Yes| No| Server status code.|
| data | string \| Object | Yes| No| The type of the returned data is determined by **responseType**. For details, see the mapping between **responseType** and **data** in **success** callback.|
| headers | Object | Yes| No| All headers in the response from the server.|
**Table 2** Mapping between responseType and data in success callback
......@@ -85,7 +84,7 @@ export default {
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **NOTE**
> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. That is:
>
> ```
......
# @system.network (Network State)
> **NOTE**
>
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead.
> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.telephony.observer`](js-apis-observer.md).
>
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -31,17 +31,17 @@ Obtains the network type.
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the execution is successful. The return value is [NetworkResponse](#networkresponse). |
| fail | Function | No | Called when the operation fails. |
| complete | Function | No | Called when the execution is complete |
| success | Function | No| Called when the API call is successful. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No| Called when API call has failed.|
| complete | Function | No| Called when the API call is complete.|
Return value of the **fail** callback:
One of the following error codes will be returned if the API call has failed.
| Error Code | Description |
| Error Code| Description|
| -------- | -------- |
| 602 | The current permission is not declared. |
| 602 | The current permission is not declared.|
**Example**
......@@ -71,17 +71,17 @@ Listens to the network connection state. If this method is called multiple times
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| success | Function | No | Called when the network connection state changes |
| fail | Function | No | Called when the multimedia volume fails to be obtained. |
| success | Function | No| Called when the network state changes. The return value is defined by [NetworkResponse](#networkresponse).|
| fail | Function | No| Called when API call has failed.|
Return value of the **fail** callback:
One of the following error codes will be returned if the API call has failed.
| Error Code | Description |
| Error Code| Description|
| -------- | -------- |
| 602 | The current permission is not declared. |
| 200 | The subscription fails. |
| 602 | The current permission is not declared.|
| 200 | Subscription failed.|
**Example**
......@@ -119,9 +119,12 @@ export default {
}
```
## NetworkResponse
| Parameter | Type | Description |
| -------- | -------- | -------- |
| metered | boolean | Whether the billing is based on the data volume. |
| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. |
\ No newline at end of file
**System capability**: SystemCapability.Communication.NetManager.Core
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| metered | boolean | No|Whether to charge by traffic.|
| type | string | Yes|Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**.|
......@@ -8,8 +8,10 @@ There are two types of updates: SD card update and over the air (OTA) update.
- The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer.
> **NOTE**
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are system APIs.
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import
......@@ -2034,7 +2036,7 @@ Enumerates update states.
| WAITING_INSTALL | 30 | Waiting for installation. |
| UPDATING | 31 | Updating. |
| WAITING_APPLY | 40 | Waiting for applying the update. |
| APPLYING | 21 | Applying the update. |
| APPLYING | 41 | Applying the update. |
| UPGRADE_SUCCESS | 50 | Update succeeded.|
| UPGRADE_FAIL | 51 | Update failed.|
......@@ -2056,7 +2058,7 @@ Enumerates event IDs.
| Name | Value | Description |
| ---------------------- | ---------- | ------ |
| EVENT_TASK_BASE | 0x01000000 | Task event. |
| EVENT_TASK_BASE | EventClassify.TASK | Task event. |
| EVENT_TASK_RECEIVE | 0x01000001 | Task received. |
| EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. |
......
# @ohos.usbV9 (USB Management)
# @ohos.usbV9 (USB)
The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md).
## Modules to Import
......@@ -29,7 +32,7 @@ Obtains the list of USB devices connected to the host. If no device is connected
```js
let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`);
console.log(`devicesList = ${devicesList}`);
// devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows:
[
......@@ -86,7 +89,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`);
connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
Connects to a USB device based on the device list obtained by using **getDevices()**.
Connects to the USB device based on the device information returned by **getDevices()**.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
......@@ -118,13 +121,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`);
console.log(`devicepipe = ${devicepipe}`);
```
## usb.hasRight
......@@ -133,7 +135,7 @@ hasRight(deviceName: string): boolean
Checks whether the application has the permission to access the device.
The value **true** is returned if the device access permission is available; the value **false** is returned otherwise.
Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise.
**System capability**: SystemCapability.USB.USBManager
......@@ -182,7 +184,7 @@ Requests the temporary permission for the application to access a USB device. Th
```js
let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`);
console.log(`requestRight = ${ret}`);
});
```
......@@ -210,7 +212,7 @@ Removes the permission for the application to access a USB device.
```js
let devicesName="1-1";
if (usb.removeRight(devicesName) {
if usb.removeRight(devicesName) {
console.log(`Succeed in removing right`);
}
```
......@@ -245,7 +247,7 @@ Adds the permission for the application to access a USB device.
```js
let devicesName = "1-1";
let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) {
if usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`);
}
```
......@@ -454,8 +456,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**Example**
```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => {
console.log(`controlTransfer = ${JSON.stringify(ret)}`);
let param = new usb.USBControlParams();
usb.controlTransfer(devicepipe, param).then((ret) => {
console.log(`controlTransfer = ${ret}`);
})
```
......@@ -491,7 +494,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`);
console.log(`bulkTransfer = ${ret}`);
});
```
......@@ -578,7 +581,7 @@ Converts the USB function list in the numeric mask format to a string in Device
**Example**
```js
let funcs = ACM | ECM;
let funcs = usb.ACM | usb.ECM;
let ret = usb.usbFunctionsToString(funcs);
```
......@@ -600,14 +603,14 @@ Sets the current USB function list in Device mode.
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Type | Description |
| --------------- | ------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```js
let funcs = HDC;
let funcs = usb.HDC;
usb.setCurrentFunctions(funcs).then(() => {
console.info('usb setCurrentFunctions successfully.');
}).catch(err => {
......@@ -707,15 +710,15 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Promise\<void\> | Promise used to return the result. |
| Type | Description |
| --------------- | ------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
```js
let portId = 1;
usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.');
}).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
......@@ -730,14 +733,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain
| Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Yes | Endpoint address. |
| attributes | number | Yes | Endpoint attributes. |
| interval | number | Yes | Endpoint interval. |
| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. |
| number | number | Yes | Endpoint number. |
| type | number | Yes | Endpoint type. |
| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.|
| address | number | Yes|Endpoint address. |
| attributes | number | Yes|Endpoint attributes. |
| interval | number | Yes|Endpoint interval. |
| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. |
| number | number | Yes|Endpoint number. |
| type | number | Yes|Endpoint type. |
| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.|
## USBInterface
......@@ -747,13 +750,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
| Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Yes | Unique ID of the USB interface. |
| protocol | number | Yes | Interface protocol. |
| clazz | number | Yes | Device type. |
| subClass | number | Yes | Device subclass. |
| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. |
| id | number | Yes|Unique ID of the USB interface. |
| protocol | number | Yes|Interface protocol. |
| clazz | number | Yes|Device type. |
| subClass | number | Yes|Device subclass. |
| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes|Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. |
## USBConfig
......@@ -763,13 +766,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
| Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Yes | Unique ID of the USB configuration. |
| attributes | number | Yes | Configuration attributes. |
| maxPower | number | Yes | Maximum power consumption, in mA. |
| name | string | Yes | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes | Support for remote wakeup.|
| isSelfPowered | boolean | Yes | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. |
| id | number | Yes|Unique ID of the USB configuration. |
| attributes | number | Yes|Configuration attributes. |
| maxPower | number | Yes|Maximum power consumption, in mA. |
| name | string | Yes|Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes|Support for remote wakeup.|
| isSelfPowered | boolean | Yes| Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. |
## USBDevice
......@@ -779,19 +782,19 @@ Represents the USB device information.
| Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Yes | Bus address. |
| devAddress | number | Yes | Device address. |
| serial | string | Yes | Sequence number. |
| name | string | Yes | Device name. |
| manufacturerName | string | Yes | Device manufacturer. |
| productName | string | Yes | Product name. |
| version | string | Yes | Version number. |
| vendorId | number | Yes | Vendor ID. |
| productId | number | Yes | Product ID. |
| clazz | number | Yes | Device class. |
| subClass | number | Yes | Device subclass. |
| protocol | number | Yes | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.|
| busNum | number | Yes|Bus address. |
| devAddress | number | Yes|Device address. |
| serial | string | Yes|Sequence number. |
| name | string | Yes|Device name. |
| manufacturerName | string | Yes| Device manufacturer. |
| productName | string | Yes|Product name. |
| version | string | Yes|Version number. |
| vendorId | number | Yes|Vendor ID. |
| productId | number | Yes|Product ID. |
| clazz | number | Yes|Device class. |
| subClass | number | Yes|Device subclass. |
| protocol | number | Yes|Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes|Device configuration descriptor information.|
## USBDevicePipe
......@@ -812,12 +815,12 @@ Represents control transfer parameters.
| Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Yes | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. |
| value | number | Yes | Request parameter value. |
| index | number | Yes | Index of the request parameter value.|
| data | Uint8Array | Yes | Buffer for writing or reading data. |
| request | number | Yes |Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. |
| value | number | Yes |Request parameter value. |
| index | number | Yes |Index of the request parameter value.|
| data | Uint8Array | Yes |Buffer for writing or reading data. |
## USBPort
......@@ -829,9 +832,9 @@ Represents a USB port.
| Name | Type | Mandatory |Description |
| -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Yes | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. |
| id | number | Yes |Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. |
## USBPortStatus
......@@ -843,9 +846,9 @@ Enumerates USB port roles.
| Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Yes | Current USB mode. |
| currentPowerRole | number | Yes | Current power role. |
| currentDataRole | number | Yes | Current data role.|
| currentMode | number | Yes|Current USB mode. |
| currentPowerRole | number | Yes |Current power role. |
| currentDataRole | number | Yes |Current data role.|
## USBRequestTargetType
......@@ -853,12 +856,12 @@ Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ---------------------------- | ----- | ----------- |
| USB_REQUEST_TARGET_DEVICE | 0 | Device |
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface |
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint |
| USB_REQUEST_TARGET_OTHER | 3 | Other |
| Name | Value | Description |
| ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint|
| USB_REQUEST_TARGET_OTHER | 3 | Other|
## USBControlRequestType
......
# @ohos.usbManager (USB Management)
# @ohos.usbManager (USB Manager)
The **usbManager** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
......@@ -30,7 +30,7 @@ Obtains the list of USB devices connected to the host. If no device is connected
```js
let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`);
console.log(`devicesList = ${devicesList}`);
// devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows:
[
......@@ -119,13 +119,12 @@ For details about the error codes, see [USB Error Codes](../errorcodes/errorcode
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`);
console.log(`devicepipe = ${devicepipe}`);
```
## usb.hasRight
......@@ -155,7 +154,7 @@ Checks whether the user, for example, the application or system, has the device
```js
let devicesName="1-1";
let bool = usb.hasRight(devicesName);
console.log(bool);
console.log(`${bool}`);
```
## usb.requestRight
......@@ -183,7 +182,7 @@ Requests the temporary permission for the application to access a USB device. Th
```js
let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`);
console.log(`requestRight = ${ret}`);
});
```
......@@ -211,7 +210,7 @@ Removes the permission for the application to access a USB device.
```js
let devicesName="1-1";
if (usb.removeRight(devicesName) {
if usb.removeRight(devicesName) {
console.log(`Succeed in removing right`);
}
```
......@@ -246,7 +245,7 @@ Adds the permission for the application to access a USB device.
```js
let devicesName = "1-1";
let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) {
if usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`);
}
```
......@@ -455,8 +454,9 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**Example**
```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => {
console.log(`controlTransfer = ${JSON.stringify(ret)}`);
let param = new usb.USBControlParams();
usb.controlTransfer(devicepipe, param).then((ret) => {
console.log(`controlTransfer = ${ret}`);
})
```
......@@ -492,7 +492,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`);
console.log(`bulkTransfer = ${ret}`);
});
```
......@@ -579,7 +579,7 @@ Converts the USB function list in the numeric mask format to a string in Device
**Example**
```js
let funcs = ACM | ECM;
let funcs = usb.ACM | usb.ECM;
let ret = usb.usbFunctionsToString(funcs);
```
......@@ -608,7 +608,7 @@ Sets the current USB function list in Device mode.
**Example**
```js
let funcs = HDC;
let funcs = usb.HDC;
usb.setCurrentFunctions(funcs).then(() => {
console.info('usb setCurrentFunctions successfully.');
}).catch(err => {
......@@ -716,7 +716,7 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
```js
let portId = 1;
usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
console.info('usb setPortRoles successfully.');
}).catch(err => {
console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
......
......@@ -64,7 +64,7 @@ ws.connect(defaultIpAddress, (err, value) => {
## webSocket.createWebSocket
createWebSocket\(\): WebSocket
createWebSocket(): WebSocket
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
......@@ -89,7 +89,7 @@ Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call
### connect
connect\(url: string, callback: AsyncCallback<boolean\>\): void
connect(url: string, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
......@@ -128,7 +128,7 @@ ws.connect(url, (err, value) => {
### connect
connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback<boolean\>\): void
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
......@@ -173,7 +173,7 @@ ws.connect(url, {
### connect
connect\(url: string, options?: WebSocketRequestOptions\): Promise<boolean\>
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
......@@ -217,7 +217,7 @@ promise.then((value) => {
### send
send\(data: string | ArrayBuffer, callback: AsyncCallback<boolean\>\): void
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
Sends data through a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -229,7 +229,7 @@ Sends data through a WebSocket connection. This API uses an asynchronous callbac
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result. |
**Error codes**
......@@ -258,7 +258,7 @@ ws.connect(url, (err, value) => {
### send
send\(data: string | ArrayBuffer\): Promise<boolean\>
send(data: string | ArrayBuffer): Promise\<boolean\>
Sends data through a WebSocket connection. This API uses a promise to return the result.
......@@ -270,7 +270,7 @@ Sends data through a WebSocket connection. This API uses a promise to return the
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------ |
| data | string \| ArrayBuffer <sup>8+</sup> | Yes | Data to send.|
| data | string \| ArrayBuffer | Yes | Data to send.<br>Only the string type is supported for API version 6 or earlier. Both the string and ArrayBuffer types are supported for API version 8 or later.|
**Return value**
......@@ -303,7 +303,7 @@ ws.connect(url, (err, value) => {
### close
close\(callback: AsyncCallback<boolean\>\): void
close(callback: AsyncCallback\<boolean\>): void
Closes a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -341,7 +341,7 @@ ws.close((err, value) => {
### close
close\(options: WebSocketCloseOptions, callback: AsyncCallback<boolean\>\): void
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses an asynchronous callback to return the result.
......@@ -383,7 +383,7 @@ ws.close({
### close
close\(options?: WebSocketCloseOptions\): Promise<boolean\>
close(options?: WebSocketCloseOptions): Promise\<boolean\>
Closes a WebSocket connection carrying specified options such as **code** and **reason**. This API uses a promise to return the result.
......@@ -427,9 +427,9 @@ promise.then((value) => {
```
### on\('open'\)
### on('open')
on\(type: 'open', callback: AsyncCallback<Object\>\): void
on(type: 'open', callback: AsyncCallback\<Object\>): void
Enables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -453,9 +453,9 @@ ws.on('open', (err, value) => {
```
### off\('open'\)
### off('open')
off\(type: 'open', callback?: AsyncCallback<Object\>\): void
off(type: 'open', callback?: AsyncCallback\<Object\>): void
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -484,14 +484,14 @@ ws.off('open', callback1);
```
### on\('message'\)
### on('message')
on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
**System capability**: SystemCapability.Communication.NetStack
......@@ -512,14 +512,14 @@ ws.on('message', (err, value) => {
```
### off\('message'\)
### off('message')
off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>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
......@@ -539,9 +539,9 @@ ws.off('message');
```
### on\('close'\)
### on('close')
on\(type: 'close', callback: AsyncCallback<\{ code: number, reason: string \}\>\): void
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
Enables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -552,7 +552,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<{ code: number, reason: string }\> | Yes | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
**Example**
......@@ -564,9 +564,9 @@ ws.on('close', (err, value) => {
```
### off\('close'\)
### off('close')
off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\>\): void
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -580,7 +580,7 @@ Disables listening for the **close** events of a WebSocket connection. This API
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. <br />**close**: event indicating that a WebSocket connection has been closed.|
| callback | AsyncCallback<{ code: number, reason: string }> | No | Callback used to return the result. |
| callback | AsyncCallback\<{ code: number, reason: string }\> | No | Callback used to return the result.<br>**close** indicates the close error code and **reason** indicates the error code description.|
**Example**
......@@ -590,9 +590,9 @@ ws.off('close');
```
### on\('error'\)
### on('error')
on\(type: 'error', callback: ErrorCallback\): void
on(type: 'error', callback: ErrorCallback): void
Enables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......@@ -615,9 +615,9 @@ ws.on('error', (err) => {
```
### off\('error'\)
### off('error')
off\(type: 'error', callback?: ErrorCallback\): void
off(type: 'error', callback?: ErrorCallback): void
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
......
# Socket Error Codes
> **NOTE**
>
> The following describes only the error codes specific to the **socket** module. For details about common error codes, see [Common Error Codes](errorcode-universal.md) file.
## 2301001 Operation Not Allowed
**Error Message**
......
......@@ -109,3 +109,6 @@
- [bytrace](subsys-toolchain-bytrace-guide.md)
- [hdc](subsys-toolchain-hdc-guide.md)
- [hiperf](subsys-toolchain-hiperf.md)
- Power Management
- Display Management
- [System Brightness Customization](subsys-power-brightness-customization.md)
# System Brightness Customization
## Overview
### Introduction
By default, the system brightness of OpenHarmony ranges from **0** to **255** (**0** indicates the minimum luminance and **255** the maximum). It is applicable to the entire system and all application windows. Due to hardware restrictions, some display devices are unable to support the system brightness range. To address this issue, OpenHarmony provides the function of customizing the system brightness range. This way, you can adjust the system brightness range based on the hardware specifications of the display devices.
### Basic Concepts
**System brightness**
Global brightness of OpenHarmony. The customized brightness range is effective for all application windows.
**Window brightness**
Brightness of an application window. The customized brightness range is effective only for this application window. After a brightness is specified for an application window, its brightness is not affected by the system brightness.
### Constraints
The [sysparam](./subsys-boot-init-sysparam.md) module of OpenHarmony provides an easy-to-use key-value pair access interface for system services to configure service functions based on their own system parameters. The customization of the system brightness range is dependent on this feature.
## How to Develop
### Setting Up the Environment
**Hardware requirements:**
Development board running the standard system, for example, the DAYU200 or Hi3516D V300 open source suite.
**Environment requirements:**
For details about the requirements on the Linux environment, see [Quick Start](../quick-start/Readme-EN.md).
### How to Develop
1. In the target directory, create a target folder by referring to the [default brightness value configuration folder](https://gitee.com/openharmony/powermgr_display_manager/tree/master/service/etc). The file format is as follows:
```text
etc
├── BUILD.gn
├── display.para
├── display.para.dac
```
2. Write the customized **display.para** file by referring to the [**display.para** file](https://gitee.com/openharmony/powermgr_display_manager/blob/master/service/etc/display.para) in the default brightness range configuration folder. Include the customized brightness thresholds, for example, **max=150**, **default=75**, and **min=50**, into the file:
```shell
# Brightness limits is 0-255.
const.display.brightness.min=50
const.display.brightness.default=75
const.display.brightness.max=150
```
3. Write the customized **display.para.dac** file by referring to the [**display.para.dac** file](https://gitee.com/openharmony/powermgr_display_manager/blob/master/service/etc/display.para.dac) in the default brightness range configuration folder, so as to grant the permission required to access the customized configuration.
```shell
const.display.brightness.="foundation:foundation:444"
```
4. Write the customized **BUILD.gn** file by referring to the [**BUILD.gn** file](https://gitee.com/openharmony/powermgr_display_manager/blob/master/service/etc/BUILD.gn) in the default brightness range configuration folder. Then, put the **display.para** and **display.para.dac** files to the **/vendor/etc/param** directory. For example:
```shell
import("//base/powermgr/display_manager/displaymgr.gni")
import("//build/ohos.gni")
## Install display.para to /vendor/etc/param/display.para
ohos_prebuilt_etc("display.para") {
source = "display.para"
relative_install_dir = "param"
install_images = [ chipset_base_dir ]
part_name = "${displaymgr_part_name}"
subsystem_name = "powermgr"
}
ohos_prebuilt_etc("display.para.dac") {
source = "display.para.dac"
relative_install_dir = "param"
install_images = [ chipset_base_dir ]
part_name = "${displaymgr_part_name}"
subsystem_name = "powermgr"
}
group("param_files") {
deps = [
":display.para",
":display.para.dac",
]
}
```
5. Write the customized **bundle.json** file by referring to the [**bundle.json** file](https://gitee.com/openharmony/powermgr_display_manager/blob/master/bundle.json) in the default brightness range configuration folder, so as to compile the **BUILD.gn** file.
```shell
"service_group": [ "//base/powermgr/display_manager/service/etc:param_files" ]
```
In the preceding code, **//base/powermgr/display_manager/service** indicates the directory of the created folder, and **etc** indicates the folder name.
6. Build the customized version by referring to [Quick Start](../quick-start/Readme-EN.md). The following command uses DAYU200 as an example:
```shell
./build.sh --product-name rk3568 --ccache
```
7. Burn the customized version to the DAYU200 development board.
### Debugging and Verification
1. After startup, run the following command to launch the shell command line:
```shell
hdc shell
```
2. Run the following command to check the console output:
```shell
hidumper -s 3308 -a -a
```
3. Check the console output for the customized system brightness thresholds.
The default system brightness thresholds are as follows:
```shell
----------------------------------DisplayPowerManagerService---------------------------------
DISPLAY POWER MANAGER DUMP:
Display Id=0 State=2 Discount=1.000000 Brightness=102
DeviceBrightness=102
Support Ambient Light: FALSE
Auto Adjust Brightness: OFF
Brightness Limits: Max=255 Min=5 Default=102
```
Assume that the system brightness thresholds are set to **Max=150 Min=50 Default=75**. The console output is as follows:
```shell
# cd vendor/etc/param
# ls
display.para thermal.para usb.para.dac
display.para.dac thermal.para.dac
# cat display.para
# Copyright (C) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Brightness limits is 0-255.
const.display.brightness.min=50
const.display.brightness.default=75
const.display.brightness.max=150#
#
# cd
# hidumper -s 3308 -a -a
-------------------------------[ability]-------------------------------
----------------------------------DisplayPowerManagerService---------------------------------
DISPLAY POWER MANAGER DUMP:
Display Id=0 State=0 Discount=1.000000 Brightness=75
DeviceBrightness=75
Support Ambient Light: FALSE
Auto Adjust Brightness: OFF
Brightness Limits: Max=150 Min=50 Default=75
```
4. Set the system brightness thresholds to the customized values.
## Reference
For details about how to write the configuration file during system brightness customization, refer to the [default brightness range configuration file](https://gitee.com/openharmony/powermgr_display_manager/tree/master/service/etc).
Default configuration:
```shell
# Brightness limits is 0-255.
const.display.brightness.min=5
const.display.brightness.default=102
const.display.brightness.max=255
```
Packing directory: /system/etc/param
......@@ -36,7 +36,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI
* **Programming language**: C/C++
* **Operating system**: OpenHarmony
* **Operating system**: OpenHarmony mini- and small-system
* **Others**: The System Ability Manager \(Samgr\) has been started and is running properly.
......@@ -314,9 +314,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI
}
```
4. Develop a sample application. For details, see the [keyword spotting demo](https://gitee.com/openharmony/applications_sample_camera/tree/master/ai).
Directory: //applications/sample/camera/ai/asr/keyword\_spotting
4. Develop a sample application.
Call the **Create** API.
......
......@@ -36,6 +36,8 @@ foundation/communication/
4. Call **conn.register()** to subscribe to network status changes of the specified network.
5. When the network is available, the callback will be invoked to return the **netAvailable** event.
6. Call **conn.unregister()** to unsubscribe from the network status changes if required.
```
......@@ -43,9 +45,9 @@ foundation/communication/
import connection from '@ohos.net.connection'
let netCap = {
// Set the network type to cellular network.
// Set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to Internet.
// Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
};
let netSpec = {
......@@ -55,7 +57,7 @@ foundation/communication/
let timeout = 10 * 1000;
// Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout);
// Subscribe to the netAvailable event. When the network is available, the callback will be invoked to report the event.
// Subscribe to the netAvailable event.
conn.on('netAvailable', (data=> {
console.log("net is available, netId is " + data.netId);
}));
......@@ -67,16 +69,12 @@ foundation/communication/
### Sharing a Network
1. Import the network sharing namespace from **@ohos.net.sharing**.
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Set the network sharing type.
3. Start network sharing.
4. Stop network sharing.
```
// Import the network sharing namespace.
// Import the connection namespace.
import sharing from '@ohos.net.sharing';
// Set the network sharing type.
this.sharingType = 0; // The value 0 indicates Wi-Fi, 1 indicates USB, and 2 indicates Bluetooth.
......@@ -92,33 +90,30 @@ sharing.stopSharing(this.sharingType,(err)=>{
### Initiating a Network Request
1. Import the HTTP namespace from **@ohos.net.http.d.ts**.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to an HTTP response header. This method returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **httpRequest.destroy()** to release resources after the request is processed.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```
// Import the HTTP namespace.
// Import the http namespace.
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than the response to httpRequest.
httpRequest.on('headersReceive', (data) => {
console.info('header: ' + data.header);
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Set the URL for the httpRequest. You must specify the URL address, and set httpRequestOptions as required. You can specify the parameters for GET in extraData.
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: 'POST', // Optional. The default value is GET.
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
......@@ -127,21 +122,28 @@ httpRequest.request(
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s.
readTimeout: 60000, // This parameter is optional. The default value is 60000, that is, 60s.
},(err, data) => {
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + data.header);
console.info('header:' + data.cookies);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + err);
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
// Call destroy() to release resources after HttpRequest is complete.
httpRequest.destroy();
}
);
```
......@@ -150,8 +152,6 @@ httpRequest.request(
**Network Management Subsystem**
[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base)
[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext)
[communication_netstack](https://gitee.com/openharmony/communication_netstack)
\ No newline at end of file
[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base/blob/master/README_zh.md)
[communication_netmanager_ext](https://gitee.com/openharmony/communication_netmanager_ext/blob/master/README_zh.md)
[communication_netstack](https://gitee.com/openharmony/communication_netstack/blob/master/README_zh.md)
# Globalization Subsystem Changelog
## cl.resourceManager.1 Change in the Meaning of the Return Value for the API Used to Obtain the rawfile Descriptor
Changed the meaning of the return value for the API used to obtain the rawfile descriptor after the non-decompression feature is added in this version. The change in the meaning of the return value, namely, **descriptor: RawFileDescriptor {fd, offset, length}**, is described as follows:
**Before change:**
**fd**: file descriptor for accessing the rawfile.
**offset**: offset for accessing the rawfile. In this case, the value is **0**.
**length**: size of the rawfile to access.
**After change:**
**fd**: file descriptor for accessing the HAP where the rawfile is located.
**offset**: offset of the accessed rawfile relative to the HAP.
**length**: size of the rawfile to access.
**Change Impact**
In versions earlier than 4.0.2.2, the rawfile can be accessed only through **fd**. In version 4.0.2.2 or later, the rawfile can be accessed only through **{fd, offset, and length}**.
**Key API/Component Changes**
| **Original API** |
| ---------------- |
| getRawFd(path: string, callback: AsyncCallback\<RawFileDescriptor>): void |
| getRawFd(path: string): Promise\<RawFileDescriptor> |
| getRawFileDescriptor(path: string, callback: AsyncCallback\<RawFileDescriptor>): void|
| getRawFileDescriptor(path: string): Promise\<RawFileDescriptor>|
||
**Sample Code**
The following is an example of calling the **getRawFd** API:
```
try {
this.context.resourceManager.getRawFd("test.ogg", (error, value) => {
if (error != null) {
console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
} else {
let fileDescriptor = {
fd = value.fd,
offset = value.offset,
length = value.length
}
this.avPlayer.fdSrc(fileDescriptor); // Take the audio player as an example. When calling fdSrc, pass fileDescriptor in addition to fd.
}
});
} catch (error) {
console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`)
};
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册