diff --git a/CODEOWNERS b/CODEOWNERS
index 025c30e10317662d65ab6b1d45688bf87ef41817..a98eba13b7b574232201efd76d84579561a42ccd 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -85,14 +85,19 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin
-zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23
-zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23
-zh-cn/device-dev/subsystems/subsys-boot-appspawn-standard.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23
-zh-cn/device-dev/subsystems/subsys-boot-syspara.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-cfg.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-service.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-sysparam.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-ref.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot.md @Austin23
zh-cn/device-dev/subsystems/subsys-testguide-test.md @Austin23
zh-cn/device-dev/subsystems/subsys-dfx-overview.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md @duangavin123_admin
diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md
index 6d25dfc5658b20f7005c59287d4475f3eb4e5071..1331ac52206cf1980ce59a7def62bfd32c27e406 100644
--- a/en/OpenHarmony-Overview.md
+++ b/en/OpenHarmony-Overview.md
@@ -146,13 +146,13 @@ The following table describes the subsystems of OpenHarmony. For details about t
## Supported Development Boards
-Currently, the OpenHarmony community supports 17 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master).
+Currently, the OpenHarmony community supports 17 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master. You can visit http://ci.openharmony.cn/dailys/dailybuilds to obtain daily builds.
-| System Type| Board Model| Chip Model| Function Description and Use Case| Application Scenario| Code Repository and Daily Build|
+| System Type| Board Model| Chip Model|
Function Description and Use Case
| Application Scenario| Code Repository |
| -------- | -------- | -------- | -------- | -------- | -------- |
-| Standard system| Runhe HH-SCDAYU200| RK3568 | Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
Use case:
[DAYU200 Use Case](device-dev/porting/porting-dayu200-on_standard-demo.md)| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| Code repositories:
[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Small system| Hispark_Taurus | Hi3516DV300 | Function Description:
Hi3516D V300 is the next-generation system on chip (SoC) for smart HD IP cameras. It integrates the next-generation image signal processor (ISP), H.265 video compression encoder, and high-performance NNIE engine, and delivers high performance in terms of low bit rate, high image quality, intelligent processing and analysis, and low power consumption.| Smart device with screens, such as refrigerators with screens and head units.| Code repositories:
[device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Mini system| Multi-modal V200Z-R | BES2600 | Function description:
The multi-modal V200Z-R development board is a high-performance, multi-functional, and cost-effective AIoT SoC powered by the BES2600WM chip of Bestechnic. It integrates a quad-core ARM processor with a frequency of up to 1 GHz as well as dual-mode Wi-Fi and dual-mode Bluetooth. The board supports the 802.11 a/b/g/n/ and BT/BLE 5.2 standards. It is able to accommodate RAM of up to 42 MB and flash memory of up to 32 MB, and supports the MIPI display serial interface (DSI) and camera serial interface (CSI). It is applicable to various AIoT multi-modal VUI and GUI interaction scenarios.
Use case:
[Multi-modal V200Z-R Use Case](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md)| Smart hardware, and smart devices with screens, such as speakers and watches.| Code repositories:
[device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
+| Standard system| Runhe HH-SCDAYU200| RK3568 | Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
Use case:
[DAYU200 Use Case](device-dev/porting/porting-dayu200-on_standard-demo.md)
| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| [device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
|
+| Small system| Hispark_Taurus | Hi3516DV300 | Function Description:
Hi3516D V300 is the next-generation system on chip (SoC) for smart HD IP cameras. It integrates the next-generation image signal processor (ISP), H.265 video compression encoder, and high-performance NNIE engine, and delivers high performance in terms of low bit rate, high image quality, intelligent processing and analysis, and low power consumption.
| Smart device with screens, such as refrigerators with screens and head units.| [device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
|
+| Mini system| Multi-modal V200Z-R | BES2600 | Function description:
The multi-modal V200Z-R development board is a high-performance, multi-functional, and cost-effective AIoT SoC powered by the BES2600WM chip of Bestechnic. It integrates a quad-core ARM processor with a frequency of up to 1 GHz as well as dual-mode Wi-Fi and dual-mode Bluetooth. The board supports the 802.11 a/b/g/n/ and BT/BLE 5.2 standards. It is able to accommodate RAM of up to 42 MB and flash memory of up to 32 MB, and supports the MIPI display serial interface (DSI) and camera serial interface (CSI). It is applicable to various AIoT multi-modal VUI and GUI interaction scenarios.
Use case:
[Multi-modal V200Z-R Use Case](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md)
| Smart hardware, and smart devices with screens, such as speakers and watches.| [device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
|
## Getting Started
diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability/ability-brief.md
index 187064a1c67d7bd21c823a945cca79366428d3f8..9943d4d697fa787db084fc14848d37abdad90fe9 100644
--- a/en/application-dev/ability/ability-brief.md
+++ b/en/application-dev/ability/ability-brief.md
@@ -4,8 +4,8 @@ An ability is the abstraction of a functionality that an application can provide
The ability framework model has two forms.
-- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
-- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
+- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
+- Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md
index c07f787d38091637215907537e54812c397a417e..7065480d1c4a12bd0984f4916d678c1bed7a4997 100644
--- a/en/application-dev/application-dev-guide.md
+++ b/en/application-dev/application-dev-guide.md
@@ -54,8 +54,14 @@ To make you better understand how functions work together and jumpstart your app
API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively.
They are organized as follows:
-- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
-- Native APIs
- - [Standard Library](reference/native-lib/third_party_libc/musl.md)
- - [Node_API](reference/native-lib/third_party_napi/napi.md)
+
+- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
+
+- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
+
+- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
+
+- Native APIs
+ - [Standard Library](reference/native-lib/third_party_libc/musl.md)
+ - [Node_API](reference/native-lib/third_party_napi/napi.md)
diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md
index 3d541e4832aa72a585972d327e2fb2f31a077fa6..fadb084eecebc65fe59fba9245829d28ce7b6095 100644
--- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md
+++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md
@@ -33,7 +33,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
IRemoteProxy
|
- |
+ |
Service proxy classes are derived from the IRemoteProxy class.
|
diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md
index fa70738556ec7992c33fd8bcf3e74fbd6145fcb6..8d9365d6bbba940bb85d9ac7493b7069c48845eb 100755
--- a/en/application-dev/connectivity/subscribe-remote-state.md
+++ b/en/application-dev/connectivity/subscribe-remote-state.md
@@ -1,25 +1,30 @@
-# Subscribing to State Changes of a Remote Object
+# Subscribing to State Changes of a Remote Object
-IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. You can also unsubscribe from the state changes if they are no longer needed. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **IRemoteObject.DeathRecipient** interface and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
+IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** callback and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network.
-**Development Using Native APIs**
+Note that the proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
-The following APIs are used to add a recipient for death notifications of a remote stub object, remove such a recipient, and perform subsequent operations upon receiving a death notification of the remote stub object:
-```
-bool AddDeathRecipient(const sptr &recipient);
-bool RemoveDeathRecipient(const sptr &recipient);
-void OnRemoteDied(const wptr &object);
-```
-The sample code is as follows:
+
+## **Development Using Native APIs**
+
+| API| Description|
+| -------- | -------- |
+| AddDeathRecipient(const sptr\ &recipient); | Adds a recipient for death notifications of a remote stub object.|
+| RemoveDeathRecipient(const sptr\ &recipient); | Removes the recipient for death notifications of a remote stub object.|
+| OnRemoteDied(const wptr\ &object); | Called when the remote stub object dies.|
+
+
+## Sample Code
+
```
class TestDeathRecipient : public IRemoteObject::DeathRecipient {
public:
virtual void OnRemoteDied(const wptr& remoteObject);
}
-sptr deathRecipient (new TestDeathRecipient()); // Construct a death notification recipient.
-bool result = proxy->AddDeathRecipient(deathRecipient); // Add the recipient to the proxy.
-result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient.
+sptr deathRecipient (new TestDeathRecipient());// Construct a death notification recipient.
+bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
+result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
```
diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md
index 01f5f38fad74e234c8a9fb483ee4a11ae2a8c7a7..b68d537fc5ad96f3ab60b53e2e75a96d7b555f76 100644
--- a/en/application-dev/connectivity/websocket-connection.md
+++ b/en/application-dev/connectivity/websocket-connection.md
@@ -3,7 +3,7 @@
## Use Cases
-You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket** API to create a **WebSocket** object and then use the **connect** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
+You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
@@ -18,14 +18,14 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. |
-| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
-| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
-| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
-| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
-| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
-| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
-| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
-| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
+| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
+| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
+| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
+| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
+| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
+| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
+| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
+| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
## How to Develop
@@ -50,9 +50,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
if (!err) {
- console.log("send success");
+ console.log("Message sent successfully");
} else {
- console.log("send fail, err:" + JSON.stringify(err));
+ console.log("Failed to send the message. Err:" + JSON.stringify(err));
}
});
});
@@ -62,9 +62,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
- console.log("close success");
+ console.log("Connection closed successfully");
} else {
- console.log("close fail, err is " + JSON.stringify(err));
+ console.log("Failed to close the connection. Err: " + JSON.stringify(err));
}
});
}
@@ -77,9 +77,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
- console.log("connect success");
+ console.log("Connected successfully");
} else {
- console.log("connect fail, err:" + JSON.stringify(err));
+ console.log("Connection failed. Err:" + JSON.stringify(err));
}
});
```
diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md
index e1d4cddeb2ff96c8a07a6df84382ad0b8d22464c..54199719cd93a523d8f2b0af14c12578997a02a2 100644
--- a/en/application-dev/dfx/hiappevent-guidelines.md
+++ b/en/application-dev/dfx/hiappevent-guidelines.md
@@ -2,13 +2,13 @@
## When to Use
-The event logging function helps applications log various information generated during running.
+The event logging function helps applications to log various information generated during running.
## Available APIs
JS application event logging APIs are provided by the **hiAppEvent** module.
-**APIs for Event Logging**
+**Table 1** APIs for event logging
| API | Return Value | Description |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
@@ -17,7 +17,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module.
When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
-**APIs for Event Logging Configuration**
+**Table 2** APIs for event logging configuration
| API | Return Value | Description |
| ------------------------------ | ------------ | ------------------------------------------------------------ |
diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md
index 403aec02035c965da4633e8667be6803031ddf60..2a5e36f879a922f3d6bf845e700068c2a299b337 100644
--- a/en/application-dev/dfx/hiappevent-overview.md
+++ b/en/application-dev/dfx/hiappevent-overview.md
@@ -2,8 +2,10 @@
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
+The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
+
## Basic Concepts
-The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
+- **Logging**
-**Logging**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
+ Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md
index de4f037bab24fd90b7196b5cc89e56cb1b771a06..316ee1b07898a24721b81625c2e9193ae08aa85f 100644
--- a/en/application-dev/dfx/hitracemeter-guidelines.md
+++ b/en/application-dev/dfx/hitracemeter-guidelines.md
@@ -8,7 +8,7 @@ HiTraceMeter provides APIs for system performance tracing. You can call the APIs
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
-**APIs for performance tracing**
+**Table 1** APIs for performance tracing
| API| Return Value| Description|
| ---------------------------------------------------------------------------- | --------- | ------------ |
diff --git a/en/application-dev/dfx/hitracemeter-overview.md b/en/application-dev/dfx/hitracemeter-overview.md
index 3683092b34fcd23a65245303406934b3fb8acad5..649fa7704dd566ab8bc02776de6f62756d7f26a6 100644
--- a/en/application-dev/dfx/hitracemeter-overview.md
+++ b/en/application-dev/dfx/hitracemeter-overview.md
@@ -15,4 +15,4 @@ hiTraceMeter is a tool for you to trace service processes and monitor system per
## Constraints
-- Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
+Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md
index 66b002200fc1c1965f1d3e741739685ae97236e6..0e34d66d523abea51e259bbcea5d7be08e755e3e 100644
--- a/en/application-dev/internationalization/i18n-guidelines.md
+++ b/en/application-dev/internationalization/i18n-guidelines.md
@@ -23,57 +23,64 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop
-1. Obtain the system language.
+1. Obtain the system language.
+
Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module).
- ```
+ ```js
var language = i18n.getSystemLanguage();
```
-2. Obtain the system region.
+2. Obtain the system region.
+
Call the **getSystemRegion** method to obtain the system region.
- ```
+ ```js
var region = i18n.getSystemRegion();
```
-3. Obtain the system locale.
+3. Obtain the system locale.
+
Call the **getSystemLocale** method to obtain the system locale.
- ```
+ ```js
var locale = i18n.getSystemLocale();
```
-4. Check whether the locale's language is RTL.
+4. Check whether the locale's language is RTL.
+
Call the **isRTL** method to check whether the locale's language is RTL.
- ```
+ ```js
var rtl = i18n.isRTL("zh-CN");
```
-5. Check whether the system uses a 24-hour clock.
+5. Check whether the system uses a 24-hour clock.
+
Call the **is24HourClock** method to check whether the system uses a 24-hour clock.
- ```
+ ```js
var hourClock = i18n.is24HourClock();
```
-6. Obtain the localized display of a language.
+6. Obtain the localized display of a language.
+
Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
- ```
+ ```js
var language = "en";
var locale = "zh-CN";
var sentenceCase = false;
var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase);
```
-7. Obtain the localized display of a country.
+7. Obtain the localized display of a country.
+
Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
- ```
+ ```js
var country = "US";
var locale = "zh-CN";
var sentenceCase = false;
@@ -106,70 +113,78 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop
-1. Instantiate a **Calendar** object.
+1. Instantiate a **Calendar** object.
+
Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used.
- ```
+ ```js
var calendar = i18n.getCalendar("zh-CN", "gregory);
```
-2. Set the time for the **Calendar** object.
+2. Set the time for the **Calendar** object.
+
Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT.
- ```
+ ```js
var date1 = new Date();
calendar.setTime(date1);
var date2 = 1000;
calendar.setTime(date2);
```
-3. Set the year, month, day, hour, minute, and second for the **Calendar** object.
+3. Set the year, month, day, hour, minute, and second for the **Calendar** object.
+
Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object.
- ```
+ ```js
calendar.set(2021, 12, 21, 6, 0, 0)
```
-4. Set and obtain the time zone for the **Calendar** object.
+4. Set and obtain the time zone for the **Calendar** object.
+
Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set.
- ```
+ ```js
calendar.setTimeZone("Asia/Shanghai");
var timezone = calendar.getTimeZone();
```
-5. Set and obtain the first day of a week for the **Calendar** object.
+5. Set and obtain the first day of a week for the **Calendar** object.
+
Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.
- ```
+ ```js
calendar.setFirstDayOfWeek(1);
var firstDayOfWeek = calendar.getFirstDayOfWeek();
```
-6. Set and obtain the minimum count of days in the first week for the **Calendar** object.
+6. Set and obtain the minimum count of days in the first week for the **Calendar** object.
+
Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object.
- ```
+ ```js
calendar.setMinimalDaysInFirstWeek(3);
var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek();
```
-7. Obtain the localized display of the **Calendar** object.
+7. Obtain the localized display of the **Calendar** object.
+
Call the **getDisplayName** method to obtain the localized display of the **Calendar** object.
- ```
+ ```js
var localizedName = calendar.getDisplayName("zh-CN");
```
-8. Check whether a date is a weekend.
+8. Check whether a date is a weekend.
+
Call the **isWeekend** method to determine whether the input date is a weekend.
- ```
+ ```js
var date = new Date();
var weekend = calendar.isWeekend(date);
```
@@ -191,25 +206,26 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop
-1. Instantiate a **PhoneNumberFormat** object.
+1. Instantiate a **PhoneNumberFormat** object.
+
Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**.
- ```
+ ```js
var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"});
```
2. Check whether the phone number format is correct.
Call the **isValidNumber** method to check whether the format of the input phone number is correct.
- ```
+ ```js
var validNumber = phoneNumberFormat.isValidNumber("15812341234");
```
3. Format a phone number.
Call the **format** method of **PhoneNumberFormat** to format the input phone number.
- ```
+ ```js
var formattedNumber = phoneNumberFormat.format("15812341234");
```
@@ -232,7 +248,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result.
- ```
+ ```js
var fromUnit = {unit: "cup", measureSystem: "US"};
var toUnit = {unit: "liter", measureSystem: "SI"};
var number = 1000;
@@ -259,32 +275,36 @@ The **unitConvert** API is provided to help you implement measurement conversion
### How to Develop
-1. Instantiate an **IndexUtil** object.
+1. Instantiate an **IndexUtil** object.
+
Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale.
- ```
+ ```js
var indexUtil = getInstance("zh-CN");
```
-2. Obtain the index list.
+2. Obtain the index list.
+
Call the **getIndexList** method to obtain the alphabet index list of the current locale.
- ```
+ ```js
var indexList = indexUtil.getIndexList();
```
-3. Add an index.
+3. Add an index.
+
Call the **addLocale** method to add the alphabet index of a new locale to the current index list.
- ```
+ ```js
indexUtil.addLocale("ar")
```
-4. Obtain the index of a string.
+4. Obtain the index of a string.
+
Call the **getIndex** method to obtain the alphabet index of a string.
- ```
+ ```js
var text = "access index";
indexUtil.getIndex(text);
```
@@ -313,38 +333,42 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
### How to Develop
-1. Instantiate a **BreakIterator** object.
+1. Instantiate a **BreakIterator** object.
+
Call the **getLineInstance** method to instantiate a **BreakIterator** object.
- ```
+ ```js
var locale = "en-US"
var breakIterator = i18n.getLineInstance(locale);
```
-2. Set and access the text that requires line breaking.
+2. Set and access the text that requires line breaking.
+
Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking.
- ```
+ ```js
var text = "Apple is my favorite fruit";
breakIterator.setLineBreakText(text);
var breakText = breakIterator.getLineBreakText();
```
-3. Obtain the current position of the **BreakIterator** object.
+3. Obtain the current position of the **BreakIterator** object.
+
Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed.
- ```
+ ```js
var pos = breakIterator.current();
```
-4. Set the position of a **BreakIterator** object.
+4. Set the position of a **BreakIterator** object.
+
The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed.
- ```
+ ```js
var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text.
var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end.
// Move a BreakIterator object forward or backward by a certain number of break points.
@@ -356,10 +380,11 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
var followingPos = breakIterator.following(10);
```
-5. Determine whether a position is a break point.
+5. Determine whether a position is a break point.
+
Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position.
- ```
+ ```js
var isboundary = breakIterator.isBoundary(5);
```
diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md
index 34d2d1b19aea81ee810c472b7ffaf297b0478091..44748056f7886d4817cda2d9d0504f6966c32700 100644
--- a/en/application-dev/internationalization/intl-guidelines.md
+++ b/en/application-dev/internationalization/intl-guidelines.md
@@ -3,7 +3,8 @@
This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402.
The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
-> **NOTE**
+> **NOTE**
+>
> In the code snippets in this document, **intl** refers to the name of the imported module.
## Setting Locale Information
@@ -24,7 +25,8 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
### How to Develop
-1. Instantiate a **Locale** object.
+1. Instantiate a **Locale** object.
+
Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list.
A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-).
@@ -42,30 +44,33 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
| kf | Whether upper case or lower case is considered when sorting or comparing strings.|
- ```
+ ```js
var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: pinyin};
var localeObj = new intl.Locale(locale, options);
```
-2. Obtain the string representing a **Locale** object.
+2. Obtain the string representing a **Locale** object.
+
Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options.
- ```
+ ```js
var localeStr = localeObj.toString();
```
-3. Maximize locale information.
+3. Maximize locale information.
+
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information.
- ```
+ ```js
var maximizedLocale = localeObj.maximize();
```
-4. Minimize locale information.
+4. Minimize locale information.
+
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information.
- ```
+ ```js
var minimizedLocale = localeObj.minimize();
```
@@ -88,42 +93,46 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
### How to Develop
-1. Instantiate a **DateTimeFormat** object.
+1. Instantiate a **DateTimeFormat** object.
+
Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object.
- ```
+ ```js
var dateTimeFormat = new intl.DateTimeFormat();
```
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var options = {dateStyle: "full", timeStyle: "full"};
var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options);
```
-2. Format the date and time.
+2. Format the date and time.
+
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
- ```
+ ```js
Date date = new Date();
var formatResult = dateTimeFormat.format(date);
```
-3. Format a period.
+3. Format a period.
+
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
- ```
+ ```js
Date startDate = new Date();
Date endDate = new Date();
var formatResult = dateTimeFormat.formatRange(startDate, endDate);
```
-4. Obtain attributes of the **DateTimeFormat** object.
+4. Obtain attributes of the **DateTimeFormat** object.
+
Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object.
- ```
+ ```js
var options = dateTimeFormat.resolvedOptions();
```
@@ -145,33 +154,36 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
### How to Develop
-1. Instantiate a **NumberFormat** object.
+1. Instantiate a **NumberFormat** object.
+
Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object.
- ```
+ ```js
var numberFormat = new intl.NumberFormat();
```
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var options = {compactDisplay: "short", notation: "compact"};
var numberFormat = new intl.NumberFormat("zh-CN", options);
```
-2. Format a number.
+2. Format a number.
+
Call the **format** method to format a number. A string is returned as the formatting result.
- ```
+ ```js
var number = 1234.5678
var formatResult = numberFormat.format(number);
```
-3. Obtain attributes of the **NumberFormat** object.
+3. Obtain attributes of the **NumberFormat** object.
+
Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object.
- ```
+ ```js
var options = numberFormat.resolvedOptions();
```
@@ -193,33 +205,36 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
### How to Develop
-1. Instantiate a **Collator** object.
+1. Instantiate a **Collator** object.
+
Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object.
- ```
+ ```js
var collator = new intl.Collator();
```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md).
+ ```js
+ var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"});
```
- var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"};
- ```
-2. Compare two strings.
+2. Compare two strings.
+
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths.
- ```
+ ```js
var str1 = "first string";
var str2 = "second string";
var compareResult = collator.compare(str1, str2);
```
-3. Obtain attributes of the **Collator** object.
+3. Obtain attributes of the **Collator** object.
+
Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object.
- ```
+ ```js
var options = collator.resolvedOptions();
```
@@ -240,24 +255,26 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
### How to Develop
-1. Instantiate a **PluralRules** object.
+1. Instantiate a **PluralRules** object.
+
Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object.
- ```
+ ```js
var pluralRules = new intl.PluralRules();
```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md).
- ```
- var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"};
+ ```js
+ var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
```
-2. Determine the singular-plural type.
+2. Determine the singular-plural type.
+
Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**.
- ```
+ ```js
var number = 1234.5678
var categoryResult = plurals.select(number);
```
@@ -281,41 +298,45 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
### How to Develop
-1. Instantiate a **RelativeTimeFormat** object.
+1. Instantiate a **RelativeTimeFormat** object.
+
Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object.
- ```
+ ```js
var relativeTimeFormat = new intl.RelativeTimeFormat();
```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
```
-2. Format the relative time.
+2. Format the relative time.
+
Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result.
- ```
+ ```js
var number = 2;
var unit = "year"
var formatResult = relativeTimeFormat.format(number, unit);
```
-3. Obtain each part of the relative time format.
+3. Obtain each part of the relative time format.
+
Upon obtaining each part of the relative time format, customize the relative time formatting result.
- ```
+ ```js
var number = 2;
var unit = "year"
var formatResult = relativeTimeFormat.formatToParts(number, unit);
```
-4. Obtain attributes of the **RelativeTimeFormat** object.
+4. Obtain attributes of the **RelativeTimeFormat** object.
+
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var options = numberFormat.resolvedOptions();
```
diff --git a/en/application-dev/media/audio-interruptmode.md b/en/application-dev/media/audio-interruptmode.md
index 9f9355f68c326ec9b6ae8140a6579114bfaefcc3..8be8a00cedd10ff4ecd08ee46d746d9803b3c71a 100644
--- a/en/application-dev/media/audio-interruptmode.md
+++ b/en/application-dev/media/audio-interruptmode.md
@@ -48,7 +48,7 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference
```js
var mode_ = audio.InterruptMode.SHARE_MODE;
- await this.audioRenderer.setInterruptMode(mode_).then(()=>{
+ await this.audioRenderer.setInterruptMode(mode_).then(() => {
console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success");
});
```
diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md
index 17ef631d0f7207b676177a59d0903cc77dcd1045..f9d286cbd34296fa43596032fe89f2ecdd6e5d93 100644
--- a/en/application-dev/reference/apis/js-apis-accessibility.md
+++ b/en/application-dev/reference/apis/js-apis-accessibility.md
@@ -1,6 +1,9 @@
# Accessibility
-> **NOTE**
+The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration.
+
+> **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.
## Modules to Import
@@ -13,162 +16,162 @@ import accessibility from '@ohos.accessibility';
Enumerates the states of an accessibility application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | enable | The accessibility application is enabled. |
- | disable | The accessibility application is disabled. |
- | install | The accessibility application has been installed. |
+| Name| Description|
+| -------- | -------- |
+| enable | The accessibility application is enabled.|
+| disable | The accessibility application is disabled.|
+| install | The accessibility application has been installed.|
## AbilityType
Enumerates the types of accessibility applications.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | audible | The accessibility application provides audible feedback. |
- | generic | The accessibility application provides generic feedback. |
- | haptic | The accessibility application provides haptic feedback. |
- | spoken | The accessibility application provides spoken feedback. |
- | visual | The accessibility application provides visual feedback. |
+| Name| Description|
+| -------- | -------- |
+| audible | The accessibility application provides audible feedback.|
+| generic | The accessibility application provides generic feedback.|
+| haptic | The accessibility application provides haptic feedback.|
+| spoken | The accessibility application provides spoken feedback.|
+| visual | The accessibility application provides visual feedback.|
+| all9+ | All the preceding types.|
## AccessibilityAbilityInfo
Provides information about an accessibility application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | id | number | Yes | No | Ability ID. |
- | name | string | Yes | No | Ability name. |
- | bundleName | string | Yes | No | Bundle name. |
- | abilityTypes | Array<[AbilityType](#abilitytype)> | Yes | No | Accessibility application type. |
- | capabilities | Array<[Capability](#capability)> | Yes | No | Capabilities list of the accessibility application. |
- | description | string | Yes | No | Description of the accessibility application. |
- | eventTypes | Array<[EventType](#eventtype)> | Yes | No | List of events that the accessibility application focuses on. |
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| id | number | Yes| No| Ability ID.|
+| name | string | Yes| No| Ability name.|
+| bundleName | string | Yes| No| Bundle name.|
+| targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.|
+| abilityTypes | Array<[AbilityType](#abilitytype)> | Yes| No| Accessibility application type.|
+| capabilities | Array<[Capability](#capability)> | Yes| No| Capabilities list of the accessibility application.|
+| description | string | Yes| No| Description of the accessibility application.|
+| eventTypes | Array<[EventType](#eventtype)> | Yes| No| List of events that the accessibility application focuses on.|
## Action
Describes the target action supported by an accessibility application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
-
- | Name | Description |
- | -------- | -------- |
- | click | Clicking. |
- | longClick | Long pressing. |
- | scrollForward | Scrolling forward. |
- | scrollBackward | Scrolling backward. |
- | focus | Obtaining focus. |
- | clearFocus | Clearing focus. |
- | clearSelection | Clearing selection. |
- | accessibilityFocus | Obtaining the accessibility focus. |
- | clearAccessibilityFocus | Clearing the accessibility focus. |
- | cut | Cut. |
- | copy | Copy. |
- | paste | Paste. |
- | select | Select. |
- | setText | Setting the text. |
- | delete | Delete. |
- | setSelection | Setting the selection. |
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
+
+| Name| Description|
+| -------- | -------- |
+| click | Clicking.|
+| longClick | Long pressing.|
+| scrollForward | Scrolling forward.|
+| scrollBackward | Scrolling backward.|
+| focus | Obtaining focus.|
+| clearFocus | Clearing focus.|
+| clearSelection | Clearing selection.|
+| accessibilityFocus | Obtaining the accessibility focus.|
+| clearAccessibilityFocus | Clearing the accessibility focus.|
+| cut | Cut.|
+| copy | Copy.|
+| paste | Paste.|
+| select | Select.|
+| setText | Setting the text.|
+| delete | Delete.|
+| setSelection | Setting the selection.|
## Capability
Enumerates the capabilities of an auxiliary application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | retrieve | Capability to retrieve the window content. |
- | touchGuide | Capability of touch guide mode. |
- | keyEventObserver | Capability to filter key events. |
- | zoom | Capability to control the display zoom level. |
- | gesture | Capability to perform gesture actions. |
+| Name| Description|
+| -------- | -------- |
+| retrieve | Capability to retrieve the window content.|
+| touchGuide | Capability of touch guide mode.|
+| keyEventObserver | Capability to filter key events.|
+| zoom | Capability to control the display zoom level.|
+| gesture | Capability to perform gesture actions.|
## CaptionsFontEdgeType8+
-Enumerates the caption font edge type.
+Enumerates the font edge types of captions.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Description |
- | -------- | -------- |
- | none | No effect. |
- | raised | Raised effect. |
- | depressed | Depressed effect. |
- | uniform | Uniform effect. |
- | dropShadow | Drop shadow effect. |
+| Name| Description|
+| -------- | -------- |
+| none | No effect.|
+| raised | Raised effect.|
+| depressed | Depressed effect.|
+| uniform | Uniform effect.|
+| dropShadow | Drop shadow effect.|
## CaptionsFontFamily8+
-Enumerates the caption font families.
+Enumerates the font families of captions.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Description |
- | -------- | -------- |
- | default | Default font family. |
- | monospacedSerif | Monospaced Serif fonts, which use the same width for each character. |
- | serif | Serif fonts. |
- | monospacedSansSerif | Monospaced Sans Serif fonts, which use the same width for each character. |
- | sansSerif | Sans Serif fonts. |
- | casual | Casual fonts. |
- | cursive | Cursive fonts. |
- | smallCapitals | Small caps fonts. |
+| Name| Description|
+| -------- | -------- |
+| default | Default font family.|
+| monospacedSerif | Monospaced Serif fonts, which use the same width for each character.|
+| serif | Serif fonts.|
+| monospacedSansSerif | Monospaced Sans Serif fonts, which use the same width for each character.|
+| sansSerif | Sans Serif fonts.|
+| casual | Casual fonts.|
+| cursive | Cursive fonts.|
+| smallCapitals | Small caps fonts.|
## CaptionsStyle8+
-Describes the caption style.
+Describes the style of captions.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes | No | Font family of the captions. |
- | fontScale | number | Yes | No | Font scale of the captions. |
- | fontColor | number \ | string | Yes | No | Font color of the captions. |
- | fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes | No | Font edge type of the captions. |
- | backgroundColor | number \ | string | Yes | No | Background color of the captions. |
- | windowColor | number \ | string | Yes | No | Window color of the captions. |
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes| No| Font family of captions.|
+| fontScale | number | Yes| No| Font scale of captions.|
+| fontColor | number \| string | Yes| No| Font color of captions.|
+| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes| No| Font edge type of captions.|
+| backgroundColor | number \| string | Yes| No| Background color of captions.|
+| windowColor | number \| string | Yes| No| Window color of captions.|
## CaptionsManager8+
-Implements caption configuration management.
+Implements configuration management for captions.
-### Attributes
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | enabled | boolean | Yes | No | Whether to enable caption configuration. |
- | style | [CaptionsStyle](#captionsstyle8) | Yes | No | Caption style. |
+### Attributes
-### Methods
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| enabled | boolean | Yes| No| Whether to enable captions configuration.|
+| style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.|
-In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) method to obtain a **captionsManager** instance, and then call the methods using the obtained instance.
+In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **captionsManager** instance, and then call the methods using the obtained instance.
-#### on('enableChange')
+### on('enableChange')
on(type: 'enableChange', callback: Callback<boolean>): void;
-Enables listening for enable status changes of caption configuration.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Enables listening for enabled status changes of captions configuration.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **enableChange** in this API. |
- | callback | Callback<boolean> | Yes | Callback invoked when the enable status of caption configuration changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.|
+ | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.|
-- Example
+- **Example**
```typescript
captionsManager.on('enableChange',(data) => {
@@ -176,22 +179,20 @@ Enables listening for enable status changes of caption configuration.
})
```
-#### on('styleChange')
+### on('styleChange')
on(type: 'styleChange', callback: Callback<CaptionsStyle>): void;
-Enables listening for caption style changes.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Enables listening for captions style changes.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **styleChange** in this API. |
- | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes | Callback invoked when the caption style changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.|
+ | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.|
-- Example
+- **Example**
```typescript
captionsManager.on('styleChange',(data) => {
@@ -199,43 +200,39 @@ Enables listening for caption style changes.
})
```
-#### off('enableChange')
+### off('enableChange')
off(type: 'enableChange', callback?: Callback<boolean>): void;
-Disables listening for enable status changes of caption configuration.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Disables listening for enabled status changes of captions configuration.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **enableChange** in this API. |
- | callback | Callback<boolean> | No | Callback invoked when the enable status of caption configuration changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.|
+ | callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.|
-- Example
+- **Example**
```typescript
captionsManager.off('enableChange')
```
-#### off('styleChange')
+### off('styleChange')
off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void;
-Disables listening for caption style changes.s is removed.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Disables listening for captions style changes.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **styleChange** in this API. |
- | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No | Callback invoked when the caption style changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.|
+ | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.|
-- Example
+- **Example**
```typescript
captionsManager.off('styleChange')
@@ -245,80 +242,92 @@ Disables listening for caption style changes.s is removed.
Describes a GUI change event.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | type | [EventType](#eventtype) | Yes | Yes | Accessibility event type. |
- | windowUpdateType | [WindowUpdateType](#windowupdatetype) | Yes | Yes | Window update type. |
- | bundleName | string | Yes | Yes | Target application name. |
- | componentType | string | Yes | Yes | Type of the event source component, for example, button or chart. |
- | pageId | number | Yes | Yes | Page ID of the event source. |
- | description | string | Yes | Yes | Event description. |
- | triggerAction | [Action](#action) | Yes | Yes | Action that triggers the event. |
- | textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes | Yes | Text movement unit. |
- | contents | Array<string> | Yes | Yes | Array of contents. |
- | lastContent | string | Yes | Yes | Latest content. |
- | beginIndex | number | Yes | Yes | Sequence number of the first item displayed on the page. |
- | currentIndex | number | Yes | Yes | Sequence number of the current item. |
- | endIndex | number | Yes | Yes | Sequence number of the last item displayed on the page. |
- | itemCount | number | Yes | Yes | Total number of items. |
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| type | [EventType](#eventtype) | Yes| Yes| Accessibility event type.|
+| windowUpdateType | [WindowUpdateType](#windowupdatetype) | Yes| Yes| Window update type.|
+| bundleName | string | Yes| Yes| Target application name.|
+| componentType | string | Yes| Yes| Type of the event source component, for example, button or chart.|
+| pageId | number | Yes| Yes| Page ID of the event source.|
+| description | string | Yes| Yes| Event description.|
+| triggerAction | [Action](#action) | Yes| Yes| Action that triggers the event.|
+| textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes| Yes| Text movement unit.|
+| contents | Array<string> | Yes| Yes| Array of contents.|
+| lastContent | string | Yes| Yes| Latest content.|
+| beginIndex | number | Yes| Yes| Sequence number of the first item displayed on the page.|
+| currentIndex | number | Yes| Yes| Sequence number of the current item.|
+| endIndex | number | Yes| Yes| Sequence number of the last item displayed on the page.|
+| itemCount | number | Yes| Yes| Total number of items.|
+
+### constructor
+
+constructor(jsonObject)
+
+Implements a constructor.
+
+- **Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | jsonObject | string | Yes| JSON string required for creating an object.|
+
+- **Example**
+
+ ```typescript
+ let eventInfo = new accessibility.EventInfo({"type":"click","bundleName":"com.example.MyApplication","triggerAction":"click"})
+ ```
## EventType
Enumerates accessibility event types.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
-
- | Name | Description |
- | -------- | -------- |
- | click | Event of clicking a component. |
- | longClick | Event of long-pressing a component. |
- | select | Event of selecting a component. |
- | focus | Event indicating that the component obtains the focus. |
- | textUpdate | Event indicating that the component text has been updated. |
- | hoverEnter | Event indicating that the hover enters a component. |
- | hoverExit | Event indicating that the hover exits a component. |
- | scroll | Event of the scroll view. |
- | textSelectionUpdate | Event indicating that the selected text has been updated. |
- | accessibilityFocus | Event indicating that the accessibility focus has been obtained. |
- | accessibilityFocusClear | Event indicating that the accessibility focus has been cleared. |
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
+
+| Name| Description|
+| -------- | -------- |
+| click | Event of clicking a component.|
+| longClick | Event of long-pressing a component.|
+| select | Event of selecting a component.|
+| focus | Event indicating that the component obtains the focus.|
+| textUpdate | Event indicating that the component text has been updated.|
+| hoverEnter | Event indicating that the hover enters a component.|
+| hoverExit | Event indicating that the hover exits a component.|
+| scroll | Event of the scroll view.|
+| textSelectionUpdate | Event indicating that the selected text has been updated.|
+| accessibilityFocus | Event indicating that the accessibility focus has been obtained.|
+| accessibilityFocusClear | Event indicating that the accessibility focus has been cleared.|
## TextMoveUnit
Enumerates the movement units for traversing the node text.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | char | The movement unit for traversing the node text is by character. |
- | word | The movement unit for traversing the node text is by word. |
- | line | The movement unit for traversing the node text is by line. |
- | page | The movement unit for traversing the node text is by page. |
- | paragraph | The movement unit for traversing the node text is by paragraph. |
+| Name| Description|
+| -------- | -------- |
+| char | The movement unit for traversing the node text is by character.|
+| word | The movement unit for traversing the node text is by word.|
+| line | The movement unit for traversing the node text is by line.|
+| page | The movement unit for traversing the node text is by page.|
+| paragraph | The movement unit for traversing the node text is by paragraph.|
## WindowUpdateType
Enumerates window update types.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
-
- | Name | Description |
- | -------- | -------- |
- | add | Window adding. |
- | remove | Window deletion. |
- | title | Window title change. |
- | bounds | Window boundary change. |
- | layer | Window layer change. |
- | active | Window activity change. |
- | focus | Window focus change. |
- | accessibilityFocus | Window accessibility focus change. |
- | parent | Parent window change. |
- | children | Child window change. |
- | pip | Picture-in-picture (PIP) mode change. |
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
+
+| Name| Description|
+| -------- | -------- |
+| add | Window adding.|
+| remove | Window deletion.|
+| bounds | Window boundary change.|
+| active | Window activity change.|
+| focus | Window focus change.|
## accessibility.getAbilityLists
@@ -326,22 +335,22 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<A
Obtains the accessibility application list. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type. |
- | stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.|
+ | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.|
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.|
-- Example
+- **Example**
```typescript
accessibility.getAbilityLists("spoken", "enable")
@@ -369,17 +378,17 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: Asyn
Obtains the accessibility application list. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type. |
- | stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status. |
- | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes | Callback used to return the accessibility application list. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.|
+ | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.|
+ | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.|
-- Example
+- **Example**
```typescript
accessibility.getAbilityLists("visual", "enable", (err, data) => {
@@ -406,17 +415,17 @@ Obtains the accessibility application list. This API uses an asynchronous callba
getCaptionsManager(): CaptionsManager
-Obtains the accessibility caption configuration.
+Obtains the captions configuration.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | [CaptionsManager](#captionsmanager8) | Accessibility caption configuration. |
+ | Type| Description|
+ | -------- | -------- |
+ | [CaptionsManager](#captionsmanager8) | Captions configuration.|
-- Example
+- **Example**
```typescript
captionsManager = accessibility.getCaptionsManager()
@@ -430,12 +439,12 @@ Enables listening for the accessibility application or touch guide mode status c
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for.
- **accessibilityStateChange** means to listen for enable status changes of the accessibility application.
**System capability**: SystemCapability.Barrierfree.Accessibility.Core
- **touchGuideStateChange** means to listen for enable status changes of the touch guide mode.
**System capability**: SystemCapability.Barrierfree.Accessibility.Vision |
- | callback | Callback<boolean> | Yes | Callback invoked when the enable status changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision|
+ | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.|
-- Example
+- **Example**
```typescript
accessibility.on('accessibilityStateChange',(data) => {
@@ -447,18 +456,16 @@ Enables listening for the accessibility application or touch guide mode status c
off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void
-Disables listening for the accessibility application or touch guide mode status changes.
-
-
+Disables listening for the accessibility application or touch guide mode status changes.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | No | Type of the event to listen for.
- **accessibilityStateChange** means to listen for enable status changes of the accessibility application.
**System capability**: SystemCapability.Barrierfree.Accessibility.Core
- **touchGuideStateChange** means to listen for enable status changes of the touch guide mode.
**System capability**: SystemCapability.Barrierfree.Accessibility.Vision |
- | callback | Callback<boolean> | No | Callback invoked when the enable status changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision|
+ | callback | Callback<boolean> | No| Callback invoked when the enabled status changes.|
-- Example
+- **Example**
```typescript
accessibility.off('accessibilityStateChange',(data) => {
@@ -472,15 +479,15 @@ isOpenAccessibility(): Promise<boolean>
Checks whether accessibility is enabled. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenAccessibility()
@@ -497,15 +504,15 @@ isOpenAccessibility(callback: AsyncCallback<boolean>): void
Checks whether accessibility is enabled. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
-- Parameters
+- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenAccessibility((err, data) => {
@@ -523,15 +530,15 @@ isOpenTouchGuide(): Promise<boolean>
Checks whether touch guide mode is enabled. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Vision
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenTouchGuide()
@@ -548,15 +555,15 @@ isOpenTouchGuide(callback: AsyncCallback<boolean>): void
Checks whether touch guide mode is enabled. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Vision
-- Parameters
+- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenTouchGuide((err, data) => {
@@ -574,21 +581,21 @@ sendEvent(event: EventInfo): Promise<void>
Sends an accessibility event. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | event | [EventInfo](#eventinfo) | Yes | Accessibility event. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | event | [EventInfo](#eventinfo) | Yes| Accessibility event.|
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.|
-- Example
+- **Example**
```typescript
accessibility.sendEvent(this.eventInfo)
@@ -605,16 +612,16 @@ sendEvent(event: EventInfo, callback: AsyncCallback<void>): void
Sends an accessibility event. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | event | [EventInfo](#eventinfo) | Yes | Accessibility event. |
- | callback | AsyncCallback<void> | Yes | Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | event | [EventInfo](#eventinfo) | Yes| Accessibility event.|
+ | callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.|
-- Example
+- **Example**
```typescript
accessibility.sendEvent(this.eventInfo,(err, data) => {
diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-application-StartOptions.md
index dd0c20515c460318c629a1e197353b28fe7002dc..d1d7416500d37ab61523633f3880670ad8b98779 100644
--- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md
+++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md
@@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions';
| Name| Readable| Writable| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | -------- |
-| windowMode | Yes| No| number | No| Window mode.|
+| [windowMode](js-apis-application-abilityConstant.md#AbilityConstant.WindowMode) | Yes| No| number | No| Window mode.|
| displayId | Yes| No| number | No| Display ID.|
diff --git a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..8a366b1e21bb988c608ba0a5e57251f2bd237d75
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md
@@ -0,0 +1,137 @@
+# Window Extension Ability
+**WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows.
+
+> **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 APIs of this module can be used only in the stage model.
+
+## Modules to Import
+
+```ts
+import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility';
+```
+
+## Attributes
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name | Type| Readable| Writable| Description |
+| --------- | -------- | ---- | ---- | ------------------------- |
+| context | [ExtensionContext](js-apis-extension-context.md) | Yes | No | Context of an Extension ability. |
+
+## WindowExtensionAbility.onConnect
+
+onConnect(want: Want): rpc.RemoteObject
+
+Called when this Window Extension ability is connected to an ability for the first time.
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. |
+
+**Return value**
+| Type | Description |
+| ----------------------------------------------- | -------------------- |
+| [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Proxy of this Window Extension ability.|
+
+**Example**
+
+```ts
+import rpc from '@ohos.rpc';
+
+class StubTest extends rpc.RemoteObject {
+ constructor(des) {
+ super(des);
+ }
+ onRemoteRequest(code, data, reply, option) {
+ return true;
+ }
+ queryLocalInterface(descriptor) {
+ return null;
+ }
+ getInterfaceDescriptor() {
+ return "";
+ }
+ sendRequest(code, data, reply, options) {
+ return null;
+ }
+ getCallingPid() {
+ return 1;
+ }
+ getCallingUid() {
+ return 1;
+ }
+ attachLocalInterface(localInterface, descriptor){}
+}
+
+export default class MyWindowExtensionAbility extends WindowExtensionAbility {
+
+ onConnect(want): rpc.RemoteObject {
+ console.info('WindowExtAbility onConnect ' + want.abilityName);
+ return new StubTest("test");
+ }
+
+}
+```
+
+## WindowExtensionAbility.onDisconnect
+
+onDisconnect(want: Want): void
+
+Called when this Window Extension ability is disconnected from all connected abilities.
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. |
+
+
+**Example**
+
+```ts
+export default class MyWindowExtensionAbility extends WindowExtensionAbility {
+
+ onDisconnect(want) {
+ console.info('WindowExtAbility onDisconnect ' + want.abilityName);
+ }
+
+}
+```
+
+
+## WindowExtensionAbility.onWindowReady
+
+onWindowReady(window: Window): void
+
+Called when a window is ready.
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| window | [Window](js-apis-window.md) | Yes| Current **Window** instance.|
+
+
+**Example**
+
+```ts
+export default class MyWindowExtensionAbility extends WindowExtensionAbility {
+
+ onWindowReady(window) {
+ window.loadContent('WindowExtAbility/pages/index1').then(() => {
+ window.getProperties().then((pro) => {
+ console.log("WindowExtension " + JSON.stringify(pro));
+ })
+ window.show();
+ })
+ }
+
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md
index 3dbdff01d34bed0a34df2b07a75c4d68d8d3e889..ca3269353344ca06935afaf6b390ae0c906f1a1a 100644
--- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md
+++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md
@@ -62,3 +62,17 @@ Enumerates ability continuation results.
| AGREE | 0 | Continuation agreed.|
| REJECT | 1 | Continuation denied.|
| MISMATCH | 2 | Mismatch.|
+
+## AbilityConstant.WindowMode
+
+Enumerates the window modes when an ability is started.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+| Name | Value| Description |
+| --- | --- | --- |
+| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. |
+| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. |
+| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. |
+| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. |
+| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
diff --git a/en/application-dev/reference/apis/js-apis-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-application-applicationContext.md
index 7a76626655a193e7f146190df319fbbeafe8430d..88eccc98c39c5373930f35465ca48da1df19c40d 100644
--- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md
+++ b/en/application-dev/reference/apis/js-apis-application-applicationContext.md
@@ -7,7 +7,7 @@ The **ApplicationContext** module provides application-level context. You can us
> 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 of this module can be used only in the stage model.
-## How to Use
+## Usage
Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance.
@@ -28,7 +28,7 @@ Registers a listener to monitor the ability lifecycle of the application.
| Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ |
-| [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | callback | Yes | Callback used to return the ID of the registered listener.|
+| callback | [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value**
@@ -98,7 +98,7 @@ Deregisters the listener that monitors the ability lifecycle of the application.
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | Yes | ID of the listener to deregister.|
-| AsyncCallback | callback | Yes | Callback used to return the result. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
@@ -123,7 +123,7 @@ Registers a listener for system environment changes. This API uses an asynchrono
| Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ |
-| [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | callback | Yes | Callback used to return the ID of the registered listener.|
+| callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value**
@@ -175,7 +175,7 @@ Deregisters the listener for system environment changes. This API uses an asynch
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | Yes | ID of the listener to deregister. |
-| AsyncCallback | callback | Yes | Callback used to return the result. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md
index f9e8ea3be2d7ccfff71426848d2dbc2f0e349201..eb85e5d52d50068b8147c1a4789389b2cf5506e1 100644
--- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md
@@ -1,45 +1,41 @@
# BundleInfo
-
-
> **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.
-
-
-Provides the application bundle information.
+The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## BundleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
-| Name | Type | Readable| Writable| Description |
-| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------ |
-| name | string | Yes | No | Bundle name. |
-| type | string | Yes | No | Bundle type. |
-| appId | string | Yes | No | ID of the application to which the bundle belongs. |
-| uid | number | Yes | No | UID of the application to which the bundle belongs. |
-| installTime | number | Yes | No | Time when the HAP file was installed. |
-| updateTime | number | Yes | No | Time when the HAP file was updated. |
-| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. |
-| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information. |
-| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application. |
-| reqPermissionDetails | Array\<[ReqPermissionDetail](#ReqPermissionDetail)> | Yes | No | Detailed information of the permissions to request from the system.|
-| vendor | string | Yes | No | Vendor of the bundle. |
-| versionCode | number | Yes | No | Version number of the bundle. |
-| versionName | string | Yes | No | Version description of the bundle. |
-| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. |
-| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. |
-| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. |
-| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. |
-| entryModuleName | string | Yes | No | Name of the entry module. |
-| cpuAbi | string | Yes | No | cpuAbi information of the bundle. |
-| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. |
-| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. |
-| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. |
-| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. |
-| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information. |
+| Name | Type | Readable| Writable| Description |
+| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
+| name | string | Yes | No | Bundle name. |
+| type | string | Yes | No | Bundle type. |
+| appId | string | Yes | No | ID of the application to which the bundle belongs. |
+| uid | number | Yes | No | UID of the application to which the bundle belongs. |
+| installTime | number | Yes | No | Time when the HAP file was installed. |
+| updateTime | number | Yes | No | Time when the HAP file was updated. |
+| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. |
+| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.|
+| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
+| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
+| vendor | string | Yes | No | Vendor of the bundle. |
+| versionCode | number | Yes | No | Version number of the bundle. |
+| versionName | string | Yes | No | Version description of the bundle. |
+| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. |
+| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. |
+| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. |
+| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. |
+| entryModuleName | string | Yes | No | Name of the entry module. |
+| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. |
+| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. |
+| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. |
+| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. |
+| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. |
+| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.|
diff --git a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md
index 3c98a25b721a8f3cce41f927d7a35456761db366..9b11bb2f18da535af770b96cda13981cef95c62a 100644
--- a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md
@@ -6,9 +6,7 @@
>
> 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.
-
-
-Provides the Extension ability information.
+The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## ExtensionAbilityInfo
@@ -28,5 +26,5 @@ Provides the Extension ability information.
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. |
| metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. |
| enabled | boolean | Yes | No | Whether the Extension ability is enabled. |
-| readPermission | string | Yes | No | Permission required for reading the Extension ability data. |
+| readPermission | string | Yes | No | Permission required for reading data from the Extension ability. |
| writePermission | string | Yes | No | Permission required for writing data to the Extension ability. |
diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md
index 2f6dbbef26e41ec1f78fe5768c2389d1a8ee0578..5a11609281eebb7464b1e627ec432b4ffad72700 100644
--- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md
@@ -6,16 +6,12 @@
>
> 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.
-
-
-Provides the HAP module information.
+The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## HapModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
-
-
| Name | Type | Readable| Writable| Description |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- |
| name | string | Yes | No | Module name. |
@@ -36,4 +32,4 @@ Provides the HAP module information.
| mainElementName9+ | string | Yes | No | Information about the main ability. |
| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.|
| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. |
-| hashValue9+ | string | Yes | No | Hash value of the module. |
+| hashValue9+ | string | Yes | No | Hash value of the module.
The value is obtained by passing **GET_BUNDLE_WITH_HASH_VALUE**.|
diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md
index 3d532293b18ca1b262feabe80615dc1807ac30dc..72fcfaca8fb39e4345c2392e761b19b364922499 100644
--- a/en/application-dev/reference/apis/js-apis-bytrace.md
+++ b/en/application-dev/reference/apis/js-apis-bytrace.md
@@ -7,7 +7,7 @@
## Modules to Import
-```
+ ```js
import bytrace from '@ohos.bytrace';
```
@@ -35,7 +35,7 @@ Marks the start of a timeslice trace task.
**Example**
-```
+ ```js
bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms.
```
@@ -62,7 +62,7 @@ Marks the end of a timeslice trace task.
**Example**
-```
+ ```js
bytrace.finishTrace("myTestFunc", 1);
```
@@ -105,7 +105,7 @@ Defines the variable that indicates the number of timeslice trace tasks.
**Example**
-```
+ ```js
let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4;
diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md
index 755557fba6455122d78e1bc4c8f09c12e305521a..cfbfb83e3359a4b7d41cf6ab039d0c1f0552c9eb 100644
--- a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md
+++ b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md
@@ -1,9 +1,9 @@
# ContinuationExtraParams
-The **ContinuationExtraParams** module provides the extra parameters required by the device manager in the continuation management entry.
+The **ContinuationExtraParams** module provides the extra parameters required by the device selection module in the continuation management entry.
> **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.
## ContinuationExtraParams
diff --git a/en/application-dev/reference/apis/js-apis-distributed-data .md b/en/application-dev/reference/apis/js-apis-distributed-data .md
new file mode 100644
index 0000000000000000000000000000000000000000..5682921badad9367817fd3e421b1afb823970425
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-distributed-data .md
@@ -0,0 +1,5671 @@
+# Distributed Data Management
+
+The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases.
+
+This module provides the following functions:
+
+- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores.
+- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position.
+- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates.
+- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance.
+- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device.
+- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device.
+
+>**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.
+
+
+## Modules to Import
+
+```js
+import distributedData from '@ohos.data.distributedData';
+```
+
+
+## distributedData.createKVManager
+
+createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
+
+Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.|
+| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.|
+
+**Example**
+
+Stage model:
+```ts
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context,
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+FA model:
+```js
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context.getApplicationContext(),
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+## distributedData.createKVManager
+
+createKVManager(config: KVManagerConfig): Promise<KVManager>
+
+Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.|
+
+**Example**
+
+Stage model:
+```ts
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context,
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+FA model:
+```js
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context.getApplicationContext(),
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+## KVManagerConfig
+
+Provides configuration of the **KVManager** object, including the bundle name and user information of the caller.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).|
+| userInfo | [UserInfo](#userinfo) | Yes | User information.|
+| bundleName | string | Yes | Bundle name.|
+
+## UserInfo
+
+Defines user information.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| userId | string | Yes | User ID.|
+| userType | [UserType](#usertype) | Yes | User type.|
+
+
+## UserType
+
+Enumerates the user types.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name| Value| Description|
+| ----- | ------ | ------ |
+| SAME_USER_ID | 0 | User who logs in to different devices using the same account.|
+
+
+## KVManager
+
+Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use [createKVManager](#distributeddatacreatekvmanager) to create a **KVManager** object.
+
+### getKVStore
+
+getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
+
+Creates and obtains a KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| options | [Options](#options) | Yes | Configuration of the KV store.|
+| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.|
+
+**Example**
+
+```js
+let kvStore;
+let kvManager;
+try {
+ const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ securityLevel : distributedData.SecurityLevel.S2,
+ };
+ kvManager.getKVStore('storeId', options, function (err, store) {
+ if (err) {
+ console.log("getKVStore err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("getKVStore success");
+ kvStore = store;
+ });
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### getKVStore
+
+getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T>
+
+Creates and obtains a KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ------- | ---------------------- | ---- | -------------------- |
+| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| options | [Options](#options) | Yes | Configuration of the KV store.|
+
+
+**Return value**
+
+| Type | Description |
+| -------------------------------------- | ------------------------ |
+| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.|
+
+**Example**
+
+```js
+let kvStore;
+let kvManager;
+try {
+ const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ securityLevel : distributedData.SecurityLevel.S2,
+ };
+ kvManager.getKVStore('storeId', options).then((store) => {
+ console.log("getKVStore success");
+ kvStore = store;
+ }).catch((err) => {
+ console.log("getKVStore err: " + JSON.stringify(err));
+ });
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### closeKVStore8+ ###
+
+closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void
+
+Closes a KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+
+| Name | Type | Mandatory| Description |
+| ------- | ----------------- | ---- | --------------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| kvStore | [KVStore](#kvstore) | Yes | KV store to close. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+let kvManager;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+ }
+ try {
+ kvManager.getKVStore('storeId', options, async function (err, store) {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) {
+ console.log('closeKVStore success');
+ });
+ });
+} catch (e) {
+ console.log('closeKVStore e ' + e);
+}
+```
+
+
+### closeKVStore8+ ###
+
+closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void>
+
+Closes a KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| kvStore | [KVStore](#kvstore) | Yes | KV store to close. |
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| Promise\ | Promise that returns no value.|
+
+**Example**
+
+```js
+let kvManager;
+let kvStore;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+}
+ try {
+ kvManager.getKVStore('storeId', options).then(async (store) => {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => {
+ console.log('closeKVStore success');
+ }).catch((err) => {
+ console.log('closeKVStore err ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('CloseKVStore getKVStore err ' + JSON.stringify(err));
+ });
+ } catch (e) {
+ console.log('closeKVStore e ' + e);
+}
+```
+
+
+### deleteKVStore8+ ###
+
+deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void
+
+Deletes a KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+let kvManager;
+let kvStore;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+}
+try {
+ kvManager.getKVStore('store', options, async function (err, store) {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.deleteKVStore('appId', 'storeId', function (err, data) {
+ console.log('deleteKVStore success');
+ });
+ });
+} catch (e) {
+ console.log('DeleteKVStore e ' + e);
+}
+```
+
+### deleteKVStore8+ ###
+
+deleteKVStore(appId: string, storeId: string): Promise<void>
+
+Deletes a KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```js
+let kvManager;
+let kvStore;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+}
+try {
+ kvManager.getKVStore('storeId', options).then(async (store) => {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.deleteKVStore('appId', 'storeId').then(() => {
+ console.log('deleteKVStore success');
+ }).catch((err) => {
+ console.log('deleteKVStore err ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('getKVStore err ' + JSON.stringify(err));
+ });
+} catch (e) {
+ console.log('deleteKVStore e ' + e);
+}
+```
+
+
+### getAllKVStoreId8+ ###
+
+getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void
+
+Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| callback | AsyncCallback<string[]> | Yes |Callback used to return the KV store IDs obtained. |
+
+**Example**
+
+```js
+let kvManager;
+try {
+ kvManager.getAllKVStoreId('appId', function (err, data) {
+ console.log('GetAllKVStoreId success');
+ console.log('GetAllKVStoreId size = ' + data.length);
+ });
+} catch (e) {
+ console.log('GetAllKVStoreId e ' + e);
+}
+```
+
+
+### getAllKVStoreId8+ ###
+
+getAllKVStoreId(appId: string): Promise<string[]>
+
+Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| Promise<string[]>| Promise used to return the KV store IDs obtained.|
+
+**Example**
+
+```js
+let kvManager;
+try {
+ console.log('GetAllKVStoreId');
+ kvManager.getAllKVStoreId('appId').then((data) => {
+ console.log('getAllKVStoreId success');
+ console.log('size = ' + data.length);
+ }).catch((err) => {
+ console.log('getAllKVStoreId err ' + JSON.stringify(err));
+ });
+} catch(e) {
+ console.log('getAllKVStoreId e ' + e);
+}
+```
+
+
+### on('distributedDataServiceDie')8+ ###
+
+on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void
+
+Subscribes to service status changes.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.|
+| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.|
+
+**Example**
+
+```js
+let kvManager;
+try {
+
+ console.log('KVManagerOn');
+ const deathCallback = function () {
+ console.log('death callback call');
+ }
+ kvManager.on('distributedDataServiceDie', deathCallback);
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### off('distributedDataServiceDie')8+ ###
+
+off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void
+
+Unsubscribes from the service status changes.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.|
+| deathCallback | Callback<void> | No | Callback used to return service status changes.|
+
+
+**Example**
+
+```js
+let kvManager;
+try {
+ console.log('KVManagerOff');
+ const deathCallback = function () {
+ console.log('death callback call');
+ }
+ kvManager.off('distributedDataServiceDie', deathCallback);
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+
+```
+
+## Options
+
+Provides KV store configuration.
+
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC |
+| kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
+| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
+
+
+## KVStoreType
+
+Enumerates the KV store types.
+
+
+| Name | Value| Description |
+| --- | ---- | ----------------------- |
+| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
+| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
+| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
+
+
+## SecurityLevel
+
+Enumerates the KV store security levels.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value| Description |
+| --- | ---- | ----------------------- |
+| NO_LEVEL | 0 | No security level is set for the KV store. |
+| S0 | 1 | The KV store security level is public.|
+| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.|
+| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.|
+| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.|
+| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.|
+
+
+## Constants
+
+Defines the KV store constants.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value| Description |
+| --- | ---- | ----------------------- |
+| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. |
+| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. |
+| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.|
+| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. |
+| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.|
+| MAX_BATCH_SIZE | 128 | Maximum number of batch operations.|
+
+## Schema8+ ##
+
+Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+| Name | Type| Description |
+| --- | ---- | ----------------------- |
+| root8+ | [FieldNode](#fieldnode8) | JSON root object.|
+| indexes8+ | Array\ | String array in JSON format. |
+| mode8+ | number | Schema mode. |
+| skip8+ | number | Size of a skip of the schema. |
+
+### constructor8+ ###
+
+constructor()
+
+A constructor used to create a **Schema** instance.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+## FieldNode8+ ##
+
+Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+| Name | Type| Description |
+| --- | ---- | ----------------------- |
+| nullable8+ | boolean | Whether the database field can be null. |
+| default8+ | string | Default value of a **FieldNode**.|
+| type8+ | number | Value of the data type corresponding to the specified node.|
+
+### constructor8+ ###
+
+constructor(name: string)
+
+A constructor used to create a **FieldNode** instance with a string field.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name| Type| Mandatory| Description |
+| ------ | -------- | ---- | --------------- |
+| name | string | Yes | Value of **FieldNode**.|
+
+### appendChild8+ ###
+
+appendChild(child: FieldNode): boolean
+
+Appends a child node to this **FieldNode**.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| child | [FieldNode](#fieldnode8) | Yes | Child node to append. |
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise.|
+
+**Example**
+
+```js
+import ddm from '@ohos.data.distributedData';
+try {
+ let node = new ddm.FieldNode("root");
+ let child1 = new ddm.FieldNode("child1");
+ let child2 = new ddm.FieldNode("child2");
+ let child3 = new ddm.FieldNode("child3");
+ node.appendChild(child1);
+ node.appendChild(child2);
+ node.appendChild(child3);
+ console.log("appendNode " + JSON.stringify(node));
+ child1 = null;
+ child2 = null;
+ child3 = null;
+ node = null;
+} catch (e) {
+ console.log("AppendChild " + e);
+}
+```
+
+
+## KvStoreResultSet8+ ##
+
+Provides methods to obtain the KV store result sets, and query and move the data read position.
+
+Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object.
+
+
+### getCount8+ ###
+
+getCount(): number
+
+Obtains the total number of rows in the result set.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| number |Total number of rows obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const count = resultSet.getCount();
+ console.log("getCount succeed:" + count);
+} catch (e) {
+ console.log("getCount failed: " + e);
+}
+```
+
+### getPosition8+ ###
+
+getPosition(): number
+
+Obtains the current data read position (position from which data is read) in the result set.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| number |Current data read position obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeeded.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const position = resultSet.getPosition();
+ console.log("getPosition succeed:" + position);
+} catch (e) {
+ console.log("getPosition failed: " + e);
+}
+```
+
+
+### moveToFirst8+ ###
+
+moveToFirst(): boolean
+
+Moves the data read position to the first row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved1 = resultSet.moveToFirst();
+ console.log("moveToFirst succeed: " + moved1);
+} catch (e) {
+ console.log("moveToFirst failed " + e);
+}
+```
+
+
+### moveToLast8+ ###
+
+moveToLast(): boolean
+
+Moves the data read position to the last row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved2 = resultSet.moveToLast();
+ console.log("moveToLast succeed:" + moved2);
+} catch (e) {
+ console.log("moveToLast failed: " + e);
+}
+```
+
+
+### moveToNext8+ ###
+
+moveToNext(): boolean
+
+Moves the data read position to the next row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved3 = resultSet.moveToNext();
+ console.log("moveToNext succeed: " + moved3);
+} catch (e) {
+ console.log("moveToNext failed: " + e);
+}
+```
+
+
+### moveToPrevious8+ ###
+
+moveToPrevious(): boolean
+
+Moves the data read position to the previous row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved4 = resultSet.moveToPrevious();
+ console.log("moveToPrevious succeed:" + moved4);
+} catch (e) {
+ console.log("moveToPrevious failed: " + e);
+}
+```
+
+
+### move8+ ###
+
+move(offset: number): boolean
+
+Moves the data read position with the specified offset from the current position.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward. |
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved5 = resultSet.move();
+ console.log("move succeed:" + moved5);
+} catch (e) {
+ console.log("move failed: " + e);
+}
+```
+
+
+### moveToPosition8+ ###
+
+moveToPosition(position: number): boolean
+
+Moves the data read position from 0 to an absolute position.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| position | number | Yes |Absolute position to move to. |
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved6 = resultSet.moveToPosition();
+ console.log("moveToPosition succeed: " + moved6);
+} catch (e) {
+ console.log("moveToPosition failed: " + e);
+}
+```
+
+
+### isFirst8+ ###
+
+isFirst(): boolean
+
+Checks whether the data read position is the first row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the first row is being read; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const isfirst = resultSet.isFirst();
+ console.log("Check isFirst succeed:" + isfirst);
+} catch (e) {
+ console.log("Check isFirst failed: " + e);
+}
+```
+
+
+### isLast8+ ###
+
+isLast(): boolean
+
+Checks whether the data read position is the last row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the last row is being read; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const islast = resultSet.isLast();
+ console.log("Check isLast succeed: " + islast);
+} catch (e) {
+ console.log("Check isLast failed: " + e);
+}
+```
+
+### isBeforeFirst8+ ###
+
+isBeforeFirst(): boolean
+
+Checks whether the data read position is before the first row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const isbeforefirst = resultSet.isBeforeFirst();
+ console.log("Check isBeforeFirst succeed: " + isbeforefirst);
+} catch (e) {
+ console.log("Check isBeforeFirst failed: " + e);
+}
+```
+
+
+### isAfterLast8+ ###
+
+isAfterLast(): boolean
+
+Checks whether the data read position is after the last row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the data read position is after the last row; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const isafterlast = resultSet.isAfterLast();
+ console.log("Check isAfterLast succeed:" + isafterlast);
+} catch (e) {
+ console.log("Check isAfterLast failed: " + e);
+}
+```
+
+
+### getEntry8+ ###
+
+getEntry(): Entry
+
+Obtains the KV pair from the current position.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Entry](#entry) |KV pair obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const entry = resultSet.getEntry();
+ console.log("getEntry succeed:" + JSON.stringify(entry));
+} catch (e) {
+ console.log("getEntry failed: " + e);
+}
+```
+
+
+## Query8+ ##
+
+Provides methods to create a **Query** object, which defines different data query criteria.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+### constructor8+ ###
+
+constructor()
+
+A constructor used to create a **Schema** instance.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+
+### reset8+ ###
+
+reset(): Query
+
+Resets the **Query** object.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object reset.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.equalTo("key", "value");
+ console.log("query is " + query.getSqlLike());
+ query.reset();
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("simply calls should be ok :" + e);
+}
+```
+
+
+### equalTo8+ ###
+
+equalTo(field: string, value: number|string|boolean): Query
+
+Creates a **Query** object to match the specified field whose value is equal to the given value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.equalTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### notEqualTo8+ ###
+
+notEqualTo(field: string, value: number|string|boolean): Query
+
+Creates a **Query** object to match the specified field whose value is not equal to the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### greaterThan8+ ###
+
+greaterThan(field: string, value: number|string|boolean): Query
+
+Creates a **Query** object to match the specified field whose value is greater than the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.greaterThan("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### lessThan8+ ###
+
+lessThan(field: string, value: number|string): Query
+
+Creates a **Query** object to match the specified field whose value is less than the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.lessThan("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### greaterThanOrEqualTo8+ ###
+
+greaterThanOrEqualTo(field: string, value: number|string): Query
+
+Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.greaterThanOrEqualTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### lessThanOrEqualTo8+ ###
+
+lessThanOrEqualTo(field: string, value: number|string): Query
+
+Creates a **Query** object to match the specified field whose value is less than or equal to the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.lessThanOrEqualTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### isNull8+ ###
+
+isNull(field: string): Query
+
+Creates a **Query** object to match the specified field whose value is **null**.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.isNull("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### inNumber8+ ###
+
+inNumber(field: string, valueList: number[]): Query
+
+Creates a **Query** object to match the specified field whose value is within the specified list of numbers.
+
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | number[] | Yes | List of numbers.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.inNumber("field", [0, 1]);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### inString8+ ###
+
+inString(field: string, valueList: string[]): Query
+
+Creates a **Query** object to match the specified field whose value is within the specified list of strings.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | string[] | Yes | List of strings.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.inString("field", ['test1', 'test2']);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### notInNumber8+ ###
+
+notInNumber(field: string, valueList: number[]): Query
+
+Creates a **Query** object to match the specified field whose value is not within the specified list of numbers.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | number[] | Yes | List of numbers.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notInNumber("field", [0, 1]);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### notInString8+ ###
+
+notInString(field: string, valueList: string[]): Query
+
+Creates a **Query** object to match the specified field whose value is not within the specified list of strings.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | string[] | Yes | List of strings.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notInString("field", ['test1', 'test2']);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### like8+ ###
+
+like(field: string, value: string): Query
+
+Creates a **Query** object to match the specified field whose value is similar to the specified string.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | string | Yes | String specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.like("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### unlike8+ ###
+
+unlike(field: string, value: string): Query
+
+Creates a **Query** object to match the specified field whose value is not similar to the specified string.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | string | Yes | String specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.unlike("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### and8+ ###
+
+and(): Query
+
+Creates a **Query** object with the AND condition.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object Created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value1");
+ query.and();
+ query.notEqualTo("field", "value2");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### or8+ ###
+
+or(): Query
+
+Creates a **Query** object with the OR condition.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object Created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value1");
+ query.or();
+ query.notEqualTo("field", "value2");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### orderByAsc8+ ###
+
+orderByAsc(field: string): Query
+
+Creates a **Query** object to sort the query results in ascending order.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ query.orderByAsc("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### orderByDesc8+ ###
+
+orderByDesc(field: string): Query
+
+Creates a **Query** object to sort the query results in descending order.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ query.orderByDesc("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### limit8+ ###
+
+limit(total: number, offset: number): Query
+
+Creates a **Query** object to specify the number of results and where to start.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| total | number | Yes |Number of results to query. |
+| offset | number | Yes |Start position for query. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+let total = 10;
+let offset = 1;
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ query.limit(total, offset);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### isNotNull8+ ###
+
+isNotNull(field: string): Query
+
+Creates a **Query** object to match the specified field whose value is not **null**.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.isNotNull("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### beginGroup8+ ###
+
+beginGroup(): Query
+
+Creates a **Query** object for a query condition group with a left parenthesis.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.beginGroup();
+ query.isNotNull("field");
+ query.endGroup();
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### endGroup8+ ###
+
+endGroup(): Query
+
+Creates a **Query** object for a query condition group with a right parenthesis.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.beginGroup();
+ query.isNotNull("field");
+ query.endGroup();
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### prefixKey8+ ###
+
+prefixKey(prefix: string): Query
+
+Creates a **Query** object with a specified key prefix.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| prefix | string | Yes |Key prefix. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.prefixKey("$.name");
+ query.prefixKey("0");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### setSuggestIndex8+ ###
+
+setSuggestIndex(index: string): Query
+
+Creates a **Query** object with an index preferentially used for query.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| index | string | Yes |Index preferentially used for query. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.setSuggestIndex("$.name");
+ query.setSuggestIndex("0");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### deviceId8+ ###
+
+deviceId(deviceId:string):Query
+
+Creates a **Query** object with the device ID as the key prefix.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId | string | Yes |Device ID. |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.deviceId("deviceId");
+ console.log("query is " + query.getSqlLike());
+} catch (e) {
+ console.log("should be ok on Method Chaining : " + e);
+}
+```
+
+
+### getSqlLike8+ ###
+
+getSqlLike():string
+
+Obtains the query statement of the **Query** object.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| string |Returns the query statement obtained.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ let sql1 = query.getSqlLike();
+ console.log("GetSqlLike sql=" + sql1);
+} catch (e) {
+ console.log("duplicated calls should be ok : " + e);
+}
+```
+
+
+## KVStore
+
+Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization.
+
+Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object.
+
+### put
+
+put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void
+
+Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). |
+| callback | AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("put err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("put success");
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### put
+
+put(key: string, value: Uint8Array | string | number | boolean): Promise<void>
+
+Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
+ console.log("put success: " + JSON.stringify(data));
+ }).catch((err) => {
+ console.log("put err: " + JSON.stringify(err));
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### delete
+
+delete(key: string, callback: AsyncCallback<void>): void
+
+Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| callback | AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("put err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("put success");
+ kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("delete err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("delete success");
+ });
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### delete
+
+delete(key: string): Promise<void>
+
+Deletes a KV pair from this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
+ console.log("put success: " + JSON.stringify(data));
+ kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log("delete success");
+ }).catch((err) => {
+ console.log("delete err: " + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log("put err: " + JSON.stringify(err));
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### delete9+
+
+delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>)
+
+Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.|
+| callback | AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ kvStore.delete(predicates, function (err, data) {
+ if (err == undefined) {
+ console.log('delete success');
+ } else {
+ console.log('delete fail' + err);
+ }
+ });
+} catch (e) {
+ console.log('An unexpected error occurred. Error:' + e);
+}
+```
+
+### delete9+
+
+delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void>
+
+Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.|
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise used to return the result.|
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let arr = ["name"];
+ predicates.inKeys(arr);
+ kvStore.put("name", "bob").then((data) => {
+ console.log('put success' + JSON.stringify(data));
+ kvStore.delete(predicates).then((data) => {
+ console.log('delete success');
+ }).catch((err) => {
+ console.log('delete fail' + JSON.stringify(err));
+ });
+ }) .catch((err) => {
+ console.log(' put fail' + err);
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+
+```
+
+### on('dataChange')
+
+on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void
+
+Subscribes to data change notifications of the specified type.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. |
+| type |[SubscribeType](#subscribetype) | Yes |Type of data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
+ console.log("dataChange callback call data: " + JSON.stringify(data));
+});
+```
+
+
+### on('syncComplete')
+
+on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void
+
+Subscribes to data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('syncComplete', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+
+### off('dataChange')8+
+
+off(event:'dataChange', listener?: Callback<ChangeNotification>): void
+
+Unsubscribes from data change notifications.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+kvStore.off('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+
+### off('syncComplete')9+
+
+off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void
+
+Unsubscribes from data change events. This API uses a synchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const func = function (data) {
+ console.log('syncComplete ' + data)
+ };
+ kvStore.on('syncComplete', func);
+ kvStore.off('syncComplete', func);
+}catch(e) {
+ console.log('syncComplete e ' + e);
+}
+```
+
+
+### putBatch8+
+
+putBatch(entries: Entry[], callback: AsyncCallback<void>): void
+
+Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
+| callback |Asyncallback<void> |Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_string_key', function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+}catch(e) {
+ console.log('PutBatch e ' + JSON.stringify(e));
+}
+```
+
+
+### putBatch8+
+
+putBatch(entries: Entry[]): Promise<void>
+
+Inserts KV pairs in batches to this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_string_key').then((entries) => {
+ console.log('getEntries success');
+ console.log('PutBatch ' + JSON.stringify(entries));
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + JSON.stringify(e));
+}
+```
+
+### putBatch9+
+
+putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void
+
+Writes data to this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. |
+| callback |Asyncallback<void> |Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let v8Arr = [];
+ let arr = new Uint8Array([4,5,6,7]);
+ let vb1 = {key : "name_1", value : 32}
+ let vb2 = {key : "name_2", value : arr};
+ let vb3 = {key : "name_3", value : "lisi"};
+
+ v8Arr.push(vb1);
+ v8Arr.push(vb2);
+ v8Arr.push(vb3);
+ kvStore.putBatch(v8Arr, async function (err,data) {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('putBatch e ' + JSON.stringify(e));
+}
+```
+
+### putBatch9+
+
+putBatch(value: Array<ValuesBucket>): Promise<void>
+
+Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let v8Arr = [];
+ let arr = new Uint8Array([4,5,6,7]);
+ let vb1 = {key : "name_1", value : 32}
+ let vb2 = {key : "name_2", value : arr};
+ let vb3 = {key : "name_3", value : "lisi"};
+
+ v8Arr.push(vb1);
+ v8Arr.push(vb2);
+ v8Arr.push(vb3);
+ kvStore.putBatch(v8Arr).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + JSON.stringify(e));
+}
+
+```
+
+### deleteBatch8+
+
+deleteBatch(keys: string[], callback: AsyncCallback<void>): void
+
+Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keys |string[] | Yes |KV pairs to delete in batches. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ let keys = [];
+ for (var i = 0; i < 5; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ keys.push(key + i);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.deleteBatch(keys, async function (err,data) {
+ console.log('deleteBatch success');
+ });
+ });
+}catch(e) {
+ console.log('DeleteBatch e ' + e);
+}
+```
+
+
+### deleteBatch8+ ###
+
+deleteBatch(keys: string[]): Promise<void>
+
+Deletes KV pairs in batches from this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keys |string[] | Yes |KV pairs to delete in batches. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ let keys = [];
+ for (var i = 0; i < 5; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ keys.push(key + i);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.deleteBatch(keys).then((err) => {
+ console.log('deleteBatch success');
+ }).catch((err) => {
+ console.log('deleteBatch fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('DeleteBatch e ' + e);
+}
+```
+
+
+### startTransaction8+ ###
+
+startTransaction(callback: AsyncCallback<void>): void
+
+Starts the transaction in this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+function putBatchString(len, prefix) {
+ let entries = [];
+ for (var i = 0; i < len; i++) {
+ var entry = {
+ key : prefix + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ return entries;
+}
+try {
+ var count = 0;
+ kvStore.on('dataChange', 0, function (data) {
+ console.log('startTransaction 0' + data)
+ count++;
+ });
+ kvStore.startTransaction(async function (err,data) {
+ console.log('startTransaction success');
+ let entries = putBatchString(10, 'batch_test_string_key');
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ });
+ });
+}catch(e) {
+ console.log('startTransaction e ' + e);
+}
+```
+
+
+### startTransaction8+ ###
+
+startTransaction(): Promise<void>
+
+Starts the transaction in this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var count = 0;
+ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
+ console.log('startTransaction ' + JSON.stringify(data));
+ count++;
+ });
+ kvStore.startTransaction().then(async (err) => {
+ console.log('startTransaction success');
+ }).catch((err) => {
+ console.log('startTransaction fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('startTransaction e ' + e);
+}
+```
+
+
+### commit8+ ###
+
+commit(callback: AsyncCallback<void>): void
+
+Commits the transaction in this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.commit(function (err,data) {
+ if (err == undefined) {
+ console.log('commit success');
+ } else {
+ console.log('commit fail');
+ }
+ });
+}catch(e) {
+ console.log('Commit e ' + e);
+}
+```
+
+
+### commit8+ ###
+
+commit(): Promise<void>
+
+Commits the transaction in this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.commit().then(async (err) => {
+ console.log('commit success');
+ }).catch((err) => {
+ console.log('commit fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('Commit e ' + e);
+}
+```
+
+
+### rollback8+ ###
+
+rollback(callback: AsyncCallback<void>): void
+
+Rolls back the transaction in this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.rollback(function (err,data) {
+ if (err == undefined) {
+ console.log('commit success');
+ } else {
+ console.log('commit fail');
+ }
+ });
+}catch(e) {
+ console.log('Rollback e ' + e);
+}
+```
+
+
+### rollback8+ ###
+
+rollback(): Promise<void>
+
+Rolls back the transaction in this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.rollback().then(async (err) => {
+ console.log('rollback success');
+ }).catch((err) => {
+ console.log('rollback fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('Rollback e ' + e);
+}
+```
+
+
+### enableSync8+ ###
+
+enableSync(enabled: boolean, callback: AsyncCallback<void>): void
+
+Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.enableSync(true, function (err,data) {
+ if (err == undefined) {
+ console.log('enableSync success');
+ } else {
+ console.log('enableSync fail');
+ }
+ });
+}catch(e) {
+ console.log('EnableSync e ' + e);
+}
+```
+
+
+### enableSync8+ ###
+
+enableSync(enabled: boolean): Promise<void>
+
+Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.enableSync(true).then((err) => {
+ console.log('enableSync success');
+ }).catch((err) => {
+ console.log('enableSync fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('EnableSync e ' + e);
+}
+```
+
+
+### setSyncRange8+ ###
+
+setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void
+
+Sets the data synchronization range. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| localLabels |string[] | Yes |Synchronization labels set for the local device. |
+| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const localLabels = ['A', 'B'];
+ const remoteSupportLabels = ['C', 'D'];
+ kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) {
+ console.log('SetSyncRange put success');
+ });
+}catch(e) {
+ console.log('SetSyncRange e ' + e);
+}
+```
+
+
+### setSyncRange8+ ###
+
+setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void>
+
+Sets the data synchronization range. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| localLabels |string[] | Yes |Synchronization labels set for the local device. |
+| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const localLabels = ['A', 'B'];
+ const remoteSupportLabels = ['C', 'D'];
+ kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => {
+ console.log('setSyncRange success');
+ }).catch((err) => {
+ console.log('delete fail ' + err);
+ });
+}catch(e) {
+ console.log('SetSyncRange e ' + e);
+}
+```
+
+
+## SubscribeType
+
+Enumerates the subscription types.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value | Description |
+| ----- | ------ | ----------------------- |
+| SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. |
+| SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. |
+| SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. |
+
+## ChangeNotification
+
+Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Type |Readable |Writable | Description |
+| ----- | ------- | -----| ------|------------------------ |
+| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. |
+| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. |
+| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. |
+| deviceId | string | Yes | Yes|UUID of the device. |
+
+## Entry
+
+Defines the KV pairs stored in the KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Type |Readable |Writable | Description |
+| ----- | ------- | -----| ------|------------------------ |
+| key | string | Yes | Yes|Key of the KV pair stored in the KV store. |
+| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. |
+
+
+## Value
+
+Defines the **value** object in a KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Type |Readable |Writable | Description |
+| ----- | ------- | -----| ------|------------------------ |
+| type | [ValueType](#value) | Yes | Yes|Type of the value. |
+| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. |
+
+## ValueType
+
+Enumerates the data types.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value | Description |
+| ----- | ------ | ----------------------- |
+| STRING |0 |String. |
+| INTEGER |1 |Integer. |
+| FLOAT |2 |Float (single-precision floating point). |
+| BYTE_ARRAY |3 |Byte array. |
+| BOOLEAN |4 |Boolean. |
+| DOUBLE |5 |Double (double-precision floating point). |
+
+## SingleKVStore
+
+Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore).
+
+Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices.
+
+Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance.
+
+### get
+
+get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void
+
+Obtains the value of the specified key. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("put err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("put success");
+ kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
+ console.log("get success data: " + data);
+ });
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### get
+
+get(key: string): Promise<Uint8Array | string | boolean | number>
+
+Obtains the value of the specified key. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
+ console.log("put success: " + JSON.stringify(data));
+ kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log("get success data: " + data);
+ }).catch((err) => {
+ console.log("get err: " + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log("put err: " + JSON.stringify(err));
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### getEntries8+ ###
+
+getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void
+
+Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_number_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.INTEGER,
+ value : 222
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_number_key', function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(keyPrefix: string): Promise<Entry[]>
+
+Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + entries);
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_string_key').then((entries) => {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
+ console.log('entries[0].value.value: ' + entries[0].value.value);
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query, callback: AsyncCallback<Entry[]>): void
+
+Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |Key prefix to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getEntries(query, function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query): Promise<Entry[]>
+
+Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getEntries(query).then((entries) => {
+ console.log('getEntries success');
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('GetEntries putBatch fail ' + JSON.stringify(err))
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match.|
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('GetResultSet putBatch success');
+ kvStore.getResultSet('batch_test_string_key', async function (err, result) {
+ console.log('GetResultSet getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('GetResultSet closeResultSet success');
+ })
+ });
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(keyPrefix: string): Promise<KvStoreResultSet>
+
+Obtains the result set with the specified prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('PutBatch putBatch fail ' + JSON.stringify(err));
+ });
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('GetResult getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('GetResult closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResult e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |Query | Yes |**Query** object to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet(query, async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ });
+ });
+} catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet(query).then((result) => {
+ console.log(' getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+### getResultSet9+ ###
+
+getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let resultSet;
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.prefixKey("batch_test_string_key");
+ kvStore.getResultSet(predicates, async function (err, result) {
+ console.log(' GetResultSet success');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log(' closeResultSet success');
+ })
+ });
+}catch(e) {
+ console.log('An unexpected error occurred. Error:' + e);
+}
+```
+### getResultSet9+ ###
+
+getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let resultSet;
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.prefixKey("batch_test_string_key");
+ kvStore.getResultSet(predicates) .then((result) => {
+ console.log(' GetResultSet success');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log(' closeResultSet success');
+ })
+ });
+}catch(e) {
+ console.log('An unexpected error occurred. Error:' + e);
+}
+```
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void
+
+Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ if (err == undefined) {
+ console.log('closeResultSet success');
+ } else {
+ console.log('closeResultSet fail');
+ }
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet): Promise<void>
+
+Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet).then(() => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query, callback: AsyncCallback<number>): void
+
+Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize(query, async function (err, resultSize) {
+ console.log('getResultSet succeed.');
+ });
+ });
+} catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query): Promise<number>
+
+Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<number> |Promise used to return the number of results obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize(query).then((resultSize) => {
+ console.log('getResultSet succeed.');
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void
+
+Deletes data of a device. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('put success');
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid, async function (err,data) {
+ if (err == undefined) {
+ console.log('removeDeviceData success');
+ } else {
+ console.log('removeDeviceData fail');
+ kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('RemoveDeviceData get success');
+ });
+ }
+ });
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string): Promise<void>
+
+Deletes data of a device. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => {
+ console.log('removeDeviceData put success');
+ }).catch((err) => {
+ console.log('put fail ' + JSON.stringify(err));
+ });
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid).then((err) => {
+ console.log('removeDeviceData success');
+ }).catch((err) => {
+ console.log('removeDeviceData fail ' + JSON.stringify(err));
+ });
+ kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log('get success data:' + data);
+ }).catch((err) => {
+ console.log('RemoveDeviceData get fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### on('syncComplete')8+ ###
+
+on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void
+
+Subscribes to the data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
+const VALUE_TEST_FLOAT_ELEMENT = 321.12;
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('syncComplete ' + data)
+ });
+ kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
+ console.log('syncComplete put success');
+ }).catch((error) => {
+ console.log('syncComplete put fail ' + error);
+ });
+}catch(e) {
+ console.log('syncComplete put e ' + e);
+}
+```
+
+
+### off('syncComplete')8+ ###
+
+off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void
+
+Unsubscribes from the data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const func = function (data) {
+ console.log('syncComplete ' + data)
+ };
+ kvStore.on('syncComplete', func);
+ kvStore.off('syncComplete', func);
+}catch(e) {
+ console.log('syncComplete e ' + e);
+}
+```
+
+### on('dataChange')9+ ###
+
+on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void
+
+Subscribes to data changes of the specified type. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. |
+| type |[SubscribeType](#subscribetype) | Yes |Subscription type. |
+| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
+ console.log("dataChange callback call data: " + JSON.stringify(data));
+});
+
+```
+
+### off('dataChange')9+ ###
+
+off(event:'dataChange', listener?: Callback<ChangeNotification>): void
+
+Unsubscribes from the data change events. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+kvStore.off('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+### sync7+
+
+
+sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
+| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000);
+```
+
+### sync9+
+sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
+| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
+const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
+ console.log('Sync put success');
+ const devices = ['deviceList'];
+ const mode = distributedData.SyncMode.PULL_ONLY;
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.sync(devices, query, mode , 1000);
+ });
+}catch(e) {
+ console.log('Sync e' + e);
+}
+```
+
+### setSyncParam8+ ###
+
+setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void
+
+Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const defaultAllowedDelayMs = 500;
+ kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) {
+ console.log('SetSyncParam put success');
+ });
+}catch(e) {
+ console.log('testSingleKvStoreSetSyncParam e ' + e);
+}
+```
+
+
+### setSyncParam8+ ###
+
+setSyncParam(defaultAllowedDelayMs: number): Promise<void>
+
+Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const defaultAllowedDelayMs = 500;
+ kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => {
+ console.log('SetSyncParam put success');
+ }).catch((err) => {
+ console.log('SetSyncParam put fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('SetSyncParam e ' + e);
+}
+```
+
+
+### getSecurityLevel8+ ###
+
+getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void
+
+Obtains the security level of this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.getSecurityLevel(function (err,data) {
+ console.log('getSecurityLevel success');
+ });
+}catch(e) {
+ console.log('GetSecurityLevel e ' + e);
+}
+```
+
+
+### getSecurityLevel8+ ###
+
+getSecurityLevel(): Promise<SecurityLevel>
+
+Obtains the security level of this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.getSecurityLevel().then((data) => {
+ console.log(' getSecurityLevel success');
+ }).catch((err) => {
+ console.log('getSecurityLevel fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetSecurityLevel e ' + e);
+}
+```
+
+
+## DeviceKVStore8+ ##
+
+Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore).
+
+Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified.
+
+For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted.
+
+Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object.
+
+### get8+ ###
+
+get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void
+
+Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| key |string | Yes |Key to match. |
+| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
+try{
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('put success');
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) {
+ console.log('get success');
+ });
+ })
+}catch(e) {
+ console.log('get e' + e);
+}
+```
+
+
+### get8+ ###
+
+get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array>
+
+Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| key |string | Yes |Key to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => {
+ console.log(' put success');
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log('get success');
+ }).catch((err) => {
+ console.log('get fail ' + JSON.stringify(err));
+ });
+ }).catch((error) => {
+ console.log('put error' + error);
+ });
+} catch (e) {
+ console.log('Get e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void
+
+Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + entries);
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]>
+
+Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + entries);
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
+ console.log('entries[0].value.value: ' + entries[0].value.value);
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query, callback: AsyncCallback<Entry[]>): void
+
+Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getEntries(query, function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query): Promise<Entry[]>
+
+Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getEntries(query).then((entries) => {
+ console.log('getEntries success');
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('GetEntries putBatch fail ' + JSON.stringify(err))
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void
+
+Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ var query = new distributedData.Query();
+ query.deviceId('localDeviceId');
+ query.prefixKey("batch_test");
+ kvStore.getEntries('localDeviceId', query, function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ })
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, query: Query): Promise<Entry[]>
+
+Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ var query = new distributedData.Query();
+ query.deviceId('localDeviceId');
+ query.prefixKey("batch_test");
+ kvStore.getEntries('localDeviceId', query).then((entries) => {
+ console.log('getEntries success');
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('closeResultSet success');
+ })
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getResultSet(query, async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('closeResultSet success');
+ })
+ });
+ });
+} catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + err);
+ });
+ const query = new distributedData.Query();
+ query.deviceId('localDeviceId');
+ query.prefixKey("batch_test");
+ console.log("GetResultSet " + query.getSqlLike());
+ kvStore.getResultSet(query).then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet('localDeviceId', query, async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('closeResultSet success');
+ })
+ });
+ });
+} catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('GetResultSet putBatch success');
+ }).catch((err) => {
+ console.log('PutBatch putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet('localDeviceId', query).then((result) => {
+ console.log('GetResultSet getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err));
+ });
+ query.deviceId('localDeviceId');
+ console.log("GetResultSet " + query.getSqlLike());
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('GetResultSet closeResultSet success');
+ }).catch((err) => {
+ console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err));
+ });
+
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void
+
+Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ console.log('CloseResultSet success');
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ if (err == undefined) {
+ console.log('closeResultSet success');
+ } else {
+ console.log('closeResultSet fail');
+ }
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet): Promise<void>
+
+Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ console.log('CloseResultSet success');
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet).then(() => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query, callback: AsyncCallback<number>): void
+
+Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getResultSize(query, async function (err, resultSize) {
+ console.log('getResultSet succeed.');
+ });
+ });
+} catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query): Promise<number>
+
+Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<number> |Promise used to return the number of results obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getResultSize(query).then((resultSize) => {
+ console.log('getResultSet succeed.');
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void;
+
+Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) {
+ console.log('getResultSet succeed.');
+ });
+ });
+} catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(deviceId: string, query: Query): Promise<number>
+
+Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<number> |Promise used to return the number of results obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ var query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize('localDeviceId', query).then((resultSize) => {
+ console.log('getResultSet succeed.');
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void
+
+Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('RemoveDeviceData put success');
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid, async function (err,data) {
+ if (err == undefined) {
+ console.log('removeDeviceData success');
+ } else {
+ console.log('removeDeviceData fail');
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('RemoveDeviceData get success');
+ });
+ }
+ });
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string): Promise<void>
+
+Deletes data of the specified device from this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => {
+ console.log('RemoveDeviceData put success');
+ }).catch((err) => {
+ console.log('RemoveDeviceData put fail ' + JSON.stringify(err));
+ });
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid).then((err) => {
+ console.log('removeDeviceData success');
+ }).catch((err) => {
+ console.log('removeDeviceData fail ' + JSON.stringify(err));
+ });
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log('RemoveDeviceData get success data:' + data);
+ }).catch((err) => {
+ console.log('RemoveDeviceData get fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### sync8+ ###
+
+sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |IDs of the devices to be synchronized.|
+| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
+const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
+ console.log('Sync put success');
+ const devices = ['deviceList'];
+ const mode = distributedData.SyncMode.PULL_ONLY;
+ kvStore.sync(devices, mode);
+ });
+}catch(e) {
+ console.log('Sync e' + e);
+}
+```
+
+### sync9+ ###
+
+sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |IDs of the devices to be synchronized.|
+| query |[Query](#query8) | Yes | **Query** object to match.|
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
+const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
+ console.log('Sync put success');
+ const devices = ['deviceList'];
+ const mode = distributedData.SyncMode.PULL_ONLY;
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.sync(devices, query, 1000);
+ });
+}catch(e) {
+ console.log('Sync e' + e);
+}
+```
+
+### on('syncComplete')8+ ###
+
+on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void
+
+Subscribes to the data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.|
+| syncCallback |Callback | Yes |Callback used to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
+const VALUE_TEST_FLOAT_ELEMENT = 321.12;
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('syncComplete ' + data)
+ });
+ kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
+ console.log('syncComplete put success');
+ }).catch((error) => {
+ console.log('syncComplete put fail ' + error);
+ });
+}catch(e) {
+ console.log('syncComplete put e ' + e);
+}
+```
+
+
+### off('syncComplete')8+ ###
+
+off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void
+
+Unsubscribes from the synchronization complete events. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.|
+| syncCallback |Callback9+ ###
+
+on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void
+
+Subscribes to data changes of the specified type. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. |
+| type |[SubscribeType](#subscribetype) | Yes |Subscription type. |
+| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
+ console.log("dataChange callback call data: " + JSON.stringify(data));
+});
+```
+
+
+### off('dataChange')9+ ###
+
+off(event:'dataChange', listener?: Callback<ChangeNotification>): void
+
+Unsubscribes from the data change events. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+kvStore.off('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+
+## SyncMode
+
+Enumerates the synchronization modes.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value | Description |
+| ----- | ------ | ----------------------- |
+| PULL_ONLY |0 |Pull data from the peer end to the local end only.|
+| PUSH_ONLY |1 |Push data from the local end to the peer end only.|
+| PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.|
+
diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md
index 24339fc434b3afe97cf0f5ebbbfd1862f86c6e6e..0abc724302fcf89b86421b90c0bb507f1894b312 100644
--- a/en/application-dev/reference/apis/js-apis-i18n.md
+++ b/en/application-dev/reference/apis/js-apis-i18n.md
@@ -673,6 +673,32 @@ Formats a phone number.
phonenumberfmt.format("15812312312");
```
+### getLocationName8+
+
+static getLocationName(number: string, locale: string): string
+
+Obtains the home location of a phone number.
+
+**System capability**: SystemCapability.Global.I18n
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ------ | ------ | ---- | ---------- |
+| number | string | Yes | Phone number.|
+| locale | string | Yes | Locale ID.|
+
+**Return value**
+| Type | Description |
+| ------ | ---------- |
+| string | Home location of the phone number.|
+
+**Example**
+ ```
+ var location = i18n.PhoneNumberFormat.getLocationName('15812312345', 'zh-CN');
+ ```
+
+
+
## PhoneNumberFormatOptions8+
diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md
index 85ff0550112bbfc81e22925c3a69ca7ac813cfab..13701cecf67e947c876789d0f1f4acde7f62a601 100644
--- a/en/application-dev/reference/apis/js-apis-image.md
+++ b/en/application-dev/reference/apis/js-apis-image.md
@@ -1,5 +1,7 @@
# Image Processing
+The **Image** module provides APIs for image processing. You can use the APIs to create a **PixelMap** object with specified properties or read image pixel data (even in an area).
+
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -11,11 +13,12 @@ import image from '@ohos.multimedia.image';
```
## image.createPixelMap8+
+
createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\
Creates a **PixelMap** object. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -34,7 +37,7 @@ Creates a **PixelMap** object. This API uses a promise to return the result.
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts)
.then((pixelmap) => {
@@ -47,7 +50,7 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: As
Creates a **PixelMap** object. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -61,10 +64,15 @@ Creates a **PixelMap** object. This API uses an asynchronous callback to return
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
-image.createPixelMap(color, opts, (pixelmap) => {
- })
+image.createPixelMap(color, opts, (error, pixelmap) => {
+ if(error) {
+ console.log('Failed to create pixelmap.');
+ } else {
+ console.log('Succeeded in creating pixelmap.');
+ }
+})
```
## PixelMap7+
@@ -73,11 +81,11 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i
### Attributes
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Type | Readable| Writable| Description |
-| ----------------------- | ------- | ---- | ---- | -------------------------- |
-| isEditable7+ | boolean | Yes | No | Whether the image pixel map is editable.|
+| Name | Type | Readable| Writable| Description |
+| ---------- | ------- | ---- | ---- | -------------------------- |
+| isEditable | boolean | Yes | No | Whether the image pixel map is editable.|
### readPixelsToBuffer7+
@@ -85,24 +93,24 @@ readPixelsToBuffer(dst: ArrayBuffer): Promise\
Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ----------- | ---- | ------------------------------------------------------------ |
-| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written.|
+| Name| Type | Mandatory| Description |
+| ------ | ----------- | ---- | ----------------------------------------------------------------------------------------------------- |
+| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written. The buffer size is obtained by calling **getPixelBytesNumber**.|
**Return value**
| Type | Description |
-| :------------- | :---------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| -------------- | ----------------------------------------------- |
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
-const readBuffer = new ArrayBuffer(400);
+const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then(() => {
console.log('Succeeded in reading image pixel data.'); // Called if the condition is met.
}).catch(error => {
@@ -116,19 +124,19 @@ readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void
Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------- | ---- | ------------------------------------------------------------ |
-| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written.|
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned. |
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- |
+| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written. The buffer size is obtained by calling **getPixelBytesNumber**.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned. |
**Example**
```js
-const readBuffer = new ArrayBuffer(400);
+const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer, (err, res) => {
if(err) {
console.log('Failed to read image pixel data.'); // Called if no condition is met.
@@ -144,7 +152,7 @@ readPixels(area: PositionArea): Promise\
Reads image pixel map data in an area. This API uses a promise to return the data read.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -156,7 +164,7 @@ Reads image pixel map data in an area. This API uses a promise to return the dat
| Type | Description |
| :------------- | :-------------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
@@ -175,20 +183,20 @@ readPixels(area: PositionArea, callback: AsyncCallback\): void
Reads image pixel map data in an area. This API uses an asynchronous callback to return the data read.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | ------------------------------ |
| area | [PositionArea](#positionarea7) | Yes | Area from which the image pixel map data will be read. |
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err, pixelmap) => {
if(pixelmap == undefined){
@@ -211,7 +219,7 @@ writePixels(area: PositionArea): Promise\
Writes image pixel map data to an area. This API uses a promise to return the operation result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -223,13 +231,13 @@ Writes image pixel map data to an area. This API uses a promise to return the op
| Type | Description |
| :------------- | :-------------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts)
.then( pixelmap => {
@@ -265,21 +273,21 @@ writePixels(area: PositionArea, callback: AsyncCallback\): void
Writes image pixel map data to an area. This API uses an asynchronous callback to return the operation result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------ | ---- | ------------------------------ |
| area | [PositionArea](#positionarea7) | Yes | Area to which the image pixel map data will be written. |
-| callback: | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const area = new ArrayBuffer(400);
pixelmap.writePixels(area, (error) => {
- if (error!=undefined) {
+ if (error != undefined) {
console.info('Failed to write pixelmap into the specified area.');
} else {
const readArea = {
@@ -298,7 +306,7 @@ writeBufferToPixels(src: ArrayBuffer): Promise\
Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** object. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -310,14 +318,14 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj
| Type | Description |
| -------------- | ----------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color).then(() => {
console.log("Succeeded in writing data from a buffer to a PixelMap.");
}).catch((err) => {
@@ -331,21 +339,21 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\): void
Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** object. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------ |
| src | ArrayBuffer | Yes | Buffer from which the image data will be read. |
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
-const color = new ArrayBuffer(96);\
+const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color, function(err) {
if (err) {
console.error("Failed to write data from a buffer to a PixelMap.");
@@ -362,7 +370,7 @@ getImageInfo(): Promise\
Obtains pixel map information of this image. This API uses a promise to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
@@ -387,7 +395,7 @@ getImageInfo(callback: AsyncCallback\): void
Obtains pixel map information of this image. This API uses an asynchronous callback to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -399,7 +407,7 @@ Obtains pixel map information of this image. This API uses an asynchronous callb
```js
pixelmap.getImageInfo((imageInfo) => {
- console.log("Succeeded in obtaining the image pixel map information..");
+ console.log("Succeeded in obtaining the image pixel map information.");
})
```
@@ -407,21 +415,21 @@ pixelmap.getImageInfo((imageInfo) => {
getBytesNumberPerRow(): number
-Obtains the number of bytes per line of the image pixel map.
+Obtains the number of bytes per row of this image pixel map.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| ------ | -------------------- |
-| number | Number of bytes per line.|
+| number | Number of bytes per row.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err,pixelmap) => {
let rowCount = pixelmap.getBytesNumberPerRow();
@@ -432,9 +440,9 @@ image.createPixelMap(color, opts, (err,pixelmap) => {
getPixelBytesNumber(): number
-Obtains the total number of bytes of the image pixel map.
+Obtains the total number of bytes of this image pixel map.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
@@ -448,25 +456,410 @@ Obtains the total number of bytes of the image pixel map.
let pixelBytesNumber = pixelmap.getPixelBytesNumber();
```
+### getDensity9+
+
+getDensity():number
+
+Obtains the density of this image pixel map.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | --------------- |
+| number | Density of the image pixel map.|
+
+**Example**
+
+```js
+let getDensity = pixelmap.getDensity();
+```
+
+### opacity9+
+
+opacity(rate: number, callback: AsyncCallback\): void
+
+Sets an opacity rate for this image pixel map. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ------------------------------ |
+| rate | number | Yes | Opacity rate to set. The value ranges from 0 to 1. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.opacity(0.5);
+}
+```
+
+### opacity9+
+
+opacity(rate: number): Promise\
+
+Sets an opacity rate for this image pixel map. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | --------------------------- |
+| rate | number | Yes | Opacity rate to set. The value ranges from 0 to 1.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | ----------------------------------------------- |
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.opacity(0.5);
+}
+```
+
+### createAlphaPixelmap9+
+
+createAlphaPixelmap(): Promise\
+
+Creates a **PixelMap** object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Return value**
+
+| Type | Description |
+| -------------------------------- | --------------------------- |
+| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.|
+
+**Example**
+
+```js
+pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => {
+ if (alphaPixelMap == undefined) {
+ console.info('Failed to obtain new pixel map.');
+ } else {
+ console.info('Succeed in obtaining new pixel map.');
+ }
+})
+```
+
+### createAlphaPixelmap9+
+
+createAlphaPixelmap(callback: AsyncCallback\): void
+
+Creates a **PixelMap** object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------ | ---- | ------------------------ |
+| callback | AsyncCallback\ | Yes | Callback used to return the **PixelMap** object.|
+
+**Example**
+
+```js
+let pixelMap = await imageSource.createPixelMap();
+if (pixelMap != undefined) {
+ pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => {
+ console.info('Failed to obtain new pixel map.');
+ })
+} else {
+ console.info('Succeed in obtaining new pixel map.');
+}
+```
+
+### scale9+
+
+scale(x: number, y: number, callback: AsyncCallback\): void
+
+Scales this image based on the input width and height. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ------------------------------- |
+| x | number | Yes | Scaling ratio of the width.|
+| y | number | Yes | Scaling ratio of the height.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned. |
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.scale(2.0, 1.0);
+}
+```
+
+### scale9+
+
+scale(x: number, y: number): Promise\
+
+Scales this image based on the input width and height. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------------------------- |
+| x | number | Yes | Scaling ratio of the width.|
+| y | number | Yes | Scaling ratio of the height.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.scale(2.0, 1.0);
+}
+```
+
+### translate9+
+
+translate(x: number, y: number, callback: AsyncCallback\): void
+
+Translates this image based on the input coordinates. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------- |
+| x | number | Yes | X coordinate to translate. |
+| y | number | Yes | Y coordinate to translate. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.translate(3.0, 1.0);
+}
+```
+
+### translate9+
+
+translate(x: number, y: number): Promise\
+
+Translates this image based on the input coordinates. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ----------- |
+| x | number | Yes | X coordinate to translate.|
+| y | number | Yes | Y coordinate to translate.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.translate(3.0, 1.0);
+}
+```
+
+### rotate9+
+
+rotate(angle: number, callback: AsyncCallback\): void
+
+Rotates this image based on the input angle. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------- |
+| angle | number | Yes | Angle to rotate. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.rotate(90.0);
+}
+```
+
+### rotate9+
+
+rotate(angle: number): Promise\
+
+Rotates this image based on the input angle. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ----------------------------- |
+| angle | number | Yes | Angle to rotate. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.rotate(90.0);
+}
+```
+
+### flip9+
+
+flip(horizontal: boolean, vertical: boolean, callback: AsyncCallback\): void
+
+Flips this image horizontally or vertically, or both. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | -------------------- | ---- | ----------------------------- |
+| horizontal | boolean | Yes | Whether to flip the image horizontally. |
+| vertical | boolean | Yes | Whether to flip the image vertically. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.flip(false, true);
+}
+```
+
+### flip9+
+
+flip(horizontal: boolean, vertical: boolean): Promise\
+
+Flips this image horizontally or vertically, or both. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------- | ---- | --------- |
+| horizontal | boolean | Yes | Whether to flip the image horizontally.|
+| vertical | boolean | Yes | Whether to flip the image vertically.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.flip(false, true);
+}
+```
+
+### crop9+
+
+crop(region: Region, callback: AsyncCallback\): void
+
+Crops this image based on the input size. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------- |
+| region | [Region](#region7) | Yes | Size of the image after cropping. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.crop(3x3);
+}
+```
+
+### crop9+
+
+crop(region: Region): Promise\
+
+Crops this image based on the input size. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------------------ | ---- | ----------- |
+| region | [Region](#region7) | Yes | Size of the image after cropping.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.crop(3x3);
+}
+```
+
### release7+
release():Promise\
Releases this **PixelMap** object. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
-| Type | Description |
-| -------------- | ------------------ |
-| Promise\ | Promise used to return the operation result.|
+| Type | Description |
+| -------------- | ------------------------------- |
+| Promise\ | Promise used to return the result.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => {
pixelmap.release().then(() => {
@@ -483,25 +876,23 @@ release(callback: AsyncCallback\): void
Releases this **PixelMap** object. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------ |
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => {
pixelmap.release().then(() => {
console.log('Succeeded in releasing pixelmap object.');
- }).catch(error => {
- console.log('Failed to release pixelmap object.');
})
})
```
@@ -512,7 +903,7 @@ createImageSource(uri: string): ImageSource
Creates an **ImageSource** instance based on the URI.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -533,18 +924,45 @@ let path = this.context.getApplicationContext().fileDirs + "test.jpg";
const imageSourceApi = image.createImageSource(path);
```
+## image.createImageSource9+
+
+createImageSource(uri: string, options: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance based on the URI.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------- | ---- | ----------------------------------- |
+| uri | string | Yes | Image path. Currently, only the application sandbox path is supported. |
+| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | -------------------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.|
+
+**Example**
+
+```js
+const imageSourceApi = image.createImageSource('/sdcard/test.jpg');
+```
+
## image.createImageSource7+
createImageSource(fd: number): ImageSource
Creates an **ImageSource** instance based on the file descriptor.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | -------------- |
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------- |
| fd | number | Yes | File descriptor.|
**Return value**
@@ -559,13 +977,144 @@ Creates an **ImageSource** instance based on the file descriptor.
const imageSourceApi = image.createImageSource(0);
```
+## image.createImageSource9+
+
+createImageSource(fd: number, options: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance based on the file descriptor.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------- | ---- | ----------------------------------- |
+| fd | number | Yes | File descriptor. |
+| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | -------------------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.|
+
+**Example**
+
+```js
+const imageSourceApi = image.createImageSource(fd);
+```
+
+## image.createImageSource9+
+
+createImageSource(buf: ArrayBuffer): ImageSource
+
+Creates an **ImageSource** instance based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ----------- | ---- | ---------------- |
+| buf | ArrayBuffer | Yes | Array of image buffers.|
+
+**Example**
+
+```js
+const buf = new ArrayBuffer(96);
+const imageSourceApi = image.createImageSource(buf);
+```
+
+## image.createImageSource9+
+
+createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | -------------------------------- | ---- | ------------------------------------ |
+| buf | ArrayBuffer | Yes | Array of image buffers. |
+| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | -------------------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.|
+
+**Example**
+
+```js
+const data = new ArrayBuffer(112);
+const imageSourceApi = image.createImageSource(data);
+```
+
+## image.CreateIncrementalSource9+
+
+CreateIncrementalSource(buf: ArrayBuffer): ImageSource
+
+Creates an **ImageSource** instance in incremental mode based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------| ---- | ----------|
+| buf | ArrayBuffer | Yes | Incremental data.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | --------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns undefined otherwise.|
+
+**Example**
+
+```js
+const buf = new ArrayBuffer(96);
+const imageSourceApi = image.CreateIncrementalSource(buf);
+```
+
+## image.CreateIncrementalSource9+
+
+CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance in incremental mode based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------- | ---- | ------------------------------------ |
+| buf | ArrayBuffer | Yes | Incremental data. |
+| options | [SourceOptions](#sourceoptions9) | No | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | --------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns undefined otherwise.|
+
+**Example**
+
+```js
+const buf = new ArrayBuffer(96);
+const imageSourceApi = image.CreateIncrementalSource(buf);
+```
+
## ImageSource
Provides APIs to obtain image information. Before calling any API in **ImageSource**, you must use **createImageSource** to create an **ImageSource** instance.
### Attributes
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable| Writable| Description |
| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
@@ -577,7 +1126,7 @@ getImageInfo(index: number, callback: AsyncCallback\): void
Obtains information about an image with the specified index. This API uses an asynchronous callback to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -604,7 +1153,7 @@ getImageInfo(callback: AsyncCallback\): void
Obtains information about this image. This API uses an asynchronous callback to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -626,7 +1175,7 @@ getImageInfo(index?: number): Promise\
Obtains information about an image with the specified index. This API uses a promise to return the image information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -657,7 +1206,7 @@ getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\ | Promise used to return the property value. If the operation fails, the default value is returned.|
**Example**
@@ -687,7 +1236,7 @@ getImageProperty(key:string, callback: AsyncCallback\): void
Obtains the value of a property with the specified index in this image. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -714,14 +1263,14 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa
Obtains the value of a property in this image. This API uses an asynchronous callback to return the property value in a string.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
-| key | string | Yes | Name of the property. |
-| options | [GetImagePropertyOptions](#getimagepropertyoptions7) | Yes | Image properties, including the image index and default property value. |
+| Name | Type | Mandatory| Description |
+| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------- |
+| key | string | Yes | Name of the property. |
+| options | [GetImagePropertyOptions](#getimagepropertyoptions7) | Yes | Image properties, including the image index and default property value. |
| callback | AsyncCallback\ | Yes | Callback used to return the property value. If the operation fails, the default value is returned.|
**Example**
@@ -737,13 +1286,128 @@ imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {
})
```
+### modifyImageProperty9+
+
+modifyImageProperty(key: string, value: string): Promise\
+
+Modifies the value of a property in this image. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------ | ---- | ------------ |
+| key | string | Yes | Name of the property.|
+| value | string | Yes | New value of the property. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+imageSourceApi.modifyImageProperty("ImageWidth", "120")
+ .then(() => {
+ const w = imageSourceApi.getImageProperty("ImageWidth")
+ console.info('w', w);
+ })
+```
+
+### modifyImageProperty9+
+
+modifyImageProperty(key: string, value: string, callback: AsyncCallback\): void
+
+Modifies the value of a property in this image. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------- | ---- | ------------------------------ |
+| key | string | Yes | Name of the property. |
+| value | string | Yes | New value of the property. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+imageSourceApi.modifyImageProperty("ImageWidth", "120",() => {})
+```
+
+### updateData9+
+
+updateData(buf: ArrayBuffer, isFinished: boolean, value: number, length: number): Promise\
+
+Updates incremental data. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ----------- | ---- | ------------ |
+| buf | ArrayBuffer | Yes | Incremental data. |
+| isFinished | boolean | Yes | Whether the update is complete.|
+| value | number | No | Offset for data reading. |
+| length | number | No | Array length. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | -------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+const array = new ArrayBuffer(100);
+imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => {
+ console.info('Succeeded in updating data.');
+ })
+```
+
+
+### updateData9+
+
+updateData(buf: ArrayBuffer, isFinished: boolean, value: number, length: number, callback: AsyncCallback\): void
+
+Updates incremental data. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------- | ---- | -------------------- |
+| buf | ArrayBuffer | Yes | Incremental data. |
+| isFinished | boolean | Yes | Whether the update is complete. |
+| value | number | No | Offset for data reading. |
+| length | number | No | Array length. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+const array = new ArrayBuffer(100);
+imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {
+ if(data !== undefined){
+ console.info('Succeeded in updating data.');
+ }
+ })
+```
+
### createPixelMap7+
createPixelMap(options?: DecodingOptions): Promise\
Creates a **PixelMap** object based on image decoding parameters. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -773,7 +1437,7 @@ createPixelMap(callback: AsyncCallback\): void
Creates a **PixelMap** object based on the default parameters. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -784,11 +1448,9 @@ Creates a **PixelMap** object based on the default parameters. This API uses an
**Example**
```js
-imageSourceApi.createPixelMap(pixelmap => {
- console.log('Succeeded in creating pixelmap object.');
-}).catch(error => {
- console.log('Failed to create pixelmap object.');
-})
+imageSourceApi.createPixelMap((err, pixelmap) => {
+ console.info('Succeeded in creating pixelmap object.');
+ })
```
### createPixelMap7+
@@ -797,7 +1459,7 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\): vo
Creates a **PixelMap** object based on image decoding parameters. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -821,7 +1483,7 @@ release(callback: AsyncCallback\): void
Releases this **ImageSource** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -843,13 +1505,13 @@ release(): Promise\
Releases this **ImageSource** instance. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Return value**
| Type | Description |
| -------------- | --------------------------- |
-| Promise\ | Promise used to return the operation result.|
+| Promise\ | Promise used to return the result.|
**Example**
@@ -867,7 +1529,7 @@ createImagePacker(): ImagePacker
Creates an **ImagePacker** instance.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Return value**
@@ -887,7 +1549,7 @@ Provide APIs to pack images. Before calling any API in **ImagePacker**, you must
### Attributes
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
| Name | Type | Readable| Writable| Description |
| ---------------- | -------------- | ---- | ---- | -------------------------- |
@@ -899,7 +1561,7 @@ packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\
Packs an image. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Parameters**
@@ -935,8 +1597,8 @@ Packs an image. This API uses a promise to return the result.
**Return value**
| Type | Description |
-| :--------------------------- | :-------------------------------------------- |
-| Promise\ | Promise used to return the packed data.|
+| ---------------------------- | --------------------------------------------- |
+| Promise\ | Promise used to return the packed data.|
**Example**
@@ -957,7 +1619,7 @@ packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\ {
console.log('Succeeded in packing the image.');
-}).catch(error => {
- console.log('Failed to pack the image.');
})
```
@@ -985,7 +1645,7 @@ packing(source: PixelMap, option: PackingOption): Promise\
Packs an image. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Parameters**
@@ -996,8 +1656,8 @@ Packs an image. This API uses a promise to return the result.
**Return value**
-| Type | Description |
-| :--------------------------- | :-------------------------------------------- |
+| Type | Description |
+| --------------------- | -------------------------------------------- |
| Promise\ | Promise used to return the packed data.|
**Example**
@@ -1019,7 +1679,7 @@ release(callback: AsyncCallback\): void
Releases this **ImagePacker** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Parameters**
@@ -1041,12 +1701,12 @@ release(): Promise\
Releases this **ImagePacker** instance. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Return value**
-| Type | Description |
-| :------------- | :------------------------------------------------------ |
+| Type | Description |
+| -------------- | ------------------------------------------------------ |
| Promise\ | Promise used to return the instance release result. If the operation fails, an error message is returned.|
**Example**
@@ -1098,11 +1758,11 @@ Before calling any APIs in **ImageReceiver**, you must create an **ImageReceiver
**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
-| Name | Type | Readable| Writable| Description |
-| --------------------- | ---------------------------- | ---- | ---- | ------------------ |
-| size9+ | [Size](#size) | Yes | No | Image size. |
-| capacity9+ | number | Yes | No | Maximum number of images that can be accessed at the same time.|
-| format9+ | [ImageFormat](#imageformat9) | Yes | No | Image format. |
+| Name | Type | Readable| Writable| Description |
+| -------- | ---------------------------- | ---- | ---- | ------------------ |
+| size | [Size](#size) | Yes | No | Image size. |
+| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.|
+| format | [ImageFormat](#imageformat9) | Yes | No | Image format. |
### getReceivingSurfaceId9+
@@ -1192,7 +1852,7 @@ Reads the latest image from the **ImageReceiver** instance. This API uses a prom
| Type | Description |
| ------------------------- | ------------------ |
-| Promise<[Image](#image8)> | Promise used to return the latest image.|
+| Promise<[Image](#image9)> | Promise used to return the latest image.|
**Example**
@@ -1327,11 +1987,11 @@ Provides APIs for basic image operations, including obtaining image information
**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Type | Readable| Writable| Description |
-| --------------------- | ------------------ | ---- | ---- | -------------------------------------------------- |
-| clipRect9+ | [Region](#region7) | Yes | Yes | Image area to be cropped. |
-| size9+ | [Size](#size) | Yes | No | Image size. |
-| format9+ | number | Yes | No | Image format. For details, see [PixelMapFormat](#pixelmapformat7).|
+| Name | Type | Readable| Writable| Description |
+| -------- | ------------------ | ---- | ---- | -------------------------------------------------- |
+| clipRect | [Region](#region7) | Yes | Yes | Image area to be cropped. |
+| size | [Size](#size) | Yes | No | Image size. |
+| format | number | Yes | No | Image format. For details, see [PixelMapFormat](#pixelmapformat7).|
### getComponent9+
@@ -1407,8 +2067,6 @@ The corresponding resources must be released before another image arrives.
```js
img.release(() =>{
console.log('release succeeded.');
-}).catch(error => {
- console.log('release failed.');
})
```
@@ -1442,7 +2100,7 @@ img.release().then(() =>{
Describes area information in an image.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Type | Readable| Writable| Description |
| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ |
@@ -1455,7 +2113,7 @@ Describes area information in an image.
Describes image information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name| Type | Readable| Writable| Description |
| ---- | ------------- | ---- | ---- | ---------- |
@@ -1465,7 +2123,7 @@ Describes image information.
Describes the size of an image.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Type | Readable| Writable| Description |
| ------ | ------ | ---- | ---- | -------------- |
@@ -1476,19 +2134,20 @@ Describes the size of an image.
Enumerates the pixel formats of images.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Default Value| Description |
-| --------- | ------ | ----------------- |
-| UNKNOWN | 0 | Unknown format. |
-| RGBA_8888 | 3 | RGBA_8888.|
-| RGB_565 | 2 | RGB_565. |
+| Name | Default Value| Description |
+| ---------------------- | ------ | ----------------- |
+| UNKNOWN | 0 | Unknown format. |
+| RGB_565 | 2 | RGB_565. |
+| RGBA_8888 | 3 | RGBA_8888.|
+| BGRA_88889+ | 4 | BGRA_8888.|
## AlphaType9+
Enumerates the alpha types of images.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Default Value| Description |
| -------- | ------ | ----------------------- |
@@ -1501,32 +2160,45 @@ Enumerates the alpha types of images.
Enumerates the scale modes of images.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Default Value| Description |
| --------------- | ------ | -------------------------------------------------- |
| CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.|
| FIT_TARGET_SIZE | 2 | Reduces the image size to the dimensions of the target. |
+## SourceOptions9+
+
+Defines image source initialization options.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+| Name | Type | Readable| Writable| Description |
+| ----------------- | ---------------------------------- | ---- | ---- | ------------------ |
+| sourceDensity | number | Yes | Yes | Density of the image source.|
+| sourcePixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel format of the image source. |
+| sourceSize | [Size](#size) | Yes | Yes | Pixel size of the image source. |
+
+
## InitializationOptions8+
Defines pixel map initialization options.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Type | Readable| Writable| Description |
-| ---------------------- | ---------------------------------- | ---- | ---- | -------------- |
-| alphaType9+ | [AlphaType](#alphatype9) | Yes | Yes | Alpha type. |
-| editable | boolean | Yes | Yes | Whether the image is editable. |
-| pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. |
-| scaleMode9+ | [ScaleMode](#scalemode9) | Yes | Yes | Scale mode. |
-| size | [Size](#size) | Yes | Yes | Image size.|
+| Name | Type | Readable| Writable| Description |
+| ------------------------ | ---------------------------------- | ---- | ---- | -------------- |
+| alphaType9+ | [AlphaType](#alphatype9) | Yes | Yes | Alpha type. |
+| editable | boolean | Yes | Yes | Whether the image is editable. |
+| pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. |
+| scaleMode9+ | [ScaleMode](#scalemode9) | Yes | Yes | Scale mode. |
+| size | [Size](#size) | Yes | Yes | Image size.|
## DecodingOptions7+
Defines image decoding options.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable| Writable| Description |
| ------------------ | ---------------------------------- | ---- | ---- | ---------------- |
@@ -1542,7 +2214,7 @@ Defines image decoding options.
Describes region information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name| Type | Readable| Writable| Description |
| ---- | ------------- | ---- | ---- | ------------ |
@@ -1554,18 +2226,18 @@ Describes region information.
Defines the option for image packing.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | -------------- |
-| format | string | Yes | Yes | Format of the packed image. |
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | --------------------------------------------------- |
+| format | string | Yes | Yes | Format of the packed image. |
| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.|
## GetImagePropertyOptions7+
Describes image properties.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable| Writable| Description |
| ------------ | ------ | ---- | ---- | ------------ |
@@ -1576,18 +2248,18 @@ Describes image properties.
Describes the exchangeable image file format (Exif) information of an image.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Default Value | Description |
-| ----------------- | ----------------- | -------------------- |
-| BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. |
-| ORIENTATION | "Orientation" | Image orientation. |
-| IMAGE_LENGTH | "ImageLength" | Image length. |
-| IMAGE_WIDTH | "ImageWidth" | Image width. |
-| GPS_LATITUDE | "GPSLatitude" | Image latitude. |
-| GPS_LONGITUDE | "GPSLongitude" | Image longitude. |
-| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S.|
-| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E.|
+| Name | Default Value | Description |
+| ----------------- | ----------------------- | ------------------------ |
+| BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. |
+| ORIENTATION | "Orientation" | Image orientation. |
+| IMAGE_LENGTH | "ImageLength" | Image length. |
+| IMAGE_WIDTH | "ImageWidth" | Image width. |
+| GPS_LATITUDE | "GPSLatitude" | Image latitude. |
+| GPS_LONGITUDE | "GPSLongitude" | Image longitude. |
+| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. |
+| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. |
## ImageFormat9+
@@ -1625,3 +2297,45 @@ Describes the color components of an image.
| rowStride | number | Yes | No | Row stride. |
| pixelStride | number | Yes | No | Pixel stride. |
| byteBuffer | ArrayBuffer | Yes | No | Component buffer.|
+
+## ResponseCode
+
+Enumerates the response codes returned upon build errors.
+
+| Name | Value | Description |
+| ----------------------------------- | -------- | --------------------------------------------------- |
+| ERR_MEDIA_INVALID_VALUE | -1 | Invalid value. |
+| SUCCESS | 0 | Operation successful. |
+| ERROR | 62980096 | Operation failed. |
+| ERR_IPC | 62980097 | IPC error. |
+| ERR_SHAMEM_NOT_EXIST | 62980098 | The shared memory does not exist. |
+| ERR_SHAMEM_DATA_ABNORMAL | 62980099 | The shared memory is abnormal. |
+| ERR_IMAGE_DECODE_ABNORMAL | 62980100 | An error occurs during image decoding. |
+| ERR_IMAGE_DATA_ABNORMAL | 62980101 | The input image data is incorrect. |
+| ERR_IMAGE_MALLOC_ABNORMAL | 62980102 | An error occurs during image memory allocation. |
+| ERR_IMAGE_DATA_UNSUPPORT | 62980103 | Unsupported image type. |
+| ERR_IMAGE_INIT_ABNORMAL | 62980104 | An error occurs during image initialization. |
+| ERR_IMAGE_GET_DATA_ABNORMAL | 62980105 | An error occurs during image data retrieval. |
+| ERR_IMAGE_TOO_LARGE | 62980106 | The image data is too large. |
+| ERR_IMAGE_TRANSFORM | 62980107 | An error occurs during image transformation. |
+| ERR_IMAGE_COLOR_CONVERT | 62980108 | An error occurs during image color conversion. |
+| ERR_IMAGE_CROP | 62980109 | An error occurs during image cropping. |
+| ERR_IMAGE_SOURCE_DATA | 62980110 | The image source data is incorrect. |
+| ERR_IMAGE_SOURCE_DATA_INCOMPLETE | 62980111 | The image source data is incomplete. |
+| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image format does not match. |
+| ERR_IMAGE_UNKNOWN_FORMAT | 62980113 | Unknown image format. |
+| ERR_IMAGE_SOURCE_UNRESOLVED | 62980114 | The image source is not parsed. |
+| ERR_IMAGE_INVALID_PARAMETER | 62980115 | Invalid image parameter. |
+| ERR_IMAGE_DECODE_FAILED | 62980116 | Decoding failed. |
+| ERR_IMAGE_PLUGIN_REGISTER_FAILED | 62980117 | Failed to register the plug-in. |
+| ERR_IMAGE_PLUGIN_CREATE_FAILED | 62980118 | Failed to create the plug-in. |
+| ERR_IMAGE_ENCODE_FAILED | 62980119 | Failed to encode the image. |
+| ERR_IMAGE_ADD_PIXEL_MAP_FAILED | 62980120 | Failed to add the image pixel map. |
+| ERR_IMAGE_HW_DECODE_UNSUPPORT | 62980121 | Unsupported image hardware decoding. |
+| ERR_IMAGE_DECODE_HEAD_ABNORMAL | 62980122 | The image decoding header is incorrect. |
+| ERR_IMAGE_DECODE_EXIF_UNSUPPORT | 62980123 | EXIF decoding is not supported. |
+| ERR_IMAGE_PROPERTY_NOT_EXIST | 62980124 | The image property does not exist. The error codes for the image start from 150.|
+| ERR_IMAGE_READ_PIXELMAP_FAILED | 62980246 | Failed to read the pixel map. |
+| ERR_IMAGE_WRITE_PIXELMAP_FAILED | 62980247 | Failed to write the pixel map. |
+| ERR_IMAGE_PIXELMAP_NOT_ALLOW_MODIFY | 62980248 | Modification to the pixel map is not allowed. |
+| ERR_IMAGE_CONFIG_FAILED | 62980259 | The software parameter setting is incorrect. |
diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md
index b863c6189f1c4d89bf5b7ccb7fd3dc887992ec03..3abc771bff725718ccd5df3eb0334331701faea4 100644
--- a/en/application-dev/reference/apis/js-apis-resource-manager.md
+++ b/en/application-dev/reference/apis/js-apis-resource-manager.md
@@ -2,7 +2,8 @@
The resource management module provides APIs to obtain information about the current device configuration (including the language, region, screen direction, and MCC/MNC) and device capability (including the device type and resolution).
-> **NOTE**
+> **NOTE**
+>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -12,9 +13,9 @@ The resource management module provides APIs to obtain information about the cur
import resourceManager from '@ohos.resourceManager';
```
-## Usage
+## How to Use
-Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its APIs without first importing the required bundle. This method, however, is not applicable to the FA model.
+Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This method, however, is not applicable to the FA model.
```
this.context.resourceManager;
@@ -26,14 +27,14 @@ getResourceManager(callback: AsyncCallback<ResourceManager>): void
Obtains the **ResourceManager** object of this application. This API uses an asynchronous callback to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------- |
-| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.|
**Example**
```
@@ -59,7 +60,7 @@ getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManage
Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses an asynchronous callback to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
@@ -67,7 +68,7 @@ This API is used only in the FA model.
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ----------------------------- |
| bundleName | string | Yes | Bundle name of the target application. |
-| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.|
**Example**
```
@@ -82,7 +83,7 @@ getResourceManager(): Promise<ResourceManager>
Obtains the **ResourceManager** object of this application. This API uses a promise to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
@@ -113,7 +114,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager>
Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses a promise to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
@@ -229,21 +230,34 @@ resourceManager.getResourceManager((error, mgr) => {
## RawFileDescriptor8+
-Defines the descriptor information of the raw file.
+Defines the descriptor of the raw file.
**System capability**: SystemCapability.Global.ResourceManager
| Name | Type | Description |
| ------ | ------ | ------------------ |
-| fd | number | Descriptor of a raw file.|
-| offset | number | Offset to the start position of the raw file. |
+| fd | number | Descriptor of the raw file.|
+| offset | number | Start offset of the raw file. |
| length | number | Length of the raw file. |
+## Resource9+
+
+Defines the resource information of an application.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+| Name | Type | Description |
+| ------ | ------ | ------------------ |
+| bundleName | string | Bundle name of the application.|
+| moduleName | string | Module name of the application. |
+| id | number | Resource ID. |
+
## ResourceManager
Defines the capability of accessing application resources.
-> **NOTE**
+> **NOTE**
+>
> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
>
> - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**.
@@ -261,7 +275,7 @@ Obtains the string corresponding to the specified resource ID. This API uses an
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
@@ -307,6 +321,68 @@ Obtains the string corresponding to the specified resource ID. This API uses a p
```
+### getString9+
+
+getString(resource: Resource, callback: AsyncCallback<string>): void
+
+Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
+ this.context.resourceManager.getString(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
+ ```
+
+### getString9+
+
+getString(resource: Resource): Promise<string>
+
+Obtains the string corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
+ this.context.resourceManager.getString(resource).then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getstring promise error is " + error);
+ });
+ ```
+
### getStringArray
getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void
@@ -319,7 +395,7 @@ Obtains the string array corresponding to the specified resource ID. This API us
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Example**
```
@@ -364,6 +440,67 @@ Obtains the string array corresponding to the specified resource ID. This API us
});
```
+### getStringArray9+
+
+getStringArray(resource: Resource, callback: AsyncCallback<Array<string>>): void
+
+Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
+ };
+ this.context.resourceManager.getStringArray(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let strArray = value;
+ }
+ });
+ ```
+
+### getStringArray9+
+
+getStringArray(resource: Resource): Promise<Array<string>>
+
+Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<Array<string>> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
+ };
+ this.context.resourceManager.getStringArray(resource).then(value => {
+ let strArray = value;
+ }).catch(error => {
+ console.log("getStringArray promise error is " + error);
+ });
+ ```
### getMedia
@@ -377,7 +514,7 @@ Obtains the content of the media file corresponding to the specified resource ID
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Example**
```
@@ -422,6 +559,67 @@ Obtains the content of the media file corresponding to the specified resource ID
});
```
+### getMedia9+
+
+getMedia(resource: Resource, callback: AsyncCallback<Uint8Array>): void
+
+Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMedia(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
+ });
+ ```
+
+### getMedia9+
+
+getMedia(resource: Resource): Promise<Uint8Array>
+
+Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<Uint8Array> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMedia(resource).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.log("getMedia promise error is " + error);
+ });
+ ```
### getMediaBase64
@@ -435,7 +633,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
@@ -480,6 +678,68 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
});
```
+### getMediaBase649+
+
+getMediaBase64(resource: Resource, callback: AsyncCallback<string>): void
+
+Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------ |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMediaBase64(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
+ });
+ ```
+
+### getMediaBase649+
+
+getMediaBase64(resource: Resource): Promise<string>
+
+Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | -------------------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMediaBase64(resource).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.log("getMediaBase64 promise error is " + error);
+ });
+ ```
+
### getConfiguration
@@ -492,7 +752,7 @@ Obtains the device configuration. This API uses an asynchronous callback to retu
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------- |
-| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the result.|
**Example**
```
@@ -546,7 +806,7 @@ Obtains the device capability. This API uses an asynchronous callback to return
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------- |
-| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the result.|
**Example**
```
@@ -593,7 +853,7 @@ Obtains the device capability. This API uses a promise to return the result.
getPluralString(resId: number, num: number, callback: AsyncCallback<string>): void
-Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -601,8 +861,8 @@ Obtains the specified number of singular-plural strings corresponding to the spe
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------- |
| resId | number | Yes | Resource ID. |
-| num | number | Yes | Number that determines the plural or singular form. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
@@ -622,7 +882,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe
getPluralString(resId: number, num: number): Promise<string>
-Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -630,7 +890,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
-| num | number | Yes | Number that determines the plural or singular form. |
+| num | number | Yes | Number. |
**Return value**
| Type | Description |
@@ -648,6 +908,70 @@ Obtains the specified number of singular-plural strings corresponding to the spe
});
```
+### getPluralString9+
+
+getPluralString(resource: Resource, num: number, callback: AsyncCallback<string>): void
+
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
+ };
+ this.context.resourceManager.getPluralString(resource, 1, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
+ ```
+
+### getPluralString9+
+
+getPluralString(resource: Resource, num: number): Promise<string>
+
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+| num | number | Yes | Number. |
+
+**Return value**
+| Type | Description |
+| --------------------- | ------------------------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
+ };
+ this.context.resourceManager.getPluralString(resource, 1).then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getPluralString promise error is " + error);
+ });
+ ```
+
### getRawFile8+
getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void
@@ -660,7 +984,7 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the raw file. |
-| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Example**
```
@@ -716,7 +1040,7 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------------- |
| path | string | Yes | Path of the raw file. |
-| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.|
**Example**
```
@@ -776,7 +1100,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
-| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```
@@ -805,7 +1129,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th
**Return value**
| Type | Description |
| ------------------- | ---- |
-| Promise<void> | No value is returned.|
+| Promise<void> | Promise that returns no value.|
**Example**
```
@@ -822,7 +1146,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th
release()
-Releases the created **resourceManager**.
+Releases a created **resourceManager** object.
**System capability**: SystemCapability.Global.ResourceManager
@@ -845,11 +1169,11 @@ Obtains the string corresponding to the specified resource name. This API uses a
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getStringByName("test", (error, value) => {
+ this.context.resourceManager.getStringByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -874,11 +1198,11 @@ Obtains the string corresponding to the specified resource name. This API uses a
**Return value**
| Type | Description |
| --------------------- | ----------- |
-| Promise<string> | String corresponding to the resource name.|
+| Promise<string> | Promise used to return the result.|
**Example**
```
- resourceManager.getStringByName("test").then(value => {
+ this.context.resourceManager.getStringByName("test").then(value => {
let string = value;
}).catch(error => {
console.log("getStringByName promise error is " + error);
@@ -897,11 +1221,11 @@ Obtains the string array corresponding to the specified resource name. This API
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getStringArrayByName("test", (error, value) => {
+ this.context.resourceManager.getStringArrayByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -930,7 +1254,7 @@ Obtains the string array corresponding to the specified resource name. This API
**Example**
```
- resourceManager.getStringArrayByName("test").then(value => {
+ this.context.resourceManager.getStringArrayByName("test").then(value => {
let strArray = value;
}).catch(error => {
console.log("getStringArrayByName promise error is " + error);
@@ -949,11 +1273,11 @@ Obtains the content of the media file corresponding to the specified resource na
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getMediaByName("test", (error, value) => {
+ this.context.resourceManager.getMediaByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -982,7 +1306,7 @@ Obtains the content of the media file corresponding to the specified resource na
**Example**
```
- resourceManager.getMediaByName("test").then(value => {
+ this.context.resourceManager.getMediaByName("test").then(value => {
let media = value;
}).catch(error => {
console.log("getMediaByName promise error is " + error);
@@ -1001,11 +1325,11 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getMediaBase64ByName("test", (error, value) => {
+ this.context.resourceManager.getMediaBase64ByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -1034,7 +1358,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
**Example**
```
- resourceManager.getMediaByName("test").then(value => {
+ this.context.resourceManager.getMediaBase64ByName("test").then(value => {
let media = value;
}).catch(error => {
console.log("getMediaBase64ByName promise error is " + error);
@@ -1045,7 +1369,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void
-Obtains the plural string corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
+Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1053,12 +1377,12 @@ Obtains the plural string corresponding to the specified resource name. This API
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------- |
| resName | string | Yes | Resource name. |
-| num | number | Yes | Number that determines the plural or singular form. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getPluralStringByName("test", 1, (error, value) => {
+ this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -1071,7 +1395,7 @@ Obtains the plural string corresponding to the specified resource name. This API
getPluralStringByName(resName: string, num: number): Promise<string>
-Obtains the plural string corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1079,7 +1403,7 @@ Obtains the plural string corresponding to the specified resource name. This API
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----- |
| resName | string | Yes | Resource name.|
-| num | number | Yes | Number that determines the plural or singular form. |
+| num | number | Yes | Number. |
**Return value**
| Type | Description |
@@ -1088,7 +1412,7 @@ Obtains the plural string corresponding to the specified resource name. This API
**Example**
```
- resourceManager.getPluralStringByName("test", 1).then(value => {
+ this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
let str = value;
}).catch(error => {
console.log("getPluralStringByName promise error is " + error);
@@ -1115,7 +1439,35 @@ Obtains the string corresponding to the specified resource ID. This API returns
**Example**
```
- resourceManager.getStringSync($r('app.string.test').id);
+ this.context.resourceManager.getStringSync($r('app.string.test').id);
+ ```
+
+### getStringSync9+
+
+getStringSync(resource: Resource): string
+
+Obtains the string corresponding to the specified resource object. This API returns the result synchronously.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| string | String corresponding to the resource object.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
+ this.context.resourceManager.getStringSync(resource);
```
### getStringByNameSync9+
@@ -1138,7 +1490,7 @@ Obtains the string corresponding to the specified resource name. This API return
**Example**
```
- resourceManager.getStringByNameSync("test");
+ this.context.resourceManager.getStringByNameSync("test");
```
### getBoolean9+
@@ -1161,7 +1513,34 @@ Obtains the Boolean result corresponding to the specified resource ID. This API
**Example**
```
- resourceManager.getBoolean($r('app.boolean.boolean_test').id);
+ this.context.resourceManager.getBoolean($r('app.boolean.boolean_test').id);
+ ```
+### getBoolean9+
+
+getBoolean(resource: Resource): boolean
+
+Obtains the Boolean result corresponding to the specified resource object. This API returns the result synchronously.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| boolean | Boolean result corresponding to the specified resource object.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.boolean.boolean_test').id
+ };
+ this.context.resourceManager.getBoolean(resource);
```
### getBooleanByName9+
@@ -1184,7 +1563,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP
**Example**
```
- resourceManager.getBooleanByName("boolean_test");
+ this.context.resourceManager.getBooleanByName("boolean_test");
```
### getNumber9+
@@ -1207,8 +1586,36 @@ Obtains the integer or float value corresponding to the specified resource ID. T
**Example**
```
- resourceManager.getNumber($r('app.integer.integer_test').id);
- resourceManager.getNumber($r('app.float.float_test').id);
+ this.context.resourceManager.getNumber($r('app.integer.integer_test').id);
+ this.context.resourceManager.getNumber($r('app.float.float_test').id);
+ ```
+
+### getNumber9+
+
+getNumber(resource: Resource): number
+
+Obtains the integer or float value corresponding to the specified resource object. This API returns the result synchronously.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| number | Integer or float value corresponding to the specified resource object.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.integer.integer_test').id
+ };
+ this.context.resourceManager.getNumber(resource);
```
### getNumberByName9+
@@ -1231,6 +1638,6 @@ Obtains the integer or float value corresponding to the specified resource name.
**Example**
```
- resourceManager.getNumberByName("integer_test");
- resourceManager.getNumberByName("float_test");
+ this.context.resourceManager.getNumberByName("integer_test");
+ this.context.resourceManager.getNumberByName("float_test");
```
diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md
index d75b957512e60e55aacfac1fdce2fdf063eb9c56..832d9754db5e41a11d38b020e77673ee5fe4d346 100644
--- a/en/application-dev/reference/apis/js-apis-screen-lock.md
+++ b/en/application-dev/reference/apis/js-apis-screen-lock.md
@@ -1,8 +1,10 @@
# Screen Lock Management
+The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set.
+
> **NOTE**
>
-> The initial APIs of this module are supported since API version … 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
@@ -73,6 +75,7 @@ Checks whether a device is in secure mode. This API uses an asynchronous callbac
**System capability**: SystemCapability.MiscServices.ScreenLock
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -125,6 +128,7 @@ Unlocks the screen. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -174,10 +178,12 @@ Subscribes to screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'beginWakeUp'**: Wakeup starts.
- **'endWakeUp'**: Wakeup ends.
- **'beginScreenOn'**: Screen turn-on starts.
- **'endScreenOn'**: Screen turn-on ends.
- **'beginScreenOff'**: Screen turn-off starts.
- **'endScreenOff'**: Screen turn-off ends.
- **'unlockScreen'**: The screen is unlocked.
- **'beginExitAnimation'**: Animation starts to exit. |
+| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.|
| callback | Callback\ | Yes| Callback used to return the result.|
**Example**
@@ -196,10 +202,12 @@ Subscribes to screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'beginSleep'**: The screen enters sleep mode.
- **'endSleep'**: The screen exits sleep mode.
- **'changeUser'**: The user is switched.|
+| type | string | Yes| Event type.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.|
| callback | Callback\ | Yes| Callback used to return the result. |
**Example**
@@ -217,11 +225,13 @@ Subscribes to screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'screenlockEnabled'**: Screen lock is enabled.|
-| callback | Callback\ | Yes| Callback used to return the result. |
+| type | string | Yes| Event type.
- **"screenlockEnabled"**: Screen lock is enabled.|
+| callback | Callback\ | Yes| Callback used to return the result.|
**Example**
@@ -240,10 +250,12 @@ Unsubscribes from screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'beginWakeUp'**: Wakeup starts.
- **'endWakeUp'**: Wakeup ends.
- **'beginScreenOn'**: Screen turn-on starts.
- **'endScreenOn'**: Screen turn-on ends.
- **'beginScreenOff'**: Screen turn-off starts.
- **'endScreenOff'**: Screen turn-off ends.
- **'unlockScreen'**: The screen is unlocked.
- **'beginExitAnimation'**: Animation starts to exit.
- **'screenlockEnabled'**: Screen lock is enabled.
- **'beginSleep'**: The screen enters sleep mode.
- **'endSleep'**: The screen exits sleep mode.
- **'changeUser'**: The user is switched.|
+| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.
- **"screenlockEnabled"**: Screen lock is enabled.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.|
| callback | Callback\ | Yes| Callback used to return the result.|
**Example**
@@ -262,11 +274,13 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| event | String | Yes| Event type.
- **'unlockScreenResult'**: Screen unlock result.
- **'screenDrawDone'**: Screen drawing is complete.|
-| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **0**: The unlock failed.
- **2**: The unlock was canceled.|
+| event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.|
+| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.|
| callback | AsyncCallback\ | Yes| Callback used to return the result.|
**Example**
@@ -279,18 +293,19 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac
## screenlock.sendScreenLockEvent9+
-sendScreenLockEvent(event: String, parameter: number): Promise
+sendScreenLockEvent(event: String, parameter: number): Promise\
Sends an event to the screen lock service. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
-**Parameters**
+**System API**: This is a system API and cannot be called by third-party applications.
+**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| event | String | Yes| Event type.
- **'unlockScreenResult'**: Screen unlock result.
- **'screenDrawDone'**: Screen drawing is complete.|
-| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **0**: The unlock failed.
- **2**: The unlock was canceled.|
+| event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.|
+| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.|
**Return value**
| Type| Description|
@@ -300,7 +315,7 @@ Sends an event to the screen lock service. This API uses a promise to return the
**Example**
```js
- screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((err, result) => {
+ screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => {
console.log('sending result:' + result);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md
index d2c9431ec4c0a4c8c4228b74e3bf85a30c697c0f..94f5f3cb5e532f3e28f221addb164358589b1754 100644
--- a/en/application-dev/reference/apis/js-apis-screen.md
+++ b/en/application-dev/reference/apis/js-apis-screen.md
@@ -223,6 +223,8 @@ Creates a virtual screen. This API uses an asynchronous callback to return the r
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid; available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -256,6 +258,8 @@ Creates a virtual screen. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------- | ---- | ------------------------ |
@@ -343,6 +347,8 @@ Sets the surface for a virtual screen. This API uses an asynchronous callback to
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -372,6 +378,8 @@ Sets the surface for a virtual screen. This API uses a promise to return the res
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------- |
@@ -696,9 +704,6 @@ Enumerates the screen orientations.
| HORIZONTAL | 2 | Horizontal. |
| REVERSE_VERTICAL | 3 | Reverse vertical. |
| REVERSE_HORIZONTAL | 4 | Reverse horizontal. |
-| SENSOR | 5 | The screen orientation follows the sensor direction. |
-| SENSOR_VERTICAL | 6 | The screen orientation follows the sensor direction vertically.|
-| SENSOR_HORIZONTAL | 7 | The screen orientation follows the sensor direction horizontally.|
## ScreenModeInfo
Defines the screen mode information.
diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
index 56ac3823f29e6cee7efa13094d4becf5528fa854..d98f43faaf7bc2a575cfa80907a776d9436bfbff 100644
--- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md
+++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
@@ -1,5 +1,7 @@
# User Authentication
+The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login.
+
> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -10,26 +12,7 @@
import userIAM_userAuth from '@ohos.userIAM.userAuth';
```
-## Example
-
-```js
-// API version 6
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-export default {
- startAuth() {
- console.info("start auth");
- let auth = userIAM_userAuth.getAuthenticator();
- auth.execute("FACE_ONLY", "S2").then((code)=>{
- console.info("auth success");
- // Add the logic to be executed when the authentication is successful.
- }).catch((code)=>{
- console.error("auth fail, code = " + code);
- // Add the logic to be executed when the authentication fails.
- });
- }
-}
-```
+## Sample Code
```js
// API version 8
@@ -106,133 +89,25 @@ export default {
}
```
-## userIAM_userAuth.getAuthenticator(deprecated)
-
-getAuthenticator(): Authenticator
-
-> **NOTE**
-> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8).
-
-Obtains an **Authenticator** object for user authentication.
-
-**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-**Return value**
-| Type | Description |
-| ----------------------------------------- | ------------ |
-| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.|
-
-**Example**
- ```js
- let authenticator = userIAM_userAuth.getAuthenticator();
- ```
-
-## Authenticator(deprecated)
-
-> **NOTE**
-> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8).
-
-Provides methods to manage an **Authenticator** object.
-
-
-### execute(deprecated)
-
-execute(type: string, level: string, callback: AsyncCallback<number>): void
-
-> **NOTE**
-> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
-
-Performs user authentication. This API uses asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
-| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
-| callback | AsyncCallback<number> | No | Callback used to return the result. |
-
- Parameters returned in callback
-
-| Type | Description |
-| ------ | ------------------------------------------------------------ |
-| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
-
-**Example**
- ```js
- authenticator.execute("FACE_ONLY", "S2", (code)=>{
- if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) {
- console.info("auth success");
- return;
- }
- console.error("auth fail, code = " + code);
- })
- ```
-
-
-### execute(deprecated)
-
-execute(type:string, level:string): Promise<number>
-
-> **NOTE**
-> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
-
-Performs user authentication. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
-| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
-
-**Return value**
-| Type | Description |
-| --------------------- | ------------------------------------------------------------ |
-| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
-
-**Example**
-
```js
-let authenticator = userIAM_userAuth.getAuthenticator();
-authenticator.execute("FACE_ONLY", "S2").then((code)=>{
- console.info("auth success");
-}).catch((code)=>{
- console.error("auth fail, code = " + code);
-});
-```
-
-## AuthenticationResult(deprecated)
-
-> **NOTE**
-> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8).
-
-Enumerates the authentication results.
+// API version 6
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
+export default {
+ startAuth() {
+ console.info("start auth");
+ let auth = userIAM_userAuth.getAuthenticator();
+ auth.execute("FACE_ONLY", "S2").then((code)=>{
+ console.info("auth success");
+ // Add the logic to be executed when the authentication is successful.
+ }).catch((code)=>{
+ console.error("auth fail, code = " + code);
+ // Add the logic to be executed when the authentication fails.
+ });
+ }
+}
+```
-| Name | Default Value| Description |
-| ------------------ | ------ | -------------------------- |
-| NO_SUPPORT | -1 | The device does not support the current authentication mode.|
-| SUCCESS | 0 | The authentication is successful. |
-| COMPARE_FAILURE | 1 | The feature comparison failed. |
-| CANCELED | 2 | The authentication was canceled by the user. |
-| TIMEOUT | 3 | The authentication has timed out. |
-| CAMERA_FAIL | 4 | The camera failed to start. |
-| BUSY | 5 | The authentication service is not available. Try again later. |
-| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. |
-| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.|
-| NOT_ENROLLED | 8 | No authentication credential is registered. |
-| GENERAL_ERROR | 100 | Other errors. |
## UserAuth8+
@@ -607,3 +482,131 @@ Enumerates the trust levels of the authentication result.
| ATL2 | 20000 | Trust level 2.|
| ATL3 | 30000 | Trust level 3.|
| ATL4 | 40000 | Trust level 4.|
+
+## userIAM_userAuth.getAuthenticator(deprecated)
+
+getAuthenticator(): Authenticator
+
+> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8).
+
+Obtains an **Authenticator** object for user authentication.
+
+**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+**Return value**
+| Type | Description |
+| ----------------------------------------- | ------------ |
+| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.|
+
+**Example**
+ ```js
+ let authenticator = userIAM_userAuth.getAuthenticator();
+ ```
+
+## Authenticator(deprecated)
+
+> **NOTE**
+> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8).
+
+Provides methods to manage an **Authenticator** object.
+
+
+### execute(deprecated)
+
+execute(type: string, level: string, callback: AsyncCallback<number>): void
+
+> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
+
+Performs user authentication. This API uses asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
+| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
+| callback | AsyncCallback<number> | No | Callback used to return the result. |
+
+ Parameters returned in callback
+
+| Type | Description |
+| ------ | ------------------------------------------------------------ |
+| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
+
+**Example**
+ ```js
+ authenticator.execute("FACE_ONLY", "S2", (code)=>{
+ if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) {
+ console.info("auth success");
+ return;
+ }
+ console.error("auth fail, code = " + code);
+ })
+ ```
+
+
+### execute(deprecated)
+
+execute(type:string, level:string): Promise<number>
+
+> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
+
+Performs user authentication. This API uses a promise to return the result.
+
+**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+**Parameters**
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
+| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ------------------------------------------------------------ |
+| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
+
+**Example**
+
+```js
+let authenticator = userIAM_userAuth.getAuthenticator();
+authenticator.execute("FACE_ONLY", "S2").then((code)=>{
+ console.info("auth success");
+}).catch((code)=>{
+ console.error("auth fail, code = " + code);
+});
+```
+
+## AuthenticationResult(deprecated)
+
+> **NOTE**
+> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8).
+
+Enumerates the authentication results.
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+| Name | Default Value| Description |
+| ------------------ | ------ | -------------------------- |
+| NO_SUPPORT | -1 | The device does not support the current authentication mode.|
+| SUCCESS | 0 | The authentication is successful. |
+| COMPARE_FAILURE | 1 | The feature comparison failed. |
+| CANCELED | 2 | The authentication was canceled by the user. |
+| TIMEOUT | 3 | The authentication has timed out. |
+| CAMERA_FAIL | 4 | The camera failed to start. |
+| BUSY | 5 | The authentication service is not available. Try again later. |
+| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. |
+| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.|
+| NOT_ENROLLED | 8 | No authentication credential is registered. |
+| GENERAL_ERROR | 100 | Other errors. |
diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md
index 9d801b2503cc4225907879d5eba7596c120db3b6..5be81d94fdc351f56722eb6a106ca5c0157b658e 100644
--- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md
+++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md
@@ -1,8 +1,10 @@
# Popup Control
+The popup attribute defines the popup displayed when a component is clicked.
->  **NOTE**
-> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
+> **NOTE**
+>
+> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
@@ -13,48 +15,52 @@ None
## Attributes
-| Name | Type | Default Value | Description |
+| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
-| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the current popup. |
+| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the popup.|
-- PopupOptions attributes
- | Name | Type | Mandatory | Default Value | Description |
+- PopupOptions
+ | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | message | string | Yes | - | Content of the popup message. |
- | placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. |
- | primaryButton | {
value: string,
action: () => void
} | No | - | First button.
**value**: text of the primary button in the popup.
**action**: callback function for clicking the primary button. |
- | secondaryButton | {
value: string,
action: () => void
} | No | - | Second button.
**value**: text of the secondary button in the popup.
**action**: callback function for clicking the secondary button. |
- | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
+ | message | string | Yes| - | Content of the popup message.|
+ | placementOnTop | boolean | No| false | Whether to display the popup above the component. The default value is **false**.|
+ | primaryButton | {
value: string,
action: () => void
} | No| - | Primary button.
**value**: text of the primary button in the popup.
**action**: callback for clicking the primary button.|
+ | secondaryButton | {
value: string,
action: () => void
} | No| - | Secondary button.
**value**: text of the secondary button in the popup.
**action**: callback for clicking the secondary button.|
+ | onStateChange | (isVisible: boolean) => void | No| - | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
- CustomPopupOptions8+
- | Name | Type | Mandatory | Default Value | Description |
+ | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | builder | () => any | Yes | - | Builder of the tooltip content. |
- | placement | Placement | No | Placement.Bottom | Preferred position of the tooltip component. If the set position is insufficient for holding the component, it will be automatically adjusted. |
- | maskColor | [Color](../../ui/ts-types.md) | No | - | Color of the tooltip mask. |
- | popupColor | [Color](../../ui/ts-types.md) | No | - | Color of the tooltip. |
- | enableArrow | boolean | No | true | Whether to display arrows. Arrows are displayed only for tooltips in the up and down directions. |
- | autoCancel | boolean | No | true | Whether to automatically close the tooltip when an operation is performed on the page. |
- | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
+ | builder | () => any | Yes| - | Builder of the popup content.|
+ | placement | Placement | No| Placement.Bottom | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.|
+ | maskColor | [ResourceColor](../../ui/ts-types.md) | No| - | Color of the popup mask.|
+ | popupColor | [ResourceColor](../../ui/ts-types.md) | No| - | Color of the popup.|
+ | enableArrow | boolean | No| true | Whether to display an arrow.
Since API version 9, if the location set for the arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.|
+ | autoCancel | boolean | No| true | Whether to automatically close the popup when an operation is performed on the page.|
+ | onStateChange | (isVisible: boolean) => void | No| - | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
- Placement8+ enums
- | Name | Description |
+ | Name| Description|
| -------- | -------- |
- | Left | The tooltip is on the left of the component. |
- | Right | The tooltip is on the right of the component. |
- | Top | The tooltip is on the top of the component. |
- | Bottom | The tooltip is at the bottom of the component. |
- | TopLeft | The tooltip is in the upper left corner of the component. |
- | TopRight | The tooltip is in the upper right corner of the component. |
- | BottomLeft | The tooltip is in the lower left corner of the component. |
- | BottomRight | The tooltip is in the lower right corner of the component. |
+ | Left | The popup is on the left of the component, vertically aligned with the component on the left.|
+ | Right | The popup is on the right of the component, vertically aligned with the component on the right.|
+ | Top | The popup is at the top of the component, horizontally aligned with the component at the top.|
+ | Bottom | The popup is at the bottom of the component, horizontally aligned with the component at the bottom.|
+ | TopLeft | The popup is at the top of the component and, since API version 9, aligned with the left of the component.|
+ | TopRight | The popup is at the top of the component and, since API version 9, aligned with the right of the component.|
+ | BottomLeft | The popup is at the bottom of the component and, since API version 9, aligned with the left of the component.|
+ | BottomRight | The popup is at the bottom of the component and, since API version 9, aligned with the right of the component.|
+ | LeftTop9+ | The popup is on the left of the component and aligned with the top of the component.|
+ | LeftBottom9+ | The popup is on the left of the component and aligned with the bottom of the component.|
+ | RightTop9+ | The popup is on the right of the component and aligned with the top of the component.|
+ | RightBottom9+ | The popup is on the right of the component and aligned with the bottom of the component.|
## Example
-
-```
+```ts
+// xxx.ets
@Entry
@Component
struct PopupExample {
@@ -65,7 +71,7 @@ struct PopupExample {
@Builder popupBuilder() {
Row({ space: 2 }) {
Image('/resource/ic_public_thumbsup.svg').width(24).height(24).margin({ left: -5 })
- Text('Custom Popup').fontSize(12)
+ Text('Custom Popup').fontSize(10)
}.width(100).height(50).backgroundColor(Color.White)
}
diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md
index 2e706b7617e79deb17393ebd3ac1a86e42374e80..f6ef8fc8ba202071cfa01c1f559e35d4654e5230 100644
--- a/en/application-dev/security/accesstoken-guidelines.md
+++ b/en/application-dev/security/accesstoken-guidelines.md
@@ -24,13 +24,13 @@ The table below lists only the API used in this guide. For more information, see
## Declaring Permissions
-Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and Stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md).
+Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md).
Note that the app bundle structure and configuration file vary with the ability framework model.
### FA Model
-For the apps based on the FA model, declare the permissions in the **config.json** file.
+For the apps based on the FA model, declare the required permissions in the **config.json** file.
**Description of config.json**
@@ -75,7 +75,7 @@ For the apps based on the FA model, declare the permissions in the **config.json
### Stage Model
-For the apps based on the stage model, declare the permissions in the **module.json5** file.
+For the apps based on the stage model, declare the required permissions in the **module.json5** file.
**Example**
diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md
index 179073eec8928e709c45fc558344a1fef6898085..9578c8d43b2a216171ec36c2f5056600d4e3ab9f 100644
--- a/en/application-dev/security/permission-list.md
+++ b/en/application-dev/security/permission-list.md
@@ -97,7 +97,7 @@ For details about permission usage examples, see [Access Control Development](ac
| ohos.permission.EDM_MANAGE_DATETIME | normal | system_grant | FALSE | Allows the device administrator app to set the system time. |
| ohos.permission.NFC_TAG | normal | system_grant | FALSE | Allows an app to read NFC tag information. |
| ohos.permission.NFC_CARD_EMULATION | normal | system_grant | FALSE | Allows an app to implement card emulation. |
-| ohos.permission.PERMISSION_USED_STATS | system_core | system_grant | TRUE | Allows a system application to access the permission usage records. |
+| ohos.permission.PERMISSION_USED_STATS | system_basic | system_grant | TRUE | Allows a system application to access the permission usage records. |
| ohos.permission.NOTIFICATION_AGENT_CONTROLLER | system_core | system_grant | TRUE | Allows an app to send agent-powered notifications. |
| ohos.permission.ANSWER_CALL | system_basic | user_grant | TRUE | Allows an app to answer incoming calls. |
| ohos.permission.READ_CALENDAR | normal | user_grant | TRUE | Allows an app to read calendar data. |
@@ -129,3 +129,5 @@ For details about permission usage examples, see [Access Control Development](ac
| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | Allows an app to query the unique identifier of a device. |
| ohos.permission.DUMP | system_core | system_grant | TRUE | Allows the basic system information and SA service information to be exported. |
| ohos.permission.DISTRIBUTED_SOFTBUS_CENTER | system_basic | system_grant | FALSE | Allows networking between different devices. |
+| ohos.permission.ACCESS_DLP_FILE | system_core | system_grant | TRUE | Allows configuration and management of the permissions on .dlp files. |
+| ohos.permission.PROVISIONING_MESSAGE | system_core | system_grant | TRUE | Allows activiation of the Super Device Manager application. |
diff --git a/en/contribute/documentation-contribution.md b/en/contribute/documentation-contribution.md
index 8a5eb74e52b929e155418875cef25dfde9ebdc15..430587fe0ffa3386cf17d64f49af4f9d7f1e2bd4 100755
--- a/en/contribute/documentation-contribution.md
+++ b/en/contribute/documentation-contribution.md
@@ -17,7 +17,7 @@ OpenHarmony has the right to modify the adopted content according to the communi
[Creative Commons License version 4.0](https://creativecommons.org/licenses/by/4.0/legalcode)
-## Contribution Methods
+## Contribution Methods
### Submitting Issues for Existing Documents
@@ -65,7 +65,7 @@ You are welcome to contribute documents to the release. For details, see [Writin
You are welcome to share your experience and expertise with other developers to help them get started. For example, you can contribute tutorials and FAQs by using the following templates:
-- [Tutorial Template](template/tutorial-template.md). You can contribute tutorials in the `contribute/tutorial` folder.
-- [FAQ Template](template/faq-template.md). You can contribute FAQs in the `contribute/faqs` folder.
+- [Tutorial Template](https://gitee.com/openharmony/docs/blob/master/en/contribute/template/tutorial-template.md). You can contribute tutorials in the `contribute/tutorial` folder.
+- [FAQ Template](https://gitee.com/openharmony/docs/blob/master/en/contribute/template/faq-template.md). You can contribute FAQs in the `contribute/faqs` folder.
More writing templates are available in the **contribute** folder in the **Docs** repository.
diff --git a/en/contribute/template/concept-overview-template.md b/en/contribute/template/concept-overview-template.md
deleted file mode 100644
index 76b46ec93252db454751976d43397c821ea20f4e..0000000000000000000000000000000000000000
--- a/en/contribute/template/concept-overview-template.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Overview Template
-
-## Basic Concepts
-
-***[Writing Requirements]***
-
-*Mandatory. Describe basic concepts related to a development task to help developers better understand the task. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Common concepts in the industry are not described.| |
-| Common terms in the industry, rather than internal terms, are used.| |
-
-
-***[Example]***
-
-
-The XX system provides the audio module for your application to implement audio-related features, including audio playback, recording, and volume management.
-
-
-It is considered good practice that you understand the following concepts before starting application development:
-
-
-- Sampling
- Sampling is a process where analog signals are converted into digital signals that can be represented by 0101.
-
-- Sampling rate
- Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
-
-- Channel
- Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
-
-- Audio frame
- Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
-
-
-## Working Principles
-
-***[Writing Requirements]***
-
-*Optional. You can delete this section if the working principles are simple and the basic concepts in the **Overview** section are enough for understanding.*
-
-*Describe the implementation principles, for example, the time for calling the APIs and triggering callbacks related to key steps, to help developers better understand the basic operation principles, carry out development tasks, and locate problems.*
-
-*The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Only principles related to the development task are described.| |
-| Supplementary graphics are used, such as sequence diagrams and flowcharts. The text description is consistent with the figure description.| |
-
-***[Example 1]***
-
-- Semaphore initialization: The system allocates memory for the semaphores configured (the value of *N* can be configured by users and is limited by the memory), initializes all semaphores to be unused semaphores, and adds them to a linked list for the system to use.
-
-- Semaphore creation: The system obtains a semaphore from the linked list of unused semaphores and assigns an initial value to the semaphore.
-
-- Semaphore request: If the counter value is greater than 0, the system allocates a semaphore, decreases the value by 1, and returns a success message. Otherwise, the system blocks the task and adds the task to the end of a task queue waiting for semaphores. The wait timeout period can be set.
-
-- When a semaphore is released, if there is no task waiting for it, the counter is increased by 1. Otherwise, the first task in the wait queue is woken up.
-
-- Semaphore deletion: The system sets a semaphore in use to the unused state and inserts it to the linked list of unused semaphores.
-
-- Semaphore allows only a specified number of tasks to access a shared resource at a time. When the number of tasks accessing the resource reaches the limit, other tasks will be blocked until the semaphore is released.
-
-
-***[Example 2]***
-
-**Working Principles of Mutexes**
-
-In a multi-task environment, multiple tasks may access the same shared resource. However, certain shared resources are not shared, and can only be accessed exclusively by tasks. A mutex can be used to address this issue.
-
-When non-shared resources are accessed by a task, the mutex is locked. Other tasks will be blocked until the mutex is released by the task. The mutex allows only one task to access the shared resources at a time, ensuring integrity of operations on the shared resources.
-
-
-
-## Limitations and Constraints
-
-***[Writing Requirements]***
-
-*Mandatory. Describe the constraints of the development task and the negative impact of the constraints, including but not limited to the following:*
-
-- ***Function Limitations***
- - *Application scope of the function (specify scenarios that are not supported)*
- - *Specification limitations*
-
-- ***Operation Limitations***
-
- - *Operations on known issues*
- - *Potentially risky operations (such as performance deterioration)*
- - *Operations that may cause performance deterioration*
-
-*The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| The function limitations or operation restrictions are clearly specified.| |
-| Only constraints that affect task development or user experience are described.| |
-| Operations that are prone to errors are described in the procedure but not described in this section.| |
-
-***[Example]***
-
-**Limitations and Constraints on Mutexes:**
-
-- Two tasks cannot lock the same mutex. If a task attempts to lock a mutex held by another task, the task will be blocked until the mutex is unlocked.
-
-- Mutexes cannot be used in the interrupt service program.
-
-- When using the LiteOS-A kernel, the xx system must ensure real-time task scheduling and avoid long-time task blocking. Therefore, a mutex must be released as soon as possible.
-
-- When a mutex is held by a task, the task priority cannot be changed by using APIs such as **LOS_TaskPriSet**.
diff --git a/en/contribute/template/figures/how-distributedobject-works.png b/en/contribute/template/figures/how-distributedobject-works.png
new file mode 100644
index 0000000000000000000000000000000000000000..33785a3fd4c66624b298b1aa36959dbf635d2343
Binary files /dev/null and b/en/contribute/template/figures/how-distributedobject-works.png differ
diff --git a/en/contribute/template/guide-template.md b/en/contribute/template/guide-template.md
index 90b5133d0817050586903c8514ddb5e2b838a324..c497b984ff363a56376a5e1d470a177d9e540003 100644
--- a/en/contribute/template/guide-template.md
+++ b/en/contribute/template/guide-template.md
@@ -1,158 +1,405 @@
-# Development Guidelines
+# Development Guide Writing Template
-***[Writing Requirements]***
+> **NOTE**
+>
+> *1. This template provides the recommended development guide document framework and writing instructions for typical knowledge points. In your writing, complete the development task scenario analysis and development guide outline design based on the specific **solution/feature/function/module**, and then write the content based on this template.*
+>
+> *2. Do not add any content between level-1 title (marked with #) and level-2 title (marked with ##).*
+>
+> *3. Delete all the writing instructions in italics from your formal documents.*
+
+
+## *Example* Overview
+
+*Mandatory. Based on the scenario division of the solution/feature/function/module, you need to provide either "Example Overview" or "Example Task Scenario Overview", or both of them.*
+
+*1. "Example Overview" provides an overview that is common to all task scenarios of this solution/feature/function/module and that developers need to understand. If there is nothing in common, delete it.*
+
+*2. "Example Task Scenario Overview" describes the contents directly related to a task scenario. The knowledge points and key writing points are the same as those in "Example Overview". In this section, you need to introduce this specific task scenario and describe basic concepts, working principles, constraints, and samples that are directly related to the task scenario. If there is no specific task scenario, delete it.*
+
+***[General Instructions for Writing the Development Guide]***
+
+***1. Target audience**: internal and external developers (including product managers). Guidelines for UX designers are usually carried by UX design specifications and are not covered in the development guide. If UX design specifications need to be mentioned in the development guide, use hyperlinks.*
+
+***2. Content positioning**: Introduce what the solution/feature/function/module is, why it is required, and how to design, develop, and release related applications/devices. The development guide aims to help developers learn necessary knowledge and achieve specified task objectives in actual development activities.*
-*Mandatory. Describe how a developer completes tasks in a specific scenario. Include one scenario in each section. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
+***3. User-oriented****: Always provide developer-concerned, perceptible, and useful content from the perspective of developers.*
+***4. Task-oriented****: Focus on actual tasks of developers, and provide complete, correct guidance that is easy to follow.*
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Each section covers only one scenario. If there are multiple scenarios, provide development guidelines for each scenario in separate sections. For example, you can use the following sections in **Audio**: **Development Guidelines on Audio Playback**, **Development Guidelines on Volume Management**, and **Development Guidelines on Sound Playback**.| |
-| Use verbs + nouns to describe task operations in titles.| |
+*5. This template only provides the basic document framework. You can adjust the content based on the actual requirements.*
-## When to Use
+### Introduction
+
+*Mandatory.*
+
+***[Developers' Concerns]***
+
+*What is the solution/feature/function/module (definition)? What problems can it solve or what benefits can it bring (purpose/customer benefits - why)? *
+
+***[Key Writing Points]***
+
+- *Provide easy-to-understand and scenario-specific descriptions. Refer to the SCQA method below to introduce the scenarios and characteristics of the solution/feature/function/module.*
+ - *S: situation. Introduce a familiar scenario.*
+ - *C: complication. Describe the conflict between the situation and requirement.*
+ - *Q: question. Ask a question. What can I do in such a case?*
+ - *A: answer. Describe the solution.*
+
+- *Visualize abstract concepts. You can provide content from the perspective of consumers for better understanding, for example, scenario effect in UX.*
***[Writing Requirements]***
-*Mandatory. Describe in which scenario, what problem is solved, and what the final effect is. Use the SCQA method.*
+- *Provide clear content. Avoid vague, obscure, and ambiguous expressions.*
+
+- *Use only necessary terms, acronyms, abbreviations, and proper nouns, and provide explanations or links to the glossary.*
+
+- *Use consistent terms, acronyms, abbreviations, and proper nouns throughout the document.*
+
-- *S: situation. Introduce a familiar scenario.*
+### Basic Concepts
-- *C: complication. Describe the conflict between the situation and requirement.*
+*Optional. Describe the basic concepts that are common to all task scenarios.*
-- *Q: question. Ask a question. What can I do in such a case?*
+***[Developers' Concerns]***
-- *A: answer. Describe the solution.*
+*What are the unique concepts that I need to know when using the solution/feature/function/module?*
-*The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
+***[Key Writing Points]***
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Clearly describe the background, what operations are done when and where, what problems are solved, and what benefits are delivered.| |
+- *Provide only the concepts that are mandatory in development tasks.*
+
+- *Describe here concepts used in multiple chapters such as the operation mechanism, restrictions, and development process. If a concept is used only in a chapter, describe the concept in that chapter only.*
+
+- *Do not describe common concepts in the industry. Use common terms in the industry instead of jargon.*
+
+- *If there are logical relationships between concepts, you are advised to use figures to describe the relationships.*
+
+***[Writing Requirements]***
+
+- *Provide clear content. Avoid vague, obscure, and ambiguous expressions.*
+
+- *Use only necessary terms, acronyms, abbreviations, and proper nouns, and provide explanations or links to the glossary.*
+
+- *Use consistent terms, acronyms, abbreviations, and proper nouns throughout the document.*
***[Example]***
-You can use APIs described in this section to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks.
+Before developing relational databases, you must understand the following basic concepts:
+
+- **RDB**
+
+A type of database based on the relational model of data. The RDB stores data in rows and columns. An RDB is also called RDB store.
+
+- **Predicate**
+
+ Property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions.
+
+- **Result set**
+
+ A set of query results used to access the data. You can access the required data in a result set in flexible modes.
+
+
+### Working Principles
+
+*Optional. Describe the working principles that are common to all task scenarios.*
+
+***[Developers' Concerns]***
+
+*How does the solution/feature/function/module work? What are the API calling and triggering time of key steps? I want to understand its principles for better use and debugging.*
+***[Key Writing Points]***
-## Available APIs
+- *If the principle is simple and can be understood from the content under "Basic Concepts", do not provide this section.*
+
+- *Describe only the mechanisms and principles that are visible in the development tasks (use or access). Do not provide internal implementation that is invisible to developers.*
+
+- *If necessary, use sequence diagrams and flowcharts. Ensure that the text description matches the figure description.*
+
+- *Be careful not to disclose internal information.*
***[Writing Requirements]***
-*Mandatory. Describe APIs involved in the development guideline to help developers have a general understanding of the APIs, thereby improving development efficiency. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
+- *Provide clear content. Avoid vague, obscure, and ambiguous expressions.*
+
+- *Use only necessary terms, acronyms, abbreviations, and proper nouns, and provide explanations or links to the glossary.*
+
+- *Use consistent terms, acronyms, abbreviations, and proper nouns throughout the document.*
+
+***[Example]***
+
+The distributed data objects are encapsulated into JS objects in distributed in-memory databases, which allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization.
+
+**Figure 1** Working mechanism
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Include only APIs relevant to the development task.| |
-| If there are more than 10 APIs, you can provide only main APIs.| |
+
+
+
+### Constraints
+
+*Optional. Describe constraints that are common to all task scenarios.*
+
+***[Developers' Concerns]***
+
+*What are the constraints for using the solution/feature/function/module? How well is the solution/feature/function/module implemented? Can it meet my requirements?*
+
+***[Key Writing Points]***
+
+- *Describe perceptible constraints that affect development activities, including but not limited to the following:*
+ - ***Function constraints***
+ - *Application scope of the solution/feature/function/module (Specify scenarios that are not supported.)*
+ - *Specification constraints*
+ - ***Operation constraints***
+ - *Operations on known issues*
+ - *Potentially risky operations (such as performance deterioration)*
+
+- *Describe operations that are prone to errors in the procedure, but not in this section.*
***[Example]***
-The **AudioRenderer** class provides open audio playback capabilities. For details about the APIs, see the API reference.
+- Data synchronization can be implemented across devices only for the applications with the same bundleName.
+
+- Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects.
-**Table 1** Audio playback APIs
+- The maximum size of a distributed data object is 500 KB.
-| API| Description|
-| -------- | -------- |
-| AudioRenderer(AudioRendererInfo audioRendererInfo, PlayMode pm) throws IllegalArgumentException | A constructor used to create an **AudioRenderer** instance based on the specified playback parameters, the specified playback mode, and the default playback device.|
-| AudioRenderer(AudioRendererInfo audioRendererInfo, PlayMode pm, AudioDeviceDescriptor outputDevice) throws IllegalArgumentException | A constructor used to create an **AudioRenderer** instance based on the specified playback parameters, playback mode, and playback device.|
-| boolean play() | Plays audio streams.|
-| boolean write(byte[] data, int offset, int size) | Writes audio data in the specified byte array into an audio receiver for playback.|
+### Samples
-## How to Develop
+*Optional. Provide samples that are common to all task scenarios.*
+
+***[Developers' Concerns]***
+
+*What sample code, codelabs, and demo projects are available?*
+
+***[Key Writing Points]***
+
+*Provide links (generally Gitee links) to the released sample code, codelabs, and demo projects. Do not include project packages into the document as an attachment.*
+
+***[Example]***
+
+The following sample is provided to help you better understand how to develop abilities:
+
+- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
+
+
+## Setting Up the Environment
+
+*Optional.*
+
+*Based on the analysis and breakdown of a specific task scenario, you can place the environment setup content under "Prerequisites" or "Preparations" and close to the "How to Develop" of the specific scenario.*
+
+*Specify how to prepare the development environment, including software and hardware configuration requirements, tool requirements, and device requirements.*
+
+*Delete this section if no special requirements are involved.*
+
+
+### Environment Requirements
***[Writing Requirements]***
- *Mandatory. Describe the overall process to help developers quickly complete the task. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| **Writing a Development Procedure**| |
-| Complete: All mandatory steps are provided.| |
-| Clear: The logic of the writing is clear and reasonable. The overview, preparations, and operations in the document are described by following certain logic, and the chapters are not broken or contradictory.| |
-| Sentence pattern for tasks: Use verbs + nouns to describe actions in titles or sentences.| |
-| Prevention in advance: Describe the restrictions, error-prone operations, and potential risks in advance. Use general icons and styles.| |
-| Clear steps-1: Describe the purpose of each step, no matter whether it is simple or not.| |
-| Clear steps-2: Specify the environment, tools, operations, and how-to.| |
-| If an operation is optional, specify the optional conditions.| |
-| After the development procedure is complete, specify the expected results.| |
-| **Writing a Code Segment**| |
-| If a code segment involves commands to be copied by developers, display the commands in editable mode, instead of using screenshots. Use code snippets to wrap the commands.| |
-| Highlight key code segments in blue (RGB: 0.0.255), and comment out key steps.| |
-| The code display meets the code indentation requirements.| |
-| If an API call is involved in a step, provide the API and its usage description or sample code. The code comes from specific instances.| |
+*Describe the software and hardware configurations required by the development environment so that developers can prepare the environment in advance. You can use subtitles if there is a large amount of content.*
***[Example]***
-1. Use **AudioStreamInfo.Builder** to create an **AudioStreamInfo** instance for audio stream parameters. The following example uses the default values of the input parameters for **AudioStreamInfo.Builder**. You need to set the parameters based on the audio stream specification.
- ```
- AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder()
- .sampleRate(AudioStreamInfo.SAMPLE_RATE_UNSPECIFIED)
- .audioStreamFlag(AudioStreamInfo.AudioStreamFlag.AUDIO_STREAM_FLAG_NONE)
- .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_INVALID)
- .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_INVALID)
- .streamUsage(AudioStreamInfo.StreamUsage.STREAM_USAGE_UNKNOWN)
- .build();
- ```
+The following table describes the environment configuration requirements specific to the Hi3861 development board.
+
+ **Table 1** Hi3861 development environment-specific requirements
+
+| Platform Type| Development Tool| Function| How to Obtain|
+| -------- | -------- | -------- | -------- |
+| Linux server| SCons3.0.4+ | Executes script compilation.| Internet|
+| Linux server| build-essential | Provides a basic software package for compilation and building.| Internet|
+
+
+### Setting Up the Environment
+
+***[Writing Requirements]***
+
+*Describe the procedure for setting up the development environment. If there is a large amount of content, use subtitles, for example, "Setting Up the Basic Build Environment" and "Setting Up the Compilation Tool Environment".*
+
+***[Example]***
+
+1. Start a Linux server.
- Example code for playing a PCM stream:
+2. Run the following command to install the tool installation package:
+
```
- AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder().sampleRate(44100)// 44.1 kHz
- .audioStreamFlag(AudioStreamInfo.AudioStreamFlag.AUDIO_STREAM_FLAG_MAY_DUCK)// Set audio ducking.
- .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT)//16-bit PCM
- .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_OUT_STEREO)// Set the dual output channel.
- .streamUsage(AudioStreamInfo.StreamUsage.STREAM_USAGE_MEDIA)// Set the stream to be used for media.
- .build();
+ xxxxx
```
-2. Build the playback parameter structure via **AudioRendererInfo** for the audio stream created in Step 1, and use **AudioRendererInfo.Builder** to create an instance. The following example uses the default parameter values of the **AudioRendererInfo.Builder** instance. You need to set the playback parameters based on the audio playback specification.
+
+3. Run the following command to check whether the tool is successfully installed.
+
```
- AudioRendererInfo audioRendererInfo = new AudioRendererInfo.Builder()
- .audioStreamInfo(audioStreamInfo)
- .audioStreamOutputFlag(AudioRendererInfo.AudioStreamOutputFlag.AUDIO_STREAM_OUTPUT_FLAG_NONE)
- .bufferSizeInBytes(0)
- .distributedDeviceId("")
- .isOffload(false)
- .sessionID(AudioRendererInfo.SESSION_ID_UNSPECIFIED)
- .build();
+ xxxxx
```
- Example code for playing a PCM stream:
- ```
- AudioRendererInfo audioRendererInfo = new AudioRendererInfo.Builder()
- .audioStreamInfo(audioStreamInfo)
- .audioStreamOutputFlag(AudioRendererInfo.AudioStreamOutputFlag.AUDIO_STREAM_OUTPUT_FLAG_DIRECT_PCM)// Set direct PCM output.
- .bufferSizeInBytes(100)
- .distributedDeviceId("E54***5E8")// Use distributed device E54***5E8 for playback.
- .isOffload(false)// Value false indicates that the audio stream is transmitted to the buffer on a segment-by-segment basis for several times and then played. Value true indicates that the audio stream is transmitted to the HAL layer at a time.
- .build();
- ```
-
-3. Specify the playback mode based on the audio stream to be played. The playback modes differ only in the data writing process. Create an **AudioRenderer** instance using a constructor that fits your need.
-4. After the playback task is complete, call the **release()** method on the **AudioRenderer** instance to release resources.
+### Verifying the Environment
+
+***[Writing Requirements]***
+
+*Optional. Provide the criteria for checking whether the environment is set up successfully. You can also provide the criteria along with the environment setup procedure, as provided in the preceding example.*
+
+
+## *Example Task Scenario* Development (Use a specific scenario name. If there is only one scenario, use the solution/feature/function/module name.)
+
+*Mandatory.*
+
+***[Developers' Concerns]***
+
+*How do I use or access the solution/feature/function/module?*
+
+***[Key Writing Points]***
+
+*Provide scenarios that are close to actual development scenarios.*
+
+- *Task scenarios are what developers need to use to achieve development objectives.*
+
+- *There can be one or more task scenarios. You can use multiple "Development Guidelines" sections. Follow the hierarchical logic when writing the guidelines, that is, a task scenario -> a subtask scenario -> task logic ("Development Process") -> operation procedure ("How to Develop").*
+
+### *Example Task Scenario* Overview
+
+*Based on the scenario division of the solution/feature/function/module, you can provide either "Example Task Scenario Overview" or "Example Overview", or both of them.*
+
+*1. "Example Overview" provides an overview that is common to all task scenarios of this solution/feature/function/module and that developers need to understand. If there is nothing in common, delete it.*
+
+*2. "Example Task Scenario Overview" describes the contents directly related to a task scenario. The knowledge points and key writing points are the same as those in "Example Overview". In this section, you need to introduce this specific task scenario and describe basic concepts, working principles, constraints, and samples that are directly related to the task scenario. If there is no specific task scenario, delete it.*
+
+### Development Process
+
+***[Key Writing Points]***
+
+- *Optional. If there are many development steps (five or more core operations) or complex logical relationships between steps, provide the development process so that developers can have a panoramic view of the operations to be performed.*
+
+- *Provide flowcharts and tables if necessary.*
-## (Optional) Commissioning and Verification
+### Available APIs
***[Writing Requirements]***
-*Optional. After the development is complete, perform commissioning and verification to ensure that the operation is successful. The operation procedure requirements are the same as those in **Development Guidelines**. Other specific writing requirements are as follows. After finishing the writing, check your content against these requirements one by one.*
+- *Optional. Describe the key APIs in the development steps and provide the API introduction, so that developers can have a general understanding of development.*
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Describe the final service commissioning process. The operation result of each step should be verified after the corresponding development task is complete.| |
-| Specify the criteria for development success.| |
+- *If there are more than 10 APIs, provide the main APIs only.*
+
+- *Ensure that the APIs and their functions of the corresponding version are supported when the document is released.*
+
+***[Example]***
+
+Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md).
+
+**Table 1** APIs for notification enabling
+
+| API | Description |
+| ------------------------------------------------------------ | ---------------- |
+| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.|
+| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. |
+
+
+### How to Develop
+
+***[Writing Requirements]***
+
+*Mandatory.*
+
+- *Completeness and Correctness*
+ - *Describe the complete development process (for example, steps related to the code, resources, third-party libraries, and application configuration files in the HAP) so that developers can correctly complete the development. Do not omit key configuration operations.*
+ - *Ensure that the code snippet provided in the document can be built with the context in DevEco Studio.*
+ - *Ensure that the complete sample code provided in the document can be run in DevEco Studio, and the execution result is the same as that described in the document.*
+
+- *Clarity*
+ - *Provide a clear execution owner (who), operation purpose (why), operation content (what/how), and scenario (when/where) for each step. Use imperative sentence to describe steps.*
+ - *Clearly provide the APIs (if involved) in steps, as well as their usage description and sample code.*
+ - *Provide development suggestions or precautions for key steps and sample code (comments for sample code).*
+ *Think about what questions may be raised when developers are performing the operations.* *These problems are obstacles to developers.* *Provide support information in the document to help them handle these obstacles.* *Examples of support information:*
+ - *Branch selection principle. Provide principles or suggestions for selecting branches and parameters.*
+
+ - *Necessary supplementary description. Describe possible special operations, required operation permissions, high efficiency skills, and concise and clear background knowledge.*
+
+ - *Precautions. Describe operations that may adversely affect other functions or system performance and reliability, and operations that may cause data loss or security problems.* *Provide this type of information in a style different from that of the body prior to the operation procedure.*
+
+ - *Error prevention/correction information. Provide guidance for preventing, locating, or rectifying typical problems that may occur in the development process.* *This type of information can be provided in "How to Develop" or "FAQs", depending on the content amount.*
+
+- *Standardization*
+ - *Provide both logically and syntactically correct sample code and write it in a standard manner. Anonymize sensitive information, such as mobile numbers, ID cards, and account names, for example, 186\*\*\*\*\*\*\*\*. Use private IP addresses or a corresponding format, for example, xx.xx.xx.xx and www.example.com, rather than real IP addresses and domain names.*
+ - *Provide code that complies with the code indentation requirements. Do not use the **Tab** key to indent code. Instead, use four spaces, to avoid incorrect display.*
+
+**[Example (Excerpt)]**
+
+1. Import the required modules.
+
+ ```javascript
+ import formBindingData from '@ohos.application.formBindingData'
+ import formInfo from '@ohos.application.formInfo'
+ import formProvider from '@ohos.application.formProvider'
+ ```
+
+2. Implement the lifecycle callbacks of **LifecycleForm**.
+
+ ```javascript
+ export default {
+ onCreate(want) {
+ console.log('FormAbility onCreate');
+ // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
+ let obj = {
+ "title": "titleOnCreate",
+ "detail": "detailOnCreate"
+ };
+ let formData = formBindingData.createFormBindingData(obj);
+ return formData;
+ },
+ onCastToNormal(formId) {
+ // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion.
+ console.log('FormAbility onCastToNormal');
+ },
+ }
+ ```
+
+
+### Verification
-## Development Example
***[Writing Requirements]***
-*Provide a complete sample, briefly describe the principle and implementation of the sample, and provide a link to the source code repository.*
+- *Optional. After the development is complete, provide a guide to check whether the operation is successful if there is an independent commissioning and verification operation. The operation procedure is the same as that described in "How to Develop."*
+
+- *Provide only the final service commissioning. You are advised to verify the operation result of each subtask after the development is complete.*
+
+
+## FAQs
+
+*Optional.*
+
+***[Developers' Concerns]***
+
+*What are the typical problems that may occur in the development process of the solution/feature/function/module? How do I locate and solve these problems?*
+
+***[Key Writing Points]***
+
+*Describe the problems that may occur during the development and the solutions to them.*
+
+- *Delete this section if there are no common problems.*
+
+- *It is recommended that common problems in each task scenario be described in a separate chapter. Common problems related to a single task scenario be described in the corresponding chapter.*
+
+
+
+### 1. XX problem (simple problem)
+
+XXX
+
+
+### 2. XX problem (complex problem)
+
+**Symptom**
+
+XXX
+
+**Possible Causes**
-The following sample is provided to help you better understand how to xx:
+XXX
-- xxx (A link to the source code repository)
+**Solution**
- This sample xxx.
+XXX
diff --git a/en/design/hdi-design-specifications.md b/en/design/hdi-design-specifications.md
index c2958495278c0cde9dc7c259fdba56ed56bef720..dcaf228795c5ffb81a5ddfc90a24aaaf9c7a8237 100644
--- a/en/design/hdi-design-specifications.md
+++ b/en/design/hdi-design-specifications.md
@@ -2,7 +2,7 @@
## Overview
-Hardware device interface (HDI) provides a set of interfaces that function as a bridge between a driver and a system service for data transmission. They have a direct impact on system efficiency, stability, compatibility, and reliability, as well as data accuracy and integrity. This document aims to standardize the design and development of OpenHarmony HDIs, thereby ensuring consistent styles and complete functionalities for the HDIs.
+Hardware device interface (HDI) provides a set of interfaces that function as a bridge between drivers and system services for data transmission. They have a direct impact on system efficiency, stability, compatibility, and reliability, as well as data accuracy and integrity. This document aims to standardize the design and development of OpenHarmony HDI interfaces, thereby ensuring consistent styles and complete functionalities for the interfaces.
This document is developed by the [driver SIG](https://gitee.com/openharmony/community/blob/master/sig/sig-driver/sig_driver.md) and approved by the [PMC](https://gitee.com/link?target=https%3A%2F%2Fwww.openharmony.cn%2Fcommunity%2Fpmc%2F). Any revision to this document must be reviewed by the driver SIG and approved by the PMC.
**Acronyms**
@@ -21,10 +21,10 @@ This document is developed by the [driver SIG](https://gitee.com/openharmony/com
**Note**: an explanation to a rule or rec
**Change History**
-
| Version | Change Description |
| --- | --------------------- |
| v1.0 Beta | This issue is the initial version. |
+| v1.0 | This issue is the official version. |
## Scope and Definition
@@ -35,19 +35,19 @@ Located between the system service layer and the device driver layer, HDI provid
## General Rules
-### HDI Version Control
+### Version Control
-The HDI version number must be in the format of `major.minor`, where the `major` version number must be an integer increased in ascending order and the `minor` version number is a one-digit integer.
+The HDI version number must be in the format of `major.minor`, where `major` must be an integer increased in ascending order and `minor` is a one-digit integer.
-- A change in the `major` version number indicates architecture adjustment or interface definition that is not backward compatible.
+- A change in `major` indicates architecture adjustment or interface definition that is not backward compatible.
-- A change in the `minor` version number indicates enhanced or extended interface definitions that are backward compatible.
+- A change in `minor` indicates enhanced or extended interface definitions that are backward compatible.
When `major` changes, `minor` is reset to `0`.
[Example]
-For released vibrator HDIs:
+For released vibrator interfaces:
```cpp
package ohos.hdi.vibrator.v1_0;
@@ -58,7 +58,7 @@ interface IVibrator {
}
```
-If the update to the existing HDIs does not affect version compatibility, for example, adding a function, adding an enum definition, or changing a variable name, change only the `minor`, for example, to `ohos.hdi.vibrator.v1_1`, as follows:
+If the update to the existing interfaces does not affect version compatibility, for example, adding a function, adding an enum definition, or changing a variable name, change only `minor`, for example, to `ohos.hdi.vibrator.v1_1`, as follows:
```cpp
package ohos.hdi.vibrator.v1_1;
@@ -80,20 +80,21 @@ interface IVibrator {
}
```
-### HDI Review and Control
+### Review and Control
-HDIs are provided to implement upper-layer system service requirements and perform hardware operations (such as initialization). New and updated HDIs must be fully reviewed and strictly controlled. Only HDIs that meet universal requirements can be added.
+HDI interfaces are provided to implement upper-layer system service requirements and perform hardware operations (such as initialization). New and updated interfaces must be fully reviewed and strictly controlled. Only interfaces that meet universal requirements can be added.
-Table 1 HDI review and control roles
+Table 1 Interface review and control roles
-| **Role**| **Responsibility** |
-| ------------ | ------------------------------------------------------------ |
-| Contributor | Write HDI code and submit the code and design documents for review. |
-| Committer | Review and approve the HDI code, and submit HDIs to the domain SIG for further review. |
-| Domain SIG | Comment on the commits of new HDI code. Review and approve new HDIs, and submit the updated HDIs to the driver SIG for further review. |
-| Driver SIG | Review and approve the updated HDIs. |
+| **Role** | **Responsibility** |
+| ----------- | ------------------------------------------------ |
+| Contributor | Write HDI code and submit the code and design documents for review. |
+| Committer | Review the HDI code, and submit the code to the domain SIG for further review. |
+| Domain SIG | Review the new or updated HDI code.|
+| Driver SIG | Review the new or updated HDI code. |
+| PMC | Revise and publish this design specifications. |
-#### HDI Release
+### Release
- HDI review process
@@ -101,10 +102,10 @@ Table 1 HDI review and control roles
The main process is as follows:
- 1. The contributor commits code and initiates a review. In addition to the code of new or updated HDIs, the contributor must provide information about the HDI requirement source, usage scenario, permission design, and privacy protection design. For details, see "Review application composites" below. To increase the review efficiency, the contributor can email the design documents to the committer, domain SIG, and driver SIG before submitting the review application.
- 2. The committer reviews the code and HDIs.
- 3. The domain SIG reviews the new or updated HDIs.
- 4. The driver SIG reviews and approves the new or updated HDIs.
+ 1. The contributor commits code and initiates a review. In addition to the code of new or updated HDI interfaces, the contributor must provide information about the HDI requirement source, usage scenario, permission design, and privacy protection design. For details, see "Review application composites" below. To increase the review efficiency, the contributor can email the design documents to the committer, domain SIG, and driver SIG before submitting the review application.
+ 2. The committer reviews the code and HDI interfaces.
+ 3. The domain SIG reviews the new or updated HDI interfaces.
+ 4. The driver SIG reviews and approves the new or updated HDI interfaces.
5. The review is complete, and the code is merged.
- Review application composites
@@ -115,9 +116,9 @@ Table 1 HDI review and control roles
- **HDI version differences, with a clear addition or change scope**
- - Complete interface context, which must be provided in the design document to specify when and how to use each HDI
+ - Complete interface context, which must be provided in the design document to specify when and how to use each interface
- - Resource status transition diagram in the design document for resource-oriented HDIs
+ - Resource status transition diagram in the design document for resource-oriented interfaces
- Compliance with the HDI design constraints proposed in this document
@@ -125,13 +126,13 @@ Table 1 HDI review and control roles
1. Change `major` for any release that is incompatible with earlier versions.
- 2. Change `minor` for any HDI released for function extension.
+ 2. Change `minor` for any interface released for function extension.
- 3. To deprecate any released HDI:
+ 3. To deprecate any released interface:
- The `deprecated` flag must be provided.
- - The deprecated HDIs must be retained in at least four OpenHarmony HDI versions.
+ - The deprecated interfaces must be retained in at least four OpenHarmony HDI versions.
## HDI Design Constraints
@@ -143,7 +144,7 @@ Multiple nouns with similar semantic meanings are not allowed to represent the s
#### [Rule] Keep the parameter sequence consistent.
-The sequence of a parameter or parameter group in multiple HDIs must be the same.
+The sequence of a parameter or parameter group in multiple interfaces must be the same.
For object-oriented C programming, place the interface object as the first parameter by convention.
@@ -239,7 +240,7 @@ Camel case is the practice of writing words without spaces. It indicates the sep
#### [Rule] Follow the single responsibility principle.
-The functionalities of each HDI must be stable and clear, and the trigger source of interface changes must be unique.
+The functionalities of each interface must be stable and clear, and the trigger source of interface changes must be unique.
[Example]
@@ -271,7 +272,7 @@ When defining an interface parameter, consider whether to pass the parameter sep
If no, pass the parameter separately.
-3. Does a parameter group occur in multiple HDIs?
+3. Does a parameter group occur in multiple interfaces?
If yes, you can pass these parameters as a struct. In this case, you also need to consider whether these parameter groups are cohesive.
@@ -292,9 +293,9 @@ struct AudioSampleAttributes
};
```
-#### [Rule] Make HDIs of different device types independent from each other.
+#### [Rule] Make interfaces of different device types independent from each other.
-HDIs are managed by driver type, such as `Camera`, `Input`, `Display`, `Audio`, `Sensor`, and `Storage`. HDIs of different device types should not depend on each other. It is recommended that common capabilities that may be used by more than two types of driver modules be abstracted as common interfaces and archived to the common interface capability library for management.
+Interfaces are managed by driver type, such as `Camera`, `Input`, `Display`, `Audio`, `Sensor`, and `Storage`. Interfaces of different device types should not depend on each other. It is recommended that common capabilities that may be used by more than two types of driver modules be abstracted as common interfaces and archived to the common interface capability library for management.
[Exceptions]
@@ -373,7 +374,7 @@ The correct practice is to copy the data to the memory managed by the service be
#### [Rule] Consider reentrancy.
-HDIs often need to support multiple clients, and a single client may have concurrent requests. Therefore, you must consider reentrancy during HDI design. To ensure correct processing of reentrant interfaces, use locks or semaphores to protect critical resources.
+Interfaces often need to support multiple clients, and a single client may have concurrent requests. Therefore, you must consider reentrancy during HDI design. To ensure correct processing of reentrant interfaces, use locks or semaphores to protect critical resources.
[Example]
@@ -399,28 +400,28 @@ The correct practice is to design and implement the callback interface using a c
### Compatibility
-#### [Rule] Verify the version number before the client calls an HDI.
+#### [Rule] Verify the version number before the client calls an interface.
-Due to the independent component update policy, the version number of an HDI on the client may be different from that on the server. This requires the client to verify the version number on the server and use the matching version to call the HDI on the server.
+Due to the independent component update policy, the version number of an interface on the client may be different from that on the server. This requires the client to verify the version number on the server and use the matching version to call the interface on the server.
[Example]
-Assume that the TP module provides HDIs of versions 1.0 and 1.1. The later version has new interfaces. The components on the client have updated to 1.1, and the server still uses 1.0. If the client directly calls an interface of 1.1 on the server, an error may occur. Instead, the client must use the service version query interface to check the server version. If the server version is 1.0, the client must use the HDI of 1.0 to call the server.
+Assume that the TP module provides interfaces of versions 1.0 and 1.1. The later version has new interfaces. The components on the client have updated to 1.1, and the server still uses 1.0. If the client directly calls an interface of 1.1 on the server, an error may occur. Instead, the client must use the service version query interface to check the server version. If the server version is 1.0, the client must use the interface of 1.0 to call the server.
-#### [Rule] Release HDIs in .idl format.
+#### [Rule] Release HDI interfaces in .idl format.
-Currently, Unix-like drivers use virtual file system (VFS) interfaces to expose internal interfaces. The user mode and kernel mode communicate with each other using system calls. They are packed in different images, and two sets of interfaces are maintained separately. To ensure the consistency of the interface definition and parameter format between the two and consider the design objective of cross-kernel hardware driver foundation (HDF) deployment, release HDIs in .idl format and use a tool to generate interfaces of the target form. In addition, the user-mode caller is not allowed to operate the driver VFS interfaces through the file interface. This causes the framework to strongly depend on the kernel and violates the principle of depending on the interface instead of the implementation.
+Currently, Unix-like drivers use virtual file system (VFS) interfaces to expose internal interfaces. The user mode and kernel mode communicate with each other using system calls. They are packed in different images, and two sets of interfaces are maintained separately. To ensure the consistency of the interface definition and parameter format between the two and consider the design objective of cross-kernel hardware driver foundation (HDF) deployment, release interfaces in .idl format and use a tool to generate interfaces of the target form. In addition, the user-mode caller is not allowed to operate the driver VFS interfaces through the file interface. This causes the framework to strongly depend on the kernel and violates the principle of depending on the interface instead of the implementation.
-Recommended practice: The driver provides HDIs in .idl format and encapsulates the access to the kernel device in the HDI implementation.
+Recommended practice: The driver provides interfaces in .idl format and encapsulates the access to the kernel device in the interface implementation.
[Example]
-An input device provides query interfaces for attributes such as the device type and data precision. The input service should not directly access the VFS interface created by the kernel in open-ioctl mode. Instead, the input driver should provide an HDI to abstract the input device as an object. Then the input service calls this HDI to implement the required functionalities.
+An input device provides query interfaces for attributes such as the device type and data precision. The input service should not directly access the VFS interface created by the kernel in open-ioctl mode. Instead, the input driver should provide an interface to abstract the input device as an object. Then the input service calls this interface to implement the required functionalities.
### Documentation
-#### [Rule] Release HDIs in .idl format.
-To ensure interface compatibility and consistency, release HDIs in .idl format. It is prohibited to directly release interfaces in C/C++ header files.
+#### [Rule] Release HDI interfaces in .idl format.
+To ensure interface compatibility and consistency, release interfaces in .idl format. It is prohibited to directly release interfaces in C/C++ header files.
#### [Rule] Provide an interface description during interface release.
@@ -442,7 +443,7 @@ GetExecutorInfo([out] struct ExecutorInfo executorInfo);
### Programming Languages
-To ensure data interworking between HDIs implemented in different programming languages, follow the restrictions below when using data types in the HDI description.
+To ensure data interworking between interfaces implemented in different programming languages, follow the restrictions below when using data types in the interface description.
#### Constraints on using basic data types
@@ -470,7 +471,7 @@ To ensure data interworking between HDIs implemented in different programming la
#### Constraints on Using Array Types
-| IDL Array Data Type| C++ Data Type | C Data Type |
+| IDL Array Data Type | C++ Data Type | C Data Type |
| --------- | -------------- | ----------- |
| T[] | std::vector | T*,int size |
@@ -480,7 +481,3 @@ To ensure data interworking between HDIs implemented in different programming la
| ------- | ------- | ------ |
| struct | struct | struct |
| enum | enum | enum |
-
-
-## Supplementary Notes
-The beta period of this document is one month from the release date. During this period, your comments are well welcome.
diff --git a/en/device-dev/driver/driver-peripherals-lcd-des.md b/en/device-dev/driver/driver-peripherals-lcd-des.md
index 06941d7c81bcd714357cb6a9e5e22997aa91a2ad..d5ba25a559c9c255a829ac083e869c0b28db9b00 100644
--- a/en/device-dev/driver/driver-peripherals-lcd-des.md
+++ b/en/device-dev/driver/driver-peripherals-lcd-des.md
@@ -319,7 +319,7 @@ static struct PanelInfo g_panelInfo = {
.vsw = VERTICAL_SYNC_WIDTH, /* vertical sync width */
.frameRate = FRAME_RATE, /* frame rate */
.intfType = MIPI_DSI, /* panel interface type */
- .intfSync = OUTPUT_USER, /* output timming type */
+ .intfSync = OUTPUT_USER, /* output timing type */
/* MIPI configuration */
.mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT },
/* backlight config info */
diff --git a/en/device-dev/driver/driver-platform-regulator-develop.md b/en/device-dev/driver/driver-platform-regulator-develop.md
index 960c3b88bfaf225ec1f911a22be8ffad0b25037b..022df8b238b518c4560789843391f751b1fabb5a 100644
--- a/en/device-dev/driver/driver-platform-regulator-develop.md
+++ b/en/device-dev/driver/driver-platform-regulator-develop.md
@@ -5,23 +5,18 @@
### Regulator
-The regulator module controls the voltage and current supplies of some devices in the system.
-
-### Basic Concepts
-
The regulator module controls the voltage and current supplies of some devices in the system. In an embedded system (especially a mobile phone), it is important to control the power consumption, which directly affects the battery endurance. You can use a regulator to shut down the power supply to an idle module in the system or reduce the voltage and current for the module.
### Working Principles
-In the Hardware Driver Foundation (HDF), the regulator module uses the unified service mode for API adaptation. In this mode, a device service is used as the regulator manager to handle external access requests in a unified manner, which is reflected in the configuration file. The unified service mode applies to the scenario where there are many device objects of the same type, for example, when the regulator has more than 10 controllers. If the independent service mode is used, more device nodes need to be configured and more memory resources will be consumed by services.
+In the Hardware Driver Foundation (HDF), the regulator module uses the unified service mode for API adaptation. In this mode, a device service is used as the regulator manager to handle external access requests in a unified manner, which is reflected in the configuration file. The unified service mode applies when there are many device objects of the same type, for example, when the regulator has more than 10 controllers. If the independent service mode is used, more device nodes need to be configured and more memory resources will be consumed by services.
The regulator module is divided into the following layers:
+- Interface layer: provides APIs for opening or closing a device and writing data.
+- Core layer: provides the capabilities of binding, initializing, and releasing devices.
+- Adaptation layer: implements other functions.
-- The interface layer provides APIs for opening or closing a device and writing data.
-- The core layer provides the capabilities of binding, initializing, and releasing devices.
-- The adaptation layer implements other functions.
-
-NOTE
The core layer can call the functions of the interface layer and uses the hook to call functions of the adaptation layer. In this way, the adaptation layer can indirectly call the functions of the interface layer, but the interface layer cannot call the functions of the adaptation layer.
+NOTE
The core layer can call the APIs of the interface layer and uses hooks to call APIs of the adaptation layer. In this way, the adaptation layer can indirectly call the APIs of the interface layer, but the interface layer cannot call the APIs of the adaptation layer.
**Figure 1** Unified service mode
@@ -33,13 +28,12 @@ The regulator module is divided into the following layers:
Currently, the regulator module supports only the kernels (LiteOS) of mini and small systems.
-## Development Guidelines
### When to Use
The regulator module controls the voltage and current supplies of some devices in the system.
-### Available APIs
+## Available APIs
The functions in **RegulatorMethod** are used to call the corresponding regulator driver functions:
@@ -65,31 +59,34 @@ struct RegulatorMethod {
| Method | Input Parameter | Return Value | Description |
-| ------------ | ------------------------------------------------------------ | ------------------ | ---------------- |
+| ------------ | ----------------------------------------------------------- | ----------------- | ---------------- |
| open | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Opens a device. |
| close | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Closes a device. |
| release | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Releases a device handle. |
-| enable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Enabling a Regulator |
-| disable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Disabling a Regulator |
-| forceDisable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Forcibly Disabling a Regulator |
+| enable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Enables a regulator. |
+| disable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Disables a regulator. |
+| forceDisable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Forcibly disables a regulator. |
| setVoltage | **node**: structure pointer to the regulator node at the core layer.
**minUv**: minimum voltage to set. It is a uint32_t variable.
**maxUv**: maximum voltage to set. It is a uint32_t variable.| HDF_STATUS| Sets the output voltage range.|
-| getVoltage | **node**: structure pointer to the regulator node at the core layer.
**voltage**: pointer to the output voltage value.| HDF_STATUS| Obtains the voltage. |
+| getVoltage | **node**: structure pointer to the regulator node at the core layer.
**voltage**: pointer to the output voltage.| HDF_STATUS| Obtains the voltage. |
| setCurrent | **node**: structure pointer to the regulator node at the core layer.
**minUa**: minimum current to set. It is a uint32_t variable.
**maxUa**: maximum current to set. It is a uint32_t variable.| HDF_STATUS| Sets the output current range.|
| getCurrent | **node**: structure pointer to the regulator node at the core layer.
**regCurrent**: pointer to the output current, which is of the uint32_t type.| HDF_STATUS| Obtains the current. |
| getStatus | **node**: structure pointer to the regulator node at the core layer.
**status**: pointer to the output status, which is of the uint32_t type.| HDF_STATUS| Obtains the device status. |
-### How to Develop
+
+## How to Develop
The regulator module adaptation procedure is as follows:
-- Instantiate the driver entry.
-- Configure attribute files.
-- Instantiate the core layer APIs.
-- Debug the driver.
+1. Instantiate the driver entry.
+2. Configure attribute files.
+3. Instantiate the core layer APIs.
+4. Debug the driver.
+
+## Development Example
1. Instantiate the driver entry.
- Instantiate the driver entry. The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers are collected to form a segment address space similar to an array for the upper layer to invoke.
+ The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
Generally, the HDF calls the **Init()** function to load the driver. If **Init()** fails to be called, the HDF calls **Release** to release driver resources and exit.
@@ -100,7 +97,7 @@ The regulator module adaptation procedure is as follows:
.Init = VirtualRegulatorInit,
.Release = VirtualRegulatorRelease,
};
- // Call HDF_INIT to register the driver entry with the HDF framework.
+ // Call HDF_INIT to register the driver entry with the HDF.
HDF_INIT(g_regulatorDriverEntry);
```
@@ -115,15 +112,15 @@ The regulator module adaptation procedure is as follows:
| Member | Value |
| --------------- | ------------------------------------------------------------ |
| policy | **0**, which indicates that no service is published. |
- | priority | Driver startup priority. The value range is 0 to 200. A larger value indicates a lower priority. If the priorities are the same, the device loading sequence is not ensured.|
+ | priority | Driver startup priority, which ranges form 0 to 200. A larger value indicates a lower priority. If the priorities are the same, the device loading sequence is not ensured.|
| permission | Driver permission. |
- | moduleName | The value is **HDF_PLATFORM_REGULATOR_MANAGER**. |
- | serviceName | The value is **HDF_PLATFORM_REGULATOR_MANAGER**. |
- | deviceMatchAttr | Reserved. |
+ | moduleName | **HDF_PLATFORM_REGULATOR_MANAGER** |
+ | serviceName | **HDF_PLATFORM_REGULATOR_MANAGER** |
+ | deviceMatchAttr | This parameter is reserved. |
Configure regulator controller information from the second node. This node specifies a type of regulator controllers rather than a specific regulator controller. In this example, there is only one regulator device. If there are multiple regulator devices, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **regulator\_config** file.
- - **device_info.hcs** configuration reference
+ - **device_info.hcs** configuration example
```
root {
@@ -132,14 +129,14 @@ The regulator module adaptation procedure is as follows:
hostName = "platform_host";
priority = 50;
device_regulator :: device {
- device0 :: deviceNode { // Configure an HDF device node for each regulator controller.
- policy = 1; // 2: visible in user mode; 1: visible in kernel mode; 0: no service required.
- priority = 50; // Driver startup priority.
- permission = 0644; // Permission to create device nodes of the driver.
+ device0:: deviceNode { // Set an HDF device node for each regulator controller.
+ policy = 1; // Policy for the driver to publish services.
+ priority = 50; // Driver startup priority.
+ permission = 0644; // Permission to create device nodes for the driver.
/* (Mandatory) Driver name, which must be the same as the moduleName in the driver entry. */
moduleName = "HDF_PLATFORM_REGULATOR_MANAGER";
serviceName = "HDF_PLATFORM_REGULATOR_MANAGER"; // (Mandatory) Unique name of the service published by the driver.
- /* (Mandatory) Set the controller private data, which must be same as that in regulator_config.hcs. */
+ /* (Mandatory) Set the controller private data, which must be same as that in regulator_config.hcs. */
deviceMatchAttr = "hdf_platform_regulator_manager";
}
device1 :: deviceNode {
@@ -155,7 +152,7 @@ The regulator module adaptation procedure is as follows:
}
```
- - **regulator\_config.hcs** reference:
+ - **regulator\_config.hcs** configuration example:
```
root {
@@ -184,7 +181,7 @@ The regulator module adaptation procedure is as follows:
minUa = 0;
maxUa = 0;
}
- /* Each regulator controller corresponds to a controller node. If there are multiple regulator controllers, add the corresponding controller nodes one by one.*/
+ /* Each regulator controller corresponds to a controller node. If there are multiple regulator controllers, add the corresponding controller nodes one by one. */
controller_0x130d0001 :: regulator_controller {
device_num = 1;
name = "regulator_adapter_2";
@@ -201,146 +198,152 @@ The regulator module adaptation procedure is as follows:
}
```
-3. Instantiate the APIs of the core layer.
-
- - Initialize the **RegulatorNode** object at the core layer, including initializing the vendor custom structure (passing parameters and data), instantiating **RegulatorMethod** (used to call underlying functions of the driver) in **PinCntlr**, and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**).
-
- - Initializing the vendor custom structure
+3. Instantiate the APIs of the core layer.
- The **RegulatorNode** structure holds parameters and data for the driver. The HDF obtains the values in **regulator\_config.hcs** using **DeviceResourceIface**.
-
- ```
- // RegulatorNode is the controller structure at the core layer. Its members are assigned with values by using the Init function.
- struct RegulatorNode {
- struct RegulatorDesc regulatorInfo;
- struct DListHead node;
- struct RegulatorMethod *ops;
- void *priv;
- struct OsalMutex lock;
- };
-
- struct RegulatorDesc {
- const char *name; /* Regulator name. */
- const char *parentName; /* Regulator parent node name. */
- struct RegulatorConstraints constraints; /* Regulator constraint information. */
- uint32_t minUv; /* Minimum output voltage. */
- uint32_t maxUv; /* Maximum output voltage. */
- uint32_t minUa; /* Minimum output current. */
- uint32_t maxUa; /* Maximum output current. */
- uint32_t status; /* Regulator status, which can be on or off. */
- int useCount;
- int consumerRegNums; /* Number of regulator consumers. */
- RegulatorStatusChangecb cb; /* Variable used to notify the regulator status changes. */
- };
-
- struct RegulatorConstraints {
- uint8_t alwaysOn; /* Whether the regulator is always on. */
- uint8_t mode; /* Voltage or current. */
- uint32_t minUv; /* Minimum output voltage allowed. */
- uint32_t maxUv; /* Maximum output voltage allowed. */
- uint32_t minUa; /* Minimum output current allowed. */
- uint32_t maxUa; /* Maximum output current allowed. */
- };
- ```
-
+ Initialize the **RegulatorNode** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **RegulatorMethod** in **RegulatorNode** (so that the underlying driver functions can be called).
+
+ - Defining a custom structure
+
+ The **RegulatorNode** structure holds parameters and data for the driver. The HDF obtains the values in **regulator_config.hcs** using **DeviceResourceIface**.
+
+
+
+ ```
+ // RegulatorNode is the core layer controller structure. The Init function assigns values to the members of RegulatorNode.
+ struct RegulatorNode {
+ struct RegulatorDesc regulatorInfo;
+ struct DListHead node;
+ struct RegulatorMethod *ops;
+ void *priv;
+ struct OsalMutex lock;
+ };
+
+ struct RegulatorDesc {
+ const char *name; /* Regulator name. */
+ const char *parentName; /* Regulator parent node name. */
+ struct RegulatorConstraints constraints; /* Regulator constraint information. */
+ uint32_t minUv; /* Minimum output voltage. */
+ uint32_t maxUv; /* Maximum output voltage. */
+ uint32_t minUa; /* Minimum output current. */
+ uint32_t maxUa; /* Maximum output current. */
+ uint32_t status; /* Regulator status, which can be on or off. */
+ int useCount;
+ int consumerRegNums; /* Number of regulator consumers. */
+ RegulatorStatusChangecb cb; /* Variable used to notify the regulator status changes. */
+ };
+
+ struct RegulatorConstraints {
+ uint8_t alwaysOn; /* Whether the regulator is always on. */
+ uint8_t mode; /* Voltage or current. */
+ uint32_t minUv; /* Minimum output voltage allowed. */
+ uint32_t maxUv; /* Maximum output voltage allowed. */
+ uint32_t minUa; /* Minimum output current allowed. */
+ uint32_t maxUa; /* Maximum output current allowed. */
+ };
+ ```
+
+
+
+ - Instantiating **RegulatorMethod** (other members are initialized by **Init**)
+
+ ```c
+ // Example of regulator_virtual.c: Instantiate the hooks.
+ static struct RegulatorMethod g_method = {
+ .enable = VirtualRegulatorEnable,
+ .disable = VirtualRegulatorDisable,
+ .setVoltage = VirtualRegulatorSetVoltage,
+ .getVoltage = VirtualRegulatorGetVoltage,
+ .setCurrent = VirtualRegulatorSetCurrent,
+ .getCurrent = VirtualRegulatorGetCurrent,
+ .getStatus = VirtualRegulatorGetStatus,
+ };
+ ```
+
+
+
+ - **Init** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
-
- - Instantiating **RegulatorMethod** (other members are initialized by **Init**)
-
+ Return value:
+
+ **HDF\_STATUS**
+
+ The table below lists some states. For more details, see **HDF\_STATUS** in **/drivers/framework/include/utils/hdf\_base.h**.
+
+ **Table 2** HDF_STATUS
+
+ | State | Description |
+ | ---------------------- | -------------- |
+ | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
+ | HDF_ERR_MALLOC_FAIL | Failed to allocate memory. |
+ | HDF_ERR_INVALID_PARAM | Invalid parameter. |
+ | HDF_ERR_IO | I/O error. |
+ | HDF_SUCCESS | Initialization successful. |
+ | HDF_FAILURE | Initialization failed. |
+
+ Function description:
+
+ Initializes the custom structure and **RegulatorNode** members, and adds the regulator controller by calling the **RegulatorNodeAdd** function at the core layer.
+
+
```c
- // Example of regulator_virtual.c: Instantiate the hook.
- static struct RegulatorMethod g_method = {
- .enable = VirtualRegulatorEnable,
- .disable = VirtualRegulatorDisable,
- .setVoltage = VirtualRegulatorSetVoltage,
- .getVoltage = VirtualRegulatorGetVoltage,
- .setCurrent = VirtualRegulatorSetCurrent,
- .getCurrent = VirtualRegulatorGetCurrent,
- .getStatus = VirtualRegulatorGetStatus,
- };
+ static int32_t VirtualRegulatorInit(struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ const struct DeviceResourceNode *childNode = NULL;
+ ...
+ DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) {
+ ret = VirtualRegulatorParseAndInit(device, childNode);// (Mandatory) The implementation is as follows:
+ ...
+ }
+ ...
+ }
+
+ static int32_t VirtualRegulatorParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node)
+ {
+ int32_t ret;
+ struct RegulatorNode *regNode = NULL;
+ (void)device;
+
+ regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode));// Load the .hcs file.
+ ...
+ ret = VirtualRegulatorReadHcs(regNode, node);// Read .hcs information.
+ ...
+ regNode->priv = (void *)node; // Instantiate the node.
+ regNode->ops = &g_method; // Instantiate OPS.
+
+ ret = RegulatorNodeAdd(regNode); // Add the node.
+ ...
+ }
```
-
-
-
- - **Init** function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration.
+
+ - **Release** function
- Return value:
+ Input parameter:
- **HDF\_STATUS** (The following table lists some states. For more details, see **HDF\_STATUS** in **/drivers/framework/include/utils/hdf\_base.h**.)
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
- **Table 2** HDF\_STATUS
-
- | State | Description |
- | ---------------------- | -------------- |
- | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
- | HDF_ERR_MALLOC_FAIL | Failed to allocate memory. |
- | HDF_ERR_INVALID_PARAM | Invalid parameter. |
- | HDF_ERR_IO | I/O error. |
- | HDF_SUCCESS | Initialization successful. |
- | HDF_FAILURE | Initialization failed. |
-
- Function description:
-
- Initializes the custom structure and **RegulatorNode** members, and adds the regulator controller by calling the **RegulatorNodeAdd** function at the core layer.
-
-
+ Return value:
+
+ No value is return.
+
+ Function description:
+
+ Releases the memory and deletes the controller. This function assigns values to the **Release** function in the driver entry structure. If the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources.
+
```c
- static int32_t VirtualRegulatorInit(struct HdfDeviceObject *device)
+ static void VirtualRegulatorRelease(struct HdfDeviceObject *device)
{
- int32_t ret;
- const struct DeviceResourceNode *childNode = NULL;
- ...
- DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) {
- ret = VirtualRegulatorParseAndInit(device, childNode);// (Mandatory) The implementation is as follows:
- ...
- }
- ...
- }
-
- static int32_t VirtualRegulatorParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node)
- {
- int32_t ret;
- struct RegulatorNode *regNode = NULL;
- (void)device;
-
- regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode));// Load the .hcs file.
- ...
- ret = VirtualRegulatorReadHcs(regNode, node);// Read .hcs information.
- ...
- regNode->priv = (void *)node; // Instantiate the node.
- regNode->ops = &g_method; // Instantiate OPS.
-
- ret = RegulatorNodeAdd(regNode); // Add the node.
...
+ RegulatorNodeRemoveAll();// (Mandatory) Call the function at the core layer to release regulator controller devices and services.
}
```
-
- - **Release** function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration.
-
- Return value:
-
- –
-
- Function description:
-
- Releases memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. If the HDF fails to call the **Init()** function to initialize the driver, the **Release()** function can be called to release driver resources.
-
- ```c
- static void VirtualRegulatorRelease(struct HdfDeviceObject *device)
- {
- ...
- RegulatorNodeRemoveAll();// (Mandatory) Call the function at the core layer to release regulator controller devices and services.
- }
- ```
-
-4. (Optional) Debug the driver.
- Verify the basic functions of the new driver, for example, whether the test cases are successful after the driver is loaded.
\ No newline at end of file
+4. Debug the driver.
+
+ (Optional) Verify the basic functions of the new driver, for example, check whether the test cases are successful after the driver is loaded.
+
+
diff --git a/en/device-dev/driver/driver-platform-spi-des.md b/en/device-dev/driver/driver-platform-spi-des.md
index 8c536413b9eb82b92de579038d2f639865f3b157..696087ee948f1d8ac9747942551c1a166fd7cabd 100644
--- a/en/device-dev/driver/driver-platform-spi-des.md
+++ b/en/device-dev/driver/driver-platform-spi-des.md
@@ -1,160 +1,101 @@
-# SPI
+# SPI
-## Overview
-Serial Peripheral Interface \(SPI\) is a serial bus specification used for high-speed, full-duplex, and synchronous communication.
-SPI is developed by Motorola. It is commonly used for communication with flash memory, real-time clocks, sensors, and analog-to-digital \(A/D\) converters.
+## **Overview**
+
+Serial Peripheral Interface (SPI) is a serial bus specification used for high-speed, full-duplex, and synchronous communication. SPI is developed by Motorola. It is commonly used for communication with flash memory, real-time clocks, sensors, and analog-to-digital (A/D) converters.
+
SPI works in controller/device mode. Generally, there is one SPI controller that controls one or more SPI devices. They are connected via four wires:
-- SCLK: clock signals output from the SPI controller
-- MOSI: data output from the SPI controller and input into an SPI device
-- MISO: data output from an SPI device and input into the SPI controller
-- CS: signals enabled by an SPI device and controlled by the SPI controller
-
-
-[Figure 1](#fig89085710359) shows the connection between one SPI controller and two SPI devices \(device A and device B\). In this figure, device A and device B share three pins \(SCLK, MISO, and MOSI\) of the controller. CS0 of device A and CS1 of device B are connected to CS0 and CS1 of the controller, respectively.
-
-**Figure 1** SPI controller/device connection
-
-
-SPI communication is usually initiated by the SPI controller and is operated as follows:
-
-1. A single SPI device is selected at a time via the CS to communicate with the SPI controller.
-2. Clock signals are provided for the selected SPI device via the SCLK.
-3. The SPI controller sends data to SPI devices via the MOSI, and receives data from SPI devices via the MISO.
-
-- SPI can work in one of the following four modes, equivalent to one of the four possible states for Clock Polarity \(CPOL\) and Clock Phase \(CPHA\):
- - If both CPOL and CPHA are **0**, the clock signal level is low in the idle state and data is sampled on the first clock edge.
- - If CPOL is **0** and CPHA is **1**, the clock signal level is low in the idle state and data is sampled on the second clock edge.
- - If CPOL is **1** and CPHA is **0**, the clock signal level is high in the idle state and data is sampled on the first clock edge.
- - If both CPOL and CPHA are **1**, the clock signal level is high in the idle state and data is sampled on the second clock edge.
-
-
-- SPI defines a set of common functions for operating an SPI device, including those for:
- - Obtaining and releasing the handle of an SPI device.
- - Reading or writing data of a specified length from or into an SPI device.
- - Customizing data reading or writing via **SpiMsg**.
- - Obtaining and setting SPI device configuration parameters.
-
-
-> **NOTE**
->Currently, these functions are only applicable in the communication initiated by the SPI controller.
-
-## Available APIs
-
-**Table 1** APIs for the SPI driver
-
-
-Capability
- |
-Function
- |
-Description
- |
-
-
-SPI device handle obtaining/releasing
- |
-SpiOpen
- |
-Obtains an SPI device handle.
- |
-
-SpiClose
- |
-Releases an SPI device handle.
- |
-
-SPI reading/writing
- |
-SpiRead
- |
-Reads data of a specified length from an SPI device.
- |
-
-SpiWrite
- |
-Writes data of a specified length into an SPI device.
- |
-
-SpiTransfer
- |
-Transfers SPI data.
- |
-
-SPI device configuration
-
- |
-SpiSetCfg
- |
-Sets configuration parameters for an SPI device.
- |
-
-SpiGetCfg
- |
-Obtains configuration parameters of an SPI device.
- |
-
-
-
-
-> **NOTE:**
->All functions provided in this document can be called only in kernel space.
-
-## Usage Guidelines
-
-### How to Use
-
-The figure below illustrates how to use the APIs.
-
-**Figure 2** Using SPI driver APIs
-
-
-### Obtaining an SPI Device Handle
-
-Before performing SPI communication, obtain an SPI device handle by calling **SpiOpen**. This function returns an SPI device handle with a specified bus number and CS number.
-
-DevHandle SpiOpen\(const struct SpiDevInfo \*info\);
-
-**Table 2** Description of SpiOpen
-
-
-Parameter
- |
-Description
- |
-
-info
- |
-Pointer to the SPI device descriptor.
- |
-
-Return Value
- |
-Description
- |
-
-NULL
- |
-Failed to obtain an SPI device handle.
- |
-
-Device handle
- |
-Returns the pointer to the SPI device handle.
- |
-
-
-
-
-The following example shows how to obtain an SPI device handle based on the assumption that both the bus number and CS number of the SPI device are **0**.
+ - SCLK: clock signal output from the SPI controller
+ - MOSI: data output from the SPI controller to a device
+ - MISO: data output from an SPI device to the controller
+ - Chip select (CS): output from the SPI controller to indicate that data is being sent. It is controlled by the SPI controller.
+
+The figure below shows the connection between one controller and two devices (device A and device B). Device A and device B share three pins (SCLK, MISO, and MOSI) of the controller. CS 0 of device A and CS 1 of device B are connected to CS 0 and CS 1 of the controller, respectively.
+
+ **Figure 1** Connection between the SPI controller and devices
+
+ 
+
+- SPI communication is usually initiated by the controller and is performed as follows:
+ 1. The SPI controller selects a device to communicate on the select line. Only one device can be selected at a time.
+ 2. SCLK provides clock signals to the selected device.
+ 3. The SPI controller sends data to the device via MOSI, and receives data from the devices via MISO.
+
+- SPI can work in one of the following modes according to the combination of Clock Polarity (CPOL) and Clock Phase (CPHA) of the clock signal:
+ - If both CPOL and CPHA are **0**, the clock signal level is low in the idle state and data is sampled on the first clock edge.
+ - If CPOL is **0** and CPHA is **1**, the clock signal level is low in the idle state and data is sampled on the second clock edge.
+ - If CPOL is **1** and CPHA is **0**, the clock signal level is high in the idle state and data is sampled on the first clock edge.
+ - If both CPOL and CPHA are **1**, the clock signal level is high in the idle state and data is sampled on the second clock edge.
+
+- SPI defines a set of common functions for operating an SPI device, including those for:
+ - Obtaining and releasing an SPI device handle.
+ - Reading or writing data of the specified length from or into an SPI device.
+ - Customizing data reading or writing via **SpiMsg**.
+ - Obtaining and setting SPI device attributes.
+
+>  **NOTE**
+> Currently, these functions are only applicable in the communication initiated by the SPI controller.
+
+
+## **Available APIs**
+
+ **Table 1** SPI driver APIs
+
+| API| Description|
+| -------- | -------- |
+| SpiOpen | Opens an SPI device handle.|
+| SpiClose | Closes an SPI device handle.|
+| SpiRead | Reads data of the specified length from a device.|
+| SpiWrite | Writes data of the specified length to a device.|
+| SpiTransfer | Transfers SPI data.|
+| SpiSetCfg | Sets SPI device attributes.|
+| SpiGetCfg | Obtains SPI device attributes.|
+
+>  **NOTE**
+> All APIs described in this document can be called only in kernel mode.
+
+
+## Usage Guidelines
+
+
+### How to Use
+
+The figure below shows the general process of using SPI.
+
+ **Figure 2** Process of using SPI APIs
+
+ 
+
+
+### Opening an SPI Device Handle
+Before performing SPI communication, call **SpiOpen** to open the SPI device handle. This function returns the device handle of the SPI based on the specified bus number and CS number.
+
+
+```
+DevHandle SpiOpen(const struct SpiDevInfo *info);
```
-struct SpiDevInfo spiDevinfo; /* SPI device descriptor */
-DevHandle spiHandle = NULL; /* SPI device handle */
-spiDevinfo.busNum = 0; /* SPI device bus number */
-spiDevinfo.csNum = 0; /* SPI device CS number */
-/* Obtain an SPI device handle. */
+ **Table 2** Description of SpiOpen
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| info | Pointer to the SPI device descriptor.|
+| **Return Value**| **Description**|
+| NULL | The operation failed.|
+| Device handle| The operation is successful. The SPI device handle obtained is returned.|
+
+For example, open the handle of the SPI device, whose bus number and the CS number are both **0**.
+
+
+```
+struct SpiDevInfo spiDevinfo; /* SPI device descriptor. */
+DevHandle spiHandle = NULL; /* SPI device handle */
+spiDevinfo.busNum = 0; /* SPI device bus number. */
+spiDevinfo.csNum = 0; /* SPI device CS number. */
+
+/* Obtain the SPI device handle. */
spiHandle = SpiOpen(&spiDevinfo);
if (spiHandle == NULL) {
HDF_LOGE("SpiOpen: failed\n");
@@ -162,324 +103,201 @@ if (spiHandle == NULL) {
}
```
-### Obtaining SPI Device Configuration Parameters
-
-After obtaining the SPI device handle, obtain the SPI device configuration parameters by calling the following function:
-
-int32\_t SpiGetCfg\(DevHandle handle, struct SpiCfg \*cfg\);
-
-**Table 3** Description of SpiGetCfg
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-cfg
- |
-Pointer to SPI device configuration parameters.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in obtaining SPI device configuration parameters.
- |
-
-Negative value
- |
-Failed to obtain SPI device configuration parameters.
- |
-
-
-
-```
-int32_t ret;
-struct SpiCfg cfg = {0}; /* SPI configuration information */
-ret = SpiGetCfg(spiHandle, &cfg); /* Obtain SPI device configuration parameters. */
-if (ret != 0) {
- HDF_LOGE("SpiGetCfg: failed, ret %d\n", ret);
-}
-```
+### Obtaining SPI Device Attributes
+
+After obtaining the SPI device handle, you need to configure the device attributes. Before configuring the device attributes, you can call **SpiGetCfg** to obtain the device attributes.
-### Setting SPI Device Configuration Parameters
-
-After obtaining the SPI device handle, set SPI device configuration parameters by calling the following function:
-
-int32\_t SpiSetCfg\(DevHandle handle, struct SpiCfg \*cfg\);
-
-**Table 4** Description of SpiSetCfg
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-cfg
- |
-Pointer to SPI device configuration parameters.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in setting SPI device configuration parameters.
- |
-
-Negative value
- |
-Failed to set SPI device configuration parameters.
- |
-
-
-
```
-int32_t ret;
-struct SpiCfg cfg = {0}; /* SPI configuration information */
-cfg.mode = SPI_MODE_LOOP; /* Communication in loopback mode */
-cfg.transferMode = PAL_SPI_POLLING_TRANSFER; /* Communication in polling mode */
-cfg.maxSpeedHz = 115200; /* Maximum transmission frequency */
-cfg.bitsPerWord = 8; /* The width of per word to be read or written is 8 bits. */
-ret = SpiSetCfg(spiHandle, &cfg); /* Set SPI device configuration parameters. */
-if (ret != 0) {
- HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret);
-}
+int32_t SpiGetCfg(DevHandle handle, struct SpiCfg *cfg);
```
-### Performing SPI Communication
-
-- Writing data of a specific length into an SPI device
-
-To write data into an SPI device only once, call the following function:
-
-int32\_t SpiWrite\(DevHandle handle, uint8\_t \*buf, uint32\_t len\);
-
-**Table 5** Description of SpiWrite
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-buf
- |
-Pointer to the data to write.
- |
-
-len
- |
-Length of the data to write.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in writing data into an SPI device.
- |
-
-Negative value
- |
-Failed to write data into an SPI device.
- |
-
-
-
+ **Table 3** Description of SpiGetCfg
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| cfg | Pointer to the SPI device attributes.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value | The operation failed.|
+
```
int32_t ret;
-uint8_t wbuff[4] = {0x12, 0x34, 0x56, 0x78};
-/* Write data of a specific length into an SPI device. */
-ret = SpiWrite(spiHandle, wbuff, 4);
+struct SpiCfg cfg = {0}; /* SPI configuration. */
+ret = SpiGetCfg(spiHandle, &cfg); /* Obtain SPI device attributes. */
if (ret != 0) {
- HDF_LOGE("SpiWrite: failed, ret %d\n", ret);
+ HDF_LOGE("SpiGetCfg: failed, ret %d\n", ret);
}
```
-- Reading data of a specific length from an SPI device
-
-To read data from an SPI device only once, call the following function:
-
-int32\_t SpiRead\(DevHandle handle, uint8\_t \*buf, uint32\_t len\);
-
-**Table 6** Description of SpiRead
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-buf
- |
-Pointer to the data to read.
- |
-
-len
- |
-Length of the data to read.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in reading data from an SPI device.
- |
-
-Negative value
- |
-Failed to read data from an SPI device.
- |
-
-
-
+
+### Setting SPI Device Attributes
+
+After obtaining the SPI device handle, call **SpiSetCfg** to set SPI device attributes.
+
```
-int32_t ret;
-uint8_t rbuff[4] = {0};
-/* Read data of a specific length from an SPI device. */
-ret = SpiRead(spiHandle, rbuff, 4);
-if (ret != 0) {
- HDF_LOGE("SpiRead: failed, ret %d\n", ret);
-}
+int32_t SpiSetCfg(DevHandle handle, struct SpiCfg *cfg);
```
-- Launching a custom transfer
-
-To launch a custom transfer, call the following function:
-
-int32\_t SpiTransfer\(DevHandle handle, struct SpiMsg \*msgs, uint32\_t count\);
-
-**Table 7** Description of SpiTransfer
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-msgs
- |
-Pointer to the message array to be transferred.
- |
-
-count
- |
-Number of messages in the message array.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in launching the custom transfer.
- |
-
-Negative value
- |
-Failed to launch the custom transfer.
- |
-
-
-
+ **Table 4** Description of SpiSetCfg
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| cfg | Pointer to the SPI device attributes.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value | The operation failed.|
+
```
int32_t ret;
-uint8_t wbuff[1] = {0x12};
-uint8_t rbuff[1] = {0};
-struct SpiMsg msg; /* Custom message to be transferred */
-msg.wbuf = wbuff; /* Pointer to the data to write */
-msg.rbuf = rbuff; /* Pointer to the data to read */
-msg.len = 1; /* The length of the data to read or write is 1 bit. */
-msg.csChange = 1; /* Disable the CS before the next transfer. */
-msg.delayUs = 0; /* No delay before the next transfer */
-msg.speed = 115200; /* Speed of this transfer */
-/* Launch a custom transfer. The number of messages to be transferred is 1. */
-ret = SpiTransfer(spiHandle, &msg, 1);
+struct SpiCfg cfg = {0}; /* SPI configuration. */
+cfg.mode = SPI_MODE_LOOP; /* Communicate in loop mode. */
+cfg.transferMode = PAL_SPI_POLLING_TRANSFER; /* Communicate in polling mode. */
+cfg.maxSpeedHz = 115200; /* Maximum transfer frequency. */
+cfg.bitsPerWord = 8; /* The width of per word to be read or written is 8 bits. */
+ret = SpiSetCfg(spiHandle, &cfg); /* Set SPI device attributes. */
if (ret != 0) {
- HDF_LOGE("SpiTransfer: failed, ret %d\n", ret);
+ HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret);
}
```
-### Destroying the SPI Device Handle
-After the SPI communication, destroy the SPI device handle by calling the following function:
+### Performing SPI Communication
+
+- Write data to an SPI device
+
+ Call **SpiWrite()** to write data to an SPI device only once.
+
+
+ ```
+ int32_t SpiWrite(DevHandle handle, uint8_t *buf, uint32_t len);
+ ```
+
+ **Table 5** Description of SpiWrite
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| buf | Pointer to the data to write.|
+| len | Length of the data to write.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value | The operation failed.|
+
+
+ ```
+ int32_t ret;
+ uint8_t wbuff[4] = {0x12, 0x34, 0x56, 0x78};
+ /* Write data of the specified length to an SPI device. */
+ ret = SpiWrite(spiHandle, wbuff, 4);
+ if (ret != 0) {
+ HDF_LOGE("SpiWrite: failed, ret %d\n", ret);
+ }
+ ```
+
+- Read data from an SPI device
+
+ Call **SpiRead()** to read data from an SPI device only once.
+
-void SpiClose\(DevHandle handle\);
+ ```
+ int32_t SpiRead(DevHandle handle, uint8_t *buf, uint32_t len);
+ ```
-This function will release the resources previously obtained.
+ **Table 6** Description of SpiRead
-**Table 8** Description of SpiClose
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| buf | Pointer to the data to read.|
+| len | Length of the data to read.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
+
+ ```
+ int32_t ret;
+ uint8_t rbuff[4] = {0};
+ /* Read data of the specified length from an SPI device. */
+ ret = SpiRead(spiHandle, rbuff, 4);
+ if (ret != 0) {
+ HDF_LOGE("SpiRead: failed, ret %d\n", ret);
+ }
+ ```
+
+- Perform a custom transfer
+
+ Call **SpiTransfer()** to perform a custom transfer.
+
+
+ ```
+ int32_t SpiTransfer(DevHandle handle, struct SpiMsg *msgs, uint32_t count);
+ ```
+
+ **Table 7** Description of SpiTransfer
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| msgs | Pointer to the message array to be transferred.|
+| count | Number of messages in the message array.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
+
+ ```
+ int32_t ret;
+ uint8_t wbuff[1] = {0x12};
+ uint8_t rbuff[1] = {0};
+ struct SpiMsg msg; /* Custom message to be transferred. */
+ msg.wbuf = wbuff; /* Data to write. */
+ msg.rbuf = rbuff; /* Data to read. */
+ msg.len = 1; /* The length of the data to read or write is 1 bit. */
+ msg.csChange = 1; /* Close the CS before the next transfer. */
+ msg.delayUs = 0; /* No delay before the next transfer. */
+ msg.speed = 115200; /* Transfer speed. */
+ /* Perform a custom transfer. The number of messages to be transferred is 1. */
+ ret = SpiTransfer(spiHandle, &msg, 1);
+ if (ret != 0) {
+ HDF_LOGE("SpiTransfer: failed, ret %d\n", ret);
+ }
+ ```
+
+
+### Closing an SPI Device Handle
+
+After the SPI communication, call **SpiClose()** to close the SPI device handle.
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-
-
```
-SpiClose(spiHandle); /* Destroy the SPI device handle. */
+void SpiClose(DevHandle handle);
```
-## Usage Example
+This function releases the resources requested by **MipiDsiOpen**.
+
+ **Table 8** Description of SpiClose
-The following example shows how to obtain an SPI device handle, set the configuration parameters, and then read or write data from or into the SPI device, and finally destroy the SPI device handle.
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+
+
+```
+SpiClose(spiHandle); /* Close the SPI device handle. */
+```
+
+
+## Example
+
+The following example shows how to obtain an SPI device handle, set device attributes, and then read or write data from or into the SPI device, and finally close the SPI device handle.
```
#include "hdf_log.h"
@@ -488,61 +306,61 @@ The following example shows how to obtain an SPI device handle, set the configur
void SpiTestSample(void)
{
int32_t ret;
- struct SpiCfg cfg; /* SPI device configuration information */
- struct SpiDevInfo spiDevinfo; /* SPI device descriptor */
- DevHandle spiHandle = NULL; /* SPI device handle */
- struct SpiMsg msg; /* Custom message to be transferred */
+ struct SpiCfg cfg; /* SPI device configuration. */
+ struct SpiDevInfo spiDevinfo; /* SPI device descriptor. */
+ DevHandle spiHandle = NULL; /* SPI device handle. */
+ struct SpiMsg msg; /* Custom message to be transferred. */
uint8_t rbuff[4] = { 0 };
uint8_t wbuff[4] = { 0x12, 0x34, 0x56, 0x78 };
uint8_t wbuff2[4] = { 0xa1, 0xb2, 0xc3, 0xd4 };
- spiDevinfo.busNum = 0; /* SPI device bus number */
- spiDevinfo.csNum = 0; /* SPI device CS number */
- spiHandle = SpiOpen(&spiDevinfo); /* Obtain an SPI device handle based on spiDevinfo. */
+ spiDevinfo.busNum = 0; /* SPI device bus number. */
+ spiDevinfo.csNum = 0; /* SPI device CS number. */
+ spiHandle = SpiOpen(&spiDevinfo); /* Open the SPI device handle based on spiDevinfo. */
if (spiHandle == NULL) {
HDF_LOGE("SpiOpen: failed\n");
return;
}
- /* Obtain configuration parameters of an SPI device. */
+ /* Obtain SPI attributes. */
ret = SpiGetCfg(spiHandle, &cfg);
if (ret != 0) {
HDF_LOGE("SpiGetCfg: failed, ret %d\n", ret);
goto err;
}
- cfg.maxSpeedHz = 115200; /* Change the maximum clock frequency to 115200. */
- cfg.bitsPerWord = 8; /* Change the word width to 8 bits. */
- /* Set configuration parameters for an SPI device. */
+ cfg.maxSpeedHz = 115200; /* Set the maximum clock frequency to 115200. */
+ cfg.bitsPerWord = 8; /* Set the word width to 8 bits. */
+ /* Set SPI attributes. */
ret = SpiSetCfg(spiHandle, &cfg);
if (ret != 0) {
HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret);
goto err;
}
- /* Write specified length of data into an SPI device. */
+ /* Write data of the specified length to an SPI device. */
ret = SpiWrite(spiHandle, wbuff, 4);
if (ret != 0) {
HDF_LOGE("SpiWrite: failed, ret %d\n", ret);
goto err;
}
- /* Read data of a specific length from an SPI device. */
+ /* Read data of the specified length from an SPI device. */
ret = SpiRead(spiHandle, rbuff, 4);
if (ret != 0) {
HDF_LOGE("SpiRead: failed, ret %d\n", ret);
goto err;
}
- msg.wbuf = wbuff2; /* Pointer to the data to write */
- msg.rbuf = rbuff; /* Pointer to the data to read */
- msg.len = 4; /* The length of the data to read or write is 4 bits. */
- msg.csChange = 1; /* Disable the CS before the next transfer. */
- msg.delayUs = 0; /* No delay before the next transfer */
- msg.speed = 115200; /* Speed of this transfer */
- /* Launch a custom transfer. The number of messages to be transferred is 1. */
+ msg.wbuf = wbuff2; /* Data to write. */
+ msg.rbuf = rbuff; /* Data to read. */
+ msg.len = 4; /* Set the length of the data to read or write to 4 bits. */
+ msg.csChange = 1; /* Close the CS before the next transfer. */
+ msg.delayUs = 0; /* No delay before the next transfer. */
+ msg.speed = 115200; /* Transfer speed. */
+ /* Perform a custom transfer. The number of messages to be transferred is 1. */
ret = SpiTransfer(spiHandle, &msg, 1);
if (ret != 0) {
HDF_LOGE("SpiTransfer: failed, ret %d\n", ret);
goto err;
}
err:
- /* Destroy the SPI device handle. */
+ /* Close the SPI device handle. */
SpiClose(spiHandle);
}
-```
\ No newline at end of file
+```
diff --git a/en/device-dev/driver/driver-platform-spi-develop.md b/en/device-dev/driver/driver-platform-spi-develop.md
index 40ed76d02446262f32d8d6e55eba044eca88fd89..992424e32ed99b6cbc5dba998871a9d46f3660e6 100644
--- a/en/device-dev/driver/driver-platform-spi-develop.md
+++ b/en/device-dev/driver/driver-platform-spi-develop.md
@@ -1,16 +1,18 @@
-# SPI
+# SPI
-## Overview
+## Overview
-In the Hardware Driver Foundation \(HDF\), the Serial Peripheral Interface \(SPI\) uses the independent service mode for API adaptation. In this mode, each device independently publishes a device service to handle external access requests. After receiving an access request from an API, the device manager extracts the parameters in the request to call the internal method of the target device. In the independent service mode, the service management capabilities of the HDFDeviceManager can be directly used. However, you need to configure a device node for each device, which increases the memory usage.
+Serial Peripheral Interface (SPI) is a serial bus specification used for high-speed, full-duplex, and synchronous communication. In the Hardware Driver Foundation (HDF), the SPI module uses the independent service mode for API adaptation. In this mode, each device independently publishes a service to process external access requests. When receiving an access request, the HDF DeviceManager extracts parameters from the request to call the internal APIs of the target device. In the independent service mode, the HDF DeviceManager provides service management capabilities. However, you need to configure a node for each device, which increases memory usage.
-**Figure 1** Independent service mode
-
+ **Figure 1** Independent service mode
-## Available APIs
+ 
+
+## **Available APIs**
+
+**SpiCntlrMethod**:
-SpiCntlrMethod:
```
struct SpiCntlrMethod {
@@ -21,422 +23,348 @@ struct SpiCntlrMethod {
int32_t (*Close)(struct SpiCntlr *cntlr);
};
```
-**Table 1** Callbacks for the members in the SpiCntlrMethod structure
-
-
-Callback
- |
-Input Parameter
- |
-Return Value
- |
-Description
- |
-
-
-Transfer
- |
-cntlr: structure pointer to the SPI controller at the core layer.
-msg: structure pointer to the SPI message.
-count: number of messages. The value is of the uint32_t type.
- |
-HDF_STATUS
- |
-Transfers messages.
- |
-
-SetCfg
- |
-cntlr: structure pointer to the SPI controller at the core layer.
-cfg: structure pointer to the SPI attributes.
- |
-HDF_STATUS
- |
-Sets SPI controller attributes.
- |
-
-GetCfg
- |
-cntlr: structure pointer to the SPI controller at the core layer.
-cfg: structure pointer to the SPI attributes.
- |
-HDF_STATUS
- |
-Obtains SPI controller attributes.
- |
-
-Open
- |
-cntlr: structure pointer to the SPI controller at the core layer.
- |
-HDF_STATUS
- |
-Enables the SPI.
- |
-
-Close
- |
-cntlr: structure pointer to the SPI controller at the core layer.
- |
-HDF_STATUS
- |
-Disables the SPI.
- |
-
-
-
-
-## How to Develop
+
+ **Table 1** Description of the callback functions in SpiCntlrMethod
+
+| Function| Input Parameter| Return Value| Description|
+| -------- | -------- | -------- | -------- |
+| Transfer | **cntlr**: structure pointer to the SPI controller at the core layer.
**msg**: structure pointer to the SPI message.
**count**: number of messages. The value is of the uint32_t type.| HDF_STATUS| Transfers messages.|
+| SetCfg | **cntlr**: structure pointer to the SPI controller at the core layer.
**cfg**: structure pointer to the SPI attributes.| HDF_STATUS| Sets SPI controller attributes.|
+| GetCfg | **cntlr**: structure pointer to the SPI controller at the core layer.
**cfg**: structure pointer to the SPI attributes.| HDF_STATUS| Obtains SPI controller attributes.|
+| Open | **cntlr**: structure pointer to the SPI controller at the core layer.| HDF_STATUS| Opens an SPI device.|
+| Close | **cntlr**: structure pointer to the SPI controller at the core layer.| HDF_STATUS| Closes an SPI device.|
+
+
+## How to Develop
The SPI module adaptation involves the following steps:
-1. Instantiate the driver entry.
- - Instantiate the **HdfDriverEntry** structure.
- - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF.
-
-2. Configure attribute files.
- - Add the **deviceNode** information to the **device\_info.hcs** file.
- - \(Optional\) Add the **spi\_config.hcs** file.
-
-3. Instantiate the SPI controller object.
- - Initialize **SpiCntlr**.
- - Instantiate **SpiCntlrMethod** in the **SpiCntlr** object.
-
- For details, see [Available APIs](#section752964871810).
-
- 4. \(Optional\) Debug the driver.
- For new drivers, verify the basic functions, such as the SPI control status and response to interrupts.
-
-
-## Development Example
-
-The following uses **spi\_hi35xx.c** as an example to present the contents that need to be provided by the vendor to implement device functions.
-
-1. Instantiate the driver entry. The driver entry must be a global variable of the **HdfDriverEntry** type \(defined in **hdf\_device\_desc.h**\), and the value of **moduleName** must be the same as that in **device\_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
-
- Generally, HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, HDF calls **Release** to release driver resources and exit.
-
- - SPI driver entry reference
-
- ```
- struct HdfDriverEntry g_hdfSpiDevice = {
- .moduleVersion = 1,
- .moduleName = "HDF_PLATFORM_SPI",// (Mandatory) The value must be the same as that of moduleName in the .hcs file.
- .Bind = HdfSpiDeviceBind, // See the Bind function.
- .Init = HdfSpiDeviceInit, // See the Init function.
- .Release = HdfSpiDeviceRelease, //See the Release function.
- };
- // Call HDF_INIT to register the driver entry with the HDF.
- HDF_INIT(g_hdfSpiDevice);
- ```
-
-2. Add the **deviceNode** information to the **device\_info.hcs** file and configure the device attributes in the **spi\_config.hcs** file. The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **SpiCntlr** members at the core layer.
-
- In this example, there is only one SPI controller. If there are multiple SPI controllers, you need to add the **deviceNode** information to the **device\_info** file and add the corresponding device attributes to the **spi\_config** file.
-
- - **device\_info.hcs** configuration reference
-
- ```
- root {
- device_info {
- match_attr = "hdf_manager";
- platform :: host {
- hostName = "platform_host";
- priority = 50;
- device_spi :: device {// Configure an HDF device node for each SPI controller.
- device0 :: deviceNode {
- policy = 1;
- priority = 60;
- permission = 0644;
- moduleName = "HDF_PLATFORM_SPI";
- serviceName = "HDF_PLATFORM_SPI_0";
- deviceMatchAttr = "hisilicon_hi35xx_spi_0";
- }
- device1 :: deviceNode {
- policy = 1;
- priority = 60;
- permission = 0644;
- moduleName = "HDF_PLATFORM_SPI"; // (Mandatory) Driver name, which must be the same as that of moduleName in the driver entry structure.
- serviceName = "HDF_PLATFORM_SPI_1"; // (Mandatory) Unique name of the service published by the driver
- deviceMatchAttr = "hisilicon_hi35xx_spi_1";// The value must be the same as that of match_attr in the .hcs file.
- }
- ...
- }
- }
- }
- }
- ```
-
- - **spi\_config.hcs** configuration reference
-
- ```
- root {
- platform {
- spi_config {// Configure private data for each SPI controller.
- template spi_controller {// Template configuration. In the template, you can configure the common parameters shared by service nodes.
- serviceName = "";
- match_attr = "";
- transferMode = 0; // Data transfer mode, which can be interrupt transfer (0), flow control transfer (1), or DMA transfer (2).
- busNum = 0; // Bus number
- clkRate = 100000000;
- bitsPerWord = 8; // Bit width of the data transferred
- mode = 19; // SPI data input/output mode
- maxSpeedHz = 0; // Maximum clock frequency
- minSpeedHz = 0; // Minimum clock frequency
- speed = 2000000; // Current message transfer speed
- fifoSize = 256; // FIFO size
- numCs = 1; // Chip select (CS) number
- regBase = 0x120c0000; // Used for address mapping.
- irqNum = 100; // Interruption number
- REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4
- CRG_SPI_CKEN = 0;
- CRG_SPI_RST = 0;
- REG_MISC_CTRL_SPI = 0x12030024; // MISC_REG_BASE(0x12030000) + 0x24
- MISC_CTRL_SPI_CS = 0;
- MISC_CTRL_SPI_CS_SHIFT = 0;
- }
- controller_0x120c0000 :: spi_controller {
- busNum = 0; // (Mandatory) Bus number
- CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk
- CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset
- match_attr = "hisilicon_hi35xx_spi_0";// (Mandatory) The value must be the same as that of deviceMatchAttr in device_info.hcs.
- }
- controller_0x120c1000 :: spi_controller {
- busNum = 1;
- CRG_SPI_CKEN = 0x20000; // (0x1 << 17) 0:close clk, 1:open clk
- CRG_SPI_RST = 0x2; // (0x1 << 1) 0:cancel reset, 1:reset
- match_attr = "hisilicon_hi35xx_spi_1";
- regBase = 0x120c1000; // (Mandatory) Used for address mapping.
- irqNum = 101; // (Mandatory) Interrupt number
- }
- ...
- //(Optional) Add nodes to the device_info.hcs file as required.
- }
- }
- }
- ```
-
-3. Initialize the **SpiCntlr** object at the core layer, including initializing the vendor custom structure \(transferring parameters and data\), instantiating **SpiCntlrMethod** \(used to call underlying functions of the driver\) in **SpiCntlr**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\).
- - Custom structure reference
-
- To the driver, the custom structure carries parameters and data. The values in the **spi\_config.hcs** file are read by HDF, and the structure members are initialized through **DeviceResourceIface**. Some important values, such as the device number and bus number, are also passed to the object at the core layer.
-
- ```
- struct Pl022 {// Corresponds to parameters in .hcs.
- struct SpiCntlr *cntlr;
- struct DListHead deviceList;
- struct OsalSem sem;
- volatile unsigned char *phyBase;
- volatile unsigned char *regBase;
- uint32_t irqNum;
- uint32_t busNum;
- uint32_t numCs;
- uint32_t curCs;
- uint32_t speed;
- uint32_t fifoSize;
- uint32_t clkRate;
- uint32_t maxSpeedHz;
- uint32_t minSpeedHz;
- uint32_t regCrg;
- uint32_t clkEnBit;
- uint32_t clkRstBit;
- uint32_t regMiscCtrl;
- uint32_t miscCtrlCsShift;
- uint32_t miscCtrlCs;
- uint16_t mode;
- uint8_t bitsPerWord;
- uint8_t transferMode;
- };
-
- // SpiCntlr is the core layer controller structure. Its members are assigned with values by using the Init function.
- struct SpiCntlr {
- struct IDeviceIoService service;
- struct HdfDeviceObject *device;
- uint32_t busNum;
- uint32_t numCs;
- uint32_t curCs;
- struct OsalMutex lock;
- struct SpiCntlrMethod *method;
- struct DListHead list;
- void *priv;
- };
- ```
-
- - Instantiate the callback function structure **SpiCntlrMethod** in **SpiCntlr**. Other members are initialized by using the **Init** function.
-
- ```
- // Example in spi_hi35xx.c: instantiate the hook.
- struct SpiCntlrMethod g_method = {
- .Transfer = Pl022Transfer,
- .SetCfg = Pl022SetCfg,
- .GetCfg = Pl022GetCfg,
- .Open = Pl022Open,
- .Close = Pl022Close,
- };
- ```
-
- - Bind function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
-
- Return values:
-
- HDF\_STATUS
-
- Function description:
-
- Associates the **SpiCntlr** object with **HdfDeviceObject**.
-
- ```
- static int32_t HdfSpiDeviceBind(struct HdfDeviceObject *device)
- {
- ...
- return (SpiCntlrCreate(device) == NULL) ? HDF_FAILURE : HDF_SUCCESS;
- }
-
- struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device)
- {
- struct SpiCntlr *cntlr = NULL; // Create the SpiCntlr object of the core layer.
- ...
- cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr));// Allocate memory.
- ...
- cntlr->device = device; // Enable conversion between HdfDeviceObject and SpiCntlr.
- device->service = &(cntlr->service); // Enable conversion between HdfDeviceObject and SpiCntlr.
- (void)OsalMutexInit(&cntlr->lock); // Initialize the lock.
- DListHeadInit(&cntlr->list); // Add the corresponding node.
- cntlr->priv = NULL;
- return cntlr;
- }
- ```
-
- - Init function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
-
- Return values:
-
- HDF\_STATUS \(The following table lists some status. For details about other status, see **HDF\_STATUS** in the **/drivers/framework/include/utils/hdf\_base.h** file.\)
-
- **Table 2** Input parameters and return values of the init function
-
-
- Status (Value)
- |
- Description
- |
-
-
- HDF_ERR_INVALID_OBJECT
- |
- Invalid controller object
- |
-
- HDF_ERR_MALLOC_FAIL
- |
- Failed to allocate memory
- |
-
- HDF_ERR_INVALID_PARAM
- |
- Invalid parameter
- |
-
- HDF_ERR_IO
- |
- I/O error
- |
-
- HDF_SUCCESS
- |
- Initialization successful
- |
-
- HDF_FAILURE
- |
- Initialization failed
- |
-
-
-
-
- Function description:
-
- Initializes the custom structure object and **SpiCntlr**.
-
- ```
- static int32_t HdfSpiDeviceInit(struct HdfDeviceObject *device)
- {
- int32_t ret;
- struct SpiCntlr *cntlr = NULL;
- ...
- cntlr = SpiCntlrFromDevice(device);// Forcibly convert HdfDeviceObject to SpiCntlr by using service. For details about the value assignment, see the Bind function.
- //return (device == NULL) ? NULL : (struct SpiCntlr *)device->service;
- ...
- ret = Pl022Init(cntlr, device);// (Mandatory) Instantiate the operation object customized by the vendor. The following is an example:
- ...
- ret = Pl022Probe(cntlr->priv);
- ...
- return ret;
- }
-
- static int32_t Pl022Init(struct SpiCntlr *cntlr, const struct HdfDeviceObject *device)
- {
- int32_t ret;
- struct Pl022 *pl022 = NULL;
- ...
- pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022));// Apply for memory.
- ...
- ret = SpiGetBaseCfgFromHcs(pl022, device->property); // Initialize busNum, numCs, speed, fifoSize, clkRate, mode, bitsPerWord, and transferMode.
- ...
- ret = SpiGetRegCfgFromHcs(pl022, device->property); // Initialize regBase, phyBase, irqNum, regCrg, clkEnBit ,clkRstBit, regMiscCtrl, miscCtrlCs, and miscCtrlCsShift.
- ...
- // Calculate the frequencies corresponding to the maximum and minimum speeds.
- pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN);
- pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX);
- DListHeadInit(&pl022->deviceList);// Initialize the DList linked list.
- pl022->cntlr = cntlr; // Enable conversion between Pl022 and SpiCntlr.
- cntlr->priv = pl022; // Enable conversion between Pl022 and SpiCntlr.
- cntlr->busNum = pl022->busNum; // Assign a value to busNum in SpiCntlr.
- cntlr->method = &g_method; // Connect to the SpiCntlrMethod instance.
- ...
- ret = Pl022CreatAndInitDevice(pl022);
- if (ret != 0) {
- Pl022Release(pl022); // Release the Pl022 object if the initialization fails.
- return ret;
- }
- return 0;
- }
- ```
-
- - Release function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
-
- Return values:
-
- –
-
- Function description:
-
- Releases the memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the corresponding value assignment operations.
-
- ```
- static void HdfSpiDeviceRelease(struct HdfDeviceObject *device)
- {
- struct SpiCntlr *cntlr = NULL;
- ...
- cntlr = SpiCntlrFromDevice(device);// Forcibly convert HdfDeviceObject to SpiCntlr by using service. For details about the value assignment, see the Bind function.
- // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service;
- ...
- if (cntlr->priv != NULL) {
- Pl022Remove((struct Pl022 *)cntlr->priv);// A forced conversion from SpiCntlr to Pl022 is involved.
- }
- SpiCntlrDestroy(cntlr); // Release the Pl022 object.
- }
- ```
\ No newline at end of file
+1. Instantiate the driver entry.
+ - Instantiate the **HdfDriverEntry** structure.
+ - Call **HDF_INIT** to register the **HdfDriverEntry** instance with the HDF.
+
+2. Configure attribute files.
+ - Add the **deviceNode** information to the **device_info.hcs** file.
+ - (Optional) Add the **spi_config.hcs** file.
+
+3. Instantiate the SPI controller object.
+ - Initialize **SpiCntlr**.
+ - Instantiate **SpiCntlrMethod** in the **SpiCntlr** object.
+ >  **NOTE**
+ > For details about the functions in **SpiCntlrMethod**, see [Available APIs](#available-apis).
+
+4. Debug the driver.
+ (Optional) For new drivers, verify the basic functions, such as the SPI status control and response to interrupts.
+
+
+## Development Example
+
+The following uses **spi_hi35xx.c** as an example to present the information required for implementing device functions.
+
+1. Instantiate the driver entry.
The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF framework, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
+ Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
+
+ SPI driver entry example:
+
+ ```
+ struct HdfDriverEntry g_hdfSpiDevice = {
+ .moduleVersion = 1,
+ .moduleName = "HDF_PLATFORM_SPI",// (Mandatory) The value must be the same as that of moduleName in the .hcs file.
+ .Bind = HdfSpiDeviceBind, // See the Bind function.
+ .Init = HdfSpiDeviceInit, // See the Init function.
+ .Release = HdfSpiDeviceRelease, //See the Release function.
+ };
+ // Call HDF_INIT to register the driver entry with the HDF.
+ HDF_INIT(g_hdfSpiDevice);
+ ```
+
+2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **spi_config.hcs** file.
+
+ The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **SpiCntlr** members at the core layer.
+
+ In this example, there is only one SPI controller. If there are multiple SPI controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **spi_config** file for each controller.
+
+ - **device_info.hcs** configuration example
+
+
+ ```
+ root {
+ device_info {
+ match_attr = "hdf_manager";
+ platform :: host {
+ hostName = "platform_host";
+ priority = 50;
+ device_spi :: device { // Configure an HDF device node for each SPI controller.
+ device0 :: deviceNode {
+ policy = 1;
+ priority = 60;
+ permission = 0644;
+ moduleName = "HDF_PLATFORM_SPI";
+ serviceName = "HDF_PLATFORM_SPI_0";
+ deviceMatchAttr = "hisilicon_hi35xx_spi_0";
+ }
+ device1 :: deviceNode {
+ policy = 1;
+ priority = 60;
+ permission = 0644;
+ moduleName = "HDF_PLATFORM_SPI"; // (Mandatory) Driver name, which must be the same as that of moduleName in the driver entry structure.
+ serviceName = "HDF_PLATFORM_SPI_1"; // (Mandatory) Unique name of the service published by the driver.
+ deviceMatchAttr = "hisilicon_hi35xx_spi_1";// The value must be the same as that of match_attr in the .hcs file.
+ }
+ ...
+ }
+ }
+ }
+ }
+ ```
+
+ - **spi_config.hcs** configuration example
+
+
+ ```
+ root {
+ platform {
+ spi_config {// Configure private data for each SPI controller.
+ template spi_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes.
+ serviceName = "";
+ match_attr = "";
+ transferMode = 0; // Data transfer mode. The value **0** indicates interrupt transfer, **1** indicates flow control transfer, and **2** indicates DMA transfer.
+ busNum = 0; // Bus number.
+ clkRate = 100000000;
+ bitsPerWord = 8 // Number of bits per word.
+ mode = 19; // SPI data input/output mode.
+ maxSpeedHz = 0; // Maximum clock frequency.
+ minSpeedHz = 0; // Minimum clock frequency.
+ speed = 2000000; // Current message transfer speed.
+ fifoSize = 256; // FIFO size.
+ numCs = 1; // Chip select (CS) number.
+ regBase = 0x120c0000; // Used for address mapping.
+ irqNum = 100; // Interrupt request (IRQ) number.
+ REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4
+ CRG_SPI_CKEN = 0;
+ CRG_SPI_RST = 0;
+ REG_MISC_CTRL_SPI = 0x12030024; // MISC_REG_BASE(0x12030000) + 0x24
+ MISC_CTRL_SPI_CS = 0;
+ MISC_CTRL_SPI_CS_SHIFT = 0;
+ }
+ controller_0x120c0000 :: spi_controller {
+ busNum = 0; // (Mandatory) Bus number.
+ CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk
+ CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset
+ match_attr = "hisilicon_hi35xx_spi_0";// (Mandatory) The value must be the same as that of deviceMatchAttr in device_info.hcs.
+ }
+ controller_0x120c1000 :: spi_controller {
+ busNum = 1;
+ CRG_SPI_CKEN = 0x20000; // (0x1 << 17) 0:close clk, 1:open clk
+ CRG_SPI_RST = 0x2; // (0x1 << 1) 0:cancel reset, 1:reset
+ match_attr = "hisilicon_hi35xx_spi_1";
+ regBase = 0x120c1000; // (Mandatory) Used for address mapping.
+ irqNum = 101; // (Mandatory) IRQ number.
+ }
+ ...
+ //(Optional) Add nodes to the device_info.hcs file as required.
+ }
+ }
+ }
+ ```
+
+3. Initialize the **SpiCntlr** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **SpiCntlrMethod** in **SpiCntlr** (so that the underlying driver functions can be called).
+ - Defining a custom structure
+
+ To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **spi_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number and bus number, to the **SpiCntlr** object at the core layer.
+
+
+ ```
+ struct Pl022 {// Corresponds to parameters in .hcs.
+ struct SpiCntlr *cntlr;
+ struct DListHead deviceList;
+ struct OsalSem sem;
+ volatile unsigned char *phyBase;
+ volatile unsigned char *regBase;
+ uint32_t irqNum;
+ uint32_t busNum;
+ uint32_t numCs;
+ uint32_t curCs;
+ uint32_t speed;
+ uint32_t fifoSize;
+ uint32_t clkRate;
+ uint32_t maxSpeedHz;
+ uint32_t minSpeedHz;
+ uint32_t regCrg;
+ uint32_t clkEnBit;
+ uint32_t clkRstBit;
+ uint32_t regMiscCtrl;
+ uint32_t miscCtrlCsShift;
+ uint32_t miscCtrlCs;
+ uint16_t mode;
+ uint8_t bitsPerWord;
+ uint8_t transferMode;
+ };
+
+ // SpiCntlr is the core layer controller structure. The Init function assigns values to the members of SpiCntlr.
+ struct SpiCntlr {
+ struct IDeviceIoService service;
+ struct HdfDeviceObject *device;
+ uint32_t busNum;
+ uint32_t numCs;
+ uint32_t curCs;
+ struct OsalMutex lock;
+ struct SpiCntlrMethod *method;
+ struct DListHead list;
+ void *priv;
+ };
+ ```
+
+ - Instantiating **SpiCntlrMethod** in **SpiCntlr** (other members are initialized by **Init**)
+
+
+ ```
+ // Example in spi_hi35xx.c: instantiate the hooks.
+ struct SpiCntlrMethod g_method = {
+ .Transfer = Pl022Transfer,
+ .SetCfg = Pl022SetCfg,
+ .GetCfg = Pl022GetCfg,
+ .Open = Pl022Open,
+ .Close = Pl022Close,
+ };
+ ```
+
+ - **Bind** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
+
+ Return value:
+
+ HDF_STATUS
+
+ Function description:
+
+ Associates the **SpiCntlr** object with **HdfDeviceObject**.
+
+
+ ```
+ static int32_t HdfSpiDeviceBind(struct HdfDeviceObject *device)
+ {
+ ...
+ return (SpiCntlrCreate(device) == NULL) ? HDF_FAILURE : HDF_SUCCESS;
+ }
+
+ struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device)
+ {
+ struct SpiCntlr *cntlr = NULL; // Create the SpiCntlr object at the core layer.
+ ...
+ cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr));// Allocate memory.
+ ...
+ cntlr->device = device; // Prerequisites for conversion between HdfDeviceObject and SpiCntlr.
+ device->service = &(cntlr->service); // Prerequisites for conversion between HdfDeviceObject and SpiCntlr.
+ (void)OsalMutexInit(&cntlr->lock); // Initialize the lock.
+ DListHeadInit(&cntlr->list); // Add the corresponding nodes.
+ cntlr->priv = NULL;
+ return cntlr;
+ }
+ ```
+
+ - **Init** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
+
+ Return value:
+
+ HDF_STATUS
+
+ The table below lists some status. For more information, see **HDF_STATUS** in the /drivers/framework/include/utils/hdf_base.h file.
+
+ **Table 2** HDF_STATUS
+
+ | Status| Description|
+ | -------- | -------- |
+ | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
+ | HDF_ERR_MALLOC_FAIL | Failed to allocate memory.|
+ | HDF_ERR_INVALID_PARAM | Invalid parameter.|
+ | HDF_ERR_IO | I/O error.|
+ | HDF_SUCCESS | Initialization successful.|
+ | HDF_FAILURE | Initialization failed.|
+
+ Function description:
+
+ Initializes the custom structure object and **SpiCntlr**.
+
+
+ ```
+ static int32_t HdfSpiDeviceInit(struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ struct SpiCntlr *cntlr = NULL;
+ ...
+ cntlr = SpiCntlrFromDevice(device); // Use service to forcibly convert HdfDeviceObject to SpiCntlr. For details about the value assignment, see the Bind function.
+ // return (device == NULL) ? NULL : (struct SpiCntlr *)device->service;
+ ...
+ ret = Pl022Init(cntlr, device); // (Mandatory) Instantiate the operation object customized by the vendor. The following is an example:
+ ...
+ ret = Pl022Probe(cntlr->priv);
+ ...
+ return ret;
+ }
+
+ static int32_t Pl022Init(struct SpiCntlr *cntlr, const struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ struct Pl022 *pl022 = NULL;
+ ...
+ pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022));// Request memory.
+ ...
+ ret = SpiGetBaseCfgFromHcs(pl022, device->property); // Initialize busNum, numCs, speed, fifoSize, clkRate, mode, bitsPerWord, and transferMode.
+ ...
+ ret = SpiGetRegCfgFromHcs(pl022, device->property); // Initialize regBase, phyBase, irqNum, regCrg, clkEnBit, clkRstBit, regMiscCtrl, miscCtrlCs, and miscCtrlCsShift.
+ ...
+ // Calculate the frequencies corresponding to the maximum and minimum speeds.
+ pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN);
+ pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX);
+ DListHeadInit(&pl022->deviceList);// Initialize the DList linked list.
+ pl022->cntlr = cntlr; // Prerequisite for conversion between Pl022 and SpiCntlr.
+ cntlr->priv = pl022; // Prerequisite for conversion between Pl022 and SpiCntlr.
+ cntlr->busNum = pl022->busNum; // Assign a value to busNum in SpiCntlr.
+ cntlr->method = &g_method; // Attach the SpiCntlrMethod instance.
+ ...
+ ret = Pl022CreatAndInitDevice(pl022);
+ if (ret != 0) {
+ Pl022Release(pl022); // Release the Pl022 object if the initialization fails.
+ return ret;
+ }
+ return 0;
+ }
+ ```
+
+ - **Release** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
+
+ Return value:
+
+ No value is returned.
+
+ Function description:
+
+ Releases the memory and deletes the controller. This function assigns values to the **Release** function in the driver entry structure. If the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the value assignment operations.
+
+
+ ```
+ static void HdfSpiDeviceRelease(struct HdfDeviceObject *device)
+ {
+ struct SpiCntlr *cntlr = NULL;
+ ...
+ cntlr = SpiCntlrFromDevice(device); // Use service to forcibly convert HdfDeviceObject to SpiCntlr. For details about the value assignment, see the Bind function.
+ // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service;
+ ...
+ if (cntlr->priv != NULL) {
+ Pl022Remove((struct Pl022 *)cntlr->priv);// A forced conversion from SpiCntlr to Pl022 is involved.
+ }
+ SpiCntlrDestroy(cntlr); // Release the Pl022 object.
+ }
+ ```
diff --git a/en/device-dev/driver/figures/spi-controller-device-connection.png b/en/device-dev/driver/figures/spi-controller-device-connection.png
index 96f68d24918dacf9244e0ad020f2e99d77f589c4..7a467a4d7278415cbd1174706b12cb9f598369b8 100644
Binary files a/en/device-dev/driver/figures/spi-controller-device-connection.png and b/en/device-dev/driver/figures/spi-controller-device-connection.png differ
diff --git a/en/device-dev/kernel/kernel-basic-mini-time.md b/en/device-dev/kernel/kernel-basic-mini-time.md
index 586349d0c4683c5b782b61ea2cd0b714e7b1b4b1..375e481f4c04354b83d1e043cac3d3f7f0a83c0c 100644
--- a/en/device-dev/kernel/kernel-basic-mini-time.md
+++ b/en/device-dev/kernel/kernel-basic-mini-time.md
@@ -1,8 +1,7 @@
-# Time Management
+# Time Management
-
-## Basic Concepts
+## Basic Concepts
Time management provides all time-related services for applications based on the system clock.
@@ -12,67 +11,79 @@ People use second or millisecond as the time unit, while the operating system us
The time management module of the OpenHarmony LiteOS-M kernel provides time conversion and statistics functions.
-## Time Unit
-- Cycle
+## Time Unit
+
+- Cycle
+
+ Cycle is the minimum time unit in the system. The cycle duration is determined by the system clock frequency, that is, the number of cycles per second.
+- Tick
+
+ Tick is the basic time unit of the operating system and is determined by the number of ticks per second configured by the user.
- Cycle is the minimum time unit in the system. The cycle duration is determined by the system clock frequency, that is, the number of cycles per second.
-- Tick
+## Available APIs
- Tick is the basic time unit of the operating system and is determined by the number of ticks per second configured by the user.
+The following table describes APIs available for OpenHarmony LiteOS-M time management. For more details about the APIs, see the API reference.
+**Table 1** APIs of the time management module
-## Available APIs
+| API| Description|
+| -------- | -------- |
+| LOS_MS2Tick | Converts milliseconds into ticks.|
+| LOS_Tick2MS | Converts ticks into milliseconds.|
+| OsCpuTick2MS | Converts cycles into milliseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
+| OsCpuTick2US | Converts cycles into microseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
-The following table describes APIs available for the OpenHarmony LiteOS-M time management. For more details about the APIs, see the API reference.
+**Table 2** APIs for time statistics
-**Table 1** APIs of the time management module
+| API| Description|
+| -------- | -------- |
+| LOS_SysClockGet | Obtains the system clock.|
+| LOS_TickCountGet | Obtains the number of ticks since the system starts.|
+| LOS_CyclePerTickGet | Obtains the number of cycles for each tick.|
-| Category| API| Description|
-| -------- | -------- | -------- |
-| Time conversion| LOS_MS2Tick | Converts milliseconds into ticks.|
-| | LOS_Tick2MS | Converts ticks into milliseconds.|
-| | OsCpuTick2MS | Converts cycles into milliseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
-| | OsCpuTick2US | Converts cycles into microseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
-| Time statistics| LOS_SysClockGet | Obtains the system clock.|
-| | LOS_TickCountGet | Obtains the number of ticks since the system starts.|
-| | LOS_CyclePerTickGet | Obtains the number of cycles for each tick.|
-| | LOS_CurrNanosec |Obtains the number of nanoseconds since the system starts.|
-| Delay management| LOS_UDelay |Performs busy waiting in μs, which can be preempted by a task with a higher priority.|
-| | LOS_MDelay |Performs busy waiting in ms, which can be preempted by a task with a higher priority.|
-## How to Develop
+## How to Develop
The typical development process of time management is as follows:
-1. Complete board configuration and adaptation as required, and configure the system clock frequency \(**OS\_SYS\_CLOCK** in Hz and **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND**\). The default value of **OS\_SYS\_CLOCK** varies with the hardware platform.
-2. Call the clock conversion and statistics APIs.
+1. Complete board configuration and adaptation as required, and configure the system clock frequency (**OS_SYS_CLOCK** in Hz and **LOSCFG_BASE_CORE_TICK_PER_SECOND**). The default value of **OS_SYS_CLOCK** varies with the hardware platform.
-> **NOTE**
+2. Call the clock conversion and statistics APIs.
+
+> **NOTE**
>
->- The time management module depends on **OS\_SYS\_CLOCK** and **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND**.
->- The number of system ticks is not counted when the interrupt feature is disabled. Therefore, the number of ticks cannot be used as the accurate time.
->- The configuration options are maintained in the **target\_config.h** file of the development board project.
+> - The time management module depends on **OS_SYS_CLOCK** and **LOSCFG_BASE_CORE_TICK_PER_SECOND**.
+>
+> - The number of system ticks is not counted when the interrupt feature is disabled. Therefore, the number of ticks cannot be used as the accurate time.
+>
+> - The configuration options are maintained in the **target_config.h** file of the development board project.
+
-## Development Example
+## Development Example
-### Example Description
+
+### Example Description
The following example describes basic time management methods, including:
- Time conversion: convert milliseconds to ticks or convert ticks to milliseconds.
+
- Time statistics: obtain the number of cycles per tick, number of ticks since system startup, and number of delayed ticks.
-### Sample Code
+
+### Sample Code
Prerequisites
-- The default value of **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND** is **100**.
-- The system clock frequency **OS\_SYS\_CLOCK** is configured.
+- The default value of **LOSCFG_BASE_CORE_TICK_PER_SECOND** is **100**.
+
+- The system clock frequency **OS_SYS_CLOCK** is configured.
Time conversion:
+
```
VOID Example_TransformTime(VOID)
{
@@ -88,6 +99,7 @@ VOID Example_TransformTime(VOID)
Time statistics and delay:
+
```
VOID Example_GetTime(VOID)
{
@@ -112,12 +124,14 @@ VOID Example_GetTime(VOID)
}
```
-### Verification
+
+### Verification
The development is successful if the return result is as follows:
Time conversion:
+
```
tick = 1000
ms = 1000
@@ -125,6 +139,7 @@ ms = 1000
Time statistics and delay:
+
```
LOS_CyclePerTickGet = 495000
LOS_TickCountGet = 1
diff --git a/en/device-dev/kernel/kernel-mini-basic-soft.md b/en/device-dev/kernel/kernel-mini-basic-soft.md
index ec8e10ec130d2feb0d5c931b1ffbcccca56a7818..e6bb601669fcc6fd7403c25ccea520323eeea70d 100644
--- a/en/device-dev/kernel/kernel-mini-basic-soft.md
+++ b/en/device-dev/kernel/kernel-mini-basic-soft.md
@@ -1,5 +1,6 @@
# Software Timer
+
## Basic Concepts
The software timer is a software-simulated timer based on system tick interrupts. When the preset tick counter value has elapsed, the user-defined callback will be invoked. The timing precision is related to the cycle of the system tick clock.
@@ -8,144 +9,132 @@ Due to the limitation in hardware, the number of hardware timers cannot meet use
The software timer supports the following functions:
-- Disabling the software timer using a macro
-- Creating a software timer
-- Starting a software timer
-- Stopping a software timer
-- Deleting a software timer
-- Obtaining the number of remaining ticks of a software timer
+- Disabling the software timer using a macro
-## Working Principles
+- Creating a software timer
-The software timer is a system resource. When modules are initialized, a contiguous section of memory is allocated for software timers. The maximum number of timers supported by the system is configured by the **LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT** macro in **los\_config.h**.
+- Starting a software timer
-Software timers use a queue and a task resource of the system. The software timers are triggered based on the First In First Out \(FIFO\) rule. A timer with a shorter value is always closer to the queue head than a timer with a longer value, and is preferentially triggered.
+- Stopping a software timer
-The software timer counts time in ticks. When a software timer is created and started, the OpenHarmony LiteOS-M kernel determines the timer expiry time based on the current system time \(in ticks\) and the timing interval set by the user, and adds the timer control structure to the global timing list.
+- Deleting a software timer
-When a tick interrupt occurs, the tick interrupt handler scans the global timing list for expired timers. If such timers are found, the timers are recorded.
+- Obtaining the number of remaining ticks of a software timer
-When the tick interrupt handling function is complete, the software timer task \(with the highest priority\) is woken up. In this task, the timeout callback function for the recorded timer is called.
-### Timer States
+## Working Principles
-- OS\_SWTMR\_STATUS\_UNUSED
+The software timer is a system resource. When modules are initialized, a contiguous section of memory is allocated for software timers. The maximum number of timers supported by the system is configured by the **LOSCFG_BASE_CORE_SWTMR_LIMIT** macro in **los_config.h**.
- The timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state.
+Software timers use a queue and a task resource of the system. The software timers are triggered based on the First In First Out (FIFO) rule. A timer with a shorter value is always closer to the queue head than a timer with a longer value, and is preferentially triggered.
+The software timer counts time in ticks. When a software timer is created and started, the OpenHarmony LiteOS-M kernel determines the timer expiry time based on the current system time (in ticks) and the timing interval set by the user, and adds the timer control structure to the global timing list.
-- OS\_SWTMR\_STATUS\_CREATED
+When a tick interrupt occurs, the tick interrupt handler scans the global timing list for expired timers. If such timers are found, the timers are recorded.
- The timer is created but not started or the timer is stopped. When **LOS\_SwtmrCreate** is called for a timer that is not in use or **LOS\_SwtmrStop** is called for a newly started timer, the timer changes to this state.
+When the tick interrupt handling function is complete, the software timer task (with the highest priority) is woken up. In this task, the timeout callback function for the recorded timer is called.
-- OS\_SWTMR\_STATUS\_TICKING
+### Timer States
- The timer is running \(counting\). When **LOS\_SwtmrStart** is called for a newly created timer, the timer enters this state.
+- OS_SWTMR_STATUS_UNUSED
+
+ The timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state.
+- OS_SWTMR_STATUS_CREATED
+
+ The timer is created but not started or the timer is stopped. When **LOS_SwtmrCreate** is called for a timer that is not in use or **LOS_SwtmrStop** is called for a newly started timer, the timer changes to this state.
+
+- OS_SWTMR_STATUS_TICKING
+
+ The timer is running (counting). When **LOS_SwtmrStart** is called for a newly created timer, the timer enters this state.
-### Timer Modes
+### Timer Modes
-The OpenHarmony LiteOS-M kernel provides three types of software timers:
+The OpenHarmony LiteOS-M kernel provides the following types of software timers:
+
+- One-shot timer: Once started, the timer is automatically deleted after triggering only one timer event.
+
+- Periodic timer: This type of timer periodically triggers timer events until it is manually stopped.
+
+- One-shot timer deleted by calling an API
-- One-shot timer: Once started, the timer is automatically deleted after triggering only one timer event.
-- Periodic timer: This type of timer periodically triggers timer events until it is manually stopped.
-- One-shot timer deleted by calling an API
## Available APIs
The following table describes APIs available for the OpenHarmony LiteOS-M software timer module. For more details about the APIs, see the API reference.
-**Table 1** Software timer APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Creating or deleting timers
- |
-LOS_SwtmrCreate
- |
-Creates a software timer.
- |
-
-LOS_SwtmrDelete
- |
-Deletes a software timer.
- |
-
-Starting or stopping timers
- |
-LOS_SwtmrStart
- |
-Starts a software timer.
- |
-
-LOS_SwtmrStop
- |
-Stop a software timer.
- |
-
-Obtaining remaining ticks of a software timer
- |
-LOS_SwtmrTimeGet
- |
-Obtaining remaining ticks of a software timer
- |
-
-
-
+ **Table 1** Software timer APIs
+
+| API| Description|
+| -------- | -------- |
+| LOS_SwtmrCreate| Creates a timer.|
+| LOS_SwtmrDelete| Deletes a timer.|
+| LOS_SwtmrStart| Starts a timer.|
+| LOS_SwtmrStop| Stops a timer.|
+| LOS_SwtmrTimeGet| Obtains the remaining ticks of a software timer.|
+
## How to Develop
The typical development process of software timers is as follows:
-1. Configure the software timer.
- - Check that **LOSCFG\_BASE\_CORE\_SWTMR** and **LOSCFG\_BASE\_IPC\_QUEUE** are set to **1**.
- - Configure **LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT** \(maximum number of software timers supported by the system\).
- - Configure **OS\_SWTMR\_HANDLE\_QUEUE\_SIZE** \(maximum length of the software timer queue\).
+1. Configure the software timer.
+ - Check that **LOSCFG_BASE_CORE_SWTMR** and **LOSCFG_BASE_IPC_QUEUE** are set to **1**.
+ - Configure **LOSCFG_BASE_CORE_SWTMR_LIMIT** (maximum number of software timers supported by the system).
+ - Configure **OS_SWTMR_HANDLE_QUEUE_SIZE** (maximum length of the software timer queue).
+
+2. Call **LOS_SwtmrCreate** to create a software timer.
+ - Create a software timer with the specified timing duration, timeout handling function, and triggering mode.
+ - Return the function execution result (success or failure).
-2. Call **LOS\_SwtmrCreate** to create a software timer.
- - Create a software timer with the specified timing duration, timeout handling function, and triggering mode.
- - Return the function execution result \(success or failure\).
+3. Call **LOS_SwtmrStart** to start the software timer.
-3. Call **LOS\_SwtmrStart** to start the software timer.
-4. Call **LOS\_SwtmrTimeGet** to obtain the remaining number of ticks of the software timer.
-5. Call **LOS\_SwtmrStop** to stop the software timer.
-6. Call **LOS\_SwtmrDelete** to delete the software timer.
+4. Call **LOS_SwtmrTimeGet** to obtain the remaining number of ticks of the software timer.
+
+5. Call **LOS_SwtmrStop** to stop the software timer.
+
+6. Call **LOS_SwtmrDelete** to delete the software timer.
+
+> **NOTE**
+> - Avoid too many operations in the callback function of the software timer. Do not use APIs or perform operations that may cause task suspension or blocking.
+>
+> - The software timers use a queue and a task resource of the system. The priority of the software timer tasks is set to **0** and cannot be changed.
+>
+> - The number of software timer resources that can be configured in the system is the total number of software timer resources available to the entire system, not the number of software timer resources available to users. For example, if the system software timer occupies one more resource, the number of software timer resources available to users decreases by one.
+>
+> - If a one-shot software timer is created, the system automatically deletes the timer and reclaims resources after the timer times out and the callback function is executed.
+>
+> - For a one-shot software timer that will not be automatically deleted after expiration, you need to call **LOS_SwtmrDelete** to delete it and reclaim the timer resource to prevent resource leakage.
-> **NOTE**
->- Avoid too many operations in the callback function of the software timer. Do not use APIs or perform operations that may cause task suspension or blocking.
->- The software timers use a queue and a task resource of the system. The priority of the software timer tasks is set to **0** and cannot be changed.
->- The number of software timer resources that can be configured in the system is the total number of software timer resources available to the entire system, not the number of software timer resources available to users. For example, if the system software timer occupies one more resource, the number of software timer resources available to users decreases by one.
->- If a one-shot software timer is created, the system automatically deletes the timer and reclaims resources after the timer times out and the callback function is executed.
->- For a one-shot software timer that will not be automatically deleted after expiration, you need to call **LOS\_SwtmrDelete** to delete it and reclaim the timer resource to prevent resource leakage.
## Development Example
+
### Example Description
The following programming example demonstrates how to:
-1. Create, start, delete, pause, and restart a software timer.
-2. Use a one-shot software timer and a periodic software timer
+1. Create, start, delete, pause, and restart a software timer.
+
+2. Use a one-shot software timer and a periodic software timer
+
### Sample Code
Prerequisites
-- In **los\_config.h**, **LOSCFG\_BASE\_CORE\_SWTMR** is enabled.
-- In **los\_config.h**, **LOSCFG\_BASE\_CORE\_SWTMR\_ALIGN** is disabled. The sample code does not involve timer alignment.
-- The maximum number of software timers supported by the system \(**LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT**\) is configured.
-- The maximum length of the software timer queue \(OS\_SWTMR\_HANDLE\_QUEUE\_SIZE\) is configured.
+- In **los_config.h**, **LOSCFG_BASE_CORE_SWTMR** is enabled.
+
+- In **los_config.h**, **LOSCFG_BASE_CORE_SWTMR_ALIGN** is disabled. The sample code does not involve timer alignment.
+
+- The maximum number of software timers supported by the system (**LOSCFG_BASE_CORE_SWTMR_LIMIT**) is configured.
+
+- The maximum length of the software timer queue (OS_SWTMR_HANDLE_QUEUE_SIZE) is configured.
The sample code is as follows:
+
```
#include "los_swtmr.h"
@@ -156,7 +145,7 @@ UINT32 g_timerCount2 = 0;
/* Task ID*/
UINT32 g_testTaskId01;
-void Timer1_Callback(UINT32 arg) //Callback function 1
+void Timer1_Callback(UINT32 arg) //Callback 1
{
UINT32 tick_last1;
g_timerCount1++;
@@ -164,7 +153,7 @@ void Timer1_Callback(UINT32 arg) //Callback function 1
printf("g_timerCount1=%d, tick_last1=%d\n", g_timerCount1, tick_last1);
}
-void Timer2_Callback(UINT32 arg) //Callback function 2
+void Timer2_Callback(UINT32 arg) //Callback 2
{
UINT32 tick_last2;
tick_last2 = (UINT32)LOS_TickCountGet();
@@ -237,10 +226,12 @@ UINT32 Example_TaskEntry(VOID)
}
```
+
### Verification
The output is as follows:
+
```
create Timer1 success
start Timer1 success
@@ -261,4 +252,3 @@ g_timerCount2=9 tick_last2=2113
g_timerCount2=10 tick_last2=2213
delete Timer2 success
```
-
diff --git a/en/device-dev/kernel/kernel-mini-basic-task.md b/en/device-dev/kernel/kernel-mini-basic-task.md
index b431d06f674446fe4d0ac7c990eea128d641f7af..e2b71e961f6335ce9da5485e8b025b0df88e7308 100644
--- a/en/device-dev/kernel/kernel-mini-basic-task.md
+++ b/en/device-dev/kernel/kernel-mini-basic-task.md
@@ -1,65 +1,68 @@
# Task Management
+
## Basic Concepts
From the perspective of the operating system, tasks are the minimum running units that compete for system resources. They can use or wait for CPUs, use system resources such as memory, and run independently.
The task module of the OpenHarmony LiteOS-M provides multiple tasks and supports switching between tasks, helping users manage business process procedures. The task module has the following features:
-- Multiple tasks are supported.
-- A task represents a thread.
-- The preemptive scheduling mechanism is used for tasks. High-priority tasks can interrupt low-priority tasks. Low-priority tasks can be scheduled only after high-priority tasks are blocked or complete.
-- Time slice round-robin is used to schedule tasks with the same priority.
-- A total of 32 \(**0** to **31**\) priorities are defined. **0** is the highest priority, and **31** is the lowest.
-
-### Task-related Concepts
-
-**Task States**
-
-A task has multiple states. After the system initialization is complete, the created tasks can compete for certain resources in the system according to the scheduling procedure regulated by the kernel.
-
-A task can be in any of the following states:
-
-- Ready: The task is in the ready queue, waiting for execution by a CPU.
-- Running: The task is being executed.
-- Blocked: The task is not in the ready queue. The task may be suspended, delayed, waiting for a semaphore, waiting to read from or write into a queue, or reading from or writing into an event.
-- Dead: The task execution is complete and waiting for the system to reclaim resources.
-
-**Task State Transitions**
-
-**Figure 1** Task state transitions
-
-
-The task transition process is as follows:
+- Multiple tasks are supported.
-- Ready → Running
+- A task represents a thread.
- A task enters Ready state once created. When task switching occurs, the task with the highest priority in the Ready queue will be executed. The task being executed enters the Running state and is removed from the Ready queue.
+- The preemptive scheduling mechanism is used for tasks. High-priority tasks can interrupt low-priority tasks. Low-priority tasks can be scheduled only after high-priority tasks are blocked or complete.
-- Running → Blocked
+- Time slice round-robin is used to schedule tasks with the same priority.
- When a running task is blocked \(suspended, delayed, or reading semaphores\), it will be inserted to the blocked task queue and changes from the Running state to the Blocked state. Then, task switching is triggered to run the task with the highest priority in the Ready queue.
+- A total of 32 (**0** to **31**) priorities are defined. **0** is the highest priority, and **31** is the lowest.
-- Blocked → Ready \(Blocked → Running\)
- When a blocked task is recovered \(for example, the task is resumed, the delay period or semaphore read period times out, or the task successfully reads a semaphore\), the task will be added to the Ready queue and change from the Blocked state to the Ready state. If the priority of the recovered task is higher than that of the running task, task switching will be triggered to run the recovered task. Then, the task changes from the Ready state to the Running state.
+### Task-related Concepts
-- Ready → Blocked
+**Task States**
- When a task in the Ready state is blocked \(suspended\), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
+A task has multiple states. After the system initialization is complete, the created tasks can compete for certain resources in the system according to the scheduling procedure regulated by the kernel.
-- Running → Ready
+A task can be in any of the following states:
- When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and remains in the Ready queue.
+- Ready: The task is in the ready queue, waiting for execution by a CPU.
-- Running → Dead
+- Running: The task is being executed.
- When a running task is complete, it changes to the Dead state. The Dead state includes normal exit state as the task is complete and the Invalid state. For example, if a task is complete but is not automatically deleted, the task is in the Invalid state.
+- Blocked: The task is not in the ready queue. The task may be suspended, delayed, waiting for a semaphore, waiting to read from or write into a queue, or reading from or writing into an event.
-- Blocked → Dead
+- Dead: The task execution is complete and waiting for the system to reclaim resources.
- If an API is called to delete a blocked task, the task state change from Blocked to Dead.
+**Task State Transitions**
+**Figure 1** Task state transition
+
+ 
+
+The task state transition process is as follows:
+
+- Ready → Running
+
+ A task enters Ready state once created. When task switching occurs, the task with the highest priority in the Ready queue will be executed. The task being executed enters the Running state and is removed from the Ready queue.
+- Running → Blocked
+
+ When a running task is blocked (suspended, delayed, or reading semaphores), it will be inserted to the blocked task queue and changes from the Running state to the Blocked state. Then, task switching is triggered to run the task with the highest priority in the Ready queue.
+- Blocked → Ready (Blocked → Running)
+
+ When a blocked task is recovered (for example, the task is resumed, the delay period or semaphore read period times out, or the task successfully reads a semaphore), the task will be added to the Ready queue and change from the Blocked state to the Ready state. If the priority of the recovered task is higher than that of the running task, task switching will be triggered to run the recovered task. Then, the task changes from the Ready state to the Running state.
+- Ready → Blocked
+
+ When a task in the Ready state is blocked (suspended), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
+- Running → Ready
+
+ When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and remains in the Ready queue.
+- Running → Dead
+
+ When a running task is complete, it changes to the Dead state. The Dead state includes normal exit state as the task is complete and the Invalid state. For example, if a task is complete but is not automatically deleted, the task is in the Invalid state.
+- Blocked → Dead
+
+ If an API is called to delete a blocked task, the task state change from Blocked to Dead.
**Task ID**
@@ -83,81 +86,84 @@ Resources, such as registers, used during the running of a task. When a task is
**Task Control Block**
-Each task has a task control block \(TCB\). A TCB contains task information, such as context stack pointer, state, priority, ID, name, and stack size. The TCB reflects the running status of a task.
+Each task has a task control block (TCB). A TCB contains task information, such as context stack pointer, state, priority, ID, name, and stack size. The TCB reflects the running status of a task.
**Task Switching**
Task switching involves actions, such as obtaining the task with the highest priority in the Ready queue, saving the context of the switched-out task, and restoring the context of the switched-in task.
-### Task Running Mechanism
+
+### Task Running Mechanism
When a task is created, the system initializes the task stack and presets the context. The system places the task entry function in the corresponding position so that the function is executed when the task enters the running state for the first time.
+
## Available APIs
The following table describes APIs available for the OpenHarmony LiteOS-M task module. For more details about the APIs, see the API reference.
-**Table 1** APIs of the task management module
-
-| Category| API| Description|
-| -------- | -------- | -------- |
-| Creating or deleting a task| LOS_TaskCreateOnly | Creates a task and suspends the task to disable scheduling of the task. To enable scheduling of the task, call **LOS_TaskResume** to make the task enter the Ready state.|
-| | LOS_TaskCreate | Creates a task and places the task in the Ready state. If there is no task with a higher priority in the Ready queue, the task will be executed.|
-| | LOS_TaskDelete | Deletes a task.|
-| Controlling task status| LOS_TaskResume | Resumes a suspended task to place it in the Ready state.|
-| | LOS_TaskSuspend | Suspends the specified task and performs task switching.|
-| | LOS_TaskJoin | Suspends this task till the specified task is complete and the task control block resources are reclaimed.|
-| | LOS_TaskDetach | Changes the task attribute from **joinable** to **detach**. After the task of the **detach** attribute is complete, the task control block resources will be automatically reclaimed.|
-| | LOS_TaskDelay | Makes a task wait for a period of time (in ticks) and releases CPU resources. When the delay time expires, the task enters the Ready state again. The input parameter is the number of ticks.|
-| | LOS_Msleep | Converts the input number of milliseconds into number of ticks, and use the result to call **LOS_TaskDelay**.|
-| | LOS_TaskYield | Sets the time slice of the current task to **0** to release CPU resources and schedule the task with the highest priority in the Ready queue to run.|
-| Controlling task scheduling| LOS_TaskLock | Locks task scheduling. However, tasks can still be interrupted.|
-| | LOS_TaskUnlock | Unlocks task scheduling.|
-| | LOS_Schedule | Triggers task scheduling|
-| Controlling task priority| LOS_CurTaskPriSet | Sets the priority for the current task.|
-| | LOS_TaskPriSet | Sets the priority for a specified task.|
-| | LOS_TaskPriGet | Obtains the priority of a specified task.|
-| Obtaining Job information| LOS_CurTaskIDGet | Obtains the ID of the current task.|
-| | LOS_NextTaskIDGet | Obtains the ID of the task with the highest priority in the Ready queue.|
-| | LOS_NewTaskIDGet | Same as **LOS_NextTaskIDGet**.|
-| | LOS_CurTaskNameGet | Obtains the name of the current task.|
-| | LOS_TaskNameGet | Obtains the name of a specified task.|
-| | LOS_TaskStatusGet | Obtains the state of a specified task.|
-| | LOS_TaskInfoGet | Obtains information about a specified task, including the task state, priority, stack size, stack pointer (SP), task entry function, and used stack space.|
-| | LOS_TaskIsRunning | Checks whether the task module has started scheduling.|
-| Updating task information| LOS_TaskSwitchInfoGet | Obtains task switching information. The macro **LOSCFG_BASE_CORE_EXC_TSK_SWITCH** must be enabled.|
-| Reclaiming task stack resources| LOS_TaskResRecycle | Reclaims all task stack resources.|
+ **Table 1** APIs of the task management module
+
+| Category| Description|
+| -------- | -------- |
+| Creating or deleting a task| **LOS_TaskCreateOnly**: creates a task and places the task in the Ready state. If there is no task with a higher priority in the Ready queue, the task will be executed.
**LOS_TaskCreate**: creates a task and places the task in the Ready state. If there is no task with a higher priority in the Ready queue, the task will be executed.
**LOS_TaskDelete**: deletes a task.|
+| Controlling task status| **LOS_TaskResume**: resumes a suspended task to place the task in the Ready state.
**LOS_TaskSuspend**: suspends the specified task and performs task switching.
**LOS_TaskJoin**: suspends this task till the specified task is complete and the task control block resources are reclaimed.
**LOS_TaskDelay**: makes a task wait for a period of time (in ticks) and releases CPU resources. When the delay timer expires, the task enters the Ready state again. The input parameter is the number of ticks.
**LOS_Msleep**: converts the input parameter number of milliseconds into number of ticks, and use the result to call **LOS_TaskDelay**.
**LOS_TaskYield**: sets the time slice of the current task to **0** to release CPU resources and schedule the task with the highest priority in the Ready queue to run.|
+| Controlling task scheduling| **LOS_TaskLock**: locks task scheduling. However, tasks can still be interrupted.
**LOS_TaskUnlock**: unlocks task scheduling.
**LOS_Schedule**: triggers task scheduling.|
+| Controlling task priority| **LOS_CurTaskPriSet**: sets the priority for the current task.
**LOS_TaskPriSet**: sets the priority for a specified task.
**LOS_TaskPriGet**: obtains the priority of a specified task.|
+| Obtaining Job information| **LOS_CurTaskIDGet**: obtains the ID of the current task.
**LOS_NextTaskIDGet**: obtains the ID of the task with the highest priority in the Ready queue.
**LOS_NewTaskIDGet**: equivalent to **LOS_NextTaskIDGet**.
**LOS_CurTaskNameGet**: obtains the name of the current task.
**LOS_TaskNameGet**: obtains the name of a task.
**LOS_TaskStatusGet**: obtains the state of a task.
**LOS_TaskInfoGet**: obtains information about a specified task, including the task state, priority, stack size, stack pointer (SP), task entry function, and used stack space.
**LOS_TaskIsRunning**: checks whether the task module has started scheduling.|
+| Updating task information| **LOS_TaskSwitchInfoGet**: obtains task switching information. The macro **LOSCFG_BASE_CORE_EXC_TSK_SWITCH** must be enabled.|
## How to Develop
The typical development process of the task module is as follows:
-1. Use **LOS\_TaskLock** to lock task scheduling and prevent high-priority tasks from being scheduled.
-2. Use **LOS\_TaskCreate** to create a task.
-3. Use **LOS\_TaskUnlock** to unlock task scheduling so that tasks can be scheduled by priority.
-4. Use **LOS\_TaskDelay** to delay a task.
-5. Use **LOS\_TaskSuspend** to suspend a task.
-6. Use **LOS\_TaskResume** to resume the suspended task.
-
-> **NOTE**
->- Running idle tasks reclaims the TCBs and stacks in the to-be-recycled linked list.
->- The task name is a pointer without memory space allocated. When setting the task name, do not assign the local variable address to the task name pointer.
->- The task stack size is 8-byte aligned. Follow the "nothing more and nothing less" principle while determining the task stack size.
->- A running task cannot be suspended if task scheduling is locked.
->- Idle tasks and software timer tasks cannot be suspended or deleted.
->- In an interrupt handler or when a task is locked, the operation of calling **LOS\_TaskDelay** fails.
->- Locking task scheduling does not disable interrupts. Tasks can still be interrupted while task scheduling is locked.
->- Locking task scheduling must be used together with unlocking task scheduling.
->- Task scheduling may occur while a task priority is being set.
->- The maximum number of tasks that can be set for the operating system is the total number of tasks of the operating system, not the number of tasks available to users. For example, if the system software timer occupies one more task resource, the number of task resources available to users decreases by one.
->- **LOS\_CurTaskPriSet** and **LOS\_TaskPriSet** cannot be used in interrupts or used to modify the priorities of software timer tasks.
->- If the task corresponding to the task ID sent to **LOS\_TaskPriGet** has not been created or the task ID exceeds the maximum number of tasks, **-1** will be returned.
->- Resources such as a mutex or a semaphore allocated to a task must have been released before the task is deleted.
+1. Use **LOS_TaskLock** to lock task scheduling and prevent high-priority tasks from being scheduled.
+
+2. Use **LOS_TaskCreate** to create a task.
+
+3. Use **LOS_TaskUnlock** to unlock task scheduling so that tasks can be scheduled by priority.
+
+4. Use **LOS_TaskDelay** to delay a task.
+
+5. Use **LOS_TaskSuspend** to suspend a task.
+
+6. Use **LOS_TaskResume** to resume the suspended task.
+
+> **NOTE**
+> - Running idle tasks reclaims the TCBs and stacks in the to-be-recycled linked list.
+>
+> - The task name is a pointer without memory space allocated. When setting the task name, do not assign the local variable address to the task name pointer.
+>
+> - The task stack size is 8-byte aligned. Follow the "nothing more and nothing less" principle while determining the task stack size.
+>
+> - A running task cannot be suspended if task scheduling is locked.
+>
+> - Idle tasks and software timer tasks cannot be suspended or deleted.
+>
+> - In an interrupt handler or when a task is locked, the operation of calling **LOS_TaskDelay** fails.
+>
+> - Locking task scheduling does not disable interrupts. Tasks can still be interrupted while task scheduling is locked.
+>
+> - Locking task scheduling must be used together with unlocking task scheduling.
+>
+> - Task scheduling may occur while a task priority is being set.
+>
+> - The maximum number of tasks that can be set for the operating system is the total number of tasks of the operating system, not the number of tasks available to users. For example, if the system software timer occupies one more task resource, the number of task resources available to users decreases by one.
+>
+> - **LOS_CurTaskPriSet** and **LOS_TaskPriSet** cannot be used in interrupts or used to modify the priorities of software timer tasks.
+>
+> - If the task corresponding to the task ID sent to **LOS_TaskPriGet** has not been created or the task ID exceeds the maximum number of tasks, **-1** will be returned.
+>
+> - Resources such as a mutex or a semaphore allocated to a task must have been released before the task is deleted.
+
## Development Example
-This example describes the priority-based task scheduling and use of task-related APIs, including creating, delaying, suspending, and resuming two tasks with different priorities, and locking/unlocking task scheduling. The sample code is as follows:
+This example describes the priority-based task scheduling and use of task-related APIs, including creating, delaying, suspending, and resuming two tasks with different priorities, and locking/unlocking task scheduling.
+
+The sample code is as follows:
+
```
UINT32 g_taskHiId;
@@ -249,7 +255,7 @@ UINT32 Example_TskCaseEntry(VOID)
initParam.pcName = "TaskLo";
initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
- /*Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */
+ /* Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */
ret = LOS_TaskCreate(&g_taskLoId, &initParam);
if (ret != LOS_OK) {
LOS_TaskUnlock();
@@ -271,10 +277,12 @@ UINT32 Example_TskCaseEntry(VOID)
}
```
+
### Verification
The development is successful if the return result is as follows:
+
```
LOS_TaskLock() Success!
Example_TaskHi create Success!
diff --git a/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md b/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md
index 1bf198e1fa337518d06a4062c74a2cf290630b4c..3e6ab8c31e41128a1f15f10a2d396cb74dd7bc7f 100644
--- a/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md
+++ b/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md
@@ -1,17 +1,26 @@
# Dynamic Loading
+
## Basic Concepts
-In small devices with limited hardware resources, dynamic algorithm deployment capability is required to solve the problem that multiple algorithms cannot be deployed at the same time. The LiteOS-M kernel uses the Executable and Linkable Format \(ELF\) loading because it is easy to use and compatible with a wide variety of platforms. The LiteOS-M provides APIs similar to **dlopen** and **dlsym**. Apps can load and unload required algorithm libraries by using the APIs provided by the dynamic loading module. As shown in the following figure, the app obtains the corresponding information output through the API required by the third-party algorithm library. The third-party algorithm library depends on the basic APIs provided by the kernel, such as **malloc**. After the app loads the API and relocates undefined symbols, it can call the API to complete the function. The dynamic loading component supports only the Arm architecture. In addition, the signature and source of the shared library to be loaded must be verified to ensure system security.
+In small devices with limited hardware resources, dynamic algorithm deployment capability is required to allow multiple algorithms to be deployed at the same time. The LiteOS-M kernel uses the Executable and Linkable Format (ELF) loading because it is easy to use and compatible with a wide variety of platforms.
+
+The LiteOS-M provides APIs similar to **dlopen** and **dlsym**. Apps can load and unload required algorithm libraries by using the APIs provided by the dynamic loading module. As shown in the following figure, the app obtains the corresponding information output through the API required by the third-party algorithm library. The third-party algorithm library depends on the basic APIs provided by the kernel, such as **malloc**. After the app loads the API and relocates undefined symbols, it can call the API to complete the function.
+
+The dynamic loading component supports only the Arm architecture. In addition, the signature and source of the shared library to be loaded must be verified to ensure system security.
+
+ **Figure 1** LiteOS-M kernel dynamic loading architecture
+
+ 
-**Figure 1** LiteOS-M kernel dynamic loading architecture
-
## Working Principles
+
### Exporting the Symbol Table
-The kernel needs to proactively expose the API required by the dynamic library when the shared library calls a kernel API, as shown in the following figure. This mechanism compiles the symbol information to the specified section and calls the **SYM\_EXPORT** macro to export information of the specified symbol. The symbol information is described in the structure **SymInfo**. Its members include the symbol name and symbol address information. The macro **SYM\_EXPORT** imports the symbol information to the **.sym.\*** section by using the **\_\_attribute\_\_** compilation attribute.
+The kernel needs to proactively expose the API required by the dynamic library when the shared library calls a kernel API, as shown in the following figure. This mechanism compiles the symbol information to the specified section and calls the **SYM_EXPORT** macro to export information of the specified symbol. The symbol information is described in the structure **SymInfo**, which includes the symbol name and address information. The macro **SYM_EXPORT** imports the symbol information to the **.sym.*** section by using **__attribute__**.
+
```
typedef struct {
@@ -26,12 +35,15 @@ const SymInfo sym_##func __attribute__((section(".sym."#func))) = { \
};
```
-**Figure 2** Exported symbol table information
-
+ **Figure 2** Exported symbol table
+
+ 
+
### Loading an ELF File
-During the loading process, the LOAD section to be loaded to the memory is obtained based on the ELF file handle and the section offset of the program header table. Generally, there are two sections: read-only section and read-write section. You can run the **readelf -l** command to view the LOAD section information of the ELF file. The physical memory is requested according to the related alignment attributes. Then, a code section or a data segment is written into the memory based on the loading base address and an offset of each section.
+The **LOAD** section to be loaded to the memory can be obtained based on the ELF file handle and the section offset of the program header table. Generally, there are two sections: read-only and read-write. You can run the **readelf -l** command to view the LOAD section information of the ELF file. The physical memory is requested according to the related alignment attributes. Then, a code section or a data segment is written into the memory based on the loading base address and an offset of each section.
+
```
$ readelf -l lib.so
@@ -43,8 +55,7 @@ There are 4 program headers, starting at offset 52
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
EXIDX 0x000760 0x00000760 0x00000760 0x00008 0x00008 R 0x4
- LOAD 0x000000 0x00000000 0x00000000 0x0076c 0x0076c R E 0x10000
- LOAD 0x00076c 0x0001076c 0x0001076c 0x0010c 0x00128 RW 0x10000
+ LOAD 0x000000 0x00000000 0x00000000 0x0076c 0x0076c R E 0x10000LOAD 0x00076c 0x0001076c 0x0001076c 0x0010c 0x00128 RW 0x10000
DYNAMIC 0x000774 0x00010774 0x00010774 0x000c8 0x000c8 RW 0x4
Section to Segment mapping:
@@ -55,29 +66,45 @@ Program Headers:
03 .dynamic
```
-**Figure 3** Process of loading an ELF file
-
+ **Figure 3** Process of loading an ELF file
+ 
+
-### ELF File Link
+### ELF File Linking
A relocation table is obtained by using a **.dynamic** section of the ELF file. Each entry that needs to be relocated in the table is traversed. Then, the symbol is searched, based on the symbol name that needs to be relocated, in the shared library and the exported symbol table provided by the kernel. The relocation information is updated based on the symbol found.
-**Figure 4** ELF file linking process
-
+ **Figure 4** ELF file linking process
+
+ 
+
## ELF Specifications
+
### ELF Type
-When compiling a shared library, you can add **-fPIC** \(a compilation option\) to compile location-independent code. The shared library file type is **ET\_DYN**, which can be loaded to any valid address range.
+When compiling a shared library, you can add **-fPIC** (a compilation option) to compile location-independent code. The shared library file type is **ET_DYN**, which can be loaded to any valid address range.
Example: **arm-none-eabi-gcc -fPIC –shared –o lib.so lib.c**
+
### Options for Linking
-1. **-nostdlib**: Do not use the lib library in the compiler when linking.
-2. **-nostartfiles**: Do not use the startup files in the compiler when linking.
-3. **-fPIC**: compiles location-independent shared libraries.
-4. **-z max-page-size=4**: sets the number of alignment bytes of the loadable sections in the binary file to **4**. This setting saves memory and can be used for a dynamic library.
-5. **-mcpu=** specifies the CPU architecture.
+- **-nostdlib**: Do not use the lib library in the compiler when linking.
+
+- **-nostartfiles**: Do not use the startup files in the compiler when linking.
+
+- **-fPIC**: compiles location-independent shared libraries.
+
+- **-z max-page-size=4**: sets the number of alignment bytes of the loadable sections in the binary file to **4**. This setting saves memory and can be used for a dynamic library.
+
+- **-mcpu=** specifies the CPU architecture.
+
+
+## Constraints
+
+- Applications cannot be loaded. Only shared libraries can be loaded.
+- The shared library to be loaded cannot depend on the libc library or other shared libraries in the compiler. It can depend only on the external APIs provided by the kernel (provided by the exported symbol table).
+- This feature depends on the cross compiler and file system.
diff --git a/en/device-dev/kernel/kernel-mini-extend-file-fat.md b/en/device-dev/kernel/kernel-mini-extend-file-fat.md
index 5f191076a6e75743b254e0b8611698de701bb8e0..b7a9bffdd5e106d1afedff3f960b4f29d9b8dca2 100644
--- a/en/device-dev/kernel/kernel-mini-extend-file-fat.md
+++ b/en/device-dev/kernel/kernel-mini-extend-file-fat.md
@@ -1,20 +1,27 @@
# FAT
+
## Basic Concepts
-File Allocation Table \(FAT\) is a file system developed for personal computers. It consists of the DOS Boot Record \(DBR\) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system supports multiple media, especially removable media \(such as USB flash drives, SD cards, and removable hard drives\). The FAT file system ensures good compatibility between embedded devices and desktop systems \(such as Windows and Linux\) and facilitates file management.
+File Allocation Table (FAT) is a file system developed for personal computers. It consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster.
+
+The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system supports multiple media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). The FAT file system ensures good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management.
The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary partition and logical partition.
+
## Development Guidelines
-### Adaptation of Drivers
-The use of the FAT file system requires support from the underlying MultiMediaCard \(MMC\) drivers. To run FatFS on a board with an MMC storage device, you must:
+### Driver Adaptation
+
+The use of the FAT file system requires support from the underlying MultiMedia Card (MMC) drivers. To run FatFS on a board with an MMC storage device, you must:
-1. Implement the **disk\_status**, **disk\_initialize**, **disk\_read**, **disk\_write**, and **disk\_ioctl** APIs to adapt to the embedded MMC \(eMMC\) drivers on the board.
+1. Implement the **disk_status**, **disk_initialize**, **disk_read**, **disk_write**, and **disk_ioctl** APIs to adapt to the embedded MMC (eMMC) drivers on the board.
+2. Add the **fs_config.h** file with information such as **FS_MAX_SS** (maximum sector size of the storage device) and **FF_VOLUME_STRS** (partition names) configured.
+
+The following is an example:
-2. Add the **fs\_config.h** file with information such as **FS\_MAX\_SS** \(maximum sector size of the storage device\) and **FF\_VOLUME\_STRS** \(partition names\) configured. The following is an example:
```
#define FF_VOLUME_STRS "system", "inner", "update", "user"
@@ -22,63 +29,70 @@ The use of the FAT file system requires support from the underlying MultiMediaCa
#define FAT_MAX_OPEN_FILES 50
```
+
### How to Develop
-> **NOTE**
->- Note the following when managing FatFS files and directories:
-> - A file cannot exceed 4 GB.
-> - **FAT\_MAX\_OPEN\_FILES** specifies the maximum number files you can open at a time, and **FAT\_MAX\_OPEN\_DIRS** specifies the maximum number of folders you can open at a time.
-> - Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the file or directory **testfile** in the **user** partition.
-> - To open a file multiple times, use **O\_RDONLY** \(read-only mode\). **O\_RDWR** or **O\_WRONLY** \(writable mode\) can open a file only once.
-> - The read and write pointers are not separated. If a file is open in **O\_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer.
-> - File and directory permission management is not supported.
-> - The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980.
->- Note the following when mounting and unmounting FatFS partitions:
-> - Partitions can be mounted with the read-only attribute. When the input parameter of the **mount** function is **MS\_RDONLY**, all APIs with the write attribute, such as **write**, **mkdir**, **unlink**, and **open** with **non-O\_RDONLY** attributes, will be rejected.
-> - You can use the **MS\_REMOUNT** flag with **mount** to modify the permission for a mounted partition.
-> - Before unmounting a partition, ensure that all directories and files in the partition are closed.
-> - You can use **umount2** with the **MNT\_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when running **umount2**.
->- The FAT file system supports re-partitioning and formatting of storage devices using **fatfs\_fdisk** and **fatfs\_format**.
-> - If a partition is mounted before being formatted using **fatfs\_format**, you must close all directories and files in the partition and unmount the partition first.
-> - Before calling **fatfs\_fdisk**, ensure that all partitions in the device are unmounted.
-> - Using **fatfs\_fdisk** and **fatfs\_format** may cause data loss. Exercise caution when using them.
+>  **NOTE**
+>
+> Note the following when managing FatFS files and directories:
+> - A file cannot exceed 4 GB.
+> - **FAT\_MAX\_OPEN\_FILES** specifies the maximum number files you can open at a time, and **FAT\_MAX\_OPEN\_DIRS** specifies the maximum number of folders you can open at a time.
+> - Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the file or directory **testfile** in the **user** partition.
+> - To open a file multiple times, use **O_RDONLY** (read-only mode). **O_RDWR** or **O_WRONLY** (writable mode) can open a file only once.
+> - The read and write pointers are not separated. If a file is open in **O_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer.
+> - File and directory permission management is not supported.
+> - The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980.
+>
+> Note the following when mounting and unmounting FatFS partitions:
+> - Partitions can be mounted with the read-only attribute. When the input parameter of the **mount** function is **MS_RDONLY**, all APIs with the write attribute, such as **write**, **mkdir**, **unlink**, and **open** with **non-O_RDONLY** attributes, will be rejected.
+> - You can use the **MS_REMOUNT** flag with **mount** to modify the permission for a mounted partition.
+> - Before unmounting a partition, ensure that all directories and files in the partition are closed.
+> - You can use **umount2** with the **MNT_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when running **umount2**.
+>
+> The FAT file system supports re-partitioning and formatting of storage devices using **fatfs_fdisk** and **fatfs_format**.
+> - If a partition is mounted before being formatted using **fatfs_format**, you must close all directories and files in the partition and unmount the partition first.
+> - Before calling **fatfs_fdisk**, ensure that all partitions in the device are unmounted.
+> - Using **fatfs_fdisk** and **fatfs_format** may cause data loss. Exercise caution when using them.
+
## Development Example
+
### Example Description
This example implements the following:
-1. Create the **user/test** directory.
-2. Create the **file.txt** file in the **user/test** directory.
-3. Write "Hello OpenHarmony!" at the beginning of the file.
-4. Save the update of the file to the device.
-5. Set the offset to the beginning of the file.
-6. Read the file.
-7. Close the file.
-8. Delete the file.
-9. Delete the directory.
+1. Create the **user/test** directory.
+2. Create the **file.txt** file in the **user/test** directory.
+3. Write **Hello OpenHarmony!** at the beginning of the file.
+4. Save the file to a device.
+5. Set the offset to the start position of the file.
+6. Read the file.
+7. Close the file.
+8. Delete the file.
+9. Delete the directory.
+
### Sample Code
-Prerequisites
+**Prerequisites**
-- The MMC device partition is mounted to the **user** directory.
+The MMC device partition is mounted to the **user** directory.
-The sample code is as follows:
+ The sample code is as follows:
-```
-#include
-#include
-#include "sys/stat.h"
-#include "fcntl.h"
-#include "unistd.h"
+ ```
+ #include
+ #include
+ #include "sys/stat.h"
+ #include "fcntl.h"
+ #include "unistd.h"
-#define LOS_OK 0
-#define LOS_NOK -1
+ #define LOS_OK 0
+ #define LOS_NOK -1
-int FatfsTest(void)
-{
+ int FatfsTest(void)
+ {
int ret;
int fd = -1;
ssize_t len;
@@ -88,14 +102,14 @@ int FatfsTest(void)
char writeBuf[20] = "Hello OpenHarmony!";
char readBuf[20] = {0};
- /* Create the user/test directory.*/
+ /* Create the user/test directory. */
ret = mkdir(dirName, 0777);
if (ret != LOS_OK) {
printf("mkdir failed.\n");
return LOS_NOK;
}
- /* Create the file user/test/file.txt and make it readable and writable.*/
+ /* Create a readable and writable file named file.txt in the user/test/ directory. */
fd = open(fileName, O_RDWR | O_CREAT, 0777);
if (fd < 0) {
printf("open file failed.\n");
@@ -109,21 +123,21 @@ int FatfsTest(void)
return LOS_NOK;
}
- /* Save the update of the file to the device.*/
+ /* Save the file to a storage device. */
ret = fsync(fd);
if (ret != LOS_OK) {
printf("fsync failed.\n");
return LOS_NOK;
}
- /* Move the read/write pointer to the file header. */
+ /* Move the read/write pointer to the beginning of the file. */
off = lseek(fd, 0, SEEK_SET);
if (off != 0) {
printf("lseek failed.\n");
return LOS_NOK;
}
- /* Read the file content, with the same size as readBuf, to readBuf.*/
+ /* Read the file content with the length of readBuf to readBuf. */
len = read(fd, readBuf, sizeof(readBuf));
if (len != strlen(writeBuf)) {
printf("read file failed.\n");
@@ -138,14 +152,14 @@ int FatfsTest(void)
return LOS_NOK;
}
- /*Delete the file user/test/file.txt.*/
+ /* Delete the file file.txt from the user/test directory. */
ret = unlink(fileName);
if (ret != LOS_OK) {
printf("unlink failed.\n");
return LOS_NOK;
}
- /*Delete the user/test directory.*/
+ /* Delete the user/test directory. */
ret = rmdir(dirName);
if (ret != LOS_OK) {
printf("rmdir failed.\n");
@@ -153,14 +167,15 @@ int FatfsTest(void)
}
return LOS_OK;
-}
-```
+ }
+ ```
+
### Verification
The development is successful if the return result is as follows:
+
```
Hello OpenHarmony!
```
-
diff --git a/en/device-dev/kernel/kernel-mini-extend-file-lit.md b/en/device-dev/kernel/kernel-mini-extend-file-lit.md
index 7d51b76ab3167951eeaa72d839481a4630ec2390..599c94b5a12ea632374a03fcf0ca3e03afea7d8b 100644
--- a/en/device-dev/kernel/kernel-mini-extend-file-lit.md
+++ b/en/device-dev/kernel/kernel-mini-extend-file-lit.md
@@ -1,15 +1,17 @@
# LittleFS
+
## Basic Concepts
-LittleFS is a small file system designed for flash. By combining the log-structured file system and the copy-on-write \(COW\) file system, LittleFS stores metadata in log structure and data in the COW structure. This special storage empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size \(configurable\). That is, the RAM usage does not grow with the file system.
+LittleFS is a small file system designed for flash. By combining the log-structured file system and the copy-on-write (COW) file system, LittleFS stores metadata in log structure and data in the COW structure. This special storage empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size (configurable). That is, the RAM usage does not grow with the file system.
LittleFS is a good choice when you look for a flash file system that is power-cut resilient and has wear leveling support on a small device with limited resources.
## Development Guidelines
-When porting LittleFS to a new hardware device, you need to declare **lfs\_config**:
+When porting LittleFS to a new hardware device, you need to declare **lfs_config**:
+
```
const struct lfs_config cfg = {
// block device operations
@@ -29,20 +31,21 @@ const struct lfs_config cfg = {
};
```
-**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively.
+**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively.
-**read\_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed.
+**read_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed.
-**prog\_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read\_size**. However, if the value is too large, more memory is consumed.
+**prog_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read_size**. However, if the value is too large, more memory is consumed.
-**block\_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog\_size**.
+**block_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog_size**.
-**block\_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased \(**block\_size**\).
+**block_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased (**block_size**).
-## Sample Code
-The sample code is as follows:
+## Sample Code
+ The sample code is as follows:
+
```
#include "lfs.h"
#include "stdio.h"
@@ -89,11 +92,12 @@ int main(void) {
}
```
-### Verification
+
+ **Verification**
The development is successful if the return result is as follows:
+
```
Say hello 1 times.
```
-
diff --git a/en/device-dev/kernel/kernel-mini-memory-perf.md b/en/device-dev/kernel/kernel-mini-memory-perf.md
index 3da1dd5dc276a844ed393af9b7d73bed23a4b767..95d097792307376342a55eefcfde96f7f921952b 100644
--- a/en/device-dev/kernel/kernel-mini-memory-perf.md
+++ b/en/device-dev/kernel/kernel-mini-memory-perf.md
@@ -3,7 +3,8 @@
## Basic Concepts
-perf is a performance analysis tool. It uses the performance monitoring unit \(PMU\) to count sampling events and collect context information and provides hot spot distribution and hot paths.
+perf is a performance analysis tool. It uses the performance monitoring unit (PMU) to count sampling events and collect context information and provides hot spot distribution and hot paths.
+
## Working Principles
@@ -13,227 +14,142 @@ perf provides two working modes: counting mode and sampling mode.
In counting mode, perf collects only the number of event occurrences and duration. In sampling mode, perf also collects context data and stores the data in a circular buffer. The IDE then analyzes the data and provides information about hotspot functions and paths.
+
## Available APIs
+
### Kernel Mode
-The perf module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h) reference.
-
-**Table 1** perf module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Starting or stopping perf sampling
- |
-LOS_PerfStart
- |
-Starts sampling.
- |
-
-LOS_PerfStop
- |
-Stops sampling.
- |
-
-Configuring perf sampling events
- |
-LOS_PerfConfig
- |
-Sets the type and period of a sampling event.
- |
-
-Reading sampling data
- |
-LOS_PerfDataRead
- |
-Reads the sampling data to a specified address.
- |
-
-Registering a hook for the sampling data buffer
- |
-LOS_PerfNotifyHookReg
- |
-Registers the hook to be called when the buffer waterline is reached.
- |
-
-LOS_PerfFlushHookReg
- |
-Registers the hook for flushing the cache in the buffer.
- |
-
-
-
-
-1. The structure of the perf sampling event is **PerfConfigAttr**. For details, see **kernel\\include\\los\_perf.h**.
-2. The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten.
-3. The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size. The sample code is as follows:
-
- ```
- VOID Example_PerfNotifyHook(VOID)
- {
- CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0};
- UINT32 len;
- PRINT_DEBUG("perf buffer reach the waterline!\n");
- len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE);
- OsPrintBuff(buf, len); /* print data */
- }
- LOS_PerfNotifyHookReg(Example_PerfNotifyHook);
- ```
+The Perf module of the OpenHarmony LiteOS-A kernel provides the following functions. For details about the interfaces, see the [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h).
-4. If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency. The sample code is as follows:
+ **Table 1** APIs of the perf module
- ```
- VOID Example_PerfFlushHook(VOID *addr, UINT32 size)
- {
- OsCacheFlush(addr, size); /* platform interface */
- }
- LOS_PerfNotifyHookReg(Example_PerfFlushHook);
- ```
+| API| Description|
+| -------- | -------- |
+| LOS_PerfStart| Starts sampling.|
+| LOS_PerfStop| Stops sampling.|
+| LOS_PerfConfig| Sets the event type and sampling interval.|
+| LOS_PerfDataRead| Reads the sampling data.|
+| LOS_PerfNotifyHookReg| Registers the hook to be called when the buffer waterline is reached.|
+| LOS_PerfFlushHookReg| Registers the hook for flushing the cache in the buffer.|
+
+- The structure of the perf sampling event is **PerfConfigAttr**. For details, see **kernel\include\los_perf.h**.
+
+- The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten.
- The API for flushing the cache is configured based on the platform.
+- The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size.
+
+ Example:
+
+ ```
+ VOID Example_PerfNotifyHook(VOID)
+ {
+ CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0};
+ UINT32 len;
+ PRINT_DEBUG("perf buffer reach the waterline!\n");
+ len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE);
+ OsPrintBuff(buf, len); /* print data */
+ }
+ LOS_PerfNotifyHookReg(Example_PerfNotifyHook);
+ ```
+
+- If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency.
+
+ Example:
+
+ ```
+ VOID Example_PerfFlushHook(VOID *addr, UINT32 size)
+ {
+ OsCacheFlush(addr, size); /* platform interface */
+ }
+ LOS_PerfNotifyHookReg(Example_PerfFlushHook);
+ ```
+
+ The API for flushing the cache is configured based on the platform.
### User Mode
-The perf character device is located in **/dev/perf**. You can read, write, and control the user-mode perf by running the following commands on the device node:
-- **read**: reads perf data in user mode.
-- **write**: writes user-mode sampling events.
-- **ioctl**: controls the user-mode perf, which includes the following:
+The perf character device is located in **/dev/perf**. You can read, write, and control the user-mode perf by running the following commands on the device node:
+
- ```
- #define PERF_IOC_MAGIC 'T'
- #define PERF_START _IO(PERF_IOC_MAGIC, 1)
- #define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
- ```
+- **read**: reads perf data in user mode.
- The operations correspond to **LOS\_PerfStart** and **LOS\_PerfStop**.
+- **write**: writes user-mode sampling events.
+- **ioctl**: controls the user-mode perf, which includes the following:
+
+ ```
+ #define PERF_IOC_MAGIC 'T'
+ #define PERF_START _IO(PERF_IOC_MAGIC, 1)
+ #define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
+ ```
-For more details, see [User-mode Development Example](#user-mode-development-example).
+ The operations correspond to **LOS_PerfStart** and **LOS_PerfStop**.
-## Development Guidelines
-### Kernel-mode Development Process
+For details, see [User-Mode Development Example](#user-mode-development-example).
+
+
+## How to Develop
+
+
+### Kernel-Mode Development Process
The typical process of enabling perf is as follows:
-1. Configure the macros related to the perf module.
-
- Configure the perf control macro **LOSCFG\_KERNEL\_PERF**, which is disabled by default. In the **kernel/liteos\_a** directory, run the **make update\_config** command, choose **Kernel**, and select **Enable Perf Feature**.
-
-
- Macro
- |
- menuconfig Option
- |
- Description
- |
- Value
- |
-
-
- LOSCFG_KERNEL_PERF
- |
- Enable Perf Feature
- |
- Whether to enable perf.
- |
- YES/NO
- |
-
- LOSCFG_PERF_CALC_TIME_BY_TICK
- |
- Time-consuming Calc Methods->By Tick
- |
- Whether to use tick as the perf timing unit.
- |
- YES/NO
- |
-
- LOSCFG_PERF_CALC_TIME_BY_CYCLE
- |
- Time-consuming Calc Methods->By Cpu Cycle
- |
- Whether to use cycle as the perf timing unit.
- |
- YES/NO
- |
-
- LOSCFG_PERF_BUFFER_SIZE
- |
- Perf Sampling Buffer Size
- |
- Size of the buffer used for perf sampling.
- |
- INT
- |
-
- LOSCFG_PERF_HW_PMU
- |
- Enable Hardware Pmu Events for Sampling
- |
- Whether to enable hardware PMU events. The target platform must support the hardware PMU.
- |
- YES/NO
- |
-
- LOSCFG_PERF_TIMED_PMU
- |
- Enable Hrtimer Period Events for Sampling
- |
- Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).
- |
- YES/NO
- |
-
- LOSCFG_PERF_SW_PMU
- |
- Enable Software Events for Sampling
- |
- Whether to enable software events. LOSCFG_KERNEL_HOOK must also be enabled.
- |
- YES/NO
- |
-
-
-
-
-2. Call **LOS\_PerfConfig** to configure the events to be sampled.
-
- perf provides two working modes and three types of events.
-
- Two modes: counting mode \(counts only the number of event occurrences\) and sampling mode \(collects context information such as task IDs, PC, and backtrace\)
-
- Three types of events: CPU hardware events \(such as cycle, branch, icache, and dcache\), high-precision periodical events \(such as CPU clock\), and OS software events \(such as task switch, mux pend, and IRQ\)
-
-3. Call **LOS\_PerfStart\(UINT32 sectionId\)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs.
-4. Call **LOS\_PerfStop** at the end of the code to be sampled.
-5. Call **LOS\_PerfDataRead** to read the sampling data and use IDE to analyze the collected data.
-
-## Kernel-mode Development Example
+1. Configure the macros related to the perf module.
+
+ Configure the perf control macro **LOSCFG_KERNEL_PERF**, which is disabled by default. In the **kernel/liteos_a** directory, run the **make update_config** command, choose **Kernel**, and select **Enable Perf Feature**.
+
+ | Item| menuconfig Option| Description| Value|
+ | -------- | -------- | -------- | -------- |
+ | LOSCFG_KERNEL_PERF | Enable Perf Feature | Whether to enable perf.| YES/NO |
+ | LOSCFG_PERF_CALC_TIME_BY_TICK | Time-consuming Calc Methods->By Tick | Whether to use tick as the perf timing unit.| YES/NO |
+ | LOSCFG_PERF_CALC_TIME_BY_CYCLE | Time-consuming Calc Methods->By Cpu Cycle | Whether to use cycle as the perf timing unit.| YES/NO |
+ | LOSCFG_PERF_BUFFER_SIZE | Perf Sampling Buffer Size | Size of the buffer used for perf sampling.| INT |
+ | LOSCFG_PERF_HW_PMU | Enable Hardware Pmu Events for Sampling | Whether to enable hardware PMU events. The target platform must support the hardware PMU.| YES/NO |
+ | LOSCFG_PERF_TIMED_PMU | Enable Hrtimer Period Events for Sampling | Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).| YES/NO |
+ | LOSCFG_PERF_SW_PMU | Enable Software Events for Sampling | Whether to enable software events. **LOSCFG_KERNEL_HOOK** must also be enabled.| YES/NO |
+
+2. Call **LOS_PerfConfig** to configure the events to be sampled.
+
+ perf provides two working modes and three types of events.
+
+ Working modes: counting mode (counts only the number of event occurrences) and sampling mode (collects context information such as task IDs, PC, and backtrace)
+
+ Events: CPU hardware events (such as cycle, branch, icache, and dcache), high-precision periodical events (such as CPU clock), and OS software events (such as task switch, mux pend, and IRQ)
+
+3. Call **LOS_PerfStart(UINT32 sectionId)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs.
+
+4. Call **LOS_PerfStop** at the end of the code to be sampled.
+
+5. Call **LOS_PerfDataRead** to read the sampling data and use IDE to analyze the collected data.
+
+
+#### Kernel-Mode Development Example
This example implements the following:
-1. Create a perf task.
-2. Configure sampling events.
-3. Start perf.
-4. Execute algorithms for statistics.
-5. Stop perf.
-6. Export the result.
+1. Create a perf task.
-## Kernel-mode Sample Code
+2. Configure sampling events.
-Prerequisites: The perf module configuration is complete in **menuconfig**.
+3. Start perf.
-The code is as follows:
+4. Execute algorithms for statistics.
+
+5. Stop perf.
+
+6. Export the result.
+
+
+#### Kernel-Mode Sample Code
+
+Prerequisites: The perf module configuration is complete in **menuconfig**.
+
+The sample code is as follows:
```
#include "los_perf.h"
@@ -299,10 +215,10 @@ STATIC VOID perfTestHwEvent(VOID)
UINT32 Example_Perf_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S perfTestTask;
- /* Create a perf task.*/
+ /* Create a perf task. */
memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S));
perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent;
- perfTestTask.pcName = "TestPerfTsk"; /* Task name.*/
+ perfTestTask.pcName = "TestPerfTsk"; /* Test task name. */
perfTestTask.uwStackSize = 0x800;
perfTestTask.usTaskPrio = 5;
perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
@@ -316,9 +232,10 @@ UINT32 Example_Perf_test(VOID){
LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
-### Kernel-mode Verification
-The output is as follows:
+#### Kernel-Mode Verification
+
+ The output is as follows:
```
--------count mode----------
@@ -330,48 +247,50 @@ num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00
```
-- For the counting mode, the following information is displayed after perf is stopped:
-
- Event name \(cycles\), event type \(0xff\), and number of event occurrences \(5466989440\)
+- For the counting mode, the following information is displayed after perf is stopped:
+ Event name (cycles), event type (0xff), and number of event occurrences (5466989440)
- For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**.
+ For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**.
-- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped:
+- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped:
+ dump section data, addr: (0x8000000) length: (0x5000)
- dump section data, addr: \(0x8000000\) length: \(0x5000\)
+ You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data.
- You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data.
+ You can also call **LOS_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte.
- You can also call **LOS\_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte.
+### User-Mode Development Process
-### User-mode Development Process
+Choose **Driver** > **Enable PERF DRIVER** in **menuconfig** to enable the perf driver. This option is available in **Driver** only after **Enable Perf Feature** is selected in the kernel.
-Choose **Driver** \> **Enable PERF DRIVER** in **menuconfig** to enable the perf driver. This option is available in **Driver** only after **Enable Perf Feature** is selected in the kernel.
+1. Open the **/dev/perf** file and perform read, write, and ioctl operations.
-1. Open the **/dev/perf** file and perform read, write, and ioctl operations.
-2. Run the **perf** commands in user mode in the **/bin** directory. After running **cd bin**, you can use the following commands:
- - **./perf start \[_id_\]**: starts perf sampling. _id_ is optional and is **0** by default.
- - **./perf stop**: stops perf sampling.
- - **./perf read <_nBytes_\>**: reads n-byte data from the sampling buffer and displays the data.
- - **./perf list**: lists the events supported by **-e**.
- - **./perf stat/record \[_option_\] <_command_\>**: sets counting or sampling parameters.
- - The \[_option_\] can be any of the following:
- - **-e**: sets sampling events. Events of the same type listed in **./perf list** can be used.
- - **-p**: sets the event sampling interval.
- - **-o**: specifies the path of the file for saving the perf sampling data.
- - **-t**: specifies the task IDs for data collection. Only the contexts of the specified tasks are collected. If this parameter is not specified, all tasks are collected by default.
- - **-s**: specifies the context type for sampling. For details, see **PerfSampleType** defined in **los\_perf.h**.
- - **-P**: specifies the process IDs for data collection. Only the contexts of the specified processes are collected. If this parameter is not specified, all processes are collected by default.
- - **-d**: specifies whether to divide the frequency \(the value is incremented by 1 each time an event occurs 64 times\). This option is valid only for hardware cycle events.
-
- - _command_ specifies the program to be checked by perf.
+2. Run the **perf** commands in user mode in the **/bin** directory.
+
+ After running **cd bin**, you can use the following commands:
+
+ - **./perf start [*id*]**: starts perf sampling. *id* is optional and is **0** by default.
+ - **./perf stop**: stops perf sampling.
+ - **./perf read <*nBytes*>**: reads n-byte data from the sampling buffer and displays the data.
+ - **./perf list**: lists the events supported by **-e**.
+ - **./perf stat/record [*option*] <*command*>**: sets counting or sampling parameters.
+ - The [*option*] can be any of the following:
+ - -**-e**: sets sampling events. Events of the same type listed in **./perf list** can be used.
+ - -**-p**: sets the event sampling interval.
+ - -**-o**: specifies the path of the file for saving the perf sampling data.
+ - -**-t**: specifies the task IDs for data collection. Only the contexts of the specified tasks are collected. If this parameter is not specified, all tasks are collected by default.
+ - -**-s**: specifies the context type for sampling. For details, see **PerfSampleType** defined in **los_perf.h**.
+ - -**-P**: specifies the process IDs for data collection. Only the contexts of the specified processes are collected. If this parameter is not specified, all processes are collected by default.
+ - -**-d**: specifies whether to divide the frequency (the value is incremented by 1 each time an event occurs 64 times). This option is valid only for hardware cycle events.
+ - *command* specifies the program to be checked by perf.
+Examples:
+Run the **./perf list** command to display available events.
-Examples:
+The output is as follows:
-Run the **./perf list** command to display available events. The output is as follows:
```
cycles [Hardware event]
@@ -389,7 +308,10 @@ mem-alloc [Software event]
mux-pend [Software event]
```
-Run **./perf stat -e cycles os\_dump**. The output is as follows:
+Run **./perf stat -e cycles os_dump**.
+
+The output is as follows:
+
```
type: 0
@@ -406,7 +328,10 @@ time used: 0.058000(s)
[cycles] eventType: 0xff [core 1]: 13583830
```
-Run **./perf record -e cycles os\_dump**. The output is as follows:
+Run **./perf record -e cycles os_dump**.
+
+The output is as follows:
+
```
type: 0
@@ -423,22 +348,28 @@ time used: 0.059000(s)
save perf data success at /storage/data/perf.data
```
-> **NOTE**
->After running the **./perf stat/record** command, you can run the **./perf start** and **./perf stop** commands multiple times. The sampling event configuration is as per the parameters set in the latest **./perfstat/record** command.
+>  **NOTE**
+> After running the **./perf stat/record** command, you can run the **./perf start** and **./perf stop** commands multiple times. The sampling event configuration is as per the parameters set in the latest **./perfstat/record** command.
+
-### User-mode Development Example
+#### User-Mode Development Example
This example implements the following:
-1. Open the perf character device.
-2. Write the perf events.
-3. Start perf.
-4. Stop perf.
-5. Read the perf sampling data.
+1. Open the perf character device.
+
+2. Write the perf events.
-### User-Mode Sample Code
+3. Start perf.
-The code is as follows:
+4. Stop perf.
+
+5. Read the perf sampling data.
+
+
+#### User-Mode Sample Code
+
+ The code is as follows:
```
#include "fcntl.h"
@@ -506,13 +437,13 @@ int main(int argc, char **argv)
}
```
-### User-mode Verification
-The output is as follows:
+#### User-Mode Verification
+
+ The output is as follows:
```
[EMG] dump section data, addr: 0x8000000 length: 0x800000
num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ...
hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00
```
-
diff --git a/en/device-dev/kernel/kernel-mini-overview.md b/en/device-dev/kernel/kernel-mini-overview.md
index 7b86f1a82028e03366eb3441d6257eb7791764c3..a1b7902c802ad44bac6477e73757955d4611aecf 100644
--- a/en/device-dev/kernel/kernel-mini-overview.md
+++ b/en/device-dev/kernel/kernel-mini-overview.md
@@ -1,59 +1,35 @@
# Kernel Overview
+
## Overview
-The OpenHarmony LiteOS-M kernel is a lightweight operating system \(OS\) kernel designed for the IoT field. It features small size, low power consumption, and high performance. The LiteOS-M kernel has simple code structure, including the minimum function set, kernel abstraction layer \(KAL\), optional components, and project directory. It supports the Hardware Driver Foundation \(HDF\), which provides unified driver standards and access mode for device vendors to simplify porting of drivers and allow one-time development for multi-device deployment.
+The OpenHarmony LiteOS-M kernel is a lightweight operating system (OS) kernel designed for the IoT field. It features small size, low power consumption, and high performance. The LiteOS-M kernel has simple code structure, including the minimum function set, kernel abstraction layer (KAL), optional components, and project directory. It supports the Hardware Driver Foundation (HDF), which provides unified driver standards and access mode for device vendors to simplify porting of drivers and allow one-time development for multi-device deployment.
+
+The OpenHarmony LiteOS-M kernel architecture consists of the hardware layer and hardware-irrelevant layers, as shown in the figure below. The hardware layer is classified based on the compiler toolchain and chip architecture, and provides a unified Hardware Abstraction Layer (HAL) interface to improve hardware adaptation and facilitate the expansion of various types of AIoT hardware and compilation toolchains. The other modules are irrelevant to the hardware. The basic kernel module provides basic kernel capabilities. The extended modules provide capabilities of components, such as the network and file systems, as well as exception handling and debug tools. The KAL provides unified standard APIs.
-The OpenHarmony LiteOS-M kernel architecture consists of the hardware layer and hardware-irrelevant layers, as shown in the figure below. The hardware layer is classified based on the compiler toolchain and chip architecture, and provides a unified Hardware Abstraction Layer \(HAL\) interface to improve hardware adaptation and facilitate the expansion of various types of AIoT hardware and compilation toolchains. The other modules are irrelevant to the hardware. The basic kernel module provides basic kernel capabilities. The extended modules provide capabilities of components, such as the network and file systems, as well as exception handling and debug tools. The KAL provides unified standard APIs.
+ **Figure 1** Kernel architecture
-**Figure 1** Kernel architecture
-
+ 
-### CPU Architecture Support
+
+## CPU Architecture Support
The CPU architecture includes two layers: general architecture definition layer and specific architecture definition layer. The former provides interfaces supported and implemented by all architectures. The latter is specific to an architecture. For a new architecture to be added, the general architecture definition layer must be implemented first and the architecture-specific functions can be implemented at the specific architecture definition layer.
-**Table 1** CPU architecture rules
-
-
-Rule
- |
-General Architecture Definition Layer
- |
-Specific Architecture Definition Layer
- |
-
-
-Header file location
- |
-arch/include
- |
-arch/<arch>/<arch>/<toolchain>/
- |
-
-Header file name
- |
-los_<function>.h
- |
-los_arch_<function>.h
- |
-
-Function name
- |
-Halxxxx
- |
-Halxxxx
- |
-
-
-
-
-LiteOS-M supports mainstream architectures, such as ARM Cortex-M3, ARM Cortex-M4, ARM Cortex-M7, ARM Cortex-M33, and RISC-V. If you need to expand the CPU architecture, see [Chip Architecture Adaptation](../porting/porting-chip-kernel-overview.md#section137431650339).
-
-### Working Principles
-
-Configure the system clock and number of ticks per second in the **target\_config.h** file of the development board. Configure the task, memory, inter-process communication \(IPC\), and exception handling modules based on service requirements. When the system boots, the modules are initialized based on the configuration. The kernel startup process includes peripheral initialization, system clock configuration, kernel initialization, and OS boot, as shown in the figure below.
-
-**Figure 2** Kernel startup process
-
+ **Table 1** CPU architecture rules
+
+| Rule| General Architecture Layer| Specific Architecture Layer|
+| -------- | -------- | -------- |
+| Header file location| arch/include | arch/<arch>/<arch>/<toolchain>/ |
+| Header file name| los_<function>.h | los_arch_<function>.h |
+| Function name| Halxxxx | Halxxxx |
+
+LiteOS-M supports mainstream architectures, such as ARM Cortex-M3, ARM Cortex-M4, ARM Cortex-M7, ARM Cortex-M33, and RISC-V. If you need to expand the CPU architecture, see [Chip Architecture Adaptation](../porting/porting-chip-kernel-overview.md).
+
+
+## Working Principles
+
+In the **target\_config.h** file of the development board, configure the system clock and number of ticks per second, and configure the task, memory, inter-process communication (IPC), and exception handling modules based on service requirements. When the system boots, the modules are initialized based on the configuration. The kernel startup process includes peripheral initialization, system clock configuration, kernel initialization, and OS boot, as shown in the figure below.
+ **Figure 2** Kernel startup process
+ 
diff --git a/en/device-dev/kernel/kernel-small-apx-dll.md b/en/device-dev/kernel/kernel-small-apx-dll.md
index 2e7bb0d0fadcf92e14ea957b89728e240542c18a..e33e8e55d65e6a5e39fbb33e154557e2751148e9 100644
--- a/en/device-dev/kernel/kernel-small-apx-dll.md
+++ b/en/device-dev/kernel/kernel-small-apx-dll.md
@@ -1,178 +1,69 @@
# Doubly Linked List
-
## Basic Concepts
-A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains a pointer to the previous node and a pointer to the next node in the sequence of nodes. The pointer head is unique. A doubly linked list allows access from a list node to its next node and also the previous node on the list. This data structure facilitates data search, especially traversal of a large amount of data. The symmetry of the doubly linked list also makes operations, such as insertion and deletion, easy. However, pay attention to the pointer direction when performing operations.
+A doubly linked list (DLL) is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains a pointer to the previous node and a pointer to the next node in the sequence of nodes. The pointer head is unique. A DLL allows access from a list node to its next node and also the previous node on the list. This data structure facilitates data search, especially traversal of a large amount of data. The symmetry of the DLL also makes operations, such as insertion and deletion, easy. However, pay attention to the pointer direction when performing operations.
+
## Available APIs
-The following table describes APIs available for the doubly linked list. For more details about the APIs, see the API reference.
-
-
-Function
- |
-API
- |
-Description
- |
-
-Initializing a linked list
- |
-LOS_ListInit
- |
-Initializes a specified node as a doubly linked list node.
- |
-
-LOS_DL_LIST_HEAD
- |
-Defines a node and initializes it as a doubly linked list node.
- |
-
-Adding a node
- |
-LOS_ListAdd
- |
-Inserts the specified node to the head of a doubly linked list.
- |
-
-LOS_ListHeadInsert
- |
-Inserts the specified node to the head of a doubly linked list. It is the same as LOS_ListAdd.
- |
-
-LOS_ListTailInsert
- |
-Inserts the specified node to the end of a doubly linked list.
- |
-
-Adding a linked list
- |
-LOS_ListAddList
- |
-Inserts the head of a specified linked list into the head of a doubly linked list.
- |
-
-LOS_ListHeadInsertList
- |
-Inserts the head of a specified linked list into the head of a doubly linked list. It is the same as LOS_ListAddList.
- |
-
-LOS_ListTailInsertList
- |
-Inserts the end of a specified linked list into the head of a doubly linked list.
- |
-
-Deleting a node
- |
-LOS_ListDelete
- |
-Deletes the specified node from a doubly linked list.
- |
-
-LOS_ListDelInit
- |
-Deletes the specified node from the linked list and uses the node to initialize the linked list.
- |
-
-Determining a doubly linked list
- |
-LOS_ListEmpty
- |
-Checks whether a linked list is empty.
- |
-
-LOS_DL_LIST_IS_END
- |
-Checks whether the specified linked list node is at the end of the linked list.
- |
-
-LOS_DL_LIST_IS_ON_QUEUE
- |
-Checks whether the linked list node is in a doubly linked list.
- |
-
-Obtaining structure information
- |
-LOS_OFF_SET_OF
- |
-Obtains the offset of a member in a specified structure relative to the start address of the structure.
- |
-
-LOS_DL_LIST_ENTRY
- |
-Obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.
- |
-
-LOS_ListPeekHeadType
- |
-Obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Return Null if the linked list is empty.
- |
-
-LOS_ListRemoveHeadType
- |
-Obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Return Null if the linked list is empty.
- |
-
-LOS_ListNextType
- |
-Obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL is returned.
- |
-
-Traversing a doubly linked list
- |
-LOS_DL_LIST_FOR_EACH
- |
-Traverses a doubly linked list.
- |
-
-LOS_DL_LIST_FOR_EACH_SAFE
- |
-Traverses a doubly linked list, and stores the next node of the current node for security verification.
- |
-
-Traversing the structure that contains the doubly linked list
- |
-LOS_DL_LIST_FOR_EACH_ENTRY
- |
-Traverses the specified doubly linked list and obtains the address of the structure that contains the linked list node.
- |
-
-LOS_DL_LIST_FOR_EACH_ENTRY_SAFE
- |
-Traverses the specified doubly linked list, obtains the structure address of the node that contains the linked list, and stores the structure address that contains the next node of the current node.
- |
-
-
-
-
-## How to Develop
-
-The typical development process of the doubly linked list is as follows:
-
-1. Call **LOS\_ListInit/LOS\_DL\_LIST\_HEAD** to initialize a doubly linked list.
-2. Call **LOS\_ListAdd** to insert a node to the list.
-3. Call **LOS\_ListTailInsert** to insert a node to the end of the list.
-4. Call **LOS\_ListDelete** to delete the specified node.
-5. Call **LOS\_ListEmpty** to check whether a linked list is empty.
-6. Call **LOS\_ListDelInit** to delete a specified node, and initialize the linked list based on this node.
-
-> **NOTE:**
->- Pay attention to the operations of the front and back pointer of the node.
->- The linked list operation APIs are underlying APIs and do not check whether the input parameters are empty. You must ensure that the input parameters are valid.
->- If the memory of a linked list node is dynamically requested, release the memory after deleting the node.
-
-### Development Example
+The table below describes the DLL APIs. For more details about the APIs, see the API reference.
+
+| **Category**| **API**|
+| -------- | -------- |
+| Initializing a DLL| - **LOS_ListInit**: initializes a node as a DLL node.
- **LOS_DL_LIST_HEAD**: defines a node and initializes it as a DLL node.|
+| Adding a node| - **LOS_ListAdd**: adds a node to the head of a DLL.
- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.
- **LOS_ListTailInsert**: inserts a node to the tail of a DLL.|
+| Adding a DLL| - **LOS_ListAddList**: adds the head of a DLL to the head of this DLL.
- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.
- **LOS_ListTailInsertList**: Inserts the end of a DLL to the head of this DLL.|
+| Deleting a node| - **LOS_ListDelete**: deletes a node from this DLL.
- **LOS_ListDelInit**: deletes a node from this DLL and uses this node to initialize the DLL.|
+| Checking a DLL| - **LOS_ListEmpty**: checks whether a DLL is empty.
- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.
- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.|
+| Obtains structure information.| - **LOS_OFF_SET_OF**: obtains the offset of a member in the specified structure relative to the start address of the structure.
- **LOS_DL_LIST_ENTRY**: obtains the address of the structure that contains the first node in the DLL. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.
- **LOS_ListPeekHeadType**: obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListRemoveHeadType**: obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListNextType**: obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL will be returned.|
+| Traversing a DLL| - **LOS_DL_LIST_FOR_EACH**: traverses a DLL.
- **LOS_DL_LIST_FOR_EACH_SAFE**: traverses the DLL and stores the subsequent nodes of the current node for security verification.|
+| Traversing the structure that contains the DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.
- **LOS_DL_LIST_FOR_EACH_ENTRY_SAFE**: traverses a DLL, obtains the address of the structure that contains the linked list node, and stores the address of the structure that contains the subsequent node of the current node.|
+
+
+## How to Develop
+
+The typical development process of the DLL is as follows:
+
+1. Call **LOS_ListInit** or **LOS_DL_LIST_HEAD** to initialize a DLL.
+
+2. Call **LOS_ListAdd** to add a node into the DLL.
+
+3. Call **LOS_ListTailInsert** to insert a node to the tail of the DLL.
+
+4. Call **LOS_ListDelete** to delete the specified node.
+
+5. Call **LOS_ListEmpty** to check whether the DLL is empty.
+
+6. Call **LOS_ListDelInit** to delete the specified node and initialize the DLL based on the node.
+
+
+>  **NOTE**
+> - Pay attention to the operations operations of the front and back pointer of the node.
+>
+> - The DLL APIs are underlying interfaces and do not check whether the input parameters are empty. You must ensure that the input parameters are valid.
+>
+> - If the memory of a linked list node is dynamically allocated, release the memory when deleting the node.
+
+
+ **Development Example**
**Example Description**
+
This example implements the following:
-1. Initialize a doubly linked list.
-2. Add nodes.
-3. Delete nodes.
-4. Check the operation result.
+
+1. Initialize a DLL.
+
+2. Add nodes.
+
+3. Delete nodes.
+
+4. Check the operation result.
+
+
```
#include "stdio.h"
@@ -184,7 +75,7 @@ static UINT32 ListSample(VOID)
LOS_DL_LIST listNode1 = {NULL,NULL};
LOS_DL_LIST listNode2 = {NULL,NULL};
- // Initialize the linked list.
+ // Initialize the DLL.
PRINTK("Initial head\n");
LOS_ListInit(&listHead);
@@ -203,7 +94,7 @@ static UINT32 ListSample(VOID)
LOS_ListDelete(&listNode1);
LOS_ListDelete(&listNode2);
- // Check that the linked list is empty.
+ // Check whether the DLL is empty.
if (LOS_ListEmpty(&listHead)) {
PRINTK("Delete success\n");
}
@@ -212,8 +103,10 @@ static UINT32 ListSample(VOID)
}
```
+
**Verification**
+
The development is successful if the return result is as follows:
```
@@ -222,4 +115,3 @@ Add listNode1 success
Tail insert listNode2 success
Delete success
```
-
diff --git a/en/device-dev/kernel/kernel-small-basic-memory-virtual.md b/en/device-dev/kernel/kernel-small-basic-memory-virtual.md
index 1c3b440fd5ecc5741b2cad1a49ef59b90d9082aa..bcef2eb5c93bf3ba1b15552d055a5cfa7dc9405b 100644
--- a/en/device-dev/kernel/kernel-small-basic-memory-virtual.md
+++ b/en/device-dev/kernel/kernel-small-basic-memory-virtual.md
@@ -1,322 +1,129 @@
# Virtual Memory Management
-## Basic Concepts
+## Basic Concepts
Virtual memory management is a technology used by computer systems to manage memory. Each process has a continuous virtual address space. The size of the virtual address space is determined by the number of CPU bits. The maximum addressing space for a 32-bit hardware platform ranges from 0 GiB to 4 GiB. The 4 GiB space is divided into two parts: 3 GiB higher-address space for the LiteOS-A kernel and 1 GiB lower-address space for user-mode processes. The virtual address space of each process space is independent, and the code and data do not affect each other.
-The system divides the virtual memory into memory blocks called virtual pages. The size of a virtual page is generally 4 KiB or 64 KiB. The virtual page of the LiteOS-A kernel is 4 KiB by default. You can configure memory management units \(MMUs\) as required. The minimum unit of the virtual memory management is a page. A virtual address region in the LiteOS-A kernel can contain one virtual page or multiple virtual pages with contiguous addresses. Similarly, the physical memory is also divided by page, and each memory block is called page frame. The virtual address space is divided as follows: 3 GiB \(**0x40000000** to **0xFFFFFFFF**\) for the kernel space and 1 GiB \(**0x01000000** to **0x3F000000**\) for the user space. The following tables describe the virtual address plan. You can view or configure virtual addresses in **los\_vm\_zone.h**.
-
-**Table 1** Kernel-mode addresses
-
-
-Zone
- |
-Description
- |
-Property
- |
-
-
-DMA zone
- |
-Addresses for direct memory access (DMA) of I/O devices.
- |
-Uncache
- |
-
-Normal zone
- |
-Addresses for loading the kernel code segment, data segment, heap, and stack.
- |
-Cache
- |
-
-high mem zone
- |
-Addresses for allocating contiguous virtual memory. The mapped physical memory blocks may not be contiguous.
- |
-Cache
- |
-
-
-
-
-**Table 2** User-mode virtual addresses
-
-
-Zone
- |
-Description
- |
-Property
- |
-
-
-Code segment
- |
-User-mode code segment address range
- |
-Cache
- |
-
-Heap
- |
-User-mode heap address range
- |
-Cache
- |
-
-Stack
- |
-User-mode stack address range
- |
-Cache
- |
-
-Shared library
- |
-Address range for loading the user-mode shared library, including the address range mapped by mmap.
- |
-Cache
- |
-
-
-
-
-## Working Principles
+The system divides the virtual memory into memory blocks called virtual pages. The size of a virtual page is generally 4 KiB or 64 KiB. The virtual page of the LiteOS-A kernel is 4 KiB by default. You can configure memory management units (MMUs) as required. The minimum unit of the virtual memory management is a page. A virtual address region in the LiteOS-A kernel can contain one virtual page or multiple virtual pages with contiguous addresses. Similarly, the physical memory is also divided by page, and each memory block is called page frame. The virtual address space is divided as follows: 3 GiB (**0x40000000** to **0xFFFFFFFF**) for the kernel space and 1 GiB (**0x01000000** to **0x3F000000**) for the user space. The following tables describe the virtual address plan. You can view or configure virtual addresses in **los_vm_zone.h**.
+
+**Table 1** Kernel-mode addresses
+
+| Zone| Description| Property|
+| -------- | -------- | -------- |
+| DMA zone | Addresses for direct memory access (DMA) of I/O devices.| Uncache |
+| Normal zone | Addresses for loading the kernel code segment, data segment, heap, and stack.| Cache |
+| high mem zone | Addresses for allocating contiguous virtual memory. The mapped physical memory blocks may not be contiguous.| Cache |
+
+**Table 2** User-mode virtual addresses
+
+| Zone| Description| Property|
+| -------- | -------- | -------- |
+| Code snippet| User-mode code segment address range.| Cache |
+| Heap| User-mode heap address range.| Cache |
+| Stack| User-mode stack address range.| Cache |
+| Shared databases| Address range for loading the user-mode shared library, including the address range mapped by mmap.| Cache |
+
+
+## Working Principles
In virtual memory management, the virtual address space is contiguous, but the mapped physical memory is not necessarily contiguous, as depicted in the following figure. When an executable program is loaded and runs, the CPU accesses the code or data in the virtual address space in the following two cases:
-- If the page \(for example, V0\) containing the virtual address accessed by the CPU is mapped to a physical page \(for example, P0\), the CPU locates the page table entry corresponding to the process \(for details, see [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md)"\), accesses the physical memory based on the physical address information in the page table entry, and returns the content.
-- If the page \(for example, V2\) containing the virtual address accessed by the CPU is not mapped to a physical page, the system triggers a page missing fault, requests a physical page, copies the corresponding information to the physical page, and updates the start address of the physical page to the page table entry. Then, the CPU can access specific code or data by executing the instruction for accessing the virtual memory again.
-
-**Figure 1** Mapping between the virtual and physical memory addresses
-
-
-## Development Guidelines
-
-### Available APIs
-
-**Table 3** APIs of the virtual memory management module
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Obtaining process memory space
- |
-LOS_CurrSpaceGet
- |
-Obtains the pointer to the current process space structure.
- |
-
-LOS_SpaceGet
- |
-Obtains the pointer to the process space structure corresponding to the virtual address.
- |
-
-LOS_GetKVmSpace
- |
-Obtains the pointer to the kernel process space structure.
- |
-
-LOS_GetVmallocSpace
- |
-Obtains the pointer to the vmalloc space structure.
- |
-
-LOS_GetVmSpaceList
- |
-Obtains the pointer to the process space linked list.
- |
-
-Operations related to the virtual address region
- |
-LOS_RegionFind
- |
-Searches for and returns the virtual address region corresponding to the specified address in the process space.
- |
-
-LOS_RegionRangeFind
- |
-Searches for and returns the virtual address region corresponding to the specified address range in the process space.
- |
-
-LOS_IsRegionFileValid
- |
-Checks whether the virtual address region is mapped to a file.
- |
-
-LOS_RegionAlloc
- |
-Requests a free virtual address region.
- |
-
-LOS_RegionFree
- |
-Releases a specific region in the process space.
- |
-
-LOS_RegionEndAddr
- |
-Obtains the end address of the specified address region.
- |
-
-LOS_RegionSize
- |
-Obtains the size of a region.
- |
-
-LOS_IsRegionTypeFile
- |
-Checks whether the address region is a file memory mapping.
- |
-
-LOS_IsRegionPermUserReadOnly
- |
-Checks whether the address region is read-only in the user space.
- |
-
-LOS_IsRegionFlagPrivateOnly
- |
-Checks whether the address region has private attributes.
- |
-
-LOS_SetRegionTypeFile
- |
-Sets the file memory mapping attribute.
- |
-
-LOS_IsRegionTypeDev
- |
-Checks whether the address region is device memory mapping.
- |
-
-LOS_SetRegionTypeDev
- |
-Sets the device memory mapping attribute.
- |
-
-LOS_IsRegionTypeAnon
- |
-Checks whether the address region is an anonymous mapping.
- |
-
-LOS_SetRegionTypeAnon
- |
-Sets the anonymous mapping attribute.
- |
-
-Verifying address
- |
-LOS_IsUserAddress
- |
-Checks whether the address is in the user space.
- |
-
-LOS_IsUserAddressRange
- |
-Checks whether the address region is in the user space.
- |
-
-LOS_IsKernelAddress
- |
-Checks whether the address is in the kernel space.
- |
-
-LOS_IsKernelAddressRange
- |
-Checks whether the address region is in the kernel space.
- |
-
-LOS_IsRangeInSpace
- |
-Checks whether the address region is in the process space.
- |
-
-vmalloc operations
- |
-LOS_VMalloc
- |
-Requests memory using vmalloc.
- |
-
-LOS_VFree
- |
-Releases memory using vmalloc.
- |
-
-LOS_IsVmallocAddress
- |
-Checks whether the address is requested by using vmalloc.
- |
-
-Requesting memory
- |
-LOS_KernelMalloc
- |
-Allocates memory from the heap memory pool if the requested memory is less than 16 KiB; allocates multiple contiguous physical pages for memory allocation if the requested memory is greater than 16 KiB.
- |
-
-LOS_KernelMallocAlign
- |
-Allocates memory with alignment attributes. The allocation rule is the same as that of the LOS_KernelMalloc API.
- |
-
-LOS_KernelFree
- |
-Releases the memory requested by LOS_KernelMalloc and LOS_KernelMallocAlign.
- |
-
-LOS_KernelRealloc
- |
-Reallocates the memory requested by LOS_KernelMalloc and LOS_KernelMallocAlign.
- |
-
-Others
- |
-LOS_PaddrQuery
- |
-Obtains the physical address based on the virtual address.
- |
-
-LOS_VmSpaceFree
- |
-Releases the process space, including the virtual memory region and page table.
- |
-
-LOS_VmSpaceReserve
- |
-Reserves a memory space in the process space.
- |
-
-LOS_VaddrToPaddrMmap
- |
-Maps the physical address region with the specified length to a virtual address region. You need to request the physical address region before the operation.
- |
-
-
-
-
-### How to Develop
+- If the page (for example, V0) containing the virtual address accessed by the CPU is mapped to a physical page (for example, P0), the CPU locates the page table entry corresponding to the process (for details, see [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md)"), accesses the physical memory based on the physical address information in the page table entry, and returns the content.
-To use APIs related to virtual memory:
+- If the page (for example, V2) containing the virtual address accessed by the CPU is not mapped to a physical page, the system triggers a page missing fault, requests a physical page, copies the corresponding information to the physical page, and updates the start address of the physical page to the page table entry. Then, the CPU can access specific code or data by executing the instruction for accessing the virtual memory again.
+
+ **Figure 1** Mapping between the virtual and physical memory addresses
+
+ 
+
+
+## Development Guidelines
+
+
+### Available APIs
+
+**Table 3** APIs of the virtual memory management module
-1. Obtain the process space structure using the APIs for obtaining the process space, and access the structure information.
-2. Perform the following operations on the virtual address region:
- - Call **LOS\_RegionAlloc** to request a virtual address region.
+| API| Description|
+| -------- | -------- |
+| LOS_CurrSpaceGet | Obtains the pointer to the current process space structure.|
+| LOS_SpaceGet | Obtains the pointer to the process space structure corresponding to the virtual address.|
+| LOS_GetKVmSpace | Obtains the pointer to the kernel process space structure.|
+| LOS_GetVmallocSpace | Obtains the pointer to the vmalloc space structure.|
+| LOS_GetVmSpaceList | Obtains the pointer to the process space linked list.|
- - Call **LOS\_RegionFind** and **LOS\_RegionRangeFind** to check whether the corresponding address region exists.
- - Call **LOS\_RegionFree** to release a virtual address region.
+**Table 4** Operations related to the virtual address region
+
+| API| Description|
+| -------- | -------- |
+| LOS_RegionFind | Searches for and returns the virtual address region corresponding to the specified address in the process space.|
+| LOS_RegionRangeFind | Searches for and returns the virtual address region corresponding to the specified address range in the process space.|
+| LOS_IsRegionFileValid | Checks whether the virtual address region is mapped to a file.|
+| LOS_RegionAlloc | Requests a free virtual address region.|
+| LOS_RegionFree | Releases a specific region in the process space.|
+| LOS_RegionEndAddr | Obtains the end address of the specified address region.|
+| LOS_RegionSize | Obtains the size of a region.|
+| LOS_IsRegionTypeFile | Checks whether the address region is a file memory mapping.|
+| LOS_IsRegionPermUserReadOnly | Checks whether the address region is read-only in the user space.|
+| LOS_IsRegionFlagPrivateOnly | Checks whether the address region has private attributes.|
+| LOS_SetRegionTypeFile | Sets the file memory mapping attributes. |
+| LOS_IsRegionTypeDev | Checks whether the address region is device memory mapping.|
+| LOS_SetRegionTypeDev | Sets the device memory mapping attributes. |
+| LOS_IsRegionTypeAnon | Checks whether the address region is an anonymous mapping.|
+| LOS_SetRegionTypeAnon | Sets the anonymous mapping attributes. |
+
+**Table 5** APIs for address verification
+
+| API| Description|
+| -------- | -------- |
+| LOS_IsUserAddress | Checks whether the address is in the user space.|
+| LOS_IsUserAddressRange | Checks whether the address region is in the user space.|
+| LOS_IsKernelAddress | Checks whether the address is in the kernel space.|
+| LOS_IsKernelAddressRange | Checks whether the address region is in the kernel space.|
+| LOS_IsRangeInSpace | Checks whether the address region is in the process space.|
+
+**Table 6** APIs for vmalloc operations
+
+| API| Description|
+| -------- | -------- |
+| LOS_VMalloc | Requests memory using **vmalloc**.|
+| LOS_VFree | Releases memory using **vmalloc**.|
+| LOS_IsVmallocAddress | Checks whether the address is requested using **vmalloc**. |
+
+**Table 7** APIs for memory allocation
+
+| API| Description|
+| -------- | -------- |
+| LOS_KernelMalloc | Allocates memory from the heap memory pool if the requested memory is less than 16 KiB; allocates multiple contiguous physical pages if the requested memory is greater than 16 KiB. |
+| LOS_KernelMallocAlign | Allocates memory with alignment attributes. The allocation rule is the same as that of the **LOS_KernelMalloc** API.|
+| LOS_KernelFree | Releases the memory requested by **LOS_KernelMalloc** and **LOS_KernelMallocAlign**.|
+| LOS_KernelRealloc | Reallocates the memory requested by **LOS_KernelMalloc** and **LOS_KernelMallocAlign**.|
+
+**Table 8** Other APIs
+
+| API | Description |
+| -------- | -------- |
+| LOS_PaddrQuery | Obtains the physical address based on the virtual address. |
+| LOS_VmSpaceFree | Releases the process space, including the virtual memory region and page table. |
+| LOS_VmSpaceReserve | Reserves a memory space in the process space. |
+| LOS_VaddrToPaddrMmap | Maps the physical address region with the specified length to a virtual address region. You need to request the physical address region before the operation. |
+
+
+### How to Develop
+
+To use APIs related to virtual memory:
-3. Call **vmalloc** and memory requesting APIs to apply for memory in the kernel as demanded.
+1. Obtain the process space structure using the APIs for obtaining the process space, and access the structure information.
+2. Perform the following operations on the virtual address region:
+ - Call **LOS_RegionAlloc** to request a virtual address region.
+ - Call **LOS_RegionFind** and **LOS_RegionRangeFind** to check whether the corresponding address region exists.
+ - Call **LOS_RegionFree** to release a virtual address region.
-> **NOTE:**
->The physical memory requested by using the memory requesting APIs must be contiguous. If the system cannot provide a large number of contiguous memory blocks, the request fails. Therefore, the memory requesting APIs are recommended for requesting small memory blocks. **vmalloc** is recommended for requesting non-contiguous physical memory. However, the memory is allocated in the unit of pages \(4096 bytes/page in the current system\). If you want memory that is an integer multiple of a page, you can use **vmalloc**. For example, you can use **vmalloc** to request memory for file reading in a file system, which demands a large cache.
+3. Call **vmalloc** APIs (see table 6) and memory allocation APIs (see table 7) to apply for memory in the kernel as required.
+>  **NOTE**
+>
+> The physical memory requested by using the memory allocation APIs must be contiguous. If the system cannot provide a large number of contiguous memory blocks, the request fails. Therefore, the memory allocation APIs are recommended for requesting small memory blocks.
+>
+> **vmalloc** APIs are recommended for requesting non-contiguous physical memory. However, the memory is allocated in the unit of pages (4096 bytes/page in the current system). If you want memory that is an integer multiple of a page, you can use **vmalloc** APIs. For example, you can use **vmalloc** to request memory for file reading in a file system, which demands a large cache.
diff --git a/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md b/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md
index 97f8b77622ee03c6701df1e0b426778c8a956ddd..18558986daf9a5cf45e72a771aa8dc6e98454876 100644
--- a/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md
+++ b/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md
@@ -1,128 +1,85 @@
# RW Lock
-## Basic Concepts
+## Basic Concepts
-Similar to a mutex, a read-write lock \(RW lock\) can be used to synchronize tasks in the same process. Different from a mutex, an RW lock allows concurrent access for read operations and exclusive access for write operations.
+Similar to a mutex, a read-write lock (RW lock) can be used to synchronize tasks in the same process. Different from a mutex, an RW lock allows concurrent access for read operations and exclusive access for write operations.
An RW lock has three states: locked in read mode, locked in write mode, and unlocked.
Observe the following rules when using RW locks:
-- If there is no lock in write mode in the protected area, any task can add a lock in read mode.
-- A lock in write mode can be added only when the protected area is in the unlocked state.
+- If there is no lock in write mode in the protected area, any task can add a lock in read mode.
+
+- A lock in write mode can be added only when the protected area is in the unlocked state.
In a multi-task environment, multiple tasks may access the same shared resource. A lock in read mode allows access to a protected area in shared mode, and a lock in a write mode allows exclusive access to the shared resource.
This sharing-exclusive manner is suitable for a multi-task environment where the data read operations are far more than data write operations. It can improve multi-task concurrency of the application.
-## Working Principles
+
+## Working Principles
How does an RW lock implement lock in read mode and lock in write mode to control read/write access of multiple tasks?
-- If task A acquires the lock in write mode for the first time, other tasks cannot acquire or attempt to acquire the lock in read mode.
-
-- If task A acquires the lock in read mode, the RW lock count increments by 1 when a task acquires or attempts to acquire the lock in read mode.
-
-## Development Guidelines
-
-### Available APIs
-
-**Table 1** Read/write lock module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Creating and deleting an RW lock
- |
-LOS_RwlockInit
- |
-Creates an RW lock.
- |
-
-LOS_RwlockDestroy
- |
-Deletes the specified RW lock.
- |
-
-Requesting a lock in read mode
- |
-LOS_RwlockRdLock
- |
-Requests the specified lock in read mode.
- |
-
-LOS_RwlockTryRdLock
- |
-Attempts to request the specified lock in read mode.
- |
-
-Requesting a lock in write mode
- |
-LOS_RwlockWrLock
- |
-Requests the specified lock in write mode.
- |
-
-LOS_RwlockTryWrLock
- |
-Attempts to request the specified lock in write mode.
- |
-
-Releasing an RW lock
- |
-LOS_RwlockUnLock
- |
-Releases the specified RW lock.
- |
-
-Verifying RW lock validity
- |
-LOS_RwlockIsValid
- |
-Checks the validity of an RW lock.
- |
-
-
-
-
-### How to Develop
+- If task A acquires the lock in write mode for the first time, other tasks cannot acquire or attempt to acquire the lock in read mode.
+
+- If task A acquires the lock in read mode, the RW lock count increments by 1 when a task acquires or attempts to acquire the lock in read mode.
+
+
+## Development Guidelines
+
+
+### Available APIs
+
+**Table 1** APIs of the RW lock module
+
+| API| Description|
+| -------- | -------- |
+| LOS_RwlockInit| Creates an RW lock.|
+| LOS_RwlockDestroy| Deletes an RW lock.|
+| LOS_RwlockRdLock| Requests the specified lock in read mode.|
+| LOS_RwlockTryRdLock| Attempts to request a lock in read mode.|
+| LOS_RwlockWrLock| Requests the specified lock in write mode.|
+| LOS_RwlockTryWrLock| Attempts to request a lock in write mode.|
+| LOS_RwlockUnLock| Releases the specified RW lock.|
+| LOS_RwlockIsValid| Checks the validity of an RW lock.|
+
+
+### How to Develop
The typical development process is as follows:
-1. Call **LOS\_RwlockInit** to create an RW lock.
+1. Call **LOS_RwlockInit** to create an RW lock.
-2. Call **LOS\_RwlockRdLock** to request a lock in read mode or call **LOS\_RwlockWrLock** to request a lock in write mode.
+2. Call **LOS_RwlockRdLock** to request a lock in read mode or call **LOS_RwlockWrLock** to request a lock in write mode.
-If a lock in read mode is requested:
+ If a lock in read mode is requested:
-- If the lock is not held, the read task can acquire the lock.
-- If the lock is held, the read task acquires the lock and is executed based on the task priority.
-- If the lock in write mode is held by another task, the task cannot acquire the lock until the lock in write mode is released.
+ - If the lock is not held, the read task can acquire the lock.
-If a lock in write mode is requested:
+ - If the lock is held, the read task acquires the lock and is executed based on the task priority.
-- If the lock is not held or if the task that holds the lock in read mode is the one that requests the lock in write mode, the task acquires the lock in write mode immediately.
-- If the lock already has a lock in read mode and the read task has a higher priority, the current task is suspended until the lock in read mode is released.
+ - If the lock in write mode is held by another task, the task cannot acquire the lock until the lock in write mode is released.
-3. There are three types of locks in read mode and write mode: non-block mode, permanent block mode, and scheduled block mode. The difference lies in the task suspension time.
+ If a lock in write mode is requested:
+
+ - If the lock is not held or if the task that holds the lock in read mode is the one that requests the lock in write mode, the task acquires the lock in write mode immediately.
-4. Call **LOS\_RwlockUnLock** to release an RW lock.
+ - If the lock already has a lock in read mode and the read task has a higher priority, the current task is suspended until the lock in read mode is released.
-- If tasks are blocked by the specified RW lock, the task with the highest priority is woken up, enters the Ready state, and is scheduled.
+3. There are three types of locks in read mode and write mode: non-block mode, permanent block mode, and scheduled block mode. The difference lies in the task suspension time.
-- If no task is blocked by the specified RW lock, the RW lock is released.
+4. Call **LOS_RwlockUnLock** to release an RW lock.
-5. Call **LOS\_RwlockDestroy** to delete an RW lock.
+ - If tasks are blocked by the specified RW lock, the task with the highest priority is woken up, enters the Ready state, and is scheduled.
+ - If no task is blocked by the specified RW lock, the RW lock is released.
-> **NOTE:**
->- The RW lock cannot be used in the interrupt service program.
->- When using the LiteOS-A kernel, the OpenHarmony must ensure real-time task scheduling and avoid long-time task blocking. Therefore, an RW lock must be released as soon as possible after use.
->- When an RW lock is held by a task, the task priority cannot be changed by using APIs such as **LOS\_TaskPriSet**.
+5. Call **LOS_RwlockDestroy** to delete an RW lock.
+ >  **NOTE**
+ > - The RW lock cannot be used in the interrupt service program.
+ >
+ > - The LiteOS-A kernel used in the RTOS must ensure real-time task scheduling and avoid long-time task blocking. Therefore, RW locks must be released as soon as possible after use.
+ >
+ > - When an RW lock is held by a task, the task priority cannot be changed by using APIs, such as **LOS_TaskPriSet**.
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md
index d82858014b528de1c82b4313cfc3a0e0312a9540..e2bf8109175e2498239134fd959f71326d263bf9 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md
@@ -1,40 +1,49 @@
# FAT
-## Basic Concepts
+## Basic Concepts
-File Allocation Table \(FAT\) is a file system developed for personal computers. It consists of the DOS Boot Record \(DBR\) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, the number of the next cluster of the file, and whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, and also restrict the maximum file size in the system. The FAT file system supports multiple media, especially removable media \(such as USB flash drives, SD cards, and removable hard drives\). The FAT file system ensures good compatibility between embedded devices and desktop systems \(such as Windows and Linux\) and facilitates file management.
+File Allocation Table (FAT) is a file system developed for personal computers. It consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, and also restrict the maximum file size in the system. The FAT file system supports multiple media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). The FAT file system ensures good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management.
The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary partition and logical partition.
-## Working Principles
+
+## Working Principles
This document does not include the FAT design and physical layout. You can find a lot of reference on the Internet.
-The OpenHarmony LiteOS-A kernel uses block cache \(Bcache\) to improve FAT performance. When read and write operations are performed, Bcache caches the sectors close to the read and write sectors to reduce the number of I/Os and improve performance. The basic cache unit of Bcache is block. The size of each block is the same. By default, there are 28 blocks, and each block caches data of 64 sectors. When the Bcache dirty block rate \(number of dirty sectors/total number of sectors\) reaches the threshold, writeback is triggered and cached data is written back to disks. You can manually call **sync** and **fsync** to write data to disks if you want. Some FAT APIs \(such as **close** and **umount**\) may also trigger writeback operations. However, you are advised not to use them to trigger writeback.
+The OpenHarmony LiteOS-A kernel uses block cache (Bcache) to improve FAT performance. When read and write operations are performed, Bcache caches the sectors close to the read and write sectors to reduce the number of I/Os and improve performance. The basic cache unit of Bcache is block. The size of each block is the same. By default, there are 28 blocks, and each block caches data of 64 sectors. When the Bcache dirty block rate (number of dirty sectors/total number of sectors) reaches the threshold, writeback is triggered and cached data is written back to disks. You can manually call **sync** and **fsync** to write data to disks if you want. Some FAT APIs (such as **close** and **umount**) may also trigger writeback operations. However, you are advised not to use them to trigger writeback.
+
-## Development Guidelines
+## Development Guidelines
-### How to Develop
+
+ **How to Develop**
The development process involves mounting partitions, managing files and directories, and unmounting partitions.
-The device name of the SD card or MMC is **mmcblk\[x\]p\[y\]**, and the file system type is **vfat**.
+The device name of the SD card or MMC is **mmcblk[x]p[y]**, and the file system type is **vfat**.
Example:
+
```
mount("/dev/mmcblk0p0", "/mnt", "vfat", 0, NULL);
```
-> **NOTE**
->- The size of a single FAT file cannot be greater than 4 GiB.
->- When there are two SD card slots, the first card inserted is card 0, and that inserted later is card 1.
->- When multi-partition is enabled and there are multiple partitions, the device node **/dev/mmcblk0** \(primary device\) registered by card 0 and **/dev/mmcblk0p0** \(secondary device\) are the same device. In this case, you cannot perform operations on the primary device.
->- Before removing an SD card, close the open files and directories and unmount the related nodes. Otherwise, SD card exceptions or memory leaks may occur.
->- Before performing the **format** operation, unmount the mount point.
->- After the Bcache feature takes effect, note the following:
-> - When **MS\_NOSYNC** is carried in the **mount** function, FAT does not proactively write the content in the cache back to the storage device. The FAT-related APIs **open**, **close**, **unlink**, **rename**, **mkdir**, **rmdir**, and **truncate** do not automatically perform the **sync** operation, which improves the operation speed. However, the upper layer must actively invoke the **sync** operation to synchronize data. Otherwise, data loss may occur.
-> - Bcache provides scheduled writeback. After **LOSCFG\_FS\_FAT\_CACHE\_SYNC\_THREAD** is enabled in **menuconfig**, the OpenHarmony kernel creates a scheduled task to write the Bcache data back to disks. By default, the kernel checks the dirty block rate in the Bcache every 5 seconds. If the dirty block rate exceeds 80%, the **sync** operation will be performed to write all dirty data in the Bcache to disks. You can call **LOS\_SetSyncThreadPrio**, **LOS\_SetSyncThreadInterval**, and **LOS\_SetDirtyRatioThreshold** to set the task priority, flush interval, and dirty block rate threshold, respectively.
-> - The cache has 28 blocks by default, and each block has 64 sectors.
-
+>  **NOTE**
+> - The size of a single FAT file cannot be greater than 4 GiB.
+>
+> - When there are two SD card slots, the first card inserted is card 0, and that inserted later is card 1.
+>
+> - When multi-partition is enabled and there are multiple partitions, the device node **/dev/mmcblk0** (primary device) registered by card 0 and **/dev/mmcblk0p0** (secondary device) are the same device. In this case, you cannot perform operations on the primary device.
+>
+> - Before removing an SD card, close the open files and directories and unmount the related nodes. Otherwise, SD card exceptions or memory leaks may occur.
+>
+> - Before performing the **format** operation, unmount the mount point.
+>
+> - After the Bcache feature takes effect, note the following:
+> - When **MS_NOSYNC** is carried in the **mount** function, FAT does not proactively write the content in the cache back to the storage device. The FAT-related APIs **open**, **close**, **unlink**, **rename**, **mkdir**, **rmdir**, and **truncate** do not automatically perform the **sync** operation, which improves the operation speed. However, the upper layer must actively invoke the **sync** operation to synchronize data. Otherwise, data loss may occur.
+>
+> - Bcache provides scheduled writeback. After **LOSCFG_FS_FAT_CACHE_SYNC_THREAD** is enabled in **menuconfig**, the OpenHarmony kernel creates a scheduled task to write the Bcache data back to disks. By default, the kernel checks the dirty block rate in the Bcache every 5 seconds. If the dirty block rate exceeds 80%, the **sync** operation will be performed to write all dirty data in the Bcache to disks. You can call **LOS_SetSyncThreadPrio**, **LOS_SetSyncThreadInterval**, and **LOS_SetDirtyRatioThreshold** to set the task priority, flush interval, and dirty block rate threshold, respectively.
+> - The cache has 28 blocks by default, and each block has 64 sectors.
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
index d205531eb3d7ac83645ce872669a645d0d4d5aa5..57e01b4a58d9430f167b89c0cd03f6b4ded73dbf 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
@@ -1,135 +1,140 @@
# NFS
-## Basic Concepts
+## Basic Concepts
-NFS allows you to share files across hosts and OSs over a network. You can treat NFS as a file system service, which is equivalent to folder sharing in the Windows OS to some extent.
+Network File System (NFS) allows you to share files across hosts and OSs over a network. You can treat NFS as a file system service, which is equivalent to folder sharing in the Windows OS to some extent.
-## Working Principles
-The NFS of the OpenHarmony LiteOS-A kernel acts as an NFS client. The NFS client can mount the directory shared by a remote NFS server to the local machine and run the programs and shared files without occupying the storage space of the current system. To the local machine, the directory on the remote server is like its disk.
-
-## Development Guidelines
-
-1. Create an NFS server.
-
-The following uses the Ubuntu OS as an example to describe how to configure an NFS server.
-
-- Install the NFS server software.
-
-Set the download source of the Ubuntu OS when the network connection is normal.
-
-```
-sudo apt-get install nfs-kernel-server
-```
+## Working Principles
-- Create a directory for mounting and assign full permissions for the directory.
-
-```
-mkdir -p /home/sqbin/nfs
-sudo chmod 777 /home/sqbin/nfs
-```
-
-- Configure and start the NFS server.
-
-Append the following line in the **/etc/exports** file:
-
-```
-/home/sqbin/nfs *(rw,no_root_squash,async)
-```
-
-**/home/sqbin/nfs** is the root directory shared by the NFS server.
-
-Start the NFS server.
+The NFS of the OpenHarmony LiteOS-A kernel acts as an NFS client. The NFS client can mount the directory shared by a remote NFS server to the local machine and run the programs and shared files without occupying the storage space of the current system. To the local machine, the directory on the remote server is like its disk.
-```
-sudo /etc/init.d/nfs-kernel-server start
-```
-Restart the NFS server.
+## Development Guidelines
-```
-sudo /etc/init.d/nfs-kernel-server restart
-```
+1. Create an NFS server.
-1. Configure the board as an NFS client.
+ The following uses the Ubuntu OS as an example to describe how to configure an NFS server.
-In this section, the NFS client is a device running the OpenHarmony kernel.
+ - Install the NFS server software.
-- Set the hardware connection.
+ Set the download source of the Ubuntu OS when the network connection is normal.
-Connect the OpenHarmony kernel device to the NFS server. Set their IP addresses in the same network segment. For example, set the IP address of the NFS server to **10.67.212.178/24** and set the IP address of the OpenHarmony kernel device to **10.67.212.3/24**. Note that the preceding IP addresses are private IP addresses used as examples. You need to use your actual IP addresses.
+ ```
+ sudo apt-get install nfs-kernel-server
+ ```
-You can run the **ifconfig** command to check the OpenHarmony kernel device's IP address.
+ - Create a directory for mounting and assign full permissions for the directory.
-- Start the network and ensure that the network between the board and NFS server is normal.
+ ```
+ mkdir -p /home/sqbin/nfs
+ sudo chmod 777 /home/sqbin/nfs
+ ```
-Start the Ethernet or another type of network, and then run **ping** to check whether the network connection to the server is normal.
+ - Configure and start the NFS server.
-```
-OHOS # ping 10.67.212.178
-[0]Reply from 10.67.212.178: time=1ms TTL=63
-[1]Reply from 10.67.212.178: time=0ms TTL=63
-[2]Reply from 10.67.212.178: time=1ms TTL=63
-[3]Reply from 10.67.212.178: time=1ms TTL=63
---- 10.67.212.178 ping statistics ---
-4 packets transmitted, 4 received, 0 loss
-```
+ Append the following line in the **/etc/exports** file:
-Initialize the NFS client.
+ ```
+ /home/sqbin/nfs *(rw,no_root_squash,async)
+ ```
+
+ **/home/sqbin/nfs** is the root directory shared by the NFS server.
+
+ Start the NFS server.
-```
-OHOS # mkdir /nfs
-OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
-```
+ ```
+ sudo /etc/init.d/nfs-kernel-server start
+ ```
+
+ Restart the NFS server.
-If the following information is displayed, the NFS client is initialized.
+ ```
+ sudo /etc/init.d/nfs-kernel-server restart
+ ```
-```
-OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
-Mount nfs on 10.67.212.178:/home/sqbin/nfs, uid:1011, gid:1000
-Mount nfs finished.
-```
+2. Configure the board as an NFS client.
-This command mounts the **/home/sqbin/nfs** directory on the NFS server whose IP address is 10.67.212.178 to the **/nfs** directory on the OpenHarmony kernel device.
+ In this section, the NFS client is a device running the OpenHarmony kernel.
-> **NOTE:**
->This section assumes that the NFS server is available, that is, the **/home/sqbin/nfs** directory on the NFS server 10.67.212.178 is accessible.
->The **mount** command format is as follows:
->```
->mount nfs
->```
->- **SERVER\_IP** indicates the IP address of the server.
->- **SERVER\_PATH** indicates the path of the shared directory on the NFS server.
->- **CLIENT\_PATH** indicates the NFS path on the local device.
->- **nfs** indicates the path to which the remote shared directory is mounted on the local device.
->Replace the parameters as required.
->If you do not want to restrict the NFS access permission, set the permission of the NFS root directory to **777** on the Linux CLI.
->```
->chmod -R 777 /home/sqbin/nfs
->```
->The NFS client setting is complete, and the NFS file system has been mounted.
+ - Set the hardware connection.
-1. Share files using NFS.
+ Connect the OpenHarmony kernel device to the NFS server. Set their IP addresses in the same network segment. For example, set the IP address of the NFS server to **10.67.212.178/24** and the IP address of the OpenHarmony kernel device to
+ **10.67.212.3/24**. Note that this IP address is an intranet private IP address. Use the actual IP address.
-Create the **dir** directory on the NFS server and save the directory. Run the **ls** command in the OpenHarmony kernel.
+ You can run the **ifconfig** command to check the OpenHarmony kernel device's IP address.
-```
-OHOS # ls /nfs
-```
+ - Start the network and ensure that the network between the board and NFS server is normal.
-The following information is returned from the serial port:
+ Start the Ethernet or another type of network, and then run **ping** to check whether the network connection to the server is normal.
-```
-OHOS # ls /nfs
-Directory /nfs:
-drwxr-xr-x 0 u:0 g:0 dir
-```
-The **dir** directory created on the NFS server has been synchronized to the **/nfs** directory on the client \(OpenHarmony kernel system\).
+ ```
+ OHOS # ping 10.67.212.178
+ [0]Reply from 10.67.212.178: time=1ms TTL=63
+ [1]Reply from 10.67.212.178: time=0ms TTL=63
+ [2]Reply from 10.67.212.178: time=1ms TTL=63
+ [3]Reply from 10.67.212.178: time=1ms TTL=63
+ --- 10.67.212.178 ping statistics ---
+ 4 packets transmitted, 4 received, 0 loss
+ ```
+
+ Initialize the NFS client.
-Similarly, you can create files and directories on the client \(OpenHarmony kernel system\) and access them from the NFS server.
+ ```
+ OHOS # mkdir /nfs
+ OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
+ ```
+
+ If the following information is displayed, the NFS client is initialized.
-> **NOTE:**
->Currently, the NFS client supports some NFS v3 specifications. Therefore, the NFS client is not fully compatible with all types of NFS servers. You are advised to use the Linux NFS server to perform the development.
+ ```
+ OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
+ Mount nfs on 10.67.212.178:/home/sqbin/nfs, uid:1011, gid:1000
+ Mount nfs finished.
+ ```
+
+ This command mounts the **/home/sqbin/nfs** directory on the NFS server (IP address: 10.67.212.178) to the **/nfs** directory on the OpenHarmony kernel device.
+ >  **NOTE**
+ >
+ > This example assumes that the NFS server is available, that is, the **/home/sqbin/nfs** directory on the NFS server 10.67.212.178 is accessible.
+ >
+ > The **mount** command format is as follows:
+ >
+ > ```
+ > mount nfs
+ > ```
+ >
+ > **SERVER_IP** indicates the IP address of the server; **SERVER_PATH** indicates the path of the shared directory on the NFS server; **CLIENT_PATH** indicates the NFS path on the local device; **nfs** indicates the path to which the remote shared directory is mounted on the local device. Replace the parameters as required.
+ >
+ > If you do not want to restrict the NFS access permission, set the permission of the NFS root directory to **777** on the Linux CLI.
+ >
+ > ```
+ > chmod -R 777 /home/sqbin/nfs
+ > ```
+ >
+ > The NFS client setting is complete, and the NFS file system is mounted.
+
+3. Share files using NFS.
+
+ Create the **dir** directory on the NFS server. Run the **ls** command in the OpenHarmony kernel.
+
+ ```
+ OHOS # ls /nfs
+ ```
+
+ The following information is returned from the serial port:
+
+ ```
+ OHOS # ls /nfs
+ Directory /nfs:
+ drwxr-xr-x 0 u:0 g:0 dir
+ ```
+
+ The **dir** directory created on the NFS server has been synchronized to the **/nfs** directory on the client (OpenHarmony kernel system). Similarly, you can create files and directories on the client (OpenHarmony kernel system) and access them from the NFS server.
+
+ >  **NOTE**
+ >
+ > Currently, the NFS client supports some NFS v3 specifications. Therefore, the NFS client is not fully compatible with all types of NFS servers. You are advised to use the Linux NFS server to perform the development.
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md
index a9b031e9f72b535f22f3083491c5b76c08459e3f..261eae927bd78029daead0a19c56aca175a8623e 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md
@@ -1,28 +1,32 @@
# procfs
-## Basic Concepts
+## Basic Concepts
-The proc filesystem \(procfs\) is a virtual file system that displays process or other system information in a file-like structure. It is more convenient to obtain system information in file operation mode than API calling mode.
+The proc filesystem (procfs) is a virtual file system that displays process or other system information in a file-like structure. It is more convenient to obtain system information in file operation mode than API calling mode.
-## Working Principles
-In the OpenHarmony kernel, procfs is automatically mounted to the **/proc** directory during startup. Only the kernel module can create file nodes to provide the query service.
+## Working Principles
-## Development Guidelines
+In the OpenHarmony kernel, procfs is automatically mounted to the **/proc** directory during startup. Only the kernel module can create file nodes to provide the query service.
-To create a procfs file, you need to use **ProcMkdir** to create a directory and use **CreateProcEntry** to create a file. The development of the file node function is to hook the read and write functions to the file created by **CreateProcEntry**. When the procfs file is read or written, the hooked functions will be called to implement custom functions.
-### Development Example
+## Development Guidelines
-The following describes how to create the **/proc/hello/world** file to implement the following functions:
+To create a procfs file, you need to use **ProcMkdir** to create a directory and use **CreateProcEntry** to create a file. The development of the file node function is to hook the read and write functions to the file created by **CreateProcEntry**. When the procfs file is read or written, the hooked functions will be called to implement custom functions.
-1. Create a file in **/proc/hello/world**.
+
+### Development Example
+
+The following describes how to create the **/proc/hello/world** file to implement the following functions:
+
+1. Create a file in **/proc/hello/world**.
2. Read the file. When the file is read, "HelloWorld!" is returned.
3. Write the file and print the data written in the file.
+
```
#include "proc_fs.h"
@@ -48,7 +52,7 @@ static const struct ProcFileOperations HELLO_WORLD_OPS = {
void HelloWorldInit(void)
{
- /* Create the hello directory.*/
+ /* Create the hello directory. */
struct ProcDirEntry *dir = ProcMkdir("hello", NULL);
if (dir == NULL) {
PRINT_ERR("create dir failed!\n");
@@ -69,7 +73,8 @@ void HelloWorldInit(void)
**Verification**
-After the OS startup, run the following command in the shell:
+After the OS startup, run the following commands in the shell:
+
```
OHOS # cat /proc/hello/world
@@ -77,4 +82,3 @@ OHOS # Hello World!
OHOS # echo "yo" > /proc/hello/world
OHOS # your input is: yo
```
-
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md
index 975baff8c25166e4e9afa703c4208aa03af5d066..ee785aeffd5fa016fe4a605183d68324aaff73dc 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md
@@ -1,60 +1,43 @@
# Ramfs
-## Basic Concepts
-Ramfs is a RAM-based file system whose size can be dynamically adjusted. Ramfs does not have a backing store. Directory entries and page caches are allocated when files are written into ramfs. However, data is not written back to any other storage medium. This means that data will be lost after a power outage.
-
-## Working Principles
-
-Ramfs stores all files in RAM, and read/write operations are performed in RAM. Ramfs is generally used to store temporary data or data that needs to be frequently modified, such as the **/tmp** and **/var** directories. Using ramfs reduces the read/write loss of the memory and improves the data read/write speed.
-
-## Development Guidelines
+## Basic Concepts
+Ramfs is a RAM-based file system whose size can be dynamically adjusted. Ramfs does not have a backing store. Directory entries and page caches are allocated when files are written into ramfs. However, data is not written back to any other storage medium. This means that data will be lost after a power outage.
+## Working Principles
+Ramfs stores all files in RAM, and read/write operations are performed in RAM. Ramfs is generally used to store temporary data or data that needs to be frequently modified, such as the **/tmp** and **/var** directories. Using ramfs reduces the read/write loss of the memory and improves the data read/write speed.
+## Development Guidelines
Mount:
-
```
mount(NULL, "/dev/shm", "ramfs", 0, NULL)
```
-
-Create a directory:
-
+Create a directory:
```
mkdir(pathname, mode)
```
-
Create a file:
-
```
open(pathname, O_NONBLOCK | O_CREAT | O_RDWR, mode)
```
-
-Read a directory:
-
+Read a directory:
```
dir = opendir(pathname)
ptr = readdir(dir)
closedir(dir)
```
-
-Delete a file:
-
+Delete a file:
```
unlink(pathname)
```
-
Delete a directory:
-
```
rmdir(pathname)
```
-
-Unmount:
-
+Unmount:
```
umount("/dev/shm")
```
-
-> **CAUTION:**
->- A ramfs file system can be mounted only once. Once mounted to a directory, it cannot be mounted to other directories.
->- Ramfs is under debugging and disabled by default. Do not use it in formal products.
-
+>  **CAUTION**
+> - A ramfs file system can be mounted only once. Once mounted to a directory, it cannot be mounted to other directories.
+>
+> - Ramfs is under debugging and disabled by default. Do not use it in formal products.
diff --git a/en/device-dev/kernel/kernel-small-debug-shell-guide.md b/en/device-dev/kernel/kernel-small-debug-shell-guide.md
index d20dd2abf4420eb5f115171aafaa697108f38ed7..3bb07ddf59843ff76a2b7f4472ecc9a089f99421 100644
--- a/en/device-dev/kernel/kernel-small-debug-shell-guide.md
+++ b/en/device-dev/kernel/kernel-small-debug-shell-guide.md
@@ -1,164 +1,87 @@
-# Shell Command Development Guidelines
-
-
-## Development Guidelines
+# Shell Command Development
You can perform the following operations to add shell commands:
-1. Include the following header files:
-
- ```
- #include "shell.h"
- #include "shcmd.h"
- ```
-
-2. Register commands. You can register commands either statically or dynamically when the system is running. In most cases, static registration is widely used by common system commands, and dynamic registration is widely used by user commands.
-
- 1. Static registration:
-
- 1. Register a command using a macro.
-
- The prototype of the macro is as follows:
-
- ```
- SHELLCMD_ENTRY(l, cmdType, cmdKey, paraNum, cmdHook)
- ```
-
- **Table 1** Parameters of the SHELLCMD\_ENTRY macro
-
-
- Parameter
- |
- Description
- |
-
-
- l
- |
- Specifies the global variable name passed in static registration. Note that the name cannot be the same as other symbol names in the system.
- |
-
- cmdType
- |
- Specifies the command type, which can be any of the following:
- CMD_TYPE_EX: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter ls /ramfs, only /ramfs will be passed to the registration function, and ls will be masked.
- CMD_TYPE_STD: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed.
-
- |
-
- cmdKey
- |
- Specifies the command keyword, which is the name used to access a shell function.
- |
-
- paraNum
- |
- Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently.
- |
-
- cmdHook
- |
- Specifies the address of the execution function, that is, the function executed by the command.
- |
-
-
-
-
- Example:
-
- ```
- SHELLCMD_ENTRY(ls_shellcmd, CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
- ```
-
- 2. Add options to the **build/mk/liteos\_tables\_ldflags.mk** file.
-
- For example, when registering the **ls** command, add **-uls\_shellcmd** to the **build/mk/liteos\_tables\_ldflags.mk** file. **-u** is followed by the first parameter of **SHELLCMD\_ENTRY**.
-
- 2. Dynamic registration:
-
- The prototype of the function to register is as follows:
-
- ```
- UINT32 osCmdReg(CmdT ype cmdType, CHAR *cmdKey, UINT32 paraNum, CmdCallBackFunc cmdProc)
- ```
-
- **Table 2** Parameters of UINT32 osCmdReg
-
-
- Parameter
- |
- Description
- |
-
-
- cmdType
- |
- Specifies the command type, which can be any of the following:
- CMD_TYPE_EX: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter ls /ramfs, only /ramfs will be passed to the registration function, and ls will be masked.
- CMD_TYPE_STD: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed.
-
- |
-
- cmdKey
- |
- Specifies the command keyword, which is the name used to access a shell function.
- |
-
- paraNum
- |
- Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently. The default value is XARGS(0xFFFFFFFF).
- |
-
- cmdHook
- |
- Specifies the address of the execution function, that is, the function executed by the command.
- |
-
-
-
-
- Example:
-
- ```
- osCmdReg(CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
- ```
+1. Include header files.
- > **NOTE:**
- >The command keyword must be unique. That is, two different commands cannot share the same command keyword. Otherwise, only one command is executed.
- >When executing user commands sharing the same keyword, the shell executes only the first command in the **help** commands.
+
+ ```
+ #include "shell.h"
+ #include "shcmd.h"
+ ```
-3. Use the following function prototype to add built-in commands:
+2. Register commands.
- ```
- UINT32 osShellCmdLs(UINT32 argc, CHAR **argv)
- ```
+ You can register commands either statically or dynamically (with the system running). Generally, common system commands are registered statically, and user commands are registered dynamically.
- **Table 3** Parameters of osShellCmdLs
+ - Static registration
-
- Parameter
- |
- Description
- |
-
-
- argc
- |
- Specifies the number of parameters in the shell command.
- |
-
- argv
- |
- Specifies a pointer array, where each element points to a string. You can determine whether to pass the command keyword to the registration function by specifying the command type.
- |
-
-
-
+ 1. Register a command using a macro.
-4. Enter the shell command in either of the following methods:
- - Enter the shell command in a serial port tool.
+ The prototype of the macro is as follows:
- - Enter the shell command in the Telnet tool. For details, see [telnet](kernel-small-debug-shell-net-telnet.md).
+ ```
+ SHELLCMD_ENTRY(l, cmdType, cmdKey, paraNum, cmdHook)
+ ```
+ **Table 1** SHELLCMD_ENTRY parameters
+ | Parameter| Description|
+ | -------- | -------- |
+ | l | Specifies the global variable name passed in static registration. Note that the name cannot be the same as other symbol names in the system.|
+ | cmdType | Specifies the command type, which can be any of the following:
**CMD_TYPE_EX**: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter **ls /ramfs**, only **/ramfs** will be passed to the registration function and **ls** will be masked.
**CMD_TYPE_STD**: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed. |
+ | cmdKey | Specifies the command keyword, which is the name used to access a shell function.|
+ | paraNum | Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently.|
+ | cmdHook | Specifies the address of the execution function, that is, the function executed by the command.|
+ Example:
+
+ ```
+ SHELLCMD_ENTRY(ls_shellcmd, CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
+ ```
+
+
+ 2. Add options to the **build/mk/liteos_tables_ldflags.mk** file.
+
+ For example, when registering the **ls** command, add **-uls_shellcmd** to the **build/mk/liteos_tables_ldflags.mk** file. **-u** is followed by the first parameter of **SHELLCMD_ENTRY**.
+
+ - Dynamic registration
+
+ The prototype of the function to register is as follows:
+
+ ```
+ UINT32 osCmdReg(CmdT ype cmdType, CHAR *cmdKey, UINT32 paraNum, CmdCallBackFunc cmdProc)
+ ```
+ **Table 2** UINT32 osCmdReg parameters
+ | Parameter| Description|
+ | -------- | -------- |
+ | cmdType | Specifies the command type, which can be any of the following:
**CMD_TYPE_EX**: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter **ls /ramfs**, only **/ramfs** will be passed to the registration function, and **ls** will be masked.
**CMD_TYPE_STD**: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed.|
+ | cmdKey | Specifies the command keyword, which is the name used to access a shell function.|
+ | paraNum | Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently. The default value is **XARGS(0xFFFFFFFF)**.|
+ | cmdHook | Specifies the address of the execution function, that is, the function executed by the command.|
+
+ Example:
+ ```
+ osCmdReg(CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
+ ```
+  NOTE
+ > The command keyword must be unique. That is, two different commands cannot share the same command keyword. Otherwise, only one command is executed. When executing user commands sharing the same keyword, the shell executes only the first command in the **help** commands.
+
+
+3. Use the following function prototype to add built-in commands:
+
+ ```
+ UINT32 osShellCmdLs(UINT32 argc, CHAR **argv)
+ ```
+
+ **Table 3** osShellCmdLs parameters
+
+ | Parameter| Description|
+ | -------- | -------- |
+ | argc | Specifies the number of parameters in the shell command.|
+ | argv | Specifies a pointer array, where each element points to a string. You can determine whether to pass the command keyword to the registration function by specifying the command type.|
+
+4. Enter the shell command in either of the following methods:
+
+ - Enter the shell command using a serial port tool.
+ - Enter the shell command using the Telnet tool. For details about how to use Telnet, see [telnet](../kernel/kernel-small-debug-shell-net-telnet.md).
diff --git a/en/device-dev/kernel/kernel-small-debug-shell-magickey.md b/en/device-dev/kernel/kernel-small-debug-shell-magickey.md
index 95dd7f69f0160ae301c51a210ddb51c3c357728b..80248ba4e5fbc59fbef823ca8b34e8584709c243 100644
--- a/en/device-dev/kernel/kernel-small-debug-shell-magickey.md
+++ b/en/device-dev/kernel/kernel-small-debug-shell-magickey.md
@@ -1,42 +1,36 @@
# Magic Key
-## When to Use
+## When to Use
-When the system does not respond, you can use the magic key to check whether the system is locked and interrupted \(the magic key also does not respond\) or view the system task running status.
+When the system does not respond, you can use the magic key function to check whether the system is suspended by an interrupt lock (the magic key also does not respond) or view the system task running status.
-If an interrupt is responded, you can use the magic key to check the task CPU usage \(**cpup**\) and find out the task with the highest CPU usage. Generally, the task with a higher priority preempts the CPU resources.
+If interrupts are responded, you can use the magic key to check the task CPU usage (**cpup**) and find out the task with the highest CPU usage. Generally, the task with a higher priority preempts the CPU resources.
-## How to Use
-1. Configure the macro **LOSCFG\_ENABLE\_MAGICKEY**.
+## How to Use
-The magic key depends on the **LOSCFG\_ENABLE\_MAGICKEY** macro. Before using the magic key, select **Enable MAGIC KEY** on **menuconfig**.
+1. Configure the macro **LOSCFG_ENABLE_MAGICKEY**.
-**Enable MAGIC KEY**: **Debug** ---\> **Enable MAGIC KEY**
+ The magic key depends on the **LOSCFG_ENABLE_MAGICKEY** macro. Before using the magic key, select **Enable MAGIC KEY** (**Debug** ---> **Enable MAGIC KEY**) on **menuconfig**. The magic key cannot be used if this option is disabled.
-The magic key cannot be used if this macro is disabled.
+ >  **NOTE**
+ >
+ > On **menuconfig**, you can move the cursor to **LOSCFG_ENABLE_MAGICKEY** and enter a question mark (?) to view help Information.
+
+2. Press **Ctrl+R** to enable the magic key.
-> **NOTE:**
->On **menuconfig**, you can move the cursor to **LOSCFG\_ENABLE\_MAGICKEY** and type a question mark \(?\) to view help information.
+ When the UART or USB-to-virtual serial port is connected, press **Ctrl+R**. If "Magic key on" is displayed, the magic key is enabled. To disable it, press **Ctrl+R** again. If "Magic key off" is displayed, the magic key is disabled.
-2. Press **Ctrl+R** to enable the magic key.
+ The functions of the magic key are as follows:
-When the UART or USB-to-virtual serial port is connected, press **Ctrl+R**. If "Magic key on" is displayed, the magic key is enabled.
+ - **Ctrl+Z**: displays help information about the related magic keys.
-To disable the magic key, press **Ctrl+R** again. If "Magic key off" is displayed, the magic key is disabled.
+ - **Ctrl+T**: displays task information.
-You can use the magic key combinations as follows:
-
-- **Ctrl+Z**: displays help information about the related magic keys.
-
-- **Ctrl+T**: displays task information.
-
-- **Ctrl+P**: allows the system to proactively enter the panic state. After the panic-related information is printed, the system is suspended.
-
-- **Ctrl+E**: Checks the integrity of the memory pool. If an error is detected, the system displays an error message. If no error is detected, the system displays "system memcheck over, all passed!".
-
-
-> **NOTICE:**
->If magic key is enabled, when special characters need to be entered through the UART or USB-to-virtual serial port, avoid using characters the same as the magic keys. Otherwise, the magic key may be triggered by mistake, causing errors in the original design.
+ - **Ctrl+P**: allows the system to proactively enter the panic state. After the panic-related information is printed, the system is suspended.
+ - **Ctrl+E**: Checks the integrity of the memory pool. If an error is detected, the system displays an error message. If no error is detected, the system displays "system memcheck over, all passed!".
+
+ >  **NOTICE**
+ > If magic key is enabled, when special characters need to be entered through the UART or USB-to-virtual serial port, avoid using characters the same as the magic keys. Otherwise, the magic key may be triggered by mistake, causing errors in the original design.
diff --git a/en/device-dev/kernel/kernel-small-debug-shell-overview.md b/en/device-dev/kernel/kernel-small-debug-shell-overview.md
index 5ac89f7eb900197534dca3a3d73846a9bdde0b6f..7c1ce9d0e6e8d0caf21fc5bd38d7c4f976de65eb 100644
--- a/en/device-dev/kernel/kernel-small-debug-shell-overview.md
+++ b/en/device-dev/kernel/kernel-small-debug-shell-overview.md
@@ -1,35 +1,34 @@
-# Introduction to the Shell
+# Shell
The shell provided by the OpenHarmony kernel supports commonly used debugging commands. You can also add and customize commands to the shell of the OpenHarmony kernel to address your service needs. The common debugging commands include the following:
-- System commands: commands used to query information, such as system tasks, semaphores, system software timers, CPU usage, and interrupts.
-- File commands: commands used to manage files and directories, such as **ls** and **cd**.
+- System commands: commands used to query information, such as system tasks, semaphores, system software timers, CPU usage, and interrupts.
-- Network commands: commands used to query the IP addresses of other devices connected to the development board, querying the IP address of the local device, testing network connectivity, and setting the access point \(AP\) and station \(STA\) modes of the development board.
+- File commands: commands used to manage files and directories, such as **ls** and **cd**.
- For details about how to add a command, see [Shell Command Development Guidelines](kernel-small-debug-shell-guide.md) and [Shell Command Programming Example](kernel-small-debug-shell-build.md).
+- Network commands: commands used to query the IP addresses of other devices connected to the development board, querying the IP address of the local device, testing network connectivity, and setting the access point (AP) and station (STA) modes of the development board.
+ For details about the process of adding commands, see [Shell Command Development](../kernel/kernel-small-debug-shell-guide.md) and [Shell Command Programming Example](../kernel/kernel-small-debug-shell-build.md).
-## Important Notes
-Note the following when using the shell:
+ **Precautions**
-- You can use the **exec** command to run executable files.
-- The shell supports English input by default. To delete the Chinese characters entered in UTF-8 format, press the backspace key for three times.
+Note the following when using shell:
-- When entering shell commands, file names, and directory names, you can press **Tab** to enable automatic completion. If there are multiple completions, multiple items are printed based on the same characters they have. If more than 24 lines of completions are available, the system displays the message "Display all num possibilities?\(y/n\)", asking you to determine whether to print all items. You can enter **y** to print all items or enter **n** to exit the printing. If more than 24 lines are printed after your selection, the system displays "--More--". In this case, you can press **Enter** to continue the printing or press **q** \(or **Ctrl+c**\) to exit.
+- You can use the **exec** command to run executable files.
-- The shell working directory is separated from the system working directory. You can run commands such as **cd** and **pwd** on the shell to perform operations on the shell working directory, and run commands such as **chdir** and **getcwd** to perform operations on the system working directory. Pay special attention when an input parameter in a file system operation command is a relative path.
+- The shell supports English input by default. To delete the Chinese characters entered in UTF-8 format, press the backspace key for three times.
-- Before using network shell commands, you need to call the **tcpip\_init** function to initialize the network and set up the Telnet connection. By default, the kernel does not call **tcpip\_init**.
+- When entering shell commands, file names, and directory names, you can press **Tab** to enable automatic completion. If there are multiple completions, multiple items are printed based on the same characters they have. If more than 24 lines of completions are available, the system displays the message "Display all num possibilities?(y/n)", asking you to determine whether to print all items. You can enter **y** to print all items or enter **n** to exit the printing. If more than 24 lines are printed after your selection, the system displays "--More--". In this case, you can press **Enter** to continue the printing or press **q** (or **Ctrl+c**) to exit.
-- You are not advised to run shell commands to perform operations on device files in the **/dev** directory, which may cause unexpected results.
+- The shell working directory is separated from the system working directory. You can run commands such as **cd** and **pwd** on the shell to perform operations on the shell working directory, and run commands such as **chdir** and **getcwd** to perform operations on the system working directory. Pay special attention when an input parameter in a file system operation command is a relative path.
-- The shell functions do not comply with the POSIX standards and are used only for debugging.
-
- > **NOTICE**
- >The shell functions are used for debugging only and can be enabled only in the Debug version \(by enabling the **LOSCFG\_DEBUG\_VERSION** configuration item using **menuconfig**\).
+- Before using network shell commands, you need to call the **tcpip_init** function to initialize the network and set up the Telnet connection. By default, the kernel does not call **tcpip_init**.
+- You are not advised to run shell commands to perform operations on device files in the **/dev** directory, which may cause unexpected results.
+- The shell functions do not comply with the POSIX standards and are used only for debugging.
+ >  **NOTICE**
+ > The shell functions are used for debugging only and can be enabled only in the Debug version (by enabling **LOSCFG_DEBUG_VERSION** using **menuconfig**).
diff --git a/en/device-dev/kernel/kernel-small-debug-trace.md b/en/device-dev/kernel/kernel-small-debug-trace.md
index b808e35d2515e9ede4def18ec35fd7a06a638d59..df41fd67f3d7d2ddc196e1ea4ddc3c10e701aa95 100644
--- a/en/device-dev/kernel/kernel-small-debug-trace.md
+++ b/en/device-dev/kernel/kernel-small-debug-trace.md
@@ -1,10 +1,12 @@
# Trace
-## Basic Concepts
+
+## Basic Concepts
Trace helps you learn about the kernel running process and the execution sequence of modules and tasks. With the information, you can better understand the code running process of the kernel and locate time sequence problems.
-## Working Principles
+
+## Working Principles
The kernel provides a hook framework to embed hooks in the main process of each module. In the initial startup phase of the kernel, the trace function is initialized and the trace handlers are registered with the hooks.
@@ -16,170 +18,117 @@ In offline mode, trace frames are stored in a circular buffer. If too many frame

-The online mode must be used with the integrated development environment \(IDE\). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner.
-
-## **Available APIs**
-
-### Kernel Mode
-
-The trace module of the OpenHarmony LiteOS-A kernel provides the following functions. For details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h) reference.
-
-**Table 1** Trace module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Starting and stopping trace
- |
-LOS_TraceStart
- |
-Starts trace.
- |
-
-LOS_TraceStop
- |
-Stops trace.
- |
-
-Managing trace records
- |
-LOS_TraceRecordDump
- |
-Exports data in the trace buffer.
- |
-
-LOS_TraceRecordGet
- |
-Obtains the start address of the trace buffer.
- |
-
-LOS_TraceReset
- |
-Clears events in the trace buffer.
- |
-
-Filtering trace records
- |
-LOS_TraceEventMaskSet
- |
-Sets the event mask to trace only events of the specified modules.
- |
-
-Masking events of specified interrupt IDs
- |
-LOS_TraceHwiFilterHookReg
- |
-Registers a hook to filter out events of specified interrupt IDs.
- |
-
-Performing function instrumentation
- |
-LOS_TRACE_EASY
- |
-Performs simple instrumentation.
- |
-
-LOS_TRACE
- |
-Performs standard instrumentation.
- |
-
-
-
-
-- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
- - **LOS\_TRACE\_EASY\(TYPE, IDENTITY, params...\)** for simple instrumentation
- - You only need to insert this API into the source code.
- - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
- - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
- - **Params** specifies the event parameters. The value is of the **UIntPtr** type.
-
- Example:
-
- ```
- Perform simple instrumentation for reading and writing files fd1 and fd2.
- Set TYPE to 1 for read operations and 2 for write operations.
- Insert the following to the position where the fd1 file is read:
- LOS_TRACE_EASY(1, fd1, flag, size);
- Insert the following to the position where the fd2 file is read:
- LOS_TRACE_EASY(1, fd2, flag, size);
- Insert the following to the position where the fd1 file is written:
- LOS_TRACE_EASY(2, fd1, flag, size);
- Insert the following in the position where the fd2 file is written:
- LOS_TRACE_EASY(2, fd2, flag, size);
- ```
-
- - **LOS\_TRACE\(TYPE, IDENTITY, params...\)** for standard instrumentation.
- - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
- - **TYPE** specifies the event type. You can define the event type in **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**. For details about methods and rules for defining events, see other event types.
- - The **IDENTITY** and **Params** are the same as those of simple instrumentation.
-
- Example:
-
- ```
- 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK.
- Format: TRACE_#MOD#_FLAG (MOD indicates the module name)
- Example:
- TRACE_FS_FLAG = 0x4000
- 2. Define the event type in enum LOS_TRACE_TYPE.
- Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER
- Example:
- FS_READ = TRACE_FS_FLAG | 0; // Read files
- FS_WRITE = TRACE_FS_FLAG | 1; // Write files
- 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format.
- #TYPE# is the #TYPE# defined in step 2.
- Example:
- #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size
- The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required.
- If no parameter is specified, events of this type are not traced.
- #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced.
- 4. Insert a code stub in a proper position.
- Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...))
- LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files
- The parameters following #TYPE# are the input parameter of the FS_READ_PARAMS function in step 3.
- ```
-
- > **NOTE:**
- >The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\\include\\los\_trace.h**.
-
-
-
-- For **LOS\_TraceEventMaskSet\(UINT32 mask\)**, only the most significant 28 bits \(corresponding to the enable bit of the module in **LOS\_TRACE\_MASK**\) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS\_TraceEventMaskSet\(0x202\)**, the effective mask is **0x200 \(TRACE\_QUE\_FLAG\)** and all events of the QUE module are collected. The recommended method is **LOS\_TraceEventMaskSet\(TRACE\_EVENT\_FLAG | TRACE\_MUX\_FLAG | TRACE\_SEM\_FLAG | TRACE\_QUE\_FLAG\);**.
-- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE\_MAX\_FLAG**.
-- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS\_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
-- The typical trace operation process includes **LOS\_TraceStart**, **LOS\_TraceStop**, and **LOS\_TraceRecordDump**.
-- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
-
- The sample code is as follows:
-
- ```
- BOOL Example_HwiNumFilter(UINT32 hwiNum)
- {
- if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) {
- return TRUE;
- }
- return FALSE;
+The online mode must be used with the integrated development environment (IDE). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner.
+
+
+## Available APIs
+
+
+### Kernel Mode
+
+The trace module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
+
+ **Table 1** APIs of the trace module
+
+| Category| Description|
+| -------- | -------- |
+| Starting/Stopping trace| **LOS_TraceStart**: starts trace.
**LOS_TraceStop**: stops trace. |
+| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.
**LOS_TraceRecordGet**: obtains the start address of the trace buffer.
**LOS_TraceReset**: clears events in the trace buffer. |
+| Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.|
+| Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.|
+| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.
**LOS_TRACE**: performs standard instrumentation. |
+
+You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
+
+- **LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation
+
+ - You only need to insert this API into the source code.
+ - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
+ - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
+ - **Params** specifies the event parameters. The value is of the **UIntPtr** type.
+ Example:
+
+ ```
+ Perform simple instrumentation for reading and writing files fd1 and fd2.
+ Set TYPE to 1 for read operations and 2 for write operations.
+ Insert the following to the position where the fd1 file is read:
+ LOS_TRACE_EASY(1, fd1, flag, size);
+ Insert the following to the position where the fd2 file is read:
+ LOS_TRACE_EASY(1, fd2, flag, size);
+ Insert the following to the position where the fd1 file is written:
+ LOS_TRACE_EASY(2, fd1, flag, size);
+ Insert the following in the position where the fd2 file is written:
+ LOS_TRACE_EASY(2, fd2, flag, size);
+ ```
+- **LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation.
+ - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
+ - **TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types.
+ - The **IDENTITY** and **Params** are the same as those of simple instrumentation.
+ Example:
+
+ ```
+ 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK.
+ Format: TRACE_#MOD#_FLAG (MOD indicates the module name)
+ Example:
+ TRACE_FS_FLAG = 0x4000
+ 2. Define the event type in **enum LOS_TRACE_TYPE**.
+ Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER
+ Example:
+ FS_READ = TRACE_FS_FLAG | 0; // Read files.
+ FS_WRITE = TRACE_FS_FLAG | 1; // Write files.
+ 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format.
+ #TYPE# is the #TYPE# defined in step 2.
+ Example:
+ #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size
+ The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required.
+ If no parameter is specified, events of this type are not traced.
+ #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced.
+ 4. Insert a code stub in a proper position.
+ Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...))
+ LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files.
+ The parameters following #TYPE# are the input parameter of the **FS_READ_PARAMS** function in step 3.
+ ```
+
+ >  **NOTE**
+ > The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\include\los_trace.h**.
+
+For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**.
+
+To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**.
+
+The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
+
+The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**.
+
+You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
+
+Example:
+
+```
+BOOL Example_HwiNumFilter(UINT32 hwiNum)
+{
+ if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) {
+ return TRUE;
}
- LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
- ```
+ return FALSE;
+}
+LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
+```
+
+The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced.
+
+### User Mode
-The interrupt events with interrupt ID of **TIMER\_INT** or **DMA\_INT** are not traced.
+The trace character device is added in **/dev/trace**. You can use **read()**, **write()**, and **ioctl()** on the device node to read, write, and control trace in user mode.
-### User Mode
+- **read()**: reads the trace data in user mode.
-The trace character device is added in **/dev/trace**. You can use **read\(\)**, **write\(\)**, and **ioctl\(\)** on the device node to read, write, and control trace in user mode.
+- **write()**: writes an event in user mode.
-- **read\(\)**: reads the trace data in user mode.
-- **write\(\)**: writes an event in user mode.
-- **ioctl\(\)**: performs user-mode trace operations, including:
+- **ioctl()**: performs user-mode trace operations, including:
+
```
#define TRACE_IOC_MAGIC 'T'
#define TRACE_START _IO(TRACE_IOC_MAGIC, 1)
@@ -189,134 +138,77 @@ The trace character device is added in **/dev/trace**. You can use **read\(\)*
#define TRACE_SET_MASK _IO(TRACE_IOC_MAGIC, 5)
```
-The operations specified by the input parameter of **ioctl\(\)** correspond to **LOS\_TraceStart**, **LOS\_TraceStop**, **LOS\_TraceReset**, **LOS\_TraceRecordDump**, and **LOS\_TraceEventMaskSet**, respectively.
+The operations specified by the input parameter of **ioctl()** correspond to **LOS_TraceStart**, **LOS_TraceStop**, **LOS_TraceReset**, **LOS_TraceRecordDump**, and **LOS_TraceEventMaskSet**, respectively.
+
+For details, see [User-Mode Development Example](kernel-small-debug-trace.md#user-mode).
+
-For more details, see [User-mode Programming Example](https://gitee.com/openharmony/docs/blob/70744e1e0e34d66e11108a00c8db494eea49dd02/en/device-dev/kernel/kernel-small-debug-trace.md#section4.2.2).
+## Development Guidelines
-## Development Guidelines
-### Kernel-mode Development Process
+### Kernel-Mode Development Process
The typical trace process is as follows:
-1. Configure the macro related to the trace module.
-
- Configure the trace macro **LOSCFG\_KERNEL\_TRACE**, which is disabled by default. Run the **make update\_config** command in the **kernel/liteos\_a** directory, choose **Kernel** \> **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**.
-
-
- Configuration
- |
- menuconfig Option
- |
- Description
- |
- Value
- |
-
-
- LOSCFG_KERNEL_TRACE
- |
- Enable Trace Feature
- |
- Specifies whether to enable the trace feature.
- |
- YES/NO
- |
-
- LOSCFG_RECORDER_MODE_OFFLINE
- |
- Trace work mode ->Offline mode
- |
- Specifies whether to enable the online trace mode.
- |
- YES/NO
- |
-
- LOSCFG_RECORDER_MODE_ONLINE
- |
- Trace work mode ->Online mode
- |
- Specifies whether to enable the offline trace mode.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_CLIENT_INTERACT
- |
- Enable Trace Client Visualization and Control
- |
- Specifies whether to enable interaction with Trace IDE (dev tools), including data visualization and process control.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_FRAME_CORE_MSG
- |
- Enable Record more extended content ->Record cpuid, hardware interrupt status, task lock status
- |
- Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_FRAME_EVENT_COUNT
- |
- Enable Record more extended content ->Record event count, which indicate the sequence of happend events
- |
- Specifies whether to enables recording of the event sequence number.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_FRAME_MAX_PARAMS
- |
- Record max params
- |
- Specifies the maximum number of parameters for event recording.
- |
- INT
- |
-
- LOSCFG_TRACE_BUFFER_SIZE
- |
- Trace record buffer size
- |
- Specifies the trace buffer size.
- |
- INT
- |
-
-
-
-
-2. \(Optional\) Preset event parameters and stubs \(or use the default event parameter settings and event stubs\).
-3. \(Optional\) Call **LOS\_TraceStop** to stop trace and call **LOS\_TraceReset** to clear the trace buffer. \(Trace is started by default.\)
-4. \(Optional\) Call **LOS\_TraceEventMaskSet** to set the event mask for trace \(only the interrupts and task events are enabled by default\). For details about the event mask, see **LOS\_TRACE\_MASK** in **los\_trace.h**.
-5. Call **LOS\_TraceStart** at the start of the code where the event needs to be traced.
-6. Call **LOS\_TraceStop** at the end of the code where the event needs to be traced.
-7. Call **LOS\_TraceRecordDump** to output the data in the buffer. \(The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.\)
-
-The methods in steps 3 to 7 are encapsulated with shell commands. After the shell is enabled, the corresponding commands can be executed. The mapping is as follows:
-
-- LOS\_TraceReset —— trace\_reset
-- LOS\_TraceEventMaskSet —— trace\_mask
-- LOS\_TraceStart —— trace\_start
-- LOS\_TraceStop —— trace\_stop
-- LOS\_TraceRecordDump —— trace\_dump
-
-## Kernel-mode Programming Example
+1. Configure the macro related to the trace module.
+
+ Configure the macro **LOSCFG_KERNEL_TRACE**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel** > **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**.
+
+| Configuration Item | menuconfig Option| Description| Value|
+| -------- | -------- | -------- | -------- |
+| LOSCFG_KERNEL_TRACE | Enable Trace Feature | Specifies whether to enable the trace feature.| YES/NO |
+| LOSCFG_RECORDER_MODE_OFFLINE | Trace work mode ->Offline mode | Specifies whether to enable the online trace mode.| YES/NO |
+| LOSCFG_RECORDER_MODE_ONLINE | Trace work mode ->Online mode | Specifies whether to enable the offline trace mode.| YES/NO |
+| LOSCFG_TRACE_CLIENT_INTERACT | Enable Trace Client Visualization and Control | Enables interaction with Trace IDE (dev tools), including data visualization and process control.| YES/NO |
+| LOSCFG_TRACE_FRAME_CORE_MSG | Enable Record more extended content -
>Record cpuid, hardware interrupt
status, task lock status | Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.| YES/NO |
+| LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable Record more extended content
->Record event count,
which indicate the sequence of happend events | Specifies whether to enables recording of the event sequence number.| YES/NO |
+| LOSCFG_TRACE_FRAME_MAX_PARAMS | Record max params | Specifies the maximum number of parameters for event recording.| INT |
+| LOSCFG_TRACE_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT |
+
+2. (Optional) Preset event parameters and stubs (or use the default event parameter settings and event stubs).
+
+3. (Optional) Call **LOS_TraceStop** to stop trace and call **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.)
+
+4. (Optional) Call **LOS_TraceEventMaskSet** to set the event mask for trace (only the interrupts and task events are enabled by default). For details about the event mask, see **LOS_TRACE_MASK** in **los_trace.h**.
+
+5. Call **LOS_TraceStart** at the start of the code where the event needs to be traced.
+
+6. Call **LOS_TraceStop** at the end of the code where the event needs to be traced.
+
+7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.)
+
+The methods in steps 3 to 7 are encapsulated with shell commands. You can run these commands on shell. The mappings between the functions and commands are as follows:
+
+- LOS_TraceReset —— trace_reset
+
+- LOS_TraceEventMaskSet —— trace_mask
+
+- LOS_TraceStart —— trace_start
+
+- LOS_TraceStop —— trace_stop
+
+- LOS_TraceRecordDump —— trace_dump
+
+
+### Kernel-Mode Development Example
This example implements the following:
-1. Create a trace task.
-2. Set the event mask.
-3. Start trace.
-4. Stop trace.
-5. Output trace data in the specified format.
+1. Create a trace task.
+
+2. Set the event mask.
+
+3. Start trace.
+
+4. Stop trace.
+
+5. Output trace data in the specified format.
+
+
+### Kernel-Mode Sample Code
-## Kernel-mode Sample Code
+The sample code is as follows:
-The code is as follows:
```
#include "los_trace.h"
@@ -331,21 +223,21 @@ VOID Example_Trace(VOID)
dprintf("trace start error\n");
return;
}
- /* Trigger a task switching event.*/
+ /* Trigger a task switching event. */
LOS_TaskDelay(1);
LOS_TaskDelay(1);
LOS_TaskDelay(1);
- /* Stop trace.*/
+ /* Stop trace. */
LOS_TraceStop();
LOS_TraceRecordDump(FALSE);
}
UINT32 Example_Trace_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S traceTestTask;
- /* Create a trace task. */
+ /* Create a trace task. */
memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S));
traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace;
- traceTestTask.pcName = "TestTraceTsk"; /* Trace task name*/
+ traceTestTask.pcName = "TestTraceTsk"; /* Test task name. */
traceTestTask.uwStackSize = 0x800;
traceTestTask.usTaskPrio = 5;
traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
@@ -354,22 +246,24 @@ UINT32 Example_Trace_test(VOID){
dprintf("TraceTestTask create failed .\n");
return LOS_NOK;
}
- /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then restart trace. */
+ /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then start trace. */
LOS_TraceStop();
LOS_TraceReset();
- /* Enable trace of the Task module events. */
+ /* Enable trace of the Task module events. */
LOS_TraceEventMaskSet(TRACE_TASK_FLAG);
return LOS_OK;
}
LOS_MODULE_INIT(Example_Trace_test, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
-## Verification
+
+### Verification
The output is as follows:
+
```
-*******TraceInfo begin*******
+***TraceInfo begin***
clockFreq = 50000000
CurEvtIndex = 7
Index Time(cycles) EventType CurTask Identity params
@@ -381,36 +275,41 @@ Index Time(cycles) EventType CurTask Identity params
5 0x36eec810 0x45 0xc 0x1 0x9 0x8 0x1f
6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0
7 0x37070e59 0x45 0x0 0x1 0x0 0x8 0x1f
-*******TraceInfo end*******
+***TraceInfo end***
```
The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event.
-- **EventType**: event type. For details, see **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**.
-- **CurrentTask**: ID of the running task.
-- **Identity**: object of the event operation. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**.
-- **params**: event parameters. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**.
+- **EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**.
+
+- **CurrentTask**: ID of the running task.
+
+- **Identity**: object of the event operation. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
+
+- **params**: event parameters. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
The following uses output No. 0 as an example.
+
```
Index Time(cycles) EventType CurTask Identity params
0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4
```
-- **Time \(cycles\)** can be converted into time \(in seconds\) by dividing the cycles by clockFreq.
-- **0x45** indicates the task switching event. **0x1** is the ID of the task in running.
-- For details about the meanings of **Identity** and **params**, see the **TASK\_SWITCH\_PARAMS** macro.
+- **Time (cycles)** can be converted into time (in seconds) by dividing the cycles by clockFreq.
+
+- **0x45** indicates the task switching event. **0x1** is the ID of the task in running.
+
+- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro.
```
#define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \
taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus
```
-Because of **\#TYPE\#\_PARAMS\(IDENTITY, parma1...\) IDENTITY, ...**, **Identity** is **taskId \(0x0\)** and the first parameter is **oldPriority \(0x1f\)**.
-
-> **NOTE:**
->The number of **param**s is specified by the **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** parameter. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** based on service requirements.
+Because of **#TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ...**, **Identity** is **taskId (0x0)** and the first parameter is **oldPriority (0x1f)**.
-Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
+>  **NOTE**
+> The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements.
+Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
diff --git a/en/device-dev/kernel/kernel-small-memory-lms.md b/en/device-dev/kernel/kernel-small-memory-lms.md
index 74595cb951918bad29df9240c52395866cc5e853..277cbea8a28268a9c4597be980a22bb69f8f85f8 100644
--- a/en/device-dev/kernel/kernel-small-memory-lms.md
+++ b/en/device-dev/kernel/kernel-small-memory-lms.md
@@ -1,186 +1,119 @@
# LMS
-## Basic Concepts
+## Basic Concepts
-Lite Memory Sanitizer \(LMS\) is a tool used to detect memory errors on a real-time basis. LMS can detect buffer overflow, Use-After-Free \(UAF\), and double free errors in real time, and notify the operating system immediately. Together with locating methods such as Backtrace, LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors.
+Lite Memory Sanitizer (LMS) is a tool used to detect memory errors on a real-time basis. LMS can detect buffer overflow, Use-After-Free (UAF), and double free errors in real time, and notify the operating system immediately. Together with locating methods such as Backtrace, LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors.
The LMS module of the OpenHarmony LiteOS-A kernel provides the following functions:
-- Supports check of multiple memory pools.
-- Checks the memory allocated by **LOS\_MemAlloc**, **LOS\_MemAllocAlign**, and **LOS\_MemRealloc**.
-- Checks the memory when bounds-checking functions are called \(enabled by default\).
-- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called.
-
-## Working Principles
-
-LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool.
-
-- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state.
-- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state.
-- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported.
-- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported.
-
-## Available APIs
-
-### Kernel Mode
-
-The LMS module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_lms.h) reference.
-
-**Table 1** LMS module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Adding a memory pool to be checked
- |
-LOS_LmsCheckPoolAdd
- |
-Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, LOS_MemInit calls this API to add the initialized memory pool to the LMS check linked list by default.
- |
-
-Deleting a memory pool from the LMS check linked list
- |
-LOS_LmsCheckPoolDel
- |
-Cancels the validity check on the specified memory pool.
- |
-
-Protecting a specified memory chunk
- |
-LOS_LmsAddrProtect
- |
-Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.
- |
-
-Disabling protection of a specified memory chunk
- |
-LOS_LmsAddrDisableProtect
- |
-Unlocks a memory chunk to make it readable and writable.
- |
-
-
-
-
-### User Mode
+- Supports check of multiple memory pools.
+
+- Checks the memory allocated by **LOS_MemAlloc**, **LOS_MemAllocAlign**, and **LOS_MemRealloc**.
+
+- Checks the memory when bounds-checking functions are called (enabled by default).
+
+- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called.
+
+
+## Working Principles
+
+LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool.
+
+- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state.
+
+- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state.
+
+- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported.
+
+- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported.
+
+
+## Available APIs
+
+
+### Kernel Mode
+
+The LMS module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_lms.h).
+
+ **Table 1** APIs of the LMS module
+
+| Category| API| Description|
+| -------- | -------- | -------- |
+| Adding a memory pool to be checked| LOS_LmsCheckPoolAdd | Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, **LOS_MemInit** calls this API to add the initialized memory pool to the LMS check linked list by default.|
+| Deleting a memory pool from the LMS check linked list| LOS_LmsCheckPoolDel | Cancels the validity check on the specified memory pool.|
+| Protecting a specified memory chunk| LOS_LmsAddrProtect | Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.|
+| Disabling protection of a specified memory chunk| LOS_LmsAddrDisableProtect | Unlocks a memory chunk to make it readable and writable.|
+
+
+### User Mode
The user mode provides only the LMS check library. It does not provide external APIs.
-## Development Guidelines
-### Kernel-mode Development Process
+## Development Guidelines
-The typical process for enabling LMS is as follows:
-1. Configure the macros related to the LMS module.
-
- Configure the LMS macro **LOSCFG\_KERNEL\_LMS**, which is disabled by default. Run the **make update\_config** command in the **kernel/liteos\_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**.
-
-
- Macro
- |
- menuconfig Option
- |
- Description
- |
- Value
- |
-
-
- LOSCFG_KERNEL_LMS
- |
- Enable Lms Feature
- |
- Whether to enable LMS.
- |
- YES/NO
- |
-
- LOSCFG_LMS_MAX_RECORD_POOL_NUM
- |
- Lms check pool max num
- |
- Maximum number of memory pools that can be checked by LMS.
- |
- INT
- |
-
- LOSCFG_LMS_LOAD_CHECK
- |
- Enable lms read check
- |
- Whether to enable LMS read check.
- |
- YES/NO
- |
-
- LOSCFG_LMS_STORE_CHECK
- |
- Enable lms write check
- |
- Whether to enable LMS write check.
- |
- YES/NO
- |
-
- LOSCFG_LMS_CHECK_STRICT
- |
- Enable lms strict check, byte-by-byte
- |
- Whether to enable LMS byte-by-byte check.
- |
- YES/NO
- |
-
-
-
-
-2. Modify the compile script of the target module.
-
- Add "-fsanitize=kernel-address" to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler.
-
- The modifications vary depending on the compiler \(GCC or Clang\) used. The following is an example:
-
- ```
- if ("$ohos_build_compiler_specified" == "gcc") {
- cflags_c = [
- "-O0",
- "-fsanitize=kernel-address",
- ]
- } else {
- cflags_c = [
- "-O0",
- "-fsanitize=kernel-address",
- "-mllvm",
- "-asan-instrumentation-with-call-threshold=0",
- "-mllvm",
- "-asan-stack=0",
- "-mllvm",
- "-asan-globals=0",
- ]
- }
- ```
+### Kernel-Mode Development Process
-3. Recompile the code and check the serial port output. The memory problem detected will be displayed.
+The typical process for enabling LMS is as follows:
-## Kernel-mode Development Example
+1. Configure the macros related to the LMS module.
+
+ Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**.
+
+ | Macro| menuconfig Option| Description| Value:|
+ | -------- | -------- | -------- | -------- |
+ | LOSCFG_KERNEL_LMS | Enable Lms Feature | Whether to enable LMS.| YES/NO |
+ | LOSCFG_LMS_MAX_RECORD_POOL_NUM | Lms check pool max num | Maximum number of memory pools that can be checked by LMS.| INT |
+ | LOSCFG_LMS_LOAD_CHECK | Enable lms read check | Whether to enable LMS read check.| YES/NO |
+ | LOSCFG_LMS_STORE_CHECK | Enable lms write check | Whether to enable LMS write check.| YES/NO |
+ | LOSCFG_LMS_CHECK_STRICT | Enable lms strict check, byte-by-byte | Whether to enable LMS byte-by-byte check.| YES/NO |
+
+
+2. Modify the build script of the target module.
+
+ Add **-fsanitize=kernel-address** to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler.
+
+ The modifications vary depending on the compiler (GCC or Clang) used. The following is an example:
+
+ ```
+ if ("$ohos_build_compiler_specified" == "gcc") {
+ cflags_c = [
+ "-O0",
+ "-fsanitize=kernel-address",
+ ]
+ } else {
+ cflags_c = [
+ "-O0",
+ "-fsanitize=kernel-address",
+ "-mllvm",
+ "-asan-instrumentation-with-call-threshold=0",
+ "-mllvm",
+ "-asan-stack=0",
+ "-mllvm",
+ "-asan-globals=0",
+ ]
+ }
+ ```
+
+3. Recompile the code and check the serial port output. The memory problem detected will be displayed.
+
+
+#### Kernel-Mode Development Example
This example implements the following:
-1. Create a task for LMS.
-2. Construct a buffer overflow error and a UAF error.
-3. Add "-fsanitize=kernel-address", execute the compilation, and check the output.
+1. Create a task for LMS.
-## Kernel-mode Sample Code
+2. Construct a buffer overflow error and a UAF error.
-The code is as follows:
+3. Add "-fsanitize=kernel-address", execute the compilation, and check the output.
+
+
+#### Kernel-Mode Sample Code
+
+ The sample code is as follows:
```
#define PAGE_SIZE (0x1000U)
@@ -221,10 +154,10 @@ VOID LmsTestCaseTask(VOID)
UINT32 Example_Lms_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S lmsTestTask;
- /* Create a task for LMS. */
+ /* Create a task for LMS. */
memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S));
lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask;
- lmsTestTask.pcName = "TestLmsTsk"; /* Task name. */
+ lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */
lmsTestTask.uwStackSize = 0x800;
lmsTestTask.usTaskPrio = 5;
lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
@@ -238,20 +171,21 @@ UINT32 Example_Lms_test(VOID){
LOS_MODULE_INIT(Example_Lms_test, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
-### Kernel-mode Verification
-The output is as follows:
+#### Kernel-Mode Verification
+
+ The output is as follows:
```
######LmsTestOsmallocOverflow start ######
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected Start *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected Start *
[ERR][KProcess:LmsTestCaseTask]Heap buffer overflow error detected
[ERR][KProcess:LmsTestCaseTask]Illegal READ address at: [0x4157a3c8]
[ERR][KProcess:LmsTestCaseTask]Shadow memory address: [0x4157be3c : 4] Shadow memory value: [2]
OsBackTrace fp = 0x402c0f88
runTask->taskName = LmsTestCaseTask
runTask->taskID = 2
-*******backtrace begin*******
+***backtrace begin***
traceback fp fixed, trace using fp = 0x402c0fd0
traceback 0 -- lr = 0x400655a4 fp = 0x402c0ff8
traceback 1 -- lr = 0x40065754 fp = 0x402c1010
@@ -269,18 +203,18 @@ traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca
[0x4157a3e0]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 0]: 3 3
[0x4157a3e8]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 4]: 3 3
[0x4157a3f0]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 0]: 3 3
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected End *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected End *
str[20]=0xffffffba
######LmsTestOsmallocOverflow stop ######
###### LmsTestUseAfterFree start ######
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected Start *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected Start *
[ERR][KProcess:LmsTestCaseTask]Use after free error detected
[ERR][KProcess:LmsTestCaseTask]Illegal READ address at: [0x4157a3d4]
[ERR][KProcess:LmsTestCaseTask]Shadow memory address: [0x4157be3d : 2] Shadow memory value: [3]
OsBackTrace fp = 0x402c0f90
runTask->taskName = LmsTestCaseTask
runTask->taskID = 2
-*******backtrace begin*******
+***backtrace begin***
traceback fp fixed, trace using fp = 0x402c0fd8
traceback 0 -- lr = 0x40065680 fp = 0x402c0ff8
traceback 1 -- lr = 0x40065758 fp = 0x402c1010
@@ -298,35 +232,36 @@ traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca
[0x4157a3e8]: ba dc cd ab c8 a3 57 41 | [0x4157be3e | 4]: 2 2
[0x4157a3f0]: 0c 1a 00 00 00 00 00 00 | [0x4157be3f | 0]: 2 3
[0x4157a3f8]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 4]: 3 3
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected End *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected End *
str[ 0]=0x 0
######LmsTestUseAfterFree stop ######
```
The key output information is as follows:
-- Error type:
- - Heap buffer overflow
- - UAF
+- Error type:
+ - Heap buffer overflow
+ - UAF
+
+- Incorrect operations:
+ - Illegal read
+ - Illegal write
+ - Illegal double free
-- Incorrect operations:
- - Illegal read
- - Illegal write
- - Illegal double free
+- Context:
+ - Task information (**taskName** and **taskId**)
+ - Backtrace
-- Context:
- - Task information \(**taskName** and **taskId**\)
- - Backtrace
+- Memory information of the error addresses:
+ - Memory value and the value of the corresponding shadow memory
+ - Memory address: memory value|[shadow memory address|shadow memory byte offset]: shadow memory value
+ - Shadow memory value. **0** (Accessible), **3** (Freed), **2** (RedZone), and **1** (filled value)
-- Memory information of the error addresses:
- - Memory value and the value of the corresponding shadow memory
- - Memory address: memory value|\[shadow memory address|shadow memory byte offset\]: shadow memory value
- - Shadow memory value. **0** \(Accessible\), **3** \(Freed\), **2** \(RedZone\), and **1** \(filled value\)
+### User-Mode Development Process
-### User-mode Development Process
+Add the following to the build script of the app to be checked. For details about the complete code, see **/kernel/liteos_a/apps/lms/BUILD.gn**.
-Add the following to the build script of the app to be checked. For details about the complete code, see **/kernel/liteos\_a/apps/lms/BUILD.gn**.
```
if ("$ohos_build_compiler_specified" == "gcc") {
@@ -369,16 +304,19 @@ if ("$ohos_build_compiler_specified" == "gcc") {
deps = [ "//kernel/liteos_a/kernel/extended/lms/usr:usrlmslib" ]
```
-### User-mode Development Example
+
+#### User-Mode Development Example
This example implements the following:
-1. Construct a buffer overflow error and a UAF error.
-2. Modify the build script and perform the build again.
+1. Construct a buffer overflow error and a UAF error.
+
+2. Modify the build script and perform the build again.
+
-### User-Mode Sample Code
+#### User-Mode Sample Code
-The code is as follows:
+ The code is as follows:
```
static void BufWriteTest(void *buf, int start, int end)
@@ -421,16 +359,17 @@ int main(int argc, char * const * argv)
}
```
-### User-mode Verification
-The output is as follows:
+#### User-Mode Verification
+
+ The output is as follows:
```
-***** Lite Memory Sanitizer Error Detected *****
+* Lite Memory Sanitizer Error Detected *
Heap buffer overflow error detected!
Illegal READ address at: [0x1f8b3edf]
Shadow memory address: [0x3d34d3ed : 6] Shadow memory value: [2]
-Accessable heap addr 0
+Accessible heap addr 0
Heap red zone 2
Heap freed buffer 3
Dump info around address [0x1f8b3edf]:
@@ -443,7 +382,7 @@ Dump info around address [0x1f8b3edf]:
[0x1f8b3ee8]: 09 00 00 00 00 00 00 00 | [0x3d34d3ee | 4]: 0 0
[0x1f8b3ef0]: 00 00 00 00 08 03 09 00 | [0x3d34d3ef | 0]: 2 2
[0x1f8b3ef8]: 00 00 00 00 00 00 00 00 | [0x3d34d3ef | 4]: 2 2
-***** Lite Memory Sanitizer Error Detected End *****
+* Lite Memory Sanitizer Error Detected End *
Backtrace() returned 5 addresses
#01: [0x4d6c] -> ./sample_usr_lms
#02: <(null)+0x2004074>[0x4074] -> ./sample_usr_lms
@@ -451,11 +390,11 @@ Backtrace() returned 5 addresses
#04: [0x363c] -> ./sample_usr_lms
#05: <(null)+0x1f856f30>[0x56f30] -> /lib/libc.so
-------- LMS_malloc_test End --------
-***** Lite Memory Sanitizer Error Detected *****
+* Lite Memory Sanitizer Error Detected *
Use after free error detected!
Illegal Double free address at: [0x1f8b3ee0]
Shadow memory address: [0x3d34d3ee : 0] Shadow memory value: [3]
-Accessable heap addr 0
+Accessible heap addr 0
Heap red zone 2
Heap freed buffer 3
Dump info around address [0x1f8b3ee0]:
@@ -468,7 +407,7 @@ Dump info around address [0x1f8b3ee0]:
[0x1f8b3ef0]: 20 40 8b 1f 20 20 8b 1f | [0x3d34d3ef | 0]: 3 3
[0x1f8b3ef8]: 00 00 00 00 00 00 00 00 | [0x3d34d3ef | 4]: 3 3
[0x1f8b3f00]: 00 00 00 00 00 00 00 00 | [0x3d34d3f0 | 0]: 3 3
-***** Lite Memory Sanitizer Error Detected End *****
+* Lite Memory Sanitizer Error Detected End *
Backtrace() returned 5 addresses
#01: [0x4d6c] -> ./sample_usr_lms
#02: [0x5548] -> ./sample_usr_lms
@@ -479,4 +418,3 @@ Backtrace() returned 5 addresses
```
The Backtrace output contains the names of the files where the addresses are located. You can locate the code line corresponding to the address in the related file.
-
diff --git a/en/device-dev/kernel/kernel-small-start-kernel.md b/en/device-dev/kernel/kernel-small-start-kernel.md
index c92af04ba02216c05708e280bd427b7b8cb128d8..01c4373ac8b51dc17a9ea91985c98688f4965311 100644
--- a/en/device-dev/kernel/kernel-small-start-kernel.md
+++ b/en/device-dev/kernel/kernel-small-start-kernel.md
@@ -1,99 +1,46 @@
# Startup in Kernel Mode
-## Kernel Startup Process
-
-The kernel startup process consists of the assembly startup and C language startup, as shown in the following figure. The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language. The C language startup involves the following operations: starting the OsMain function and starting scheduling. As shown in the following figure, the OsMain function is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. [Table 1](#table38544719428) describes each phase.
-
-**Figure 1** Kernel startup process
-
-
-**Table 1** Startup framework levels
-
-
-Level
- |
-Description
- |
-
-
-LOS_INIT_LEVEL_EARLIEST
- |
-Earliest initialization.
-The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.
-Example: trace module
- |
-
-LOS_INIT_LEVEL_ARCH_EARLY
- |
-Early initialization of the architecture.
-The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at LOS_INIT_LEVEL_ARCH.
- |
-
-LOS_INIT_LEVEL_PLATFORM_EARLY
- |
-Early initialization of the platform.
-The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend. It is recommended that functions required for startup be placed at LOS_INIT_LEVEL_PLATFORM.
- |
-
-LOS_INIT_LEVEL_KMOD_PREVM
- |
-Kernel module initialization before memory initialization.
-Initialize the modules that need to be enabled before memory initialization.
- |
-
-LOS_INIT_LEVEL_VM_COMPLETE
- |
-Initialization after the basic memory is ready.
-After memory initialization, initialize the modules that need to be enabled and do not depend on inter-process communication (IPC) and system processes.
-Example: shared memory function
- |
-
-LOS_INIT_LEVEL_ARCH
- |
-Late initialization of the architecture.
-The initialization is related to the architecture extension functions. Subsequent modules initialize the modules on which they depend.
- |
-
-LOS_INIT_LEVEL_PLATFORM
- |
-Late initialization of the platform.
-The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend.
-Example: initialization of the driver kernel abstraction layer (MMC and MTD)
- |
-
-LOS_INIT_LEVEL_KMOD_BASIC
- |
-Initialization of the kernel basic modules.
-Initialize the basic modules that can be detached from the kernel.
-Example: VFS initialization
- |
-
-LOS_INIT_LEVEL_KMOD_EXTENDED
- |
-Initialization of the kernel extended modules.
-Initialize the extended modules that can be detached from the kernel.
-Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC
- |
-
-LOS_INIT_LEVEL_KMOD_TASK
- |
-Kernel task creation
-Create kernel tasks (kernel tasks and software timer tasks).
-Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task.
- |
-
-
-
-
-## Programming Example
-
-### Example Description
+## Kernel Startup Process
+
+The kernel startup process consists of the assembly startup and C language startup, as shown in the following figure.
+
+The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language.
+
+The C language startup involves the following operations: starting the **OsMain** function and starting scheduling. As shown in the following figure, the **OsMain** function is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. The table below describes each phase.
+
+
+ **Figure 1** Kernel startup process
+ 
+
+
+ **Table 1** Start framework
+
+| Level | Startup Description |
+| -------- | -------- |
+| LOS_INIT_LEVEL_EARLIEST | Earliest initialization.
The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.
Example: trace module|
+| LOS_INIT_LEVEL_ARCH_EARLY | Early initialization of the architecture.
The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at **LOS_INIT_LEVEL_ARCH**.|
+| LOS_INIT_LEVEL_PLATFORM_EARLY | Early initialization of the platform.
The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend. It is recommended that functions required for startup be placed at **LOS_INIT_LEVEL_PLATFORM**.
Example: UART module|
+| LOS_INIT_LEVEL_KMOD_PREVM | Kernel module initialization before memory initialization.
Initialize the modules that need to be enabled before memory initialization.|
+| LOS_INIT_LEVEL_VM_COMPLETE | Initialization after the basic memory is ready.
After memory initialization, initialize the modules that need to be enabled and do not depend on inter-process communication (IPC) and system processes.
Example: shared memory function|
+| LOS_INIT_LEVEL_ARCH | Late initialization of the architecture.
The initialization is related to the architecture extension functions. Subsequent modules initialize the modules on which they depend.|
+| LOS_INIT_LEVEL_PLATFORM | Late initialization of the platform.
The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend.
Example: initialization of the driver kernel abstraction layer (MMC and MTD)|
+| LOS_INIT_LEVEL_KMOD_BASIC | Initialization of the kernel basic modules.
Initialize the basic modules that can be detached from the kernel.
Example: VFS initialization|
+| LOS_INIT_LEVEL_KMOD_EXTENDED | Initialization of the kernel extended modules.
Initialize the extended modules that can be detached from the kernel.
Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC|
+| LOS_INIT_LEVEL_KMOD_TASK | Kernel task creation.
Create kernel tasks (kernel tasks and software timer tasks).
Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task|
+
+
+## Programming Example
+
+**Example Description**
Add a kernel module and register the initialization function of the module to the kernel startup process through the kernel startup framework, so as to complete the module initialization during the kernel initialization process.
+
**Sample Code**
+
+
```
/* Header file of the kernel startup framework */
#include "los_init.h"
@@ -110,8 +57,11 @@ unsigned int OsSampleModInit(void)
LOS_MODULE_INIT(OsSampleModInit, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
+
**Verification**
+
+
```
main core booting up...
OsSampleModInit SUCCESS!
@@ -120,9 +70,12 @@ cpu 1 entering scheduler
cpu 0 entering scheduler
```
+
According to the information displayed during the system startup, the kernel has called the initialization function of the registered module during the startup to initialize the module.
-> **NOTE:**
->Modules at the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required.
->You can view the symbol table in the **.rodata.init.kernel.\*** segment of the **OHOS\_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect.
+>  **NOTE**
+>
+> Modules at the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required.
+>
+> You can view the symbol table in the **.rodata.init.kernel.*** segment of the **OHOS_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect.
diff --git a/en/device-dev/kernel/kernel-standard-build.md b/en/device-dev/kernel/kernel-standard-build.md
index 747c9133458aec67156d3a1200d705b1a45df4a5..3c950570cf2ae2638fd00a68756c3cefaaf3ddce 100644
--- a/en/device-dev/kernel/kernel-standard-build.md
+++ b/en/device-dev/kernel/kernel-standard-build.md
@@ -1,14 +1,16 @@
# Compiling and Building the Linux Kernel
-## Example 1
+
+ **Example**
The following uses the Hi3516D V300 board and Ubuntu x86 server as an example.
-Perform a full build for the project to generate the **uImage** kernel image.
+
+Perform a full build for the project to generate the **uImage** kernel image.
+
```
-./build.sh --product-name hispark_taurus_standard # Build the hispark_taurus_standard image.
- --build-target build_kernel # Build the uImage kernel image of the hispark_taurus_standard.
- --gn-args linux_kernel_version=\"linux-5.10\" # Build the specified kernel version.
+./build.sh --product-name hispark_taurus_standard # Build the hispark_taurus_standard image.
+ --build-target build_kernel # Build the uImage kernel image of hispark_taurus_standard.
+ --gn-args linux_kernel_version=\"linux-5.10\" # Specify the kernel version.
```
-
diff --git a/en/device-dev/kernel/kernel-standard-sched-rtg.md b/en/device-dev/kernel/kernel-standard-sched-rtg.md
index 534cdcdab06c04c6f3abce5e29766411e4c819cc..61a36ab5bb7aad13789b0ce053e3dbcd73be6b25 100644
--- a/en/device-dev/kernel/kernel-standard-sched-rtg.md
+++ b/en/device-dev/kernel/kernel-standard-sched-rtg.md
@@ -51,11 +51,11 @@ STATE COMM PID PRIO CPU // Thread information, including th
## Available APIs
-The RTG provides the device node and ioctl APIs for querying and configuring group information. The device node is in `/dev/sched_rtg_ctrl`.
-
-| Device Node | request | Description |
-| ------------------- | ------------------- | ------------------- |
-| /dev/sched_rtg_ctrl | CMD_ID_SET_RTG | Creates an RTG, and adds, updates, or deletes threads in the group. |
-| | CMD_ID_SET_CONFIG | Configures global group attributes, for example, the maximum number of real-time RTGs.|
-| | CMD_ID_SET_RTG_ATTR | Configures specified group attributes, for example, the thread priority. |
-| | CMD_ID_SET_MIN_UTIL | Sets the minimum utilization of an RTG. |
+The RTG provides the device node and ioctl APIs for querying and configuring group information. The device node is in **/dev/sched_rtg_ctrl**.
+
+| Request | Description |
+| ------------------- | ------------------- |
+| CMD_ID_SET_RTG | Creates an RTG, and adds, updates, or deletes threads in the group. |
+| CMD_ID_SET_CONFIG | Sets global group attributes, for example, the maximum number of real-time RTGs. |
+| CMD_ID_SET_RTG_ATTR | Sets specified group attributes, for example, the thread priority. |
+| CMD_ID_SET_MIN_UTIL | Sets the minimum utilization of an RTG. |
diff --git a/en/device-dev/porting/porting-chip-prepare-knows.md b/en/device-dev/porting/porting-chip-prepare-knows.md
index 6422f0f6bddd007815c9122704f67713d5f78c7a..64a136cd4884c4d76a9ddf86c9160e410177cdc8 100644
--- a/en/device-dev/porting/porting-chip-prepare-knows.md
+++ b/en/device-dev/porting/porting-chip-prepare-knows.md
@@ -18,7 +18,7 @@ The implementation of the OpenHarmony project directories and functions relies o
| /build/lite | OpenHarmony basic compilation and building framework.|
| /kernel/liteos_m | Basic kernel. The implementation related to the chip architecture is in the **arch** directory.|
| /device | Board-level implementation, which complies with the OpenHarmony specifications. For details about the directory structure and porting process, see [Overview](../porting/porting-chip-board-overview.md).|
-| /vendor | Product-level implementation, which is contributed by Huawei or product vendors.|
+| /vendor | Product-level implementation, which is contributed by product vendors. |
The **device** directory is in the internal structure of **device/{Chip solution vendor}/{Development board}**. The following uses HiSilicon **hispark_taurus** as an example:
@@ -37,7 +37,7 @@ device
```
-The **vendor** directory is in the internal structure of **vendor/{Product solution vendor}/{Product name}**. The following uses the Huawei Wi-Fi IoT product as an example:
+The **vendor** directory is in the internal structure of **vendor/{Product solution vendor}/{Product name}**. The following uses the Wi-Fi IoT product as an example:
diff --git a/en/device-dev/subsystems/subsys-build-mini-lite.md b/en/device-dev/subsystems/subsys-build-mini-lite.md
index 5edca2ba8449a7001b207a3bc802bf9a29813471..fa47c3a94b36fdc69c207ae602c218574c9074c7 100644
--- a/en/device-dev/subsystems/subsys-build-mini-lite.md
+++ b/en/device-dev/subsystems/subsys-build-mini-lite.md
@@ -2,7 +2,7 @@
## Overview
- The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
+The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
- Assemble components into a product and build the product.
@@ -75,7 +75,7 @@ You can build a component, a chipset solution, and a product solution. To ensure
### Component
- The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows:
+The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows:
>  **CAUTION**
> The .json file of the subsystem in the **build/lite/components** directory contains component attributes, including the name, source code directory, function description, mandatory or not, build targets, RAM, ROM, build outputs, adapted kernels, configurable features, and dependencies of the component. When adding a component, add the component information in the .json file of the corresponding subsystem. The component configured for a product must have been defined in a subsystem. Otherwise, the verification will fail.
@@ -94,42 +94,42 @@ component
```
{
- "name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the @Organization/Component name format.
- "description": "Sensor services", # Description of the component functions.
- "version": "3.1", # Version, which must be the same as the version of OpenHarmony.
- "license": "MIT", # Component license.
- "publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
+ "name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the "@Organization/Component name" format.
+ "description": "Sensor services", # Description of the component functions.
+ "version": "3.1", # Version, which must be the same as the version of OpenHarmony.
+ "license": "MIT", # Component license.
+ "publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
- }, # Code restoration path (source code path) set when "publishAs is code-segment.
- "dirs": {"base/sensors/sensor_lite"} # Directory structure of the HPM package. This field is mandatory and can be left empty.
- "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
+ }, # Code restoration path (source code path) set when "publishAs" is code-segment.
+ "dirs": {"base/sensors/sensor_lite"}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
+ "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
- "component": { # Component attributes.
- "name": "sensor_lite", # Component name.
- "subsystem": "", # Subsystem to which the component belongs.
- "syscap": [], # System capabilities provided by the component for applications.
- "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
- "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
- "rom": "92KB", # Size of the component's ROM.
- "ram": "~200KB", # Size of the component's RAM.
+ "component": { # Component attributes.
+ "name": "sensor_lite", # Component name.
+ "subsystem": "", # Subsystem to which the component belongs.
+ "syscap": [], # System capabilities provided by the component for applications.
+ "features": [], # List of external configurable features of a component. Generally, this parameter corresponds to sub_component in build and can be configured by the product.
+ "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, and standard.
+ "rom": "92KB", # Component ROM size.
+ "ram": "~200KB",, # Component RAM size.
"deps": {
- "components": [ # Other components on which this component depends.
+ "components": [ # Other components on which this component depends.
"samgr_lite"
],
- "third_party": [ # Third-party open-source software on which this component depends.
+ "third_party": [ # Third-party open-source software on which this component depends.
"bounds_checking_function"
]
}
- "build": { # Build-related configurations.
+ "build": { # Build-related configuration.
"sub_component": [
""//base/sensors/sensor_lite/services:sensor_service"", # Component build entry
- ], # Component build entry. Configure the module here.
- "inner_kits": [], # APIs between components.
- "test": [] # Entry for building the component's test cases.
+ ], # Component build entry. Configure modules here.
+ "inner_kits": [], # APIs between components.
+ "test": [] # Entry for building the component's test cases.
}
}
}
@@ -195,28 +195,28 @@ component
### Chipset Solution
-The chipset solution is a special component. It is built based on a development board, including the drivers, device API adaptation, and SDK.
+- The chipset solution is a special component. It is built based on a development board, including the drivers, device API adaptation, and SDK.
-The source code path is named in the **device/{Development board}/{Chipset solution vendor}** format.
+- The source code path is named in the **device/{Development board}/{Chipset solution vendor}** format.
-The chipset solution component is built by default based on the development board selected.
-
-The chipset solution directory structure is as follows:
+- The chipset solution component is built by default based on the development board selected.
+
+- The chipset solution directory structure is as follows:
-```
-device
-└── board # Chipset solution vendor
- └── company # Development board name
- ├── BUILD.gn # Build script
- ├── hals # OS device API adaptation
- ├── linux # (Optional) Linux kernel version
- │ └── config.gni # Linux build configuration
- └── liteos_a # (Optional) LiteOS kernel version
- └── config.gni # LiteOS_A build configuration
-```
+ ```
+ device
+ └── board # Chipset solution vendor
+ └── company # Development board name
+ ├── BUILD.gn # Build script
+ ├── hals # OS device API adaptation
+ ├── linux # (Optional) Linux kernel version
+ │ └── config.gni # Linux build configuration
+ └── liteos_a # (Optional) LiteOS kernel version
+ └── config.gni # LiteOS_A build configuration
+ ```
->  **NOTE**
-> The **config.gni** file contains build-related configuration of the development board. The parameters in the file are used to build all OS components, and are globally visible to the system during the build process.
+ >  **NOTE**
+ > The **config.gni** file contains build-related configuration of the development board. The parameters in the file are used to build all OS components, and are globally visible to the system during the build process.
- The **config.gni** file contains the following key parameters:
@@ -267,18 +267,21 @@ The key directories and files are described as follows:
This file is the configuration file for the **init** process to start services. Currently, the following commands are supported:
- **start**: starts a service.
-- **mkdir**: creates a folder.
-
+
+ - **mkdir**: creates a folder.
+
- **chmod**: changes the permission on a specified directory or file.
-- **chown**: changes the owner group of a specified directory or file.
- - **mount**: mounts a device.
- The fields in the file are described as follows:
+ - **chown**: changes the owner group of a specified directory or file.
+
+ - **mount**: mounts a device.
+
+ The fields in the file are described as follows:
```
{
"jobs" : [{ # Job array. A job corresponds to a command set. Jobs are executed in the following sequence: pre-init > init > post-init.
- "name" : "pre-init",
+ "name" : "pre-init",
"cmds" : [
"mkdir /storage/data", # Create a directory.
"chmod 0755 /storage/data", #Modify the permissions. The format of the permission value is 0xxx, for example, 0755.
@@ -314,7 +317,7 @@ The key directories and files are described as follows:
]
}
```
-
+
3. **vendor/company/product/init_configs/hals**
This file contains the OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component.
@@ -361,9 +364,9 @@ The key directories and files are described as follows:
source_dir: (Optional) specifies target file directory in the out directory. If this field is not specified, an empty directory will be created in the file system based on target_dir.
target_dir: (Mandatory) specifies the file directory in the file system.
ignore_files: (Optional) declares ignored files during the copy operation.
- dir_mode: (Optional) specifies the file directory permissions. The default value is 755.
- file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555.
- fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list.
+ dir_mode: (Optional) specifies the file directory permissions. The default value is 755.
+ file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555.
+ fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list.
file_dir: (Mandatory) specifies the detailed file path in the file system.
file_mode: (Mandatory) declares file permissions.
fs_symlink: (Optional) specifies the soft link of the file system.
@@ -373,11 +376,12 @@ The key directories and files are described as follows:
The **fs_symlink** and **fs_make_cmd** fields support the following variables:
- - ${root_path}: code root directory, which corresponds to **${ohos_root_path}** of GN.
- - ${out_path}: **out** directory of the product, which corresponds to **${root_out_dir}** of GN.
- - ${fs_dir}: file system directory, which consists of variables ${root_path} and ${fs_dir_name}.
->  **NOTE**
-> **fs.yml** is optional and not required for devices without a file system.
+ - **${root_path}**: Code root directory, which corresponds to **${ohos_root_path}** of GN.
+ - **${out_path}**: The **out** directory of the product, which corresponds to **${root_out_dir}** of GN.
+ - **${fs_dir}**: File system directory, which consists of variables **${root_path}** and **${fs_dir_name}**.
+
+ >  **NOTE**
+ > **fs.yml** is optional and not required for devices without a file system.
6. **vendor/company/product/BUILD.gn**
@@ -405,7 +409,7 @@ The development environment has GN, Ninja, Python 3.9.2 or later, and hb availab
**hb** is an OpenHarmony command line tool for executing build commands. Common hb commands are described as follows:
- **hb set**
+**hb set**
```
hb set -h
@@ -438,7 +442,7 @@ hb env
[OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19
```
- **hb build**
+**hb build**
```
hb build -h
@@ -660,7 +664,6 @@ The following uses the RTL8720 development board provided by Realtek as an examp
```
4. Build the chipset solution.
-
Run the **hb build** command in the development board directory to start the build.
### Adding a Product Solution
@@ -668,7 +671,6 @@ The following uses the RTL8720 development board provided by Realtek as an examp
You can customize a product solution by flexibly assembling a chipset solution and components. The procedure is as follows:
1. Create a product directory based on the [configuration rules](#product-solution).
-
The following uses the Wi-Fi IoT module on the RTL8720 development board as an example. Run the following command in the root directory to create a product directory:
```
@@ -676,9 +678,8 @@ You can customize a product solution by flexibly assembling a chipset solution a
```
2. Assemble the product.
-
- Create a **config.json** file, for example for wifiiot, in the product directory. The **vendor/my_company/wifiiot/config.json** file is as follows:
-
+ Create a **config.json** file, for example for wifiiot, in the product directory. The **vendor/my_company/wifiiot/config.json** file is as follows:
+
```
{
"product_name": "wifiiot", # Product name
@@ -704,25 +705,22 @@ You can customize a product solution by flexibly assembling a chipset solution a
}
```
->  **CAUTION**
-> Before the build, the Compilation and Building subsystem checks the validity of fields in **config.json**. The **device_company**, **board**, **kernel_type**, and **kernel_version** fields must match the fields of the chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file.
+ >  **CAUTION**
+ > Before the build, the Compilation and Building subsystem checks the validity of fields in **config.json**. The **device_company**, **board**, **kernel_type**, and **kernel_version** fields must match the fields of the chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file.
3. Implement adaptation to OS APIs.
-
Create the **hals** directory in the product directory and save the source code as well as the build script for OS adaptation in this directory.
4. Configure system services.
-
Create the **init_configs** directory in the product directory and then the **init.cfg** file in the **init_configs** directory, and configure the system services to be started.
5. (Optional) Configure the init process for the Linux kernel.
-
Create the **etc** directory in the **init_configs** directory, and then the **init.d** folder and the **fstab** file in the **etc** directory. Then, create the **rcS** and **S***xxx* files in the **init.d** file and edit them based on product requirements.
6. (Optional) Configure the file system image for the development board that supports the file system.
-
+
Create a **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows:
-
+
```
-
fs_dir_name: rootfs # Image name
@@ -823,7 +821,7 @@ You can customize a product solution by flexibly assembling a chipset solution a
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4
```
-
+
7. (Optional) Configure patches if the product and components need to be patched.
Create a **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows:
@@ -841,14 +839,14 @@ You can customize a product solution by flexibly assembling a chipset solution a
...
```
+
Add **--patch** when running the **hb build** command. Then, the patch files can be added to the specified directory before the build.
- ```
- hb build -f --patch
- ```
+ ```
+ hb build -f --patch
+ ```
8. Write the build script.
-
Create a **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT module in step 1 as an example:
```
@@ -864,9 +862,9 @@ You can customize a product solution by flexibly assembling a chipset solution a
```
9. Build the product.
-
Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command.
+
## Troubleshooting
### "usr/sbin/ninja: invalid option -- w" Displayed During the Build Process
@@ -892,10 +890,10 @@ You can customize a product solution by flexibly assembling a chipset solution a
- **Possible Causes**
The ncurses library is not installed.
-
+
- **Solution**
- ```
+ ```
sudo apt-get install lib32ncurses5-dev
```
@@ -929,9 +927,9 @@ You can customize a product solution by flexibly assembling a chipset solution a
1. Run the following command to locate **gcc_riscv32**:
- ```
+ ```
which riscv32-unknown-elf-gcc
- ```
+ ```
2. Run the **chmod** command to change the directory permission to **755**.
diff --git a/en/device-dev/subsystems/subsys-xts-guide.md b/en/device-dev/subsystems/subsys-xts-guide.md
index d9ee3223e3aa282f5e7e847a07f7a20b00c628c5..90992e3e0449cd9a883ba5ddba171f5ae8fefb9d 100644
--- a/en/device-dev/subsystems/subsys-xts-guide.md
+++ b/en/device-dev/subsystems/subsys-xts-guide.md
@@ -2,7 +2,7 @@
## Introduction
-The X test suite \(XTS\) subsystem contains a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite \(ACTS\) and the device compatibility test suite \(DCTS\) that will be supported in the future.
+The X test suite (XTS) subsystem contains a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite (ACTS) and the device compatibility test suite (DCTS) that will be supported in the future.
This subsystem contains the ACTS and **tools** software package.
@@ -19,7 +19,7 @@ OpenHarmony supports the following systems:
- Small system
- A small system runs on a device that comes with memory greater than or equal to 1 MiB and application processors such as ARM Cortex-A. It provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders \(EDRs\) for smart travel.
+ A small system runs on a device that comes with memory greater than or equal to 1 MiB and application processors such as ARM Cortex-A. It provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders (EDRs) for smart travel.
- Standard system
@@ -34,7 +34,7 @@ OpenHarmony supports the following systems:
│ └── subsystem # Source code of subsystem test cases for the standard system
│ └── subsystem_lite # Source code of subsystems test cases for mini and small systems
│ └── BUILD.gn # Build configuration of test cases for the standard system
-│ └── build_lite
+│ └── build_lite # Build configuration of test cases for the mini and small systems.
│ └── BUILD.gn # Build configuration of test cases for mini and small systems
└── tools # Test tool code
```
@@ -72,9 +72,9 @@ Test cases for the mini system must be developed in C, and those for the small s
| Performance | Tests the processing capability of the tested object under specific preset conditions and load models. The processing capability is measured by the service volume that can be processed in a unit time, for example, call per second, frame per second, or event processing volume per second. |
| Power | Tests the power consumption of the tested object in a certain period of time under specific preset conditions and load models. |
| Reliability | Tests the service performance of the tested object under common and uncommon input conditions, or specified service volume pressure and long-term continuous running pressure. The test covers stability, pressure handling, fault injection, and Monkey test times. |
-| Security | - Tests the capability of defending against security threats, including but not limited to unauthorized access, use, disclosure, damage, modification, and destruction, to ensure information confidentiality, integrity, and availability.
- Tests the privacy protection capability to ensure that the collection, use, retention, disclosure, and disposal of users' private data comply with laws and regulations.
- Tests the compliance with various security specifications, such as security design, security requirements, and security certification of the Ministry of Industry and Information Technology (MIIT).
|
+| Security | Tests the capability of defending against security threats, including but not limited to unauthorized access, use, disclosure, damage, modification, and destruction, to ensure information confidentiality, integrity, and availability.
Tests the privacy protection capability to ensure that the collection, use, retention, disclosure, and disposal of users' private data comply with laws and regulations.
Tests the compliance with various security specifications, such as security design, security requirements, and security certification of the Ministry of Industry and Information Technology (MIIT). |
| Global | Tests the internationalized data and localization capabilities of the tested object, including multi-language display, various input/output habits, time formats, and regional features, such as currency, time, and culture taboos. |
-| Compatibility | - Tests backward compatibility of an application with its own data, the forward and backward compatibility with the system, and the compatibility with different user data, such as audio file content of the player and smart SMS messages.
- Tests system backward compatibility with its own data and the compatibility of common applications in the ecosystem.
- Tests software compatibility with related hardware.
|
+| Compatibility | Tests backward compatibility of an application with its own data, the forward and backward compatibility with the system, and the compatibility with different user data, such as audio file content of the player and smart SMS messages.
Tests system backward compatibility with its own data and the compatibility of common applications in the ecosystem.
Tests software compatibility with related hardware. |
| User | Tests user experience of the object in real user scenarios. All conclusions and comments should come from the users, which are all subjective evaluation in this case. |
| Standard | Tests the compliance with industry and company-specific standards, protocols, and specifications. The standards here do not include any security standards that should be classified into the security test. |
| Safety | Tests the safety property of the tested object to avoid possible hazards to personal safety, health, and the object itself. |
@@ -92,107 +92,109 @@ The test framework and programming language vary with the system type.
| Small | HCPPTest | C++ |
| Standard | HJSUnit and HCPPTest | JavaScript and C++ |
-### Developing Test Cases in C (for the Mini System\)
+### Developing Test Cases in C (for the Mini System)
**Developing Test Cases for the Mini System**
HCTest and the C language are used to develop test cases. HCTest is enhanced and adapted based on the open-source test framework Unity.
-1. Define the test case directory. The test cases are stored to **test/xts/acts**.
+1. Define the test case directory. The test cases are stored to **test/xts/acts**.
+
+ ```
+ ├── acts
+ │ └──subsystem_lite
+ │ │ └── module_hal
+ │ │ │ └── BUILD.gn
+ │ │ │ └── src
+ │ └──build_lite
+ │ │ └── BUILD.gn
+ ```
- ```
- ├── acts
- │ └──subsystem_lite
- │ │ └── module_hal
- │ │ │ └── BUILD.gn
- │ │ │ └── src
- │ └──build_lite
- │ │ └── BUILD.gn
- ```
2. Write the test case in the **src** directory.
- a) Include the test framework header file.
+ (1) Include the test framework header file.
- ```
- #include "hctest.h"
- ```
+ ```
+ #include "hctest.h"
+ ```
- b) Use the **LITE\_TEST\_SUIT** macro to define names of the subsystem, module, and test suite.
+ (2) Use the **LITE_TEST_SUIT** macro to define names of the subsystem, module, and test suite.
- ```
- /**
- * @brief Registers a test suite named IntTestSuite.
- * @param test Subsystem name
- * @param example Module name
- * @param IntTestSuite Test suite name
- */
- LITE_TEST_SUIT(test, example, IntTestSuite);
- ```
+ ```
+ /**
+ * @brief register a test suite named "IntTestSuite"
+ * @param test subsystem name
+ * @param example module name
+ * @param IntTestSuite test suite name
+ */
+ LITE_TEST_SUIT(test, example, IntTestSuite);
+ ```
- c) Define Setup and TearDown.
+ (3) Define Setup and TearDown.
- Format: Test suite name+Setup, Test suite name+TearDown.
+ Format: Test suite name+Setup, Test suite name+TearDown.
+ The Setup and TearDown functions must exist, but function bodies can be empty.
+
+ (4) Use the **LITE_TEST_CASE** macro to write the test case.
- The Setup and TearDown functions must exist, but function bodies can be empty.
+ Three parameters are involved: test suite name, test case name, and test case properties (including type, granularity, and level).
+
+ ```
+ LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1)
+ {
+ // Do something.
+ };
+ ```
+
+ (5) Use the **RUN_TEST_SUITE** macro to register the test suite.
- d) Use the **LITE\_TEST\_CASE** macro to write the test case.
+ ```
+ RUN_TEST_SUITE(IntTestSuite);
+ ```
- Three parameters are involved: test suite name, test case name, and test case properties \(including type, granularity, and level\).
+3. Create the configuration file (**BUILD.gn**) of the test module.
- ```
- LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1)
- {
- // Do something
- };
- ```
+ Create a **BUILD.gn** (example) file in each test module directory, and specify the name of the built static library and its dependent header files and libraries.
- e) Use the **RUN\_TEST\_SUITE** macro to register the test suite.
+ The format is as follows:
```
- RUN_TEST_SUITE(IntTestSuite);
+ import("//test/xts/tools/lite/build/suite_lite.gni")
+ hctest_suite("ActsDemoTest") {
+ suite_name = "acts"
+ sources = [
+ "src/test_demo.c",
+ ]
+ include_dirs = [ ]
+ cflags = [ "-Wno-error" ]
+ }
```
-3. Create the configuration file \(**BUILD.gn**\) of the test module.
-
- Create a **BUILD.gn** \(example\) file in each test module directory, and specify the name of the built static library and its dependent header files and libraries. The format is as follows:
-
- ```
- import("//test/xts/tools/lite/build/suite_lite.gni")
- hctest_suite("ActsDemoTest") {
- suite_name = "acts"
- sources = [
- "src/test_demo.c",
- ]
- include_dirs = [ ]
- cflags = [ "-Wno-error" ]
- }
- ```
+4. Add build options to the **BUILD.gn** file in the **acts** directory.
-4. Add build options to the **BUILD.gn** file in the **acts** directory.
+ You need to add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
- You need to add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
-
- ```
- lite_component("acts") {
- ...
- if(board_name == "liteos_m") {
- features += [
- ...
- "//xts/acts/subsystem_lite/module_hal:ActsDemoTest"
- ]
- }
- }
- ```
+ ```
+ lite_component("acts") {
+ ...
+ if(board_name == "liteos_m") {
+ features += [
+ ...
+ "//xts/acts/subsystem_lite/module_hal:ActsDemoTest"
+ ]
+ }
+ }
+ ```
-5. Run build commands.
+5. Run build commands.
- Test suites are built along with the OS version. The ACTS is built together with the debug version.
+ Test suites are built along with the OS version. The ACTS is built together with the debug version.
- > **NOTE**
The ACTS build middleware is a static library, which will be linked to the image.
+ > **NOTE**
The ACTS build middleware is a static library, which will be linked to the image.
-### Executing Test Cases in C (for the Mini System\)
+### Executing Test Cases in C (for the Mini System)
**Executing Test Cases for the Mini System**
@@ -211,120 +213,122 @@ The log for each test suite starts with "Start to run test suite:" and ends wit
### Developing Test Cases in C++ (for Standard and Small Systems)
-**Developing Test Cases for Small-System Devices** \(for the standard system, see the **global/i18n\_standard directory**.\)
+**Developing Test Cases for Small-System Devices** (for the standard system, see the **global/i18n_standard directory**.)
The HCPPTest framework, an enhanced version based on the open-source framework Googletest, is used.
-1. Define the test case directory. The test cases are stored to **test/xts/acts**.
-
- ```
- ├── acts
- │ └──subsystem_lite
- │ │ └── module_posix
- │ │ │ └── BUILD.gn
- │ │ │ └── src
- │ └──build_lite
- │ │ └── BUILD.gn
- ```
-
-2. Write the test case in the **src** directory.
-
- a) Include the test framework header file.
-
- The following statement includes **gtest.h**.
+1. Define the test case directory. The test cases are stored to **test/xts/acts**.
```
- #include "gtest/gtest.h"
+ ├── acts
+ │ └──subsystem_lite
+ │ │ └── module_posix
+ │ │ │ └── BUILD.gn
+ │ │ │ └── src
+ │ └──build_lite
+ │ │ └── BUILD.gn
```
- b) Define Setup and TearDown.
-
- ```
- using namespace std;
- using namespace testing::ext;
- class TestSuite: public testing::Test {
- protected:
- // Preset action of the test suite, which is executed before the first test case
- static void SetUpTestCase(void){
- }
- // Test suite cleanup action, which is executed after the last test case
- static void TearDownTestCase(void){
- }
- // Preset action of the test case
- virtual void SetUp()
- {
- }
- // Cleanup action of the test case
- virtual void TearDown()
- {
- }
- };
- ```
-
- c) Use the **HWTEST** or **HWTEST\_F** macro to write the test case.
-
- **HWTEST**: definition of common test cases, including the test suite name, test case name, and case annotation.
-
- **HWTEST\_F**: definition of SetUp and TearDown test cases, including the test suite name, test case name, and case annotation.
-
- Three parameters are involved: test suite name, test case name, and test case properties \(including type, granularity, and level\).
+2. Write the test case in the **src** directory.
- ```
- HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) {
- // Do something
- }
- ```
+ (1) Include the test framework.
+
+ Include **gtest.h**.
+ ```
+ #include "gtest/gtest.h"
+ ```
+
+
+ (2) Define Setup and TearDown.
+
+ ```
+ using namespace std;
+ using namespace testing::ext;
+ class TestSuite: public testing::Test {
+ protected:
+ // Preset action of the test suite, which is executed before the first test case
+ static void SetUpTestCase(void){
+ }
+ // Test suite cleanup action, which is executed after the last test case
+ static void TearDownTestCase(void){
+ }
+ // Preset action of the test case
+ virtual void SetUp()
+ {
+ }
+ // Cleanup action of the test case
+ virtual void TearDown()
+ {
+ }
+ };
+ ```
+
+
+ (3) Use the **HWTEST** or **HWTEST_F** macro to write the test case.
+
+ **HWTEST**: definition of common test cases, including the test suite name, test case name, and case annotation.
+
+ **HWTEST_F**: definition of SetUp and TearDown test cases, including the test suite name, test case name, and case annotation.
+
+ Three parameters are involved: test suite name, test case name, and test case properties (including type, granularity, and level).
+
+ ```
+ HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) {
+ // Do something
+ ```
-3. Create a configuration file \(**BUILD.gn**\) of the test module.
+3. Create a configuration file (**BUILD.gn**) of the test module.
Create a **BUILD.gn** file in each test module directory, and specify the name of the built static library and its dependent header files and libraries. Each test module is independently built into a **.bin** executable file, which can be directly pushed to the development board for testing.
Example:
-
- ```
- import("//test/xts/tools/lite/build/suite_lite.gni")
- hcpptest_suite("ActsDemoTest") {
- suite_name = "acts"
- sources = [
- "src/TestDemo.cpp"
- ]
-
- include_dirs = [
- "src",
- ...
- ]
- deps = [
- ...
- ]
- cflags = [ "-Wno-error" ]
- }
+
+ ```
+ import("//test/xts/tools/lite/build/suite_lite.gni")
+ hcpptest_suite("ActsDemoTest") {
+ suite_name = "acts"
+ sources = [
+ "src/TestDemo.cpp"
+ ]
+
+ include_dirs = [
+ "src",
+ ...
+ ]
+ deps = [
+ ...
+ ]
+ cflags = [ "-Wno-error" ]
+ }
+ ```
- ```
-
4. Add build options to the **BUILD.gn** file in the **acts** directory.
- Add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
+ Add the test module to the **test/xts/acts/build_lite/BUILD.gn** script in the **acts** directory.
+
+ ```
+ lite_component("acts") {
+ ...
+ else if(board_name == "liteos_a") {
+ features += [
+ ...
+ "//xts/acts/subsystem_lite/module_posix:ActsDemoTest"
+ ]
+ }
+ }
+ ```
- ```
- lite_component("acts") {
- ...
- else if(board_name == "liteos_a") {
- features += [
- ...
- "//xts/acts/subsystem_lite/module_posix:ActsDemoTest"
- ]
- }
- }
- ```
5. Run build commands.
Test suites are built along with the OS version. The ACTS is built together with the debug version.
- > **NOTE**
The ACTS for the small system is independently built to an executable file \(.bin\) and archived in the **suites\\acts** directory of the build result.
+ > **NOTE**
+ >
+ >The ACTS for the small system is independently built to an executable file (.bin) and archived in the **suites\acts** directory of the build result.
-### Executing Test Cases in C++ (for Standard and Small Systems\)
+### Executing Test Cases in C++ (for Standard and Small Systems)
**Executing Test Cases for the Small System**
@@ -332,24 +336,29 @@ Currently, test cases are shared by the NFS and mounted to the development board
**Setting Up the Environment**
-1. Use a network cable or wireless network to connect the development board to your PC.
-2. Configure the IP address, subnet mask, and gateway for the development board. Ensure that the development board and the PC are in the same network segment.
-3. Install and register the NFS server on the PC and start the NFS service.
+1. Use a network cable or wireless network to connect the development board to your PC.
+
+2. Configure the IP address, subnet mask, and gateway for the development board. Ensure that the development board and the PC are in the same network segment.
+
+3. Install and register the NFS server on the PC and start the NFS service.
+
4. Run the **mount** command for the development board to ensure that the development board can access NFS shared files on the PC.
Format: **mount** _NFS server IP address_**:/**_NFS shared directory_ **/**_development board directory_ **nfs**
- Example:
+ Example:
```
mount 192.168.1.10:/nfs /nfs nfs
```
+
+
**Executing Test Cases**
Execute **ActsDemoTest.bin** to trigger test case execution, and analyze serial port logs generated after the execution is complete.
-### Developing Test Cases in JavaScript (for the Standard System\)
+### Developing Test Cases in JavaScript (for the Standard System)
The HJSUnit framework is used to support automated test of OpenHarmony apps that are developed using the JavaScript language based on the JS application framework.
@@ -366,73 +375,82 @@ The test cases are developed with the JavaScript language and must meet the prog
| beforeEach | Presets a test-case-level action executed before each test case is executed. The number of execution times is the same as the number of test cases defined by it. You can pass the action function as the only parameter. | No |
| afterEach | Presets a test-case-level clear action executed after each test case is executed. The number of execution times is the same as the number of test cases defined by it. You can pass the clear function as the only parameter. | No |
| describe | Defines a test suite. You can pass two parameters: test suite name and test suite function. The describe statement supports nesting. You can use beforeall, beforeEach, afterEach, and afterAll in each describe statement. | Yes |
-| it | Defines a test case. You can pass three parameters: test case name, filter parameter, and test case function.
**Usage of the filter parameter:**
The value of the filter parameter is a 32-bit integer. Setting different bits to 1 means different configurations:
- Bit 0: whether the filter parameter takes effect. 1 means that the test case is used for the function test and other settings of the parameter do not take effect.
- Bits 0-10: test case categories
- Bits 16-18: test case scales
- Bits 24-28: test levels
**Test case categories**: Bits 0-10 indicate FUNCTION (function test), PERFORMANCE (performance test), POWER (power consumption test), RELIABILITY (reliability test), SECURITY (security compliance test), GLOBAL (integrity test), COMPATIBILITY (compatibility test), USER (user test), STANDARD (standard test), SAFETY (security feature test), and RESILIENCE (resilience test), respectively.
**Test case scales**: Bits 16-18 indicate SMALL (small-scale test), MEDIUM (medium-scale test), and LARGE (large-scale test), respectively.
**Test levels**: Bits 24-28 indicate LEVEL0 (level-0 test), LEVEL1 (level-1 test), LEVEL2 (level-2 test), LEVEL3 (level-3 test), and LEVEL4 (level-4 test), respectively. | Yes |
+| it | Defines a test case. You can pass three parameters: test case name, filter parameter, and test case function.
**Filter parameter:**
The value is a 32-bit integer. Setting different bits to 1 means different configurations.
- Setting bit 0 to **1** means bypassing the filter.
- Setting bits 0-10 to **1** specifies the test case type, which can be FUNCTION (function test), PERFORMANCE (performance test), POWER (power consumption test), RELIABILITY (reliability test), SECURITY (security compliance test), GLOBAL (integrity test), COMPATIBILITY (compatibility test), USER (user test), STANDARD (standard test), SAFETY (security feature test), and RESILIENCE (resilience test), respectively.
- Setting bits 16-18 to **1** specifies the test case scale, which can be SMALL (small-scale test), MEDIUM (medium-scale test), and LARGE (large-scale test), respectively.
- Seting bits 24-28 to **1** specifies the test level, which can be LEVEL0 (level-0 test), LEVEL1 (level-1 test), LEVEL2 (level-2 test), LEVEL3 (level-3 test), and LEVEL4 (level-4 test), respectively.
| Yes |
Use the standard syntax of Jasmine to write test cases. The ES6 specification is supported.
1. Define the test case directory. The test cases are stored in the **entry/src/main/js/test** directory.
```
- ├── BUILD.gn
- │ └──entry
- │ │ └──src
- │ │ │ └──main
- │ │ │ │ └──js
- │ │ │ │ │ └──default
- │ │ │ │ │ │ └──pages
- │ │ │ │ │ │ │ └──index
- │ │ │ │ │ │ │ │ └──index.js # Entry file
- │ │ │ │ │ └──test # Test code
- │ │ │ └── resources # HAP resources
- │ │ │ └── config.json # HAP configuration file
- ```
+ ├── BUILD.gn
+ │ └──entry
+ │ │ └──src
+ │ │ │ └──main
+ │ │ │ │ └──js
+ │ │ │ │ │ └──default
+ │ │ │ │ │ │ └──pages
+ │ │ │ │ │ │ │ └──index
+ │ │ │ │ │ │ │ │ └──index.js # Entry file
+ │ │ │ │ │ └──test # Test code directory
+ │ │ │ └── resources # HAP resources
+ │ │ │ └── config.json # HAP configuration file
+ ```
-2. Start the JS test framework and load test cases. The following is an example for **index.js**.
- ```
- // Start the JS test framework and load test cases.
+2. Start the JS test framework and load test cases.
+
+ The following is an example for **index.js**.
+
+ ```
+ // Start the JS test framework and load test cases.
import {Core, ExpectExtend} from 'deccjsunit/index'
export default {
- data: {
- title: ""
- },
- onInit() {
- this.title = this.$t('strings.world');
- },
- onShow() {
- console.info('onShow finish')
- const core = Core.getInstance()
- const expectExtend = new ExpectExtend({
- 'id': 'extend'
- })
- core.addService('expect', expectExtend)
- core.init()
- const configService = core.getDefaultService('config')
- configService.setConfig(this)
- require('../../../test/List.test')
- core.execute()
- },
- onReady() {
- },
- }
- ```
+ data: {
+ title: ""
+ },
+ onInit() {
+ this.title = this.$t('strings.world');
+ },
+ onShow() {
+ console.info('onShow finish')
+ const core = Core.getInstance()
+ const expectExtend = new ExpectExtend({
+ 'id': 'extend'
+ })
+ core.addService('expect', expectExtend)
+ core.init()
+ const configService = core.getDefaultService('config')
+ configService.setConfig(this)
+ require('../../../test/List.test')
+ core.execute()
+ },
+ onReady() {
+ },
+ }
+ ```
-3. Write a unit test case by referring to the following example:
+
- ```
- // Use HJSUnit to perform the unit test.
- describe('appInfoTest', function () {
- it('app_info_test_001', 0, function () {
- var info = app.getInfo()
- expect(info.versionName).assertEqual('1.0')
- expect(info.versionCode).assertEqual('3')
- })
- })
- ```
+3. Write a unit test case.
+
+ The following is an example:
+
+ ```
+ // Example 1: Use HJSUnit to perform a unit test.
+ describe('appInfoTest', function () {
+ it('app_info_test_001', 0, function () {
+ var info = app.getInfo()
+ expect(info.versionName).assertEqual('1.0')
+ expect(info.versionCode).assertEqual('3')
+ })
+ })
+ ```
+
-### Packaging Test Cases in JavaScript (for the Standard System\)
+
+### Packaging Test Cases in JavaScript (for the Standard System)
For details about how to build a HAP, see the JS application development guide of the standard system [Building and Creating HAPs](https://developer.harmonyos.com/en/docs/documentation/doc-guides/build_overview-0000001055075201).
@@ -444,12 +462,15 @@ Run the following command:
./build.sh suite=acts system_size=standard
```
+
+
+
Test case directory: **out/release/suites/acts/testcases**
Test framework and test case directory: **out/release/suites/acts** \(the test suite execution framework is compiled during the build process)
-## Executing Test Cases in a Full Build (for Small and Standard Systems\)
+## Executing Test Cases in a Full Build (for Small and Standard Systems)
**Setting Up a Test Environment**
@@ -468,29 +489,30 @@ Install Python 3.7 or a later version on a Windows environment and ensure that t
**Executing Test Cases**
-1. On the Windows environment, locate the directory in which the test cases are stored \(**out/release/suites/acts**, copied from the Linux server\), go to the directory in the Windows command window, and run **acts\\run.bat**.
+1. On the Windows environment, locate the directory in which the test cases are stored \(**out/release/suites/acts**, copied from the Linux server), go to the directory in the Windows command window, and run **acts\\run.bat**.
-1. Enter the command for executing the test case.
+2. Enter the command for executing the test case.
- Execute all test cases.
- ```
- run acts
- ```
-
- 
-
- - Execute the test cases of a module \(view specific module information in **\\acts\\testcases\\**\).
-
- ```
- run –l ActsSamgrTest
- ```
-
- 
-
- Wait until the test cases are complete.
-
+ ```
+ run acts
+ ```
+
+ 
+
+ - Execute the test cases of a module \(view specific module information in **\acts\testcases\**).
+
+ ```
+ run –l ActsSamgrTest
+ ```
+
+ 
+
+ You can view specific module information in **\acts\testcases\**.
+
+ Wait until the test cases are complete.
3. View the test report.
- Go to **acts\\reports\\**, obtain the current execution record, and open **summary\_report.html** to view the test report.
+ Go to **acts\reports**, obtain the current execution record, and open **summary_report.html** to view the test report.
diff --git a/en/device-dev/website.md b/en/device-dev/website.md
index 5807147be58a44f7fe2e9da0ee47bd33e267f1ea..058c142b50164cd3f0e38649a61024b6e8eac8c8 100644
--- a/en/device-dev/website.md
+++ b/en/device-dev/website.md
@@ -24,6 +24,7 @@
- Appendix
- [Introduction to the Hi3861 Development Board](quick-start/quickstart-ide-lite-introduction-hi3861.md)
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-ide-lite-introduction-hi3516.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- Getting Started with Mini and Small Systems (Installation Package Mode)
- [Mini and Small System Overview](quick-start/quickstart-lite-overview.md)
- [Environment Preparation](quick-start/quickstart-lite-env-setup.md)
@@ -51,6 +52,7 @@
- [Introduction to the Hi3861 Development Board](quick-start/quickstart-lite-introduction-hi3861.md)
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-lite-introduction-hi3516.md)
- [Reference](quick-start/quickstart-lite-reference.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- Getting Started with Standard System (IDE Mode, Recommended)
- [Standard System Overview](quick-start/quickstart-ide-standard-overview.md)
- Environment Preparation
@@ -71,6 +73,7 @@
- Appendix
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-ide-standard-board-introduction-hi3516.md)
- [Introduction to the RK3568 Development Board](quick-start/quickstart-ide-standard-board-introduction-rk3568.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- Getting Started with Standard System (Installation Package Mode)
- [Standard System Overview](quick-start/quickstart-standard-overview.md)
- [Setting Up Environments for Standard System](quick-start/quickstart-standard-env-setup.md)
@@ -94,6 +97,7 @@
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-standard-board-introduction-hi3516.md)
- [Introduction to the RK3568 Development Board](quick-start/quickstart-standard-board-introduction-rk3568.md)
- [Reference](quick-start/quickstart-standard-reference.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- [Obtaining Source Code](get-code/sourcecode-acquire.md)
- Compatibility and Security
@@ -379,6 +383,7 @@
- [Audio](driver/driver-peripherals-audio-des.md)
- [Camera](driver/driver-peripherals-camera-des.md)
- [Facial Authentication](driver/driver-peripherals-face_auth-des.md)
+ - [Fingerprint Authentication](driver/driver-peripherals-fingerprint_auth-des.md)
- [LCD](driver/driver-peripherals-lcd-des.md)
- [Light](driver/driver-peripherals-light-des.md)
- [PIN Authentication](driver/driver-peripherals-pinauth-des.md)
diff --git a/zh-cn/application-dev/ability/fa-serviceability.md b/zh-cn/application-dev/ability/fa-serviceability.md
index bae0e29ea3a3947ac0fe5db65d10a2b4e5256a85..58991ec7147c2789774dff1892c68f8a34d72653 100644
--- a/zh-cn/application-dev/ability/fa-serviceability.md
+++ b/zh-cn/application-dev/ability/fa-serviceability.md
@@ -32,7 +32,7 @@
},
onConnect(want) {
console.log('ServiceAbility OnConnect');
- return null;
+ return new FirstServiceAbilityStub('test');
},
onDisconnect(want) {
console.log('ServiceAbility OnDisConnect');
@@ -139,41 +139,36 @@ let promise = featureAbility.startAbility(
```javascript
import prompt from '@system.prompt'
- let mRemote;
- function onConnectCallback(element, remote){
- console.log('onConnectLocalService onConnectDone element: ' + element);
- console.log('onConnectLocalService onConnectDone remote: ' + remote);
- mRemote = remote;
- if (mRemote == null) {
- prompt.showToast({
- message: "onConnectLocalService not connected yet"
- });
- return;
- }
- let option = new rpc.MessageOption();
- let data = new rpc.MessageParcel();
- let reply = new rpc.MessageParcel();
- data.writeInt(1);
- data.writeInt(99);
- mRemote.sendRequest(1, data, reply, option).then((result) => {
- console.log('sendRequest success');
- let msg = reply.readInt();
+ var option = {
+ onConnect: function onConnectCallback(element, proxy) {
+ console.log(`onConnectLocalService onConnectDone`)
+ if (proxy === null) {
+ prompt.showToast({
+ message: "Connect service failed"
+ })
+ return
+ }
+ let data = rpc.MessageParcel.create()
+ let reply = rpc.MessageParcel.create()
+ let option = new rpc.MessageOption()
+ data.writeInterfaceToken("connect.test.token")
+ proxy.sendRequest(0, data, reply, option)
prompt.showToast({
- message: "onConnectLocalService connect result: " + msg,
- duration: 3000
- });
- }).catch((e) => {
- console.log('sendRequest error:' + e);
- });
-
- }
-
- function onDisconnectCallback(element){
- console.log('ConnectAbility onDisconnect Callback')
- }
-
- function onFailedCallback(code){
- console.log('ConnectAbility onFailed Callback')
+ message: "Connect service success"
+ })
+ },
+ onDisconnect: function onDisconnectCallback(element) {
+ console.log(`onConnectLocalService onDisconnectDone element:${element}`)
+ prompt.showToast({
+ message: "Disconnect service success"
+ })
+ },
+ onFailed: function onFailedCallback(code) {
+ console.log(`onConnectLocalService onFailed errCode:${code}`)
+ prompt.showToast({
+ message: "Connect local service onFailed"
+ })
+ }
}
```
@@ -201,44 +196,27 @@ let promise = featureAbility.startAbility(
```javascript
import rpc from "@ohos.rpc";
- let mMyStub;
- export default {
- onStart() {
- class MyStub extends rpc.RemoteObject{
- constructor(des) {
- if (typeof des === 'string') {
- super(des);
- }
- return null;
- }
- onRemoteRequest(code, data, reply, option) {
- console.log("ServiceAbility onRemoteRequest called");
- if (code === 1) {
- let op1 = data.readInt();
- let op2 = data.readInt();
- console.log("op1 = " + op1 + ", op2 = " + op2);
- reply.writeInt(op1 + op2);
- } else {
- console.log("ServiceAbility unknown request code");
- }
- return true;
- }
- }
- mMyStub = new MyStub("ServiceAbility-test");
- },
- onCommand(want, startId) {
- console.log('ServiceAbility onCommand');
- },
- onConnect(want) {
- console.log('ServiceAbility OnConnect');
- return mMyStub;
- },
- onDisconnect(want) {
- console.log('ServiceAbility OnDisConnect');
- },
- onStop() {
- console.log('ServiceAbility onStop');
- },
+ class FirstServiceAbilityStub extends rpc.RemoteObject {
+ constructor(des: any) {
+ if (typeof des === 'string') {
+ super(des)
+ } else {
+ return
+ }
+ }
+
+ onRemoteRequest(code: number, data: any, reply: any, option: any) {
+ console.log(printLog + ` onRemoteRequest called`)
+ if (code === 1) {
+ let string = data.readString()
+ console.log(printLog + ` string=${string}`)
+ let result = Array.from(string).sort().join('')
+ console.log(printLog + ` result=${result}`)
+ reply.writeString(result)
+ } else {
+ console.log(printLog + ` unknown request code`)
+ }
+ return true;
}
```
@@ -255,40 +233,36 @@ let promise = featureAbility.startAbility(
```ts
import prompt from '@system.prompt'
-let mRemote;
-function onConnectCallback(element, remote){
- console.log('onConnectRemoteService onConnectDone element: ' + element);
- console.log('onConnectRemoteService onConnectDone remote: ' + remote);
- mRemote = remote;
- if (mRemote == null) {
- prompt.showToast({
- message: "onConnectRemoteService not connected yet"
- });
- return;
- }
- let option = new rpc.MessageOption();
- let data = new rpc.MessageParcel();
- let reply = new rpc.MessageParcel();
- data.writeInt(1);
- data.writeInt(99);
- mRemote.sendRequest(1, data, reply, option).then((result) => {
- console.log('sendRequest success');
- let msg = reply.readInt();
+var option = {
+ onConnect: function onConnectCallback(element, proxy) {
+ console.log(`onConnectRemoteService onConnectDone`)
+ if (proxy === null) {
+ prompt.showToast({
+ message: "Connect service failed"
+ })
+ return
+ }
+ let data = rpc.MessageParcel.create()
+ let reply = rpc.MessageParcel.create()
+ let option = new rpc.MessageOption()
+ data.writeInterfaceToken("connect.test.token")
+ proxy.sendRequest(0, data, reply, option)
prompt.showToast({
- message: "onConnectRemoteService connect result: " + msg,
- duration: 3000
- });
- }).catch((e) => {
- console.log('sendRequest error:' + e);
- });
-}
-
-function onDisconnectCallback(element){
- console.log('ConnectRemoteAbility onDisconnect Callback')
-}
-
-function onFailedCallback(code){
- console.log('ConnectRemoteAbility onFailed Callback')
+ message: "Connect service success"
+ })
+ },
+ onDisconnect: function onDisconnectCallback(element) {
+ console.log(`onConnectRemoteService onDisconnectDone element:${element}`)
+ prompt.showToast({
+ message: "Disconnect service success"
+ })
+ },
+ onFailed: function onFailedCallback(code) {
+ console.log(`onConnectRemoteService onFailed errCode:${code}`)
+ prompt.showToast({
+ message: "Connect local service onFailed"
+ })
+ }
}
```
@@ -374,23 +348,25 @@ Service侧把自身的实例返回给调用侧的代码示例如下:
```ts
import rpc from "@ohos.rpc";
-class FirstServiceAbilityStub extends rpc.RemoteObject{
- constructor(des) {
+class FirstServiceAbilityStub extends rpc.RemoteObject {
+ constructor(des: any) {
if (typeof des === 'string') {
- super(des);
+ super(des)
} else {
- return null;
+ return
}
}
- onRemoteRequest(code, data, reply, option) {
- console.log("ServiceAbility onRemoteRequest called");
+
+ onRemoteRequest(code: number, data: any, reply: any, option: any) {
+ console.log(printLog + ` onRemoteRequest called`)
if (code === 1) {
- let op1 = data.readInt();
- let op2 = data.readInt();
- console.log("op1 = " + op1 + ", op2 = " + op2);
- reply.writeInt(op1 + op2);
+ let string = data.readString()
+ console.log(printLog + ` string=${string}`)
+ let result = Array.from(string).sort().join('')
+ console.log(printLog + ` result=${result}`)
+ reply.writeString(result)
} else {
- console.log("ServiceAbility unknown request code");
+ console.log(printLog + ` unknown request code`)
}
return true;
}
diff --git a/zh-cn/application-dev/ability/stage-ability-continuation.md b/zh-cn/application-dev/ability/stage-ability-continuation.md
index 260f37a05751269cf368f539214de8632c935e8e..b50cab8a17cfbcb49e8ff6098e410c76b1c3ae18 100755
--- a/zh-cn/application-dev/ability/stage-ability-continuation.md
+++ b/zh-cn/application-dev/ability/stage-ability-continuation.md
@@ -13,7 +13,8 @@
|接口名 | 描述|
|:------ | :------|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | 迁移**发起端**在该回调中保存迁移所需要的数据,同时返回是否同意迁移:AGREE表示同意,REJECT表示拒绝;MISMATCH表示版本不匹配。 |
-| onCreate(want: Want, param : LaunchParam): void | 迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
+| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | 多实例应用迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
+| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | 单实例应用迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
@@ -21,10 +22,12 @@

-迁移实际上是Ability携带数据的跨端启动。触发迁移动作时,会在A设备上通过系统回调应用的onContinue()方法,开发者需要在此方法中实现当前数据的保存。然后系统发起在B设备上的跨端启动,并将数据一同传输到B设备。B设备系统回调onCreate()方法,开发者需要在此方法中实现传输过来的数据的恢复。
+迁移实际上是Ability携带数据的跨端启动。触发迁移动作时,会在A设备上通过系统回调应用的onContinue()方法,开发者需要在此方法中实现当前数据的保存。然后系统发起在B设备上的跨端启动,并将数据一同传输到B设备。B设备系统回调onCreate()/onNewWant()方法,开发者需要在此方法中实现传输过来的数据的恢复。
## 开发步骤
+下文代码片段来自参考[示例](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/samples/continuationManualTestSuite)。
+
### 迁移应用
1. 配置
@@ -32,9 +35,17 @@
- 配置应用支持迁移
在module.json5中配置continuable字段:true表示支持迁移,false表示不支持,默认为false。配置为false的应用将被系统识别为无法迁移。
-
+
```javascript
- "continuable": true
+ {
+ "module": {
+ "abilities": [
+ {
+ "continuable": true,
+ }
+ ]
+ }
+ }
```
@@ -42,30 +53,53 @@
- 配置应用启动类型
- 迁移当前只支持多实例应用,需要在在module.json5中配置launchType字段为standard。
+ 多实例应用在module.json5中将launchType字段配置为standard,目标端将会拉起一个新的应用,并恢复页面;单实例将该字段配置为singleton,如果目标端应用已经打开,迁移将会将已有页面栈清空,并根据迁移数据恢复页面。关于单实例与多实例的更多信息详见[ability开发指导](./stage-ability.md)启动模式。
+
+ 多实例:
```javascript
- "launchType": "standard"
+ {
+ "module": {
+ "abilities": [
+ {
+ "launchType": "standard",
+ }
+ ]
+ }
+ }
```
-
-
-
+ 缺省或如下配置为单实例:
+
+ ```javascript
+ {
+ "module": {
+ "abilities": [
+ {
+ "launchType": "singleton",
+ }
+ ]
+ }
+ }
+ ```
+
+
+
- 申请分布式权限
支持跨端迁移的应用需要在module.json5申请分布式权限 DISTRIBUTED_DATASYNC。
-
+
```javascript
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
},
```
-
+
这个权限需要在应用首次启动的时候弹窗让用户授予,可以通过在ability的onWindowStageCreate中添加如下代码实现:
-
+
```javascript
requestPermissions = async () => {
let permissions: Array = [
@@ -102,12 +136,11 @@
}
}
```
-
-
-2. 实现onContinue()接口
+
+2. 实现onContinue接口
onContinue()接口在发起端被调用,主要用于在迁移发起时,通知开发者保存控件状态变量和内存中数据,准备迁移。当应用准备完成后,需要返回OnContinueResult.AGREE(0)表示同意迁移,否则返回相应的错误码拒绝迁移。如果不实现该接口,系统将默认为拒绝迁移。
@@ -119,22 +152,25 @@
```
要实现迁移,此接口必须实现并返回AGREE,否则默认为拒绝迁移。
-
+
+ 另外,在该接口的入参wantParam中可以获取目标设备的deviceId(key为“targetDevice”),以及目标设备上所安装的应用的版本号(key为“version”)。版本号可用来与本应用版本进行对比,做兼容性判断,如果判定本应用版本与远端不兼容,可以返回OnContinueResult.MISMATCH拒绝迁移。
+
示例
-
+
```javascript
- onContinue(wantParam : {[key: string]: any}) {
- Logger.info("onContinue using distributedObject")
- // set user input data into want params
- wantParam["input"] = AppStorage.Get('ContinueInput');
- Logger.info(`onContinue input = ${wantParam["input"]}`);
- return AbilityConstant.OnContinueResult.AGREE
- }
+ onContinue(wantParam : {[key: string]: any}) {
+ Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
+ let workInput = AppStorage.Get('ContinueWork');
+ // set user input data into want params
+ wantParam["work"] = workInput // set user input data into want params
+ Logger.info(`onContinue input = ${wantParam["input"]}`);
+ return AbilityConstant.OnContinueResult.AGREE
+ }
```
-
+
-3. 在onCreate()接口中实现迁移逻辑
+3. 在onCreate/onNewWant接口中实现迁移逻辑
onCreate()接口在迁移目标端被调用,在目标端ability被拉起时,通知开发者同步已保存的内存数据和控件状态,完成后触发页面的恢复。如果不实现该接口中迁移相关逻辑,ability将会作为普通的启动方式拉起,无法恢复页面。
@@ -142,22 +178,34 @@
完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复。
- 示例
+
+ 在入参want中也可以通过want.parameters.version来获取发起端的应用版本号。
+
+ 示例
+
```javascript
- onCreate(want, launchParam) {
- Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
- globalThis.abilityWant = want;
- if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
- let input = want.parameters.input // get user data from want params
- AppStorage.SetOrCreate('ContinueInput', input)
- Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
-
- this.contentStorage = new ContentStorage();
- this.context.restoreWindowStage(this.contentStorage);
- }
- }
+ import Ability from '@ohos.application.Ability';
+ import distributedObject from '@ohos.data.distributedDataObject';
+
+ export default class MainAbility extends Ability {
+ storage : LocalStorag;
+
+ onCreate(want, launchParam) {
+ Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
+ if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
+ // get user data from want params
+ let workInput = want.parameters.work
+ Logger.info(`work input ${workInput}`)
+ AppStorage.SetOrCreate('ContinueWork', workInput)
+
+ this.storage = new LocalStorage();
+ this.context.restoreWindowStage(this.storage);
+ }
+ }
+ }
```
+如果是单实例应用,则同样的代码实现onNewWant接口即可。
@@ -165,32 +213,42 @@
使用分布式对象
-分布式数据对象提供了与本地变量类似的操作,实现两个设备的数据同步,当设备1的应用A的分布式数据对象增、删、改数据后,设备2的应用A也可以获取到对应的数据变化,同时还能监听数据变更以及对端数据对象的上下线。用法详见[分布式对象指导文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-distributedobject-guidelines.md)。
+分布式数据对象提供了与本地变量类似的操作,实现两个设备的数据同步,当设备1的应用A的分布式数据对象增、删、改数据后,设备2的应用A也可以获取到对应的数据变化,同时还能监听数据变更以及对端数据对象的上下线。用法详见[分布式对象指导文档](../database/database-distributedobject-guidelines.md)。
迁移场景中,分布式对象(distributedDataObject)主要用于将本机内存数据同步到目标设备。
-- 发起端在onContinue()中,将待迁移的数据存入分布式对象中,然后设置好session id,并通过wantParam将session id传到远端设备。
+- 发起端在onContinue()中,将待迁移的数据存入分布式对象中,并调用save接口将数据保存并同步到远端,然后设置好session id,并通过wantParam将session id传到远端设备。
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
- var g_object = distributedObject.createDistributedObject({name:undefined});
+ var g_object = distributedObject.createDistributedObject({data:undefined});
export default class MainAbility extends Ability {
- contentStorage : ContentStorage
sessionId : string;
onContinue(wantParam : {[key: string]: any}) {
- Logger.info("onContinue using distributedObject")
- this.sessionId = distributedObject.genSessionId();
- //set distributed data object session id
- g_object.setSessionId(this.sessionId);
- g_object.name = "Amy";
- // set session id into want params
- wantParam["session"] = this.sessionId;
- return AbilityConstant.OnContinueResult.AGREE
- }
+ Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
+
+ if (g_object.__sessionId === undefined) {
+ this.sessionId = distributedObject.genSessionId()
+ Logger.info(`onContinue generate new sessionId`)
+ }
+ else {
+ this.sessionId = g_object.__sessionId;
+ }
+
+ wantParam["session"] = this.sessionId
+ g_object.data = AppStorage.Get('ContinueStudy');
+ Logger.info(`onContinue sessionId = ${this.sessionId}, name = ${g_object.data}`)
+ g_object.setSessionId(this.sessionId);
+ g_object.save(wantParam.targetDevice, (result, data)=>{
+ Logger.info("save callback");
+ Logger.info("save sessionId " + data.sessionId);
+ Logger.info("save version " + data.version);
+ Logger.info("save deviceId " + data.deviceId);
+ });
```
@@ -201,15 +259,11 @@
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
- var g_object = distributedObject.createDistributedObject({name:undefined});
+ var g_object = distributedObject.createDistributedObject({data:undefined});
export default class MainAbility extends Ability {
- contentStorage : ContentStorage
- sessionId : string;
+ storage : LocalStorag;
- statusCallback(sessionId, networkid, status) {
- Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
- }
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
@@ -218,15 +272,40 @@
this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
- g_object.on("status", this.statusCallback);
- // set session id, so it will sync data from remote device
- g_object.setSessionId(this.sessionId);
+ // in order to fetch from remote, reset g_object.data to undefined first
+ g_object.data = undefined;
+ // set session id, so it will fetch data from remote
+ g_object.setSessionId(this.sessionId);
- this.contentStorage = new ContentStorage();
- this.context.restoreWindowStage(this.contentStorage);
+ AppStorage.SetOrCreate('ContinueStudy', g_object.data)
+ this.storage = new LocalStorage();
+ this.context.restoreWindowStage(this.storage);
}
+
}
}
```
+
+
+
+### 其他说明
+
+1. 超时机制:
+
+ - 如果目标端迁移应用未安装,系统会去查询在目标端设备上能否安装,这段最大时间为4s,超出此时间,调用者会收到超时错误码,视为不可在目标端安装。若可安装,则系统会提示用户在目标端安装,安装完成后可再次尝试发起迁移。
+ - 如果目标端迁移应用已安装 ,那么发起迁移后超时时间为20s,若超过此时间,调用者会收到超时错误码,视为此次迁移失败。
+
+2. 当前系统默认支持页面栈信息的迁移,即发起端页面栈会被自动迁移到目标端,无需开发者适配。
+
+
+
+### 约束
+
+1. 迁移要求在同ability之间进行,也就是需要相同的bundleName、moduleName和abilityName,具体含义[应用包配置文件说明](../quick-start/stage-structure.md)。
+2. 当前应用只能实现迁移能力,但迁移的动作只能由系统发起。
+
+
+### 最佳实践
+ 为了获得最佳体验,建议100kb以下的数据直接使用wantParam传输,大于100kb的数据采用分布式对象传输。
\ No newline at end of file
diff --git a/zh-cn/application-dev/database/database-distributedobject-guidelines.md b/zh-cn/application-dev/database/database-distributedobject-guidelines.md
index dac9fb45126a7f3b3dce8f9ee0cc194ec625ff93..b0e4d49ad058984fb57ad4ec5bb7a8c6ae1ae41d 100644
--- a/zh-cn/application-dev/database/database-distributedobject-guidelines.md
+++ b/zh-cn/application-dev/database/database-distributedobject-guidelines.md
@@ -130,7 +130,7 @@
```js
//发起方
var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true,
- parent:{mother:"jack mom",father:"jack Dad"},list:[{mother:"jack mom"}, {father:"jack Dad"}]});
+ parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]});
local_object.setSessionId(sessionId);
//被拉起方
@@ -166,7 +166,7 @@
local_object.name = "jack";
local_object.age = 19;
local_object.isVis = false;
- local_object.parent = {mother:"jack mom",father:"jack Dad"};
+ local_object.parent = {mother:"jack mom", father:"jack Dad"};
local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}];
```
@@ -210,14 +210,14 @@
```js
// 保存数据对象
- local_object.save("local", (result, data)=>{
+ local_object.save("local", (result, data) => {
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// 撤回保存的数据对象
- local_object.revokeSave((result, data) =>{
+ local_object.revokeSave((result, data) => {
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
@@ -225,7 +225,7 @@
2.Promise方式
```js
// 保存数据对象
- g_object.save("local").then((result)=>{
+ g_object.save("local").then((result) => {
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
@@ -233,7 +233,7 @@
console.info("save local failed.");
});
// 撤回保存的数据对象
- g_object.revokeSave().then((result)=>{
+ g_object.revokeSave().then((result) => {
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md
index 785a513f5bc434892d88b3f75b5f5c2491f07b6b..26df601aaf7dfcff5ff6fc1bce3a06640529c5b9 100644
--- a/zh-cn/application-dev/database/database-relational-guidelines.md
+++ b/zh-cn/application-dev/database/database-relational-guidelines.md
@@ -288,9 +288,9 @@
```js
"requestPermissions":
- {
- "name": "ohos.permission.DISTRIBUTED_DATASYNC"
- }
+ {
+ "name": "ohos.permission.DISTRIBUTED_DATASYNC"
+ }
```
(2) 获取应用权限。
@@ -331,7 +331,7 @@
promise.then((result) => {
console.log('sync done.')
for (let i = 0; i < result.length; i++) {
- console.log('device=' + result[i][0] + ' status=' + result[i][1])
+ console.log('device=' + result[i][0] + 'status=' + result[i][1])
}
}).catch((err) => {
console.log('sync failed')
@@ -349,7 +349,7 @@
```js
function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) {
- console.log('device=' + device[i] + ' data changed')
+ console.log('device=' + device[i] + 'data changed')
}
}
try {
@@ -382,17 +382,17 @@
```js
let promiseBackup = rdbStore.backup("dbBackup.db")
- promiseBackup.then(()=>{
+ promiseBackup.then(() => {
console.info('Backup success.')
- }).catch((err)=>{
+ }).catch((err) => {
console.info('Backup failed, err: ' + err)
})
```
```js
let promiseRestore = rdbStore.restore("dbBackup.db")
- promiseRestore.then(()=>{
+ promiseRestore.then(() => {
console.info('Restore success.')
- }).catch((err)=>{
+ }).catch((err) => {
console.info('Restore failed, err: ' + err)
})
```
diff --git a/zh-cn/application-dev/device/sensor-guidelines.md b/zh-cn/application-dev/device/sensor-guidelines.md
index 6259723f5680f363646aca21d9341c6a22435622..8ffc74e20dea5ce602b497d67405ed87312ccf87 100644
--- a/zh-cn/application-dev/device/sensor-guidelines.md
+++ b/zh-cn/application-dev/device/sensor-guidelines.md
@@ -87,7 +87,7 @@
```
import sensor from "@ohos.sensor"
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
- console.info("Subscription succeeded. data = " + data);//调用成功,打印对应传感器的数据
+ console.info("Subscription succeeded. data = " + data);// 调用成功,打印对应传感器的数据
}
);
```
@@ -101,7 +101,7 @@
```
import sensor from "@ohos.sensor"
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() {
- console.info("Succeeded in unsubscribing from acceleration sensor data.");//注销成功,返回打印结果
+ console.info("Succeeded in unsubscribing from acceleration sensor data.");// 注销成功,返回打印结果
}
);
```
@@ -115,7 +115,7 @@
```
import sensor from "@ohos.sensor"
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
- console.info("Data obtained successfully. data=" + data);//获取数据成功,打印对应传感器的数据
+ console.info("Data obtained successfully. data=" + data);// 获取数据成功,打印对应传感器的数据
}
);
```
@@ -129,7 +129,7 @@
```
try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
- console.info("Data obtained successfully. data=" + data);//获取数据成功,打印对应传感器的数据
+ console.info("Data obtained successfully. data=" + data);// 获取数据成功,打印对应传感器的数据
});
} catch (error) {
console.error(error);
diff --git a/zh-cn/application-dev/media/audio-interruptmode.md b/zh-cn/application-dev/media/audio-interruptmode.md
index 6bd6386ab04a6f2894df3e4619b780e8078e4a5a..897fa18ec4091959fc8883d637d53f14c7b9e8b8 100644
--- a/zh-cn/application-dev/media/audio-interruptmode.md
+++ b/zh-cn/application-dev/media/audio-interruptmode.md
@@ -48,7 +48,7 @@
```js
var mode_ = audio.InterruptMode.SHARE_MODE;
- await this.audioRenderer.setInterruptMode(mode_).then(()=>{
+ await this.audioRenderer.setInterruptMode(mode_).then(() => {
console.log('[JSAR] [SetInterruptMode] 设置: ' + (mode_ == 0 ? "共享模式":"独立焦点模式") + "成功" );
});
```
diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md
index d5fb8cf6df69f69998a10337f57437f0d2f33947..6313ac85397e94b8e26c955ff647fc2d5c6208f3 100644
--- a/zh-cn/application-dev/media/audio-playback.md
+++ b/zh-cn/application-dev/media/audio-playback.md
@@ -193,12 +193,12 @@ export class AudioDemo {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
- audioPlayer.src = nextFdPath; //设置src属性,并重新触发触发'dataLoad'事件回调
+ audioPlayer.src = nextFdPath; // 设置src属性,并重新触发触发'dataLoad'事件回调
}
async audioPlayerDemo() {
- let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
- this.setCallBack(audioPlayer); //设置事件回调
+ let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例
+ this.setCallBack(audioPlayer); // 设置事件回调
let fdPath = 'fd://'
// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
@@ -210,7 +210,7 @@ export class AudioDemo {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
- audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
+ audioPlayer.src = fdPath; // 设置src属性,并触发'dataLoad'事件回调
}
}
```
diff --git a/zh-cn/application-dev/media/opensles-playback.md b/zh-cn/application-dev/media/opensles-playback.md
index 3f3b891f824fc15004f8a8f1e0d6150f3d765875..66e90957f3fe127f53714bf6615bb4f85541b61a 100644
--- a/zh-cn/application-dev/media/opensles-playback.md
+++ b/zh-cn/application-dev/media/opensles-playback.md
@@ -39,7 +39,7 @@
0
};
- //具体参数需要根据音频文件格式进行适配
+ // 具体参数需要根据音频文件格式进行适配
SLDataFormat_PCM pcmFormat = {
SL_DATAFORMAT_PCM,
2,
@@ -82,7 +82,7 @@
return;
}
- //wavFile_ 需要设置为用户想要播放的文件描述符
+ // wavFile_ 需要设置为用户想要播放的文件描述符
wavFile_ = fopen(path, "rb");
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
```
diff --git a/zh-cn/application-dev/quick-start/package-structure.md b/zh-cn/application-dev/quick-start/package-structure.md
index 6345a071e3ec1d01af0169dcc9ab1de1567f3cf3..fab0b688c882f775baca2f5675fbab106a1db7db 100644
--- a/zh-cn/application-dev/quick-start/package-structure.md
+++ b/zh-cn/application-dev/quick-start/package-structure.md
@@ -505,6 +505,7 @@ skills示例:
| name | 需要使用的权限名称。 | 字符串 | 否 |
| reason | 描述申请权限的原因。不能超过256个字节。需要做多语种适配。 | 字符串 | 分情况:当申请的权限为user_grant时,必须填写此字段,否则不允许在应用市场上架;其它权限可缺省,缺省为空 |
| usedScene | 描述权限使用的场景和时机。场景类型有:ability、when。ability:ability的名称,可配置多个。when:调用时机,可填的值有inuse(使用时)、always(始终) | 对象 | ability分情况:申请的权限有user_grant时,ability必填;没有user_grant时可缺省,缺省值为空。when可缺省,缺省值为“inuse” |
+具体示例可参考[访问控制开发指导](../security/accesstoken-guidelines.md#fa模型)。
表22 js对象的内部结构说明
diff --git a/zh-cn/application-dev/quick-start/stage-structure.md b/zh-cn/application-dev/quick-start/stage-structure.md
index fa20a6d5d3cf8cbef28290a52b06576796e7fa9c..808ab2b55571653ca795e7f37379ad2821828e8a 100644
--- a/zh-cn/application-dev/quick-start/stage-structure.md
+++ b/zh-cn/application-dev/quick-start/stage-structure.md
@@ -507,6 +507,7 @@ requestPermissions示例 :
}
}
```
+权限访问的更多说明,可参考[访问控制开发指导](../security/accesstoken-guidelines.md)
#### form对象内部结构
diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md
index db88c9d3067846b7135fa205633522c4c7277470..f834060bd898647d06fc810281923bde08a42fd7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md
@@ -248,7 +248,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数,返回Ability结果。 |
**示例:**
@@ -284,7 +284,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
@@ -323,7 +323,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**返回值:**
@@ -431,7 +431,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -465,7 +465,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**示例:**
@@ -564,7 +564,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -598,7 +598,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**示例:**
@@ -786,7 +786,7 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | 否 | 远端对象实例。 |
**返回值:**
@@ -930,7 +930,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -965,7 +965,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。|
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
@@ -1004,7 +1004,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**示例:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-appmanager.md b/zh-cn/application-dev/reference/apis/js-apis-appmanager.md
index 7688a46b0bec337a7cecc801e2855afd576328c6..f4ac20aea83ca20d982eef78c375949a77094f3f 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-appmanager.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-appmanager.md
@@ -210,7 +210,7 @@ getProcessRunningInfos(callback: AsyncCallback\>): vo
registerApplicationStateObserver(observer: ApplicationStateObserver): number;
-注册应用程序状态观测器。
+注册全部应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
@@ -244,6 +244,48 @@ registerApplicationStateObserver(observer: ApplicationStateObserver): number;
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
+ ```
+
+## appManager.registerApplicationStateObserver9+
+
+registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array): number;
+
+注册指定应用程序状态观测器。
+
+**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
+
+**系统API**:该接口为系统接口,三方应用不支持调用。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | -------- | -------- | -------- |
+| observer | ApplicationStateObserver | 否 | 返回观察者的数字代码。 |
+| bundleNameList | Array | 否 | 表示需要注册监听的bundleName数组。最大值128。 |
+
+**示例:**
+
+ ```js
+ var applicationStateObserver = {
+ onForegroundApplicationChanged(appStateData) {
+ console.log('------------ onForegroundApplicationChanged -----------', appStateData);
+ },
+ onAbilityStateChanged(abilityStateData) {
+ console.log('------------ onAbilityStateChanged -----------', abilityStateData);
+ },
+ onProcessCreated(processData) {
+ console.log('------------ onProcessCreated -----------', processData);
+ },
+ onProcessDied(processData) {
+ console.log('------------ onProcessDied -----------', processData);
+ }
+ }
+ var bundleNameList = ['bundleName1', 'bundleName2'];
+ const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList);
+ console.log('-------- observerCode: ---------', observerCode);
+
```
## appManager.unregisterApplicationStateObserver8+
@@ -393,7 +435,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 应用包名。 |
- | accountId | number | 是 | account的Id。 |
+ | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**示例:**
@@ -427,7 +469,7 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 应用包名。 |
- | accountId | number | 是 | account的Id。 |
+ | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 切断account进程的回调函数。 |
**示例:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md
index 2243e9fd02bd700c8e91001293027337eec10e02..f42b90abb0d58da82d213a56dff3f0a9bad5b56a 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-audio.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md
@@ -619,8 +619,8 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => {
| 名称 | 类型 | 必填 | 说明 |
| :---------------- | :------------------------------------------------ | :--- | :----------------- |
-| type | [DeviceChangeType](#DeviceChangeType) | 是 | 设备连接状态变化。 |
-| deviceDescriptors | [AudioDeviceDescriptors](#AudioDeviceDescriptors) | 是 | 设备信息。 |
+| type | [DeviceChangeType](#devicechangetype) | 是 | 设备连接状态变化。 |
+| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 设备信息。 |
## DeviceChangeType
@@ -1675,7 +1675,7 @@ on(type: 'deviceChange', callback: Callback): void
| 参数名 | 类型 | 必填 | 说明 |
| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' |
-| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | 是 | 获取设备更新详情。 |
+| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 |
**示例:**
@@ -1701,7 +1701,7 @@ off(type: 'deviceChange', callback?: Callback): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
| type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' |
-| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | 否 | 获取设备更新详情。 |
+| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 |
**示例:**
@@ -3192,7 +3192,7 @@ setInterruptMode(mode: InterruptMode): Promise<void>
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ---------------------------------- | ------ | ---------- |
-| mode | [InterruptMode](#InterruptMode) | 是 | 焦点模型。 |
+| mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。 |
**返回值:**
@@ -3238,7 +3238,7 @@ setInterruptMode(mode: InterruptMode, callback: Callback\): void
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------- | ------ | -------------- |
-|mode | [InterruptMode](#InterruptMode) | 是 | 焦点模型。|
+|mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。|
|callback | Callback\ | 是 |回调返回执行结果。|
**示例:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md b/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md
index bbf897d68d49ceea7d709c536e7bbd55600e0567..96d1d56624bb13cb4d835f0ad54399b0181874b5 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md
@@ -27,11 +27,11 @@ isSupported(feature: number): boolean
| -------- | -------- |
| boolean | true:支持该类型卡模拟, false:不支持该类型卡模拟。 |
-## HceService
+## HceService8+
管理HCE卡模拟。在调用HceService的接口前,需要先通过new cardEmulation.HceService()创建实例。
-### startHCE
+### startHCE8+
startHCE(aidList: string[]): boolean
@@ -47,7 +47,7 @@ startHCE(aidList: string[]): boolean
| ------- | -------- | ---- | ----------------------- |
| aidList | string[] | 是 | 注册进行卡模拟的aid列表 |
-### stopHCE
+### stopHCE8+
stopHCE(): boolean
@@ -57,7 +57,7 @@ stopHCE(): boolean
**系统能力:** SystemCapability.Communication.NFC.Core
-### on
+### on8+
on(type: "hceCmd", callback: AsyncCallback): void;
@@ -74,7 +74,7 @@ on(type: "hceCmd", callback: AsyncCallback): void;
| type | string | 是 | 固定填"hceCmd"字符串 |
| callback | AsyncCallback | 是 | 订阅的事件回调,入参是符合APDU协议的数据数组 |
-### sendResponse
+### sendResponse8+
sendResponse(responseApdu: number[]): void;
diff --git a/zh-cn/application-dev/reference/apis/js-apis-huks.md b/zh-cn/application-dev/reference/apis/js-apis-huks.md
index 374cad996c0a1f7549b38c8c0773f1e247f09c41..0f4c594431e26d488432f9fd63f1022d6713dcdb 100755
--- a/zh-cn/application-dev/reference/apis/js-apis-huks.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md
@@ -1318,7 +1318,7 @@ finish操作密钥接口,使用Promise方式异步返回结果。
| -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | 是 | Finish操作的handle。 |
| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 |
-| promise | Promise\<[HuksResult](#HuksResult)> | 是 | promise实例,用于获取异步返回结果。 |
+| promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 |
## huks.finish9+
diff --git a/zh-cn/application-dev/reference/apis/js-apis-image.md b/zh-cn/application-dev/reference/apis/js-apis-image.md
index 99dce4e19d6327cee1d07f73605d99f6200a5749..f4aeef3b877acfc2634927e33743d707f60a7c07 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-image.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-image.md
@@ -936,7 +936,7 @@ createImageSource(uri: string, options: SourceOptions): ImageSource
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------- | ---- | ----------------------------------- |
| uri | string | 是 | 图片路径,当前仅支持应用沙箱路径。 |
-| options | [SourceOptions](#SourceOptions) | 是 | 图片属性,包括图片序号与默认属性值。|
+| options | [SourceOptions](#sourceoptions9) | 是 | 图片属性,包括图片序号与默认属性值。|
**返回值:**
@@ -989,7 +989,7 @@ createImageSource(fd: number, options: SourceOptions): ImageSource
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------- | ---- | ----------------------------------- |
| fd | number | 是 | 文件描述符fd。 |
-| options | [SourceOptions](#SourceOptions) | 是 | 图片属性,包括图片序号与默认属性值。|
+| options | [SourceOptions](#sourceoptions9) | 是 | 图片属性,包括图片序号与默认属性值。|
**返回值:**
@@ -1037,7 +1037,7 @@ createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------------------------------- | ---- | ------------------------------------ |
| buf | ArrayBuffer | 是 | 图像缓冲区数组。 |
-| options | [SourceOptions](#SourceOptions) | 是 | 图片属性,包括图片序号与默认属性值。 |
+| options | [SourceOptions](#sourceoptions9) | 是 | 图片属性,包括图片序号与默认属性值。 |
**返回值:**
@@ -1092,7 +1092,7 @@ CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------- | ---- | ------------------------------------ |
| buf | ArrayBuffer | 是 | 增量数据。 |
-| options | [SourceOptions](#SourceOptions) | 否 | 图片属性,包括图片序号与默认属性值。 |
+| options | [SourceOptions](#sourceoptions9) | 否 | 图片属性,包括图片序号与默认属性值。 |
**返回值:**
@@ -2135,11 +2135,12 @@ img.release().then(() =>{
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
-| 名称 | 默认值 | 描述 |
-| --------- | ------ | ----------------- |
-| UNKNOWN | 0 | 未知格式。 |
-| RGB_565 | 2 | 格式为RGB_565。 |
-| RGBA_8888 | 3 | 格式为RGBA_8888。 |
+| 名称 | 默认值 | 描述 |
+| ---------------------- | ------ | ----------------- |
+| UNKNOWN | 0 | 未知格式。 |
+| RGB_565 | 2 | 格式为RGB_565 |
+| RGBA_8888 | 3 | 格式为RGBA_8888。 |
+| BGRA_88889+ | 4 | 格式为BGRA_8888。 |
## AlphaType9+
diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md
index 6093cf1ca320d2251450fcca9e02e89526a26298..a11614d149bfd2db3c3b8370aeba57ea906f880d 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md
@@ -127,7 +127,7 @@ switchInputMethod(target: InputmethodProperty): Promise<boolean>
```
## InputMethodController
-下列API示例中都需使用[getInputMethodController](#getinputmethodcontroller)回调获取到InputMethodController实例,再通过此实例调用对应方法。
+下列API示例中都需使用[getInputMethodController](#inputmethodgetinputmethodcontroller)回调获取到InputMethodController实例,再通过此实例调用对应方法。
### stopInput
@@ -175,7 +175,7 @@ stopInput(): Promise<boolean>
## InputMethodSetting8+
-下列API示例中都需使用[getInputMethodSetting](#getinputmethodsetting)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。
+下列API示例中都需使用[getInputMethodSetting](#inputmethodgetinputmethodcontroller)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。
### listInputMethod
diff --git a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md
index f3f3ba733bc56301ba22021a4fbd3edfaa1c92e2..e41944c75170b6c9d36d451a2500dcb77c7586e7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md
@@ -1,5 +1,6 @@
# 剪贴板
+ 剪贴板服务主要组件包括剪贴板管理客户端和剪贴板服务。剪贴板管理客户端负责剪贴板接口管理,提供剪贴板北向JS API给应用;在应用框架侧创建剪贴板数据、请求剪贴板SA执行剪贴板的新建、删除、查询、转换文本、配置等。剪贴板服务负责剪贴板事件管理,管理剪贴板SA的生命周期,为系统复制、粘贴功能提供支持。
>  **说明:**
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
diff --git a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md
index 38c1f1c7be9d1814ef5990dc61516e93975d04de..cadfc12098a6e85805136f8bf78d76705179f657 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md
@@ -191,7 +191,7 @@ privacyManager.getPermissionUsedRecords(request, (err, data) => {
| -------- | -------------- | ---- | ---------------------------------------- |
| beginTime | number | 否 | 查询记录的起始时间,单位:ms。 |
| endTime | number | 否 | 查询记录的终止时间,单位:ms。 |
-| bundleRecords | Array<[BundleUsedRecord](#BundleUsedRecord)> | 否 | 应用的权限使用记录集合。 |
+| bundleRecords | Array<[BundleUsedRecord](#bundleusedrecord)> | 否 | 应用的权限使用记录集合。 |
## BundleUsedRecord
@@ -205,7 +205,7 @@ privacyManager.getPermissionUsedRecords(request, (err, data) => {
| isRemote | boolean | 否 | 默认值false。 |
| deviceId | string | 否 | 目标应用所在设备的ID。 |
| bundleName | string | 否 | 目标应用的包名。 |
-| permissionRecords | Array<[PermissionUsedRecord](#PermissionUsedRecord)> | 否 | 每个应用的权限使用记录集合。 |
+| permissionRecords | Array<[PermissionUsedRecord](#permissionusedrecord)> | 否 | 每个应用的权限使用记录集合。 |
## PermissionUsedRecord
diff --git a/zh-cn/application-dev/reference/apis/js-apis-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md
index 6bed24b80575830c7ddb0d84ea4e1edcb2b856f6..b0e42ef70ce809931acd3248d1b99bb6d7b0cd6f 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-request.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-request.md
@@ -160,7 +160,7 @@ upload(context: BaseContext, config: UploadConfig): Promise<UploadTask>
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
- | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 |
+ | context | BaseContext | 是 | 基于应用程序的上下文。 |
| config | [UploadConfig](#uploadconfig) | 是 | 上传的配置信息。 |
@@ -203,7 +203,7 @@ upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<Up
| 参数名 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
- | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 |
+ | context | BaseContext | 是 | 基于应用程序的上下文。 |
| config | [UploadConfig](#uploadconfig) | 是 | 上传的配置信息。 |
| callback | AsyncCallback<[UploadTask](#uploadtask)> | 否 | 回调函数,异步返回UploadTask对象。 |
@@ -553,7 +553,7 @@ download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask&
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
- | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 |
+ | context | BaseContext | 是 | 基于应用程序的上下文。 |
| config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 |
**返回值:**
@@ -588,7 +588,7 @@ download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&l
| 参数名 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
- | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 |
+ | context | BaseContext | 是 | 基于应用程序的上下文。 |
| config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 |
| callback | AsyncCallback<[DownloadTask](#downloadtask)> | 否 | 下载接口的回调函数。 |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md
index 8588e9c796974d98ff51c0ce1278b32b15b777c2..a6730e833657cbb840b7f34d41401697c5a27acb 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md
@@ -137,7 +137,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -170,7 +170,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
@@ -207,7 +207,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**返回值:**
@@ -323,7 +323,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -357,7 +357,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**返回值:**
@@ -469,7 +469,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 |
-| accountId | number | 是 | 需要停止的accountId。 |
+| accountId | number | 是 | 需要停止的系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 |
**示例:**
@@ -503,7 +503,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 |
-| accountId | number | 是 | 需要停止的accountId。 |
+| accountId | number | 是 | 需要停止的系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**返回值:**
@@ -632,7 +632,7 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | ConnectOptions | 否 | 远端对象实例。 |
**返回值:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md
index 06786292b2191a13172f00181d9047d86ed64153..a8a2ef957fda55a51383f73127df8edb805ba0b7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md
@@ -1,5 +1,7 @@
# 壁纸
+壁纸管理服务是OpenHarmony中系统服务,是主题框架的部分组成,主要为系统提供壁纸管理服务能力,支持系统显示、设置、切换壁纸等功能。
+
>  **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg
index b12c5fb6563c7ee9d8dfa7e6af1cfe1dcfa1361c..e5af4f50ebd9bdab6af30219f30fdf948a019a52 100644
Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg differ
diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md
index ed99d0137cd965b927013eda6897a0ee0040d528..1eb4e1283c1c98c888489b5dbfa1e75ae33d488d 100644
--- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md
+++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md
@@ -53,45 +53,47 @@ CheckboxGroup( group?: string )
@Entry
@Component
struct CheckboxExample {
-
build() {
Scroll() {
Column() {
- Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){
- CheckboxGroup({group : 'checkboxGroup'})
- .selectedColor(0xed6f21)
- .onChange((itemName:CheckboxGroupResult) => {
- console.info("TextPicker::dialogResult is" + JSON.stringify(itemName))
- })
- Text('select all').fontSize(20)
- }
- Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){
- Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
- .select(true)
- .selectedColor(0x39a2db)
- .onChange((value: boolean) => {
- console.info('Checkbox1 change is' + value)
- })
- Text('Checkbox1').fontSize(20)
- }
- Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){
- Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
- .select(false)
- .selectedColor(0x39a2db)
- .onChange((value: boolean) => {
- console.info('Checkbox2 change is' + value)
- })
- Text('Checkbox2').fontSize(20)
- }
- Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){
- Checkbox({ name: 'checkbox3', group: 'checkboxGroup' })
- .select(true)
- .selectedColor(0x39a2db)
- .onChange((value: boolean) => {
- console.info('Checkbox3 change is' + value)
- })
- Text('Checkbox3').fontSize(20)
- }
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ CheckboxGroup({ group: 'checkboxGroup' })
+ .selectedColor(0xed6f21)
+ .onChange((itemName: CheckboxGroupResult) => {
+ console.info("TextPicker::dialogResult is" + JSON.stringify(itemName))
+ })
+ Text('select all').fontSize(20)
+ }
+
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
+ .select(true)
+ .selectedColor(0x39a2db)
+ .onChange((value: boolean) => {
+ console.info('Checkbox1 change is' + value)
+ })
+ Text('Checkbox1').fontSize(20)
+ }
+
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
+ .select(false)
+ .selectedColor(0x39a2db)
+ .onChange((value: boolean) => {
+ console.info('Checkbox2 change is' + value)
+ })
+ Text('Checkbox2').fontSize(20)
+ }
+
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ Checkbox({ name: 'checkbox3', group: 'checkboxGroup' })
+ .select(true)
+ .selectedColor(0x39a2db)
+ .onChange((value: boolean) => {
+ console.info('Checkbox3 change is' + value)
+ })
+ Text('Checkbox3').fontSize(20)
+ }
}
}
}
diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md
index 290c065e01ab19dda9b62fda3739171d764f6d86..b7b0543679eab4ca33d6d88e88f3ab3144f977d0 100644
--- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md
+++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md
@@ -53,16 +53,16 @@ Select(options: Array\)
struct SelectExample {
build() {
Column() {
- Select([{value:'aaa',icon: "/common/1.png"},
- {value:'bbb',icon: "/common/2.png"},
- {value:'ccc',icon: "/common/3.png"},
- {value:'ddd',icon: "/common/4.png"}])
+ Select([{ value: 'aaa', icon: "/common/1.png" },
+ { value: 'bbb', icon: "/common/2.png" },
+ { value: 'ccc', icon: "/common/3.png" },
+ { value: 'ddd', icon: "/common/4.png" }])
.selected(2)
.value('TTT')
- .font({size: 30, weight:400, family: 'serif', style: FontStyle.Normal })
- .selectedOptionFont({size: 40, weight: 500, family: 'serif', style: FontStyle.Normal })
- .optionFont({size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
- .onSelect((index:number)=>{
+ .font({ size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
+ .selectedOptionFont({ size: 40, weight: 500, family: 'serif', style: FontStyle.Normal })
+ .optionFont({ size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
+ .onSelect((index: number) => {
console.info("Select:" + index)
})
}
diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md
index 36959733612a951be41c2149c7ceca7e4c9a4a8e..8bb8b3941407b4d87c412161d1b0453a75865348 100644
--- a/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md
+++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md
@@ -4,7 +4,7 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
-可滑动面板。提供一种轻量的内容展示的窗口,可方便的在不同尺寸中切换,属于弹出式组件。
+可滑动面板,提供一种轻量的内容展示窗口,方便在不同尺寸中切换。
## 权限列表
@@ -37,6 +37,7 @@ Panel(value:{show:boolean})
| fullHeight | Length | - | 指定PanelMode.Full状态下的高度。 |
| halfHeight | Length | - | 指定PanelMode.Half状态下的高度,默认为屏幕尺寸的一半。 |
| miniHeight | Length | - | 指定PanelMode.Mini状态下的高度。 |
+| backgroundMask9+|(color: ResourceColor)| - |指定Panel的背景蒙层。|
- PanelType枚举说明
| 名称 | 描述 |
@@ -58,7 +59,7 @@ Panel(value:{show:boolean})
| 名称 | 功能描述 |
| -------- | -------- |
| onChange(callback: (width: number, height: number, mode: PanelMode) => void) | 当可滑动面板发生状态变化时触发, 返回的height值为内容区高度值,当dragbar属性为true时,panel本身的高度值为dragbar高度加上内容区高度。 |
-
+| onHeightChange(callback: (value: number) => void)9+ |当可滑动面板发生高度变化时触发,返回的height值为内容区高度值,当dragbar属性为true时,panel本身的高度值为dragbar高度加上内容区高度。因用户体验设计原因,panel最高只能滑到 fullHeight-8vp |
## 示例
@@ -70,7 +71,7 @@ struct PanelExample {
@State show: boolean = false
build() {
- Column() {
+ Stack() {
Text('2021-09-30 Today Calendar: 1.afternoon......Click for details')
.width('90%').height(50).borderRadius(10)
.backgroundColor(0xFFFFFF).padding({ left: 20 })
diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md
index df2ace39644d48184188f66496ca8e03e40b48ed..4fa205a6d17c448a23c7036382a17dba00f84a21 100644
--- a/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md
+++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md
@@ -21,7 +21,7 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number | stri
| 参数 | 参数名 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
- | refreshing | boolean | 是 | - | 当前组件是否正在刷新。 |
+ | refreshing | boolean | 是 | - | 当前组件是否正在刷新。
该参数支持[$$](../../ui/ts-syntactic-sugar.md)双向绑定变量。 |
| offset | Length | 否 | 16 | 刷新组件静止时距离父组件顶部的距离。|
| friction | number \| string | 否 | 62 | 下拉摩擦系数,取值范围为0到100。
- 0表示下拉刷新容器不跟随手势下拉而下拉。
- 100表示下拉刷新容器紧紧跟随手势下拉而下拉。
- 数值越大,下拉刷新容器跟随手势下拉的反应越灵敏。 |
@@ -58,7 +58,7 @@ struct RefreshExample {
build() {
Column() {
- Refresh({refreshing: this.isRefreshing, offset: 120, friction: 100}) {
+ Refresh({refreshing: $$this.isRefreshing, offset: 120, friction: 100}) {
Text('Pull Down and refresh: ' + this.counter)
.fontSize(30)
.margin(10)
diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md
index 6217c50da6b0fd7d2eec01b7d3b98a59b372ebf9..7bcd121930a08b8e892d31cda640625c455117c4 100644
--- a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md
+++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md
@@ -43,6 +43,7 @@ SideBarContainer( type?: SideBarContainerType )
| minSideBarWidth | number \| [Length9+](../../ui/ts-types.md#长度类型) | 200 | 设置侧边栏最小宽度。 |
| maxSideBarWidth | number \| [Length9+](../../ui/ts-types.md#长度类型) | 280 | 设置侧边栏最大宽度。 |
| autoHide9+ | boolean | true | 设置当侧边栏拖拽到小于最小宽度后,是否自动隐藏。 |
+| sideBarPosition9+ | SideBarPosition | SideBarPosition.Start | 设置侧边栏显示位置。 |
- ButtonStyle对象说明
| 名称 | 参数类型 | 必填 | 默认值 | 描述 |
@@ -53,6 +54,11 @@ SideBarContainer( type?: SideBarContainerType )
| height | number | 否 | 32 | 设置侧边栏控制按钮的高度。 |
| icons | {
shown: string \| PixelMap \| [Resource](../../ui/ts-types.md) ,
hidden: string \| PixelMap \| [Resource](../../ui/ts-types.md) ,
switching?: string \| PixelMap \| [Resource](../../ui/ts-types.md)
} | 否 | - | 设置侧边栏控制按钮的图标:
- shown: 设置侧边栏显示时控制按钮的图标。
- hidden: 设置侧边栏隐藏时控制按钮的图标。
- switching:设置侧边栏显示和隐藏状态切换时控制按钮的图标。 |
+- SideBarPosition9+枚举说明
+ | 名称 | 描述 |
+ | -------- | -------- |
+ | Start | 侧边栏位于容器左侧。 |
+ | End | 侧边栏位于容器右侧。 |
diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md
index 57e660947ef0d81e680f46434190181e91da34ae..4232e4edc4edef65815bfc289f63d6f81ff98b0d 100644
--- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md
+++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md
@@ -24,16 +24,16 @@
| borderStyle | BorderStyle | BorderStyle.Solid | 设置元素的边框样式。 |
| borderWidth | Length | 0 | 设置元素的边框宽度。 |
| borderColor | [ResourceColor](../../ui/ts-types.md) | - | 设置元素的边框颜色。 |
-| borderRadius | Length | 0 | 设置元素的边框圆角半径。 |
+| borderRadius | Length \| BorderRadiuses9+ | 0 | 设置元素的边框圆角半径。 |
- BorderOptions属性说明
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 |
| -------- | ------------------------------------------------------------ | ----------------- | ---- | ---------- |
- | width | [Length](../../ui/ts-types.md#长度类型)\|EdgeWidth9+ | 0 | 否 | 边框宽度。 |
- | color | [ResourceColor](../../ui/ts-types.md)\|EdgeColor9+ | 'Black' | 否 | 边框颜色。 |
- | radius | [Length](../../ui/ts-types.md#长度类型)\| EdgeRadiuses9+ | 0 | 否 | 边框角度。 |
- | style | BorderStyle\|EdgeStyle9+ | BorderStyle.Solid | 否 | 边框样式。 |
+ | width | [Length](../../ui/ts-types.md#长度类型) \| EdgeWidth9+ | 0 | 否 | 边框宽度。 |
+ | color | [ResourceColor](../../ui/ts-types.md) \| EdgeColor9+ | 'Black' | 否 | 边框颜色。 |
+ | radius | [Length](../../ui/ts-types.md#长度类型) \| BorderRadiuses9+ | 0 | 否 | 边框角度。 |
+ | style | BorderStyle \| EdgeStyle9+ | BorderStyle.Solid | 否 | 边框样式。 |
- EdgeWidth9+对象说明
@@ -58,7 +58,7 @@
| top | [ResourceColor](../../ui/ts-types.md) | 否 | 'Black' | 上侧边框颜色。 |
| bottom | [ResourceColor](../../ui/ts-types.md) | 否 | 'Black' | 下侧边框颜色。 |
-- EdgeRadiuses9+对象说明
+- BorderRadiuses9+对象说明
引用该对象时,至少传入一个参数。
diff --git a/zh-cn/application-dev/ui/ts-syntactic-sugar.md b/zh-cn/application-dev/ui/ts-syntactic-sugar.md
index 0ce4cad3b5efa6ba2184a88f79649eeda9a133ac..5b824e089fdeec1e38552e7737abff9d9d7b954c 100644
--- a/zh-cn/application-dev/ui/ts-syntactic-sugar.md
+++ b/zh-cn/application-dev/ui/ts-syntactic-sugar.md
@@ -137,11 +137,11 @@ build() {
```
-## $
+## 变量双向绑定
$$支持变量双向绑定,支持简单变量、@State、@Link、@Prop等类型。
-当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,以及Radio组件的checked属性。
+当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,以及Radio组件的checked属性和Refresh组件的refreshing参数。
```ts
diff --git a/zh-cn/device-dev/driver/Readme-CN.md b/zh-cn/device-dev/driver/Readme-CN.md
index 3ee6c11799a477f3f9b9178545d23d518ba9c006..4118cdf0596261ee5c53161a6855cc7eecbfb544 100755
--- a/zh-cn/device-dev/driver/Readme-CN.md
+++ b/zh-cn/device-dev/driver/Readme-CN.md
@@ -46,6 +46,7 @@
- [Audio](driver-peripherals-audio-des.md)
- [Camera](driver-peripherals-camera-des.md)
- [Face_auth](driver-peripherals-face_auth-des.md)
+ - [Fingerprint_auth](driver-peripherals-fingerprint_auth-des.md)
- [LCD](driver-peripherals-lcd-des.md)
- [Light](driver-peripherals-light-des.md)
- [Pin_auth](driver-peripherals-pinauth-des.md)
diff --git a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md
index 4ae5304c6e6ad49648d23e5b7834770faa2fc326..04dfe33a0f2735bd355b6dea4b3c24da14410310 100644
--- a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md
+++ b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md
@@ -319,7 +319,7 @@ static struct PanelInfo g_panelInfo = {
.vsw = VERTICAL_SYNC_WIDTH, /* vertical sync width */
.frameRate = FRAME_RATE, /* frame rate */
.intfType = MIPI_DSI, /* panel interface type */
- .intfSync = OUTPUT_USER, /* output timming type */
+ .intfSync = OUTPUT_USER, /* output timing type */
/* mipi config info */
.mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT },
/* backlight config info */
diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md
index 4f32b8e9e9822ea707a23a10f9e378c5f9b97e69..fdeb7b452e6580d5db0f55d9959528bacc4e740a 100755
--- a/zh-cn/device-dev/kernel/Readme-CN.md
+++ b/zh-cn/device-dev/kernel/Readme-CN.md
@@ -6,10 +6,7 @@
- 基础内核
- [中断管理](kernel-mini-basic-interrupt.md)
- [任务管理](kernel-mini-basic-task.md)
- - 内存管理
- - [基本概念](kernel-mini-basic-memory-basic.md)
- - [静态内存](kernel-mini-basic-memory-static.md)
- - [动态内存](kernel-mini-basic-memory-dynamic.md)
+ - [内存管理](kernel-mini-basic-memory.md)
- 内核通信机制
- [事件](kernel-mini-basic-ipc-event.md)
- [互斥锁](kernel-mini-basic-ipc-mutex.md)
@@ -21,23 +18,16 @@
- [C++支持](kernel-mini-extend-support.md)
- [CPU占用率](kernel-mini-extend-cpup.md)
- [动态加载](kernel-mini-extend-dynamic-loading.md)
- - 文件系统
- - [FAT](kernel-mini-extend-file-fat.md)
- - [LittleFS](kernel-mini-extend-file-lit.md)
+ - [文件系统](kernel-mini-extend-file.md)
- 内核调测
- - 内存调测
- - [内存信息统计](kernel-mini-memory-debug-mes.md)
- - [内存泄漏检测](kernel-mini-memory-debug-det.md)
- - [踩内存检测](kernel-mini-memory-debug-cet.md)
+ - [内存调测](kernel-mini-memory-debug.md)
- [异常调测](kernel-mini-memory-exception.md)
- [Trace调测](kernel-mini-memory-trace.md)
- [LMS调测](kernel-mini-memory-lms.md)
- 附录
- [内核编码规范](kernel-mini-appx-code.md)
- [双向链表](kernel-mini-appx-data-list.md)
- - 标准库支持
- - [CMSIS支持](kernel-mini-appx-lib-cmsis.md)
- - [POSIX支持](kernel-mini-appx-lib-posix.md)
+ - [标准库支持](kernel-mini-appx-lib.md)
- 小型系统内核
- [内核概述](kernel-small-overview.md)
- 内核启动
@@ -71,13 +61,9 @@
- [虚拟动态共享库](kernel-small-bundles-share.md)
- [轻量级进程间通信](kernel-small-bundles-ipc.md)
- 文件系统
+ - [文件系统概述](kernel-small-bundles-fs.md)
- [虚拟文件系统](kernel-small-bundles-fs-virtual.md)
- - 支持的文件系统
- - [FAT](kernel-small-bundles-fs-support-fat.md)
- - [JFFS2](kernel-small-bundles-fs-support-jffs2.md)
- - [NFS](kernel-small-bundles-fs-support-nfs.md)
- - [Ramfs](kernel-small-bundles-fs-support-ramfs.md)
- - [Procfs](kernel-small-bundles-fs-support-procfs.md)
+ - [支持的文件系统](kernel-small-bundles-fs-support.md)
- [适配新的文件系统](kernel-small-bundles-fs-new.md)
- 调测与工具
- Shell
@@ -155,15 +141,7 @@
- [内存信息统计](kernel-small-debug-memory-info.md)
- [内存泄漏检测](kernel-small-debug-memory-leak.md)
- [踩内存检测](kernel-small-debug-memory-corrupt.md)
- - 用户态内存调测
- - [基本概念](kernel-small-debug-user-concept.md)
- - [运行机制](kernel-small-debug-user-function.md)
- - 使用指导
- - [接口说明](kernel-small-debug-user-guide-api.md)
- - [使用说明](kernel-small-debug-user-guide-use.md)
- - [接口调用方式](kernel-small-debug-user-guide-use-api.md)
- - [命令行参数方式](kernel-small-debug-user-guide-use-cli.md)
- - [常见问题](kernel-small-debug-user-faqs.md)
+ - [用户态内存调测](kernel-small-debug-user.md)
- 其他内核调测手段
- [临终遗言](kernel-small-debug-trace-other-lastwords.md)
- [常见问题](kernel-small-debug-trace-other-faqs.md)
diff --git a/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md b/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md
index 8ce3db5c735a90579bb5693248740808c0664419..d2f4b54be58063e23b8f7fc145e96c555b4e27ca 100644
--- a/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md
+++ b/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md
@@ -1,7 +1,500 @@
# 标准库支持
+## CMSIS支持
-- **[CMSIS支持](kernel-mini-appx-lib-cmsis.md)**
-- **[POSIX支持](kernel-mini-appx-lib-posix.md)**
\ No newline at end of file
+### 基本概念
+
+[CMSIS](https://developer.arm.com/tools-and-software/embedded/cmsis)是Cortex Microcontroller Software Interface Standard(Cortex微控制器软件接口标准)的缩写,是对于那些基于ARM Cortex处理器的微控制器独立于供应商的硬件抽象层。它包含多个组件层,其中之一是RTOS层,该层定义了一套通用及标准化的RTOS API接口,减少了应用开发者对特定RTOS的依赖,方便用户软件的移植重用。该套API有2个版本,分别为版本1(CMSIS-RTOS v1)和版本2(CMSIS-RTOS v2),OpenHarmony LiteOS-M仅提供其版本2的实现。
+
+
+### 开发指导
+
+
+#### 接口说明
+
+CMSIS-RTOS v2提供下面几种功能,接口详细信息可以查看API参考。
+
+ **表1** 内核信息与控制
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osKernelGetInfo | 获取RTOS内核信息。 |
+| osKernelGetState | 获取当前的RTOS内核状态。 |
+| osKernelGetSysTimerCount | 获取RTOS内核系统计时器计数。 |
+| osKernelGetSysTimerFreq | 获取RTOS内核系统计时器频率。 |
+| osKernelInitialize | 初始化RTOS内核。 |
+| osKernelLock | 锁定RTOS内核调度程序。 |
+| osKernelUnlock | 解锁RTOS内核调度程序。 |
+| osKernelRestoreLock | 恢复RTOS内核调度程序锁定状态。 |
+| osKernelResume | 恢复RTOS内核调度程序。(暂未实现) |
+| osKernelStart | 启动RTOS内核调度程序。 |
+| osKernelSuspend | 挂起RTOS内核调度程序。(暂未实现) |
+| osKernelGetTickCount | 获取RTOS内核滴答计数。 |
+| osKernelGetTickFreq | 获取RTOS内核滴答频率。 |
+
+ **表2** 线程管理
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osThreadDetach | 分离线程(线程终止时可以回收线程存储)。(暂未实现) |
+| osThreadEnumerate | 枚举活动线程。(暂未实现) |
+| osThreadExit | 终止当前正在运行的线程的执行。 |
+| osThreadGetCount | 获取活动线程的数量。 |
+| osThreadGetId | 返回当前正在运行的线程的线程ID。 |
+| osThreadGetName | 获取线程的名称。 |
+| osThreadGetPriority | 获取线程的当前优先级。 |
+| osThreadGetStackSize | 获取线程的堆栈大小。 |
+| osThreadGetStackSpace | 根据执行期间的堆栈水印记录获取线程的可用堆栈空间。 |
+| osThreadGetState | 获取线程的当前线程状态。 |
+| osThreadJoin | 等待指定线程终止。(暂未实现) |
+| osThreadNew | 创建一个线程并将其添加到活动线程中。 |
+| osThreadResume | 恢复线程的执行。 |
+| osThreadSetPriority | 更改线程的优先级。 |
+| osThreadSuspend | 暂停执行线程。 |
+| osThreadTerminate | 终止线程的执行。 |
+| osThreadYield | 将控制权传递给处于就绪状态的下一个线程。 |
+
+ **表3** 线程标志
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osThreadFlagsSet | 设置线程的指定线程标志。(暂未实现) |
+| osThreadFlagsClear | 清除当前正在运行的线程的指定线程标志。(暂未实现) |
+| osThreadFlagsGet | 获取当前正在运行的线程的当前线程标志。(暂未实现) |
+| osThreadFlagsWait | 等待当前正在运行的线程的一个或多个线程标志发出信号。(暂未实现) |
+
+ **表4** 事件标志
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osEventFlagsGetName | 获取事件标志对象的名称。(暂未实现) |
+| osEventFlagsNew | 创建并初始化事件标志对象。 |
+| osEventFlagsDelete | 删除事件标志对象。 |
+| osEventFlagsSet | 设置指定的事件标志。 |
+| osEventFlagsClear | 清除指定的事件标志。 |
+| osEventFlagsGet | 获取当前事件标志。 |
+| osEventFlagsWait | 等待一个或多个事件标志被发出信号。 |
+
+ **表5** 通用等待函数
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osDelay | 等待超时(时间延迟)。 |
+| osDelayUntil | 等到指定时间。 |
+
+ **表6** 计时器管理
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osTimerDelete | 删除计时器。 |
+| osTimerGetName | 获取计时器的名称。(暂未实现) |
+| osTimerIsRunning | 检查计时器是否正在运行。 |
+| osTimerNew | 创建和初始化计时器。 |
+| osTimerStart | 启动或重新启动计时器。 |
+| osTimerStop | 停止计时器。 |
+
+ **表7** 互斥管理
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osMutexAcquire | 获取互斥或超时(如果已锁定)。 |
+| osMutexDelete | 删除互斥对象。 |
+| osMutexGetName | 获取互斥对象的名称。(暂未实现) |
+| osMutexGetOwner | 获取拥有互斥对象的线程。 |
+| osMutexNew | 创建并初始化Mutex对象。 |
+| osMutexRelease | 释放由osMutexAcquire获取的Mutex。 |
+
+ **表8** 信号量
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osSemaphoreAcquire | 获取信号量令牌或超时(如果没有可用的令牌)。 |
+| osSemaphoreDelete | 删除一个信号量对象。 |
+| osSemaphoreGetCount | 获取当前信号量令牌计数。 |
+| osSemaphoreGetName | 获取信号量对象的名称。(暂未实现) |
+| osSemaphoreNew | 创建并初始化一个信号量对象。 |
+| osSemaphoreRelease | 释放信号量令牌,直到初始最大计数。 |
+
+ **表9** 内存池
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osMemoryPoolAlloc | 从内存池分配一个内存块。 |
+| osMemoryPoolDelete | 删除内存池对象。 |
+| osMemoryPoolFree | 将分配的内存块返回到内存池。 |
+| osMemoryPoolGetBlockSize | 获取内存池中的内存块大小。 |
+| osMemoryPoolGetCapacity | 获取内存池中最大的内存块数。 |
+| osMemoryPoolGetCount | 获取内存池中使用的内存块数。 |
+| osMemoryPoolGetName | 获取内存池对象的名称。 |
+| osMemoryPoolGetSpace | 获取内存池中可用的内存块数。 |
+| osMemoryPoolNew | 创建并初始化一个内存池对象。 |
+
+ **表10** 消息队列
+
+| 接口名 | 接口描述 |
+| -------- | -------- |
+| osMessageQueueDelete | 删除消息队列对象。 |
+| osMessageQueueGet | 从队列获取消息,或者如果队列为空,则从超时获取消息。 |
+| osMessageQueueGetCapacity | 获取消息队列中的最大消息数。 |
+| osMessageQueueGetCount | 获取消息队列中排队的消息数。 |
+| osMessageQueueGetMsgSize | 获取内存池中的最大消息大小。 |
+| osMessageQueueGetName | 获取消息队列对象的名称。(暂未实现) |
+| osMessageQueueGetSpace | 获取消息队列中消息的可用插槽数。 |
+| osMessageQueueNew | 创建和初始化消息队列对象。 |
+| osMessageQueuePut | 如果队列已满,则将消息放入队列或超时。 |
+| osMessageQueueReset | 将消息队列重置为初始空状态。(暂未实现) |
+
+
+#### 开发流程
+
+CMSIS-RTOS2组件可以作为库或源代码提供(下图显示了库)。通过添加CMSIS-RTOS2组件(通常是一些配置文件),可以将基于CMSIS的应用程序扩展为具有RTOS功能。只需包含cmsis_os2.h头文件就可以访问RTOS API函数,这使用户应用程序能够处理RTOS内核相关事件,而在更换内核时无需重新编译源代码。
+
+静态对象分配需要访问RTOS对象控制块定义。特定于实现的头文件(下图中的os_xx .h)提供对此类控制块定义的访问。对于OpenHarmony LiteOS-M内核,由文件名以los_开头的头文件提供,这些文件包含OpenHarmony LiteOS-M内核的这些定义。
+
+
+
+
+#### 编程实例
+
+
+```
+#include ...
+#include "cmsis_os2.h"
+
+/*----------------------------------------------------------------------------
+ * 应用程序主线程
+ *---------------------------------------------------------------------------*/
+void app_main (void *argument) {
+ // ...
+ for (;;) {}
+}
+
+int main (void) {
+ // 系统初始化
+ MySystemInit();
+ // ...
+
+ osKernelInitialize(); // 初始化CMSIS-RTOS
+ osThreadNew(app_main, NULL, NULL); // 创建应用程序主线程
+ osKernelStart(); // 开始执行线程
+ for (;;) {}
+}
+```
+
+## POSIX支持
+
+
+### 基本概念
+
+OpenHarmony内核使用**musl libc**库以及自研接口,支持部分标准POSIX接口,开发者可基于POSIX标准接口开发内核之上的组件及应用。
+
+
+### 开发指导
+
+
+#### 接口说明
+
+ **表1** process
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <stdlib.h> | void abort(void); | 中止线程执行 |
+| \#include <assert.h> | void assert(scalar expression); | 断言为假终止线程 |
+| \#include <pthread.h> | int pthread_cond_destroy(pthread_cond_t \*cond); | 销毁条件变量 |
+| \#include <pthread.h> | int pthread_cond_init(pthread_cond_t \*restrict co
nd, const pthread_condattr_t \*restrict attr); | 初始化条件变量 |
+| \#include <pthread.h> | int pthread_cond_timedwait(pthread_cond_t \*restr
ict cond, pthread_mutex_t \*restrict mutex, const st
ruct timespec \*restrict abstime); | 等待条件 |
+| \#include <pthread.h> | int pthread_condattr_init(pthread_condattr_t \*attr); | 初始化条件变量属性对象 |
+| \#include <pthread.h> | int pthread_mutex_unlock(pthread_mutex_t \*mutex); | 解锁互斥锁 |
+| \#include <pthread.h> | int pthread_create(pthread_t \*thread, const pthread_
attr_t \*attr, void \*(\*start_routine)(void \*), void \*arg); | 创建一个新的线程 |
+| \#include <pthread.h> | int pthread_join(pthread_t thread, void \*\*retval); | 等待指定的线程结束 |
+| \#include <pthread.h> | pthread_t pthread_self(void); | 获取当前线程的ID |
+| \#include <pthread.h> | int pthread_getschedparam(pthread_t thread, int \*
policy, struct sched_param \*param); | 获取线程的调度策略和参数 |
+| \#include <pthread.h> | int pthread_setschedparam(pthread_t thread, int
policy, const struct sched_param \*param); | 设置线程的调度策略和参数 |
+| \#include <pthread.h> | int pthread_mutex_init(pthread_mutex_t \*__restrict m
, const pthread_mutexattr_t \*__restrict a); | 初始化互斥锁 |
+| \#include <pthread.h> | int pthread_mutex_lock(pthread_mutex_t \*m); | 互斥锁加锁操作 |
+| \#include <pthread.h> | int pthread_mutex_trylock(pthread_mutex_t \*m); | 互斥锁尝试加锁操作 |
+| \#include <pthread.h> | int pthread_mutex_destroy(pthread_mutex_t \*m); | 销毁互斥锁 |
+| \#include <pthread.h> | int pthread_attr_init(pthread_attr_t \*attr); | 初始化线程属性对象 |
+| \#include <pthread.h> | int pthread_attr_destroy(pthread_attr_t \*attr); | 销毁线程属性对象 |
+| \#include <pthread.h> | int pthread_attr_getstacksize(const pthread_attr
_t \*attr, size_t \*stacksize); | 获取线程属性对象的堆栈大小 |
+| \#include <pthread.h> | int pthread_attr_setstacksize(pthread_attr_t \*attr
, size_t stacksize); | 设置线程属性对象的堆栈大小 |
+| \#include <pthread.h> | int pthread_attr_getschedparam(const pthread_
attr_t \*attr, struct sched_param \*param); | 获取线程属性对象的调度参数属性 |
+| \#include <pthread.h> | int pthread_attr_setschedparam(pthread_attr_t \*
attr, const struct sched_param \*param); | 设置线程属性对象的调度参数属性 |
+| \#include <pthread.h> | int pthread_getname_np(pthread_t pthread, char
\*name, size_t len); | 获取线程名称 |
+| \#include <pthread.h> | int pthread_setname_np(pthread_t pthread, const
char \*name); | 设置线程名称 |
+| \#include <pthread.h> | int pthread_cond_broadcast(pthread_cond_t \*c); | 解除若干已被等待条件阻塞的线程 |
+| \#include <pthread.h> | int pthread_cond_signal(pthread_cond_t \*c); | 解除被阻塞的线程 |
+| \#include <pthread.h> | int pthread_cond_wait(pthread_cond_t \*__restrict
c, pthread_mutex_t \*__restrict m); | 等待条件 |
+
+ **表2** fs
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <libgen.h> | char \*dirname(char \*path); | 获取目录名 |
+| \#include <dirent.h> | struct dirent \*readdir(DIR \*dirp); | 读目录 |
+| \#include <sys/stat.h> | int stat(const char \*restrict path, struct stat \*restrict buf); | 获取文件信息 |
+| \#include <unistd.h> | int unlink(const char \*pathname); | 删除文件 |
+| \#include <fcntl.h | int open(const char \*path, int oflags, ...); | 用于打开文件,如文件不存在,创建文件并打开 |
+| \#include <nistd.h> | int close(int fd); | 关闭文件 |
+| \#include <stdio.h> | int rename(const char \*oldpath, const char \*newpath); | 重命名指定的文件 |
+| \#include <dirent.h> | DIR \*opendir(const char \*dirname); | 打开指定目录 |
+| \#include <dirent.h> | int closedir(DIR \*dir); | 关闭指定目录 |
+| \#include <sys/mount.h> | int mount(const char \*source, const char \*target, con
st char \*filesystemtype, unsigned long mountflags, c
onst void \*data); | 挂载文件系统 |
+| \#include <sys/mount.h> | int umount(const char \*target); | 卸载文件系统 |
+| \#include <sys/mount.h> | int umount2(const char \*target, int flag); | 卸载文件系统 |
+| \#include <sys/stat.h> | int fsync(int fd); | 将与指定文件描述符关联的文件同步到存储设备 |
+| \#include <sys/stat.h> | int mkdir(const char \*pathname, mode_t mode); | 创建目录 |
+| \#include <unistd.h> | int rmdir(const char \*path); | 删除目录 |
+| \#include <sys/stat.h> | int fstat(int fd, struct stat \*buf); | 获取文件状态信息 |
+| \#include <sys/statfs.h> | int statfs(const char \*path, struct statfs \*buf); | 获取指定路径下文件的文件系统信息 |
+
+ **表3** time
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <sys/time.h> | int gettimeofday(struct timeval \*tv, struct timezone \*tz); | 获取时间。当前暂无时区概念,tz返回为空 |
+| \#include <time.h> | struct tm \*gmtime(const time_t \*timep); | 将日期和时间转换为细分时间或ASCII |
+| \#include <time.h> | struct tm \*localtime(const time_t \*timep); | 获取时间 |
+| \#include <time.h> | struct tm \*localtime_r(const time_t \*timep, struct tm \*result); | 获取时间 |
+| \#include <time.h> | time_t mktime(struct tm \*tm); | 将日期和时间转换为细分时间或ASCII |
+| \#include <time.h> | size_t strftime(char \*s, size_t max, const char \*
format,const struct tm \*tm); | 格式化日期和时间字符串 |
+| \#include <time.h> | time_t time(time_t \*tloc); | 获得日历时间 |
+| \#include <sys/times.h> | clock_t times(struct tms \*buf); | 获取线程时间 |
+| \#include <unistd.h> | int usleep(useconds_t usec); | 休眠(微秒单位) |
+| \#include <time.h> | int nanosleep(const struct timespec \*tspec1, struct
timespec \*tspec2); | 暂停当前线程直到指定的时间到达 |
+| \#include <time.h> | int clock_gettime(clockid_t id, struct timespec \*tspec); | 获取时钟的时间 |
+| \#include <time.h> | int timer_create(clockid_t id, struct sigevent \*__
restrict evp, timer_t \*__restrict t); | 为线程创建计时器 |
+| \#include <time.h> | int timer_delete(timer_t t); | 为线程删除计时器 |
+| \#include <time.h> | int timer_settime(timer_t t, int flags, const struct
itimerspec \*__restrict val, struct itimerspec \*__restrict old); | 为线程设置计时器 |
+| \#include <time.h> | time_t time (time_t \*t); | 获取时间 |
+| \#include <time.h> | char \*strptime(const char \*s, const char \*format, struct tm \*tm); | 将时间的字符串表示形式转换为时间tm结构 |
+
+ **表4** util
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <stdlib.h> | int atoi(const char \*nptr); | 字符串转换整型(int) |
+| \#include <stdlib.h> | long atol(const char \*nptr); | 字符串转换整型(long) |
+| \#include <stdlib.h> | long long atoll(const char \*nptr); | 字符串转换整型(long long) |
+| \#include <ctype.h> | int isalnum(int c); | 检查字母数字字符 |
+| \#include <ctype.h> | int isascii(int c); | 检查ASCII |
+| \#include <ctype.h> | int isdigit(int c); | 检查数字字符 |
+| \#include <ctype.h> | int islower(int c); | 检查小写字符 |
+| \#include <ctype.h> | int isprint(int c); | 检查任何可打印字符,包括空格 |
+| \#include <ctype.h> | int isspace(int c); | 检查空格字符 |
+| \#include <ctype.h> | int isupper(int c); | 检查所传的字符是否是大写字母 |
+| \#include <ctype.h> | int isxdigit(int c); | 判断字符是否为十六进制数 |
+| \#include <stdlib.h> | long int random (void); | 生成伪随机数 |
+| \#include <stdlib.h> | void srandom(unsigned int seed); | 初始化随机数生成器 |
+| \#include <ctype.h> | int tolower(int c); | 字母转换成小写 |
+| \#include <ctype.h> | int toupper(int c); | 字母转换成大写 |
+| \#include <stdarg.h> | type va_arg(va_list ap, type); | 获取可变参数的当前参数,返回指定类型并将指针指向下一参数 |
+| \#include <stdarg.h> | void va_copy(va_list dest, va_list src); | 复制参数 |
+| \#include <stdarg.h> | void va_end(va_list ap); | 清空va_list可变参数列表 |
+| \#include <stdarg.h> | void va_start(va_list ap, last); | 定义变长参数列表的起始位置 |
+| \#include <string.h> | char \*strchr(const char \*s, int c); | 在字符串中定位字符 |
+| \#include <string.h> | int strcmp(const char \*s1, const char \*s2); | 比较字符串 |
+| \#include <string.h> | size_t strcspn(const char \*s, const char \*reject); | 获取前缀子串的长度 |
+| \#include <string.h> | char \*strdup(const char \*s); | 字符串拷贝到新建的位置处 |
+| \#include <string.h> | size_t strlen(const char \*s); | 计算字符串长度 |
+| \#include <strings.h> | int strncasecmp(const char \*s1, const char \*s2, size_t n); | 比较固定长度字符串(忽略大小写) |
+| \#include <strings.h> | int strcasecmp(const char \*s1, const char \*s2); | 比较字符串(忽略大小写) |
+| \#include <string.h> | int strncmp(const char \*s1, const char \*s2, size_t n); | 比较字符串(指定长度) |
+| \#include <string.h> | char \*strrchr(const char \*s, int c); | 在字符串中定位字符 |
+| \#include <string.h> | char \*strstr(const char \*haystack, const char \*needle); | 寻找指定的子串 |
+| \#include <stdlib.h> | long int strtol(const char \*nptr, char \*\*endptr, int base); | 将字符串转换为long型整数 |
+| \#include <stdlib.h> | unsigned long int strtoul(const char \*nptr, char
\*\*endptr, int base); | 将字符串转换为unsigned long型整数 |
+| \#include <stdlib.h> | unsigned long long int strtoull(const char \*nptr,
char \*\*endptr,int base); | 将字符串转换为unsigned long long型整数 |
+| \#include <regex.h> | int regcomp(regex_t \*preg, const char \*regex,
int cflags); | 编译正则表达式 |
+| \#include <regex.h> | int regexec(const regex_t \*preg, const char \*
string, size_t nmatch,regmatch_t pmatch[], int eflags); | 匹配正则表达式 |
+| \#include <regex.h> | void regfree(regex_t \*preg); | 释放正则表达式 |
+| \#include <string.h> | char \*strerror(int errnum); | 返回描述错误号的字符串 |
+
+ **表5** math
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <stdlib.h> | int abs(int i); | 取绝对值 |
+| \#include <math.h> | double log(double x); | 自然对数函数 |
+| \#include <math.h> | double pow(double x, double y); | 求x的指数y次幂 |
+| \#include <math.h> | double round(double x); | 从零开始,舍入到最接近的整数 |
+| \#include <math.h> | double sqrt(double x); | 平方根 |
+
+ **表6** IO
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <stdio.h> | void clearerr(FILE \*stream); | 清除流的文件结尾和错误指示 |
+| \#include <stdio.h> | int fclose(FILE \*stream); | 关闭文件流 |
+| \#include <stdio.h> | FILE \*fdopen(int fd, const char \*mode); | 通过文件描述符打开文件流 |
+| \#include <stdio.h> | int feof(FILE \*stream); | 检测返回文件末尾指示位 |
+| \#include <stdio.h> | int fflush(FILE \*stream); | 刷新流 |
+| \#include <stdio.h> | char \*fgets(char \*s, int size, FILE \*stream); | 读取流的下一行 |
+| \#include <stdio.h> | int fileno(FILE \*stream); | 返回流的文件描述符 |
+| \#include <stdio.h> | FILE \*fopen(const char \*path, const char \*mode); | 打开流 |
+| \#include <stdio.h> | int fputs(const char \*s, FILE \*stream); | 向指定流写入一行 |
+| \#include <stdio.h> | size_t fread(void \*ptr, size_t size, size_t nmemb,
FILE \*stream); | 读一个流 |
+| \#include <stdio.h> | int fseek(FILE \*stream, long offset, int whence); | 设置流指针的位置 |
+| \#include <stdio.h> | long ftell(FILE \*stream); | 获取流指针的位置 |
+| \#include <stdio.h> | size_t fwrite(const void \*ptr, size_t size, size_t
nmemb,FILE \*stream); | 向流写入 |
+| \#include <stdio.h> | void perror(const char \*s); | 打印系统错误信息 |
+| \#include <stdio.h> | void rewind(FILE \*stream); | 重新定位流 |
+| \#include <unistd.h> | ssize_t write(int fd, const void \*buf, size_t size); | 写文件内容 |
+| \#include <unistd.h> | ssize_t read(int fd, void \*buf, size_t size); | 读文件内容 |
+
+ **表7** net
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <sys/socket.h> | void freeaddrinfo(struct addrinfo \*res); | 释放调用getaddrinfo所分配的动态内存 |
+| \#include <sys/socket.h> | int getaddrinfo(const char \*restrict nodename,const
char \*restrict servname,const struct addrinfo \*restrict
hints,struct addrinfo \*\*restrict res); | 网络地址和服务转换 |
+| \#include <sys/socket.h> | int getnameinfo(const struct sockaddr \*restrict sa,
socklen_t salen,char \*restrict node, socklen_t nodelen
, char \*restrict service,socklen_t servicelen, int flags); | 以协议无关的方式进行地址到名称的转换 |
+| \#include <net/if.h> | unsigned int if_nametoindex(const char \*ifname); | 通过网络接口名得到索引 |
+| \#include <arpa/inet.h> | in_addr_t inet_addr(const char \*cp); | 网络主机地址点分十进制形式转换位二进制形式 |
+| \#include <arpa/inet.h> | char \*inet_ntoa(struct in_addr in); | 网络主机地址二进制形式转换位点分十进制形式 |
+| \#include <arpa/inet.h> | const char \*inet_ntop(int af, const void \*src,char \*dst,
socklen_t size); | 网络地址转换 |
+| \#include <arpa/inet.h> | int inet_pton(int af, const char \*src, void \*dst); | 网络地址转换 |
+| \#include <sys/socket.h> | int listen(int sockfd, int backlog); | 监听套接字 |
+| \#include <sys/socket.h> | ssize_t recvmsg(int sockfd, struct msghdr \*msg, int flags); | 从套接字接收消息.只支持iov大小为1的场景,且不支持ancillary消息 |
+| \#include <sys/socket.h> | ssize_t send(int sockfd, const void \*buf, size_t len, int flags); | 从socket发送消息 |
+| \#include <sys/socket.h> | ssize_t sendmsg(int sockfd, const struct msghdr \*msg, int flags); | 从socket发送消息。不支持ancillary消息 |
+| \#include <sys/socket.h> | ssize_t sendto(int sockfd, const void \*buf, size_t len, int
flags,const struct sockaddr \*dest_addr, socklen_t addrlen); | 从socket发送消息 |
+| \#include <sys/socket.h> | int setsockopt(int sockfd, int level, int optname,const
void \*optval, socklen_t optlen); | 设置与套接字关联的选项 |
+
+ **表8** mem
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <string.h> | int memcmp(const void \*s1, const void \*s2, size_t n); | 内存比较 |
+| \#include <string.h> | void \*memcpy(void \*dest, const void \*src, size_t n); | 内存拷贝 |
+| \#include <string.h> | void \*memset(void \*s, int c, size_t n); | 内存初始化 |
+| \#include <stdlib.h> | void \*realloc(void \*ptr, size_t size); | 重分配内存 |
+| \#include <stdlib.h> | void \*malloc(size_t size); | 动态分配内存块大小 |
+| \#include <stdlib.h> | void free(void \*ptr); | 释放ptr所指向的内存空间 |
+
+ **表9** IPC
+
+| 需要包含的头文件 | 接口名 | 描述 |
+| -------- | -------- | -------- |
+| \#include <semaphore.h> | int sem_timedwait(sem_t \*sem, const struct
timespec \*abs_timeout); | 计时锁定信号量 |
+| \#include <semaphore.h> | int sem_destroy(sem_t \*sem); | 销毁指定的无名信号量 |
+| \#include <semaphore.h> | int sem_init(sem_t \*sem, int pshared
, unsigned int value); | 创建并初始化一个无名信号量 |
+| \#include <semaphore.h> | int sem_post(sem_t \*sem); | 增加信号量计数 |
+| \#include <semaphore.h> | int sem_wait(sem_t \*sem); | 获取信号量 |
+| \#include <mqueue.h> | mqd_t mq_open(const char \*mqName,
int openFlag, ...); | 此API用于打开一个具有指定名称的已有消息队列或创建一个新的消息队列 |
+| \#include <mqueue.h> | int mq_close(mqd_t personal); | 此API用于关闭具有指定描述符的消息队列 |
+| \#include <mqueue.h> | int mq_unlink(const char \*mqName); | 此API用于删除具有指定名称的消息队列 |
+| \#include <mqueue.h> | int mq_send(mqd_t personal, const
char \*msg,size_t msgLen, unsigned int msgPrio); | 此API用于将具有指定内容和长度的消息放入具有指定描述符的消息队列中 |
+| \#include <mqueue.h> | ssize_t mq_receive(mqd_t personal, char \*msg,
size_t msgLen, unsigned int \*msgPrio); | 此API用于从具有指定描述符的消息队列中删除最老的消息,并将其放入msg_ptr所指向的缓冲区中 |
+| \#include <mqueue.h> | int mq_timedsend(mqd_t personal, const char
\*msg, size_t msgLen, unsigned int msgPrio, c
onst struct timespec \*absTimeout) | 此API用于在预定时间将具有指定内容和长度的消息放入具有描述符的消息队列中 |
+| \#include <mqueue.h> | ssize_t mq_timedreceive(mqd_t personal, char
\*msg, size_t msgLen, unsigned int \*msgPrio,
const struct timespec \*absTimeout); | 此API用于从具有指定描述符的消息队列消息中获取具有指定消息内容和长度的消息 |
+| \#include <mqueue.h> | int mq_setattr(mqd_t mqdes, const struct mq_
attr \*__restrict newattr, struct mq_attr \*__restrict oldattr); | 设置描述符指定的消息队列属性 |
+| \#include <libc.h> | const char \*libc_get_version_string(void); | 获取libc版本字符串 |
+| \#include <libc.h> | int libc_get_version(void); | 获取libc版本号 |
+
+
+#### 注意事项
+
+常用错误码对照表:
+
+| 错误码 | 值 | 描述 | 含义 |
+| -------- | -------- | -------- | -------- |
+| ENOERR | 0 | Success | 成功 |
+| EPERM | 1 | Operation not permitted | 操作不允许 |
+| ENOENT | 2 | No such file or directory | 没有这样的文件或目录 |
+| ESRCH | 3 | No such process | 没有这样的进程(暂不支持) |
+| EINTR | 4 | Interrupted system call | 系统调用被中断 |
+| EIO | 5 | I/O error | I/O错误 |
+| ENXIO | 6 | No such device or address | 没有这样的设备或地址 |
+| E2BIG | 7 | Arg list too long | 参数列表太长 |
+| ENOEXEC | 8 | Exec format error | 执行格式错误 |
+| EBADF | 9 | Bad file number | 坏的文件描述符 |
+| ECHILD | 10 | No child processes | 没有子进程(暂不支持) |
+| EAGAIN | 11 | Try again | 资源暂时不可用 |
+| ENOMEM | 12 | Out of memory | 内存溢出 |
+| EACCES | 13 | Permission denied | 拒绝许可 |
+| EFAULT | 14 | Bad address | 错误的地址 |
+| ENOTBLK | 15 | Block device required | 块设备请求 |
+| EBUSY | 16 | Device or resource busy | 设备或资源忙 |
+| EEXIST | 17 | File exists | 文件存在 |
+| EXDEV | 18 | Cross-device link | 无效的交叉链接 |
+| ENODEV | 19 | No such device | 设备不存在 |
+| ENOTDIR | 20 | Not a directory | 不是一个目录 |
+| EISDIR | 21 | Is a directory | 是一个目录 |
+| EINVAL | 22 | Invalid argument | 无效的参数 |
+| ENFILE\* | 23 | File table overflow | 打开太多的文件系统 |
+| EMFILE | 24 | Too many open files | 打开的文件过多 |
+| EFBIG | 27 | File too large | 文件太大 |
+| ENOSPC | 28 | No space left on device | 设备上没有空间 |
+| ESPIPE | 29 | Illegal seek | 非法移位 |
+| EROFS | 30 | Read-only file system | 只读文件系统 |
+| EMLINK | 31 | Too many links | 太多的链接 |
+| EDOM | 33 | Math argument out of domain | 数值结果超出范围 |
+| ERANGE | 34 | Math result not representable | 数值结果不具代表性 |
+| EDEADLK | 35 | Resource deadlock would occur | 资源死锁错误 |
+| ENAMETOOLONG | 36 | Filename too long | 文件名太长 |
+| ENOLCK | 37 | No record locks available | 没有可用锁 |
+| ENOSYS | 38 | Function not implemented | 功能没有实现 |
+| ENOTEMPTY | 39 | Directory not empty | 目录不空 |
+| ELOOP | 40 | Too many symbolic links encountered | 符号链接层次太多 |
+| ENOMSG | 42 | No message of desired type | 没有期望类型的消息 |
+| EIDRM | 43 | Identifier removed | 标识符删除 |
+| ELNRNG | 48 | Link number out of range | 链接数超出范围 |
+| EBADR | 53 | Invalid request descriptor | 请求描述符无效 |
+| EBADRQC | 56 | Invalid request code | 无效的请求代码 |
+| ENOSTR | 60 | Device not a stream | 设备不是字符流 |
+| ENODATA | 61 | No data available | 无可用数据 |
+| ETIME | 62 | Timer expired | 计时器过期 |
+| EPROTO | 71 | Protocol error | 协议错误 |
+| EBADMSG | 74 | Not a data message | 非数据消息 |
+| EOVERFLOW | 75 | Value too large for defined data type | 值太大,对于定义数据类型 |
+| EMSGSIZE | 90 | Message too long | 消息太长 |
+
+
+#### 编程实例
+
+demo功能:
+
+创建一个线程并将父线程中的信息传递给子线程,在子线程中打印传递过来的信息和自身线程id值。
+
+
+```
+#include
+#include
+
+pthread_t ntid;
+
+void *ThreadFn(void *arg)
+{
+ pthread_t tid;
+ while(1) {
+ tid = pthread_self();
+ printf("\n++++++++++++++ %s %s tid = %d ++++++++++++++\n", (char*)arg, __FUNCTION__, tid);
+ }
+ return ((void *)0);
+}
+
+void DemoForTest()
+{
+ int err;
+ char* str = "Hello world";
+ err = pthread_create(&ntid, NULL, ThreadFn, (void*)str);
+ if(err != 0) {
+ printf("can't create thread\n");
+ }
+}
+
+```
+
+执行DemoForTest运行结果如下:
+
+
+```
+++++++++++++++ Hello world ThreadFn tid = 48 ++++++++++++++
+
+++++++++++++++ Hello world ThreadFn tid = 48 ++++++++++++++
+
+++++++++++++++ Hello world ThreadFn tid = 48 ++++++++++++++
+```
diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md
index afc518c52ce6037e598cad7b54a883c0f8c7e6eb..5071ddf325680c7d939907b5bb2fd8d8f1368e77 100644
--- a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md
+++ b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md
@@ -1,9 +1,322 @@
# 内存管理
+## 基本概念
+内存管理模块管理系统的内存资源,它是操作系统的核心模块之一,主要包括内存的初始化、分配以及释放。
-- **[基本概念](kernel-mini-basic-memory-basic.md)**
-- **[静态内存](kernel-mini-basic-memory-static.md)**
+在系统运行过程中,内存管理模块通过对内存的申请/释放来管理用户和OS对内存的使用,使内存的利用率和使用效率达到最优,同时最大限度地解决系统的内存碎片问题。
-- **[动态内存](kernel-mini-basic-memory-dynamic.md)**
\ No newline at end of file
+
+OpenHarmony LiteOS-M的内存管理分为静态内存管理和动态内存管理,提供内存初始化、分配、释放等功能。
+
+
+- 动态内存:在动态内存池中分配用户指定大小的内存块。
+ - 优点:按需分配。
+ - 缺点:内存池中可能出现碎片。
+
+- 静态内存:在静态内存池中分配用户初始化时预设(固定)大小的内存块。
+ - 优点:分配和释放效率高,静态内存池中无碎片。
+ - 缺点:只能申请到初始化预设大小的内存块,不能按需申请。
+## 静态内存
+
+
+### 运行机制
+
+静态内存实质上是一个静态数组,静态内存池内的块大小在初始化时设定,初始化后块大小不可变更。
+
+静态内存池由一个控制块LOS_MEMBOX_INFO和若干相同大小的内存块LOS_MEMBOX_NODE构成。控制块位于内存池头部,用于内存块管理,包含内存块大小uwBlkSize,内存块数量uwBlkNum,已分配使用的内存块数量uwBlkCnt和空闲内存块链表stFreeList。内存块的申请和释放以块大小为粒度,每个内存块包含指向下一个内存块的指针pstNext。
+
+ **图1** 静态内存示意图
+ 
+
+
+### 开发指导
+
+
+#### 使用场景
+
+当用户需要使用固定长度的内存时,可以通过静态内存分配的方式获取内存,一旦使用完毕,通过静态内存释放函数归还所占用内存,使之可以重复使用。
+
+
+#### 接口说明
+
+OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接口详细信息可以查看API参考。
+
+ **表1** 静态内存模块接口
+
+| 功能分类 | 接口名 |
+| -------- | -------- |
+| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 |
+| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 |
+| 申请、释放静态内存 | - LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
- LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 |
+| 获取、打印静态内存池信息 | - LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
- LOS_ShowBox:打印指定静态内存池所有节点信息(打印等级是LOS_INFO_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 |
+
+>  **说明:**
+> 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。
+
+
+#### 开发流程
+
+本节介绍使用静态内存的典型场景开发流程。
+
+1. 规划一片内存区域作为静态内存池。
+
+2. 调用LOS_MemboxInit初始化静态内存池。
+ 初始化会将入参指定的内存区域分割为N块(N值取决于静态内存总大小和块大小),将所有内存块挂到空闲链表,在内存起始处放置控制头。
+
+3. 调用LOS_MemboxAlloc接口分配静态内存。
+ 系统将会从空闲链表中获取第一个空闲块,并返回该内存块的起始地址。
+
+4. 调用LOS_MemboxClr接口。
+ 将入参地址对应的内存块清零。
+
+5. 调用LOS_MemboxFree接口。
+ 将该内存块加入空闲链表。
+
+
+#### 编程实例
+
+本实例执行以下步骤:
+
+1. 初始化一个静态内存池。
+
+2. 从静态内存池中申请一块静态内存。
+
+3. 在内存块存放一个数据。
+
+4. 打印出内存块中的数据。
+
+5. 清除内存块中的数据。
+
+6. 释放该内存块。
+ 示例代码如下:
+
+
+```
+#include "los_membox.h"
+
+VOID Example_StaticMem(VOID)
+{
+ UINT32 *mem = NULL;
+ UINT32 blkSize = 10;
+ UINT32 boxSize = 100;
+ UINT32 boxMem[1000];
+ UINT32 ret;
+
+ /*内存池初始化*/
+ ret = LOS_MemboxInit(&boxMem[0], boxSize, blkSize);
+ if(ret != LOS_OK) {
+ printf("Membox init failed!\n");
+ return;
+ } else {
+ printf("Membox init success!\n");
+ }
+
+ /*申请内存块*/
+ mem = (UINT32 *)LOS_MemboxAlloc(boxMem);
+ if (NULL == mem) {
+ printf("Mem alloc failed!\n");
+ return;
+ }
+ printf("Mem alloc success!\n");
+
+ /*赋值*/
+ *mem = 828;
+ printf("*mem = %d\n", *mem);
+
+ /*清除内存内容*/
+ LOS_MemboxClr(boxMem, mem);
+ printf("Mem clear success \n *mem = %d\n", *mem);
+
+ /*释放内存*/
+ ret = LOS_MemboxFree(boxMem, mem);
+ if (LOS_OK == ret) {
+ printf("Mem free success!\n");
+ } else {
+ printf("Mem free failed!\n");
+ }
+
+ return;
+}
+```
+
+
+#### 结果验证
+
+输出结果如下:
+
+
+```
+Membox init success!
+Mem alloc success!
+*mem = 828
+Mem clear success
+*mem = 0
+Mem free success!
+```
+## 动态内存
+
+
+### 运行机制
+
+动态内存管理,即在内存资源充足的情况下,根据用户需求,从系统配置的一块比较大的连续内存(内存池,也是堆内存)中分配任意大小的内存块。当用户不需要该内存块时,又可以释放回系统供下一次使用。与静态内存相比,动态内存管理的优点是按需分配,缺点是内存池中容易出现碎片。
+
+OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分进行了优化,获得更优的性能,降低了碎片率。动态内存核心算法框图如下:
+
+ **图1** 轻量系统动态内存核心算法
+ 
+
+根据空闲内存块的大小,使用多个空闲链表来管理。根据内存空闲块大小分为两个部分:[4, 127]和[27, 231],如上图size class所示:
+
+1. 对[4,127]区间的内存进行等分,如上图下半部分所示,分为31个小区间,每个小区间对应内存块大小为4字节的倍数。每个小区间对应一个空闲内存链表和用于标记对应空闲内存链表是否为空的一个比特位,值为1时,空闲链表非空。[4,127]区间的31个小区间内存对应31个比特位进行标记链表是否为空。
+
+2. 大于127字节的空闲内存块,按照2的次幂区间大小进行空闲链表管理。总共分为24个小区间,每个小区间又等分为8个二级小区间,见上图上半部分的Size Class和Size SubClass部分。每个二级小区间对应一个空闲链表和用于标记对应空闲内存链表是否为空的一个比特位。总共24\*8=192个二级小区间,对应192个空闲链表和192个比特位进行标记链表是否为空。
+
+例如,当有40字节的空闲内存需要插入空闲链表时,对应小区间[40,43],第10个空闲链表,位图标记的第10比特位。把40字节的空闲内存挂载第10个空闲链表上,并判断是否需要更新位图标记。当需要申请40字节的内存时,根据位图标记获取存在满足申请大小的内存块的空闲链表,从空闲链表上获取空闲内存节点。如果分配的节点大于需要申请的内存大小,进行分割节点操作,剩余的节点重新挂载到相应的空闲链表上。当有580字节的空闲内存需要插入空闲链表时,对应二级小区间[2^9,2^9+2^6],第31+2\*8=47个空闲链表,并使用位图的第47个比特位来标记链表是否为空。把580字节的空闲内存挂载第47个空闲链表上,并判断是否需要更新位图标记。当需要申请580字节的内存时,根据位图标记获取存在满足申请大小的内存块的空闲链表,从空闲链表上获取空闲内存节点。如果分配的节点大于需要申请的内存大小,进行分割节点操作,剩余的节点重新挂载到相应的空闲链表上。如果对应的空闲链表为空,则向更大的内存区间去查询是否有满足条件的空闲链表,实际计算时,会一次性查找到满足申请大小的空闲链表。
+
+内存管理结构如下图所示:
+
+ **图2** 轻量系统动态内存管理结构图
+ 
+
+- 内存池池头部分
+ 内存池池头部分包含内存池信息、位图标记数组和空闲链表数组。内存池信息包含内存池起始地址及堆区域总大小,内存池属性。位图标记数组有7个32位无符号整数组成,每个比特位标记对应的空闲链表是否挂载空闲内存块节点。空闲内存链表包含223个空闲内存头节点信息,每个空闲内存头节点信息维护内存节点头和空闲链表中的前驱、后继空闲内存节点。
+
+- 内存池节点部分
+ 包含3种类型节点:未使用空闲内存节点,已使用内存节点和尾节点。每个内存节点维护一个前序指针,指向内存池中上一个内存节点,还维护内存节点的大小和使用标记。空闲内存节点和已使用内存节点后面的内存区域是数据域,尾节点没有数据域。
+
+一些芯片片内RAM大小无法满足要求,需要使用片外物理内存进行扩充。对于这样的多段非连续性内存, LiteOS-M内核支持把多个非连续性内存逻辑上合一,用户不感知底层的多段非连续性内存区域。 LiteOS-M内核内存模块把不连续的内存区域作为空闲内存结点插入到空闲内存节点链表,把不同内存区域间的不连续部分标记为虚拟的已使用内存节点,从逻辑上把多个非连续性内存区域实现为一个统一的内存池。下面通过示意图说明下多段非连续性内存的运行机制:
+
+ **图3** 非连续性内存合一示意图
+ 
+
+结合上述示意图,非连续性内存合并为一个统一的内存池的步骤如下:
+
+1. 把多段非连续性内存区域的第一块内存区域通过调用LOS_MemInit接口进行初始化。
+
+2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。
+
+3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize+ OS_MEM_NODE_HEAD_SIZE。
+
+4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。
+
+5. 如果有更多的非连续内存区域,重复上述步骤2-4。
+
+
+### 开发指导
+
+
+#### 使用场景
+
+动态内存管理的主要工作是动态分配并管理用户申请到的内存区间。动态内存管理主要用于用户需要使用大小不等的内存块的场景,当用户需要使用内存时,可以通过操作系统的动态内存申请函数索取指定大小的内存块,一旦使用完毕,通过动态内存释放函数归还所占用内存,使之可以重复使用。
+
+
+#### 接口说明
+
+OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接口详细信息可以查看API参考。
+
+ **表1** 动态内存模块接口
+
+| 功能分类 | 接口描述 |
+| -------- | -------- |
+| 初始化和删除内存池 | - LOS_MemInit:初始化一块指定的动态内存池,大小为size。
- LOS_MemDeInit:删除指定内存池,仅打开LOSCFG_MEM_MUL_POOL时有效。 |
+| 申请、释放动态内存 | - LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
- LOS_MemFree:释放从指定动态内存中申请的内存。
- LOS_MemRealloc:释放从指定动态内存中申请的内存。 |
+| 获取内存池信息 | - LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
- LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
- LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
- LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开LOSCFG_MEM_MUL_POOL时有效。 |
+| 获取内存块信息 | - LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
- LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 |
+| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 |
+| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 |
+
+>  **说明:**
+> - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。
+>
+> - 对齐分配内存接口LOS_MemAllocAlign/LOS_MemMallocAlign因为要进行地址对齐,可能会额外消耗部分内存,故存在一些遗失内存,当系统释放该对齐内存时,同时回收由于对齐导致的遗失内存。
+>
+> - 非连续性内存区域接口LOS_MemRegionsAdd的LosMemRegion数组参数传入的非连续性内存区域需要按各个内存区域的内存开始地址升序,且内存区域不能重叠。
+
+
+#### 开发流程
+
+本节介绍使用动态内存的典型场景开发流程。
+
+1. 初始化LOS_MemInit。
+ 初始一个内存池后生成一个内存池控制头、尾节点EndNode,剩余的内存被标记为FreeNode内存节点。注:EndNode作为内存池末尾的节点,size为0。
+
+1. 申请任意大小的动态内存LOS_MemAlloc。
+ 判断动态内存池中是否存在大于申请量大小的空闲内存块空间,若存在,则划出一块内存块,以指针形式返回,若不存在,返回NULL。如果空闲内存块大于申请量,需要对内存块进行分割,剩余的部分作为空闲内存块挂载到空闲内存链表上。
+
+1. 释放动态内存LOS_MemFree。
+ 回收内存块,供下一次使用。调用LOS_MemFree释放内存块,则会回收内存块,并且将其标记为FreeNode。在回收内存块时,相邻的FreeNode会自动合并。
+
+
+#### 编程实例
+
+本实例执行以下步骤:
+
+1. 初始化一个动态内存池。
+
+2. 从动态内存池中申请一个内存块。
+
+3. 在内存块中存放一个数据。
+
+4. 打印出内存块中的数据。
+
+5. 释放该内存块。
+
+示例代码如下:
+
+
+```
+#include "los_memory.h"
+#define TEST_POOL_SIZE (2*1024)
+__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE];
+VOID Example_DynMem(VOID)
+{
+ UINT32 *mem = NULL;
+ UINT32 ret;
+
+ /*初始化内存池*/
+ ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE);
+ if (LOS_OK == ret) {
+ printf("Mem init success!\n");
+ } else {
+ printf("Mem init failed!\n");
+ return;
+ }
+
+ /*分配内存*/
+ mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4);
+ if (NULL == mem) {
+ printf("Mem alloc failed!\n");
+ return;
+ }
+ printf("Mem alloc success!\n");
+
+ /*赋值*/
+ *mem = 828;
+ printf("*mem = %d\n", *mem);
+
+ /*释放内存*/
+ ret = LOS_MemFree(g_testPool, mem);
+ if (LOS_OK == ret) {
+ printf("Mem free success!\n");
+ } else {
+ printf("Mem free failed!\n");
+ }
+
+ return;
+}
+```
+
+
+#### 结果验证
+
+输出结果如下:
+
+
+```
+Mem init success!
+Mem alloc success!
+*mem = 828
+Mem free success!
+```
diff --git a/zh-cn/device-dev/kernel/kernel-mini-extend-file.md b/zh-cn/device-dev/kernel/kernel-mini-extend-file.md
index 65e95f800c497f322f28bc990c0665978e7580bf..e0df347da27479ec128062a02c44d458cf6cd9b7 100644
--- a/zh-cn/device-dev/kernel/kernel-mini-extend-file.md
+++ b/zh-cn/device-dev/kernel/kernel-mini-extend-file.md
@@ -40,7 +40,292 @@ M核的文件系统子系统当前支持的文件系统有FATFS与LittleFS。同
| umount2 | 分区卸载,可通过MNT_FORCE参数进行强制卸载 | 支持 | 不支持 |
| statfs | 获取分区信息 | 支持 | 不支持 |
+## FAT
-- **[FAT](kernel-mini-extend-file-fat.md)**
-- **[LittleFS](kernel-mini-extend-file-lit.md)**
\ No newline at end of file
+### 基本概念
+
+FAT文件系统是File Allocation Table(文件配置表)的简称,主要包括DBR区、FAT区、DATA区三个区域。其中,FAT区各个表项记录存储设备中对应簇的信息,包括簇是否被使用、文件下一个簇的编号、是否文件结尾等。FAT文件系统有FAT12、FAT16、FAT32等多种格式,其中,12、16、32表示对应格式中FAT表项的比特数。FAT文件系统支持多种介质,特别在可移动存储介质(U盘、SD卡、移动硬盘等)上广泛使用,使嵌入式设备和Windows、Linux等桌面系统保持很好的兼容性,方便用户管理操作文件。
+
+OpenHarmony内核支持FAT12、FAT16与FAT32三种格式的FAT文件系统,具有代码量小、资源占用小、可裁切、支持多种物理介质等特性,并且与Windows、Linux等系统保持兼容,支持多设备、多分区识别等功能。OpenHarmony内核支持硬盘多分区,可以在主分区以及逻辑分区上创建FAT文件系统。
+
+
+### 开发指导
+
+
+#### 驱动适配
+
+FAT文件系统的使用需要底层MMC相关驱动的支持。在一个带MMC存储设备的板子上运行FATFS,需要:
+
+1、适配板端EMMC驱动,实现disk_status、disk_initialize、disk_read、disk_write、disk_ioctl接口;
+
+2、新增fs_config.h文件,配置FS_MAX_SS(存储设备最大sector大小)、FF_VOLUME_STRS(分区名)等信息,例如:
+
+
+```
+#define FF_VOLUME_STRS "system", "inner", "update", "user"
+#define FS_MAX_SS 512
+#define FAT_MAX_OPEN_FILES 50
+```
+
+
+#### 开发流程
+
+>  **说明:**
+> - FATFS文件与目录操作:
+> - 单个文件大小不超过4G。
+> - 支持同时打开的文件数最大为FAT_MAX_OPEN_FILES,文件夹数最大为FAT_MAX_OPEN_DIRS。
+> - 暂不支持根目录管理,文件/目录名均以分区名开头,例如“user/testfile”就是在“user”分区下名为“testfile”的文件或目录。
+> - 若需要同时多次打开同一文件,必须全部使用只读方式(O_RDONLY)。以可写方式(O_RDWR、O_WRONLY等)只能打开一次。
+> - 读写指针未分离,例如以O_APPEND(追加写)方式打开文件后,读指针也在文件尾,从头读文件前需要用户手动置位。
+> - 暂不支持文件与目录的权限管理。
+> - stat及fstat接口暂不支持查询修改时间、创建时间和最后访问时间。微软FAT协议不支持1980年以前的时间。
+>
+> - FATFS分区挂载与卸载:
+> - 支持以只读属性挂载分区。当mount函数的入参为MS_RDONLY时,所有的带有写入的接口,如write、mkdir、unlink,以及非O_RDONLY属性的open,将均被拒绝。
+> - mount支持通过MS_REMOUNT标记修改已挂载分区的权限。
+> - 在umount操作前,需确保所有目录及文件全部关闭。
+> - umount2支持通过MNT_FORCE参数强制关闭所有文件与文件夹并umount,但可能造成数据丢失,请谨慎使用。
+>
+> - FATFS支持重新划分存储设备分区、格式化分区,对应接口为fatfs_fdisk与fatfs_format:
+> - 在fatfs_format操作之前,若需要格式化的分区已挂载,需确保分区中的所有目录及文件全部关闭,并且分区umount。
+> - 在fatfs_fdisk操作前,需要该设备中的所有分区均已umount。
+> - fatfs_fdisk与fatfs_format会造成设备数据丢失,请谨慎使用。
+
+
+### 编程实例
+
+
+#### 实例描述
+
+本实例实现以下功能:
+
+1. 创建目录“user/test”
+
+2. 在“user/test”目录下创建文件“file.txt”
+
+3. 在文件起始位置写入“Hello OpenHarmony!”
+
+4. 将文件内容刷入设备中
+
+5. 设置偏移到文件起始位置
+
+6. 读取文件内容
+
+7. 关闭文件
+
+8. 删除文件
+
+9. 删除目录
+
+
+#### 示例代码
+
+ **前提条件:**
+
+ 系统已将MMC设备分区挂载到user目录
+
+ **代码实现如下:**
+
+ ```
+ #include
+ #include
+ #include "sys/stat.h"
+ #include "fcntl.h"
+ #include "unistd.h"
+
+ #define LOS_OK 0
+ #define LOS_NOK -1
+
+ int FatfsTest(void)
+ {
+ int ret;
+ int fd = -1;
+ ssize_t len;
+ off_t off;
+ char dirName[20] = "user/test";
+ char fileName[20] = "user/test/file.txt";
+ char writeBuf[20] = "Hello OpenHarmony!";
+ char readBuf[20] = {0};
+
+ /* 创建目录“user/test” */
+ ret = mkdir(dirName, 0777);
+ if (ret != LOS_OK) {
+ printf("mkdir failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 创建可读写文件"user/test/file.txt" */
+ fd = open(fileName, O_RDWR | O_CREAT, 0777);
+ if (fd < 0) {
+ printf("open file failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 将writeBuf中的内容写入文件 */
+ len = write(fd, writeBuf, strlen(writeBuf));
+ if (len != strlen(writeBuf)) {
+ printf("write file failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 将文件内容刷入存储设备中 */
+ ret = fsync(fd);
+ if (ret != LOS_OK) {
+ printf("fsync failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 将读写指针偏移至文件头 */
+ off = lseek(fd, 0, SEEK_SET);
+ if (off != 0) {
+ printf("lseek failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 将文件内容读出至readBuf中,读取长度为readBuf大小 */
+ len = read(fd, readBuf, sizeof(readBuf));
+ if (len != strlen(writeBuf)) {
+ printf("read file failed.\n");
+ return LOS_NOK;
+ }
+ printf("%s\n", readBuf);
+
+ /* 关闭文件 */
+ ret = close(fd);
+ if (ret != LOS_OK) {
+ printf("close failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 删除文件"user/test/file.txt" */
+ ret = unlink(fileName);
+ if (ret != LOS_OK) {
+ printf("unlink failed.\n");
+ return LOS_NOK;
+ }
+
+ /* 删除目录“user/test” */
+ ret = rmdir(dirName);
+ if (ret != LOS_OK) {
+ printf("rmdir failed.\n");
+ return LOS_NOK;
+ }
+
+ return LOS_OK;
+ }
+ ```
+
+
+#### 结果验证
+
+编译运行得到的结果为:
+
+
+```
+Hello OpenHarmony!
+```
+## LittleFS
+
+
+### 基本概念
+
+LittleFS是一个小型的Flash文件系统,它结合日志结构(log-structured)文件系统和COW(copy-on-write)文件系统的思想,以日志结构存储元数据,以COW结构存储数据。这种特殊的存储方式,使LittleFS具有强大的掉电恢复能力(power-loss resilience)。分配COW数据块时LittleFS采用了名为统计损耗均衡的动态损耗均衡算法,使Flash设备的寿命得到有效保障。同时LittleFS针对资源紧缺的小型设备进行设计,具有极其有限的ROM和RAM占用,并且所有RAM的使用都通过一个可配置的固定大小缓冲区进行分配,不会随文件系统的扩大占据更多的系统资源。
+
+当在一个资源非常紧缺的小型设备上,寻找一个具有掉电恢复能力并支持损耗均衡的Flash文件系统时,LittleFS是一个比较好的选择。
+
+
+### 开发指导
+
+移植LittleFS到新硬件设备上,需要申明lfs_config:
+
+
+```
+const struct lfs_config cfg = {
+ // block device operations
+ .read = user_provided_block_device_read,
+ .prog = user_provided_block_device_prog,
+ .erase = user_provided_block_device_erase,
+ .sync = user_provided_block_device_sync,
+
+ // block device configuration
+ .read_size = 16,
+ .prog_size = 16,
+ .block_size = 4096,
+ .block_count = 128,
+ .cache_size = 16,
+ .lookahead_size = 16,
+ .block_cycles = 500,
+};
+```
+
+其中.read,.prog,.erase,.sync分别对应该硬件平台上的底层的读写\擦除\同步等接口。
+
+read_size 每次读取的字节数,可以比物理读单元大以改善性能,这个数值决定了读缓存的大小,但值太大会带来更多的内存消耗。
+
+prog_size 每次写入的字节数,可以比物理写单元大以改善性能,这个数值决定了写缓存的大小,必须是read_size的整数倍,但值太大会带来更多的内存消耗。
+
+block_size 每个擦除块的字节数,可以比物理擦除单元大,但此数值应尽可能小因为每个文件至少会占用一个块。必须是prog_size的整数倍。
+
+block_count 可以被擦除的块数量,这取决于块设备的容量及擦除块的大小。
+
+
+### 示例代码
+
+ 代码实现如下:
+
+```
+#include "lfs.h"
+#include "stdio.h"
+lfs_t lfs;
+lfs_file_t file;
+const struct lfs_config cfg = {
+ // block device operations
+ .read = user_provided_block_device_read,
+ .prog = user_provided_block_device_prog,
+ .erase = user_provided_block_device_erase,
+ .sync = user_provided_block_device_sync,
+ // block device configuration
+ .read_size = 16,
+ .prog_size = 16,
+ .block_size = 4096,
+ .block_count = 128,
+ .cache_size = 16,
+ .lookahead_size = 16,
+ .block_cycles = 500,
+};
+int main(void) {
+ // mount the filesystem
+ int err = lfs_mount(&lfs, &cfg);
+ // reformat if we can't mount the filesystem
+ // this should only happen on the first boot
+ if (err) {
+ lfs_format(&lfs, &cfg);
+ lfs_mount(&lfs, &cfg);
+ }
+ // read current count
+ uint32_t boot_count = 0;
+ lfs_file_open(&lfs, &file, "boot_count", LFS_O_RDWR | LFS_O_CREAT);
+ lfs_file_read(&lfs, &file, &boot_count, sizeof(boot_count));
+ // update boot count
+ boot_count += 1;
+ lfs_file_rewind(&lfs, &file);
+ lfs_file_write(&lfs, &file, &boot_count, sizeof(boot_count));
+ // remember the storage is not updated until the file is closed successfully
+ lfs_file_close(&lfs, &file);
+ // release any resources we were using
+ lfs_unmount(&lfs);
+ // print the boot count
+ printf("boot_count: %d\n", boot_count);
+}
+```
+
+
+ **结果验证**
+
+首次编译运行得到的结果为:
+
+
+```
+Say hello 1 times.
+```
\ No newline at end of file
diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md b/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md
index 625990100c08618f1beef05b71bf496e67f2d42a..fab4a6266dabae8db627379f1ffb8073961e6d37 100644
--- a/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md
+++ b/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md
@@ -4,8 +4,336 @@
内存调测方法旨在辅助定位动态内存相关问题,提供了基础的动态内存池信息统计手段,向用户呈现内存池水线、碎片率等信息;提供了内存泄漏检测手段,方便用户准确定位存在内存泄漏的代码行,也可以辅助分析系统各个模块内存的使用情况;提供了踩内存检测手段,可以辅助定位越界踩内存的场景。
-- **[内存信息统计](kernel-mini-memory-debug-mes.md)**
+## 内存信息统计
-- **[内存泄漏检测](kernel-mini-memory-debug-det.md)**
-- **[踩内存检测](kernel-mini-memory-debug-cet.md)**
\ No newline at end of file
+### 基础概念
+
+内存信息包括内存池大小、内存使用量、剩余内存大小、最大空闲内存、内存水线、内存节点数统计、碎片率等。
+
+- 内存水线:即内存池的最大使用量,每次申请和释放时,都会更新水线值,实际业务可根据该值,优化内存池大小;
+
+- 碎片率:衡量内存池的碎片化程度,碎片率高表现为内存池剩余内存很多,但是最大空闲内存块很小,可以用公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)来度量;
+
+- 其他参数:通过调用接口(详见[内存管理](../kernel/kernel-mini-basic-memory-basic.md)章节接口说明),扫描内存池的节点信息,统计出相关信息。
+
+
+### 功能配置
+
+LOSCFG_MEM_WATERLINE:开关宏,默认打开;若关闭这个功能,在target_config.h中将这个宏定义为0。如需获取内存水线,需要打开该配置。
+
+
+### 开发指导
+
+
+#### 开发流程
+
+关键结构体介绍:
+
+
+```
+typedef struct {
+ UINT32 totalUsedSize; // 内存池的内存使用量
+ UINT32 totalFreeSize; // 内存池的剩余内存大小
+ UINT32 maxFreeNodeSize; // 内存池的最大空闲内存块大小
+ UINT32 usedNodeNum; // 内存池的非空闲内存块个数
+ UINT32 freeNodeNum; // 内存池的空闲内存块个数
+#if (LOSCFG_MEM_WATERLINE == 1) // 默认打开,如需关闭,在target_config.h中将该宏设置为0
+ UINT32 usageWaterLine; // 内存池的水线值
+#endif
+} LOS_MEM_POOL_STATUS;
+```
+
+- 内存水线获取:调用LOS_MemInfoGet接口,第1个参数是内存池首地址,第2个参数是LOS_MEM_POOL_STATUS类型的句柄,其中字段usageWaterLine即水线值。
+
+- 内存碎片率计算:同样调用LOS_MemInfoGet接口,可以获取内存池的剩余内存大小和最大空闲内存块大小,然后根据公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)得出此时的动态内存池碎片率。
+
+
+#### 编程实例
+
+本实例实现如下功能:
+
+1.创建一个监控任务,用于获取内存池的信息;
+
+2.调用LOS_MemInfoGet接口,获取内存池的基础信息;
+
+3.利用公式算出使用率及碎片率。
+
+
+#### 示例代码
+
+ 代码实现如下:
+
+```
+#include
+#include
+#include "los_task.h"
+#include "los_memory.h"
+#include "los_config.h"
+
+
+void MemInfoTaskFunc(void)
+{
+ LOS_MEM_POOL_STATUS poolStatus = {0};
+
+ /* pool为要统计信息的内存地址,此处以OS_SYS_MEM_ADDR为例 */
+ void *pool = OS_SYS_MEM_ADDR;
+ LOS_MemInfoGet(pool, &poolStatus);
+ /* 算出内存池当前的碎片率百分比 */
+ unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize;
+ /* 算出内存池当前的使用率百分比 */
+ unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool);
+ printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize,
+ poolStatus.totalFreeSize, poolStatus.usageWaterLine);
+}
+
+int MemTest(void)
+{
+ unsigned int ret;
+ unsigned int taskID;
+ TSK_INIT_PARAM_S taskStatus = {0};
+ taskStatus.pfnTaskEntry = (TSK_ENTRY_FUNC)MemInfoTaskFunc;
+ taskStatus.uwStackSize = 0x1000;
+ taskStatus.pcName = "memInfo";
+ taskStatus.usTaskPrio = 10;
+ ret = LOS_TaskCreate(&taskID, &taskStatus);
+ if (ret != LOS_OK) {
+ printf("task create failed\n");
+ return -1;
+ }
+ return 0;
+}
+```
+
+
+#### 结果验证
+
+编译运行输出的结果如下:
+
+
+```
+usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414
+```
+## 内存泄漏检测
+
+
+### 基础概念
+
+内存泄漏检测机制作为内核的可选功能,用于辅助定位动态内存泄漏问题。开启该功能,动态内存机制会自动记录申请内存时的函数调用关系(下文简称LR)。如果出现泄漏,就可以利用这些记录的信息,找到内存申请的地方,方便进一步确认。
+
+
+### 功能配置
+
+1. LOSCFG_MEM_LEAKCHECK:开关宏,默认关闭;若打开这个功能,在target_config.h中将这个宏定义为1。
+
+2. LOSCFG_MEM_RECORD_LR_CNT:记录的LR层数,默认3层;每层LR消耗sizeof(void \*)字节数的内存。
+
+3. LOSCFG_MEM_OMIT_LR_CNT:忽略的LR层数,默认4层,即从调用LOS_MemAlloc的函数开始记录,可根据实际情况调整。为啥需要这个配置?有3点原因如下:
+ - LOS_MemAlloc接口内部也有函数调用;
+ - 外部可能对LOS_MemAlloc接口有封装;
+ - LOSCFG_MEM_RECORD_LR_CNT 配置的LR层数有限;
+
+正确配置这个宏,将无效的LR层数忽略,就可以记录有效的LR层数,节省内存消耗。
+
+
+### 开发指导
+
+
+#### 开发流程
+
+该调测功能可以分析关键的代码逻辑中是否存在内存泄漏。开启这个功能,每次申请内存时,会记录LR信息。在需要检测的代码段前后,调用LOS_MemUsedNodeShow接口,每次都会打印指定内存池已使用的全部节点信息,对比前后两次的节点信息,新增的节点信息就是疑似泄漏的内存节点。通过LR,可以找到具体申请的代码位置,进一步确认是否泄漏。
+
+调用LOS_MemUsedNodeShow接口输出的节点信息格式如下:每1行为一个节点信息;第1列为节点地址,可以根据这个地址,使用GDB等手段查看节点完整信息;第2列为节点的大小,等于节点头大小+数据域大小;第3~5列为函数调用关系LR地址,可以根据这个值,结合汇编文件,查看该节点具体申请的位置。
+
+
+```
+node size LR[0] LR[1] LR[2]
+0x10017320: 0x528 0x9b004eba 0x9b004f60 0x9b005002
+0x10017848: 0xe0 0x9b02c24e 0x9b02c246 0x9b008ef0
+0x10017928: 0x50 0x9b008ed0 0x9b068902 0x9b0687c4
+0x10017978: 0x24 0x9b008ed0 0x9b068924 0x9b0687c4
+0x1001799c: 0x30 0x9b02c24e 0x9b02c246 0x9b008ef0
+0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0
+```
+
+>  **注意:**
+> 开启内存检测会影响内存申请的性能,且每个内存节点都会记录LR地址,内存开销也加大。
+
+
+#### 编程实例
+
+本实例实现如下功能:构建内存泄漏代码段。
+
+1. 调用LOS_MemUsedNodeShow接口,输出全部节点信息打印;
+
+2. 申请内存,但没有释放,模拟内存泄漏;
+
+3. 再次调用LOS_MemUsedNodeShow接口,输出全部节点信息打印;
+
+4. 将两次log进行对比,得出泄漏的节点信息;
+
+5. 通过LR地址,找出泄漏的代码位置;
+
+
+#### 示例代码
+
+代码实现如下:
+
+
+```
+#include
+#include
+#include "los_memory.h"
+#include "los_config.h"
+
+void MemLeakTest(void)
+{
+ LOS_MemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR);
+ void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8);
+ void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8);
+ LOS_MemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR);
+}
+```
+
+
+#### 结果验证
+
+编译运行输出log如下:
+
+
+```
+node size LR[0] LR[1] LR[2]
+0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc
+0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc
+0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e
+0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a
+0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220
+
+node size LR[0] LR[1] LR[2]
+0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc
+0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc
+0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e
+0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a
+0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220
+0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6
+0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000
+```
+
+对比两次log,差异如下,这些内存节点就是疑似泄漏的内存块:
+
+
+```
+0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6
+0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000
+```
+
+部分汇编文件如下:
+
+
+```
+ MemLeakTest:
+ 0x80041d4: 0xb510 PUSH {R4, LR}
+ 0x80041d6: 0x4ca8 LDR.N R4, [PC, #0x2a0] ; g_memStart
+ 0x80041d8: 0x0020 MOVS R0, R4
+ 0x80041da: 0xf7fd 0xf93e BL LOS_MemUsedNodeShow ; 0x800145a
+ 0x80041de: 0x2108 MOVS R1, #8
+ 0x80041e0: 0x0020 MOVS R0, R4
+ 0x80041e2: 0xf7fd 0xfbd9 BL LOS_MemAlloc ; 0x8001998
+ 0x80041e6: 0x2108 MOVS R1, #8
+ 0x80041e8: 0x0020 MOVS R0, R4
+ 0x80041ea: 0xf7fd 0xfbd5 BL LOS_MemAlloc ; 0x8001998
+ 0x80041ee: 0x0020 MOVS R0, R4
+ 0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a
+ 0x80041f4: 0xbd10 POP {R4, PC}
+ 0x80041f6: 0x0000 MOVS R0, R0
+```
+
+其中,通过查找0x080041ee,就可以发现该内存节点是在MemLeakTest接口里申请的且是没有释放的。
+
+## 踩内存检测
+
+
+### 基础概念
+
+踩内存检测机制作为内核的可选功能,用于检测动态内存池的完整性。通过该机制,可以及时发现内存池是否发生了踩内存问题,并给出错误信息,便于及时发现系统问题,提高问题解决效率,降低问题定位成本。
+
+
+### 功能配置
+
+LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK:开关宏,默认关闭;若打开这个功能,在target_config.h中将这个宏定义为1。
+
+1. 开启这个功能,每次申请内存,会实时检测内存池的完整性。
+
+2. 如果不开启该功能,也可以调用LOS_MemIntegrityCheck接口检测,但是每次申请内存时,不会实时检测内存完整性,而且由于节点头没有魔鬼数字(开启时才有,省内存),检测的准确性也会相应降低,但对于系统的性能没有影响,故根据实际情况开关该功能。
+
+由于该功能只会检测出哪个内存节点被破坏了,并给出前节点信息(因为内存分布是连续的,当前节点最有可能被前节点破坏)。如果要进一步确认前节点在哪里申请的,需开启内存泄漏检测功能,通过LR记录,辅助定位。
+
+>  **注意:**
+> 开启该功能,节点头多了魔鬼数字字段,会增大节点头大小。由于实时检测完整性,故性能影响较大;若性能敏感的场景,可以不开启该功能,使用LOS_MemIntegrityCheck接口检测。
+
+
+### 开发指导
+
+
+#### 开发流程
+
+通过调用LOS_MemIntegrityCheck接口检测内存池是否发生了踩内存,如果没有踩内存问题,那么接口返回0且没有log输出;如果存在踩内存问题,那么会输出相关log,详见下文编程实例的结果输出。
+
+
+#### 编程实例
+
+本实例实现如下功能:
+
+1. 申请两个物理上连续的内存块;
+
+2. 通过memset构造越界访问,踩到下个节点的头4个字节;
+
+3. 调用LOS_MemIntegrityCheck检测是否发生踩内存。
+
+
+#### 示例代码
+
+代码实现如下:
+
+
+```
+#include
+#include
+#include "los_memory.h"
+#include "los_config.h"
+
+void MemIntegrityTest(void)
+{
+ /* 申请两个物理连续的内存块 */
+ void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8);
+ void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8);
+ /* 第一个节点内存块大小是8字节,那么12字节的清零,会踩到第二个内存节点的节点头,构造踩内存场景 */
+ memset(ptr1, 0, 8 + 4);
+ LOS_MemIntegrityCheck(LOSCFG_SYS_HEAP_ADDR);
+}
+```
+
+
+#### 结果验证
+
+编译运行输出log如下:
+
+
+```
+[ERR][OsMemMagicCheckPrint], 2028, memory check error!
+memory used but magic num wrong, magic num = 0x00000000 /* 提示信息,检测到哪个字段被破坏了,用例构造了将下个节点的头4个字节清零,即魔鬼数字字段 */
+
+ broken node head: 0x20003af0 0x00000000 0x80000020, prev node head: 0x20002ad4 0xabcddcba 0x80000020
+/* 被破坏节点和其前节点关键字段信息,分别为其前节点地址、节点的魔鬼数字、节点的sizeAndFlag;可以看出被破坏节点的魔鬼数字字段被清零,符合用例场景 */
+
+ broken node head LR info: /* 节点的LR信息需要开启内存检测功能才有有效输出 */
+ LR[0]:0x0800414e
+ LR[1]:0x08000cc2
+ LR[2]:0x00000000
+
+ pre node head LR info: /* 通过LR信息,可以在汇编文件中查找前节点是哪里申请,然后排查其使用的准确性 */
+ LR[0]:0x08004144
+ LR[1]:0x08000cc2
+ LR[2]:0x00000000
+[ERR]Memory interity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* 被破坏节点和其前节点的地址 */
+```
diff --git a/zh-cn/device-dev/kernel/kernel-small-apx-dll.md b/zh-cn/device-dev/kernel/kernel-small-apx-dll.md
index f96563857060e2ef16b2397f22eb760bac77bbee..d13c006214da35581213e47da24e583cb16b861a 100644
--- a/zh-cn/device-dev/kernel/kernel-small-apx-dll.md
+++ b/zh-cn/device-dev/kernel/kernel-small-apx-dll.md
@@ -18,7 +18,7 @@
| 增加链表 | - LOS_ListAddList:将指定链表的头端插入到双向链表头端
- LOS_ListHeadInsertList:将指定链表的头端插入到双向链表头端
- LOS_ListTailInsertList:将指定链表的尾端插入到双向链表头端 |
| 删除节点 | - LOS_ListDelete:将指定节点从链表中删除
- LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 |
| 判断双向链表 | - LOS_ListEmpty:判断链表是否为空
- LOS_DL_LIST_IS_END:判断指定链表节点是否为链表尾端:LOS_DL_LIST_IS_ON_QUEUE:判断链表节点是否在双向链表里 |
-| 获取结构体信息 | - LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量
- LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。
- LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量
- LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。 |
+| 获取结构体信息 | - LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量
- LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。|
| 遍历双向链表 | - LOS_DL_LIST_FOR_EACH:遍历双向链表
- LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 |
| 遍历包含双向链表的结构体 | - LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址
- LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 |
diff --git a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
index a7090aa8cd25de4324897faaa8a89fea9bf36368..a5b14d4169aef58347e9fcc10cb4d894439a66bf 100644
--- a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
+++ b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
@@ -82,7 +82,7 @@ OpenHarmony LiteOS-A内核的NFS文件系统指的是NFS的客户端,NFS客户
[2]Reply from 10.67.212.178: time=1ms TTL=63
[3]Reply from 10.67.212.178: time=1ms TTL=63
--- 10.67.212.178 ping statistics ---
-3. packets transmitted, 4 received, 0 loss
+ packets transmitted, 4 received, 0 loss
客户端NFS初始化,运行命令:
@@ -124,7 +124,7 @@ OpenHarmony LiteOS-A内核的NFS文件系统指的是NFS的客户端,NFS客户
>
> 至此,NFS客户端设置完毕。NFS文件系统已成功挂载。
-4. 利用NFS共享文件
+3. 利用NFS共享文件
在NFS服务器下新建目录dir,并保存。在OpenHarmony内核下运行ls命令:
diff --git a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md
index 5f2ea549f7be468f4780dd7c4db0c96a8690b4e0..427cc10737c384630f2d0235131c5e7b7c8e5115 100644
--- a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md
+++ b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md
@@ -1,13 +1,424 @@
# 支持的文件系统
+## FAT
+### 基本概念
-- **[FAT](kernel-small-bundles-fs-support-fat.md)**
+FAT文件系统是File Allocation Table(文件配置表)的简称,主要包括DBR区、FAT区、DATA区三个区域。其中,FAT区各个表项记录存储设备中对应簇的信息,包括簇是否被使用、文件下一个簇的编号、是否文件结尾等。FAT文件系统有FAT12、FAT16、FAT32等多种格式,其中,12、16、32表示对应格式中FAT表项的比特数,它们同时也限制了文件系统中的最大文件大小。FAT文件系统支持多种介质,特别在可移动存储介质(U盘、SD卡、移动硬盘等)上广泛使用,使嵌入式设备和Windows、Linux等桌面系统保持很好的兼容性,方便用户管理操作文件。
-- **[JFFS2](kernel-small-bundles-fs-support-jffs2.md)**
+OpenHarmony内核支持FAT12、FAT16与FAT32三种格式的FAT文件系统,具有代码量小、资源占用小、可裁切、支持多种物理介质等特性,并且与Windows、Linux等系统保持兼容,支持多设备、多分区识别等功能。OpenHarmony内核支持硬盘多分区,可以在主分区以及逻辑分区上创建FAT文件系统。
-- **[NFS](kernel-small-bundles-fs-support-nfs.md)**
-- **[Ramfs](kernel-small-bundles-fs-support-ramfs.md)**
+### 运行机制
-- **[Procfs](kernel-small-bundles-fs-support-procfs.md)**
\ No newline at end of file
+FAT文件系统设计与物理布局的相关文档在互联网上非常丰富,请开发者自行搜索查看。
+
+OpenHarmony LiteOS-A内核通过Bcache提升FAT文件系统性能,Bcache是block cache的简称。当发生读写时,Bcache会缓存读写扇区附近的扇区,以减少I/O次数,提高性能。Bcache的基本缓存单位为block,每个block大小一致(默认有28个block,每个block缓存64个扇区的数据)。当Bcache脏块率(脏扇区数/总扇区数)达到阈值时,会触发写回;如果脏块率未达到阈值,则不会将缓存数据写回磁盘。如果需要保证数据写回,开发者应当调用sync和fsync触发写回。FAT文件系统的部分接口也会触发写回操作(如close、umount等),但开发者不应当基于这些接口触发写回。
+
+
+### 开发指导
+
+
+ **开发流程**
+
+基本使用流程为挂载→操作→卸载。
+
+SD卡或MMC的设备名为mmcblk[x]p[y],文件系统类型为“vfat”。
+
+示例:
+
+
+```
+mount("/dev/mmcblk0p0", "/mnt", "vfat", 0, NULL);
+```
+
+>  **说明:**
+> - FAT文件系统中,单个文件不能大于4 GiB。
+>
+> - 当有两个SD卡插槽时,卡0和卡1不固定,先插上的为卡0,后插上的为卡1。
+>
+> - 当多分区功能打开,存在多分区的情况下,卡0注册的设备节点/dev/mmcblk0(主设备)和/dev/mmcblk0p0(次设备)是同一个设备,禁止对主设备进行操作。
+>
+> - 为避免SD卡使用异常或内存泄漏,SD卡使用过程中拔卡,用户必须先关闭正处于打开状态的文件和目录,并且卸载挂载节点。
+>
+> - 在format操作之前,需要首先umount挂载点。
+>
+> - 当Bcache功能生效时,需要注意:
+> - 当mount函数的入参为MS_NOSYNC时,FAT不会主动将cache的内容写回存储器件。FAT的如下接口(open、close、 unlink、rename、mkdir、rmdir、truncate)不会自动进行sync操作,速度可以提升,但是需要上层主动调用sync来进行数据同步,否则可能会数据丢失。
+>
+> - Bcache有定时写回功能。在menuconfig中开启LOSCFG_FS_FAT_CACHE_SYNC_THREAD选项,打开后系统会创建一个任务定时写回Bcache中的数据,默认每隔5秒检查Bcache中脏数据块比例,超过80%时进行sync操作,将Bcache中的脏数据全部写回磁盘。任务优先级、刷新时间间隔以及脏数据块比例的阈值可分别通过接口LOS_SetSyncThreadPrio、 LOS_SetSyncThreadInterval和LOS_SetDirtyRatioThreshold设置。
+> - 当前cache的默认大小为28个块,每个块64个扇区。
+
+## JFFS2
+
+
+### 基本概念
+
+JFFS2是Journalling Flash File System Version 2(日志文件系统)的缩写,是针对MTD设备的日志型文件系统。
+
+OpenHarmony内核的JFFS2主要应用于NOR FLASH闪存,其特点是:可读写、支持数据压缩、提供了崩溃/掉电安全保护、提供“写平衡”支持等。闪存与磁盘介质有许多差异,直接将磁盘文件系统运行在闪存设备上,会导致性能和安全问题。为解决这一问题,需要实现一个特别针对闪存的文件系统,JFFS2就是这样一种文件系统。
+
+
+### 运行机制
+
+关于JFFS2文件系统的在存储设备上的实际物理布局,及文件系统本身的规格说明,请参考JFFS2的[官方规格说明文档](https://sourceware.org/jffs2/)。
+
+这里仅列举几个对开发者和使用者会有一定影响的JFFS2的重要机制/特征:
+
+1. Mount机制及速度问题:按照JFFS2的设计,所有的文件会按照一定的规则,切分成大小不等的节点,依次存储到flash设备上。在mount流程中,需要获取到所有的这些节点信息并缓存到内存里。因此,mount速度和flash设备的大小和文件数量的多少成线性比例关系。这是JFFS2的原生设计问题,对于mount速度非常介意的用户,可以在内核编译时开启“Enable JFFS2 SUMMARY”选项,可以极大提升mount的速度。这个选项的原理是将mount需要的信息提前存储到flash上,在mount时读取并解析这块内容,使得mount的速度变得相对恒定。这个实际是空间换时间的做法,会消耗8%左右的额外空间。
+
+2. 写平衡的支持:由于flash设备的物理属性,读写都只能基于某个特定大小的“块”进行,为了防止某些特定的块磨损过于严重,在JFFS2中需要对写入的块进行“平衡”的管理,保证所有的块的写入次数都是相对平均的,进而保证flash设备的整体寿命。
+
+3. GC(garbage collection)机制:在JFFS2里发生删除动作,实际的物理空间并不会立即释放,而是由独立的GC线程来做空间整理和搬移等GC动作,和所有的GC机制一样,在JFFS2里的GC会对瞬时的读写性能有一定影响。另外,为了有空间能被用来做空间整理,JFFS2会对每个分区预留3块左右的空间,这个空间是用户不可见的。
+
+4. 压缩机制:当前使用的JFFS2,底层会自动的在每次读/写时进行解压/压缩动作,实际IO的大小和用户请求读写的大小并不会一样。特别在写入时,不能通过写入大小来和flash剩余空间的大小来预估写入一定会成功或者失败。
+
+5. 硬链接机制:JFFS2支持硬链接,底层实际占用的物理空间是一份,对于同一个文件的多个硬连接,并不会增加空间的占用;反之,只有当删除了所有的硬链接时,实际物理空间才会被释放。
+
+
+### 开发指导
+
+对于基于JFFS2和nor flash的开发,总体而言,与其他文件系统非常相似,因为都有VFS层来屏蔽了具体文件系统的差异,对外接口体现也都是标准的POSIX接口。
+
+对于整个裸nor flash设备而言,没有集中的地方来管理和记录分区的信息。因此,需要通过其他的配置方式来传递这部分信息(当前使用的方式是在烧写镜像的时候,使用bootargs参数配置的),然后在代码中调用相应的接口来添加分区,再进行挂载动作。
+
+**制作JFFS2文件系统镜像**
+
+使用mkfs.jffs2工具,制作镜像默认命令如下。页大小默认为4KiB,eraseblock大小默认64KiB。若实际参数与下面不同时,修改相应参数。
+
+
+```
+./mkfs.jffs2 -d rootfs/ -o rootfs.jffs2
+```
+
+ **表1** 指令含义表(更详细的介绍可以通过mkfs.jffs2 --help来查看)
+
+| 指令 | 含义 |
+| -------- | -------- |
+| -s | 页大小,不指定默认为4KiB |
+| -e | eraseblock大小,不指定默认为64KiB |
+| -p | 镜像大小。在镜像文件后面,用0xFF填充至指定大小,不指定则用0xFF填充至eraseblock对齐。 |
+| -d | 要制作成文件系统镜像的源目录 |
+| -o | 要制成的镜像名称 |
+
+**挂载JFFS2分区**
+
+调用int mount(const char \*source, const char \*target, const char \*filesystemtype, unsigned long mountflags, const void \*data)函数实现设备节点和挂载点的挂载。
+
+该函数有五个参数,第一个参数const char \*source,表示设备节点,第二个参数const char \*target表示挂载点。第三个参数 const char \*filesystemtype,表示文件系统类型。
+
+最后两个参数unsigned long mountflags和const void \*data表示挂载标志和数据,默认为0和NULL;这一操作也可以在Shell中使用mount命令实现,最后两个参数不需要用户给出。
+
+运行命令:
+
+
+```
+OHOS # mount /dev/spinorblk1 /jffs1 jffs2
+```
+
+将从串口得到如下回应信息,表明挂载成功。
+
+
+```
+OHOS # mount /dev/spinorblk1 /jffs1 jffs2
+mount OK
+```
+
+挂载成功后,用户就能对norflash进行读写操作。
+
+**卸载JFFS2分区**
+
+调用int umount(const char \*target)函数卸载分区,只需要正确给出挂载点即可。
+
+运行命令:
+
+
+```
+OHOS # umount /jffs1
+```
+
+将从串口得到如下回应信息,表明卸载成功。
+
+
+```
+OHOS # umount /jffs1
+umount ok
+```
+## NFS
+
+
+### 基本概念
+
+NFS是Network File System(网络文件系统)的缩写。它最大的功能是可以通过网络,让不同的机器、不同的操作系统彼此分享其他用户的文件。因此,用户可以简单地将它看做是一个文件系统服务,在一定程度上相当于Windows环境下的共享文件夹。
+
+
+### 运行机制
+
+OpenHarmony LiteOS-A内核的NFS文件系统指的是NFS的客户端,NFS客户端能够将远程的NFS服务端分享的目录挂载到本地的机器中,运行程序和共享文件,但不占用当前系统的存储空间,在本地端的机器看起来,远程服务端的目录就好像是自己的一个磁盘一样。
+
+
+### 开发指导
+
+1. 搭建NFS服务器
+
+ 这里以Ubuntu操作系统为例,说明服务器端设置步骤。
+
+ - 安装NFS服务器软件。
+
+ 设置好Ubuntu系统的下载源,保证网络连接好的情况下执行:
+
+
+ ```
+ sudo apt-get install nfs-kernel-server
+ ```
+
+ - 创建用于挂载的目录并设置完全权限
+
+
+ ```
+ mkdir -p /home/sqbin/nfs
+ sudo chmod 777 /home/sqbin/nfs
+ ```
+
+ - 设置和启动NFS server。
+
+ 修改NFS配置文件/etc/exports,添加如下一行:
+
+
+ ```
+ /home/sqbin/nfs *(rw,no_root_squash,async)
+ ```
+
+ 其中/home/sqbin/nfs是NFS共享的根目录。
+
+ 执行以下命令启动NFS server:
+
+
+ ```
+ sudo /etc/init.d/nfs-kernel-server start
+ ```
+
+ 执行以下命令重启NFS server:
+
+
+ ```
+ sudo /etc/init.d/nfs-kernel-server restart
+ ```
+
+2. 设置单板为NFS客户端
+
+ 本指导中的NFS客户端指运行OpenHarmony内核的设备。
+
+ - 硬件连接设置。
+
+ OpenHarmony内核设备连接到NFS服务器的网络。设置两者IP,使其处于同一网段。比如,设置NFS服务器的IP为10.67.212.178/24,设置OpenHarmony内核设备IP为
+ 10.67.212.3/24,注意:此IP为内网私有IP地址,用户使用时有差异,以用户实际IP为准。
+
+ OpenHarmony内核设备上的IP信息可通过ifconfig命令查看。
+
+ - 启动网络,确保单板到NFS服务器之间的网络通畅。
+
+ 启动以太网或者其他类型网络,使用ping命令检查到服务器的网络是否通畅。
+
+
+ ```
+ OHOS # ping 10.67.212.178
+ [0]Reply from 10.67.212.178: time=1ms TTL=63
+ [1]Reply from 10.67.212.178: time=0ms TTL=63
+ [2]Reply from 10.67.212.178: time=1ms TTL=63
+ [3]Reply from 10.67.212.178: time=1ms TTL=63
+ --- 10.67.212.178 ping statistics ---
+ packets transmitted, 4 received, 0 loss
+
+ 客户端NFS初始化,运行命令:
+
+
+ ```
+ OHOS # mkdir /nfs
+ OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
+ ```
+
+ 将从串口得到如下回应信息,表明初始化NFS客户端成功。
+
+
+ ```
+ OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
+ Mount nfs on 10.67.212.178:/home/sqbin/nfs, uid:1011, gid:1000
+ Mount nfs finished.
+ ```
+
+ 该命令将服务器10.67.212.178上的/home/sqbin/nfs目录挂载到OpenHarmony内核设备上的/nfs上。
+
+ >  **说明:**
+ > 本例默认nfs server已经配置可用,即示例中服务器10.67.212.178上的/home/sqbin/nfs已配置可访问。
+ >
+ > mount命令的格式为:
+ >
+ >
+ > ```
+ > mount nfs
+ > ```
+ >
+ > 其中“SERVER_IP”表示服务器的IP地址;“SERVER_PATH”表示服务器端NFS共享目录路径;“CLIENT_PATH”表示设备上的NFS路径,“nfs”表示客户端要挂载的路径,可以根据自己需要替换。
+ >
+ > 如果不想有NFS访问权限限制,可以在Linux命令行将NFS根目录权限设置成777:
+ >
+ >
+ > ```
+ > chmod -R 777 /home/sqbin/nfs
+ > ```
+ >
+ > 至此,NFS客户端设置完毕。NFS文件系统已成功挂载。
+
+3. 利用NFS共享文件
+
+ 在NFS服务器下新建目录dir,并保存。在OpenHarmony内核下运行ls命令:
+
+ ```
+ OHOS # ls /nfs
+ ```
+
+ 则可从串口得到如下回应:
+
+
+ ```
+ OHOS # ls /nfs
+ Directory /nfs:
+ drwxr-xr-x 0 u:0 g:0 dir
+ ```
+
+ 可见,刚刚在NFS服务器上新建的dir目录已同步到客户端(OpenHarmony内核系统)的/nfs目录,两者保持同步。
+
+ 同样地,在客户端(OpenHarmony内核系统)上创建文件和目录,在NFS服务器上也可以访问,读者可自行体验。
+
+ >  **说明:**
+ > 目前,NFS客户端仅支持NFS v3部分规范要求,因此对于规范支持不全的服务器,无法完全兼容。在开发测试过程中,建议使用Linux的NFS server,其对NFS支持很完善。
+
+## Ramfs
+
+
+### 基本概念
+
+RAMFS是一个可动态调整大小的基于RAM的文件系统。RAMFS没有后备存储源。向RAMFS中进行的文件写操作也会分配目录项和页缓存,但是数据并不写回到任何其他存储介质上,掉电后数据丢失。
+### 运行机制
+RAMFS文件系统把所有的文件都放在 RAM 中,所以读/写操作发生在RAM中,可以用RAMFS来存储一些临时性或经常要修改的数据,例如/tmp和/var目录,这样既避免了对存储器的读写损耗,也提高了数据读写速度。
+### 开发指导
+挂载:
+```
+mount(NULL, "/dev/shm", "ramfs", 0, NULL)
+```
+创建目录:
+```
+mkdir(pathname, mode)
+```
+创建文件:
+```
+open(pathname, O_NONBLOCK | O_CREAT | O_RDWR, mode)
+```
+读取目录:
+```
+dir = opendir(pathname)
+ptr = readdir(dir)
+closedir(dir)
+```
+删除文件:
+```
+unlink(pathname)
+```
+删除目录:
+```
+rmdir(pathname)
+```
+去挂载:
+```
+umount("/dev/shm")
+```
+>  **注意:**
+> - RAMFS只能挂载一次,一次挂载成功后,后面不能继续挂载到其他目录。
+>
+> - RAMFS属于调测功能,默认配置为关闭,正式产品中不要使用该功能。
+
+## Procfs
+
+
+### 基本概念
+
+procfs是进程文件系统的简称,是一种虚拟文件系统,他用文件的形式,展示进程或其他系统信息。相比调用接口的方式获取信息,以文件操作的方式获取系统信息更为方便。
+
+
+### 运行机制
+
+OpenHarmony内核中,procfs在开机时会自动挂载到/proc目录下,仅支持内核模块创建文件节点来提供查询服务。
+
+
+### 开发指导
+
+procfs文件的创建无法使用一般的文件系统接口,需要使用ProcMkdir接口创建目录,使用CreateProcEntry接口创建文件。文件节点功能的开发就是实现read和write函数的钩子挂到CreateProcEntry创建的文件中。当用户使用读写procfs的文件时,就会调用到钩子函数来实现自定义的功能。
+
+
+编程实例
+
+下面我们以创建/proc/hello/world文件为例,实现如下功能:
+
+1.在/proc/hello/world位置创建一个文件
+
+2.当读文件内容时,返回"HelloWorld!"
+
+3.当写文件内容时,打印写入的内容
+
+
+```
+#include "proc_fs.h"
+
+static int TestRead(struct SeqBuf *buf, void *arg)
+{
+ LosBufPrintf(buf, "Hello World!\n"); /* 将数据打印到buffer中,这个buffer中的数据会返回到read的结果中 */
+ return 0;
+}
+
+static int TestWrite(struct ProcFile *pf, const char *buffer, size_t buflen, loff_t *ppos)
+{
+ if ((buffer == NULL) || (buflen <= 0)) {
+ return -EINVAL;
+ }
+
+ PRINTK("your input is: %s\n", buffer); /* 注意和上面的read接口区别,这是对write接口输入命令的反馈,这个打印只会打印到控制台 */
+ return buflen;
+}
+static const struct ProcFileOperations HELLO_WORLD_OPS = {
+ .read = TestRead,
+ .write = TestWrite,
+};
+
+void HelloWorldInit(void)
+{
+ /* 创建hello目录 */
+ struct ProcDirEntry *dir = ProcMkdir("hello", NULL);
+ if (dir == NULL) {
+ PRINT_ERR("create dir failed!\n");
+ return;
+ }
+
+ /* 创建world文件 */
+ struct ProcDirEntry *entry = CreateProcEntry("world", 0, dir);
+ if (entry == NULL) {
+ PRINT_ERR("create entry failed!\n");
+ return;
+ }
+
+ /* 将自定义的read和write钩子挂到文件中 */
+ entry->procFileOps = &HELLO_WORLD_OPS;
+}
+```
+
+**结果验证**
+
+启动后在shell输入如下命令
+
+
+```
+OHOS # cat /proc/hello/world
+OHOS # Hello World!
+OHOS # echo "yo" > /proc/hello/world
+OHOS # your input is: yo
+```
diff --git a/zh-cn/device-dev/kernel/kernel-small-debug-user.md b/zh-cn/device-dev/kernel/kernel-small-debug-user.md
index 3a57c7c48ce1b8719a750f8b53bf2a01351b8e4f..cb61d4fe832b15e30df9d1f19963be0a811eb68d 100644
--- a/zh-cn/device-dev/kernel/kernel-small-debug-user.md
+++ b/zh-cn/device-dev/kernel/kernel-small-debug-user.md
@@ -1,11 +1,552 @@
# 用户态内存调测
+## 基本概念
+Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、踩内存分析以及backtrace功能等维测手段,可以提高用户态内存相关问题的定位效率。
-- **[基本概念](kernel-small-debug-user-concept.md)**
-- **[运行机制](kernel-small-debug-user-function.md)**
+采用了对malloc/free接口进行插桩,保存关键节点信息,然后程序在申请和释放内存时进行内存节点完整性校验,最后在程序结束时通过统计节点信息得到内存统计信息并根据统计信息判断内存是否泄漏的设计思想
-- **[使用指导](kernel-small-debug-user-guide.md)**
+## 运行机制
+
+
+### 内存泄漏检查
+
+对于每个进程,内存调测模块维护了128个链表(当前系统的线程最大数量为128个),每个链表的索引为线程ID。
+
+申请内存时:保存关键信息到内存节点控制块,根据当前线程ID将内存节点控制块挂到对应链表;
+
+释放内存时:根据需要释放的内存地址匹配内存节点控制块并将该控制块删除。
+
+ **图1** 堆内存节点信息链表
+
+ 
+
+申请内存时,返回地址会被保存到LR寄存器中。进程运行过程中,系统会在内存节点控制块中添加疑似泄漏点对应的lr等信息。如下图所示:
+
+ **图2** 堆内存节点信息
+
+ 
+
+其中,TID表示线程ID;PID表示进程ID;ptr表示申请的内存地址;size表示申请的内存大小;lr[n]表示函数调用栈地址,变量n可以根据具体场景的需要进行配置。
+
+释放内存时,将free等接口的入参指针与node的ptr字段进行匹配,如果相同则删除该内存节点控制块信息。
+
+用户通过串口或文件等方式,将各个进程内存调测信息导出,利用addr2line工具将导出的信息转换成导致内存泄漏的代码行,便可以解决内存泄露问题。
+
+ **图3** 泄漏点代码行定位流程
+
+ 
+
+
+### 堆内存统计
+
+用户态线程堆内存使用统计具有一定的实际意义,统计线程申请的堆内存占比,为用户程序的内存使用优化提供数据支持。用户态堆内存统计模块主要涉及的接口为malloc和free。如上图所示,每个进程维护128个链表,链表索引即线程ID,申请内存时系统将ptr和size信息记录在内存节点控制块中并将节点控制块挂在以线程ID为头信息的链表上,堆内存释放时根据ptr从对应的链表上移除相应的堆内存块信息;同时计算出当前线程所持有的堆内存总的使用量,并更新当前进程的堆内存使用量和堆内存使用峰值。
+
+
+### 内存完整性检查
+
+- 使用malloc申请内存(小于等于0x1c000bytes时通过堆分配算法分配)
+ 用户程序申请堆内存时,在堆内存节点处添加校验值等信息,如果校验值异常,则很有可能是前一块堆内存使用越界导致的(目前无法识别校验值被野指针破坏的场景)。在内存申请、释放时校验内存节点校验值的正确性,若内存节点被破坏,校验失败时则输出tid、pid及当前被踩节点前一块堆内存申请时保存的调用栈信息,通过addr2line工具可获得具体的代码行信息,辅助用户解决问题。
+
+ **图4** node节点头信息添加校验值
+
+ 
+
+ free堆内存时,不会立即把该内存块释放掉,而是在内存中写入魔术数字0xFE,并放到free队列中(保证在一定时间内不会再被malloc函数分配),当有野指针或use-after-free的情况对该内存进行读取的操作时,能够发现数据异常,但是对于写操作则无法判断出来。
+
+ **图5** free流程图
+
+ 
+
+- 使用malloc申请内存(大于0x1c000bytes时通过mmap申请)
+ 当malloc通过mmap申请大块内存时,在返回给用户使用的内存区间头和尾分别多申请一个页,一个页PAGE_SIZE当前为0x1000,这两个页分别通过mprotect接口设置权限为PROT_NONE(无可读可写权限),可以有效防止内存越界读写问题:越界读写数据时由于无读写权限而导致用户程序异常,根据异常调用栈信息可找到相应的代码逻辑。
+
+ **图6** malloc通过mmap机制申请内存的内存布局
+
+ 
+
+### 使用指导
+#### 接口说明
+
+
+ **表1** 内存调测功能
+
+| 接口名 | 描述 |
+| -------- | -------- |
+| mem_check_init | 初始化内存检测模块。 |
+| watch_mem | 获取线程级堆内存使用信息。 |
+| check_leak | 检查是否有堆内存泄漏。 |
+| check_heap_integrity | 检查堆内存的完整性。 |
+| backtrace | 获取调用栈地址信息。 |
+| backtrace_symbols | 根据地址信息获取符号信息。 |
+| print_trace | 输出函数调用栈信息。 |
+
+
+ **表2** 调用栈回溯功能
+
+| 接口名 | 描述 |
+| -------- | -------- |
+| backtrace | 获取调用栈地址信息。 |
+| backtrace_symbols | 根据地址信息获取符号信息。 |
+| print_trace | 输出函数调用栈信息。 |
+
+### 使用说明
+
+
+编译OpenHarmony工程时默认编译的是debug版本,即libc库已经集成内存调测相关的接口实现,用户可以根据具体需要决定是否使能内存调测功能。
+
+
+堆内存调测功能提供两种方式供用户使用:接口调用及命令行参数。
+
+
+- 接口调用:优点是可以较精确的检查某一段代码逻辑的堆内存相关信息,缺点是需要修改用户代码。
+
+- 命令行参数:优点是无需修改用户代码,缺点是无法精确的校验某一段逻辑的堆内存信息。
+
+
+>  **说明:**
+> 内存调测功能使能后,进程退出时会默认进行一次堆内存泄漏和堆内存完整性检查。内存调测功能未使能时,堆内存统计、堆内存泄漏检查、堆内存完整性校验功能不会开启,调用相关调测接口无响应。
+
+
+- **[接口调用方式](kernel-small-debug-user-guide-use-api.md)**
+
+- **[命令行参数方式](kernel-small-debug-user-guide-use-cli.md)**
+
+
+
+
+#### 接口调用方式
+
+
+##### 示例代码
+
+代码功能:显式调用调测模块的相关接口对用户代码进行内存校验。
+
+
+```
+#include
+#include
+#include
+#include // 包含提供内存调测接口声明的头文件
+
+#define MALLOC_LEAK_SIZE 0x300
+
+void func(void) {
+ char *ptr = malloc(MALLOC_LEAK_SIZE);
+ memset(ptr, '3', MALLOC_LEAK_SIZE);
+}
+
+int main()
+{
+ mem_check_init(NULL); // 通过串口输出内存调测信息,必须在用户程序第一次申请堆内存之前调用(一般在main函数入口调用),否则调测信息不准确。
+ // mem_check_init("/storage/mem_debug.txt"); // 内存调测信息输出到/storage/mem_debug.txt文件中,如果该文件创建失败,则信息通过串口输出。
+ char *ptr = malloc(MALLOC_LEAK_SIZE);
+ memset(ptr, '1', MALLOC_LEAK_SIZE);
+
+ watch_mem(); // 在当前代码逻辑处查看线程级内存统计信息。
+ func();
+ check_heap_integrity(); // 检查堆内存节点完整性。
+ check_leak(); // 在当前代码逻辑处检查堆内存是否泄漏(一般在程序退出之前校验比较准确,若在malloc和free调用逻辑之间做校验,则结果不准确)。
+ return 0;
+}
+```
+
+
+##### 编译
+
+
+```
+$ clang -o mem_check mem_check.c -funwind-tables -rdynamic -g -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos --sysroot=/home//directory/out/hispark_taurus/ipcamera_hispark_taurus/sysroot $(clang -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos -print-file-name=libunwind.a)
+```
+
+
+>  **说明:**
+> - 本编译示例基于将编译器的路径写入环境变量中,即.bashrc文件中。
+>
+> - 编译用户程序及所需的lib库时,需要添加编译选项-funwind-tables,-rdynamic,-g,用于栈回溯。
+>
+> - -mfloat-abi=softfp,-mcpu=cortex-a7,-mfpu=neon-vfpv4编译选项用于指定具体的芯片架构、浮点数计算优化、fpu,与具体的libc库使用的编译选项保持一致,否则链接时可能出现找不到libc库文件。
+>
+> - -target arm-liteos用于指定编译器相关库文件路径。
+>
+> - --sysroot=/home/<user-name>/directory/out/hispark_taurus/ipcamera_hispark_taurus/sysroot用于指定编译器库文件搜索根目录,假设OpenHarmony工程代码存放路径为/home/<user-name>/directory。其中out/hispark_taurus/ipcamera_hispark_taurus路径为在编译时,hb set命令指定的具体产品,本示例选择的是ipcamera_hispark_taurus产品。
+>
+> - $(clang -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos -print-file-name=libunwind.a)用于指定相应的unwind库的路径。
+
+
+##### 调测信息
+
+
+```
+OHOS # ./mem_check
+OHOS #
+==PID:4== Heap memory statistics(bytes): // 堆内存统计信息
+ [Check point]: // check点调用栈
+ #00: [0x86c] -> mem_check
+ #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+ [TID: 18, Used: 0x320] // 18号线程堆内存占用,当前进程仅一个线程
+
+==PID:4== Total heap: 0x320 byte(s), Peak: 0x320 byte(s)
+
+Check heap integrity ok! // 堆内存完整性检查
+
+==PID:4== Detected memory leak(s): // 内存泄漏信息及调用栈
+ [Check point]:
+ #00: [0x2da4c] -> /lib/libc.so
+ #01: [0x878] -> mem_check
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x850] -> mem_check
+ #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x810] -> mem_check
+ #01: [0x870] -> mem_check
+ #02: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+
+==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2da4c] -> /lib/libc.so
+ #01: [0x111ec] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x850] -> mem_check
+ #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x810] -> mem_check
+ #01: [0x870] -> mem_check
+ #02: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+
+Check heap integrity ok!
+```
+
+
+##### 调用栈解析
+
+提供parse_mem_info.sh脚本可以对调用栈进行解析,解析脚本存放的路径:kernel/liteos_a/tools/scripts/parse_memory/parse_mem_info.sh。利用脚本可以将相应的调测信息转换成具体的源码行号,如下命令所示,mem_debug.txt保存的是内存调测信息,elf1、elf2等文件是需要解析的elf文件。
+
+
+```
+$ ./parse_mem_info.sh mem_debug.txt elf1 elf2 elf3 ...
+```
+
+例如:
+
+
+```
+$ ./parse_mem_info.sh mem_debug.txt mem_check
+Compiler is [gcc/llvm]: llvm
+Now using addr2line ...
+
+==PID:4== Heap memory statistics(bytes):
+ [Check point]:
+ #00: [0x86c] at /usr1/xxx/TEST_ELF/mem_check.c:22
+ #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+ [TID: 18, Used: 0x320]
+
+==PID:4== Total heap: 0x320 byte(s), Peak: 0x320 byte(s)
+
+Check heap integrity ok!
+
+==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2da4c] -> /lib/libc.so
+ #01: [0x878] at /usr1/xxx/TEST_ELF/mem_check.c:28
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x850] at /usr1/xxx/TEST_ELF/mem_check.c:17
+ #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x810] at /usr1/xxx/TEST_ELF/mem_check.c:9
+ #01: [0x870] at /usr1/xxx/TEST_ELF/mem_check.c:24
+ #02: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so
+
+==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+```
+
+#### 命令行参数方式
+
+
+对用户态进程进行内存相关的检查时,除了接口调用方式还可以通过命令行方式进行内存统计、内存泄漏或内存完整性检查。
+
+```
+--mwatch:初始化内存调测功能,注册信号。内存调测信息将从串口输出;
+--mrecord :初始化内存调测功能,注册信号。内存调测信息将保存至f_path文件,若f_path创建失败,则内存调测信息将从串口输出
+```
+
+
+在待调测的进程未退出时可使用信号机制获取对应信息:
+
+```
+kill -35 # 查看线程级堆内存占用
+kill -36 # 检查是否存在堆内存泄漏
+kill -37 # 检查堆内存头节点是否完整
+```
+
+
+##### 示例代码
+
+代码功能:构造内存问题利用命令行方式进行内存调测。
+
+
+```
+#include
+#include
+#include
+
+#define MALLOC_LEAK_SIZE 0x300
+
+void func(void) {
+ char *ptr = malloc(MALLOC_LEAK_SIZE);
+ memset(ptr, '3', MALLOC_LEAK_SIZE);
+}
+
+int main()
+{
+ char *ptr = malloc(MALLOC_LEAK_SIZE);
+ memset(ptr, '1', MALLOC_LEAK_SIZE);
+ func();
+ while (1);
+}
+```
+
+
+##### 编译
+
+参考[接口调用一节](../kernel/kernel-small-debug-user-guide-use-api.md#编译)。
+
+
+##### 使用mwatch参数命令
+
+
+```
+OHOS # ./mem_check --mwatch // 利用task命令可以查到mem_check进程的pid为4
+OHOS #
+OHOS # kill -35 4 // 查看堆内存统计信息
+OHOS #
+==PID:4== Heap memory statistics(bytes):
+ [Check point]:
+ #00: [0x58dfc] -> /lib/libc.so
+
+ [TID: 18, Used: 0x640]
+
+==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s)
+
+OHOS # kill -36 4 // 检查是否存在堆内存泄漏
+OHOS #
+==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2da4c] -> /lib/libc.so
+ #01: [0x58dfc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x724] -> mem_check
+ #01: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x6ec] -> mem_check
+ #01: [0x740] -> mem_check
+ #02: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so
+
+==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+
+OHOS # kill -37 4 // 检查堆内存头节点的完整性
+OHOS #
+Check heap integrity ok!
+```
+
+
+##### 调用栈解析
+
+将调测信息保存至test.txt文件中,利用脚本进行解析,获取内存泄漏的具体行号。
+
+
+```
+$ ./parse_mem_info.sh test.txt mem_check
+Compiler is [gcc/llvm]: llvm
+Now using addr2line ...
+
+==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2da4c] -> /lib/libc.so
+ #01: [0x58dfc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x724] at /usr1/xxx/TEST_ELF/mem_check.c:14
+ #01: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x6ec] at /usr1/xxx/TEST_ELF/mem_check.c:8
+ #01: [0x740] at /usr1/xxx/TEST_ELF/mem_check.c:19
+ #02: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so
+
+==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+```
+
+
+##### 使用mrecord参数命令
+
+1. 执行用户程序并指定记录内存调测信息的文件路径
+
+ ```
+ OHOS # ./mem_check --mrecord /storage/check.txt
+ ```
+
+2. 利用kill -35 <pid>统计内存信息,该信息将会输出到文件中,使用cat命令查看
+
+ ```
+ OHOS # kill -35 4
+ OHOS # Memory statistics information saved in /storage/pid(4)_check.txt
+
+ OHOS # cat /storage/pid(4)_check.txt
+
+ ==PID:4== Heap memory statistics(bytes):
+ [Check point]:
+ #00: [0x5973c] -> /lib/libc.so
+
+ [TID: 18, Used: 0x640]
+
+ ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s)
+ ```
+
+3. 利用kill -36 <pid>校验内存完整性,该信息将会输出到文件中,使用cat命令查看
+
+ ```
+ OHOS # kill -36 4
+ OHOS # Leak check information saved in /storage/pid(4)_check.txt
+
+ OHOS # cat /storage/pid(4)_check.txt
+
+ ==PID:4== Heap memory statistics(bytes):
+ [Check point]:
+ #00: [0x5973c] -> /lib/libc.so
+
+ [TID: 18, Used: 0x640]
+
+ ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s)
+
+ ==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2e38c] -> /lib/libc.so
+ #01: [0x5973c] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x724] -> mem_check
+ #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x6ec] -> mem_check
+ #01: [0x740] -> mem_check
+ #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so
+
+ ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+ ```
+
+4. 利用kill -9 <pid>杀掉当前进程,进程退出后会默认校验内存完整性,该信息将会输出到文件中,使用cat命令查看
+
+ ```
+ OHOS # kill -9 4
+ OHOS # Leak check information saved in /storage/pid(4)_check.txt
+
+ Check heap integrity ok!
+
+ OHOS # cat /storage/pid(4)_check.txt
+ OHOS #
+ ==PID:4== Heap memory statistics(bytes):
+ [Check point]:
+ #00: [0x5973c] -> /lib/libc.so
+
+ [TID: 18, Used: 0x640]
+
+ ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s)
+
+ ==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2e38c] -> /lib/libc.so
+ #01: [0x5973c] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x724] -> mem_check
+ #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x6ec] -> mem_check
+ #01: [0x740] -> mem_check
+ #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so
+
+ ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+
+ ==PID:4== Detected memory leak(s):
+ [Check point]:
+ #00: [0x2e38c] -> /lib/libc.so
+ #01: [0x11b2c] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x724] -> mem_check
+ #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so
+
+ [TID:18 Leak:0x320 byte(s)] Allocated from:
+ #00: [0x6ec] -> mem_check
+ #01: [0x740] -> mem_check
+ #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so
+
+ ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s).
+ ```
+
+>  **说明:**
+> 上述连续记录的信息会逐步追加到初始化时所指定的文件中,故最后cat文件时,文件中还包含历史记录的信息内容。
+## 常见问题
+
+
+### UAF(Use after free)
+
+- 申请小块内存(不大于0x1c000字节)
+ free之后:
+
+ 读操作:读取free之后的内存大概率是魔术数字(0xFEFEFEFE)
+
+ >  **说明:**
+ > free之后的堆内存不会立即释放进堆内存池,会先放至固定长度的队列中,并置魔术数字0xFE,队列满后会将先放至队列中的内存块释放进堆内存池
+
+ 写操作:无法校验。
+
+
+- 申请大块内存(大于0x1c000)
+ 堆内存由malloc通过调用mmap接口申请,free之后若仍访问该内存,则用户程序异常(该内存区间已被unmap)。
+
+
+### Double free
+
+Double free时,用户程序将会异常退出。
+
+
+### 堆内存节点被踩
+
+- 申请小块内存(不大于0x1c000)
+ 堆内存节点被踩时,用户程序将会异常退出,并输出破坏被踩节点的可能的堆内存申请调用栈,对于野指针踩内存情况无法校验出来。例如用户程序mem_check中存在堆内存越界踩的情况,利用命令行方式可以获得踩内存的可能的具体位置。
+
+
+ ```
+ OHOS # ./mem_check --mwatch
+ OHOS #
+ ==PID:6== Memory integrity information:
+ [TID:28 allocated addr: 0x272e1ea0, size: 0x120] The possible attacker was allocated from:
+ #00: [0x640e8] -> /lib/libc.so
+ #01: [0x21d0] -> mem_check
+ ```
+
+ 可以通过调用栈解析脚本对调用栈信息进行解析。
+
+- 申请大块内存(大于0x1c000)
+
+ 堆内存由malloc通过mmap接口申请,申请得到的堆内存块前后各置一个size为PAGE_SIZE大小的区间,设置无读写权限,读写操作会触发用户程序异常。
-- **[常见问题](kernel-small-debug-user-faqs.md)**
\ No newline at end of file
diff --git a/zh-cn/device-dev/kernel/kernel-small-overview.md b/zh-cn/device-dev/kernel/kernel-small-overview.md
index 5e17f13da79dbf801185ace1e8fe6be946d94c2f..0762afe70e21fa2020f287b687fb091c14eee61c 100644
--- a/zh-cn/device-dev/kernel/kernel-small-overview.md
+++ b/zh-cn/device-dev/kernel/kernel-small-overview.md
@@ -76,7 +76,7 @@ OpenHarmony 轻量级内核是基于IoT领域轻量级物联网操作系统Huawe
**网络协议**
-轻量级内核网络协议基于开源LWIP构建,对LWIP的RAM占用进行优化,同时提高LWIP的传输性能。
+轻量级内核网络协议基于开源lwIP(lightweight IP)构建,对lwIP的RAM占用进行优化,同时提高lwIP的传输性能。
- 协议: IP、IPv6、 ICMP、 ND、MLD、 UDP、 TCP、IGMP、ARP、PPPoS、PPPoE
diff --git a/zh-cn/device-dev/porting/Readme-CN.md b/zh-cn/device-dev/porting/Readme-CN.md
index ae54c69dc6597106a1d5e8a3cc23d0235bdba6da..8d2c217aee92178f6eb562066e5bcac3465bb7f5 100644
--- a/zh-cn/device-dev/porting/Readme-CN.md
+++ b/zh-cn/device-dev/porting/Readme-CN.md
@@ -67,3 +67,5 @@ repo init -u https://gitee.com/openharmony-sig/manifest.git -b master -m devboar
- [Combo解决方案之W800芯片移植案例](porting-w800-combo-demo.md)
- 小型系统芯片移植案例
- [小型设备STM32MP1芯片移植案例](porting-stm32mp15xx-on-smallsystem.md)
+- 标准系统芯片移植案例
+ - [标准系统方案之瑞芯微RK3568移植案例](porting-dayu200-on_standard-demo.md)
diff --git a/zh-cn/device-dev/reference/hdi-apis/_credential_info.md b/zh-cn/device-dev/reference/hdi-apis/_credential_info.md
index c51b0e7909f75385a521de317311ba46527d5a2c..2d38ca382a44d3e2df74c71b2a33e3dd69ccf44e 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_credential_info.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_credential_info.md
@@ -18,7 +18,7 @@
| [credentialId](#credentialid) | 认证凭据ID。 |
| [index](#index) | 用户认证框架的执行器索引。 |
| [templateId](#templateid) | 认证凭据模版ID。 |
-| [authType](#authtype) | 用户认证凭据类型AuthType。 |
+| [authType](#authtype) | 用户认证凭据类型。 |
| [executorMatcher](#executormatcher) | 执行器匹配器。 |
| [executorSensorHint](#executorsensorhint) | 既定用户认证凭据类型的执行器传感器提示,用于找到对应认证方式的传感器。 |
diff --git a/zh-cn/device-dev/reference/hdi-apis/_executor_info.md b/zh-cn/device-dev/reference/hdi-apis/_executor_info.md
index b769eeab63507075713a6b68f36eec417577bf81..29f4d116ca581180a4a07be6ffccddbc250ee365 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_executor_info.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_executor_info.md
@@ -18,12 +18,12 @@
| [sensorId](#sensorid) | 传感器ID,不同传感器在人脸/口令认证驱动内的唯一标识。 |
| [executorType](#executortype) | 执行器类型,根据执行器支持的能力/算法类型进行分类。 |
| [index](#index) | 用户认证框架的执行器索引。 |
-| [executorRole](#executorrole) | 执行器角色ExecutorRole。 |
+| [executorRole](#executorrole) | 执行器角色。 |
| [authType](#authtype) | 用户认证凭据类型。 |
| [esl](#esl) | 执行器安全等级。 |
| [publicKey](#publickey) | 执行器公钥,用于校验该执行器私钥签名的信息。 |
| [extraInfo](#extrainfo) | 其他相关信息,用于支持信息扩展。 |
-| [info](#info) | 执行器注册信息ExecutorRegisterInfo。 |
+| [info](#info) | 执行器注册信息。 |
## **详细描述**
@@ -63,7 +63,7 @@ enum ExecutorSecureLevel ExecutorInfo::esl
**描述:**
-执行器安全等级ExecutorSecureLevel。
+执行器安全等级[ExecutorSecureLevel](_hdf_user_auth.md#executorsecurelevel)。
### executorRole
@@ -75,7 +75,7 @@ enum ExecutorRole ExecutorInfo::executorRole
**描述:**
-执行器角色ExecutorRole。
+执行器角色[ExecutorRole](_hdf_user_auth.md#executorrole)。
### executorType
diff --git a/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md b/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md
index 85ba5209010fe793e063d5332cdc5c50a51df27c..ff242ae7d76d8749b458eac663519c3ca30fbb12 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md
@@ -16,10 +16,10 @@
| Public 属性 | 描述 |
| -------- | -------- |
| [authType](#authtype) | 用户认证凭据类型。 |
-| [executorRole](#executorrole) | 执行器角色ExecutorRole。 |
+| [executorRole](#executorrole) | 执行器角色。 |
| [executorSensorHint](#executorsensorhint) | 既定用户认证凭据类型的执行器ID。 |
| [executorMatcher](#executormatcher) | 执行器类型,根据执行器支持的认证能力进行分类。 |
-| [esl](#esl) | 执行器安全等级ExecutorSecureLevel。 |
+| [esl](#esl) | 执行器安全等级。 |
| [publicKey](#publickey) | 执行器公钥,用于校验该执行器私钥签名的信息。 |
@@ -60,7 +60,7 @@ enum ExecutorSecureLevel ExecutorRegisterInfo::esl
**描述:**
-执行器安全等级ExecutorSecureLevel。
+执行器安全等级[ExecutorSecureLevel](_hdf_user_auth.md#executorsecurelevel)。
### executorSensorHint
@@ -84,7 +84,7 @@ enum ExecutorRole ExecutorRegisterInfo::executorRole
**描述:**
-执行器角色ExecutorRole。
+执行器角色[ExecutorRole](_hdf_user_auth.md#executorrole)。
### executorMatcher
diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_controller.md b/zh-cn/device-dev/reference/hdi-apis/_input_controller.md
index d70cca07b889bad1e44b843adffde4a93db1878f..58ab8b158a18cc045e658f398061460f0ef07b0b 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_input_controller.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_input_controller.md
@@ -61,7 +61,7 @@ int32_t(* InputController::GetChipInfo) (uint32_t devIndex, char *chipInfo, uint
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### GetChipName
@@ -87,7 +87,7 @@ int32_t(* InputController::GetChipName) (uint32_t devIndex, char *chipName, uint
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### GetDeviceType
@@ -106,13 +106,13 @@ int32_t(* InputController::GetDeviceType) (uint32_t devIndex, uint32_t *deviceTy
| 名称 | 描述 |
| -------- | -------- |
| devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 |
-| deviceType | 输出参数,获取的对应设备索引的设备类型,具体参考**InputDevType**。 |
+| deviceType | 输出参数,获取的对应设备索引的设备类型,具体参考[InputDevType](_input.md#inputdevtype)。 |
**返回:**
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### GetPowerStatus
@@ -139,7 +139,7 @@ int32_t(* InputController::GetPowerStatus) (uint32_t devIndex, uint32_t *status)
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus。**
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### GetVendorName
@@ -151,7 +151,7 @@ int32_t(* InputController::GetVendorName) (uint32_t devIndex, char *vendorName,
**描述:**
-获取devIndex对应的模组厂商名
+获取devIndex对应的模组厂商名。
**参数:**
@@ -165,7 +165,7 @@ int32_t(* InputController::GetVendorName) (uint32_t devIndex, char *vendorName,
Returns INPUT_SUCCESS 表示执行成功。
-Returns 其他值表示执行失败,具体错误码查看**RetSatus**。
+Returns 其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### RunCapacitanceTest
@@ -186,7 +186,7 @@ int32_t(* InputController::RunCapacitanceTest) (uint32_t devIndex, uint32_t test
| 名称 | 描述 |
| -------- | -------- |
| devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 |
-| testType | 输入参数,容值测试的测试类型,具体参考**CapacitanceTest**。 |
+| testType | 输入参数,容值测试的测试类型,具体参考[CapacitanceTest](_input.md#capacitancetest)。 |
| result | 输出参数,容值测试的结果,成功则输出“SUCC”,失败则返回对应的错误提示。 |
| length | 输入参数,保存容值测试结果的内存长度。 |
@@ -194,7 +194,7 @@ int32_t(* InputController::RunCapacitanceTest) (uint32_t devIndex, uint32_t test
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### RunExtraCommand
@@ -213,13 +213,13 @@ int32_t(* InputController::RunExtraCommand) (uint32_t devIndex, InputExtraCmd *c
| 名称 | 描述 |
| -------- | -------- |
| devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 |
-| cmd | 输入参数,拓展指令数据包,包括指令编码及参数,具体参考**InputExtraCmd**。 |
+| cmd | 输入参数,拓展指令数据包,包括指令编码及参数,具体参考[InputExtraCmd](_input_extra_cmd.md)。 |
**返回:**
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### SetGestureMode
@@ -246,7 +246,7 @@ int32_t(* InputController::SetGestureMode) (uint32_t devIndex, uint32_t gestureM
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### SetPowerStatus
@@ -273,4 +273,4 @@ int32_t(* InputController::SetPowerStatus) (uint32_t devIndex, uint32_t status)
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_manager.md b/zh-cn/device-dev/reference/hdi-apis/_input_manager.md
index a70e520d598b2f89eccd82e8f0facc1d0522e67f..ac0611a28958d35fe31156a134270a7be2c0ba03 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_input_manager.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_input_manager.md
@@ -18,8 +18,8 @@
| ( [ScanInputDevice](#scaninputdevice) )(DevDesc \*staArr, uint32_t arrLen) | Input服务用于扫描所有在线设备。 [更多...](#scaninputdevice) |
| ( [OpenInputDevice](#openinputdevice) )(uint32_t devIndex) | Input服务打开对应设备的设备文件 [更多...](#openinputdevice) |
| ( [CloseInputDevice](#closeinputdevice) )(uint32_t devIndex) | Input服务关闭对应设备的设备文件 [更多...](#closeinputdevice) |
-| ( [GetInputDevice](#getinputdevice) )(uint32_t devIndex, [DeviceInfo](_device_info.md) \*\*devInfo) | Input服务获取对应ID的设备信息 [更多...](#getinputdevice) |
-| ( [GetInputDeviceList](#getinputdevicelist) )(uint32_t \*devNum, [DeviceInfo](_device_info.md) \*\*devList, uint32_t size) | Input服务获取所有Input设备列表的设备信息 [更多...](#getinputdevicelist) |
+| ( [GetInputDevice](#getinputdevice) )(uint32_t devIndex, [InputDeviceInfo](_device_info.md) \*\*devInfo) | Input服务获取对应ID的设备信息 [更多...](#getinputdevice) |
+| ( [GetInputDeviceList](#getinputdevicelist) )(uint32_t \*devNum, [InputDeviceInfo](_device_info.md) \*\*devList, uint32_t size) | Input服务获取所有Input设备列表的设备信息 [更多...](#getinputdevicelist) |
## **详细描述**
@@ -53,7 +53,7 @@ Input服务关闭对应设备的设备文件。
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### GetInputDevice
@@ -72,13 +72,13 @@ Input服务获取对应ID的设备信息。
| 名称 | 描述 |
| -------- | -------- |
| devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 |
-| devInfo | 输出参数,即devIndex对应的设备的设备信息,具体参考**DeviceInfo**。 |
+| devInfo | 输出参数,即devIndex对应的设备的设备信息,具体参考[InputDeviceInfo](_device_info.md)。 |
**返回:**
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### GetInputDeviceList
@@ -97,14 +97,14 @@ Input服务获取所有Input设备列表的设备信息。
| 名称 | 描述 |
| -------- | -------- |
| devNum | 输出参数,当前已经注册过的所有Input设备的总数。 |
-| devInfo | 输出参数,Input设备列表所对应的设备信息,具体参考**DeviceInfo**。 |
+| devInfo | 输出参数,Input设备列表所对应的设备信息,具体参考[InputDeviceInfo](_device_info.md)。 |
| size | 输入参数,即指定deviceList数组对应的元素个数。|
返回:
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### OpenInputDevice
@@ -128,7 +128,7 @@ Input服务打开对应设备的设备文件。
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### ScanInputDevice
@@ -153,4 +153,4 @@ Input服务用于扫描所有在线设备。
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md b/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md
index cb5424095a877c82857f3e693823bb85a1e50155..fb4feb386c944bed951b37290c8711af10e4d28f 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md
@@ -54,7 +54,7 @@ Input服务通过此接口注册回调函数到hdi中,所有Input设备由此
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### RegisterReportCallback
@@ -81,7 +81,7 @@ Input服务通过此接口注册数据回调函数到hdi中,hdi通过此回调
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### UnregisterHotPlugCallback
@@ -99,7 +99,7 @@ int32_t(* InputReporter::UnregisterHotPlugCallback) (void)
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
### UnregisterReportCallback
@@ -123,4 +123,4 @@ int32_t(* InputReporter::UnregisterReportCallback) (uint32_t devIndex)
INPUT_SUCCESS 表示执行成功。
-其他值表示执行失败,具体错误码查看**RetSatus**。
+其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。
diff --git a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md
index 955b58092baa386c07225ccf5cd317e2cf6195ed..73ab78e3a96dd2462352ba188d74bb550375939d 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md
@@ -21,4 +21,4 @@
## **详细描述**
-捕获结束相关信息,用于捕获结束回调 **OnCaptureEnded**。
+捕获结束相关信息,用于捕获结束回调[OnCaptureEnded](_camera.md#oncaptureended)。
diff --git a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md
index d37ee91131ecde1979a36b9df4fddcca26378762..ed436019406bf6e0646d37c6a78cc3996d993b0e 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md
@@ -17,7 +17,7 @@
| -------- | -------- |
| [streamIds_](_camera.md#streamids) | 捕获的流ID集合。 |
| [captureSetting_](_camera.md#capturesetting) | 捕获的配置信息。 |
-| [enableShutterCallback_](_camera.md#enableshuttercallback) | 使能捕获回调,每一次捕获后都会触发 **OnFrameShutter**。 |
+| [enableShutterCallback_](_camera.md#enableshuttercallback) | 使能捕获回调,每一次捕获后都会触发 [OnFrameShutter](_camera.md#onframeshutter)。 |
## **详细描述**
diff --git a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md
index ed579509cd197d9ba69c4aee835edeaee5d04967..9bc4102d6e28c072dee510f953bb241cf9413766 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md
@@ -54,7 +54,7 @@
| 静态 Public 成员函数 | 描述 |
| -------- | -------- |
-| [GetInstance](\_u\_s\_b.md#getinstance) () | 获取实例。 |
+| [GetInstance](_u_s_b.md#getinstance) () | 获取实例。 |
## 详细描述
diff --git a/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md b/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md
index e99f63e78499847569f19217ddfc009f6b9a99de..0b3aea7ea7efe0a9d32a357d6432cc438d455b36 100644
--- a/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md
+++ b/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md
@@ -101,7 +101,7 @@ int32_t VideoPortCap::supportPixFmts[PIX_FORMAT_NUM]
**描述:**
-支持的像素格式,详见**OMX_COLOR_FORMATTYPE**
+支持的像素格式
### whAlignment
diff --git a/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md b/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md
index 435ef85b8d72485145cff125169a1efc4b03cf62..9471fe3dcd50cd9a9eb64b937221e654fb0d024a 100644
--- a/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md
+++ b/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md
@@ -150,7 +150,7 @@ IUserAuthInterface::BeginIdentification([in] unsigned long contextId, [in] enum
| 名称 | 描述 |
| -------- | -------- |
| contextId | 上下文索引。 |
-| authType | 用户身份识别类型AuthType}。 |
+| authType | 用户身份识别类型[AuthType](_hdf_user_auth.md#authtype)。 |
| challenge | 随机挑战值,用于生成用户身份识别令牌,防止重放。 |
| executorSensorHint | 执行器传感器提示,用于找到对应认证方式的传感器。 |
| scheduleInfo | 调度信息[ScheduleInfo](_schedule_info.md)。 |
diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md
index 4f55d86f3a01808c7631404f134d6c8af3a7f7e8..d93db2c101cf19d4e158414e257abb588ee14953 100755
--- a/zh-cn/device-dev/subsystems/Readme-CN.md
+++ b/zh-cn/device-dev/subsystems/Readme-CN.md
@@ -74,7 +74,13 @@
- [设备安全等级管理开发指导](subsys-security-devicesecuritylevel.md)
- 启动恢复
- [启动恢复子系统概述](subsys-boot-overview.md)
- - [init启动引导组件](subsys-boot-init.md)
+ - init启动引导组件
+ - [引导启动配置文件](subsys-boot-init-cfg.md)
+ - [jobs管理](subsys-boot-init-jobs.md)
+ - [服务管理](subsys-boot-init-service.md)
+ - [系统参数](subsys-boot-init-sysparam.md)
+ - [沙盒管理](subsys-boot-init-sandbox.md)
+ - [插件](subsys-boot-init-plugin.md)
- [appspawn应用孵化组件](subsys-boot-appspawn.md)
- [bootstrap服务启动组件](subsys-boot-bootstrap.md)
- [常见问题](subsys-boot-faqs.md)
diff --git a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md
index 598a744eb0f8694ad238415e23d324fda3fda055..d082cc359fab9b9cb72cc9f521192c6ad1c71ea0 100644
--- a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md
+++ b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md
@@ -13,12 +13,12 @@ AI引擎框架规定了一套算法插件接入规范,各插件需实现规定
| -------- | -------- | -------- |
| const long long GetVersion() const; | **作用**:获取插件版本信息。
**返回值**:版本号(long long) | - |
| const char \*GetInferMode() const; | **作用**:获取算法推理类型。
**返回值**:"SYNC" or "ASYNC"; | - |
-| int SyncProcess(IRequest \*request,
IResponse \*&response); | **作用**:执行插件同步算法。
**返回值**:0为成功,其他返回值失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道;
**response**(NOT NULL):作为出参用于接收算法插件发回的同步算法执行结果,引擎服务端与插件的数据通道; |
-| int AsyncProcess(IRequest \*request,
IPluginAlgorithmCallback \*callback); | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道。
**callback**(NOT NULL):算法插件异步执行结果通过此回调返回引擎服务端; |
-| int Prepare(long long transactionId,
const DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:加载算法插件。
**返回值**:0为成功,其他返回值失败。 | **transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息;
**inputInfo**(可为NULL):加载算法插件传入的一些信息;
**outputInfo**(可为NULL):调用加载接口时的出参,返回相关执行结果; |
-| int Release(bool isFullUnload, long long
transactionId, const DataInfo &inputInfo); | **作用**:卸载相关算法插件。
**返回值**:0为成功,其他返回值失败。 | **isFullUnload**(NOT NULL):表示此插件是否只剩一个client调用,否则不能直接卸载插件,需等最后一个client来进行卸载;
**transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息;
**inputInfo**(可为NULL):卸载算法插件传入的一些信息; |
-| int SetOption(int optionType, const
DataInfo &inputInfo); | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值失败。 | **optionType** (NOT NULL):算法配置项,算法插件可根据需要利用此状态位;
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息; |
-| int GetOption(int optionType, const
DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值失败。 | **optionType**(NOT NULL):所获取配置项信息的对应算法状态位;
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息;
**outputInfo**(可为NULL):所要获取的配置项信息返回结果; |
+| int SyncProcess(IRequest \*request,
IResponse \*&response); | **作用**:执行插件同步算法。
**返回值**:0为成功,其他返回值为失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道。
**response**(NOT NULL):作为出参用于接收算法插件发回的同步算法执行结果,引擎服务端与插件的数据通道。 |
+| int AsyncProcess(IRequest \*request,
IPluginAlgorithmCallback \*callback); | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值为失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道。
**callback**(NOT NULL):算法插件异步执行结果通过此回调返回引擎服务端。 |
+| int Prepare(long long transactionId,
const DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:加载算法插件。
**返回值**:0为成功,其他返回值为失败。 | **transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息。
**inputInfo**(可为NULL):加载算法插件传入的一些信息。
**outputInfo**(可为NULL):调用加载接口时的出参,返回相关执行结果。 |
+| int Release(bool isFullUnload, long long
transactionId, const DataInfo &inputInfo); | **作用**:卸载相关算法插件。
**返回值**:0为成功,其他返回值为失败。 | **isFullUnload**(NOT NULL):表示此插件是否只剩一个client调用,否则不能直接卸载插件,需等最后一个client来进行卸载。
**transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息。
**inputInfo**(可为NULL):卸载算法插件传入的一些信息。 |
+| int SetOption(int optionType, const
DataInfo &inputInfo); | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值为失败。 | **optionType** (NOT NULL):算法配置项,算法插件可根据需要利用此状态位。
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息。 |
+| int GetOption(int optionType, const
DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值为失败。 | **optionType**(NOT NULL):所获取配置项信息的对应算法状态位。
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息。
**outputInfo**(可为NULL):所要获取的配置项信息返回结果。 |
算法插件类接口:Prepare、SyncProcess、AsyncProcess、Release、SetOption、GetOption分别于客户端接口AieClientPrepare、AieClientSyncProcess、AieClientAsyncProcess、AieClientRelease、AieClientSetOption、AieClientGetOption一一对应;GetInferMode接口用于返回算法执行类型——同步或异步。
@@ -31,10 +31,10 @@ AI引擎框架规定了一套算法插件接入规范,各插件需实现规定
| 接口名 | 接口说明 | 参数要求 |
| -------- | -------- | -------- |
-| void OnEvent(PluginEvent event,
IResponse \*response); | 作用:插件通过此回调返回异步算法执行结果。 | **event**:算法执行结果枚举,‘ON_PLUGIN_SUCCEED’或 ‘ON_PLUGIN_FAIL’(成功或者失败);
**response**:算法执行结果封装; |
+| void OnEvent(PluginEvent event,
IResponse \*response); | 作用:插件通过此回调返回异步算法执行结果。 | **event**:算法执行结果枚举,‘ON_PLUGIN_SUCCEED’或 ‘ON_PLUGIN_FAIL’(成功或者失败)。
**response**:算法执行结果封装。 |
-Request、Response是ai引擎服务端与算法插件进行通信的对象。Request封装了调用方的请求、输入数据等,而插件主要通过Response将运算之后的结果返回给AI引擎服务端。
+Request、Response是AI引擎服务端与算法插件进行通信的对象。Request封装了调用方的请求、输入数据等,而插件主要通过Response将运算之后的结果返回给AI引擎服务端。
Request类的属性如下表所示。
@@ -46,7 +46,7 @@ Request类的属性如下表所示。
| -------- | -------- | -------- |
| innerSequenceId_ | 类型:long long
作用:暂未启用。 | 0 |
| requestId_ | 类型:int
作用:标识请求序列,用于绑定返回运算结果。 | 0 |
-| operationId_ | 类型:int
作用:目前暂未启用。 | 0 |
+| operationId_ | 类型:int
作用:暂未启用。 | 0 |
| transactionId_ | 类型:long long
作用:事务ID,唯一标识clientId+sessionId。 | 0 |
| algoPluginType_ | 类型:int
作用:引擎框架根据插件加载顺序分配的算法类型的ID。 | 0 |
| msg_ | 类型:DataInfo
作用:存放调用算法接口的输入数据。 | .data = nullptr
.length = 0 |
diff --git a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md
index 54b413dd6cc5cffb4ecc358c368f1ef593520851..83150d465bf78878ad6b1cabe6716d2c14c95cd6 100644
--- a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md
+++ b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md
@@ -1,21 +1,21 @@
# SDK开发过程
-SDK头文件的功能实现是基于对SDK的调用映射到对客户端的调用。客户端端提供的接口如下表所示。
+SDK头文件的功能实现是基于对SDK的调用映射到对客户端的调用。Client端提供的接口如下表所示。
**表1** Client端提供的接口
| 接口名 | 接口说明 | 参数要求 |
| -------- | -------- | -------- |
-| int **AieClientInit**(const ConfigInfo &configInfo,
ClientInfo &clientInfo, const AlgorithmInfo
&algorithmInfo, IServiceDeadCb \*cb) | **作用**:链接并初始化引擎服务,激活跨进程调用。
**返回值**:0为成功,其他返回值失败。 | **configInfo**(NOT NULL):引擎相关初始化配置数据;
**clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**cb**(可为NULL):死亡回调 对象; |
-| int **AieClientPrepare**(const ClientInfo &clientInfo
, const AlgorithmInfo &algorithmInfo, const DataInfo
&inputInfo, DataInfo &outputInfo, IClientCb \*cb) | **作用**:加载算法插件。
**返回值**: 0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**inputInfo**(可为NULL):加载算法插件时输入所需信息;
**outputInfo**(可为NULL):加载算法插件之后如需返回信息则通过此出参返回;
**cb**:异步算法通过此回调返回运算结果,因此**异步算法此结构体不能为空**;若为同步算法,传入空值即可; |
-| int **AieClientAsyncProcess**(const ClientInfo &clientInfo,
const AlgorithmInfo &algorithmInfo, const DataInfo
&inputInfo) | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**inputInfo**(可为NULL):算法运算入参; |
-| int **AieClientSyncProcess**(const ClientInfo &clientInfo,
const AlgorithmInfo &algorithmInfo, const
DataInfo &inputInfo, DataInfo &outputInfo) | **作用**:执行同步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**inputInfo**(可为NULL):算法运算入参;
**outputInfo**(可为NULL):同步算法运算结果出参; |
-| int **AieClientRelease**(const ClientInfo &clientInfo,
const AlgorithmInfo &algorithmInfo, const
DataInfo &inputInfo) | **作用**:卸载算法插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):卸载算法插件的相关信息;
**inputInfo**(可为NULL):调用卸载接口时的输入信息; |
-| int **AieClientDestroy**(ClientInfo &clientInfo) | **作用**:断开与服务端的链接,释放相关缓存。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):所要销毁的引擎客户端信息; |
-| int **AieClientSetOption**(const ClientInfo &clientInfo,
int optionType, const DataInfo &inputInfo) | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**optionType** (NOT NULL):算法配置项,算法插件可根据需要利用此状态位;
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息; |
-| int **AieClientGetOption**(const ClientInfo &clientInfo,
int optionType, const DataInfo &inputInfo,
DataInfo &outputInfo) | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**optionType**(NOT NULL):所获取配置项信息的对应算法状态位;
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息;
**outputInfo**(可为NULL):所要获取的配置项信息返回结果; |
+| int **AieClientInit**(const ConfigInfo &configInfo,
ClientInfo &clientInfo, const AlgorithmInfo
&algorithmInfo, IServiceDeadCb \*cb) | **作用**:链接并初始化引擎服务,激活跨进程调用。
**返回值**:0为成功,其他返回值失败。 | **configInfo**(不能为NULL):引擎相关初始化配置数据
**clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**cb**(可为NULL):死亡回调对象 |
+| int **AieClientPrepare**(const ClientInfo &clientInfo
, const AlgorithmInfo &algorithmInfo, const DataInfo
&inputInfo, DataInfo &outputInfo, IClientCb \*cb) | **作用**:加载算法插件。
**返回值**: 0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**inputInfo**(可为NULL):加载算法插件时输入所需信息
**outputInfo**(可为NULL):加载算法插件之后如需返回信息则通过此出参返回
**cb**:异步算法通过此回调返回运算结果,因此**异步算法此结构体不能为空** 若为同步算法,传入空值即可 |
+| int **AieClientAsyncProcess**(const ClientInfo &clientInfo,
const AlgorithmInfo &algorithmInfo, const DataInfo
&inputInfo) | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**inputInfo**(可为NULL):算法运算入参 |
+| int **AieClientSyncProcess**(const ClientInfo &clientInfo,
const AlgorithmInfo &algorithmInfo, const
DataInfo &inputInfo, DataInfo &outputInfo) | **作用**:执行同步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**inputInfo**(可为NULL):算法运算入参
**outputInfo**(可为NULL):同步算法运算结果出参 |
+| int **AieClientRelease**(const ClientInfo &clientInfo,
const AlgorithmInfo &algorithmInfo, const
DataInfo &inputInfo) | **作用**:卸载算法插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):卸载算法插件的相关信息
**inputInfo**(可为NULL):调用卸载接口时的输入信息 |
+| int **AieClientDestroy**(ClientInfo &clientInfo) | **作用**:断开与服务端的链接,释放相关缓存。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):所要销毁的引擎客户端信息 |
+| int **AieClientSetOption**(const ClientInfo &clientInfo,
int optionType, const DataInfo &inputInfo) | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**optionType** (不能为NULL):算法配置项,算法插件可根据需要利用此状态位
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息 |
+| int **AieClientGetOption**(const ClientInfo &clientInfo,
int optionType, const DataInfo &inputInfo,
DataInfo &outputInfo) | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**optionType**(不能为NULL):所获取配置项信息的对应算法状态位
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息
**outputInfo**(可为NULL):所要获取的配置项信息返回结果 |
其中,ConfigInfo,ClientInfo,AlgorithmInfo,DataInfo的数据结构如下表所示。
@@ -25,10 +25,10 @@ SDK头文件的功能实现是基于对SDK的调用映射到对客户端的调
| 结构体名称 | 说明 | 属性 |
| -------- | -------- | -------- |
-| ConfigInfo | 算法配置项信息。 | **const char \*description**:配置项信息主体; |
-| ClientInfo | 客户端信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用);
**int clientId**:客户端ID;
**int sessionId:**会话ID;
**uid_t serverUid**:server端UID;
**uid_t clientUid:**client端UID;
**int extendLen**:拓展信息(extendMsg)长度;
**unsigned char \*extendMsg**:拓展信息主体; |
-| AlgorithmInfo | 算法信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用);
**bool isAsync**:是否为异步执行;
**int algorithmType:**引擎框架根据插件加载顺序分配的算法类型ID;
**long long algorithmVersion**:算法版本号;
**bool isCloud**:是否上云(当前还未启用);
**int operateId**:执行ID(当前还未启用);
**int requestId**:请求ID,标识每次request,以对应执行结果;
**int extendLen**:拓展信息(extendMsg)长度;
**unsigned char \*extendMsg**:拓展信息主体; |
-| DataInfo | 算法数据入参(inputInfo)、
接口调用结果出参(outputInfo)。 | **unsigned char \*data:**数据主体;
**int length**:数据(data)长度; |
+| ConfigInfo | 算法配置项信息。 | **const char \*description**:配置项信息主体 |
+| ClientInfo | 客户端信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用)
**int clientId**:客户端ID
**int sessionId**:会话ID
**uid_t serverUid**:server端UID
**uid_t clientUid**:client端UID
**int extendLen**:拓展信息(extendMsg)长度
**unsigned char \*extendMsg**:拓展信息主体 |
+| AlgorithmInfo | 算法信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用)
**bool isAsync**:是否为异步执行
**int algorithmType**:引擎框架根据插件加载顺序分配的算法类型ID
**long long algorithmVersion**:算法版本号
**bool isCloud**:是否上云(当前还未启用)
**int operateId**:执行ID(当前还未启用)
**int requestId**:请求ID,标识每次request,以对应执行结果
**int extendLen**:拓展信息(extendMsg)长度
**unsigned char \*extendMsg**:拓展信息主体 |
+| DataInfo | 算法数据入参(inputInfo)、
接口调用结果出参(outputInfo)。 | **unsigned char \*data**:数据主体
**int length**:数据(data)长度 |
具体开发过程可参考[唤醒词识别SDK开发示例](../subsystems/subsys-aiframework-demo-sdk.md)。
diff --git a/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md b/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md
index 659600d23bd24647f465f3e50c528c3393057e0d..8d0c3224f4dd2758f4b9479f998421414c56602e 100644
--- a/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md
+++ b/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md
@@ -17,14 +17,16 @@ AI引擎框架各模块之间的代码依赖关系如下图所示:
在AI引擎框架的整体规划中,北向SDK属于client端的一部分,插件由server端调用,属于server端的一部分,因此AI引擎框架为接入的插件与北向SDK规划的路径:
- SDK代码路径://foundation/ai/engine/services/client/algorithm_sdk
- e.g. //foundation/ai/engine/services/client/algorithm_sdk/cv
+
+ 示例1://foundation/ai/engine/services/client/algorithm_sdk/cv
- e.g. //foundation/ai/engine/services/client/algorithm_sdk/nlu
+ 示例2://foundation/ai/engine/services/client/algorithm_sdk/nlu
- 插件代码路径://foundation/ai/engine/services/server/plugin
- e.g. //foundation/ai/engine/services/server/plugin/cv
+
+ 示例1://foundation/ai/engine/services/server/plugin/cv
- e.g. //foundation/ai/engine/services/server/plugin/nlu
+ 示例2://foundation/ai/engine/services/server/plugin/nlu
## 规则:插件提供的全部对外接口,统一存放在AI业务子系统interfaces/kits目录
diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md b/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md
index a01d244546c32e94498b6b0271dcefb4c4df8801..52e2fe1650974d7011378f267ee15acc3bad192f 100644
--- a/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md
+++ b/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md
@@ -160,6 +160,20 @@ job就是命令集合,jobs管理就是对要执行的一组命令集合进行
小型系统和标准系统
+
+ |
+ write
+ |
+
+ write filename value 如:write /data/testfile 0
+ |
+
+ 写文件命令。后面跟两个参数,第一个参数是文件的绝对路径,第二个参数是要写入文件的字符串。
+ |
+
+ 标准系统
+ |
+
|
stop
@@ -300,6 +314,20 @@ job就是命令集合,jobs管理就是对要执行的一组命令集合进行
小型系统和标准系统
|
+
+ |
+ syncexec
+ |
+
+ syncexec 可执行文件路径 可执行文件传的参数 如:syncexec /system/bin/udevadm trigger
+ |
+
+ 同步执行,syncexec 会调用wait等待子进程结束。参数个数不超过10个。
+ |
+
+ 标准系统
+ |
+
|
mknode
diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-service.md b/zh-cn/device-dev/subsystems/subsys-boot-init-service.md
index 29d88d97fe509c7f1676c566032db0f0d1b204ef..36dcceb2d73a601de2bbcc06815e66e5eba44236 100644
--- a/zh-cn/device-dev/subsystems/subsys-boot-init-service.md
+++ b/zh-cn/device-dev/subsystems/subsys-boot-init-service.md
@@ -208,11 +208,11 @@
importance
|
- 当前服务优先级
+ 标准系统:当前服务优先级 小型系统:标记服务重要性
|
标准系统中: 服务优先级取值范围 [-20, 19],超出为无效设置。
- 小型系统中:0 : 非重要进程;非0 : 重要进程
+ 小型系统中:0 :不重启系统 ;非0 : 重启系统。
|
小型系统和标准系统
diff --git a/zh-cn/device-dev/subsystems/subsys-xts-guide.md b/zh-cn/device-dev/subsystems/subsys-xts-guide.md
index 991972c0d7f3684aea0dbf703cf7129a11434030..36f1f7ab87265f684f24487de5b107332ef05c15 100644
--- a/zh-cn/device-dev/subsystems/subsys-xts-guide.md
+++ b/zh-cn/device-dev/subsystems/subsys-xts-guide.md
@@ -143,18 +143,15 @@ XTS子系统当前包括acts与tools软件包:
4. 使用宏定义LITE_TEST_CASE写测试用例
包括三个参数:测试套件名称,测试用例名称,用例属性(测试类型、用例粒度、用例级别)。
-
-
```
LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1)
{
//do something
};
```
-
5. 使用宏定义 RUN_TEST_SUITE注册测试套件
-
+
```
RUN_TEST_SUITE(IntTestSuite);
```
@@ -258,16 +255,16 @@ XTS子系统当前包括acts与tools软件包:
// Test suite cleanup action, which is executed after the last test case
static void TearDownTestCase(void){
}
- // Preset action of the test case
- virtual void SetUp()
- {
- }
- // Cleanup action of the test case
- virtual void TearDown()
- {
+ // Preset action of the test case
+ virtual void SetUp()
+ {
+ }
+ // Cleanup action of the test case
+ virtual void TearDown()
+ {
}
};
- ```
+ ```
3. 使用宏定义HWTEST或HWTEST_F写测试用例
@@ -288,8 +285,7 @@ XTS子系统当前包括acts与tools软件包:
每个测试模块目录下新建BUILD.gn编译文件,用于指定编译后可执行文件的名称、依赖的头文件、依赖的库等;具体写法如下。每个测试模块将独立编译成.bin可执行文件, 该文件可直接push到单板上进行测试。
举例:
-
-
+
```
import("//test/xts/tools/lite/build/suite_lite.gni")
hcpptest_suite("ActsDemoTest") {
diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md
index 89c636ed0e58c696b02b80e8b5f0ce508cc753ba..3554669de0f544e90530523f64e038ffcfad7b69 100644
--- a/zh-cn/device-dev/website.md
+++ b/zh-cn/device-dev/website.md
@@ -390,6 +390,7 @@
- [Audio](driver/driver-peripherals-audio-des.md)
- [Camera](driver/driver-peripherals-camera-des.md)
- [Face_auth](driver/driver-peripherals-face_auth-des.md)
+ - [Fingerprint_auth](driver/driver-peripherals-fingerprint_auth-des.md)
- [LCD](driver/driver-peripherals-lcd-des.md)
- [Light](driver/driver-peripherals-light-des.md)
- [Pin_auth](driver/driver-peripherals-pinauth-des.md)
diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md
index 3eb8da4befa96166c8a54de10b512f504ecfcc05..18992d1e2478d51993d4cf7f1d2ee9bd90897428 100644
--- a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md
+++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md
@@ -148,7 +148,7 @@
| 泛Sensor服务子系统 | - 支持更多类型的传感器上报。 - 支持SELinux。 主要涉及如下需求: I53SFI 【DFX打点】【泛Sensor服务子系统】提供系统事件、SA dump、trace打点 I537CB 【新增规格】泛Sensor能力持续集成-旋转矢量传感器 I537AN 【新增规格】泛Sensor能力持续集成-重力传感器 I5379T 【新增规格】泛Sensor能力持续集成-地磁传感器 I5379C 【新增规格】泛Sensor能力持续集成-方向传感器 I53784 【新增规格】泛Sensor能力持续集成-环境光传感器 I53SFS 【新增规格】【泛Sensor服务】SELinux策略配置 | NA |
| 分布式数据管理子系统 | data_share支持多种数据类型。 主要涉及如下需求: I5EHGF 【DataShare】DataShare支持多种数据储存类型 | NA |
| web子系统 | - 新增支持JS相关交互能力。 - 新增支持网络、键鼠、webstorage、SELinux策略等能力。 主要涉及如下需求: I5DM1E 【新增规格】web组件的JS窗口管理 I5DNG2 【新增规格】JS侧提供全量hittest接口以及DefaultUserAgent获取 I5EK53 【新增规格】【web子系统】web组件http验证管理 I5EGBB 【新增规格】【web子系统】【web部件】web子系统的SELinux策略配置 I5EBG1 【新增规格】【web子系统】web子系统适配w3c network information api I5EVEC 【新增规格】【web子系统】web内核对接鼠标、键盘等外设能力 I5FF2L 【新增规格】【web子系统】web组件支持webstorage | NA |
-| 驱动子系统 | - 支持内核态驱动动态加载及DFX能力。 - 提供Codec2.0接口及codec驱动模型。 - Camera、Display、Audio、Sensor、Wlan等模块驱动能力增强。 主要涉及如下需求: I536FN 【新增特性】【驱动子系统】支持HDI passthrougt模式 I5DJE5 【增强特性】兼容Linux uevent事件上报机制,增强设备即插即用功能 I550OL 【新增特性】提供DFX跟踪定位,获取信息能力 I544XP 【新增特性】支持HDF服务SELinux权限检查 标准系统 I528DG 【新增特性】支持Codec 2.0参考实现,简化适配难度 I50I6S 【新增特性】Audio新增IPC模式与直调模式接口调用统一 I5A6H6 【增强特性】增强显示设备管理,支持多屏显示能力 I5B0C5 【新增特性】Camera支持实现Mate类型的流 I5B0BR 【新增特性】录像模式自拍镜像功能 I5AJW1 【新增特性】支持Linux libALSA音频接口兼容 I56V2N 【新增特性】HDF WLAN DAL HDI功率模式相关接口的定义与开发 I5F411 【增强特性】马达效果能力增强 | NA |
+| 驱动子系统 | - 支持内核态驱动动态加载及DFX能力。 - 提供Codec2.0接口及codec驱动模型。 - Camera、Display、Audio、Sensor、WLAN等模块驱动能力增强。 主要涉及如下需求: I536FN 【新增特性】【驱动子系统】支持HDI passthrougt模式 I5DJE5 【增强特性】兼容Linux uevent事件上报机制,增强设备即插即用功能 I550OL 【新增特性】提供DFX跟踪定位,获取信息能力 I544XP 【新增特性】支持HDF服务SELinux权限检查 标准系统 I528DG 【新增特性】支持Codec 2.0参考实现,简化适配难度 I50I6S 【新增特性】Audio新增IPC模式与直调模式接口调用统一 I5A6H6 【增强特性】增强显示设备管理,支持多屏显示能力 I5B0C5 【新增特性】Camera支持实现Mate类型的流 I5B0BR 【新增特性】录像模式自拍镜像功能 I5AJW1 【新增特性】支持Linux libALSA音频接口兼容 I56V2N 【新增特性】HDF WLAN DAL HDI功率模式相关接口的定义与开发 I5F411 【增强特性】马达效果能力增强 | NA |
| USB服务子系统 | - 支持USB服务广播消息。 - 增加SELinux安全策略。 主要涉及如下需求: I59MYK 【新增特性】USB服务广播消息 I5AR8N 【新增规格】【USB服务子系统】USB服务子系统的SELinux策略配置 | NA |
| 内核子系统 | - 新增支持内存精细化管控特性。 - 新增支持关联服务adj调整机制。 主要涉及如下需求: I58LOD 【新增特性】支持关联服务adj调整机制 I54Y5J 【新增特性】支持memtrack内存占用和进程维度adj查询接口特性 I56B3Q 【新增特性】支持OnMemoryLevel特性 I5B694 【新增特性】支持新型内存精细化管控特性 I59O8H 【新增特性】支持purgable memory特性 I5CXOK 【新增特性】支持hyperhold可靠性提升特性 | NA |
diff --git a/zh-cn/release-notes/api-change/template/changelog-x-x.md b/zh-cn/release-notes/api-change/template/changelog-x-x.md
index abf59c77cba59f171efbb6121e24f238516ad50e..b20dbfc1fc13ba0dc94a8044119ac0ae2473cfb7 100644
--- a/zh-cn/release-notes/api-change/template/changelog-x-x.md
+++ b/zh-cn/release-notes/api-change/template/changelog-x-x.md
@@ -1,14 +1,17 @@
-# ChangeLog
-## xxx子系统(该段落为示例,请不要修改或删除)
-已经release的版本发生了影响契约兼容性(契约兼容:也称语义兼容,指版本演进后,开发者原有程序行为不发生变化)的变更(包括不限于接口名、参数、返回值、所需要的权限、调用顺序、枚举值、配置参数、路径等),则需要在ChangeLog中对变更进行阐述。
-### cl.subsystemname.x xxx功能变更, 例:DeviceType属性变更、相机权限变更(尽量概括,不要超过15个字)
-每个变更标题前需要附加编号:cl.subsystemname.x。cl为ChangeLog首字母缩写,subsystemname请填写子系统英文标准名称,x表示变更序号(从低到高逐位增加)。
+# xxx子系统ChangeLog
+
+相比最近一个发布版本(包括不限于LTS、Release、Beta、monthly版本)发生了影响契约兼容性(契约兼容:也称语义兼容,指版本演进后,开发者原有程序行为不发生变化)的变更(包括不限于接口名、参数、返回值、所需要的权限、调用顺序、枚举值、配置参数、路径等),则需要在ChangeLog中对变更进行阐述。
+
+## cl.subsystemname.x xxx功能变更, 例:DeviceType属性变更、相机权限变更(尽量概括,不要超过15个字)
+
+每个变更标题前需要附加编号:cl.subsystemname.x。cl为ChangeLog首字母缩写,subsystemname请填写子系统英文标准名称,x表示变更序号(从低到高逐位增加,起始为1)。
以功能维度对变更点进行概括描述。例如:xxx功能的xxx、xxx等发生了xxx变化,开发者需要根据以下说明对应用进行适配。
如果有此变更有对应的需求或设计文档,可以在描述中附上对应的设计文档编号。
**变更影响**
-是否影响已release的接口或者接口行为发生变更等;影响的是JS接口、Java接口还是Native接口。
+是否影响已发布的接口或者接口行为发生变更,影响的是JS接口还是Native接口。
+是否影响在此前版本已开发的应用,即应用是否需要进行适配动才可以在新版本SDK环境正常编译通过。
**关键的接口/组件变更**
@@ -16,15 +19,13 @@
**适配指导(可选,不涉及则可以删除)**
-(前面空一行)提供指导,帮助开发者针对相关变更进行适配,使应用可以与新版本兼容。例:
+提供指导,帮助开发者针对相关变更进行适配,使应用可以与新版本兼容。
+例:
在xxx文件中将xxx参数修改为xxx。
+
```
sample code
```
-### cl.subsystemname.x xxx功能变更
-每个功能变更点在自己的子系统章节内新增一个功能变更章节。
-## xxx子系统
-每个子系统有且只能有一个子系统章节。
|