提交 df87f6a3 编写于 作者: 田雨 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into master

Signed-off-by: N田雨 <tianyu55@huawei.com>
...@@ -144,6 +144,8 @@ zh-cn/application-dev/telephony/ @zengyawen ...@@ -144,6 +144,8 @@ zh-cn/application-dev/telephony/ @zengyawen
zh-cn/application-dev/dfx/ @zengyawen zh-cn/application-dev/dfx/ @zengyawen
zh-cn/application-dev/database/ @ge-yafang zh-cn/application-dev/database/ @ge-yafang
zh-cn/application-dev/napi/drawing_guidelines.md @ge-yafang zh-cn/application-dev/napi/drawing_guidelines.md @ge-yafang
zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang
zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang
zh-cn/application-dev/napi/rawfile_guidelines.md @HelloCrease zh-cn/application-dev/napi/rawfile_guidelines.md @HelloCrease
zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih
zh-cn/application-dev/background-task-management/ @RayShih zh-cn/application-dev/background-task-management/ @RayShih
...@@ -165,10 +167,9 @@ zh-cn/application-dev/reference/arkui-ts/ @HelloCrease ...@@ -165,10 +167,9 @@ zh-cn/application-dev/reference/arkui-ts/ @HelloCrease
zh-cn/application-dev/reference/native-apis @RayShih zh-cn/application-dev/reference/native-apis @RayShih
zh-cn/application-dev/reference/native-lib @RayShih zh-cn/application-dev/reference/native-lib @RayShih
zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-overview.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-fa.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-js.md @ge-yafang zh-cn/application-dev/quick-start/start-with-js-fa.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-js-low-code.md @ge-yafang
zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang
zh-cn/application-dev/quick-start/package-structure.md @RayShih zh-cn/application-dev/quick-start/package-structure.md @RayShih
zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih
......
...@@ -12,7 +12,7 @@ To use related APIs, you must declare the **ohos.permission.INTERNET** permissio ...@@ -12,7 +12,7 @@ To use related APIs, you must declare the **ohos.permission.INTERNET** permissio
For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md).
The following table describes the related APIs. The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description | | API | Description |
| ----------------------------------------- | --------------------------------------------------------- | | ----------------------------------------- | --------------------------------------------------------- |
......
...@@ -15,15 +15,18 @@ Your application can call location-specific APIs to obtain the location informat ...@@ -15,15 +15,18 @@ Your application can call location-specific APIs to obtain the location informat
Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
- **Coordinate** - **Coordinate**
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
- **GNSS positioning** - **GNSS positioning**
GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
- **Base station positioning** - **Base station positioning**
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
- **WLAN or Bluetooth positioning** - **WLAN or Bluetooth positioning**
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
......
...@@ -38,7 +38,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -38,7 +38,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
// Import the USB API package. // Import the USB API package.
import usb from '@ohos.usb'; import usb from '@ohos.usb';
// Obtain the USB device list. // Obtain the USB device list.
var deviceList = usb.getDevices(); let deviceList = usb.getDevices();
/* /*
Example deviceList structure Example deviceList structure
[ [
...@@ -81,21 +81,21 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -81,21 +81,21 @@ You can set a USB device as the USB host to connect to other USB devices for dat
number: 1, number: 1,
type: 3, type: 3,
interfaceId: 0, interfaceId: 0,
}, }
], ]
}, }
], ]
}, }
], ]
}, }
], ]
*/ */
``` ```
2. Obtain the device operation permissions. 2. Obtain the device operation permissions.
```js ```js
var deviceName = deviceList[0].name; let deviceName = deviceList[0].name;
// Request the permissions to operate a specified device. // Request the permissions to operate a specified device.
usb.requestRight(deviceName).then(hasRight => { usb.requestRight(deviceName).then(hasRight => {
console.info("usb device request right result: " + hasRight); console.info("usb device request right result: " + hasRight);
...@@ -108,7 +108,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -108,7 +108,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
```js ```js
// Open the device, and obtain the USB device pipe for data transfer. // Open the device, and obtain the USB device pipe for data transfer.
var pipe = usb.connectDevice(deviceList[0]); let pipe = usb.connectDevice(deviceList[0]);
/* /*
Claim the corresponding interface from deviceList. Claim the corresponding interface from deviceList.
interface1 must be one present in the device configuration. interface1 must be one present in the device configuration.
...@@ -127,7 +127,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -127,7 +127,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
if (dataLength >= 0) { if (dataLength >= 0) {
console.info("usb readData result Length : " + dataLength); console.info("usb readData result Length : " + dataLength);
var resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. let resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string.
console.info("usb readData buffer : " + resultStr); console.info("usb readData buffer : " + resultStr);
} else { } else {
console.info("usb readData failed : " + dataLength); console.info("usb readData failed : " + dataLength);
......
...@@ -12,12 +12,10 @@ The following table provides only a brief description of related APIs. For detai ...@@ -12,12 +12,10 @@ The following table provides only a brief description of related APIs. For detai
**Table 1** APIs for application event logging **Table 1** APIs for application event logging
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ---------------------------------------------------- |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. | | write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(string eventName, EventType type, object keyValues): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. | | write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. |
| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(AppEventInfo info): Promise\<void> | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.|
When an asynchronous callback is used, the return value can be processed directly in the callback. When an asynchronous callback is used, the return value can be processed directly in the callback.
...@@ -84,6 +82,7 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -84,6 +82,7 @@ The following uses a one-time event watcher as an example to illustrate the deve
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
Button("1 writeTest").onClick(()=>{ Button("1 writeTest").onClick(()=>{
// Perform event logging based on the input event parameters.
hiAppEvent.write({ hiAppEvent.write({
domain: "test_domain", domain: "test_domain",
name: "test_event", name: "test_event",
...@@ -100,6 +99,7 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -100,6 +99,7 @@ The following uses a one-time event watcher as an example to illustrate the deve
}) })
Button("2 addWatcherTest").onClick(()=>{ Button("2 addWatcherTest").onClick(()=>{
// Add an event watcher based on the input subscription parameters.
hiAppEvent.addWatcher({ hiAppEvent.addWatcher({
name: "watcher1", name: "watcher1",
appEventFilters: [{ domain: "test_domain" }], appEventFilters: [{ domain: "test_domain" }],
...@@ -109,17 +109,23 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -109,17 +109,23 @@ The following uses a one-time event watcher as an example to illustrate the deve
timeOut: 2 timeOut: 2
}, },
onTrigger: function (curRow, curSize, holder) { onTrigger: function (curRow, curSize, holder) {
// If the holder object is null, return an error after recording it in the log.
if (holder == null) { if (holder == null) {
console.error("HiAppEvent holder is null"); console.error("HiAppEvent holder is null");
return; return;
} }
// Set the size threshold to 1,000 bytes for obtaining an event package.
holder.setSize(1000);
let eventPkg = null; let eventPkg = null;
// Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained.
while ((eventPkg = holder.takeNext()) != null) { while ((eventPkg = holder.takeNext()) != null) {
console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId); // Parse the obtained event package and display the result on the Log page.
console.info("HiAppEvent eventPkg.row=" + eventPkg.row); console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId);
console.info("HiAppEvent eventPkg.size=" + eventPkg.size); console.info('HiAppEvent eventPkg.row=' + eventPkg.row);
console.info('HiAppEvent eventPkg.size=' + eventPkg.size);
// Traverse and parse event string arrays in the obtained event package.
for (const eventInfo of eventPkg.data) { for (const eventInfo of eventPkg.data) {
console.info("HiAppEvent eventPkg.data=" + eventInfo); console.info('HiAppEvent eventPkg.data=' + eventInfo);
} }
} }
} }
...@@ -127,6 +133,7 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -127,6 +133,7 @@ The following uses a one-time event watcher as an example to illustrate the deve
}) })
Button("3 removeWatcherTest").onClick(()=>{ Button("3 removeWatcherTest").onClick(()=>{
// Remove the specified event watcher.
hiAppEvent.removeWatcher({ hiAppEvent.removeWatcher({
name: "watcher1" name: "watcher1"
}) })
......
...@@ -19,7 +19,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 ...@@ -19,7 +19,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available. Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
......
...@@ -4,5 +4,6 @@ ...@@ -4,5 +4,6 @@
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md) - [Native Window Development](native-window-guidelines.md)
- [Using MindSpore Lite for Model Inference](native-window-guidelines.md)
# Using MindSpore Lite for Model Inference
## When to Use
MindSpore Lite is an AI engine that provides AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition.
This document describes the general development process for MindSpore Lite model inference.
## Basic Concepts
Before getting started, you need to understand the following basic concepts:
**Tensor**: a special data structure that is similar to arrays and matrices. It is a basic data structure used in MindSpore Lite network operations.
**Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number.
## Available APIs
APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs.
### Context APIs
| API | Description |
| ------------------ | ----------------- |
|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.|
|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.|
| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.|
|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.|
|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.|
|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.|
|void OH_AI_ContextAddDeviceInfo(OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info)|Adds a runtime device information object.|
### Model APIs
| API | Description |
| ------------------ | ----------------- |
|OH_AI_ModelHandle OH_AI_ModelCreate()|Creates a model object.|
|OH_AI_Status OH_AI_ModelBuildFromFile(OH_AI_ModelHandle model, const char *model_path,OH_AI_ModelType odel_type, const OH_AI_ContextHandle model_context)|Loads and builds a MindSpore model from a model file.|
|void OH_AI_ModelDestroy(OH_AI_ModelHandle *model)|Destroys a model object.|
### Tensor APIs
| API | Description |
| ------------------ | ----------------- |
|OH_AI_TensorHandleArray OH_AI_ModelGetInputs(const OH_AI_ModelHandle model)|Obtains the input tensor array structure of a model.|
|int64_t OH_AI_TensorGetElementNum(const OH_AI_TensorHandle tensor)|Obtains the number of tensor elements.|
|const char *OH_AI_TensorGetName(const OH_AI_TensorHandle tensor)|Obtains the name of a tensor.|
|OH_AI_DataType OH_AI_TensorGetDataType(const OH_AI_TensorHandle tensor)|Obtains the tensor data type.|
|void *OH_AI_TensorGetMutableData(const OH_AI_TensorHandle tensor)|Obtains the pointer to variable tensor data.|
## How to Develop
The following figure shows the development process for MindSpore Lite model inference.
**Figure 1** Development process for MindSpore Lite model inference
![how-to-use-mindspore-lite](figures/01.png)
The development process consists of the following main steps:
1. Prepare the required model.
The required model can be downloaded directly or obtained using the model conversion tool.
- If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format.
2. Create a context, and set parameters such as the number of runtime threads and device type.
```c
// Create a context, and set the number of runtime threads to 2 and the thread affinity mode to 1 (big cores first).
OH_AI_ContextHandle context = OH_AI_ContextCreate();
if (context == NULL) {
printf("OH_AI_ContextCreate failed.\n");
return OH_AI_STATUS_LITE_ERROR;
}
const int thread_num = 2;
OH_AI_ContextSetThreadNum(context, thread_num);
OH_AI_ContextSetThreadAffinityMode(context, 1);
// Set the device type to CPU, and disable Float16 inference.
OH_AI_DeviceInfoHandle cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU);
if (cpu_device_info == NULL) {
printf("OH_AI_DeviceInfoCreate failed.\n");
OH_AI_ContextDestroy(&context);
return OH_AI_STATUS_LITE_ERROR;
}
OH_AI_DeviceInfoSetEnableFP16(cpu_device_info, false);
OH_AI_ContextAddDeviceInfo(context, cpu_device_info);
```
3. Create, load, and build the model.
Call **OH_AI_ModelBuildFromFile** to load and build the model.
In this example, the **argv[1]** parameter passed to **OH_AI_ModelBuildFromFile** indicates the specified model file path.
```c
// Create a model.
OH_AI_ModelHandle model = OH_AI_ModelCreate();
if (model == NULL) {
printf("OH_AI_ModelCreate failed.\n");
OH_AI_ContextDestroy(&context);
return OH_AI_STATUS_LITE_ERROR;
}
// Load and build the model. The model type is OH_AI_ModelTypeMindIR.
int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context);
if (ret != OH_AI_STATUS_SUCCESS) {
printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret);
OH_AI_ModelDestroy(&model);
return ret;
}
```
4. Input data.
Before executing model inference, you need to populate data to the input tensor. In this example, random data is used to populate the model.
```c
// Obtain the input tensor.
OH_AI_TensorHandleArray inputs = OH_AI_ModelGetInputs(model);
if (inputs.handle_list == NULL) {
printf("OH_AI_ModelGetInputs failed, ret: %d.\n", ret);
OH_AI_ModelDestroy(&model);
return ret;
}
// Use random data to populate the tensor.
ret = GenerateInputDataWithRandom(inputs);
if (ret != OH_AI_STATUS_SUCCESS) {
printf("GenerateInputDataWithRandom failed, ret: %d.\n", ret);
OH_AI_ModelDestroy(&model);
return ret;
}
```
5. Execute model inference.
Call **OH_AI_ModelPredict** to perform model inference.
```c
// Execute model inference.
OH_AI_TensorHandleArray outputs;
ret = OH_AI_ModelPredict(model, inputs, &outputs, NULL, NULL);
if (ret != OH_AI_STATUS_SUCCESS) {
printf("OH_AI_ModelPredict failed, ret: %d.\n", ret);
OH_AI_ModelDestroy(&model);
return ret;
}
```
6. Obtain the output.
After model inference is complete, you can obtain the inference result through the output tensor.
```c
// Obtain the output tensor and print the information.
for (size_t i = 0; i < outputs.handle_num; ++i) {
OH_AI_TensorHandle tensor = outputs.handle_list[i];
int64_t element_num = OH_AI_TensorGetElementNum(tensor);
printf("Tensor name: %s, tensor size is %zu ,elements num: %lld.\n", OH_AI_TensorGetName(tensor),
OH_AI_TensorGetDataSize(tensor), element_num);
const float *data = (const float *)OH_AI_TensorGetData(tensor);
printf("output data is:\n");
const int max_print_num = 50;
for (int j = 0; j < element_num && j <= max_print_num; ++j) {
printf("%f ", data[j]);
}
printf("\n");
}
```
7. Destroy the model.
If the MindSpore Lite inference framework is no longer needed, you need to destroy the created model.
```c
// Destroy the model.
OH_AI_ModelDestroy(&model);
```
## Verification
1. Compile **CMakeLists.txt**.
```cmake
cmake_minimum_required(VERSION 3.14)
project(Demo)
add_executable(demo main.c)
target_link_libraries(
demo
mindspore-lite.huawei
pthread
dl
)
```
- To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`.
- The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`.
2. Run the CMake tool.
- Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board.
- Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command:
```shell
./demo mobilenetv2.ms
```
The inference is successful if the output is similar to the following:
```shell
# ./QuickStart ./mobilenetv2.ms
Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001.
output data is:
0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023
```
...@@ -827,7 +827,7 @@ call.reject(1, (error, data) => { ...@@ -827,7 +827,7 @@ call.reject(1, (error, data) => {
## call.reject<sup>7+</sup> ## call.reject<sup>7+</sup>
reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback<void\>\): void reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback<void\>\): void
Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result.
......
...@@ -202,8 +202,8 @@ Updates a contact based on the specified contact information and attributes. Thi ...@@ -202,8 +202,8 @@ Updates a contact based on the specified contact information and attributes. Thi
contact.updateContact({ contact.updateContact({
name: {fullName: 'xxx'}, name: {fullName: 'xxx'},
phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] phoneNumbers: [{phoneNumber: '138xxxxxxxx'}]
},{ }, {
attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err) => { }, (err) => {
if (err) { if (err) {
console.log('updateContact callback: err->${JSON.stringify(err)}'); console.log('updateContact callback: err->${JSON.stringify(err)}');
...@@ -432,7 +432,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn ...@@ -432,7 +432,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn
```js ```js
contact.queryMyCard({ contact.queryMyCard({
attributes:['ATTR_EMAIL', 'ATTR_NAME'] attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => { }, (err, data) => {
if (err) { if (err) {
console.log(`queryMyCard callback: err->${JSON.stringify(err)}`); console.log(`queryMyCard callback: err->${JSON.stringify(err)}`);
...@@ -469,7 +469,7 @@ Queries my card based on the specified contact attributes. This API uses a promi ...@@ -469,7 +469,7 @@ Queries my card based on the specified contact attributes. This API uses a promi
```js ```js
let promise = contact.queryMyCard({ let promise = contact.queryMyCard({
attributes:['ATTR_EMAIL', 'ATTR_NAME'] attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}); });
promise.then((data) => { promise.then((data) => {
console.log(`queryMyCard success: data->${JSON.stringify(data)}`); console.log(`queryMyCard success: data->${JSON.stringify(data)}`);
...@@ -487,7 +487,7 @@ Selects a contact. This API uses an asynchronous callback to return the result. ...@@ -487,7 +487,7 @@ Selects a contact. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.READ_CONTACTS **Permission required**: ohos.permission.READ_CONTACTS
**System capability**: SystemCapability.Applications.ContactsData **System capability**: SystemCapability.Applications.Contacts
**Parameters** **Parameters**
...@@ -516,7 +516,7 @@ Selects a contact. This API uses a promise to return the result. ...@@ -516,7 +516,7 @@ Selects a contact. This API uses a promise to return the result.
**Permission required**: ohos.permission.READ_CONTACTS **Permission required**: ohos.permission.READ_CONTACTS
**System capability**: SystemCapability.Applications.ContactsData **System capability**: SystemCapability.Applications.Contacts
**Return Value** **Return Value**
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -18,11 +19,11 @@ Before using application event logging, you need to understand the requirements ...@@ -18,11 +19,11 @@ Before using application event logging, you need to understand the requirements
**Event Domain** **Event Domain**
An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_).
**Event Name** **Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_).
**Event Type** **Event Type**
...@@ -32,7 +33,7 @@ An event type is an enumerated value of [EventType](#eventtype). ...@@ -32,7 +33,7 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). - The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_).
- The parameter value is a string, number, boolean, or array. - The parameter value is a string, number, boolean, or array.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated.
- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
...@@ -404,12 +405,30 @@ Defines a subscription data holder for processing subscription events. ...@@ -404,12 +405,30 @@ Defines a subscription data holder for processing subscription events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
### constructor<sup>9+</sup>
constructor(watcherName: string);
A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
```
### setSize<sup>9+</sup> ### setSize<sup>9+</sup>
setSize(size: number): void setSize(size: number): void
Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example** **Example**
```js ```js
...@@ -425,6 +444,8 @@ takeNext(): [AppEventPackage](#appeventpackage9) ...@@ -425,6 +444,8 @@ takeNext(): [AppEventPackage](#appeventpackage9)
Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example** **Example**
```js ```js
......
# HiDebug # HiDebug
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
...@@ -16,7 +17,7 @@ import hidebug from '@ohos.hidebug'; ...@@ -16,7 +17,7 @@ import hidebug from '@ohos.hidebug';
getNativeHeapSize(): bigint getNativeHeapSize(): bigint
Obtains the total size of the native heap memory. Obtains the total size of the heap memory of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release. This API is defined but not implemented in OpenHarmony 3.1 Release.
...@@ -26,84 +27,80 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -26,84 +27,80 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
| Type | Description | | Type | Description |
| ------ | --------------------------- | | ------ | --------------------------- |
| bigint | Total size of the native heap memory, in kB.| | bigint | Total size of the heap memory of this application, in kB.|
**Example** **Example**
```js
```js let nativeHeapSize = hidebug.getNativeHeapSize();
let nativeHeapSize = hidebug.getNativeHeapSize(); ```
```
## hidebug.getNativeHeapAllocatedSize ## hidebug.getNativeHeapAllocatedSize
getNativeHeapAllocatedSize(): bigint getNativeHeapAllocatedSize(): bigint
Obtains the size of the allocated native heap memory. Obtains the size of the allocated heap memory of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release. This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
**Return value**
| Type | Description | | Type | Description |
| ------ | --------------------------------- | | ------ | --------------------------------- |
| bigint | Size of the allocated native heap memory, in kB.| | bigint | Size of the allocated heap memory of this application, in kB.|
**Example** **Example**
```js
```js let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize();
let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); ```
```
## hidebug.getNativeHeapFreeSize ## hidebug.getNativeHeapFreeSize
getNativeHeapFreeSize(): bigint getNativeHeapFreeSize(): bigint
Obtains the size of the free native heap memory. Obtains the size of the free heap memory of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release. This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
**Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------------- | | ------ | ------------------------------- |
| bigint | Size of the free native heap memory, in kB.| | bigint | Size of the free heap memory of this application, in kB.|
**Example** **Example**
```js
```js let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize();
let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); ```
```
## hidebug.getPss ## hidebug.getPss
getPss(): bigint getPss(): bigint
Obtains the PSS of this process. Obtains the size of the used physical memory of this process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
**Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------- | | ------ | ------------------------- |
| bigint | PSS of the process, in kB.| | bigint | Used physical memory of this process, in kB.|
**Example** **Example**
```js
```js let pss = hidebug.getPss();
let pss = hidebug.getPss(); ```
```
## hidebug.getSharedDirty ## hidebug.getSharedDirty
...@@ -114,18 +111,17 @@ Obtains the size of the shared dirty memory of this process. ...@@ -114,18 +111,17 @@ Obtains the size of the shared dirty memory of this process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
**Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| bigint | Size of the shared dirty memory of the process, in kB.| | bigint | Size of the shared dirty memory of this process, in kB.|
**Example** **Example**
```js
```js let sharedDirty = hidebug.getSharedDirty();
let sharedDirty = hidebug.getSharedDirty(); ```
```
## hidebug.getPrivateDirty<sup>9+<sup> ## hidebug.getPrivateDirty<sup>9+<sup>
...@@ -135,11 +131,11 @@ Obtains the size of the private dirty memory of this process. ...@@ -135,11 +131,11 @@ Obtains the size of the private dirty memory of this process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
**Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| bigint | Size of the private dirty memory of the process, in kB.| | bigint | Size of the private dirty memory of this process, in kB.|
**Example** **Example**
...@@ -157,18 +153,17 @@ For example, if the CPU usage is **50%**, **0.5** is returned. ...@@ -157,18 +153,17 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
**Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| number | CPU usage of the process.| | number | CPU usage of this process.|
**Example** **Example**
```js
```js let cpuUsage = hidebug.getCpuUsage();
let cpuUsage = hidebug.getCpuUsage(); ```
```
## hidebug.startProfiling ## hidebug.startProfiling
...@@ -195,6 +190,7 @@ hidebug.stopProfiling(); ...@@ -195,6 +190,7 @@ hidebug.stopProfiling();
``` ```
## hidebug.stopProfiling ## hidebug.stopProfiling
stopProfiling() : void stopProfiling() : void
...@@ -225,7 +221,7 @@ Exports data from the specified heap file. ...@@ -225,7 +221,7 @@ Exports data from the specified heap file.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| | filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example** **Example**
...@@ -250,7 +246,6 @@ This is a system API and cannot be called by third-party applications. ...@@ -250,7 +246,6 @@ This is a system API and cannot be called by third-party applications.
| serviceid | number | Yes | ID of the system service. | | serviceid | number | Yes | ID of the system service. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| string | Absolute path of the file that contains the service information to dump. | | string | Absolute path of the file that contains the service information to dump. |
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
Provides system event logging APIs for system HAP applications. Provides system event logging APIs for system HAP applications.
> **NOTE**<br> > **NOTE**
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The 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 are system APIs. > - The APIs of this module are system APIs.
...@@ -19,7 +19,7 @@ Enumerates event types. ...@@ -19,7 +19,7 @@ Enumerates event types.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Default Value| Description| | Name | Default Value | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| FAULT | 1 | Error event.| | FAULT | 1 | Error event.|
| STATISTIC | 2 | Statistic event.| | STATISTIC | 2 | Statistic event.|
...@@ -32,7 +32,7 @@ Defines a system event. ...@@ -32,7 +32,7 @@ Defines a system event.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.| | domain | string | Yes| Event domain.|
| name | string | Yes| Event name.| | name | string | Yes| Event name.|
...@@ -50,7 +50,7 @@ Writes event information to the event file. This API uses an asynchronous callba ...@@ -50,7 +50,7 @@ Writes event information to the event file. This API uses an asynchronous callba
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ------------------------------------------------------------ | | --------- | ------------------------- | ---- | ------------------------------------------------------------ |
| info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | info | [SysEventInfo](#syseventinfo) | Yes| System event information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.<br>- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously. <br>- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.<br>- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.<br>- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously. <br>- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.<br>- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.|
...@@ -91,13 +91,13 @@ Writes event information to the event file. This API uses a promise to return th ...@@ -91,13 +91,13 @@ Writes event information to the event file. This API uses a promise to return th
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory | Description|
| --------- | ----------------------- | ---- | --------------- | | --------- | ----------------------- | ---- | --------------- |
| info | [SysEventInfo](#syseventinfo) | Yes | System event information.| | info | [SysEventInfo](#syseventinfo) | Yes | System event information.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ------------------------------------------------------------ | | ------------------- | ------------------------------------------------------------ |
| Promise&lt;void&gt; | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| | Promise&lt;void&gt; | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.|
...@@ -138,7 +138,7 @@ Enumerates matching rule types. ...@@ -138,7 +138,7 @@ Enumerates matching rule types.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Default Value| Description| | Name | Default Value | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| WHOLE_WORD | 1 | Whole word matching.| | WHOLE_WORD | 1 | Whole word matching.|
| PREFIX | 2 | Prefix matching.| | PREFIX | 2 | Prefix matching.|
...@@ -150,7 +150,7 @@ Defines rules for event subscription. ...@@ -150,7 +150,7 @@ Defines rules for event subscription.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.| | domain | string | Yes| Event domain.|
| name | string | Yes| Event name.| | name | string | Yes| Event name.|
...@@ -163,7 +163,7 @@ Defines a watcher for event subscription. ...@@ -163,7 +163,7 @@ Defines a watcher for event subscription.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| | rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.|
| onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void|
...@@ -181,7 +181,7 @@ Adds a watcher for event subscription. ...@@ -181,7 +181,7 @@ Adds a watcher for event subscription.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| ------ | ----------------------------- | ---- | ------------------------ | | ------ | ----------------------------- | ---- | ------------------------ |
| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
...@@ -223,7 +223,7 @@ Removes a watcher used for event subscription. ...@@ -223,7 +223,7 @@ Removes a watcher used for event subscription.
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory | Description |
| ------ | ------------- | ---- | ------------------------ | | ------ | ------------- | ---- | ------------------------ |
| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
...@@ -260,7 +260,7 @@ Defines arguments for event query. ...@@ -260,7 +260,7 @@ Defines arguments for event query.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| beginTime | number | Yes| Start time (13-digit timestamp) for event query.| | beginTime | number | Yes| Start time (13-digit timestamp) for event query.|
| endTime | number | Yes| End time (13-digit timestamp) for event query.| | endTime | number | Yes| End time (13-digit timestamp) for event query.|
...@@ -272,7 +272,7 @@ Defines rules for event query. ...@@ -272,7 +272,7 @@ Defines rules for event query.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.| | domain | string | Yes| Event domain.|
| names | string[] | Yes| Array of event names.| | names | string[] | Yes| Array of event names.|
...@@ -283,7 +283,7 @@ Defines an event query instance. ...@@ -283,7 +283,7 @@ Defines an event query instance.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void|
| onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void|
...@@ -300,7 +300,7 @@ Queries system events. ...@@ -300,7 +300,7 @@ Queries system events.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type | Mandatory | Description |
| ------ | ----------------------------- | ---- | ------------------------ | | ------ | ----------------------------- | ---- | ------------------------ |
| queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.|
| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.|
......
...@@ -358,7 +358,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -358,7 +358,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. | | method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> | | extraData | string \| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
...@@ -432,7 +432,7 @@ Defines the response to an HTTP request. ...@@ -432,7 +432,7 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| | result | string \| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
......
...@@ -12,1218 +12,2277 @@ The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by app ...@@ -12,1218 +12,2277 @@ The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by app
```js ```js
import huks from '@ohos.security.huks' import huks from '@ohos.security.huks'
``` ```
## HuksErrorCode
Enumerates the error codes. ## HuksParam
**System capability**: SystemCapability.Security.Huks Defines the **param** in the **properties** array of **options** used in the APIs.
| Name | Value | Description| **System capability**: SystemCapability.Security.Huks
| -------------------------- | ----- | ---- |
| HUKS_SUCCESS | 0 |Success.|
| HUKS_FAILURE | -1 |Failure.|
| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.|
| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.|
| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.|
| HUKS_ERROR_NO_PERMISSION | -5 |No permission.|
| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.|
| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.|
| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.|
| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.|
| HUKS_ERROR_STORAGE_FAILURE | -10 |Storage failure.|
| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.|
| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.|
| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.|
| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.|
| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.|
| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.|
| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.|
| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.|
| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.|
| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.|
| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.|
| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.|
| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.|
| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.|
| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.|
| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.|
| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.|
| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.|
| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.|
| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.|
| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.|
| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.|
| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.|
| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.|
| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.|
| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.|
| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.|
| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.|
| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED<sup>9+</sup> | -40 |Failed to obtain the security attribute information of the user.|
| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED<sup>9+</sup> | -41 |Failed to obtain the authentication information of the user.|
| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT<sup>9+</sup> | -42 |The access control of the current authentication type is not supported.|
| HUKS_ERROR_KEY_AUTH_FAILED<sup>9+</sup> | -43 |The access control authentication has failed.|
| HUKS_ERROR_DEVICE_NO_CREDENTIAL<sup>9+</sup> | -44 |No credential has been enrolled for the device.|
| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to check whether the ALG is obtained. |
| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to check whether the key size is obtained.|
| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to check whether padding is obtained.|
| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to check whether the purpose is obtained.|
| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to check whether digest is obtained.|
| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to check whether the mode is obtained.|
| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to check whether the nonce is obtained.|
| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to check whether the AAD is obtained.|
| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to check whether the initialization vector (IV) is obtained.|
| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to check whether the AE flag is obtained.|
| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to check whether the SALT is obtained.|
| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to check whether the iteration is obtained.|
| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.|
| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.|
| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding.|
| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid purpose.|
| HUKS_ERROR_INVALID_MODE | -116 |Invalid mode.|
| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest.|
| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.|
| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.|
| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.|
| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.|
| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.|
| HUKS_ERROR_INVALID_SALT | -123 |Invalid SALT.|
| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration.|
| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.|
| HUKS_ERROR_INVALID_WRAPPED_FORMAT<sup>9+</sup> | -126 |Incorrect format of the wrapped key being imported.|
| HUKS_ERROR_INVALID_USAGE_OF_KEY<sup>9+</sup> | -127 |Incorrect purpose of the wrapped key being imported.|
| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.|
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | ------------ |
| tag | [HuksTag](#hukstag) | Yes | Tag. |
| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.|
## HuksKeyPurpose ## HuksOptions
Enumerates the key purposes. Defines the **options** used in the APIs.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | | Name | Type | Mandatory| Description |
| ------------------------ | ---- | -------------------------------- | | ---------- | ----------------- | ---- | ------------------------ |
| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext.| | properties | Array\<[HuksParam](#huksparam)> | No | Properties used to hold the **HuksParam** array.|
| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| | inData | Uint8Array | No | Input data. |
| HUKS_KEY_PURPOSE_SIGN | 4 | Used to sign data. |
| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signed data. |
| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. |
| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap a key. |
| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used to unwrap a key. |
| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). |
| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. |
## HuksKeyDigest ## HuksSessionHandle<sup>9+</sup>
Enumerates the digest algorithms. Defines the HUKS handle structure.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | | Name | Type | Mandatory| Description |
| ---------------------- | ---- | ---------------------------------------- | | --------- | ---------- | ---- | ---------------------------------------------------- |
| HUKS_DIGEST_NONE | 0 | No digest algorithm| | handle | number | Yes | Value of the handle. |
| HUKS_DIGEST_MD5 | 1 | MD5| | challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.|
| HUKS_DIGEST_SM3<sup>9+</sup> | 2 | SM3|
| HUKS_DIGEST_SHA1 | 10 | SHA1|
| HUKS_DIGEST_SHA224 | 11 | SHA-224|
| HUKS_DIGEST_SHA256 | 12 | SHA-256|
| HUKS_DIGEST_SHA384 | 13 | SHA-384|
| HUKS_DIGEST_SHA512 | 14 | SHA-512|
## HuksKeyPadding ## HuksReturnResult<sup>9+</sup>
Enumerates the padding algorithms. Defines the **HuksResult** structure.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ---------------------- | ---- | ---------------------------------------- |
| HUKS_PADDING_NONE | 0 | No padding algorithm|
| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)|
| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)|
| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5|
| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5|
| HUKS_PADDING_PKCS7 | 5 | PKCS #7|
## HuksCipherMode
Enumerates the cipher modes. | Name | Type | Mandatory| Description |
| ---------- | ------------------------------- | ---- | ---------------- |
| outData | Uint8Array | No | Output data. |
| properties | Array\<[HuksParam](#huksparam)> | No | Property information. |
| certChains | Array\<string> | No | Certificate chain information.|
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description | ## huks.generateKeyItem<sup>9+</sup>
| ------------- | ---- | --------------------- |
| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode|
| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode|
| HUKS_MODE_CTR | 3 | Counter (CTR) mode|
| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode|
| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode|
| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode|
## HuksKeySize generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
Enumerates the key sizes. Generates a key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | **Parameters**
| ---------------------------------- | ---- | ------------------------------------------ |
| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits |
| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits |
| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits |
| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits |
| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits |
| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits |
| HUKS_ECC_KEY_SIZE_224 | 224 | ECC key of 224 bits |
| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits |
| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits |
| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits |
| HUKS_AES_KEY_SIZE_128 | 128 | AES key of 128 bits |
| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits |
| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits |
| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits |
| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits|
| HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits |
| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits |
| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits |
| HUKS_SM2_KEY_SIZE_256<sup>9+</sup> | 256 | SM2 key of 256 bits |
| HUKS_SM4_KEY_SIZE_128<sup>9+</sup> | 128 | SM4 key of 128 bits |
## HuksKeyAlg | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
Enumerates the key algorithms. **Example**
**System capability**: SystemCapability.Security.Huks ```js
/* Generate an ECC key of 256 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
properties: properties
};
try {
huks.generateKeyItem(keyAlias, options, function (error, data) {
if (error) {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: generateKeyItem key success`);
}
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
| Name | Value | Description | ## huks.generateKeyItem<sup>9+</sup>
| ------------------------- | ---- | --------------------- |
| HUKS_ALG_RSA | 1 | RSA |
| HUKS_ALG_ECC | 2 | ECC |
| HUKS_ALG_DSA | 3 | DSA |
| HUKS_ALG_AES | 20 | AES |
| HUKS_ALG_HMAC | 50 | HMAC |
| HUKS_ALG_HKDF | 51 | HKDF |
| HUKS_ALG_PBKDF2 | 52 | PBKDF2 |
| HUKS_ALG_ECDH | 100 | ECDH |
| HUKS_ALG_X25519 | 101 | X25519 |
| HUKS_ALG_ED25519 | 102 | ED25519|
| HUKS_ALG_DH | 103 | DH |
| HUKS_ALG_SM2<sup>9+</sup> | 150 | SM2 |
| HUKS_ALG_SM3<sup>9+</sup> | 151 | SM3 |
| HUKS_ALG_SM4<sup>9+</sup> | 152 | SM4 |
## HuksKeyGenerateType generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
Enumerates the key generation types. Generates a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | **Parameters**
| ------------------------------ | ---- | ---------------- |
| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.|
| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.|
| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.|
## HuksKeyFlag | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.|
Enumerates the key generation modes. **Example**
**System capability**: SystemCapability.Security.Huks ```js
/* Generate an ECC key of 256 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
properties: properties
};
try {
huks.generateKeyItem(keyAlias, options)
.then((data) => {
console.info(`promise: generateKeyItem success`);
})
.catch(error => {
console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
| Name | Value | Description | ## huks.deleteKeyItem<sup>9+</sup>
| -------------------------- | ---- | ------------------------------------ |
| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. |
| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. |
| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API.|
| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API.|
## HuksKeyStorageType deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
Enumerates the key storage modes. Deletes a key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | **Parameters**
| ----------------------- | ---- | ------------------------------ |
| HUKS_STORAGE_TEMP | 0 | The key is managed locally. |
| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.|
## HuksSendType | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Key alias passed in when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
Enumerates the tag transfer modes. **Example**
**System capability**: SystemCapability.Security.Huks ```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
properties: []
};
try {
huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) {
if (error) {
console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: deleteKeyItem key success`);
}
});
} catch (error) {
console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
```
| Name | Value | Description | ## huks.deleteKeyItem<sup>9+</sup>
| -------------------- | ---- | ----------------- |
| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.|
| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.|
## HuksUnwrapSuite<sup>9+</sup> deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
Enumerates the algorithm suites used when a wrapped key is imported. Deletes a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | **Parameters**
| ---------------------------------------------- | ---- | ----------------------------------------------------- |
| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.|
| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. |
## HuksImportKeyType<sup>9+</sup>
Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ----------------------------------- |
| keyAlias | string | Yes | Key alias passed in when the key was generated.|
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
**System capability**: SystemCapability.Security.Huks **Example**
| Name | Value | Description | ```js
| ------------------------- | ---- | ------------------------------ | /* Set options to emptyOptions. */
| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | let keyAlias = 'keyAlias';
| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | let emptyOptions = {
| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| properties: []
};
## HuksUserAuthType<sup>9+</sup> try {
huks.deleteKeyItem(keyAlias, emptyOptions)
Enumerates the user authentication types. .then ((data) => {
console.info(`promise: deleteKeyItem key success`);
**System capability**: SystemCapability.Security.Huks })
.catch(error => {
| Name | Value | Description | console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`);
| ------------------------------- | ---- | ------------------------- | });
| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | } catch (error) {
| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| }
```
## HuksAuthAccessType<sup>9+</sup>
Enumerates the access control types.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| --------------------------------------- | ---- | ------------------------------------------------ |
| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key is invalid after the password is cleared. |
| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key is invalid after a new biometric feature is added.|
## HuksChallengeType<sup>9+</sup>
Enumerates the types of the challenges generated when a key is used.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.|
| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.|
| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.|
## HuksChallengePosition<sup>9+</sup>
Enumerates the positions of the 8-byte valid value in a custom challenge generated.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7 indicate the valid challenge of the key.|
| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15 indicate the valid challenge of the key.|
| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23 indicate the valid challenge of the key.|
| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31 indicate the valid challenge of the key.|
## HuksSecureSignType<sup>9+</sup>
Defines the signature type of the key generated or imported.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description | ## huks.getSdkVersion
| ------------------------------ | ---- | ------------------------------------------------------------ |
| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used to sign data, the data will be added with the authentication information and then be signed.|
## HuksTagType getSdkVersion(options: HuksOptions) : string
Enumerates the tag data types. Obtains the SDK version of the current system.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Value | Description | | Name | Type | Mandatory| Description |
| --------------------- | ------- | --------------------------------------- | | ------- | ---------- | ---- | ------------------------- |
| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | | options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.|
| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. |
| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.|
| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. |
| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. |
| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. |
## HuksTag **Return value**
Enumerates the tags used to invoke parameters. | Type | Description |
| ------ | ------------- |
| string | SDK version obtained.|
**System capability**: SystemCapability.Security.Huks **Example**
| Name | Value | Description | ```js
| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | /* Set options to emptyOptions. */
| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | let emptyOptions = {
| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | properties: []
| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | };
| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | let result = huks.getSdkVersion(emptyOptions);
| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | ```
| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. |
| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. |
| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. |
| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. |
| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. |
| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. |
| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. |
| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. |
| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. |
| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. |
| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. |
| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. |
| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. |
| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. |
| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. |
| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. |
| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. |
| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. |
| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. |
| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. |
| HUKS_TAG_IMPORT_KEY_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. |
| HUKS_TAG_UNWRAP_ALGORITHM_SUITE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. |
| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. |
| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. |
| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. |
| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. |
| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. |
| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. |
| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. |
| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.|
| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. |
| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. |
| HUKS_TAG_KEY_AUTH_ACCESS_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).|
| HUKS_TAG_KEY_SECURE_SIGN_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.|
| HUKS_TAG_CHALLENGE_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).|
| HUKS_TAG_CHALLENGE_POS<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).|
| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. |
| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. |
| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. |
| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. |
| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. |
| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. |
| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. |
| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. |
| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. |
| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. |
| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. |
| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. |
| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.|
| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. |
| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. |
| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. |
| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. |
| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. |
| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. |
| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. |
| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. |
| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. |
| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. |
| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. |
| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. |
| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. |
| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. |
| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. |
| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. |
| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. |
| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. |
| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. |
| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. |
| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. |
| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. |
| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. |
| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. |
| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. |
## huks.generateKey ## huks.importKeyItem<sup>9+</sup>
generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
Generates a key. This API uses an asynchronous callback to return the result. Imports a key in plaintext. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code defined in **HuksResult** will be returned.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
**Example** **Example**
```js ```js
/* Generate an RSA key of 512 bits. */ /* Import an AES key of 256 bits. */
var keyAlias = 'keyAlias'; let plainTextSize32 = makeRandomArr(32);
var properties = new Array(); function makeRandomArr(size) {
let arr = new Uint8Array(size);
for (let i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
return arr;
};
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA value: huks.HuksKeyAlg.HUKS_ALG_AES
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_OAEP value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}; };
properties[4] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
var options = { let options = {
properties: properties properties: properties,
inData: plainTextSize32
}; };
huks.generateKey(keyAlias, options, function (err, data){}); try {
huks.importKeyItem(keyAlias, options, function (error, data) {
if (error) {
console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: importKeyItem success`);
}
});
} catch (error) {
console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
``` ```
## huks.generateKey ## huks.importKeyItem<sup>9+</sup>
generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> importKeyItem(keyAlias: string, options: HuksOptions) : Promise\<void>
Generates a key. This API uses a promise to return the result. Imports a key in plaintext. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------ | | -------- | --------------------------- | ---- | ----------------------------------- |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.|
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
**Example** **Example**
```js ```js
/* Generate an ECC key of 256 bits. */ /* Import an AES key of 128 bits. */
var keyAlias = 'keyAlias'; let plainTextSize32 = makeRandomArr(32);
var properties = new Array();
function makeRandomArr(size) {
let arr = new Uint8Array(size);
for (let i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
return arr;
};
/* Step 1 Generate a key. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC value: huks.HuksKeyAlg.HUKS_ALG_AES
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}; };
var options = { properties[4] = {
properties: properties tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
var result = huks.generateKey(keyAlias, options); let huksoptions = {
properties: properties,
inData: plainTextSize32
};
try {
huks.importKeyItem(keyAlias, huksoptions)
.then ((data) => {
console.info(`promise: importKeyItem success`);
})
.catch(error => {
console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
``` ```
## huks.deleteKey ## huks.attestKeyItem<sup>9+</sup>
deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
Deletes a key. This API uses an asynchronous callback to return the result. Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Key alias passed in when the key was generated. | | keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ let securityLevel = stringToUint8Array('sec_level');
var keyAlias = 'keyAlias'; let challenge = stringToUint8Array('challenge_data');
var emptyOptions = { let versionInfo = stringToUint8Array('version_info');
properties: [] let keyAliasString = "key attest";
};
huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
async function generateKey(alias) {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
properties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
properties[7] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties
};
try {
huks.generateKeyItem(alias, options, function (error, data) {
if (error) {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: generateKeyItem success`);
}
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function attestKey() {
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8
};
let options = {
properties: properties
};
await generateKey(aliasString);
try {
huks.attestKeyItem(aliasString, options, function (error, data) {
if (error) {
console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: attestKeyItem success`);
}
});
} catch (error) {
console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
``` ```
## huks.deleteKey ## huks.attestKeyItem<sup>9+</sup>
deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
Deletes a key. This API uses a promise to return the result. Obtains the certificate used to verify a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ----------------------------------------------------- | | -------- | --------------------------- | ---- | ------------------------------------ |
| keyAlias | string | Yes | Key alias passed in when the key was generated.| | keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.|
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ---------------------------------------------- | --------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ let securityLevel = stringToUint8Array('sec_level');
var keyAlias = 'keyAlias'; let challenge = stringToUint8Array('challenge_data');
var emptyOptions = { let versionInfo = stringToUint8Array('version_info');
properties: [] let keyAliasString = "key attest";
};
var result = huks.deleteKey(keyAlias, emptyOptions); function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
async function generateKey(alias) {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
properties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
properties[7] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties
};
try {
await huks.generateKeyItem(alias, options)
.then((data) => {
console.info(`promise: generateKeyItem success`);
})
.catch(error => {
console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function attestKey() {
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8
};
let options = {
properties: properties
};
await generateKey(aliasString);
try {
await huks.attestKeyItem(aliasString, options)
.then ((data) => {
console.info(`promise: attestKeyItem success`);
})
.catch(error => {
console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
``` ```
## huks.getSdkVersion ## huks.importWrappedKeyItem<sup>9+</sup>
getSdkVersion(options: HuksOptions) : string importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void
Obtains the SDK version of the current system. Imports a wrapped key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ---------- | ---- | ------------------------- | | ---------------- | --------------------------- | ---- | --------------------------------------------- |
| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| | keyAlias | string | Yes | Alias of the wrapped key to import. |
| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. |
**Return value** | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.|
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
| Type | Description |
| ------ | ------------- |
| string | SDK version obtained.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ import huks from '@ohos.security.huks';
var emptyOptions = {
properties: [] let exportWrappingKey;
let alias1 = "importAlias";
let alias2 = "wrappingKeyAlias";
async function TestGenFunc(alias, options) {
try {
await genKey(alias, options)
.then((data) => {
console.info(`callback: generateKeyItem success`);
})
.catch(error => {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function genKey(alias, options) {
return new Promise((resolve, reject) => {
try {
huks.generateKeyItem(alias, options, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function TestExportFunc(alias, options) {
try {
await exportKey(alias, options)
.then ((data) => {
console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
exportWrappingKey = data.outData;
})
.catch(error => {
console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function exportKey(alias, options) : Promise<huks.HuksReturnResult> {
return new Promise((resolve, reject) => {
try {
huks.exportKeyItem(alias, options, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function TestImportWrappedFunc(alias, wrappingAlias, options) {
try {
await importWrappedKey(alias, wrappingAlias, options)
.then ((data) => {
console.info(`callback: importWrappedKeyItem success`);
})
.catch(error => {
console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
function importWrappedKey(alias, wrappingAlias, options) {
return new Promise((resolve, reject) => {
try {
huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) {
if (error) {
reject(error);
} else {
resolve(data);
}
});
} catch (error) {
throw(error);
}
});
}
async function TestImportWrappedKeyFunc(
alias,
wrappingAlias,
genOptions,
importOptions
) {
await TestGenFunc(wrappingAlias, genOptions);
await TestExportFunc(wrappingAlias, genOptions);
/*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here.
* For example, import **keyA**.
* 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**.
* 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**.
* 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**.
* 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**.
* 5. Generate the **importOptions.inData** field in the following format:
* keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 +
* nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 +
* kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 +
* nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 +
* Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc
*/
let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]);
importOptions.inData = inputKey;
await TestImportWrappedFunc(alias, wrappingAlias, importOptions);
}
function makeGenerateOptions() {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE,
value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR,
};
let options = {
properties: properties
};
return options;
}; };
var result = huks.getSdkVersion(emptyOptions);
function makeImportOptions() {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_CBC
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE,
value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING
};
let options = {
properties: properties
};
return options;
};
function huksImportWrappedKey() {
let genOptions = makeGenerateOptions();
let importOptions = makeImportOptions();
TestImportWrappedKeyFunc(
alias1,
alias2,
genOptions,
importOptions
);
}
``` ```
## huks.importKey ## huks.importWrappedKeyItem<sup>9+</sup>
importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<void>
Imports a key in plaintext. This API uses an asynchronous callback to return the result. Imports a wrapped key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------------------------------- | | ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the key to import.| | keyAlias | string | Yes | Alias of the wrapped key to import. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| | wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.|
**Example** **Example**
```js ```js
/* Import an AES key of 256 bits. */ /* The process is similar as if a callback is used, except the following:*/
var plainTextSize32 = makeRandomArr(32); async function TestImportWrappedFunc(alias, wrappingAlias, options) {
function makeRandomArr(size) { try {
var arr = new Uint8Array(size); await huks.importWrappedKeyItem(alias, wrappingAlias, options)
for (var i = 0; i < size; i++) { .then ((data) => {
arr[i] = Math.floor(Math.random() * 10); console.info(`promise: importWrappedKeyItem success`);
})
.catch(error => {
console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
return arr; }
}; ```
var keyAlias = 'keyAlias';
var properties = new Array(); ## huks.exportKeyItem<sup>9+</sup>
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
value: huks.HuksKeyAlg.HUKS_ALG_AES
}; Exports a key. This API uses an asynchronous callback to return the result.
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, **System capability**: SystemCapability.Security.Huks
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
}; **Parameters**
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, | Name | Type | Mandatory| Description |
value: | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
}; | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
properties[3] = { | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.|
tag: huks.HuksTag.HUKS_TAG_PADDING,
value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 **Example**
};
properties[4] = { ```js
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, /* Set options to emptyOptions. */
value: huks.HuksCipherMode.HUKS_MODE_ECB let keyAlias = 'keyAlias';
}; let emptyOptions = {
var options = { properties: []
properties: properties,
inData: plainTextSize32
}; };
huks.importKey(keyAlias, options, function (err, data){}); try {
huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) {
if (error) {
console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`);
}
});
} catch (error) {
console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
``` ```
## huks.importKey ## huks.exportKeyItem<sup>9+</sup>
importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
Imports a key in plaintext. This API uses a promise to return the result. Exports a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ------------------------------------ | | -------- | --------------------------- | ---- | -------------------------------------------- |
| keyAlias | string | Yes | Alias of the key to import.| | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.|
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ---------------------------------------------- | ------------------------------------------------------------ |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.|
**Example** **Example**
```js ```js
/* Import an AES key of 128 bits. */ /* Set options to emptyOptions. */
var plainTextSize32 = makeRandomArr(32); let keyAlias = 'keyAlias';
let emptyOptions = {
function makeRandomArr(size) { properties: []
var arr = new Uint8Array(size);
for (var i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
return arr;
};
/* Step 1 Generate a key. */
var keyAlias = 'keyAlias';
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
var huksoptions = {
properties: properties,
inData: plainTextSize32
}; };
var result = huks.importKey(keyAlias, huksoptions); try {
huks.exportKeyItem(keyAlias, emptyOptions)
.then ((data) => {
console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
``` ```
## huks.attestkey<sup>9+</sup> ## huks.getKeyItemProperties<sup>9+</sup>
attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. Obtains key properties. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.|
**Example** **Example**
```js ```js
let securityLevel = stringToUint8Array('sec_level'); /* Set options to emptyOptions. */
let challenge = stringToUint8Array('challenge_data'); let keyAlias = 'keyAlias';
let versionInfo = stringToUint8Array('version_info'); let emptyOptions = {
let keyAliasString = "key attest"; properties: []
};
function stringToUint8Array(str) { try {
var arr = []; huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) {
for (var i = 0, j = str.length; i < j; ++i) { if (error) {
arr.push(str.charCodeAt(i)); console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`);
} } else {
var tmpUint8Array = new Uint8Array(arr); console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
return tmpUint8Array; }
});
} catch (error) {
console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
```
function printLog(...data) { ## huks.getKeyItemProperties<sup>9+</sup>
console.error(data.toString());
}
async function generateKey(alias) { getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksReturnResult>
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
properties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
properties[7] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties
};
await huks.generateKey(alias, options).then(async (data) => { Obtains key properties. This API uses a promise to return the result.
console.error(`generateKey data ${JSON.stringify(data)}`);
}).catch((err) => { **System capability**: SystemCapability.Security.Huks
console.error(`generateKey err: " + ${JSON.stringify(err)}`);
});; **Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------------------------- |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.|
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
**Return value**
| Type | Description |
| ----------------------------------------------- | ------------------------------------------------------------ |
| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.|
**Example**
```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
properties: []
};
try {
huks.getKeyItemProperties(keyAlias, emptyOptions)
.then ((data) => {
console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
```
async function attestKey() { ## huks.isKeyItemExist<sup>9+</sup>
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString); isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void
let properties = new Array();
properties[0] = { Checks whether a key exists. This API uses an asynchronous callback to return the result.
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel **System capability**: SystemCapability.Security.Huks
};
properties[1] = { **Parameters**
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge | Name | Type | Mandatory| Description |
}; | -------- | --------------------------- | ---- | --------------------------------------- |
properties[2] = { | keyAlias | string | Yes | Alias of the key to check. |
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
value: versionInfo | callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.|
};
properties[3] = { **Example**
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8 ```js
}; /* Set options to emptyOptions. */
let options = { let keyAlias = 'keyAlias';
properties: properties let emptyOptions = {
}; properties: []
await generateKey(aliasString); };
huks.attestKey(aliasString, options, function (err, data) { try {
printLog(`key attest result : ${JSON.stringify(data)}`); huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) {
}); if (error) {
console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`);
} else {
console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
}
});
} catch (error) {
console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
``` ```
## huks.attestkey<sup>9+</sup> ## huks.isKeyItemExist<sup>9+</sup>
attestKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
Obtains the certificate used to verify a key. This API uses a promise to return the result. Checks whether a key exists. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | | keyAlias | string | Yes | Alias of the key to check. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------- | --------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.|
**Example** **Example**
```js ```js
let securityLevel = stringToUint8Array('sec_level'); /* Set options to emptyOptions. */
let challenge = stringToUint8Array('challenge_data'); let keyAlias = 'keyAlias';
let versionInfo = stringToUint8Array('version_info'); let emptyOptions = {
let keyAliasString = "key attest"; properties: []
};
function stringToUint8Array(str) { try {
var arr = []; huks.isKeyItemExist(keyAlias, emptyOptions)
for (var i = 0, j = str.length; i < j; ++i) { .then ((data) => {
arr.push(str.charCodeAt(i)); console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`);
} })
var tmpUint8Array = new Uint8Array(arr); .catch(error => {
return tmpUint8Array; console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`);
} }
```
function printLog(...data) { ## huks.initSession<sup>9+</sup>
console.error(data.toString());
}
async function generateKey(alias) { initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
properties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
properties[7] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties
};
await huks.generateKey(alias, options).then(async (data) => { Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
console.error(`generateKey data ${JSON.stringify(data)}`);
}).catch((err) => {
console.error(`generateKey err: " + ${JSON.stringify(err)}`);
});;
}
async function attestKey() { **System capability**: SystemCapability.Security.Huks
let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString);
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
value: securityLevel
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
value: challenge
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
value: versionInfo
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
value: aliasUint8
};
let options = {
properties: properties
};
await generateKey(aliasString);
huks.attestKey(aliasString, options)
.then((data) => {
console.log(`test attestKey data: ${JSON.stringify(data)}`);
})
.catch((err) => {
console.log('test attestKey information: ' + JSON.stringify(err));
});
}
```
## huks.importWrappedKey<sup>9+</sup> **Parameters**
importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- |
| keyAlias | string | Yes | Alias of the target key. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. |
| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.|
Imports a wrapped key. This API uses an asynchronous callback to return the result.
## huks.initSession<sup>9+</sup>
initSession(keyAlias: string, options: HuksOptions) : Promise\<HuksSessionHandle>
Initializes the data for a key operation. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ |
| keyAlias | string | Yes | Alias of the target key. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. |
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.|
## huks.updateSession<sup>9+</sup>
updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.|
## huks.updateSession<sup>9+</sup>
updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void
Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| token | Uint8Array | Yes | Token of the **Update** operation. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.|
## huks.updateSession<sup>9+</sup>
updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult>
Updates the key operation data by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| token | Uint8Array | No | Token of the **Update** operation. |
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.|
## huks.finishSession<sup>9+</sup>
finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void
Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | Yes | Token for the **Finish** operation. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.|
## huks.finishSession<sup>9+</sup>
finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void
Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | Yes | Token for the **Finish** operation. |
| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.|
## huks.finishSession<sup>9+</sup>
finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksReturnResult>
Completes the key operation and releases resources. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------------- | ---- | ----------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | No | Token for the **Finish** operation. |
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.|
## huks.abortSession<sup>9+</sup>
abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\<void>) : void
Aborts the use of the key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | --------------------------- | ---- | ------------------------------------------- |
| keyAlias | string | Yes | Alias of the wrapped key to import. | | handle | number | Yes | Handle of the **Abort** operation. |
| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. | | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
**Example** **Example**
```js ```js
var exportWrappingKey; /* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
var alias1 = "importAlias"; * If an error occurs in any of huks.initSession, huks.updateSession,
var alias2 = "wrappingKeyAlias"; * and huks.finishSession operation,
* huks.abortSession must be called to terminate the use of the key.
async function TestGenFunc(alias, options) { *
await genKey(alias, options) * The following uses the callback of an RSA1024 key as an example.
.then((data) => { */
console.log(`test genKey data: ${JSON.stringify(data)}`); function stringToUint8Array(str) {
}) let arr = [];
.catch((err) => { for (let i = 0, j = str.length; i < j; ++i) {
console.log('test genKey err information: ' + JSON.stringify(err)); arr.push(str.charCodeAt(i));
}); }
let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
} }
function genKey(alias, options) { let keyAlias = "HuksDemoRSA";
return new Promise((resolve, reject) => { let properties = new Array();
huks.generateKey(alias, options, function (err, data) { let options = {
console.log(`test genKey data: ${JSON.stringify(data)}`); properties: properties,
if (err.code !== 0) { inData: new Uint8Array(0)
console.log('test genKey err information: ' + JSON.stringify(err)); };
reject(err); let handle;
} else { async function generateKey() {
resolve(data); properties[0] = {
} tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
}); value: huks.HuksKeyAlg.HUKS_ALG_RSA
}); };
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB,
}
try {
await huks.generateKeyItem(keyAlias, options, function (error, data) {
if (error) {
console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
} else {
console.info(`callback: generateKeyItem success`);
}
});
} catch (error) {
console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
async function TestExportFunc(alias, options) { async function huksInit() {
await exportKey(alias, options) console.log('enter huksInit');
.then((data) => { try {
console.log(`test exportKey data: ${JSON.stringify(data)}`); huks.initSession(keyAlias, options, function (error, data) {
}) if (error) {
.catch((err) => { console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`);
console.log('test exportKey err information: ' + JSON.stringify(err)); } else {
}); console.info(`callback: initSession success, data = ${JSON.stringify(data)}`);
handle = data.handle;
}
});
} catch (error) {
console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
function exportKey(alias, options) { async function huksUpdate() {
return new Promise((resolve, reject) => { console.log('enter huksUpdate');
huks.exportKey(alias, options, function (err, data) { options.inData = stringToUint8Array("huksHmacTest");
console.log(`test exportKey data: ${JSON.stringify(data)}`); try {
if (err.code !== 0) { huks.updateSession(handle, options, function (error, data) {
console.log('test exportKey err information: ' + JSON.stringify(err)); if (error) {
reject(err); console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`);
} else { } else {
exportWrappingKey = data.outData; console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`);
resolve(data); }
} });
}); } catch (error) {
}); console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
async function TestImportWrappedFunc(alias, wrappingAlias, options) { async function huksFinish() {
await importWrappedKey(alias, wrappingAlias, options) console.log('enter huksFinish');
.then((data) => { options.inData = new Uint8Array(0);
console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`); try {
}) huks.finishSession(handle, options, function (error, data) {
.catch((err) => { if (error) {
console.log('test importWrappedKey err information: ' + JSON.stringify(err)); console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`);
}); } else {
console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`);
}
});
} catch (error) {
console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
function importWrappedKey(alias, wrappingAlias, options) { async function huksAbort() {
return new Promise((resolve, reject) => { console.log('enter huksAbort');
huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) { try {
console.log(`importWrappedKey data: ${JSON.stringify(data)}`); huks.abortSession(handle, options, function (error, data) {
if (err.code !== 0) { if (error) {
console.log('importWrappedKey err information: ' + JSON.stringify(err)); console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`);
reject(err); } else {
} else { console.info(`callback: abortSession success`);
resolve(data); }
} });
}); } catch (error) {
}); console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
} }
```
async function TestImportWrappedKeyFunc( ## huks.abortSession<sup>9+</sup>
alias,
wrappingAlias,
genOptions,
importOptions
) {
await TestGenFunc(wrappingAlias, genOptions);
await TestExportFunc(wrappingAlias, genOptions);
/*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. abortSession(handle: number, options: HuksOptions) : Promise\<void>;
* For example, import **keyA**.
* 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. Aborts the use of the key. This API uses a promise to return the result.
* 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**.
* 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. **System capability**: SystemCapability.Security.Huks
* 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, ** aad2**, ciphertext **kek_enc**, and encrypted **tag2**.
* 5. Generate the **importOptions.inData** field in the following format: **Parameters**
* keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 +
* nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + | Name | Type | Mandatory| Description |
* kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + | ------- | --------------------------- | ---- | ------------------------------------------- |
* nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + | handle | number | Yes | Handle of the **Abort** operation. |
* Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. |
*/
var inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); **Return value**
importOptions.inData = inputKey;
await TestImportWrappedFunc(alias, wrappingAlias, importOptions); | Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
/* huks.initSession, huks.updateSession, and huks.finishSession must be used together.
* If an error occurs in any of huks.initSession, huks.updateSession,
* and huks.finishSession operation,
* huks.abortSession must be called to terminate the use of the key.
*
* The following uses the callback of an RSA1024 key as an example.
*/
function stringToUint8Array(str) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
} }
function makeGenerateOptions() { let keyAlias = "HuksDemoRSA";
var properties = new Array(); let properties = new Array();
properties[0] = { let options = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, properties: properties,
value: huks.HuksKeyAlg.HUKS_ALG_ECC inData: new Uint8Array(0)
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
var options = {
properties: properties
};
return options;
}; };
let handle;
async function generateKey() {
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB,
}
function makeImportOptions() { try {
var properties = new Array(); await huks.generateKeyItem(keyAlias, options)
properties[0] = { .then((data) => {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, console.info(`promise: generateKeyItem success`);
value: huks.HuksKeyAlg.HUKS_ALG_AES })
}; .catch(error => {
properties[1] = { console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`);
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, });
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 } catch (error) {
}; console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`);
properties[2] = { }
tag: huks.HuksTag.HUKS_TAG_PURPOSE, }
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}; async function huksInit() {
properties[3] = { console.log('enter huksInit');
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, try {
value: huks.HuksCipherMode.HUKS_MODE_CBC await huks.initSession(keyAlias, options)
}; .then ((data) => {
properties[4] = { console.info(`promise: initSession success, data = ${JSON.stringify(data)}`);
tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, handle = data.handle;
value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING })
}; .catch(error => {
var options = { console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`);
properties: properties });
}; } catch (error) {
return options; console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function huksUpdate() {
console.log('enter huksUpdate');
options.inData = stringToUint8Array("huksHmacTest");
try {
await huks.updateSession(handle, options)
.then ((data) => {
console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function huksFinish() {
console.log('enter huksFinish');
options.inData = new Uint8Array(0);
try {
await huks.finishSession(handle, options)
.then ((data) => {
console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`);
})
.catch(error => {
console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
async function huksAbort() {
console.log('enter huksAbort');
try {
await huks.abortSession(keyAlias, options)
.then ((data) => {
console.info(`promise: abortSession success`);
})
.catch(error => {
console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`);
});
} catch (error) {
console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`);
}
}
```
## HuksExceptionErrCode<sup>9+</sup>
Enumerates the error codes.
For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md).
**System capability**: SystemCapability.Security.Huks
| Name | Description | Error Code |
| ---------------------------------------------- | --------------------------- | -------- |
| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 |
| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 |
| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 |
| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 |
| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 |
| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 |
| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 |
| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 |
| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 |
| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 |
| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 |
| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 |
| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 |
| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 |
| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 |
| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 |
| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 |
| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 |
## HuksKeyPurpose
Enumerates the key purposes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------ | ---- | -------------------------------- |
| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.|
| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.|
| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. |
| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. |
| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. |
| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. |
| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. |
| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). |
| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. |
## HuksKeyDigest
Enumerates the digest algorithms.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ---------------------- | ---- | ---------------------------------------- |
| HUKS_DIGEST_NONE | 0 | No digest algorithm|
| HUKS_DIGEST_MD5 | 1 | MD5|
| HUKS_DIGEST_SM3<sup>9+</sup> | 2 | SM3|
| HUKS_DIGEST_SHA1 | 10 | SHA-1|
| HUKS_DIGEST_SHA224 | 11 | SHA-224|
| HUKS_DIGEST_SHA256 | 12 | SHA-256|
| HUKS_DIGEST_SHA384 | 13 | SHA-384|
| HUKS_DIGEST_SHA512 | 14 | SHA-512|
## HuksKeyPadding
Enumerates the padding algorithms.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ---------------------- | ---- | ---------------------------------------- |
| HUKS_PADDING_NONE | 0 | No padding algorithm|
| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)|
| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)|
| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5|
| HUKS_PADDING_PKCS5 | 4 | PKCS #5|
| HUKS_PADDING_PKCS7 | 5 | PKCS #7|
## HuksCipherMode
Enumerates the cipher modes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------- | ---- | --------------------- |
| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode|
| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode|
| HUKS_MODE_CTR | 3 | Counter (CTR) mode|
| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode|
| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode|
| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode|
## HuksKeySize
Enumerates the key sizes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ---------------------------------- | ---- | ------------------------------------------ |
| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits |
| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits |
| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits |
| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits |
| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits |
| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits |
| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits |
| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits |
| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits |
| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits |
| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits |
| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits |
| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits |
| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits |
| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits|
| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits |
| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits |
| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits |
| HUKS_SM2_KEY_SIZE_256<sup>9+</sup> | 256 | ShangMi2 (SM2) key of 256 bits |
| HUKS_SM4_KEY_SIZE_128<sup>9+</sup> | 128 | ShangMi4 (SM4) key of 128 bits |
## HuksKeyAlg
Enumerates the key algorithms.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------- | ---- | --------------------- |
| HUKS_ALG_RSA | 1 | RSA |
| HUKS_ALG_ECC | 2 | ECC |
| HUKS_ALG_DSA | 3 | DSA |
| HUKS_ALG_AES | 20 | AES |
| HUKS_ALG_HMAC | 50 | HMAC |
| HUKS_ALG_HKDF | 51 | HKDF |
| HUKS_ALG_PBKDF2 | 52 | PBKDF2 |
| HUKS_ALG_ECDH | 100 | ECDH |
| HUKS_ALG_X25519 | 101 | X25519 |
| HUKS_ALG_ED25519 | 102 | ED25519|
| HUKS_ALG_DH | 103 | DH |
| HUKS_ALG_SM2<sup>9+</sup> | 150 | SM2 |
| HUKS_ALG_SM3<sup>9+</sup> | 151 | SM3 |
| HUKS_ALG_SM4<sup>9+</sup> | 152 | SM4 |
## HuksKeyGenerateType
Enumerates the key generation types.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------ | ---- | ---------------- |
| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.|
| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.|
| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.|
## HuksKeyFlag
Enumerates the key generation modes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| -------------------------- | ---- | ------------------------------------ |
| HUKS_KEY_FLAG_IMPORT_KEY | 1 | Import a key using an API. |
| HUKS_KEY_FLAG_GENERATE_KEY | 2 | Generate a key by using an API. |
| HUKS_KEY_FLAG_AGREE_KEY | 3 | Generate a key by using a key agreement API.|
| HUKS_KEY_FLAG_DERIVE_KEY | 4 | Derive a key by using an API.|
## HuksKeyStorageType
Enumerates the key storage modes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ----------------------- | ---- | ------------------------------ |
| HUKS_STORAGE_TEMP | 0 | The key is managed locally. |
| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.|
## HuksSendType
Enumerates the tag transfer modes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| -------------------- | ---- | ----------------- |
| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.|
| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.|
## HuksUnwrapSuite<sup>9+</sup>
Enumerates the algorithm suites required for encrypted imports.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ---------------------------------------------- | ---- | ----------------------------------------------------- |
| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.|
| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. |
## HuksImportKeyType<sup>9+</sup>
Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------- | ---- | ------------------------------ |
| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key |
| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key |
| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair|
## HuksUserAuthType<sup>9+</sup>
Enumerates the user authentication types.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------- | ---- | ------------------------- |
| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. |
| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.|
| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.|
## HuksAuthAccessType<sup>9+</sup>
Enumerates the access control types.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| --------------------------------------- | ---- | ------------------------------------------------ |
| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. |
| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.|
## HuksChallengeType<sup>9+</sup>
Enumerates the types of the challenges generated when a key is used.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.|
| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.|
| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.|
## HuksChallengePosition<sup>9+</sup>
Enumerates the positions of the 8-byte valid value in a custom challenge generated.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7.|
| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15.|
| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23.|
| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31.|
## HuksSecureSignType<sup>9+</sup>
Defines the signature type of the key generated or imported.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| ------------------------------ | ---- | ------------------------------------------------------------ |
| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.|
## HuksTagType
Enumerates the tag data types.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| --------------------- | ------- | --------------------------------------- |
| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. |
| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. |
| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.|
| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. |
| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. |
| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. |
## HuksTag
Enumerates the tags used to invoke parameters.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description |
| -------------------------------------------- | ---------------------------------------- | -------------------------------------- |
| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. |
| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. |
| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. |
| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. |
| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. |
| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. |
| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. |
| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. |
| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. |
| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. |
| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. |
| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. |
| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. |
| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. |
| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. |
| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. |
| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. |
| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. |
| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. |
| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. |
| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. |
| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. |
| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. |
| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. |
| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. |
| HUKS_TAG_IMPORT_KEY_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. |
| HUKS_TAG_UNWRAP_ALGORITHM_SUITE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. |
| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. |
| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. |
| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. |
| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. |
| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. |
| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. |
| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. |
| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT |
| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. |
| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. |
| HUKS_TAG_KEY_AUTH_ACCESS_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).|
| HUKS_TAG_KEY_SECURE_SIGN_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.|
| HUKS_TAG_CHALLENGE_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).|
| HUKS_TAG_CHALLENGE_POS<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).|
| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. |
| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. |
| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. |
| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. |
| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. |
| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. |
| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. |
| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. |
| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. |
| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. |
| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. |
| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. |
| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.|
| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. |
| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. |
| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. |
| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. |
| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. |
| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. |
| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. |
| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. |
| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. |
| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. |
| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. |
| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. |
| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. |
| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. |
| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. |
| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. |
| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. |
| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. |
| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. |
| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. |
| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. |
| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. |
| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. |
| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. |
| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. |
## huks.generateKey<sup>(deprecated)</sup>
generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Generates a key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. For details about other results, see HuksResult.|
**Example**
```js
/* Generate an RSA key of 512 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
properties: properties
};
huks.generateKey(keyAlias, options, function (err, data){});
```
## huks.generateKey<sup>(deprecated)</sup>
generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Generates a key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.|
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.|
**Example**
```js
/* Generate an ECC key of 256 bits. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
let options = {
properties: properties
};
let result = huks.generateKey(keyAlias, options);
```
## huks.deleteKey<sup>(deprecated)</sup>
deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Deletes a key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------------- |
| keyAlias | string | Yes | Key alias passed in when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.|
**Example**
```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
properties: []
};
huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
```
## huks.deleteKey<sup>(deprecated)</sup>
deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Deletes a key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ----------------------------------------------------- |
| keyAlias | string | Yes | Key alias passed in when the key was generated.|
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).|
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.|
**Example**
```js
/* Set options to emptyOptions. */
let keyAlias = 'keyAlias';
let emptyOptions = {
properties: []
};
let result = huks.deleteKey(keyAlias, emptyOptions);
```
## huks.importKey<sup>(deprecated)</sup>
importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Imports a key in plaintext. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------------------------------- |
| keyAlias | string | Yes | Alias of the key.|
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.|
**Example**
```js
/* Import an AES key of 256 bits. */
let plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size) {
let arr = new Uint8Array(size);
for (let i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
return arr;
};
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
}; };
properties[2] = {
function huksImportWrappedKey() { tag: huks.HuksTag.HUKS_TAG_PURPOSE,
var genOptions = makeGenerateOptions(); value:
var importOptions = makeImportOptions(); huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
TestImportWrappedKeyFunc( };
alias1, properties[3] = {
alias2, tag: huks.HuksTag.HUKS_TAG_PADDING,
genOptions, value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
importOptions };
); properties[4] = {
} tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties,
inData: plainTextSize32
};
huks.importKey(keyAlias, options, function (err, data){});
``` ```
## huks.importWrappedKey<sup>9+</sup> ## huks.importKey<sup>(deprecated)</sup>
importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<HuksResult> importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Imports a wrapped key. This API uses a promise to return the result. Imports a key in plaintext. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------------- | --------------------------- | ---- | --------------------------------------------- | | -------- | ----------- | ---- | ------------------------------------ |
| keyAlias | string | Yes | Alias of the wrapped key to import. | | keyAlias | string | Yes | Alias of the key.|
| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.|
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| | Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.|
**Example** **Example**
```js ```js
/* The process is similar as if a callback is used, except the following:*/ /* Import an AES key of 128 bits. */
async function TestImportWrappedFunc(alias, wrappingAlias, options) { let plainTextSize32 = makeRandomArr(32);
var result = await huks.importWrappedKey(alias, wrappingAlias, options);
if (result.errorCode === 0) { function makeRandomArr(size) {
console.log('test importWrappedKey success'); let arr = new Uint8Array(size);
} else { for (let i = 0; i < size; i++) {
console.log('test importWrappedKey fail'); arr[i] = Math.floor(Math.random() * 10);
} }
} return arr;
};
/* Step 1 Generate a key. */
let keyAlias = 'keyAlias';
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let huksoptions = {
properties: properties,
inData: plainTextSize32
};
let result = huks.importKey(keyAlias, huksoptions);
``` ```
## huks.exportKey
## huks.exportKey<sup>(deprecated)</sup>
exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Exports a key. This API uses an asynchronous callback to return the result. Exports a key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1232,25 +2291,27 @@ Exports a key. This API uses an asynchronous callback to return the result. ...@@ -1232,25 +2291,27 @@ Exports a key. This API uses an asynchronous callback to return the result.
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ /* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; let keyAlias = 'keyAlias';
var emptyOptions = { let emptyOptions = {
properties: [] properties: []
}; };
huks.exportKey(keyAlias, emptyOptions, function (err, data){}); huks.exportKey(keyAlias, emptyOptions, function (err, data){});
``` ```
## huks.exportKey ## huks.exportKey<sup>(deprecated)</sup>
exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Exports a key. This API uses a promise to return the result. Exports a key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1264,25 +2325,28 @@ Exports a key. This API uses a promise to return the result. ...@@ -1264,25 +2325,28 @@ Exports a key. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | ------------------------------------------------------------ | | ----------------------------------- | ------------------------------------------------------------ |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| | Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ /* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; let keyAlias = 'keyAlias';
var emptyOptions = { let emptyOptions = {
properties: [] properties: []
}; };
var result = huks.exportKey(keyAlias, emptyOptions); let result = huks.exportKey(keyAlias, emptyOptions);
``` ```
## huks.getKeyProperties
## huks.getKeyProperties<sup>(deprecated)</sup>
getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Obtains key properties. This API uses an asynchronous callback to return the result. Obtains key properties. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1291,25 +2355,27 @@ Obtains key properties. This API uses an asynchronous callback to return the res ...@@ -1291,25 +2355,27 @@ Obtains key properties. This API uses an asynchronous callback to return the res
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ /* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; let keyAlias = 'keyAlias';
var emptyOptions = { let emptyOptions = {
properties: [] properties: []
}; };
huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
``` ```
## huks.getKeyProperties ## huks.getKeyProperties<sup>(deprecated)</sup>
getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Obtains key properties. This API uses a promise to return the result. Obtains key properties. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1323,25 +2389,28 @@ Obtains key properties. This API uses a promise to return the result. ...@@ -1323,25 +2389,28 @@ Obtains key properties. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ------------------ | ------------------------------------------------------------ | | ------------------ | ------------------------------------------------------------ |
| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned. **properties** returns the parameters required for generating the key.| | Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ /* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; let keyAlias = 'keyAlias';
var emptyOptions = { let emptyOptions = {
properties: [] properties: []
}; };
var result = huks.getKeyProperties(keyAlias, emptyOptions); let result = huks.getKeyProperties(keyAlias, emptyOptions);
``` ```
## huks.isKeyExist
## huks.isKeyExist<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void
Checks whether a key exists. This API uses an asynchronous callback to return the result. Checks whether a key exists. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1350,25 +2419,27 @@ Checks whether a key exists. This API uses an asynchronous callback to return th ...@@ -1350,25 +2419,27 @@ Checks whether a key exists. This API uses an asynchronous callback to return th
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| keyAlias | string | Yes | Alias of the key to check.| | keyAlias | string | Yes | Alias of the key to check.|
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| | callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ /* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; let keyAlias = 'keyAlias';
var emptyOptions = { let emptyOptions = {
properties: [] properties: []
}; };
huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
``` ```
## huks.isKeyExist ## huks.isKeyExist<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean> isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
Checks whether a key exists. This API uses a promise to return the result. Checks whether a key exists. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1382,26 +2453,26 @@ Checks whether a key exists. This API uses a promise to return the result. ...@@ -1382,26 +2453,26 @@ Checks whether a key exists. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------- | --------------------------------------- | | ----------------- | --------------------------------------- |
| Promise\<boolean> | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| | Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */ /* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; let keyAlias = 'keyAlias';
var emptyOptions = { let emptyOptions = {
properties: [] properties: []
}; };
var result = huks.isKeyExist(keyAlias, emptyOptions); let result = huks.isKeyExist(keyAlias, emptyOptions);
``` ```
## huks.init<sup>(deprecated)</sup>
## huks.init
init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void
Initializes the data for a key operation. This API uses an asynchronous callback to return the result. Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1411,14 +2482,16 @@ Initializes the data for a key operation. This API uses an asynchronous callback ...@@ -1411,14 +2482,16 @@ Initializes the data for a key operation. This API uses an asynchronous callback
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| keyAlias | string | Yes | Alias of the target key.| | keyAlias | string | Yes | Alias of the target key.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.|
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the initialization operation.| | callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.|
## huks.init ## huks.init<sup>(deprecated)</sup>
init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle> init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle>
Initializes the data for a key operation. This API uses a promise to return the result. Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1428,52 +2501,21 @@ Initializes the data for a key operation. This API uses a promise to return the ...@@ -1428,52 +2501,21 @@ Initializes the data for a key operation. This API uses a promise to return the
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| keyAlias | string | Yes | Alias of the target key.| | keyAlias | string | Yes | Alias of the target key.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.|
| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the initialization operation.|
## huks.update<sup>(deprecated)</sup>
update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Updates the key operation data by segment. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.update<sup>9+</sup>](#huksupdate9-1). **Return value**
**System capability**: SystemCapability.Security.Huks
**Parameters** | Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.|
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. |
| token | Uint8Array | No | Token of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.|
## huks.update<sup>(deprecated)</sup> ## huks.update<sup>(deprecated)</sup>
update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult>
Updates the key operation data by segment. This API uses a promise to return the result.
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [huks.update<sup>9+</sup>](#huksupdate9-2).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. |
| token | Uint8Array | No | Token of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| promise | Promise\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.|
## huks.update<sup>9+</sup>
update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Updates the key operation by segment. This API uses an asynchronous callback to return the result. Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1483,14 +2525,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to ...@@ -1483,14 +2525,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to
| -------- | ----------------------------------------- | ---- | -------------------------------------------- | | -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. | | handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.|
## huks.update<sup>(deprecated)</sup>
## huks.update<sup>9+</sup> update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void
update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
Updates the key operation by segment. This API uses an asynchronous callback to return the result. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1499,15 +2542,17 @@ Updates the key operation by segment. This API uses an asynchronous callback to ...@@ -1499,15 +2542,17 @@ Updates the key operation by segment. This API uses an asynchronous callback to
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- | | -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. | | handle | number | Yes | Handle of the **Update** operation. |
| token | Uint8Array | No | Token of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| token | Uint8Array | Yes | Token of the **Update** operation. | | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.|
## huks.update<sup>9+</sup> ## huks.update<sup>(deprecated)</sup>
update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult> update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult>
Updates the key operation by segment. This API uses a promise to return the result. Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-2).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1516,15 +2561,23 @@ Updates the key operation by segment. This API uses a promise to return the resu ...@@ -1516,15 +2561,23 @@ Updates the key operation by segment. This API uses a promise to return the resu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ----------------------------------- | ---- | -------------------------------------------- | | ------- | ----------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. | | handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| token | Uint8Array | No | Token of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. |
| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
## huks.finish **Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.|
## huks.finish<sup>(deprecated)</sup>
finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1534,14 +2587,16 @@ Completes the key operation and releases resources. This API uses an asynchronou ...@@ -1534,14 +2587,16 @@ Completes the key operation and releases resources. This API uses an asynchronou
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation.| | handle | number | Yes | Handle of the **Finish** operation.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.|
## huks.finish ## huks.finish<sup>(deprecated)</sup>
finish(handle: number, options: HuksOptions) : Promise\<HuksResult> finish(handle: number, options: HuksOptions) : Promise\<HuksResult>
Completes the key operation and releases resources. This API uses a promise to return the result. Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1551,49 +2606,22 @@ Completes the key operation and releases resources. This API uses a promise to r ...@@ -1551,49 +2606,22 @@ Completes the key operation and releases resources. This API uses a promise to r
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation.| | handle | number | Yes | Handle of the **Finish** operation.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.|
| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.|
## huks.finish<sup>9+</sup> **Return value**
finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void
Completes the key operation and releases resources. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | Yes | Token for the **Finish** operation. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.|
## huks.finish<sup>9+</sup>
finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult>
Completes the key operation and releases resources. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks
**Parameters** | Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.|
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------- | ---- | ----------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | No | Token for the **Finish** operation. |
| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.|
## huks.abort ## huks.abort<sup>(deprecated)</sup>
abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Aborts the use of the key. This API uses an asynchronous callback to return the result. Aborts the use of the key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1602,7 +2630,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the ...@@ -1602,7 +2630,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | Yes | Handle of the **Abort** operation.| | handle | number | Yes | Handle of the **Abort** operation.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.|
**Example** **Example**
...@@ -1612,27 +2640,14 @@ Aborts the use of the key. This API uses an asynchronous callback to return the ...@@ -1612,27 +2640,14 @@ Aborts the use of the key. This API uses an asynchronous callback to return the
* *
* The following uses the callback of an RSA 1024-bit key as an example. * The following uses the callback of an RSA 1024-bit key as an example.
*/ */
import router from '@system.router'; let keyalias = "HuksDemoRSA";
import huks from '@ohos.security.huks'; let properties = new Array();
let options = {
async function routePage() {
let options = {
uri: 'pages/second'
}
try {
await router.push(options)
} catch (err) {
console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
}
}
var keyalias = "HuksDemoRSA";
var properties = new Array();
var options = {
properties: properties, properties: properties,
inData: new Uint8Array(0) inData: new Uint8Array(0)
}; };
var handle; let handle;
var resultMessage = ""; let resultMessage = "";
async function generateKey() { async function generateKey() {
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
...@@ -1657,11 +2672,11 @@ async function generateKey() { ...@@ -1657,11 +2672,11 @@ async function generateKey() {
huks.generateKey(keyalias, options); huks.generateKey(keyalias, options);
} }
function stringToUint8Array(str) { function stringToUint8Array(str) {
var arr = []; let arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array; return tmpUint8Array;
} }
async function huksInit() { async function huksInit() {
...@@ -1708,112 +2723,16 @@ async function huksAbort() { ...@@ -1708,112 +2723,16 @@ async function huksAbort() {
}); });
console.log(resultMessage); console.log(resultMessage);
} }
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Tocallback')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
routePage()
})
Button() {
Text('generateKey')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
generateKey()
})
Button() {
Text('Init')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksInit()
})
Button() {
Text('Update')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksUpdate()
})
Button() {
Text('Finish')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksFinish()
})
Button() {
Text('Abort')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksAbort()
})
}
.width('100%')
.height('100%')
}
}
``` ```
## huks.abort ## huks.abort<sup>(deprecated)</sup>
abort(handle: number, options: HuksOptions) : Promise\<HuksResult>; abort(handle: number, options: HuksOptions) : Promise\<HuksResult>;
Aborts the use of the key. This API uses a promise to return the result. Aborts the use of the key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
**Parameters** **Parameters**
...@@ -1822,7 +2741,12 @@ Aborts the use of the key. This API uses a promise to return the result. ...@@ -1822,7 +2741,12 @@ Aborts the use of the key. This API uses a promise to return the result.
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | Yes | Handle of the **Abort** operation.| | handle | number | Yes | Handle of the **Abort** operation.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.|
| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.|
**Return value**
| Type | Description |
| ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.|
**Example** **Example**
...@@ -1832,34 +2756,20 @@ Aborts the use of the key. This API uses a promise to return the result. ...@@ -1832,34 +2756,20 @@ Aborts the use of the key. This API uses a promise to return the result.
* *
* The following uses the promise of an RSA 1024-bit key as an example. * The following uses the promise of an RSA 1024-bit key as an example.
*/ */
import router from '@system.router'; let keyalias = "HuksDemoRSA";
import huks from '@ohos.security.huks'; let properties = new Array();
let options = {
async function routePage() {
let options = {
uri: 'pages/second'
}
try {
await router.push(options)
} catch (err) {
console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
}
}
var keyalias = "HuksDemoRSA";
var properties = new Array();
var options = {
properties: properties, properties: properties,
inData: new Uint8Array(0) inData: new Uint8Array(0)
}; };
var handle; let handle;
var resultMessage = ""; let resultMessage = "";
function stringToUint8Array(str) { function stringToUint8Array(str) {
var arr = []; let arr = [];
for (var i = 0, j = str.length; i < j; ++i) { for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array; return tmpUint8Array;
} }
...@@ -1890,7 +2800,7 @@ async function huksInit() { ...@@ -1890,7 +2800,7 @@ async function huksInit() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
huks.init(keyalias, options, async function (err, data) { huks.init(keyalias, options, async function (err, data) {
if (data.errorCode === 0) { if (data.errorCode === 0) {
resultMessage = "Initialization successful!" resultMessage = "init success!"
handle = data.handle; handle = data.handle;
} else { } else {
resultMessage = "init fail errorCode: " + data.errorCode resultMessage = "init fail errorCode: " + data.errorCode
...@@ -1935,128 +2845,10 @@ function huksAbort() { ...@@ -1935,128 +2845,10 @@ function huksAbort() {
}); });
}); });
} }
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('to Promise')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
router.back()
})
Button() {
Text('generateKey')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
generateKey()
})
Button() {
Text('Init')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksInit()
})
Button() {
Text('Update')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksUpdate()
})
Button() {
Text('Finish')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksFinish()
})
Button() {
Text('Abort')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksAbort()
})
}
.width('100%')
.height('100%')
}
}
``` ```
## HuksParam
Defines the **param** in the **properties** array of **options** used in the APIs.
**System capability**: SystemCapability.Security.Huks
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | ------------ |
| tag | [HuksTag](#hukstag) | Yes | Tag. |
| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.|
## HuksOptions
Defines the **options** used in the APIs.
**System capability**: SystemCapability.Security.Huks
| Name | Type | Mandatory| Description |
| ---------- | ----------------- | ---- | ------------------------ |
| properties | Array\<[HuksParam](#huksparam)> | No | Array used to hold **HuksParam**.|
| inData | Uint8Array | No | Input data. |
## HuksHandle ## HuksHandle<sup>(deprecated)</sup>
Defines the HUKS handle structure. Defines the HUKS handle structure.
...@@ -2069,7 +2861,7 @@ Defines the HUKS handle structure. ...@@ -2069,7 +2861,7 @@ Defines the HUKS handle structure.
| token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| | token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.|
## HuksResult ## HuksResult<sup>(deprecated)</sup>
Defines the **HuksResult** structure. Defines the **HuksResult** structure.
...@@ -2083,3 +2875,87 @@ Defines the **HuksResult** structure. ...@@ -2083,3 +2875,87 @@ Defines the **HuksResult** structure.
| outData | Uint8Array | No | Output data. | | outData | Uint8Array | No | Output data. |
| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | | properties | Array\<[HuksParam](#huksparam)> | No | Property information. |
| certChains | Array\<string> | No | Certificate chain information.| | certChains | Array\<string> | No | Certificate chain information.|
## HuksErrorCode<sup>(deprecated)</sup>
Enumerates the error codes.
**System capability**: SystemCapability.Security.Huks
| Name | Value | Description|
| -------------------------- | ----- | ---- |
| HUKS_SUCCESS | 0 |Success.|
| HUKS_FAILURE | -1 |Failure.|
| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.|
| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.|
| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.|
| HUKS_ERROR_NO_PERMISSION | -5 |No permission.|
| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.|
| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.|
| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.|
| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.|
| HUKS_ERROR_STORAGE_FAILURE | -10 |Insufficient storage space.|
| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.|
| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.|
| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.|
| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.|
| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.|
| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.|
| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.|
| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.|
| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.|
| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.|
| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.|
| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.|
| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.|
| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.|
| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.|
| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.|
| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.|
| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.|
| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.|
| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.|
| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.|
| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.|
| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.|
| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.|
| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.|
| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.|
| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.|
| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.|
| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED<sup>9+</sup> | -40 |Failed to obtain the security attribute information of the user.|
| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED<sup>9+</sup> | -41 |Failed to obtain the authentication information of the user.|
| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT<sup>9+</sup> | -42 |The access control of the current authentication type is not supported.|
| HUKS_ERROR_KEY_AUTH_FAILED<sup>9+</sup> | -43 |The access control authentication has failed.|
| HUKS_ERROR_DEVICE_NO_CREDENTIAL<sup>9+</sup> | -44 |No credential has been enrolled for the device.|
| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. |
| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.|
| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.|
| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to obtain the key purpose.|
| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to obtain the digest algorithm.|
| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to obtain the cipher mode.|
| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to obtain the nonce.|
| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to obtain the AAD.|
| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to obtain the initialization vector (IV).|
| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to obtain the AE flag.|
| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to obtain the salt value.|
| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to obtain the number of iterations.|
| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.|
| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.|
| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding algorithm.|
| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid key purpose.|
| HUKS_ERROR_INVALID_MODE | -116 |Invalid cipher mode.|
| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest algorithm.|
| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.|
| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.|
| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.|
| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.|
| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.|
| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.|
| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.|
| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.|
| HUKS_ERROR_INVALID_WRAPPED_FORMAT<sup>9+</sup> | -126 |Incorrect format of the wrapped key being imported.|
| HUKS_ERROR_INVALID_USAGE_OF_KEY<sup>9+</sup> | -127 |Incorrect purpose of the wrapped key being imported.|
| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.|
...@@ -64,7 +64,7 @@ Creates a Locale object. ...@@ -64,7 +64,7 @@ Creates a Locale object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------------- | ---- | ---------------------------- | | ------- | ------------- | ---- | ---------------------------- |
| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string | Yes | A string containing locale information, including the language, optional script, and region.|
| options | LocaleOptions | No | Options for creating the **Locale** object. | | options<sup>9+</sup> | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. |
**Example** **Example**
``` ```
...@@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale. ...@@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ---------------------------- | | ------- | ----------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | | options<sup>9+</sup> | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. |
**Example** **Example**
``` ```
...@@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object.
| Type | Description | | Type | Description |
| ----------------------------------- | ----------------------------- | | ----------------------------------- | ----------------------------- |
| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| | [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.|
**Example** **Example**
``` ```
...@@ -332,7 +332,7 @@ Parameters ...@@ -332,7 +332,7 @@ Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------- | ---- | ---------------------------- | | ------- | ------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | | options<sup>9+</sup> | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. |
**Example** **Example**
``` ```
...@@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object.
| Type | Description | | Type | Description |
| ------------------------------- | --------------------------- | | ------------------------------- | --------------------------- |
| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| | [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.|
**Example** **Example**
...@@ -449,7 +449,7 @@ Creates a Collator object. ...@@ -449,7 +449,7 @@ Creates a Collator object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ---------------------------- | | ------- | ----------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | | options<sup>9+</sup> | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. |
**Example** **Example**
``` ```
...@@ -497,7 +497,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -497,7 +497,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
| Type | Description | | Type | Description |
| ----------------------------------- | ----------------- | | ----------------------------------- | ----------------- |
| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| | [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.|
**Example** **Example**
...@@ -553,7 +553,7 @@ Parameters ...@@ -553,7 +553,7 @@ Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------- | | ------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | | options<sup>9+</sup> | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. |
**Example** **Example**
``` ```
...@@ -635,7 +635,7 @@ Creates a **RelativeTimeFormat** object. ...@@ -635,7 +635,7 @@ Creates a **RelativeTimeFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------- | | ------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | | options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. |
**Example** **Example**
``` ```
...@@ -711,7 +711,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ...@@ -711,7 +711,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
| Type | Description | | Type | Description |
| ---------------------------------------- | --------------------------------- | | ---------------------------------------- | --------------------------------- |
| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.|
**Example** **Example**
``` ```
......
...@@ -110,7 +110,7 @@ connection.hasDefaultNet().then(function (has) { ...@@ -110,7 +110,7 @@ connection.hasDefaultNet().then(function (has) {
getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void
Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. Obtains the list of all connected networks. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -136,7 +136,7 @@ connection.getAllNets(function (error, nets) { ...@@ -136,7 +136,7 @@ connection.getAllNets(function (error, nets) {
getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt; getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;
Obtains the list of all active data networks. This API uses a promise to return the result. Obtains the list of all connected networks. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO **Required permission**: ohos.permission.GET_NETWORK_INFO
...@@ -280,7 +280,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -280,7 +280,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports connection of the data network. This API uses an asynchronous callback to return the result. Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -308,7 +308,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -308,7 +308,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports connection of the data network. This API uses a promise to return the result. Reports connection of the data network to the network management module. This API uses a promise to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -341,7 +341,7 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -341,7 +341,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
Reports disconnection of the data network. This API uses an asynchronous callback to return the result. Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -369,7 +369,8 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -369,7 +369,8 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports disconnection of the data network. This API uses a promise to return the result. Reports disconnection of the data network to the network management module. This API uses a promise to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...@@ -558,7 +559,7 @@ connection.disableAirplaneMode().then(function (error) { ...@@ -558,7 +559,7 @@ connection.disableAirplaneMode().then(function (error) {
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
Obtains the handle of the network specified by **netSpecifier**. Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -950,9 +951,9 @@ Defines the network capability. ...@@ -950,9 +951,9 @@ Defines the network capability.
| ------------------------ | ---- | ---------------------- | | ------------------------ | ---- | ---------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| | NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| | NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| | NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).| | NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. | | NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the network management module. |
## NetBearType ## NetBearType
......
...@@ -384,6 +384,27 @@ promise.then(data => { ...@@ -384,6 +384,27 @@ promise.then(data => {
}); });
``` ```
## radio.isNrSupported<sup>7+</sup>
isNrSupported\(\): boolean
Checks whether the current device supports 5G \(NR\).
**System capability**: SystemCapability.Telephony.CoreService
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | - **true**: The current device supports 5G \(NR\).<br>- **false**: The current device does not support 5G \(NR\).|
**Example**
```js
let result = radio.isNrSupported();
console.log("Result: "+ result);
```
## radio.isNrSupported<sup>8+</sup> ## radio.isNrSupported<sup>8+</sup>
......
...@@ -2683,8 +2683,6 @@ getOpKey(slotId: number): Promise<string\> ...@@ -2683,8 +2683,6 @@ getOpKey(slotId: number): Promise<string\>
Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
**Parameters** **Parameters**
...@@ -2716,8 +2714,6 @@ getOpName(slotId: number, callback: AsyncCallback<string\>): void ...@@ -2716,8 +2714,6 @@ getOpName(slotId: number, callback: AsyncCallback<string\>): void
Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
**Parameters** **Parameters**
...@@ -2742,8 +2738,6 @@ getOpName(slotId: number): Promise<string\> ...@@ -2742,8 +2738,6 @@ getOpName(slotId: number): Promise<string\>
Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
**Parameters** **Parameters**
......
...@@ -316,7 +316,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { ...@@ -316,7 +316,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
return; return;
} }
console.log('bind success'); console.log('bind success');
let promise = udp.getState({}); let promise = udp.getState();
promise.then(data => { promise.then(data => {
console.log('getState success:' + JSON.stringify(data)); console.log('getState success:' + JSON.stringify(data));
}).catch(err => { }).catch(err => {
...@@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection. ...@@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ---------------------------------- | ---- | -------------- | | ------- | ---------------------------------- | ---- | -------------- |
| data | string | Yes | Data to send. | | data | string \| ArrayBuffer<sup>7+</sup> | Yes | Data to send. |
| address | [NetAddress](#netaddress) | Yes | Destination address.| | address | [NetAddress](#netaddress) | Yes | Destination address.|
## UDPExtraOptions ## UDPExtraOptions
...@@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection. ...@@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| data | string | Yes | Data to send. | | data | string\| ArrayBuffer<sup>7+</sup> | Yes | Data to send. |
| encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.|
## TCPExtraOptions ## TCPExtraOptions
......
...@@ -63,6 +63,29 @@ promise.then((data) => { ...@@ -63,6 +63,29 @@ promise.then((data) => {
}); });
``` ```
## data.getDefaultCellularDataSlotIdSync
getDefaultCellularDataSlotIdSync(): number
Obtains the default SIM card used for mobile data synchronously.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Telephony.CellularData
**Return value**
| Type | Description |
| ------ | -------------------------------------------------- |
| number | Card slot ID.<br>**0**: card slot 1<br>**1**: card slot 2|
**Example**
```js
console.log("Result: "+ data.getDefaultCellularDataSlotIdSync())
```
## data.setDefaultCellularDataSlotId ## data.setDefaultCellularDataSlotId
setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): void setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): void
......
...@@ -43,13 +43,13 @@ Obtains an **OnlineUpdater** object. ...@@ -43,13 +43,13 @@ Obtains an **OnlineUpdater** object.
```ts ```ts
try { try {
var upgradeInfo = { const upgradeInfo = {
upgradeApp: "com.ohos.ota.updateclient", upgradeApp: "com.ohos.ota.updateclient",
businessType: { businessType: {
vendor: update.BusinessVendor.PUBLIC, vendor: update.BusinessVendor.PUBLIC,
subType: update.BusinessSubType.FIRMWARE subType: update.BusinessSubType.FIRMWARE
} }
} };
let updater = update.getOnlineUpdater(upgradeInfo); let updater = update.getOnlineUpdater(upgradeInfo);
} catch(error) { } catch(error) {
console.error(`Fail to get updater error: ${error}`); console.error(`Fail to get updater error: ${error}`);
...@@ -233,15 +233,15 @@ Obtains the description file of the new version. This API uses an asynchronous c ...@@ -233,15 +233,15 @@ Obtains the description file of the new version. This API uses an asynchronous c
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options of the description file // Options of the description file
var descriptionOptions = { const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese language: "zh-cn" // Chinese
} };
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => {
console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); console.log(`getNewVersionDescription info ${JSON.stringify(info)}`);
...@@ -276,15 +276,15 @@ Obtains the description file of the new version. This API uses a promise to retu ...@@ -276,15 +276,15 @@ Obtains the description file of the new version. This API uses a promise to retu
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options of the description file // Options of the description file
var descriptionOptions = { const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese language: "zh-cn" // Chinese
} };
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => {
console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`);
...@@ -368,10 +368,10 @@ Obtains the description file of the current version. This API uses an asynchrono ...@@ -368,10 +368,10 @@ Obtains the description file of the current version. This API uses an asynchrono
```ts ```ts
// Options of the description file // Options of the description file
var descriptionOptions = { const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese language: "zh-cn" // Chinese
} };
updater.getCurrentVersionDescription(descriptionOptions, (err, info) => { updater.getCurrentVersionDescription(descriptionOptions, (err, info) => {
console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`); console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`);
...@@ -405,10 +405,10 @@ Obtains the description file of the current version. This API uses a promise to ...@@ -405,10 +405,10 @@ Obtains the description file of the current version. This API uses a promise to
```ts ```ts
// Options of the description file // Options of the description file
var descriptionOptions = { const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // Standard format format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese language: "zh-cn" // Chinese
} };
updater.getCurrentVersionDescription(descriptionOptions).then(info => { updater.getCurrentVersionDescription(descriptionOptions).then(info => {
console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`);
...@@ -489,15 +489,15 @@ Downloads the new version. This API uses an asynchronous callback to return the ...@@ -489,15 +489,15 @@ Downloads the new version. This API uses an asynchronous callback to return the
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Download options // Download options
var downloadOptions = { const downloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
order: update.Order.DOWNLOAD // Download order: update.Order.DOWNLOAD // Download
} };
updater.download(versionDigestInfo, downloadOptions, (err) => { updater.download(versionDigestInfo, downloadOptions, (err) => {
console.log(`download error ${JSON.stringify(err)}`); console.log(`download error ${JSON.stringify(err)}`);
}); });
...@@ -530,15 +530,15 @@ Downloads the new version. This API uses a promise to return the result. ...@@ -530,15 +530,15 @@ Downloads the new version. This API uses a promise to return the result.
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Download options // Download options
var downloadOptions = { const downloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
order: update.Order.DOWNLOAD // Download order: update.Order.DOWNLOAD // Download
} };
updater.download(versionDigestInfo, downloadOptions).then(() => { updater.download(versionDigestInfo, downloadOptions).then(() => {
console.log(`download start`); console.log(`download start`);
}).catch(err => { }).catch(err => {
...@@ -568,14 +568,14 @@ Resumes download of the new version. This API uses an asynchronous callback to r ...@@ -568,14 +568,14 @@ Resumes download of the new version. This API uses an asynchronous callback to r
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options for resuming download // Options for resuming download
var resumeDownloadOptions = { const resumeDownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
} };
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => {
console.log(`resumeDownload error ${JSON.stringify(err)}`); console.log(`resumeDownload error ${JSON.stringify(err)}`);
}); });
...@@ -608,14 +608,14 @@ Resumes download of the new version. This API uses a promise to return the resul ...@@ -608,14 +608,14 @@ Resumes download of the new version. This API uses a promise to return the resul
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options for resuming download // Options for resuming download
var resumeDownloadOptions = { const resumeDownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network
} };
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => {
console.log(`resumeDownload start`); console.log(`resumeDownload start`);
}).catch(err => { }).catch(err => {
...@@ -645,14 +645,14 @@ Pauses download of the new version. This API uses an asynchronous callback to re ...@@ -645,14 +645,14 @@ Pauses download of the new version. This API uses an asynchronous callback to re
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options for pausing download // Options for pausing download
var pauseDownloadOptions = { const pauseDownloadOptions = {
isAllowAutoResume: true // Whether to allow automatic resuming of download isAllowAutoResume: true // Whether to allow automatic resuming of download
} };
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => {
console.log(`pauseDownload error ${JSON.stringify(err)}`); console.log(`pauseDownload error ${JSON.stringify(err)}`);
}); });
...@@ -685,14 +685,14 @@ Resumes download of the new version. This API uses a promise to return the resul ...@@ -685,14 +685,14 @@ Resumes download of the new version. This API uses a promise to return the resul
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options for pausing download // Options for pausing download
var pauseDownloadOptions = { const pauseDownloadOptions = {
isAllowAutoResume: true // Whether to allow automatic resuming of download isAllowAutoResume: true // Whether to allow automatic resuming of download
} };
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => {
console.log(`pauseDownload`); console.log(`pauseDownload`);
}).catch(err => { }).catch(err => {
...@@ -722,14 +722,14 @@ Updates the version. This API uses an asynchronous callback to return the result ...@@ -722,14 +722,14 @@ Updates the version. This API uses an asynchronous callback to return the result
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Installation options // Installation options
var upgradeOptions = { const upgradeOptions = {
order: update.Order.INSTALL // Installation command order: update.Order.INSTALL // Installation command
} };
updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { updater.upgrade(versionDigestInfo, upgradeOptions, (err) => {
console.log(`upgrade error ${JSON.stringify(err)}`); console.log(`upgrade error ${JSON.stringify(err)}`);
}); });
...@@ -762,14 +762,14 @@ Updates the version. This API uses a promise to return the result. ...@@ -762,14 +762,14 @@ Updates the version. This API uses a promise to return the result.
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Installation options // Installation options
var upgradeOptions = { const upgradeOptions = {
order: update.Order.INSTALL // Installation command order: update.Order.INSTALL // Installation command
} };
updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { updater.upgrade(versionDigestInfo, upgradeOptions).then(() => {
console.log(`upgrade start`); console.log(`upgrade start`);
}).catch(err => { }).catch(err => {
...@@ -799,14 +799,14 @@ Clears errors. This API uses an asynchronous callback to return the result. ...@@ -799,14 +799,14 @@ Clears errors. This API uses an asynchronous callback to return the result.
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options for clearing errors // Options for clearing errors
var clearOptions = { const clearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL, status: update.UpgradeStatus.UPGRADE_FAIL,
} };
updater.clearError(versionDigestInfo, clearOptions, (err) => { updater.clearError(versionDigestInfo, clearOptions, (err) => {
console.log(`clearError error ${JSON.stringify(err)}`); console.log(`clearError error ${JSON.stringify(err)}`);
}); });
...@@ -839,14 +839,14 @@ Clears errors. This API uses a promise to return the result. ...@@ -839,14 +839,14 @@ Clears errors. This API uses a promise to return the result.
```ts ```ts
// Version digest information // Version digest information
var versionDigestInfo = { const versionDigestInfo = {
versionDigest: "versionDigest" // Version digest information in the check result versionDigest: "versionDigest" // Version digest information in the check result
} };
// Options for clearing errors // Options for clearing errors
var clearOptions = { lconstet clearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL, status: update.UpgradeStatus.UPGRADE_FAIL,
} };
updater.clearError(versionDigestInfo, clearOptions).then(() => { updater.clearError(versionDigestInfo, clearOptions).then(() => {
console.log(`clearError success`); console.log(`clearError success`);
}).catch(err => { }).catch(err => {
...@@ -926,7 +926,7 @@ Sets the update policy. This API uses an asynchronous callback to return the res ...@@ -926,7 +926,7 @@ Sets the update policy. This API uses an asynchronous callback to return the res
**Example** **Example**
```ts ```ts
let policy = { const policy = {
downloadStrategy: false, downloadStrategy: false,
autoUpgradeStrategy: false, autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes
...@@ -961,7 +961,7 @@ Sets the update policy. This API uses a promise to return the result. ...@@ -961,7 +961,7 @@ Sets the update policy. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
let policy = { const policy = {
downloadStrategy: false, downloadStrategy: false,
autoUpgradeStrategy: false, autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes
...@@ -1041,10 +1041,10 @@ Enables listening for update events. This API uses an asynchronous callback to r ...@@ -1041,10 +1041,10 @@ Enables listening for update events. This API uses an asynchronous callback to r
**Example** **Example**
```ts ```ts
var eventClassifyInfo = { const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: "" extraInfo: ""
} };
updater.on(eventClassifyInfo, (eventInfo) => { updater.on(eventClassifyInfo, (eventInfo) => {
console.log("updater on " + JSON.stringify(eventInfo)); console.log("updater on " + JSON.stringify(eventInfo));
...@@ -1068,10 +1068,10 @@ Disables listening for update events. This API uses an asynchronous callback to ...@@ -1068,10 +1068,10 @@ Disables listening for update events. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
var eventClassifyInfo = { const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: "" extraInfo: ""
} };
updater.off(eventClassifyInfo, (eventInfo) => { updater.off(eventClassifyInfo, (eventInfo) => {
console.log("updater off " + JSON.stringify(eventInfo)); console.log("updater off " + JSON.stringify(eventInfo));
...@@ -1153,10 +1153,10 @@ Verifies the update package. This API uses an asynchronous callback to return th ...@@ -1153,10 +1153,10 @@ Verifies the update package. This API uses an asynchronous callback to return th
**Example** **Example**
```ts ```ts
var upgradeFile = { const upgradeFile = {
fileType: update.ComponentType.OTA, // OTA package fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package filePath: "path" // Path of the local update package
} };
localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => { localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => {
console.log(`factoryReset error ${JSON.stringify(err)}`); console.log(`factoryReset error ${JSON.stringify(err)}`);
...@@ -1189,10 +1189,10 @@ Verifies the update package. This API uses a promise to return the result. ...@@ -1189,10 +1189,10 @@ Verifies the update package. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
var upgradeFile = { const upgradeFile = {
fileType: update.ComponentType.OTA, // OTA package fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package filePath: "path" // Path of the local update package
} };
localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => { localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => {
console.log(`verifyUpgradePackage success`); console.log(`verifyUpgradePackage success`);
}).catch(err => { }).catch(err => {
...@@ -1219,10 +1219,10 @@ Installs the update package. This API uses an asynchronous callback to return th ...@@ -1219,10 +1219,10 @@ Installs the update package. This API uses an asynchronous callback to return th
**Example** **Example**
```ts ```ts
var upgradeFiles = [{ const upgradeFiles = [{
fileType: update.ComponentType.OTA, // OTA package fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package filePath: "path" // Path of the local update package
}] }];
localUpdater.applyNewVersion(upgradeFiles, (err) => { localUpdater.applyNewVersion(upgradeFiles, (err) => {
console.log(`applyNewVersion error ${JSON.stringify(err)}`); console.log(`applyNewVersion error ${JSON.stringify(err)}`);
...@@ -1248,10 +1248,10 @@ Installs the update package. This API uses a promise to return the result. ...@@ -1248,10 +1248,10 @@ Installs the update package. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
var upgradeFiles = [{ localUpdater upgradeFiles = [{
fileType: update.ComponentType.OTA, // OTA package fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package filePath: "path" // Path of the local update package
}] }];
localUpdater.applyNewVersion(upgradeFiles).then(() => { localUpdater.applyNewVersion(upgradeFiles).then(() => {
console.log(`applyNewVersion success`); console.log(`applyNewVersion success`);
}).catch(err => { }).catch(err => {
...@@ -1276,10 +1276,10 @@ Enables listening for update events. This API uses an asynchronous callback to r ...@@ -1276,10 +1276,10 @@ Enables listening for update events. This API uses an asynchronous callback to r
**Example** **Example**
```ts ```ts
var eventClassifyInfo = { const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: "" extraInfo: ""
} };
function onTaskUpdate(eventInfo) { function onTaskUpdate(eventInfo) {
console.log(`on eventInfo id `, eventInfo.eventId); console.log(`on eventInfo id `, eventInfo.eventId);
...@@ -1305,10 +1305,10 @@ Disables listening for update events. This API uses an asynchronous callback to ...@@ -1305,10 +1305,10 @@ Disables listening for update events. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
var eventClassifyInfo = { const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // Listening for update events eventClassify: update.EventClassify.TASK, // Listening for update events
extraInfo: "" extraInfo: ""
} };
function onTaskUpdate(eventInfo) { function onTaskUpdate(eventInfo) {
console.log(`on eventInfo id `, eventInfo.eventId); console.log(`on eventInfo id `, eventInfo.eventId);
......
...@@ -433,7 +433,7 @@ ws.off('open', callback1); ...@@ -433,7 +433,7 @@ ws.off('open', callback1);
on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>![](public_sys-resources/icon-note.gif) **NOTE:** >![](public_sys-resources/icon-note.gif) **NOTE:**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
...@@ -462,7 +462,7 @@ ws.on('message', (err, value) => { ...@@ -462,7 +462,7 @@ ws.on('message', (err, value) => {
off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void off\(type: 'message', callback?: AsyncCallback<string | ArrayBuffer\>\): void
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>![](public_sys-resources/icon-note.gif) **NOTE:** >![](public_sys-resources/icon-note.gif) **NOTE:**
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
......
...@@ -302,7 +302,7 @@ Represents the WLAN configuration. ...@@ -302,7 +302,7 @@ Represents the WLAN configuration.
## IpType<sup>7+</sup> ## IpType<sup>7+</sup>
Enumerate the IP address types. Enumerates the IP address types.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -1851,7 +1851,7 @@ Unregisters the WLAN state change events. ...@@ -1851,7 +1851,7 @@ Unregisters the WLAN state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiStateChange**.| | type | string | Yes| Event type. The value is **wifiStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
```js ```js
...@@ -1909,7 +1909,7 @@ Unregisters the WLAN connection state change events. ...@@ -1909,7 +1909,7 @@ Unregisters the WLAN connection state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiConnectionChange**.| | type | string | Yes| Event type. The value is **wifiConnectionChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('wifiScanStateChange')<sup>7+</sup> ## wifi.on('wifiScanStateChange')<sup>7+</sup>
...@@ -1952,7 +1952,7 @@ Unregisters the WLAN scan state change events. ...@@ -1952,7 +1952,7 @@ Unregisters the WLAN scan state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiScanStateChange**.| | type | string | Yes| Event type. The value is **wifiScanStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('wifiRssiChange')<sup>7+</sup> ## wifi.on('wifiRssiChange')<sup>7+</sup>
...@@ -1988,7 +1988,7 @@ Unregisters the RSSI change events. ...@@ -1988,7 +1988,7 @@ Unregisters the RSSI change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiRssiChange**.| | type | string | Yes| Event type. The value is **wifiRssiChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('hotspotStateChange')<sup>7+</sup> ## wifi.on('hotspotStateChange')<sup>7+</sup>
...@@ -2033,7 +2033,7 @@ Unregisters the hotspot state change events. ...@@ -2033,7 +2033,7 @@ Unregisters the hotspot state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStateChange**.| | type | string | Yes| Event type. The value is **hotspotStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pStateChange')<sup>8+</sup> ## wifi.on('p2pStateChange')<sup>8+</sup>
...@@ -2078,7 +2078,7 @@ Unregisters the P2P state change events. ...@@ -2078,7 +2078,7 @@ Unregisters the P2P state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pStateChange**.| | type | string | Yes| Event type. The value is **p2pStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pConnectionChange')<sup>8+</sup> ## wifi.on('p2pConnectionChange')<sup>8+</sup>
...@@ -2114,7 +2114,7 @@ Unregisters the P2P connection state change events. ...@@ -2114,7 +2114,7 @@ Unregisters the P2P connection state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pConnectionChange**.| | type | string | Yes| Event type. The value is **p2pConnectionChange**.|
| callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pDeviceChange')<sup>8+</sup> ## wifi.on('p2pDeviceChange')<sup>8+</sup>
...@@ -2150,7 +2150,7 @@ Unregisters the P2P device state change events. ...@@ -2150,7 +2150,7 @@ Unregisters the P2P device state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDeviceChange**.| | type | string | Yes| Event type. The value is **p2pDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pPeerDeviceChange')<sup>8+</sup> ## wifi.on('p2pPeerDeviceChange')<sup>8+</sup>
...@@ -2186,7 +2186,7 @@ Unregisters the P2P peer device state change events. ...@@ -2186,7 +2186,7 @@ Unregisters the P2P peer device state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pPersistentGroupChange')<sup>8+</sup> ## wifi.on('p2pPersistentGroupChange')<sup>8+</sup>
...@@ -2222,7 +2222,7 @@ Unregisters the P2P persistent group state change events. ...@@ -2222,7 +2222,7 @@ Unregisters the P2P persistent group state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.|
| callback | Callback&lt;void&gt; | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;void&gt; | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pDiscoveryChange')<sup>8+</sup> ## wifi.on('p2pDiscoveryChange')<sup>8+</sup>
...@@ -2265,4 +2265,4 @@ Unregisters the P2P device discovery state change events. ...@@ -2265,4 +2265,4 @@ Unregisters the P2P device discovery state change events.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
# HUKS Error Codes
## 12000001 Feature Not Supported
**Error Message**
`${messageInfo}` is not supported.
**Possible Causes**
The API is supported, but certain features in the API, such as the algorithm, are not supported.
**Procedure**
Modify the parameters and use the features supported.
## 12000002 Missing Key Algorithm Parameter
**Error Message**
Failed to obtain `${messageInfo}`. It is not set in ParamSet.
**Possible Causes**
The key parameter is not set.
**Procedure**
1. Determine the missing parameter from the error message.
2. Set the parameter.
## 12000003 Invalid Key Algorithm Parameter
**Error Message**
Invalid `${messageInfo}`.
**Possible Causes**
An invalid parameter is found.
**Procedure**
1. Determine the invalid parameter from the error message.
2. Correct the invalid parameter.
## 12000004 File Error
**Error Message**
Failed to read the file.
Failed to write the file.
**Possible Causes**
The file operation failed.
**Procedure**
1. Check whether the disk space is used up and whether the file system is abnormal.
2. Clear the disk space.
## 12000005 IPC Error
**Error Message**
IPC timed out.
Failed to obtain messages from IPC.
**Possible Causes**
IPC failed.
**Procedure**
Locate and rectify the IPC failure.
## 12000006 Algorithm Library Operation Failed
**Error Message**
Crypto engine error.
**Possible Causes**
The algorithm library operation fails. The possible causes include the following:
1. The encryption and decryption on the algorithm library failed due to incorrect ciphertext data.
2. Incorrect key parameters exist.
**Procedure**
1. Check and correct the ciphertext data.
2. Check and correct the key parameters.
## 12000007 Failed to Access the Key Due to Invalidated Credential
**Error Message**
This credential is invalidated permanently.
**Possible Causes**
The possible causes include the following:
1. The key is configured with the user access control attribute and becomes invalid after the password is cleared.
2. The key is configured with the user access control attribute and becomes invalid after a new biometric feature is enrolled.
**Procedure**
1. Locate the cause of the authentication failure based on the log.
2. If the authentication fails due to the access control attribute configured, the key cannot be used any more.
## 12000008 Failed to Access the Key Due to a Failure in Authentication Token Verification
**Error Message**
The authentication token verification failed.
**Possible Causes**
The authentication token verification failed due to an incorrect challenge value.
**Procedure**
1. Check whether the challenge for userIAM authentication is correctly assembled.
2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly challenge value, and pass it to userIAM for authentication.
## 12000009 Key Access Timed Out
**Error Message**
The Authentication token timed out.
**Possible Causes**
The authentication failed because the authentication token timed out.
**Procedure**
The difference between the current time and the authentication token generation time must be less than the timeout interval. Otherwise, the access will be rejected.
## 12000010 Key Operation Sessions Reaches the Limit
**Error Message**
The number of key operation sessions has reached the limit.
**Possible Causes**
The number of concurrent key operation sessions has reached the maximum (15).
**Procedure**
1. Check whether there are multiple key session operations (**init** operations) for the same application. If yes, modify the code to avoid concurrent invoking.
2. If the key operation sessions are set up for different applications, wait until the sessions are released.
## 12000011 The Entity Does Not Exist
**Error Message**
The entity does not exist.
**Possible Causes**
The key corresponding to the key alias does not exist.
**Procedure**
1. Check whether the key alias is misspelled.
2. Check whether the key corresponding to the key alias is successfully generated.
## 12000012 External Error
**Error Message**
External error `${messageInfo}`.
**Possible Causes**
An external error, such as a hardware fault or file error occurs.
**Procedure**
Provide the error code and log information to the related party.
## 12000013 The Credential Does Not Exist
**Error Message**
The credential does not exist.
**Possible Causes**
The credential, such as the PIN, fingerprint, or face image, is not enrolled.
**Procedure**
Enroll the credential or change the authentication type bound to the key.
## 12000014 Insufficient Memory
**Error Message**
Memory is insufficient.
**Possible Causes**
The system memory is insufficient.
**Procedure**
Release memory or restart the device.
## 12000015 Failed to Invoke Other System Services
**Error Message**
Failed to call the `${messageInfo}` service to do `${messageInfo}`.
**Possible Causes**
The called system service has not started.
**Procedure**
Wait for the system service to start and call the API again.
...@@ -7,7 +7,7 @@ OpenHarmony provides the following two types of Docker environments for you to q ...@@ -7,7 +7,7 @@ OpenHarmony provides the following two types of Docker environments for you to q
- Standalone Docker environment: applicable when using Ubuntu or Windows to build a distribution - Standalone Docker environment: applicable when using Ubuntu or Windows to build a distribution
- HPM-based Docker environment: applicable when using the HarmonyOS Package Manager \(HPM\) to build a distribution - HPM-based Docker environment: applicable when using the HarmonyOS Package Manager \(HPM\) to build a distribution
**Table 1** Docker image **Table 1** Docker image
<a name="table11986917191214"></a> <a name="table11986917191214"></a>
<table><thead align="left"><tr id="row149861417121215"><th class="cellrowborder" valign="top" width="15.831583158315832%" id="mcps1.2.6.1.1"><p id="p798611714124"><a name="p798611714124"></a><a name="p798611714124"></a>Docker Environment</p> <table><thead align="left"><tr id="row149861417121215"><th class="cellrowborder" valign="top" width="15.831583158315832%" id="mcps1.2.6.1.1"><p id="p798611714124"><a name="p798611714124"></a><a name="p798611714124"></a>Docker Environment</p>
...@@ -67,11 +67,12 @@ OpenHarmony provides the following two types of Docker environments for you to q ...@@ -67,11 +67,12 @@ OpenHarmony provides the following two types of Docker environments for you to q
Before using the Docker environment, perform the following operations: Before using the Docker environment, perform the following operations:
1. Install Docker. For details, see [Install Docker Engine](https://docs.docker.com/engine/install/). 1. Install Docker. For details, see [Install Docker Engine](https://docs.docker.com/engine/install/).
2. Obtain the OpenHarmony source code. For details, see [Source Code Acquisition](sourcecode-acquire.md). 2. Obtain the OpenHarmony source code. For details, see [Source Code Acquisition](sourcecode-acquire.md).
>![](../public_sys-resources/icon-note.gif) **NOTE**<br> > **NOTE**
>You do not need to obtain the source code for the HPM-based Docker environment. >
> You do not need to obtain the source code for the HPM-based Docker environment.
## Standalone Docker Environment<a name="section2858536103611"></a> ## Standalone Docker Environment<a name="section2858536103611"></a>
...@@ -94,7 +95,7 @@ The Docker image of OpenHarmony is hosted on HUAWEI CLOUD SWR. Using the Docker ...@@ -94,7 +95,7 @@ The Docker image of OpenHarmony is hosted on HUAWEI CLOUD SWR. Using the Docker
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:1.0.0 docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:1.0.0
``` ```
Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\):
``` ```
docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:1.0.0 docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:1.0.0
...@@ -111,17 +112,17 @@ Set the build path to the current path. ...@@ -111,17 +112,17 @@ Set the build path to the current path.
hb set hb set
``` ```
**Figure 1** Setting page<a name="fig7947145854013"></a> **Figure 1** Setting page<a name="fig7947145854013"></a>
![](figure/setting-page.png "setting-page") ![](figure/setting-page.png "setting-page")
>![](../public_sys-resources/icon-note.gif) **NOTE**<br> > **NOTE**<br>
>The mapping between the development board and the building GUI: > The mapping between the development board and the building GUI:
> >
>- Hi3861: wifiiot\_hispark\_pegasus@hisilicon > - Hi3861: wifiiot\_hispark\_pegasus@hisilicon
>- Hi3516: ipcamera\_hispark\_taurus@hisilicon > - Hi3516: ipcamera\_hispark\_taurus@hisilicon
>- Hi3518: ipcamera\_hispark\_aries@hisilicon > - Hi3518: ipcamera\_hispark\_aries@hisilicon
1. Select **ipcamera\_hispark\_taurus@hisilicon** and press **Enter**. 1. Select **ipcamera\_hispark\_taurus@hisilicon** and press **Enter**.
2. Start building. 2. Start building.
``` ```
...@@ -130,7 +131,7 @@ hb set ...@@ -130,7 +131,7 @@ hb set
3. View the build result. 3. View the build result.
The files will be generated in the **out/hispark\_taurus/ipcamera\_hispark\_taurus** directory. The files will be generated in the **out/hispark\_taurus/ipcamera\_hispark\_taurus** directory.
### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section13585262391"></a> ### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section13585262391"></a>
...@@ -156,17 +157,17 @@ Run the following script to start building for standard-system devices \(referen ...@@ -156,17 +157,17 @@ Run the following script to start building for standard-system devices \(referen
./build.sh --product-name {product_name} --ccache ./build.sh --product-name {product_name} --ccache
``` ```
**product\_name** indicates the platform supported by the current distribution, for example, hispark_taurus_standard and rk3568. **product\_name** indicates the platform supported by the current distribution, for example, hispark_taurus_standard and rk3568.
Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory.
>![](../public_sys-resources/icon-note.gif) **NOTE**<br> >![](../public_sys-resources/icon-note.gif) **NOTE**<br>
>You can exit Docker by simply running the **exit** command. >You can exit Docker by simply running the **exit** command.
## HPM-based Docker Environment<a name="section485713518337"></a> ## HPM-based Docker Environment<a name="section485713518337"></a>
**docker\_dist** is a template component in the [HPM](https://hpm.harmonyos.com/#/en/home) system. It helps to quickly initialize an HPM project and use the Docker image to quickly build a distribution of OpenHarmony, greatly simplifying environment configurations needed for building. After configuring the Ubuntu and hpm-cli development environments, perform the following steps to access the Docker environment: **docker\_dist** is a template component in the [HPM](https://hpm.harmonyos.com/#/en/home) system. It helps to quickly initialize an HPM project and use the Docker image to quickly build a distribution of OpenHarmony, greatly simplifying environment configurations needed for building. After configuring the Ubuntu and hpm-cli development environments, perform the following steps to access the Docker environment:
### Setting Up the Docker Environment<a name="section3295842510"></a> ### Setting Up the Docker Environment<a name="section3295842510"></a>
...@@ -176,20 +177,20 @@ Files generated during building are stored in the **out/{device_name}/** direc ...@@ -176,20 +177,20 @@ Files generated during building are stored in the **out/{device_name}/** direc
hpm init -t @ohos/docker_dist hpm init -t @ohos/docker_dist
``` ```
2. Modify the **publishAs** field. 2. Modify the **publishAs** field.
The obtained bundle is of the template type. Open the **bundle.json** file in the current directory and change the value of **publishAs** from **template** to **distribution** as needed. The obtained bundle is of the template type. Open the **bundle.json** file in the current directory and change the value of **publishAs** from **template** to **distribution** as needed.
### Obtaining and Building Source Code<a name="section69141039143518"></a> ### Obtaining and Building Source Code<a name="section69141039143518"></a>
Start building. Docker can be automatically installed only in Ubuntu. If you are using any other operating system, manually install Docker before pulling the image. Start building. Docker can be automatically installed only in Ubuntu. If you are using any other operating system, manually install Docker before pulling the image.
- **Automatically Installing Docker \(Ubuntu\)** - **Automatically Installing Docker \(Ubuntu\)**
Running the following command will automatically install Docker, pull the Docker image, and start the pulling and building of the corresponding solution in the container. Running the following command will automatically install Docker, pull the Docker image, and start the pulling and building of the corresponding solution in the container.
**Method 1:** **Method 1:**
Add a parameter to specify the solution. For example: Add a parameter to specify the solution. For example:
...@@ -197,9 +198,9 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are ...@@ -197,9 +198,9 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are
hpm run docker solution={product} hpm run docker solution={product}
``` ```
**\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**. **\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**.
**Method 2:** **Method 2:**
Set an environment variable to specify the solution, and then run the build command. Set an environment variable to specify the solution, and then run the build command.
...@@ -209,7 +210,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are ...@@ -209,7 +210,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are
export solution={product} export solution={product}
``` ```
**\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**. **\{product\}** indicates the solution, for example, **@ohos/hispark\_taurus**, **@ohos/hispark\_aries**, and **@ohos/hispark\_pegasus**.
2. Obtain and build the source code. 2. Obtain and build the source code.
...@@ -217,7 +218,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are ...@@ -217,7 +218,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are
hpm run docker hpm run docker
``` ```
This example uses the **@ohos/hispark\_taurus** solution for illustration. If the execution is successful, the output is as follows: This example uses the **@ohos/hispark\_taurus** solution for illustration. If the execution is successful, the output is as follows:
``` ```
... ...
...@@ -226,7 +227,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are ...@@ -226,7 +227,7 @@ Start building. Docker can be automatically installed only in Ubuntu. If you are
``` ```
- **Manually Installing Docker \(Non-Ubuntu\)** - **Manually Installing Docker \(Non-Ubuntu\)**
Perform the following operations to install Docker: Perform the following operations to install Docker:
......
...@@ -63,7 +63,7 @@ The appspawn module is used only for the standard system. ...@@ -63,7 +63,7 @@ The appspawn module is used only for the standard system.
- Support for cold start of applications by using the aa command - Support for cold start of applications by using the aa command
``` ```
param set appspawn.cold.boot true // Enable cold start. param set startup.appspawn.cold.boot 1 // Enable cold start.
aa start -d 12345 -a $name -b $package -C aa start -d 12345 -a $name -b $package -C
Reference command: Reference command:
aa start -d 12345 -a ohos.acts.startup.sysparam.function.MainAbility -b ohos.acts.startup.sysparam.function -C aa start -d 12345 -a ohos.acts.startup.sysparam.function.MainAbility -b ohos.acts.startup.sysparam.function -C
...@@ -166,5 +166,5 @@ The following is the sample code for adding product-specific configuration for t ...@@ -166,5 +166,5 @@ The following is the sample code for adding product-specific configuration for t
<br>Applications fail to be started by running the cold start command. <br>Applications fail to be started by running the cold start command.
**Solution** **Solution**
<br>1. Enable cold start by setting **param set appspawn.cold.boot true**. <br>1. Enable cold start by setting **param set startup.appspawn.cold.boot 1**.
<br>2. Make sure that the cold start command is correct. <br>2. Make sure that the cold start command is correct.
...@@ -163,6 +163,22 @@ By parsing the <strong>*.cfg</strong> file, you can obtain **service** fields, a ...@@ -163,6 +163,22 @@ By parsing the <strong>*.cfg</strong> file, you can obtain **service** fields, a
| int StartServiceByTimer(const char *serviceName, uint64_t timeout) | Starts a service by timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> timeout: timeout interval.| | int StartServiceByTimer(const char *serviceName, uint64_t timeout) | Starts a service by timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> timeout: timeout interval.|
| int StopServiceTimer(const char *serviceName) | Stops a service timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.| | int StopServiceTimer(const char *serviceName) | Stops a service timer.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.|
- DAC configuration for service control APIs
Go to **/base/startup/init/services/etc/group** and add the correct user ID to **servicectrl**. For example:
```java
servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr
```
- SELinux configuration for service control APIs
Add the required SELinux permissions to the **init.te** file. For example, grant the system parameter write permission for services such as **init**, **samgr**, and **hdf_devmgr**.
```java
allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set };
```
### How to Develop ### How to Develop
The following describes how to add a system service named **MySystemApp**: The following describes how to add a system service named **MySystemApp**:
......
...@@ -98,6 +98,55 @@ Each subsystem defines the system parameters of its own modules, including the s ...@@ -98,6 +98,55 @@ Each subsystem defines the system parameters of its own modules, including the s
![UGO rule](figure/dac-definition.png) ![UGO rule](figure/dac-definition.png)
- SELinux policy for system parameter configuration
- Add SELinux tags.
To add a SELinux tag to system parameters, you first need to define the tag in the **/base/security/selinux/sepolicy/base/public/parameter.te** file. For example:
```java
type servicectrl_param, parameter_attr
```
After the tag is defined, add the system parameter prefix associated with the tag to **/base/security/selinux/sepolicy/base/public/parameter_contexts**. The following uses the prefix **ohos.servicectrl** as an example:
```java
ohos.servicectrl. u:object_r:servicectrl_param:s0
```
- Grant operation permissions. For example, to grant operation permissions such as map for the init process, add the following content to the **/base/security/selinux/sepolicy/ohos_policy/startup/init/public/init.te** file:
```java
allow servicectrl_param tmpfs:filesystem associate;
allow init servicectrl_param:file { map open read relabelto relabelfrom };
```
- Set the write permission. For example, grant the system parameter write permission for services such as **init**, **samgr**, and **hdf_devmgr**.
```java
allow { init samgr hdf_devmgr } servicectrl_param:parameter_service { set };
```
- Set the read permission. If you want to grant the permission only for certain services, replace **xxx** with the services in the following code:
```java
allow { xxx } servicectrl_param:file { map open read };
```
- If you want to grant the permission for all services, use the following code:
```java
allow { domain -limit_domain } servicectrl_param:file { map open read };
```
- Suggestions
Keep only two system parameter tags for each subsystem:
- A private tag to control system parameter settings.
- A public tag to grant access from all services.
- Loading sequence - Loading sequence
The following table provides the sequence of loading system parameters. The following table provides the sequence of loading system parameters.
...@@ -111,6 +160,22 @@ Each subsystem defines the system parameters of its own modules, including the s ...@@ -111,6 +160,22 @@ Each subsystem defines the system parameters of its own modules, including the s
| System parameters| /system/etc/param/*.para | Load the parameters defined by each subsystem. If a system parameter already exists, ignore it.| | System parameters| /system/etc/param/*.para | Load the parameters defined by each subsystem. If a system parameter already exists, ignore it.|
| Persistent parameters| /data/parameters/ | If persistent parameters exist, load them at last. Persistent parameters will overwrite the default system parameters that have been loaded.| | Persistent parameters| /data/parameters/ | If persistent parameters exist, load them at last. Persistent parameters will overwrite the default system parameters that have been loaded.|
#### System Parameter Tag File Size
If one tag corresponds to more than five system parameters, you need to set the size of the system parameter tag file in **/base/startup/init/services/etc/param/ohos.para.size**. The size value is **512** by default.
Configuring rule:
System parameter tag = Size
Example:
```java
startup_init_param=40960
```
### Constraints ### Constraints
The service management module is available only for the mini system and standard system. The service management module is available only for the mini system and standard system.
......
# OTA Update<a name="EN-US_TOPIC_0000001163932574"></a> # OTA Update
## Introduction<a name="section753413913562"></a>
Over the Air \(OTA\) is a technology that makes it easier for you to remotely update devices, such as IP cameras. Currently, the mini and small systems support update using a full package, but not a differential package. A full package contains all content of a new system, and a differential package contains the differences between the old and new systems. ## Introduction
## Constraints<a name="section61232796162135"></a>
- Only the open-source suites for devices powered by Hi3861, Hi3518E V300, and Hi3516D V300 are supported. ### Overview
- Devices developed based on Hi3518E V300 and Hi3516D V300 must support the SD card in the Virtual Festival of Aerobatic Teams \(VFAT\) format.
>![](../public_sys-resources/icon-note.gif) **NOTE:** With the rapid development of device systems, it has become a critical challenge for device vendors to help their users to access system updates in a timely manner to experience the new features and improve the system stability and security.
>Generation of update packages can only be performed on the Linux system.
Over the Air (OTA) answers this challenge with the support for remote updating of device systems. By providing unified update APIs externally, the update subsystem shields the differences of underlying chips. After secondary development based on the update APIs, device vendors can easily implement remote updating for their devices, such as IP cameras.
## Generating a Public/Private Key Pair<a name="section1392711588162135"></a>
1. Download the [OpenSSL](http://slproweb.com/products/Win32OpenSSL.html) tool, install it on a Windows PC, and configure environment variables. ### Basic Concepts
2. Use the OpenSSL tool to generate a public/private key pair.
3. Keep the private key file properly as this file stores the private key used to sign the update package. You need to specify the private key file in the command used for preparing the update package. The public key is used to verify the signature of the update package during the upgrade, and it is stored as follows:
For the mini and small systems, the generated public key is preset in the code. The vendor needs to implement the **HotaHalGetPubKey** API to obtain the key. For the standard system, the generated public key is stored in the **./device/hisilicon/hi3516dv300/build/updater\_config/signing\_cert.crt** file. - Full package: an update package that packs all images of the target version.
4. For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 suite, also use the content in **public\_arr.txt** to replace the content in **g\_pub\_key** in the **device\\hisilicon\\third\_party\\uboot\\u-boot-2020.01\\product\\hiupdate\\verify\\update\_public\_key.c** file of the U-Boot module. - Differential package: an update package that packs the differential images between the source version and target version.
Example configuration for the public key of the U-Boot module:
``` ### Implementation Principle
static unsigned char g_pub_key[PUBKEY_LEN] = {
0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, To implement an OTA update, you first need to use the packaging tool to pack the build version into an update package and upload the update package to the OTA server. Devices integrating the OTA update capability can then detect the update package and download it to implement a remote update.
0x00, 0xBF, 0xAA, 0xA5, 0xB3, 0xC2, 0x78, 0x5E,
} <a href="#ab-update-scenario">A/B Update</a>: a typical application of OTA update. In this update mode, a device has a backup system B. When system A is running, system B is updated silently. After the update is successful, the device restarts and switches to the new system.
```
### Constraints
## Generating an Update Package<a name="section704519924162135"></a>
- Only the open-source suites for devices powered by Hi3861, Hi3518E V300, and Hi3516D V300 are supported.
### Mini and Small Systems<a name="section527064658162135"></a>
- Devices developed based on Hi3518E V300 and Hi3516D V300 must support the SD card in the Virtual Festival of Aerobatic Teams (VFAT) format.
1. Create the **target\_package** folder with the following directory structure:
- Generation of update packages can only be performed on the Linux system.
```
target_package - Currently, the mini and small systems support update using a full package, but not a differential package or an update package with partitions changed.
├── OTA.tag
├── config
├── {component_1} ## Environment Preparation
├── {component_2}
├── ... - On Windows, download and install the OpenSSL tool and configure environment variables.
├── {component_N} - Prepare the packaging tool.
└── updater_config - Build version images using the packaging tool.
└── updater_specified_config.xml - On Linux, pack version images to generate the update package.
``` - To implement an A/B update, ensure that the devices running the standard system support booting from partitions A and B.
2. Place the components to be updated, including the image file \(for example, **rootfs.img**\), as \{component\_N\} in the root directory of the **target\_package** folder.
3. Configure the **updater\_specified\_config.xml** file in the **update\_config** folder. ## OTA Update Guide
Example configuration of the **updater\_specified\_config.xml** file:
### Development Procedure
```
<?xml version="1.0"?> <a href="#generating-a-publicprivate-key-pair">1. Use the OpenSSL tool to generate a public/private key pair.
<package>
<head name="Component header information"> <a href="#making-an-update-package">2. Use the packaging tool to generate an update package.</a>
<info fileVersion="01" prdID="hisi" softVersion="OpenHarmony x.x" date="202x.xx.xx" time="xx:xx:xx">head info</info>
</head> &ensp;&ensp;<a href="#mini-and-small-systems">2.1 Mini and small systems</a>
<group name="Component information">
<component compAddr="ota_tag" compId="27" resType="5" compType="0" compVer="1.0">./OTA.tag</component> &ensp;&ensp;<a href="#standard-system">2.2 Standard system</a>
<component compAddr="config" compId="23" resType="5" compType="0" compVer="1.0">./config</component>
<component compAddr="bootloader" compId="24" resType="5" compType="0" compVer="1.0">./u-boot-xxxx.bin</component> <a href="#uploading-the-update-package">3. Upload the update package to the vendor's OTA server.</a>
</group>
</package> <a href="#downloading-the-update-package">4. Download the update package from the vendor's OTA server.</a>
```
<a href="#integrating-ota-update-capabilities">5. Integrate the OTA update capability.
**Table 1** Description of nodes in the component configuration file
&ensp;&ensp;<a href="#api-application-scenario-default">5.1 API application scenario (default)</a>
<a name="table252476175162135"></a>
<table><thead align="left"><tr id="row479509028162135"><th class="cellrowborder" valign="top" width="20%" id="mcps1.1.6.1.1"><p id="entry1406757300162135p0"><a name="entry1406757300162135p0"></a><a name="entry1406757300162135p0"></a>Type</p> &ensp;&ensp;<a href="#api-application-scenario-custom">5.2 API application scenario (custom)</a>
</th>
<th class="cellrowborder" valign="top" width="20%" id="mcps1.1.6.1.2"><p id="entry442152588162135p0"><a name="entry442152588162135p0"></a><a name="entry442152588162135p0"></a>Node Name</p> &ensp;&ensp;<a href="#ab-update-scenario">5.3 A/B update scenario</a>
</th>
<th class="cellrowborder" valign="top" width="20%" id="mcps1.1.6.1.3"><p id="entry1001010016162135p0"><a name="entry1001010016162135p0"></a><a name="entry1001010016162135p0"></a>Node Label</p>
</th> ### How to Develop
<th class="cellrowborder" valign="top" width="20%" id="mcps1.1.6.1.4"><p id="entry523786033162135p0"><a name="entry523786033162135p0"></a><a name="entry523786033162135p0"></a>Mandatory</p>
</th>
<th class="cellrowborder" valign="top" width="20%" id="mcps1.1.6.1.5"><p id="entry1703280805162135p0"><a name="entry1703280805162135p0"></a><a name="entry1703280805162135p0"></a>Description</p> #### Generating a Public/Private Key Pair
</th> 1. Use the OpenSSL tool to generate a public/private key pair.
</tr>
</thead> 3. Keep the private key file properly as this file stores the private key used to sign the update package. You need to specify the private key file in the command used for preparing the update package. The public key is used to verify the signature of the update package during the update. For the mini and small systems, the generated public key is preset in the code. You need to implement the **HotaHalGetPubKey** API to obtain the key. For the standard system, the generated public key is stored in the **./device/hisilicon/hi3516dv300/build/updater_config/signing_cert.crt** file.
<tbody><tr id="row1146183787162135"><td class="cellrowborder" rowspan="6" valign="top" width="20%" headers="mcps1.1.6.1.1 "><p id="p1965185185211"><a name="p1965185185211"></a><a name="p1965185185211"></a>Header information (head node)</p>
</td> 5. For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 suite, use the content in **public\_arr.txt** to replace the content in **g\_pub\_key** in the **device\hisilicon\third_party\uboot\u-boot-2020.01\product\hiupdate\verify\update\_public\_key.c** file of the U-Boot module.
<td class="cellrowborder" rowspan="6" valign="top" width="20%" headers="mcps1.1.6.1.2 "><p id="entry787291920162135p0"><a name="entry787291920162135p0"></a><a name="entry787291920162135p0"></a>info</p> Example configuration:
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.1.6.1.3 "><p id="entry1321423743162135p0"><a name="entry1321423743162135p0"></a><a name="entry1321423743162135p0"></a>/</p> ```c
</td> static unsigned char g_pub_key[PUBKEY_LEN] = {
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.1.6.1.4 "><p id="entry414082731162135p0"><a name="entry414082731162135p0"></a><a name="entry414082731162135p0"></a>Yes</p> 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01,
</td> 0x00, 0xBF, 0xAA, 0xA5, 0xB3, 0xC2, 0x78, 0x5E,
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.1.6.1.5 "><p id="entry783609139162135p0"><a name="entry783609139162135p0"></a><a name="entry783609139162135p0"></a>Content of this node: head info</p> }
</td> ```
</tr>
<tr id="row1958159196162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry1679905595162135p0"><a name="entry1679905595162135p0"></a><a name="entry1679905595162135p0"></a>fileVersion</p>
</td> #### Making an Update Package
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry658282018162135p0"><a name="entry658282018162135p0"></a><a name="entry658282018162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry1810096705162135p0"><a name="entry1810096705162135p0"></a><a name="entry1810096705162135p0"></a>This field is reserved and does not affect the generation of the update package.</p> ##### Mini and Small Systems
</td>
</tr> 1. Create the **target\_package** folder with the following directory structure:
<tr id="row147166457162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry1081707070162135p0"><a name="entry1081707070162135p0"></a><a name="entry1081707070162135p0"></a>prdID</p>
</td> ```text
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry1297695863162135p0"><a name="entry1297695863162135p0"></a><a name="entry1297695863162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry876347577162135p0"><a name="entry876347577162135p0"></a><a name="entry876347577162135p0"></a>This field is reserved and does not affect the generation of the update package.</p>
</td>
</tr>
<tr id="row713278098162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry1527725234162135p0"><a name="entry1527725234162135p0"></a><a name="entry1527725234162135p0"></a>softVersion</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry1298699378162135p0"><a name="entry1298699378162135p0"></a><a name="entry1298699378162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry1986606994162135p0"><a name="entry1986606994162135p0"></a><a name="entry1986606994162135p0"></a>Software version number, that is, the version number of the update package. The version number must be within the range specified by <strong id="b1587416137107"><a name="b1587416137107"></a><a name="b1587416137107"></a>VERSION.mbn</strong>. Otherwise, an update package will not be generated.</p>
</td>
</tr>
<tr id="row1998569355162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry40037754162135p0"><a name="entry40037754162135p0"></a><a name="entry40037754162135p0"></a>date</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry1867473067162135p0"><a name="entry1867473067162135p0"></a><a name="entry1867473067162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry1898510646162135p0"><a name="entry1898510646162135p0"></a><a name="entry1898510646162135p0"></a>Date when the update package is generated. This field is reserved and does not affect the generation of the update package.</p>
</td>
</tr>
<tr id="row853604644162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry341395756162135p0"><a name="entry341395756162135p0"></a><a name="entry341395756162135p0"></a>time</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry411979929162135p0"><a name="entry411979929162135p0"></a><a name="entry411979929162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry1952723593162135p0"><a name="entry1952723593162135p0"></a><a name="entry1952723593162135p0"></a>Time when the update package is generated. This field is reserved and does not affect the generation of the update package.</p>
</td>
</tr>
<tr id="row311903547162135"><td class="cellrowborder" rowspan="5" valign="top" width="20%" headers="mcps1.1.6.1.1 "><p id="entry1756487158162135p0"><a name="entry1756487158162135p0"></a><a name="entry1756487158162135p0"></a>Component information (group node)</p>
</td>
<td class="cellrowborder" rowspan="5" valign="top" width="20%" headers="mcps1.1.6.1.2 "><p id="entry2070156141162135p0"><a name="entry2070156141162135p0"></a><a name="entry2070156141162135p0"></a>component</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.1.6.1.3 "><p id="entry894043714162135p0"><a name="entry894043714162135p0"></a><a name="entry894043714162135p0"></a>/</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.1.6.1.4 "><p id="entry1899300718162135p0"><a name="entry1899300718162135p0"></a><a name="entry1899300718162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.1.6.1.5 "><p id="entry1457912275162135p0"><a name="entry1457912275162135p0"></a><a name="entry1457912275162135p0"></a>Content of this node: path of the component or image file to be packed into the update package. It is the root directory of the version package by default.</p>
</td>
</tr>
<tr id="row691331702162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry1271021967162135p0"><a name="entry1271021967162135p0"></a><a name="entry1271021967162135p0"></a>compAddr</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry967575438162135p0"><a name="entry967575438162135p0"></a><a name="entry967575438162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry2010019875162135p0"><a name="entry2010019875162135p0"></a><a name="entry2010019875162135p0"></a>Name of the partition corresponding to the component, for example, <strong id="b19437823131512"><a name="b19437823131512"></a><a name="b19437823131512"></a>system</strong> or <strong id="b375692501514"><a name="b375692501514"></a><a name="b375692501514"></a>vendor</strong>.</p>
</td>
</tr>
<tr id="row849226815162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry21721216162135p0"><a name="entry21721216162135p0"></a><a name="entry21721216162135p0"></a>compId</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry674558287162135p0"><a name="entry674558287162135p0"></a><a name="entry674558287162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry1193039499162135p0"><a name="entry1193039499162135p0"></a><a name="entry1193039499162135p0"></a>Component ID, which must be unique.</p>
</td>
</tr>
<tr id="row813205598162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry897639380162135p0"><a name="entry897639380162135p0"></a><a name="entry897639380162135p0"></a>resType</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry204468393162135p0"><a name="entry204468393162135p0"></a><a name="entry204468393162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry1005669355162135p0"><a name="entry1005669355162135p0"></a><a name="entry1005669355162135p0"></a>This field is reserved and does not affect the generation of the update package.</p>
</td>
</tr>
<tr id="row2087193735162135"><td class="cellrowborder" valign="top" headers="mcps1.1.6.1.1 "><p id="entry800634310162135p0"><a name="entry800634310162135p0"></a><a name="entry800634310162135p0"></a>compType</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.2 "><p id="entry1484190922162135p0"><a name="entry1484190922162135p0"></a><a name="entry1484190922162135p0"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.1.6.1.3 "><p id="entry894563848162135p0"><a name="entry894563848162135p0"></a><a name="entry894563848162135p0"></a>Image type, which can be a full or differential package. The value <strong id="b16850185911295"><a name="b16850185911295"></a><a name="b16850185911295"></a>0</strong> indicates a full package, and value <strong id="b2095321320305"><a name="b2095321320305"></a><a name="b2095321320305"></a>1</strong> indicates a differential package.</p>
</td>
</tr>
</tbody>
</table>
>![](../public_sys-resources/icon-note.gif) **NOTE:**
>As mini and small systems do not support update using a differential package, **compType** must be set to **0**, other than **1**.
>For mini and small systems, an update package cannot be created by changing partitions.
4. Create the **OTA.tag** file, which contains the magic number of the update package. The magic number is as follows:
```
package_type:ota1234567890qwertw
```
5. Create the **config** file, and configure the **bootargs** and **bootcmd** information in the file.
Example configuration:
```
setenv bootargs 'mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 rw rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M
(u-boot.bin),9M(kernel.bin),50M(rootfs_ext4.img),50M(userfs.img)' setenv bootcmd 'mmc read 0x0 0x82000000 0x800 0x4800;bootm 0x82000000'
```
6. Generate the update package.
```
python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem -nz -nl2x
```
- **./target\_package/**: path of **target\_package**
- **./output\_package/**: output path of the update package
- **-pk ./rsa\_private\_key3072.pem**: path of the private key file
- **-nz**: **not zip** mode
- **-nl2**: non-standard system mode
### Standard System<a name="section1291354584162135"></a>
1. Create the **target\_package** folder with the following directory structure:
```
target_package target_package
├── OTA.tag
├── config
├── {component_1} ├── {component_1}
├── {component_2} ├── {component_2}
├── ... ├── ...
├── {component_N} ├── {component_N}
└── updater_config └── updater_config
├── BOARD.list └── updater_specified_config.xml
├── VERSION.mbn ```
└── updater_specified_config.xml
``` 2. Place the components to be updated, including the image file (for example, **rootfs.img**), as **{component\_N}** in the root directory of the **target\_package** folder.
2. Place the components to be updated, including the image file \(for example, **system.img**\), as \{component\_N\} in the root directory of the **target\_package** folder. 3. Configure the **updater\_specified\_config.xml** file in the **updater_config** folder.
3. Configure the component configuration file in the **update\_config** folder. Example configuration:
4. Configure the list of products supported by the current update package in **BOARD.list** in the **update\_config** folder.
```xml
Example configuration: <?xml version="1.0"?>
<package>
``` <head name="Component header information">
HI3516 <info fileVersion="01" prdID="hisi" softVersion="OpenHarmony x.x" date="202x.xx.xx" time="xx:xx:xx">head info</info>
HI3518 </head>
``` <group name="Component information">
<component compAddr="ota_tag" compId="27" resType="5" compType="0" compVer="1.0">./OTA.tag</component>
5. Configure the versions supported by the current update package in **VERSION.mbn** in the **update\_config** folder. <component compAddr="config" compId="23" resType="5" compType="0" compVer="1.0">./config</component>
<component compAddr="bootloader" compId="24" resType="5" compType="0" compVer="1.0">./u-boot-xxxx.bin</component>
Version number format: Hi3516DV300-eng 10 QP1A.XXXXXX.\{Major version number \(6 digits\)\}.XXX\{Minor version number \(3 digits\)\} </group>
</package>
For example, Hi3516DV300-eng 10 QP1A.190711.020, where **190711** is the major version number, and **020** is the minor version number. ```
Example configuration:
**Table 1** Description of nodes in the component configuration file
```
Hi3516DV300-eng 10 QP1A.190711.001 | Type| Node Name| Node Label| Mandatory| Description|
Hi3516DV300-eng 10 QP1A.190711.020 | -------- | -------- | -------- | -------- | -------- |
Hi3518DV300-eng 10 QP1A.190711.021 | Header information (head node)| info| / | Yes| Content of this node: head&nbsp;info|
``` | Header information (head node)| info| fileVersion | Yes| This field is reserved and does not affect the generation of the update package.|
| Header information (head node)| info| prdID | Yes| This field is reserved and does not affect the generation of the update package.|
6. For update using an incremental \(differential\) package, also prepare a source version package \(source\_package\) in the same format as the target version package \(target\_package\), and then compress it as a **.zip** file, that is, **source\_package.zip**. | Header information (head node)| info| softVersion | Yes| Software version number, that is, the version number of the update package. The version number must be within the range specified by **VERSION.mbn**. Otherwise, an update package will not be generated.|
| Header information (head node)| info| date| Yes| Date when the update package is generated. This field is reserved and does not affect the generation of the update package.|
7. If you create an update package with partitions changed, also provide the partition table file named **partition\_file.xml**. You can specify the file using the **-pf** parameter. For details about the configuration nodes, see the description below. | Header information (head node)| info| time| Yes| Time when the update package is generated. This field is reserved and does not affect the generation of the update package.|
| Component information (group node)| component| / | Yes| Content of this node: path of the component or image file to be packed into the update package. It is the root directory of the version package by default.|
The partition table is generated with the image. The format is as follows: | Component information (group node)| component| compAddr | Yes| Name of the partition corresponding to the component, for example, **system** or **vendor**.|
| Component information (group node)| component| compId | Yes| Component ID, which must be unique.|
``` | Component information (group node)| component| resType | Yes| This field is reserved and does not affect the generation of the update package.|
<?xml version="1.0" encoding="GB2312" ?> | Component information (group node)| component| compType | Yes| Image type, which can be a full or differential package. The value **0** indicates a full package, and value **1** indicates a differential package.|
<Partition_Info>
<Part Sel="1" PartitionName="Image 1" FlashType="Flash type" FileSystem="File system type" Start="Start address of the partition" Length="Size of the partition" SelectFile="Actual path of the image"/> > **NOTE**
<Part Sel="1" PartitionName="Image 2" FlashType="Flash type" FileSystem="File system type" Start="Start address of the partition" Length="Size of the partition" SelectFile="Actual path of the image"/> > As mini and small systems do not support updating with a differential package, **compType** must be set to **0**, other than **1**.
</Partition_Info> >
``` > For mini and small systems, an update package cannot be created by changing partitions.
**Table 2** Description of labels in the partition table 4. Create the **OTA.tag** file, which contains the magic number of the update package. The magic number is fixed, as shown below:
<a name="table806330288162135"></a> ```text
<table><thead align="left"><tr id="row682144517162135"><th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.1"><p id="entry387204270162135p0"><a name="entry387204270162135p0"></a><a name="entry387204270162135p0"></a>Label</p> package_type:ota1234567890qwertw
</th> ```
<th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.2"><p id="entry750055172162135p0"><a name="entry750055172162135p0"></a><a name="entry750055172162135p0"></a>Description</p>
</th> 5. Create the **config** file, and configure the **bootargs** and **bootcmd** information in the file.
</tr> Example configuration:
</thead>
<tbody><tr id="row1074495132162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry1271686486162135p0"><a name="entry1271686486162135p0"></a><a name="entry1271686486162135p0"></a>Sel</p>
</td> ```text
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry1588639785162135p0"><a name="entry1588639785162135p0"></a><a name="entry1588639785162135p0"></a>Whether the partition is effective. The value <strong id="b156151453173416"><a name="b156151453173416"></a><a name="b156151453173416"></a>1</strong> indicates that the partition is effective, and value <strong id="b166297633517"><a name="b166297633517"></a><a name="b166297633517"></a>0</strong> indicates the opposite.</p> setenv bootargs 'mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 rw rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M
</td> (u-boot.bin),9M(kernel.bin),50M(rootfs_ext4.img),50M(userfs.img)' setenv bootcmd 'mmc read 0x0 0x82000000 0x800 0x4800;bootm 0x82000000'
</tr> ```
<tr id="row1838873028162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry405380697162135p0"><a name="entry405380697162135p0"></a><a name="entry405380697162135p0"></a>PartitionName</p>
</td> 6. Generate the update package.
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry539229490162135p0"><a name="entry539229490162135p0"></a><a name="entry539229490162135p0"></a>Partition name, for example, <strong id="b1173483114376"><a name="b1173483114376"></a><a name="b1173483114376"></a>fastboot</strong> or <strong id="b163708336376"><a name="b163708336376"></a><a name="b163708336376"></a>boot</strong>.</p>
</td> ```text
</tr> python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem -nz -nl2
<tr id="row1321400941162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry360591364162135p0"><a name="entry360591364162135p0"></a><a name="entry360591364162135p0"></a>FlashType</p> ```
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry1536610466162135p0"><a name="entry1536610466162135p0"></a><a name="entry1536610466162135p0"></a>Flash type, for example, <strong id="b1711717453820"><a name="b1711717453820"></a><a name="b1711717453820"></a>emmc</strong> or <strong id="b86479117387"><a name="b86479117387"></a><a name="b86479117387"></a>ufs</strong>.</p> - **./target\_package/**: path of **target\_package**
</td> - **./output\_package/**: output path of the update package
</tr> - -**pk ./rsa\_private\_key3072.pem**: path of the private key file
<tr id="row1724163696162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry278309753162135p0"><a name="entry278309753162135p0"></a><a name="entry278309753162135p0"></a>FileSystem</p> - -**nz**: **not zip** mode
</td> - -**nl2**: non-standard system mode
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry218585771162135p0"><a name="entry218585771162135p0"></a><a name="entry218585771162135p0"></a>File system type, for example, <strong id="b63519206383"><a name="b63519206383"></a><a name="b63519206383"></a>ext3/4</strong> or <strong id="b172821252383"><a name="b172821252383"></a><a name="b172821252383"></a>f2fs</strong>. The value can also be <strong id="b63162773815"><a name="b63162773815"></a><a name="b63162773815"></a>none</strong>.</p>
</td>
</tr> ##### Standard System
<tr id="row1809526161162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry1440557777162135p0"><a name="entry1440557777162135p0"></a><a name="entry1440557777162135p0"></a>Start</p>
</td> 1. Create the **target\_package** folder with the following directory structure:
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry814481339162135p0"><a name="entry814481339162135p0"></a><a name="entry814481339162135p0"></a>Start address of the partition, in MB. The start address of all partitions is <strong id="b1171284398"><a name="b1171284398"></a><a name="b1171284398"></a>0</strong>.</p>
</td>
</tr> ```text
<tr id="row1052365500162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry463606592162135p0"><a name="entry463606592162135p0"></a><a name="entry463606592162135p0"></a>Length</p> target_package
</td> ├── {component_1}
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry18613946162135p0"><a name="entry18613946162135p0"></a><a name="entry18613946162135p0"></a>Size of the partition, in MB.</p> ├── {component_2}
</td> ├── ...
</tr> ├── {component_N}
<tr id="row2062761324162135"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="entry1424721291162135p0"><a name="entry1424721291162135p0"></a><a name="entry1424721291162135p0"></a>SelectFile</p> └── updater_config
</td> ├── BOARD.list
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="entry1154631273162135p0"><a name="entry1154631273162135p0"></a><a name="entry1154631273162135p0"></a>Actual path of the image or file.</p> ├── VERSION.mbn
</td> └── updater_specified_config.xml
</tr> ```
</tbody>
</table> 2. Place the components to be updated, including the image file (for example, **system.img**), as **{component\_N}** in the root directory of the **target\_package** folder.
8. Generate the update package. 3. Configure the component configuration file in the **updater\_config** folder.
**Full package** 4. Configure the list of products supported by the current update package in **BOARD.list** in the **updater\_config** folder.
Run the following command: Example configuration:
```
python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem ```text
``` HI3516
HI3518
- **./target\_package/**: path of **target\_package** ```
- **./output\_package/**: output path of the update package
- **-pk ./rsa\_private\_key3072.pem**: path of the private key file 5. Configure the versions supported by the current update package in **VERSION.mbn** in the **updater\_config** folder.
**Incremental \(differential\) package** Version number format: Hi3516DV300-eng 10 QP1A.XXXXXX.{Major version number (6 digits)}.XXX{Minor version number (3 digits)}
Run the following command: For example, **Hi3516DV300-eng 10 QP1A.190711.020**, where **190711** is the major version number, and **020** is the minor version number.
``` Example configuration:
python build_update.py ./target_package/ ./output_package/ -s ./source_package.zip -pk ./rsa_private_key3072.pem
```
```text
- **./target\_package/**: path of **target\_package** Hi3516DV300-eng 10 QP1A.190711.001
- **./output\_package/**: output path of the update package Hi3516DV300-eng 10 QP1A.190711.020
- **-s ./source\_package.zip**: path of the **source\_package.zip** file. For update using a differential package, use the **-s** parameter to specify the source version package. Hi3518DV300-eng 10 QP1A.190711.021
- **-pk ./rsa\_private\_key3072.pem**: path of the private key file ```
**Update package with partitions changed** 6. For an update using the incremental (differential) package, also prepare a source version package (source\_package) in the same format as the target version package (target\_package), and then compress it as a **.zip** file, that is, **source\_package.zip**.
Run the following command: 7. If you create an update package with partitions changed, also provide the partition table file named **partition\_file.xml**. You can specify the file using the **-pf** parameter. For details about the configuration nodes, see the description below.
``` The partition table is generated with the image. The format is as follows:
python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key3072.pem -pf ./partition_file.xml
```
```xml
- **./target\_package/**: path of **target\_package** <?xml version="1.0" encoding="GB2312" ?>
- **./output\_package/**: output path of the update package <Partition_Info>
- **-pk ./rsa\_private\_key3072.pem**: path of the private key file <Part Sel="1" PartitionName="Image 1" FlashType="Flash type" FileSystem="File system type" Start="Start address of the partition" Length="Size of the partition" SelectFile="Actual path of the image"/>
- **-pf ./partition\_file.xml**: path of the partition table file <Part Sel="1" PartitionName="Image 2" FlashType="Flash type" FileSystem="File system type" Start="Start address of the partition" Length="Size of the partition" SelectFile="Actual path of the image"/>
</Partition_Info>
```
## Uploading the Update Package<a name="section1040019352162135"></a>
**Table 2** Description of labels in the partition table
| Name | Description |
| ---- | ----------- |
| Sel | Whether the partition is effective. The value **1** indicates that the partition is effective, and value **0** indicates the opposite.|
| PartitionName | Partition name, for example, **fastboot** or **boot**.|
| FlashType | Flash type, for example, **emmc** or **ufs**.|
| FileSystem | File system type, for example, **ext3/4** or **f2fs**. The value can also be **none**.|
| Start | Start address of the partition, in MB. The start address of all partitions is **0**.|
| Length | Size of the partition, in MB.|
| SelectFile | Actual path of the image or file.|
8. Generate the update package.
**Full package**
Run the following command:
```text
python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key2048.pem
```
- **./target\_package/**: path of **target\_package**
- **./output\_package/**: output path of the update package
- -**pk ./rsa\_private\_key3072.pem**: path of the private key file
**Incremental (differential) package**
Run the following command:
```text
python build_update.py ./target_package/ ./output_package/ -s ./source_package.zip -pk ./rsa_private_key2048.pem
```
- **./target\_package/**: path of **target\_package**
- **./output\_package/**: output path of the update package
- -**s ./source\_package.zip**: path of the **source\_package.zip** file. For update using a differential package, use the **-s** parameter to specify the source version package.
- -**pk ./rsa\_private\_key3072.pem**: path of the private key file
**Update package with partitions changed**
Run the following command:
```text
python build_update.py ./target_package/ ./output_package/ -pk ./rsa_private_key2048.pem -pf ./partition_file.xml
```
- **./target\_package/**: path of **target_package**
- **./output\_package/**: output path of the update package
- -**pk ./rsa\_private_key3072.pem**: path of the private key file
- -**pf ./partition\_file.xml**: path of the partition table file
#### **Uploading the Update Package**
Upload the update package to the vendor's OTA server. Upload the update package to the vendor's OTA server.
## Downloading the Update Package<a name="section1870792413162135"></a>
1. Download the update package from the OTA server. #### **Downloading the Update Package**
2. \(Optional\) Insert an SD card \(with a capacity greater than 100 MB\) if the device is developed based on Hi3518E V300 or Hi3516D V300.
1. Download the update package from the OTA server.
## Integrating OTA Update Capabilities<a name="section2107348555162135"></a> 2. (Optional) Insert an SD card (with a capacity greater than 100 MB) if the device is developed based on Hi3518E V300 or Hi3516D V300.
1. For mini and small systems
- If a vendor requests OTA capabilities, use the dynamic library **libhota.so** and include the header files **hota\_partition.h** and **hota\_updater.h** in **base\\update\\ota\_lite\\interfaces\\kits**. #### Integrating OTA Update Capabilities
- The **libhota.so** source code is stored in **base\\update\\ota\_lite\\frameworks\\source**. 1. For mini and small systems
- For details about how to use APIs, see _API Application Scenario_ and OTA APIs in _API Reference_. - Call the dynamic library **libhota.so**. The corresponding header files **hota\_partition.h** and **hota\_updater.h** are located in **base\update\ota_lite\interfaces\kits**.
- The **libhota.so** source code is located in **base\update\ota_lite\frameworks\source**.
- For details about how to use APIs, see *API Application Scenarios* and update APIs in *API Reference*.
- If the development board needs to be adapted, see the **base\update\ota_lite\hals\hal\_hota\_board.h** file.
- If the development board needs to be adapted, see the **base\\update\\ota\_lite\\hals\\hal\_hota\_board.h** file. 2. For the standard system, see the [JS API Reference](../../application-dev/reference/apis/js-apis-update.md) for details.
2. For the standard system, see the [Reference Specifications](../../application-dev/reference/apis/js-apis-update.md) for details.
## API Application Scenario \(Default\)<a name="section1308521557162135"></a> ##### API Application Scenario (Default)
The update package is generated by following the instructions provided in Generating a Public/Private Key Pair and Generating an Update Package. The update package is generated by following the instructions provided in Generating a Public/Private Key Pair and Generating an Update Package.
### **How to Develop**<a name="section2103641927162135"></a>
1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module. ###### How to Develop
2. Call the **HotaWrite** function to verify, parse, and write data streams into the device. 1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module.
3. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update. 2. Call the **HotaWrite** function to verify, parse, and write data streams for the update into the device.
3. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update.
### **Sample Code**<a name="section1918621904162135"></a>
Perform an OTA update using the update package format and verification method provided by OpenHarmony. ###### Sample Code
``` Perform an OTA update using the update package format and verification method provided by OpenHarmony.
```cpp
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
printf("this is update print!\r\n"); printf("this is update print!\r\n");
...@@ -440,30 +389,32 @@ int main(int argc, char **argv) ...@@ -440,30 +389,32 @@ int main(int argc, char **argv)
} }
``` ```
## API Application Scenario \(Custom\)<a name="section1332839930162135"></a>
The update package is generated in other ways instead of following the instructions provided in Generating a Public/Private Key Pair and Generating an Update Package. ##### API Application Scenario (Custom)
### **How to Develop**<a name="section2120976727162135"></a> The update package is generated in other ways instead of following the instructions provided in "Generating a Public/Private Key Pair" and "Generating an Update Package."
1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module.
2. Call the **HotaSetPackageType** function to set the package type to **NOT\_USE\_DEFAULT\_PKG**. ###### How to Develop
3. Call the **HotaWrite** function to write data streams into the device. 1. Download the update package for the current device, and then call the **HotaInit** function to initialize the OTA module.
4. Call the **HotaRead** function to read data. Vendors can choose whether to verify the data. 2. Call the **HotaSetPackageType** function to set the package type to **NOT\_USE\_DEFAULT\_PKG**.
5. \(Optional\) Call the **HotaSetBootSettings** function to set the startup tag used for entering the U-Boot mode during system restarting. 3. Call the **HotaWrite** function to write data streams into the device.
6. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update. 4. Call the **HotaRead** function to read data. Vendors can choose whether to verify the data.
5. (Optional) Call the **HotaSetBootSettings** function to set the startup tag used for entering the U-Boot mode during system restarting.
### **Sample Code**<a name="section1743369672162135"></a> 6. Call the **HotaRestart** function to restart the system for the update to take effect. Call the **HotaCancel** function if you want to cancel the update.
Perform an OTA update using the update package format and verification method not provided by OpenHarmony.
``` ###### Sample Code
Perform an OTA update using the update package format and verification method not provided by OpenHarmony.
```cpp
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
printf("this is update print!\r\n"); printf("this is update print!\r\n");
...@@ -512,7 +463,7 @@ int main(int argc, char **argv) ...@@ -512,7 +463,7 @@ int main(int argc, char **argv)
while (leftLen > 0) { while (leftLen > 0) {
int tmpLen = leftLen >= READ_BUF_LEN ? READ_BUF_LEN : leftLen; int tmpLen = leftLen >= READ_BUF_LEN ? READ_BUF_LEN : leftLen;
(void)memset_s(g_readBuf, READ_BUF_LEN, 0, READ_BUF_LEN); (void)memset_s(g_readBuf, READ_BUF_LEN, 0, READ_BUF_LEN);
if (HotaRead(offset, READ_BUF_LEN, (unsigned char *)g_readBuf) != 0) {} if (HotaRead(offset, READ_BUF_LEN, (unsigned char *)g_readBuf) != 0) {
printf("ota write fail!\r\n"); printf("ota write fail!\r\n");
(void)HotaCancel(); (void)HotaCancel();
return -1; return -1;
...@@ -530,15 +481,16 @@ int main(int argc, char **argv) ...@@ -530,15 +481,16 @@ int main(int argc, char **argv)
} }
``` ```
## Upgrading the System<a name="section1704276175162135"></a>
Vendor applications call APIs of the OTA module to perform functions such as signature verification of the update package, anti-rollback, burning and data flushing-to-disk. After the update is complete, the system automatically restarts. ###### System Updating
For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 open source suite, add the value of **LOCAL\_VERSION** to the version that needs to implement the anti-rollback function. For example, for **"ohos default 1.0"-\>"ohos default 1.1"**, add the value of **LOCAL\_VERSION** in **device\\hisilicon\\third\_party\\uboot\\u-boot-2020.01\\product\\hiupdate\\ota\_update\\ota\_local\_info.c**. An application calls APIs of the OTA module to perform functions such as signature verification of the update package, anti-rollback, as well as burning and flushing to disk. After the update is complete, the system automatically restarts.
Example for modification of the local version: For the mini and small systems that use the Hi3518E V300 or Hi3516D V300 open source suite, add the value of **LOCAL\_VERSION** to the version that needs to implement the anti-rollback function. For example, for **"ohos default 1.0"-&gt;"ohos default 1.1"**, add the value of **LOCAL\_VERSION** in **device\hisilicon\third\_party\uboot\u-boot-2020.01\product\hiupdate\ota\_update\ota\_local_info.c**.
``` Example configuration:
```cpp
const char *get_local_version(void) const char *get_local_version(void)
{ {
#if defined(CONFIG_TARGET_HI3516EV200) || \ #if defined(CONFIG_TARGET_HI3516EV200) || \
...@@ -547,3 +499,88 @@ const char *get_local_version(void) ...@@ -547,3 +499,88 @@ const char *get_local_version(void)
#define LOCAL_VERSION "ohos default 1.0" /* increase: default release version */ #define LOCAL_VERSION "ohos default 1.0" /* increase: default release version */
``` ```
##### A/B Update Scenario
###### Development Procedure
1. Download the update package through the update application.
2. Invoke update_service to start the system installation service through SAMGR.
3. Let the system installation service perform a silent update.
4. Activate the new version upon restarting.
###### How to Develop
- Invoke update_service to call JS APIs to implement the related service logic in an A/B update.
1. Displaying the update package installation progress:
```cpp
on(eventType: "upgradeProgress", callback: UpdateProgressCallback): void;
```
2. Setting the activation policy (immediate restart, restart at night, and activation on next restart):
```cpp
upgrade(apply)
```
- Invoke update_service to start the system installation service through SAMGR.
1. Start the system installation service and set up an IPC connection.
```cpp
int SysInstallerInit(void * callback)
```
2. Install the A/B update package in the specified path.
```cpp
int StartUpdatePackageZip(string path)
```
3. Set the update progress callback.
```cpp
int SetUpdateProgressCallback(void * callback)
```
4. Obtain the installation status of the update package (0: not started; 1: installing; 2: installed).
```cpp
int GetUpdateStatus()
```
- Use HDI APIs to activate the new version.
1. Obtain the current boot slot to determine the partition to be updated.
```cpp
int GetCurrentSlot()
```
2. Upon completion of the update, switch the updated slot and restart the system for the new version to take effect.
```cpp
int SetActiveBootSlot(int slot)
```
3. Upon starting of the update, set the slot of the partition to be updated to the **unbootable** state.
```cpp
int setSlotUnbootable(int slot)
```
4. Obtain the number of slots. The value **1** indicates a common update, and the value **2** indicates an A/B update.
```cpp
int32 GetSlotNum(void)
```
###### FAQs
1. An exception occurs during installation of the update package.
<br>The system keeps running with the current version. It will attempt a new update in the next package search period.
2. An exception occurs during activation of the new version if the update package is installed in a non-boot partition.
<br>Perform a rollback and set the partition to the **unbootable** state so that the system does not boot from this partition.
###### Verification
In normal cases, the device can download the update package from the OTA server in the background, perform a silent update, and then restart according to the preconfigured activation policy for the new version to take effect.
...@@ -412,7 +412,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI ...@@ -412,7 +412,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI
[ai_engine](https://gitee.com/openharmony/ai_engine) [ai_engine](https://gitee.com/openharmony/ai_engine)
Dependency repositories: ## Dependency Repositories
[build\_lite](https://gitee.com/openharmony/build_lite/blob/master/README.md) [build\_lite](https://gitee.com/openharmony/build_lite/blob/master/README.md)
...@@ -422,6 +422,6 @@ Dependency repositories: ...@@ -422,6 +422,6 @@ Dependency repositories:
## Reference ## Reference
[AI Framework Development](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md) [AI Framework Development Guide](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md)
# 应用测试 # 应用测试
- 自动化测试框架 - [自动化测试框架使用指导](arkxtest-guidelines.md)
- [自动化测试框架使用指导](arkxtest-guidelines.md) - [SmartPerf性能工具使用指导](smartperf-guidelines.md)
- SmartPerf性能工具 - [wukong稳定性工具使用指导](wukong-guidelines.md)
- [SmartPerf性能工具使用指导](smartperf-guidelines.md)
- wukong稳定性工具
- [wukong稳定性工具使用指导](wukong-guidelines.md)
...@@ -2,112 +2,105 @@ ...@@ -2,112 +2,105 @@
## 场景介绍 ## 场景介绍
NativeWindow是`OpenHarmony`**本地平台化窗口**包括从`Surface`构建`NativeWindow`,从`SurfaceBuffer`构建出`NativeWindowBuffer`的能力,开发者可以通过`NativeWindow`接口进行申请和提交`Buffer` NativeWindow是`OpenHarmony`**本地平台化窗口**表示图形队列的生产者端。接口能力包括从`Surface`构建`NativeWindow`的能力,从`SurfaceBuffer`构建出`NativeWindowBuffer`的能力,开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`
针对NativeWindow,常见的开发场景如下: 针对NativeWindow,常见的开发场景如下:
* 通过`Native C++`代码绘制内容并显示在屏幕上 * 通过`NativeWindow`提供的`NAPI`接口申请图形`Buffer`,并将生产图形内容写入图形`Buffer`,最终提交`Buffer`到图形队列
* 在适配EGL层的`eglswapbuffer`接口时,进行提交和申请`Buffer` * 在适配EGL层的`eglswapbuffer`接口时,进行申请和提交`Buffer`
## 接口说明 ## 接口说明
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| OH_NativeWindow_CreateNativeWindowFromSurface (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例。 | | OH_NativeWindow_CreateNativeWindowFromSurface (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例。 |
| OH_NativeWindow_DestroyNativeWindow (struct NativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉。 | | OH_NativeWindow_DestroyNativeWindow (OHNativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉。 |
| OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例。 | | OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例。 |
| OH_NativeWindow_DestroyNativeWindowBuffer (struct NativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉。 | | OH_NativeWindow_DestroyNativeWindowBuffer (OHNativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉。 |
| OH_NativeWindow_NativeWindowRequestBuffer (struct NativeWindow \*window struct NativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产。 | | OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产。 |
| OH_NativeWindow_NativeWindowFlushBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer, int fenceFd, Region region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费。 | | OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, Region region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费。 |
| OH_NativeWindow_NativeWindowCancelBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请。 | | OH_NativeWindow_NativeWindowAbortBuffer (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请。 |
| OH_NativeWindow_NativeWindowHandleOpt (struct NativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等。 | | OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等。 |
| OH_NativeWindow_GetBufferHandleFromNative (struct NativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针。 | | OH_NativeWindow_GetBufferHandleFromNative (OHNativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针。 |
| OH_NativeWindow_NativeObjectReference (void \*obj) | 增加一个NativeObject的引用计数。 | | OH_NativeWindow_NativeObjectReference (void \*obj) | 增加一个NativeObject的引用计数。 |
| OH_NativeWindow_NativeObjectUnreference (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉。 | | OH_NativeWindow_NativeObjectUnreference (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉。 |
| OH_NativeWindow_GetNativeObjectMagic (void \*obj) | 获取NativeObject的MagicId。 | | OH_NativeWindow_GetNativeObjectMagic (void \*obj) | 获取NativeObject的MagicId。 |
| OH_NativeWindow_NativeWindowSetScalingMode (OHNativeWindow \*window, uint32_t sequence, OHScalingMode scalingMode) | 设置NativeWindow的缩放模式。 |
| OH_NativeWindow_NativeWindowSetMetaData(OHNativeWindow \*window, uint32_t sequence, int32_t size, const OHHDRMetaData \*metaData) | 设置NativeWindow的HDR静态元数据。 |
| OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow \*window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t \*metaData) | 设置NativeWindow的HDR静态元数据集。 |
| OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow \*window, const OHExtDataHandle \*handle) | 设置NativeWindow的TunnelHandle。 |
详细的接口说明请参考[native_window](../reference/native-apis/_native_window.md) 详细的接口说明请参考[native_window](../reference/native-apis/_native_window.md)
## 开发步骤 ## 开发步骤
以下步骤描述了在**OpenHarmony**中如何利用`OH_NativeXComponent`通过`Native C++`代码绘制内容并显示在屏幕上 以下步骤描述了在**OpenHarmony**中如何使用`NativeWindow`提供的`NAPI`接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列
1. **在页面中定义XComponent组件**,在`index.ets`中定义一个`texture`类型的`XComponent`,用于显示内容。 1. **获取NativeWindow实例**。例如,使用`Surface`创建`NativeWindow`实例。
```js ```c++
XComponent({ id: 'xcomponentId', type: 'texture', libraryname: 'nativerender'}) sptr<OHOS::Surface> cSurface = Surface::CreateSurfaceAsConsumer();
.borderColor(Color.Red) sptr<IBufferConsumerListener> listener = new BufferConsumerListenerTest();
.borderWidth(5) cSurface->RegisterConsumerListener(listener);
.onLoad(() => {}) sptr<OHOS::IBufferProducer> producer = cSurface->GetProducer();
.onDestroy(() => {}) sptr<OHOS::Surface> pSurface = Surface::CreateSurfaceAsProducer(producer);
``` OHNativeWindow* nativeWindow = OH_NativeWindow_CreateNativeWindow(&pSurface);
```
2. **获取OH_NativeXComponent实例**。使用 `napi_get_named_property` 接口获取一个`OH_NativeXComponent`实例 `nativeXComponent`,通过注册该实例的回调接口获取`NativeWindow`实例。
2. **设置NativeWindowBuffer的属性**。使用`OH_NativeWindow_NativeWindowHandleOpt`设置`NativeWindowBuffer`的属性。
```c++ ```c++
// 定义 napi instance // 设置 NativeWindowBuffer 的读写场景
napi_value exportInstance = nullptr; int code = SET_USAGE;
// 定义一个 OH_NativeXComponent 实例 int32_t usage = BUFFER_USAGE_CPU_READ | BUFFER_USAGE_CPU_WRITE | BUFFER_USAGE_MEM_DMA;
OH_NativeXComponent *nativeXComponent = nullptr; int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, usage);
// 通过 OH_NATIVE_XCOMPONENT_OBJ export 实例 // 设置 NativeWindowBuffer 的宽高
napi_getname_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); code = SET_BUFFER_GEOMETRY;
// 将 napi instance 转化为 OH_NativeXComponent 实例 int32_t width = 0x100;
napi_unwarp(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent)); int32_t height = 0x100;
ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, width, height);
// 设置 NativeWindowBuffer 的步长
code = SET_STRIDE;
int32_t stride = 0x8;
ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, stride);
// 设置 NativeWindowBuffer 的格式
code = SET_FORMAT;
int32_t format = PIXEL_FMT_RGBA_8888;
ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, code, format);
``` ```
3. **定义回调函数OnSurfaceCreated**。用于在`Surface`创建时,通过回调函数初始化开发者的渲染环境,例如`Skia`渲染环境。并将要显示的内容写入`NativeWindow` 3. **从图形队列申请NativeWindowBuffer**
```c++
struct NativeWindowBuffer* buffer = nullptr;
int fenceFd;
// 通过 OH_NativeWindow_NativeWindowRequestBuffer 获取 NativeWindowBuffer 实例
OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd);
// 通过 OH_NativeWindow_GetNativeBufferHandleFromNative 获取 buffer 的 handle
BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer);
```
4. **将生产的内容写入NativeWindowBuffer**
```c++ ```c++
void OnSurfaceCreatedCB(NativeXComponent* component, void* window) { auto image = static_cast<uint8_t *>(buffer->sfbuffer->GetVirAddr());
//获取 native window 的宽高 static uint32_t value = 0x00;
uint64_t width_ = 0, height_ = 0; value++;
OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_);
// 将void* 转换为 NativeWindow 实例,NativeWindow 定义在 native_window/external_window.h 中 uint32_t *pixel = static_cast<uint32_t *>(image);
NativeWindow* nativeWindow_ = (NativeWindow*)(window); for (uint32_t x = 0; x < width; x++) {
for (uint32_t y = 0; y < height; y++) {
// 通过 OH_NativeWindow_NativeWindowHandleOpt 设置或者获取NativeWindow的属性 *pixel++ = value;
// 1.通过 SET_USAGE 设置 Native Window 的 usage 属性, 例如:HBM_USE_CPU_READ }
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_USAGE, HBM_USE_CPU_READ | HBM_USE_CPU_WRITE |HBM_USE_MEM_DMA);
// 2.通过 SET_BUFFER_GEOMETRY 设置 Native Window 的 宽高属性
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_BUFFER_GEOMETRY, width_, height_);
// 3.通过 SET_FORMAT 设置 Native Window 的 format 属性, 例如:PIXEL_FMT_RGBA_8888
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_FORMAT, PIXEL_FMT_RGBA_8888);
// 4.通过 SET_STRIDE 设置 Native Window 的 stride 属性
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_STRIDE, 0x8);
// 通过 OH_NativeWindow_NativeWindowRequestBuffer 获取 NativeWindowBuffer 实例
struct NativeWindowBuffer* buffer = nullptr;
int fenceFd;
OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd);
// 通过 OH_NativeWindow_GetNativeBufferHandleFromNative 获取 buffer handle
BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer);
// 通过 BufferHandle 创建Skia Bitmap
SkBitmap bitmap;
SkImageInfo imageInfo = ...
bitmap.setInfo(imageInfo, bufferHandle->stride);
bitmap.setPixels(bufferHandle->virAddr);
//创建 Skia Canvas 并将内容写入native window
...
//写入完成后,通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上
Region region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region)
} }
``` ```
4. **注册回调函数OnSurfaceCreated等**。使用 `OH_NativeXComponent_RegisterCallback` 接口注册上一步中创建的回调函数 5. **提交NativeWindowBuffer到图形队列**
```c++ ```c++
OH_NativeXComponent_Callback &callback_; // 设置刷新区域,如果Region中的Rect为nullptr,或者rectNumber为0,则认为NativeWindowBuffer全部有内容更改。
callback_->OnSurfaceCreated = OnSurfaceCreatedCB; Region region{nullptr, 0};
callback_->OnSurfaceChanged = OnSurfaceChangedCB; // 通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上。
callback_->OnSurfaceDestroyed = OnSurfaceDestroyedCB; OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region);
callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
``` ```
## 相关实例 ## 相关实例
针对NativeWindow的使用,有以下相关实例可供参考: 针对NativeWindow的使用,有以下相关实例可供参考:
- [使用NativeWindow接口获取Buffer](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/hello_native_window/hello_native_window.cpp) - [使用NativeWindow接口获取并提交Buffer](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/hello_native_window/hello_native_window.cpp)
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
- [SysCap说明](syscap.md) - [SysCap说明](syscap.md)
- [HarmonyAppProvision配置文件](app-provision-structure.md) - [HarmonyAppProvision配置文件](app-provision-structure.md)
- [资源分类与访问](resource-categories-and-access.md)
- 学习ArkTS语言 - 学习ArkTS语言
- [初识ArkTS语言](arkts-get-started.md) - [初识ArkTS语言](arkts-get-started.md)
- ArkTS语法(声明式UI) - ArkTS语法(声明式UI)
......
...@@ -22,7 +22,8 @@ struct CompB { ...@@ -22,7 +22,8 @@ struct CompB {
build() { build() {
Column() { Column() {
Button(this.CompValue); Button(this.CompValue)
.margin(5)
} }
} }
} }
...@@ -81,6 +82,8 @@ struct CompA { ...@@ -81,6 +82,8 @@ struct CompA {
} }
} }
``` ```
![builder](figures/builder.PNG)
## @BuilderParam<sup>8+<sup> ## @BuilderParam<sup>8+<sup>
@BuilderParam装饰器用于修饰自定义组件内函数类型的属性(例如:`@BuilderParam noParam: () => void`),并且在初始化自定义组件时被@BuilderParam修饰的属性必须赋值。 @BuilderParam装饰器用于修饰自定义组件内函数类型的属性(例如:`@BuilderParam noParam: () => void`),并且在初始化自定义组件时被@BuilderParam修饰的属性必须赋值。
...@@ -151,6 +154,8 @@ struct CustomContainerUser { ...@@ -151,6 +154,8 @@ struct CustomContainerUser {
} }
``` ```
![builder1](figures/builder1.PNG)
### 尾随闭包初始化组件 ### 尾随闭包初始化组件
在自定义组件中使用@BuilderParam修饰的属性时也可通过尾随闭包进行初始化(在初始化自定义组件时,组件后紧跟一个大括号“{}”形成尾随闭包场景(`CustomContainer(){}`)。开发者可把尾随闭包看做一个容器,向其中填充内容,如在闭包内增加组件(`{Column(){...}`),闭包内语法规范与build函数一致。此场景下自定义组件内有且仅有一个使用@BuilderParam修饰的属性。 在自定义组件中使用@BuilderParam修饰的属性时也可通过尾随闭包进行初始化(在初始化自定义组件时,组件后紧跟一个大括号“{}”形成尾随闭包场景(`CustomContainer(){}`)。开发者可把尾随闭包看做一个容器,向其中填充内容,如在闭包内增加组件(`{Column(){...}`),闭包内语法规范与build函数一致。此场景下自定义组件内有且仅有一个使用@BuilderParam修饰的属性。
...@@ -204,6 +209,8 @@ struct CustomContainerUser { ...@@ -204,6 +209,8 @@ struct CustomContainerUser {
} }
``` ```
![builder2](figures/builder2.gif)
## @Styles ## @Styles
ArkTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多个样式设置提炼成一个方法,直接在组件声明时调用,通过@Styles装饰器可以快速定义并复用自定义样式。当前@Styles仅支持通用属性。 ArkTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多个样式设置提炼成一个方法,直接在组件声明时调用,通过@Styles装饰器可以快速定义并复用自定义样式。当前@Styles仅支持通用属性。
...@@ -246,6 +253,8 @@ struct FancyUse { ...@@ -246,6 +253,8 @@ struct FancyUse {
} }
``` ```
![styles](figures/styles.PNG)
@Styles还可以在[StateStyles](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)属性内部使用,在组件处于不同的状态时赋予相应的属性。 @Styles还可以在[StateStyles](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)属性内部使用,在组件处于不同的状态时赋予相应的属性。
在StateStyles内可以直接调用组件外定义的@Styles方法,但需要通过this关键字调用组件内定义的@Styles方法。 在StateStyles内可以直接调用组件外定义的@Styles方法,但需要通过this关键字调用组件内定义的@Styles方法。
...@@ -284,6 +293,8 @@ struct FancyUse { ...@@ -284,6 +293,8 @@ struct FancyUse {
} }
``` ```
![styles1](figures/styles1.gif)
## @Extend ## @Extend
@Extend装饰器将新的属性方法添加到Text、Column、Button等内置组件上,通过@Extend装饰器可以快速地扩展原生组件。@Extend不能定义在自定义组件struct内。 @Extend装饰器将新的属性方法添加到Text、Column、Button等内置组件上,通过@Extend装饰器可以快速地扩展原生组件。@Extend不能定义在自定义组件struct内。
...@@ -319,6 +330,8 @@ struct FancyUse { ...@@ -319,6 +330,8 @@ struct FancyUse {
> - @Extend装饰器不能定义在自定义组件struct内。 > - @Extend装饰器不能定义在自定义组件struct内。
> - @Extend装饰器内仅支持属性方法设置。 > - @Extend装饰器内仅支持属性方法设置。
![extend](figures/extend.PNG)
## @CustomDialog ## @CustomDialog
@CustomDialog装饰器用于装饰自定义弹窗组件,使得弹窗可以动态设置内容及样式。 @CustomDialog装饰器用于装饰自定义弹窗组件,使得弹窗可以动态设置内容及样式。
...@@ -369,4 +382,4 @@ struct CustomDialogUser { ...@@ -369,4 +382,4 @@ struct CustomDialogUser {
} }
``` ```
![custom-dialog-demo](figures/custom-dialog-demo.gif) ![customdialog](figures/customdialog.gif)
\ No newline at end of file \ No newline at end of file
...@@ -91,6 +91,8 @@ struct MyComponent { ...@@ -91,6 +91,8 @@ struct MyComponent {
} }
``` ```
![forEach1](figures/forEach1.gif)
## 数据懒加载 ## 数据懒加载
通过数据懒加载(LazyForEach)从提供的数据源中按需迭代数据,并在每次迭代过程中创建相应的组件。 通过数据懒加载(LazyForEach)从提供的数据源中按需迭代数据,并在每次迭代过程中创建相应的组件。
...@@ -212,7 +214,7 @@ class BasicDataSource implements IDataSource { ...@@ -212,7 +214,7 @@ class BasicDataSource implements IDataSource {
class MyDataSource extends BasicDataSource { class MyDataSource extends BasicDataSource {
// 初始化数据列表 // 初始化数据列表
private dataArray: string[] = ['/path/image0', '/path/image1', '/path/image2', '/path/image3'] private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png']
public totalCount(): number { public totalCount(): number {
return this.dataArray.length return this.dataArray.length
...@@ -249,7 +251,7 @@ struct MyComponent { ...@@ -249,7 +251,7 @@ struct MyComponent {
} }
.onClick(() => { .onClick(() => {
// 每点击一次列表项,数据增加一项 // 每点击一次列表项,数据增加一项
this.data.pushData('/path/image' + this.data.totalCount()) this.data.pushData('/path/image' + this.data.totalCount() + '.png')
}) })
}, item => item) }, item => item)
} }
...@@ -275,4 +277,6 @@ struct MyComponent { ...@@ -275,4 +277,6 @@ struct MyComponent {
> LazyForEach(dataSource, > LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)), > item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString()) > item => item.data.id.toString())
> ``` > ```
\ No newline at end of file
![lazyForEach](figures/lazyForEach.gif)
\ No newline at end of file
...@@ -42,6 +42,8 @@ struct bindPopupPage { ...@@ -42,6 +42,8 @@ struct bindPopupPage {
} }
``` ```
![popup](figures/popup.gif)
## 状态变量数据类型声明使用限制 ## 状态变量数据类型声明使用限制
@State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。 @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
...@@ -68,4 +70,6 @@ struct IndexPage { ...@@ -68,4 +70,6 @@ struct IndexPage {
.height('100%') .height('100%')
} }
} }
``` ```
\ No newline at end of file
![hello](figures/hello.PNG)
\ No newline at end of file
...@@ -80,6 +80,7 @@ struct ComponentA { ...@@ -80,6 +80,7 @@ struct ComponentA {
} }
``` ```
![appstorage](figures/appstorage.gif)
## [LocalStorage](../reference/arkui-ts/ts-state-management.md#localstorage9) ## [LocalStorage](../reference/arkui-ts/ts-state-management.md#localstorage9)
...@@ -188,6 +189,8 @@ struct LocalStorageComponentProp { ...@@ -188,6 +189,8 @@ struct LocalStorageComponentProp {
} }
``` ```
![appstorage1](figures/appstorage1.gif)
### 示例2(在Entry页面定义LocalStorage) ### 示例2(在Entry页面定义LocalStorage)
```ts ```ts
...@@ -223,6 +226,8 @@ struct Child { ...@@ -223,6 +226,8 @@ struct Child {
} }
``` ```
![appstorage2](figures/appstorage2.gif)
## [PersistentStorage](../reference/arkui-ts/ts-state-management.md#persistentstorage) ## [PersistentStorage](../reference/arkui-ts/ts-state-management.md#persistentstorage)
PersistentStorage提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。 PersistentStorage提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。
...@@ -260,6 +265,8 @@ struct PersistentComponent { ...@@ -260,6 +265,8 @@ struct PersistentComponent {
} }
``` ```
![appstorage3](figures/appstorage3.gif)
## [Environment](../reference/arkui-ts/ts-state-management.md#environment) ## [Environment](../reference/arkui-ts/ts-state-management.md#environment)
Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境,包括系统语言、深浅色模式等等。Environment及其属性是不可变的,所有数据类型均为简单类型。如下示例展示了从Environment获取系统是否开启无障碍屏幕朗读: Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境,包括系统语言、深浅色模式等等。Environment及其属性是不可变的,所有数据类型均为简单类型。如下示例展示了从Environment获取系统是否开启无障碍屏幕朗读:
......
# 资源文件的分类 # 资源分类与访问
## 资源分类
应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。 应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。
## resources目录 ### resources目录
应用的资源文件(字符串、图片、音频等)统一存放于resources目录下,便于开发者使用和维护。resources目录包括两大类目录,一类为base目录与限定词目录,另一类为rawfile目录,详见resources目录分类,stage模型多工程情况下共有的资源文件放到AppScope下的resources目录。 resources目录包括三大类目录,一类为base目录,一类为限定词目录,还有一类为rawfile目录。stage模型多工程情况下共有的资源文件放到AppScope下的resources目录。
资源目录示例: 资源目录示例:
...@@ -23,7 +25,7 @@ resources ...@@ -23,7 +25,7 @@ resources
|---rawfile |---rawfile
``` ```
**表1** resources目录分类 **表1** resources目录分类
| 分类 | base目录 | 限定词目录 | rawfile目录 | | 分类 | base目录 | 限定词目录 | rawfile目录 |
| ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
...@@ -32,15 +34,15 @@ resources ...@@ -32,15 +34,15 @@ resources
| 引用方式 | 通过指定资源类型(type)和资源名称(name)来引用。 | 通过指定资源类型(type)和资源名称(name)来引用。 | 通过指定文件路径和文件名来引用。 | | 引用方式 | 通过指定资源类型(type)和资源名称(name)来引用。 | 通过指定资源类型(type)和资源名称(name)来引用。 | 通过指定文件路径和文件名来引用。 |
## 限定词目录 ### 限定词目录
限定词目录可以由一个或多个表征应用场景或设备特征的限定词组合而成,包括移动国家码和移动网络码、语言、文字、国家或地区、横竖屏、设备类型、颜色模式和屏幕密度等维度,限定词之间通过下划线(_)或者中划线(-)连接。开发者在创建限定词目录时,需要掌握限定词目录的命名要求,以及限定词目录与设备状态的匹配规则。 限定词目录可以由一个或多个表征应用场景或设备特征的限定词组合而成,包括移动国家码和移动网络码、语言、文字、国家或地区、横竖屏、设备类型、颜色模式和屏幕密度等维度,限定词之间通过下划线(\_)或者中划线(\-)连接。开发者在创建限定词目录时,需要掌握限定词目录的命名要求,以及限定词目录与设备状态的匹配规则。
**限定词目录的命名要求** **限定词目录的命名要求**
- 限定词的组合顺序:_移动国家码_移动网络码-语言_文字_国家或地区-横竖屏-设备类型-颜色模式-屏幕密度_。开发者可以根据应用的使用场景和设备特征,选择其中的一类或几类限定词组成目录名称。 - 限定词的组合顺序:\_移动国家码_移动网络码-语言_文字_国家或地区-横竖屏-设备类型-颜色模式-屏幕密度_。开发者可以根据应用的使用场景和设备特征,选择其中的一类或几类限定词组成目录名称。
- 限定词的连接方式:语言、文字、国家或地区之间采用下划线(_)连接,移动国家码和移动网络码之间也采用下划线(_)连接,除此之外的其他限定词之间均采用中划线(-)连接。例如:**zh_Hant_CN****zh_CN-car-ldpi** - 限定词的连接方式:语言、文字、国家或地区之间采用下划线(\_)连接,移动国家码和移动网络码之间也采用下划线(\_)连接,除此之外的其他限定词之间均采用中划线(-)连接。例如:**zh_Hant_CN****zh_CN-car-ldpi**
- 限定词的取值范围:每类限定词的取值必须符合限定词取值要求表中的条件,否则,将无法匹配目录中的资源文件。 - 限定词的取值范围:每类限定词的取值必须符合限定词取值要求表中的条件,否则,将无法匹配目录中的资源文件。
...@@ -64,9 +66,9 @@ resources ...@@ -64,9 +66,9 @@ resources
- 如果限定词目录中包含**移动国家码和移动网络码、语言、文字、横竖屏、设备类型、颜色模式**限定词,则对应限定词的取值必须与当前的设备状态完全一致,该目录才能够参与设备的资源匹配。例如,限定词目录“zh_CN-car-ldpi”不能参与“en_US”设备的资源匹配。 - 如果限定词目录中包含**移动国家码和移动网络码、语言、文字、横竖屏、设备类型、颜色模式**限定词,则对应限定词的取值必须与当前的设备状态完全一致,该目录才能够参与设备的资源匹配。例如,限定词目录“zh_CN-car-ldpi”不能参与“en_US”设备的资源匹配。
## 资源组目录 ### 资源组目录
base目录与限定词目录下面可以创建资源组目录(包括element、media、animation、layout、graphic、profile),用于存放特定类型的资源文件,详见资源组目录说明。 base目录与限定词目录下面可以创建资源组目录(包括element、media、profile),用于存放特定类型的资源文件,详见资源组目录说明。
**表3** 资源组目录说明 **表3** 资源组目录说明
...@@ -77,9 +79,9 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 ...@@ -77,9 +79,9 @@ base目录与限定词目录下面可以创建资源组目录(包括element、
| media | 表示媒体资源,包括图片、音频、视频等非文本格式的文件。 | 文件名可自定义,例如:icon.png。 | | media | 表示媒体资源,包括图片、音频、视频等非文本格式的文件。 | 文件名可自定义,例如:icon.png。 |
| rawfile | 表示其他类型文件,在应用构建为hap包后,以原始文件形式保存,不会被集成到resources.index文件中。 | 文件名可自定义。 | | rawfile | 表示其他类型文件,在应用构建为hap包后,以原始文件形式保存,不会被集成到resources.index文件中。 | 文件名可自定义。 |
### 媒体资源类型说明 **媒体资源类型说明**
表1 图片资源类型说明 **表4** 图片资源类型说明
| 格式 | 文件后缀名 | | 格式 | 文件后缀名 |
| ---- | ----- | | ---- | ----- |
...@@ -90,7 +92,7 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 ...@@ -90,7 +92,7 @@ base目录与限定词目录下面可以创建资源组目录(包括element、
| WEBP | .webp | | WEBP | .webp |
| BMP | .bmp | | BMP | .bmp |
表2 音视频资源类型说明 **表5** 音视频资源类型说明
| 格式 | 支持的文件类型 | | 格式 | 支持的文件类型 |
| ------------------------------------ | --------------- | | ------------------------------------ | --------------- |
...@@ -99,7 +101,94 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 ...@@ -99,7 +101,94 @@ base目录与限定词目录下面可以创建资源组目录(包括element、
| MPEG-4 SP | .3gp | | MPEG-4 SP | .3gp |
| VP8 | .webm <br> .mkv | | VP8 | .webm <br> .mkv |
## 创建资源文件 **资源文件示例**
color.json文件的内容如下:
```json
{
"color": [
{
"name": "color_hello",
"value": "#ffff0000"
},
{
"name": "color_world",
"value": "#ff0000ff"
}
]
}
```
float.json文件的内容如下:
```json
{
"float":[
{
"name":"font_hello",
"value":"28.0fp"
},
{
"name":"font_world",
"value":"20.0fp"
}
]
}
```
string.json文件的内容如下:
```json
{
"string":[
{
"name":"string_hello",
"value":"Hello"
},
{
"name":"string_world",
"value":"World"
},
{
"name":"message_arrive",
"value":"We will arrive at %s."
}
]
}
```
plural.json文件的内容如下:
```json
{
"plural":[
{
"name":"eat_apple",
"value":[
{
"quantity":"one",
"value":"%d apple"
},
{
"quantity":"other",
"value":"%d apples"
}
]
}
]
}
```
## 资源访问
### 应用资源
**创建资源文件**
在resources目录下,可按照限定词目录和资源组目录的说明创建子目录和目录内的文件。 在resources目录下,可按照限定词目录和资源组目录的说明创建子目录和目录内的文件。
...@@ -129,4 +218,72 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 ...@@ -129,4 +218,72 @@ base目录与限定词目录下面可以创建资源组目录(包括element、
例如,在element目录下可新建Element Resource File。 例如,在element目录下可新建Element Resource File。
![create-resource-file-3](figures/create-resource-file-3.png) ![create-resource-file-3](figures/create-resource-file-3.png)
\ No newline at end of file
**访问应用资源**
在工程中,通过```"$r('app.type.name')"```的形式引用应用资源。app代表是应用内resources目录中定义的资源;type代表资源类型(或资源的存放位置),可以取“color”、“float”、“string”、“plural”、“media”,name代表资源命名,由开发者定义资源时确定。
引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。
> **说明:**
>
> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。
>
> `$r`返回值为Resource对象,可通过[getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) 方法获取对应的字符串。
在xxx.ets文件中,可以使用在resources目录中定义的资源。
```ts
Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Text($r('app.string.message_arrive', "five of the clock")) // 引用string资源,$r的第二个参数用于替换%s
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.plural.eat_apple', 5, 5)) // plural$r引用,第一个指定plural资源,第二个参数指定单复数的数量,此处第三个数字为对%d的替换
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Image($r('app.media.my_background_image')) // media资源的$r引用
Image($rawfile('test.png')) // rawfile$r引用rawfile目录下图片
Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下图片
```
### 系统资源
系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。
开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。
```ts
Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon'))
.border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2})
.margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')})
.height(200)
.width(300)
```
## 相关实例
针对访问应用资源,有以下相关实例可供参考:
- [`ResourceManager`:资源管理器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager)
...@@ -54,7 +54,7 @@ ...@@ -54,7 +54,7 @@
1. 使用文本组件。 1. 使用文本组件。
工程同步完成后,在“**Project**”窗口,点击“**entry &gt; src &gt; main &gt; ets &gt; MainAbility &gt; pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下: 工程同步完成后,在“**Project**”窗口,点击“**entry &gt; src &gt; main &gt; ets &gt; pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下:
```ts ```ts
// index.ets // index.ets
......
...@@ -195,7 +195,7 @@ ...@@ -195,7 +195,7 @@
- [@ohos.hiAppEvent (应用打点)](js-apis-hiappevent.md) - [@ohos.hiAppEvent (应用打点)](js-apis-hiappevent.md)
- [@ohos.hichecker (检测模式)](js-apis-hichecker.md) - [@ohos.hichecker (检测模式)](js-apis-hichecker.md)
- [@ohos.hidebug (Debug调试)](js-apis-hidebug.md) - [@ohos.hidebug (Debug调试)](js-apis-hidebug.md)
- [@ohos.hilog (日志打印)](js-apis-hilog.md) - [@ohos.hilog (HiLog日志打印)](js-apis-hilog.md)
- [@ohos.hiSysEvent (系统事件打点)](js-apis-hisysevent.md) - [@ohos.hiSysEvent (系统事件打点)](js-apis-hisysevent.md)
- [@ohos.hiTraceChain (分布式跟踪)](js-apis-hitracechain.md) - [@ohos.hiTraceChain (分布式跟踪)](js-apis-hitracechain.md)
- [@ohos.hiTraceMeter (性能打点)](js-apis-hitracemeter.md) - [@ohos.hiTraceMeter (性能打点)](js-apis-hitracemeter.md)
...@@ -209,6 +209,7 @@ ...@@ -209,6 +209,7 @@
- [@ohos.systemTimer(系统定时器)](js-apis-system-timer.md) - [@ohos.systemTimer(系统定时器)](js-apis-system-timer.md)
- [@ohos.wallpaper (壁纸)](js-apis-wallpaper.md) - [@ohos.wallpaper (壁纸)](js-apis-wallpaper.md)
- [@ohos.web.webview(Web)](js-apis-webview.md) - [@ohos.web.webview(Web)](js-apis-webview.md)
- [console (日志打印)](js-apis-logs.md)
- [Timer (定时器)](js-apis-timer.md) - [Timer (定时器)](js-apis-timer.md)
- 设备管理 - 设备管理
...@@ -235,7 +236,7 @@ ...@@ -235,7 +236,7 @@
- [@ohos.systemParameter (系统属性)](js-apis-system-parameter.md) - [@ohos.systemParameter (系统属性)](js-apis-system-parameter.md)
- [@ohos.thermal (热管理)](js-apis-thermal.md) - [@ohos.thermal (热管理)](js-apis-thermal.md)
- [@ohos.update (升级)](js-apis-update.md) - [@ohos.update (升级)](js-apis-update.md)
- [@ohos.usb (USB管理)](js-apis-usb.md) - [@ohos.usbV9 (USB管理)](js-apis-usb.md)
- [@ohos.vibrator (振动)](js-apis-vibrator.md) - [@ohos.vibrator (振动)](js-apis-vibrator.md)
- 帐号管理 - 帐号管理
- [@ohos.account.appAccount (应用帐号管理)](js-apis-appAccount.md) - [@ohos.account.appAccount (应用帐号管理)](js-apis-appAccount.md)
...@@ -273,6 +274,7 @@ ...@@ -273,6 +274,7 @@
- [@ohos.data.distributedData (分布式数据管理)](js-apis-distributed-data.md) - [@ohos.data.distributedData (分布式数据管理)](js-apis-distributed-data.md)
- [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md)
- [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md)
- [@ohos.usb (USB管理)](js-apis-usb-deprecated.md)
- [@system.app (应用上下文)](js-apis-system-app.md) - [@system.app (应用上下文)](js-apis-system-app.md)
- [@system.battery (电量信息)](js-apis-system-battery.md) - [@system.battery (电量信息)](js-apis-system-battery.md)
- [@system.bluetooth (蓝牙)](js-apis-system-bluetooth.md) - [@system.bluetooth (蓝牙)](js-apis-system-bluetooth.md)
...@@ -292,4 +294,3 @@ ...@@ -292,4 +294,3 @@
- [@system.sensor (传感器)](js-apis-system-sensor.md) - [@system.sensor (传感器)](js-apis-system-sensor.md)
- [@system.storage (数据存储)](js-apis-system-storage.md) - [@system.storage (数据存储)](js-apis-system-storage.md)
- [@system.vibrator (振动)](js-apis-system-vibrate.md) - [@system.vibrator (振动)](js-apis-system-vibrate.md)
- [console (日志打印)](js-apis-logs.md)
...@@ -2596,7 +2596,7 @@ finish(handle: number, options: HuksOptions) : Promise\<HuksResult> ...@@ -2596,7 +2596,7 @@ finish(handle: number, options: HuksOptions) : Promise\<HuksResult>
finish操作密钥接口,使用Promise方式异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。 finish操作密钥接口,使用Promise方式异步返回结果。huks.init, huks.update, huks.finish为三段式接口,需要一起使用。
> **说明:** 从API Version 9开始废弃,建议使用[huks.updateSession<sup>9+</sup>](#huksfinishsession9-1)替代。 > **说明:** 从API Version 9开始废弃,建议使用[huks.finishSession<sup>9+</sup>](#huksfinishsession9-1)替代。
**系统能力**:SystemCapability.Security.Huks **系统能力**:SystemCapability.Security.Huks
......
...@@ -21,7 +21,7 @@ Rating(options?: { rating: number, indicator?: boolean }) ...@@ -21,7 +21,7 @@ Rating(options?: { rating: number, indicator?: boolean })
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| rating | number | 是 | 设置并接收评分值。<br/>默认值:0 | | rating | number | 是 | 设置并接收评分值。<br/>默认值:0 |
| indicator | boolean | 否 | 仅作为指示器使用,不可操作。<br/>默认值:false | | indicator | boolean | 否 | 设置评分组件作为指示器使用,不可改变评分。<br/>默认值:false, 可进行评分 |
## 属性 ## 属性
......
...@@ -22,8 +22,8 @@ GridContainer(value?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: ...@@ -22,8 +22,8 @@ GridContainer(value?: { columns?: number | 'auto', sizeType?: SizeType, gutter?:
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| columns | number&nbsp;\|&nbsp;'auto' | 否 | 设置当前布局总列数。<br/>默认值:'auto' | | columns | number&nbsp;\|&nbsp;'auto' | 否 | 设置当前布局总列数。<br/>默认值:'auto' |
| sizeType | SizeType | 否 | 选用设备宽度类型。<br/>默认值:SizeType.Auto | | sizeType | SizeType | 否 | 选用设备宽度类型。<br/>默认值:SizeType.Auto |
| gutter | number&nbsp;\|&nbsp;string | 否 | 栅格布局列间距。 | | gutter | number&nbsp;\|&nbsp;string | 否 | 栅格布局列间距,不支持百分比。 |
| margin | number&nbsp;\|&nbsp;string | 否 | 栅格布局两侧间距。 | | margin | number&nbsp;\|&nbsp;string | 否 | 栅格布局两侧间距,不支持百分比。 |
## SizeType枚举说明 ## SizeType枚举说明
......
...@@ -25,7 +25,7 @@ Scroll(scroller?: Scroller) ...@@ -25,7 +25,7 @@ Scroll(scroller?: Scroller)
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| -------------- | ---------------------------------------- | --------- | | -------------- | ---------------------------------------- | --------- |
| scrollable | [ScrollDirection](#scrolldirection枚举说明) | 设置滚动方向。<br/>默认值:ScrollDirection.Vertical | | scrollable | [ScrollDirection](#scrolldirection枚举说明) | 设置滚动方向。<br/>默认值:ScrollDirection.Vertical |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Auto |
| scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 | | scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 |
| scrollBarWidth | string&nbsp;\|&nbsp;number | 设置滚动条的宽度。 | | scrollBarWidth | string&nbsp;\|&nbsp;number | 设置滚动条的宽度。 |
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。<br/>默认值:EdgeEffect.None | | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。<br/>默认值:EdgeEffect.None |
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
| border | {<br/>width?:&nbsp;[Length](ts-types.md#length)&nbsp;\|&nbsp;[EdgeWidths](#edgewidths9对象说明)<sup>9+</sup>,<br/>color?: &nbsp;[ResourceColor](ts-types.md#resourcecolor)&nbsp;\|&nbsp;[EdgeColors](#edgecolors9对象说明)<sup>9+</sup>,<br/>radius?: &nbsp;[Length](ts-types.md#length)&nbsp;\|&nbsp;[BorderRadiuses](#borderradiuses9对象说明)<sup>9+</sup>,<br/>style?:&nbsp;[BorderStyle](ts-appendix-enums.md#borderstyle)&nbsp;\|&nbsp;[EdgeStyles](#edgestyles9对象说明)<sup>9+</sup><br/>} | 统一边框样式设置接口。<br/>-&nbsp;width:设置边框宽度。<br/>-&nbsp;color:设置边框颜色。<br/>-&nbsp;radius:设置边框圆角半径。<br/>-&nbsp;style:设置边框样式。 | | border | {<br/>width?:&nbsp;[Length](ts-types.md#length)&nbsp;\|&nbsp;[EdgeWidths](#edgewidths9对象说明)<sup>9+</sup>,<br/>color?: &nbsp;[ResourceColor](ts-types.md#resourcecolor)&nbsp;\|&nbsp;[EdgeColors](#edgecolors9对象说明)<sup>9+</sup>,<br/>radius?: &nbsp;[Length](ts-types.md#length)&nbsp;\|&nbsp;[BorderRadiuses](#borderradiuses9对象说明)<sup>9+</sup>,<br/>style?:&nbsp;[BorderStyle](ts-appendix-enums.md#borderstyle)&nbsp;\|&nbsp;[EdgeStyles](#edgestyles9对象说明)<sup>9+</sup><br/>} | 统一边框样式设置接口。<br/>-&nbsp;width:设置边框宽度。<br/>-&nbsp;color:设置边框颜色。<br/>-&nbsp;radius:设置边框圆角半径。<br/>-&nbsp;style:设置边框样式。 |
| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)<sup>9+</sup> | 设置元素的边框样式。<br/>默认值:BorderStyle.Solid | | borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](#edgestyles9对象说明)<sup>9+</sup> | 设置元素的边框样式。<br/>默认值:BorderStyle.Solid |
| borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)<sup>9+</sup> | 设置元素的边框宽度,不支持百分比。 | | borderWidth | [Length](ts-types.md#length) \| [EdgeWidths](#edgewidths9对象说明)<sup>9+</sup> | 设置元素的边框宽度,不支持百分比。 |
| borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)<sup>9+</sup> | 设置元素的边框颜色。 | | borderColor | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](#edgecolors9对象说明)<sup>9+</sup> | 设置元素的边框颜色。<br/>默认值:Color.Black |
| borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)<sup>9+</sup> | 设置元素的边框圆角半径,不支持百分比。 | | borderRadius | [Length](ts-types.md#length) \| [BorderRadiuses](#borderradiuses9对象说明)<sup>9+</sup> | 设置元素的边框圆角半径,不支持百分比。 |
## EdgeWidths<sup>9+</sup>对象说明 ## EdgeWidths<sup>9+</sup>对象说明
......
...@@ -2,117 +2,145 @@ ...@@ -2,117 +2,145 @@
## 9200001 应用没有激活成设备管理器 ## 9200001 应用没有激活成设备管理器
### 错误信息 **错误信息**
The application is not a administrator of the device. The application is not a administrator of the device.
### 错误描述 **错误描述**
当应用没有激活成设备管理器时,则会产生此错误码。 当应用没有激活成设备管理器时,则会产生此错误码。
### 可能原因 **可能原因**
应用没有激活设备管理器。 应用没有激活设备管理器。
### 处理步骤 **处理步骤**
请检查调用者是否成功激活过设备管理器,没有激活过的设备管理器的应用无法调用设备管理接口。 请检查调用者是否成功激活过设备管理器,没有激活过的设备管理器的应用无法调用设备管理接口。
## 9200002 设备管理器权限不够 ## 9200002 设备管理器权限不够
### 错误信息 **错误信息**
The administrator application does not have permission to manage the device. The administrator application does not have permission to manage the device.
### 错误描述 **错误描述**
当设备管理器调用高权限接口时,则会产生此错误码。 当设备管理器调用高权限接口时,则会产生此错误码。
### 可能原因 **可能原因**
激活成了DA管理器,调用了SDA管理器接口。 激活成了DA管理器,调用了SDA管理器接口。
### 处理步骤 **处理步骤**
请检查调用者是否存在越权调用,即激活的设备管理器类型和调用的API要求的管理器类型是否一致。 请检查调用者是否存在越权调用,即激活的设备管理器类型和调用的API要求的管理器类型是否一致。
## 9200003 指定的设备管理器元能力组件无效 ## 9200003 指定的设备管理器元能力组件无效
### 错误信息 **错误信息**
The administrator ability component is invalid. The administrator ability component is invalid.
### 错误描述 **错误描述**
当应用传入参数中指定的设备管理器元能力组件无效,则会产生此错误码。 当应用传入参数中指定的设备管理器元能力组件无效,则会产生此错误码。
### 可能原因 **可能原因**
该错误码表示指定的设备管理器元能力组件无效,可能原因如下。 该错误码表示指定的设备管理器元能力组件无效,可能原因如下。
1. 应用激活设备管理器时指定的设备管理器元能力组件不存在。 1. 应用激活设备管理器时指定的设备管理器元能力组件不存在。
2. 设备管理器元能力组件不是合法的企业设备管理元能力组件。 2. 设备管理器元能力组件不是合法的企业设备管理元能力组件。
### 处理步骤 **处理步骤**
1. 请检查激活时输入的设备管理器元能力组件name是否存在应用包中。 1. 请检查激活时输入的设备管理器元能力组件name是否存在应用包中。
2. 请检查企业设备管理组件是否继承企业设备管理框架定义的EnterpriseAdminExtensionAbility组件。 2. 请检查企业设备管理组件是否继承企业设备管理框架定义的EnterpriseAdminExtensionAbility组件。
## 9200004 激活设备管理器失败 ## 9200004 激活设备管理器失败
### 错误信息 **错误信息**
Failed to activate the administrator application of the device. Failed to activate the administrator application of the device.
### 错误描述 **错误描述**
当应用重复激活不同类型的设备管理器或激活多个管理器时,则会产生此错误码。 当应用重复激活不同类型的设备管理器或激活多个管理器时,则会产生此错误码。
### 可能原因 **可能原因**
该错误码表示激活设备管理器失败,可能原因如下。 该错误码表示激活设备管理器失败,可能原因如下。
1. 同时激活多个SDA设备管理器。 1. 同时激活多个SDA设备管理器。
2. 重复激活设备管理器,且管理器类型发生变化。 2. 重复激活设备管理器,且管理器类型发生变化。
3. 同一个应用多个设备管理器元能力组件激活。 3. 同一个应用多个设备管理器元能力组件激活。
### 处理步骤 **处理步骤**
1. 检查是否激活多个SDA设备管理器,SDA设备管理器只允许激活一个。 1. 检查是否激活多个SDA设备管理器,SDA设备管理器只允许激活一个。
2. 检查指定的设备管理器是否已激活了,且重复激活时管理器类型发生变化,此时需要先去激活,再重新激活。 2. 检查指定的设备管理器是否已激活了,且重复激活时管理器类型发生变化,此时需要先去激活,再重新激活。
3. 检查待激活的设备管理器应用中是否已有设备管理元能力组件激活过,同一个应用只允许激活一个设备管理器元能力组件 3. 检查待激活的设备管理器应用中是否已有设备管理元能力组件激活过,同一个应用只允许激活一个设备管理器元能力组件
## 9200005 去激活设备管理器失败 ## 9200005 去激活设备管理器失败
### 错误信息 **错误信息**
Failed to deactivate the administrator application of the device. Failed to deactivate the administrator application of the device.
### 错误描述 **错误描述**
当应用没有激活过或者去激活其他设备管理器时,则会产生此错误码。 当应用没有激活过或者去激活其他设备管理器时,则会产生此错误码。
### 可能原因 **可能原因**
该错误码表示去激活设备管理器失败,可能原因如下。 该错误码表示去激活设备管理器失败,可能原因如下。
1. 去激活的设备管理器应用没有激活过。 1. 去激活的设备管理器应用没有激活过。
2. 不能去激活其他设备管理器。 2. 不能去激活其他设备管理器。
### 处理步骤 **处理步骤**
1. 检查去激活时设备管理应用是否激活过。 1. 检查去激活时设备管理应用是否激活过。
2. 检查去激活时设备管理应用中指定设备管理元能力组件是否激活过。 2. 检查去激活时设备管理应用中指定设备管理元能力组件是否激活过。
3. 检查调用者是否去激活自身,设备管理器应用不能去激活其他设备管理器应用。 3. 检查调用者是否去激活自身,设备管理器应用不能去激活其他设备管理器应用。
## 9200006 指定的用户ID非法 ## 9200006 指定的用户ID非法
### 错误信息 **错误信息**
The specified user ID is invalid. The specified user ID is invalid.
### 错误描述 **错误描述**
当应用调用接口设置用户策略,指定的user id不存在、或者DA,SDA管理器跨用户设置时,则会产生此错误码。 当应用调用接口设置用户策略,指定的user id不存在、或者DA,SDA管理器跨用户设置时,则会产生此错误码。
### 可能原因 **可能原因**
该错误码表示指定的用户ID非法,可能原因如下。 该错误码表示指定的用户ID非法,可能原因如下。
1. 调用接口设置用户策略时候,指定的user id不存在。 1. 调用接口设置用户策略时候,指定的user id不存在。
2. 指定的user id和调用者user id不同。DA,SDA管理器不允许跨用户设置。 2. 指定的user id和调用者user id不同。DA,SDA管理器不允许跨用户设置。
### 处理步骤 **处理步骤**
1. 检查去调用接口中指定的user id是否是有效的user id。 1. 检查去调用接口中指定的user id是否是有效的user id。
2. 检查调用者user id和指定设置的user id是否是同一user id,非SDA模式下不允许跨用户设置策略。 2. 检查调用者user id和指定设置的user id是否是同一user id,非SDA模式下不允许跨用户设置策略。
## 9200007 系统服务工作异常 ## 9200007 系统服务工作异常
### 错误信息 **错误信息**
The system ability work abnormally. The system ability work abnormally.
### 错误描述 **错误描述**
当企业设备管理服务异常时,则会产生此错误码。 当企业设备管理服务异常时,则会产生此错误码。
### 可能原因 **可能原因**
该错误码表示系统服务工作异常,可能原因如下。 该错误码表示系统服务工作异常,可能原因如下。
1. 企业设备管理服务没有正常启动。 1. 企业设备管理服务没有正常启动。
2. 企业设备管理的RPC对象无法获取。 2. 企业设备管理的RPC对象无法获取。
3. 企业设备管理依赖的其他服务没有正常启动或者RPC对象无法获取。 3. 企业设备管理依赖的其他服务没有正常启动或者RPC对象无法获取。
4. 企业设备管理运行过程中系统异常。 4. 企业设备管理运行过程中系统异常。
### 处理步骤 **处理步骤**
系统服务内部工作异常,请稍后重试,或者重启设备尝试。 系统服务内部工作异常,请稍后重试,或者重启设备尝试。
\ No newline at end of file
...@@ -2,18 +2,18 @@ ...@@ -2,18 +2,18 @@
## 100001 内部错误 ## 100001 内部错误
### 错误信息 **错误信息**
Internal error. Internal error.
### 错误描述 **错误描述**
当出现了开发者解决不了的内部异常错误,会报此错误码,并描述具体是哪种内部错误。 当出现了开发者解决不了的内部异常错误,会报此错误码,并描述具体是哪种内部错误。
### 可能原因 **可能原因**
未成功获取渲染引擎,解析参数失败等。 未成功获取渲染引擎,解析参数失败等。
### 处理步骤 **处理步骤**
NA NA
\ No newline at end of file
...@@ -2,28 +2,36 @@ ...@@ -2,28 +2,36 @@
## 890001 参数类型错误 ## 890001 参数类型错误
### 错误信息 **错误信息**
Unspported para value. Unspported para value.
### 错误描述 **错误描述**
当接口传入错误的参数类型时,系统会产生此错误码。 当接口传入错误的参数类型时,系统会产生此错误码。
### 可能原因 **可能原因**
该错误码表示参数错误,可能原因是传入参数的类型错误。 该错误码表示参数错误,可能原因是传入参数的类型错误。
### 处理步骤 **处理步骤**
检查参数的类型是否正确。 检查参数的类型是否正确。
## 890002 配置项参数错误 ## 890002 配置项参数错误
### 错误信息 **错误信息**
Unspported option value. Unspported option value.
### 错误描述 **错误描述**
当接口的option配置参数中包含不合法的配置项时,系统会产生此错误码。 当接口的option配置参数中包含不合法的配置项时,系统会产生此错误码。
### 可能原因 **可能原因**
该错误码表示配置项参数错误,可能原因是option参数中使用了不支持的配置项。 该错误码表示配置项参数错误,可能原因是option参数中使用了不支持的配置项。
### 处理步骤 **处理步骤**
检查option参数中是否使用了不合法的配置项。 检查option参数中是否使用了不合法的配置项。
\ No newline at end of file
...@@ -2,18 +2,18 @@ ...@@ -2,18 +2,18 @@
## 100001 内部错误 ## 100001 内部错误
### 错误信息 **错误信息**
Internal error. Internal error.
### 错误描述 **错误描述**
当出现了开发者解决不了的内部异常错误,会报此错误码,并描述具体是哪种内部错误。 当出现了开发者解决不了的内部异常错误,会报此错误码,并描述具体是哪种内部错误。
### 可能原因 **可能原因**
未成功获取渲染引擎,解析参数失败等。 未成功获取渲染引擎,解析参数失败等。
### 处理步骤 **处理步骤**
NA NA
\ No newline at end of file
...@@ -2,88 +2,112 @@ ...@@ -2,88 +2,112 @@
## 9001001 无效的资源id ## 9001001 无效的资源id
### 错误信息 **错误信息**
The resId invalid. The resId invalid.
### 错误描述 **错误描述**
当传入的资源id符合类型校验,但却是一个不存在的资源id时,会报出此错误。 当传入的资源id符合类型校验,但却是一个不存在的资源id时,会报出此错误。
### 可能原因 **可能原因**
传入的是一个不存在的id值。 传入的是一个不存在的id值。
### 处理步骤 **处理步骤**
检查传入参数的资源id是否已有。 检查传入参数的资源id是否已有。
## 9001002 根据当前资源id,找不到匹配的资源 ## 9001002 根据当前资源id,找不到匹配的资源
### 错误信息 **错误信息**
The resource not found by resId. The resource not found by resId.
### 错误描述 **错误描述**
当传入的资源id符合类型校验,但是根据此资源id匹配不到资源时,会报出此错误。 当传入的资源id符合类型校验,但是根据此资源id匹配不到资源时,会报出此错误。
### 可能原因 **可能原因**
1、传入的是资源id有误。 1、传入的是资源id有误。
2、资源解析有误。 2、资源解析有误。
### 处理步骤 **处理步骤**
检查传入的资源id是否符合预期。 检查传入的资源id是否符合预期。
## 9001003 无效的资源名称 ## 9001003 无效的资源名称
### 错误信息 **错误信息**
The resName invalid. The resName invalid.
### 错误描述 **错误描述**
当传入的资源名称符合类型校验,但却是一个不存在的资源名称时,会报出此错误。 当传入的资源名称符合类型校验,但却是一个不存在的资源名称时,会报出此错误。
### 可能原因 **可能原因**
传入的是一个不存在的资源名称。 传入的是一个不存在的资源名称。
### 处理步骤 **处理步骤**
检查传入的资源名称是否符合预期。 检查传入的资源名称是否符合预期。
## 9001004 根据当前资源名称,找不到匹配的资源 ## 9001004 根据当前资源名称,找不到匹配的资源
### 错误信息 **错误信息**
The resource not found by resName. The resource not found by resName.
### 错误描述 **错误描述**
当传入的资源名称符合类型校验,但是根据此资源名称,匹配不到资源。 当传入的资源名称符合类型校验,但是根据此资源名称,匹配不到资源。
### 可能原因 **可能原因**
1、传入的是资源名称有误。 1、传入的是资源名称有误。
2、资源解析有误。 2、资源解析有误。
### 处理步骤 **处理步骤**
可先检查传入的资源名称是否符合预期。 可先检查传入的资源名称是否符合预期。
## 9001005 无效的相对路径 ## 9001005 无效的相对路径
### 错误信息 **错误信息**
The resource not found by path. The resource not found by path.
### 错误描述 **错误描述**
根据参数相对路径, 找不到对应的资源。 根据参数相对路径, 找不到对应的资源。
### 可能原因 **可能原因**
传入的相对路径有误。 传入的相对路径有误。
### 处理步骤 **处理步骤**
可检查传入的相对路径是否符合预期。 可检查传入的相对路径是否符合预期。
## 9001006 循环引用 ## 9001006 循环引用
### 错误信息 **错误信息**
the resource re-ref too much. the resource re-ref too much.
### 错误描述 **错误描述**
解析引用次数过高。 解析引用次数过高。
### 可能原因 **可能原因**
出现资源循环引用的情况。 出现资源循环引用的情况。
### 处理步骤 **处理步骤**
查看资源$引用的地方,去除循环引用的情况。 查看资源$引用的地方,去除循环引用的情况。
\ No newline at end of file
...@@ -2,72 +2,72 @@ ...@@ -2,72 +2,72 @@
## 100001 内部错误 ## 100001 内部错误
### 错误信息 **错误信息**
Internal error. Internal error.
### 错误描述 **错误描述**
当出现了开发者解决不了的内部异常错误,系统会产生此错误码,并描述具体是哪种内部错误。 当出现了开发者解决不了的内部异常错误,系统会产生此错误码,并描述具体是哪种内部错误。
### 可能原因 **可能原因**
未成功获取渲染引擎,解析参数失败等。 未成功获取渲染引擎,解析参数失败等。
### 处理步骤 **处理步骤**
NA NA
## 100002 路由输入的uri错误 ## 100002 路由输入的uri错误
### 错误信息 错误信息
Uri error. The uri of router is not exist. Uri error. The uri of router is not exist.
### 错误描述 **错误描述**
当跳转页面输入的uri错误或者不存在,系统会产生此错误码。 当跳转页面输入的uri错误或者不存在,系统会产生此错误码。
### 可能原因 **可能原因**
输入的路由uri错误或者不存在。 输入的路由uri错误或者不存在。
### 处理步骤 **处理步骤**
请检查输入的路由uri是否正确。 请检查输入的路由uri是否正确。
## 100003 路由压入的page过多 ## 100003 路由压入的page过多
### 错误信息 **错误信息**
Page stack error. The pages are pushed too much. Page stack error. The pages are pushed too much.
### 错误描述 **错误描述**
当跳转页面压入页面数超过32,系统会产生此错误码。 当跳转页面压入页面数超过32,系统会产生此错误码。
### 可能原因 **可能原因**
压入pages过多。 压入pages过多。
### 处理步骤 **处理步骤**
请清除多余或无效的页面。 请清除多余或无效的页面。
## 200002 路由输入的uri错误 ## 200002 路由输入的uri错误
### 错误信息 **错误信息**
Uri error. The uri of router is not exist. Uri error. The uri of router is not exist.
### 错误描述 **错误描述**
当替换页面输入的uri错误或不存在,系统会产生此错误码。 当替换页面输入的uri错误或不存在,系统会产生此错误码。
### 可能原因 **可能原因**
输入的路由uri错误或不存在。 输入的路由uri错误或不存在。
### 处理步骤 **处理步骤**
请检查输入的路由uri是否正确。 请检查输入的路由uri是否正确。
\ No newline at end of file
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
## 14500101 传感器服务异常 ## 14500101 传感器服务异常
### 错误信息 **错误信息**
Service exception. Service exception.
### 错误描述 **错误描述**
当调用sensor模块on、once、off接口时,若hdi服务异常,会报此错误码。 当调用sensor模块on、once、off接口时,若hdi服务异常,会报此错误码。
### 可能原因 **可能原因**
访问hdi服务状态异常。 访问hdi服务状态异常。
### 处理步骤 **处理步骤**
1. 定时重试操作,如间隔1s或者按照指数增长间隔重试。 1. 定时重试操作,如间隔1s或者按照指数增长间隔重试。
2. 连续重试3次不可用则停止尝试,期间可优先尝试获取器件列表方式进一步获取设备可用性。 2. 连续重试3次不可用则停止尝试,期间可优先尝试获取器件列表方式进一步获取设备可用性。
\ No newline at end of file
...@@ -2,20 +2,20 @@ ...@@ -2,20 +2,20 @@
## 14600101 操作设备失败 ## 14600101 操作设备失败
### 错误信息 **错误信息**
Device operation failed. Device operation failed.
### 错误描述 **错误描述**
当调用vibrator模块startVibration接口时,若hdi服务异常或者设备被占用,会报此错误码。 当调用vibrator模块startVibration接口时,若hdi服务异常或者设备被占用,会报此错误码。
### 可能原因 **可能原因**
1. 访问hdi服务状态异常。 1. 访问hdi服务状态异常。
2. 当前设备被占用。 2. 当前设备被占用。
### 处理步骤 **处理步骤**
1. 间隔一段时间重试操作,或按指数增长间隔重试;连续重试3次不可用则停止尝试,期间可优先尝试获取器件列表方式进一步获取设备可用性。 1. 间隔一段时间重试操作,或按指数增长间隔重试;连续重试3次不可用则停止尝试,期间可优先尝试获取器件列表方式进一步获取设备可用性。
2. 设置振动优先级较低,尝试设置更高优先级。 2. 设置振动优先级较低,尝试设置更高优先级。
\ No newline at end of file
...@@ -7,10 +7,7 @@ ...@@ -7,10 +7,7 @@
- 文件组织 - 文件组织
- [目录结构](ts-framework-directory.md) - [目录结构](ts-framework-directory.md)
- [应用代码文件访问规则](ts-framework-file-access-rules.md) - [应用代码文件访问规则](ts-framework-file-access-rules.md)
- 资源管理 - 深入理解组件化
- [资源文件的分类](ui-ts-basic-resource-file-categories.md)
- [资源访问](ts-resource-access.md)
- 自定义组件
- [自定义组件初始化](ts-custom-component-initialization.md) - [自定义组件初始化](ts-custom-component-initialization.md)
- [自定义组件生命周期回调函数](ts-custom-component-lifecycle-callbacks.md) - [自定义组件生命周期回调函数](ts-custom-component-lifecycle-callbacks.md)
- [组件创建和重新初始化示例](ts-component-creation-re-initialization.md) - [组件创建和重新初始化示例](ts-component-creation-re-initialization.md)
......
# 资源访问
## 访问应用资源
在工程中,通过```"$r('app.type.name')"```的形式引用应用资源。app代表是应用内resources目录中定义的资源;type代表资源类型(或资源的存放位置),可以取“color”、“float”、“string”、“plural”、“media”,name代表资源命名,由开发者定义资源时确定。
引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。
> **说明:**
>
> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。
>
> `$r`返回值为Resource对象,可通过[getString](../reference/apis/js-apis-resource-manager.md#getstring) 方法获取对应的字符串。
在xxx.ets文件中,可以使用在resources目录中定义的资源。
```ts
Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Text($r('app.string.message_arrive', "five of the clock")) // 引用string资源,$r的第二个参数用于替换%s
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.plural.eat_apple', 5, 5)) // plural$r引用,第一个指定plural资源,第二个参数指定单复数的数量,此处第三个数字为对%d的替换
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Image($r('app.media.my_background_image')) // media资源的$r引用
Image($rawfile('test.png')) // rawfile$r引用rawfile目录下图片
Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下图片
```
## 访问系统资源
系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。
开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。
```ts
Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon'))
.border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2})
.margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')})
.height(200)
.width(300)
```
## 资源文件示例
color.json文件的内容如下:
```json
{
"color": [
{
"name": "color_hello",
"value": "#ffff0000"
},
{
"name": "color_world",
"value": "#ff0000ff"
}
]
}
```
float.json文件的内容如下:
```json
{
"float":[
{
"name":"font_hello",
"value":"28.0fp"
},
{
"name":"font_world",
"value":"20.0fp"
}
]
}
```
string.json文件的内容如下:
```json
{
"string":[
{
"name":"string_hello",
"value":"Hello"
},
{
"name":"string_world",
"value":"World"
},
{
"name":"message_arrive",
"value":"We will arrive at %s."
}
]
}
```
plural.json文件的内容如下:
```json
{
"plural":[
{
"name":"eat_apple",
"value":[
{
"quantity":"one",
"value":"%d apple"
},
{
"quantity":"other",
"value":"%d apples"
}
]
}
]
}
```
## 相关实例
针对访问应用资源,有以下相关实例可供参考:
- [`ResourceManager`:资源管理器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager)
...@@ -13,8 +13,9 @@ ...@@ -13,8 +13,9 @@
- [互斥锁](kernel-mini-basic-ipc-mutex.md) - [互斥锁](kernel-mini-basic-ipc-mutex.md)
- [消息队列](kernel-mini-basic-ipc-queue.md) - [消息队列](kernel-mini-basic-ipc-queue.md)
- [信号量](kernel-mini-basic-ipc-sem.md) - [信号量](kernel-mini-basic-ipc-sem.md)
- [时间管理](kernel-basic-mini-time.md) - [时间管理](kernel-mini-basic-time.md)
- [软件定时器](kernel-mini-basic-soft.md) - [软件定时器](kernel-mini-basic-soft.md)
- [双向链表](kernel-mini-basic-list.md)
- 扩展组件 - 扩展组件
- [C++支持](kernel-mini-extend-support.md) - [C++支持](kernel-mini-extend-support.md)
- [CPU占用率](kernel-mini-extend-cpup.md) - [CPU占用率](kernel-mini-extend-cpup.md)
...@@ -27,7 +28,6 @@ ...@@ -27,7 +28,6 @@
- [LMS调测](kernel-mini-memory-lms.md) - [LMS调测](kernel-mini-memory-lms.md)
- 附录 - 附录
- [内核编码规范](kernel-mini-appx-code.md) - [内核编码规范](kernel-mini-appx-code.md)
- [双向链表](kernel-mini-appx-data-list.md)
- [标准库支持](kernel-mini-appx-lib.md) - [标准库支持](kernel-mini-appx-lib.md)
- 小型系统内核(LiteOS-A) - 小型系统内核(LiteOS-A)
- [小型系统内核概述](kernel-small-overview.md) - [小型系统内核概述](kernel-small-overview.md)
......
...@@ -9,25 +9,25 @@ ...@@ -9,25 +9,25 @@
下面介绍下中断的相关概念: 下面介绍下中断的相关概念:
- 中断号 - 中断号
中断请求信号特定的标志,计算机能够根据中断号判断是哪个设备提出的中断请求。 中断请求信号特定的标志,计算机能够根据中断号判断是哪个设备提出的中断请求。
- 中断请求 - 中断请求
“紧急事件”向CPU提出申请(发一个电脉冲信号),请求中断,需要CPU暂停当前执行的任务处理该“紧急事件”,这一过程称为中断请求。 “紧急事件”向CPU提出申请(发一个电脉冲信号),请求中断,需要CPU暂停当前执行的任务处理该“紧急事件”,这一过程称为中断请求。
- 中断优先级 - 中断优先级
为使系统能够及时响应并处理所有中断,系统根据中断事件的重要性和紧迫程度,将中断源分为若干个级别,称作中断优先级。 为使系统能够及时响应并处理所有中断,系统根据中断事件的重要性和紧迫程度,将中断源分为若干个级别,称作中断优先级。
- 中断处理程序 - 中断处理程序
当外设发出中断请求后,CPU暂停当前的任务,转而响应中断请求,即执行中断处理程序。产生中断的每个设备都有相应的中断处理程序。 当外设发出中断请求后,CPU暂停当前的任务,转而响应中断请求,即执行中断处理程序。产生中断的每个设备都有相应的中断处理程序。
- 中断触发 - 中断触发
中断源向中断控制器发送中断信号,中断控制器对中断进行仲裁,确定优先级,将中断信号发送给CPU。中断源产生中断信号的时候,会将中断触发器置“1”,表明该中断源产生了中断,要求CPU去响应该中断。 中断源向中断控制器发送中断信号,中断控制器对中断进行仲裁,确定优先级,将中断信号发送给CPU。中断源产生中断信号的时候,会将中断触发器置“1”,表明该中断源产生了中断,要求CPU去响应该中断。
- 中断向量 - 中断向量
中断服务程序的入口地址。 中断服务程序的入口地址。
- 中断向量表 - 中断向量表
存储中断向量的存储区,中断向量与中断号对应,中断向量在中断向量表中按照中断号顺序存储。 存储中断向量的存储区,中断向量与中断号对应,中断向量在中断向量表中按照中断号顺序存储。
...@@ -37,37 +37,46 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 ...@@ -37,37 +37,46 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细
**表1** 创建、删除中断 **表1** 创建、删除中断
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| HalHwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | | LOS_HwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 |
| HalHwiDelete | 根据指定的中断号,删除中断。 | | LOS_HwiDelete | 根据指定的中断号,删除中断。 |
**表2** 打开、关闭中断 **表2** 打开、关闭中断
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | | LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 |
| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | | LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 |
| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | | LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 |
**表3** 其他中断操作
| 接口名 | 描述 |
| :----------------- | ---------------- |
| LOS_HwiTrigger | 中断触发。 |
| LOS_HwiEnable | 中断使能。 |
| LOS_HwiDisable | 中断禁用。 |
| LOS_HwiClear | 中断手动清除。 |
| LOS_HwiSetPriority | 设置中断优先级。 |
| LOS_HwiCurIrqNum | 获取当前中断号。 |
## 开发流程 ## 开发流程
1. 调用中断创建接口HalHwiCreate创建中断。 1. 调用中断创建接口LOS_HwiCreate创建中断。
2. 调用TestHwiTrigger接口触发指定中断(该接口在测试套中定义,通过写中断控制器的相关寄存器模拟外部中断,一般的外设设备,不需要执行这一步) 2. 调用LOS_HwiTrigger接口触发指定中断(写中断控制器的相关寄存器模拟外部中断),或通过外设触发中断
3. 调用HalHwiDelete接口删除指定中断,此接口根据实际情况使用,判断是否需要删除中断。 3. 调用LOS_HwiDelete接口删除指定中断,此接口根据实际情况使用,开发者判断是否需要删除中断。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 根据具体硬件,配置支持的最大中断数及可设置的中断优先级个数。 > - 根据具体硬件,配置支持的最大中断数及可设置的中断优先级个数。
> > - 关中断时间或中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。
> - 中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。
>
> - 中断响应过程中不能直接、间接执行引起调度的LOS_Schedule等函数。 > - 中断响应过程中不能直接、间接执行引起调度的LOS_Schedule等函数。
> > - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。
> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 > - Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。
## 编程实例 ## 编程实例
...@@ -80,29 +89,39 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 ...@@ -80,29 +89,39 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细
3. 删除中断。 3. 删除中断。
代码实现如下,演示如何创建中断和删除中断,当指定的中断号HWI_NUM_TEST产生中断时,会调用中断处理函数: 代码实现如下,演示如何创建中断、触发指定的中断号进而调用中断处理函数、删除中断。
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleInterrupt。
``` ```
#include "los_interrupt.h" #include "los_interrupt.h"
#include "los_compiler.h"
/*创建中断*/ /* 验证的中断号 */
#define HWI_NUM_TEST 7 #define HWI_NUM_TEST 7
STATIC VOID HwiUsrIrq(VOID) /* 中断处理程序 */
STATIC VOID UsrIrqEntry(VOID)
{ {
printf("in the func HwiUsrIrq \n"); printf("in the func UsrIrqEntry\n");
} }
static UINT32 Example_Interrupt(VOID) /* 注册的线程回调函数,用于触发中断 */
STATIC VOID InterruptTest(VOID)
{
LOS_HwiTrigger(HWI_NUM_TEST);
}
UINT32 ExampleInterrupt(VOID)
{ {
UINT32 ret; UINT32 ret;
HWI_PRIOR_T hwiPrio = 3; HWI_PRIOR_T hwiPrio = 3; // 3,中断优先级
HWI_MODE_T mode = 0; HWI_MODE_T mode = 0;
HWI_ARG_T arg = 0; HWI_ARG_T arg = 0;
/*创建中断*/ /* 创建中断 */
ret = HalHwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, arg); ret = LOS_HwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)UsrIrqEntry, arg);
if(ret == LOS_OK){ if(ret == LOS_OK){
printf("Hwi create success!\n"); printf("Hwi create success!\n");
} else { } else {
...@@ -110,17 +129,32 @@ static UINT32 Example_Interrupt(VOID) ...@@ -110,17 +129,32 @@ static UINT32 Example_Interrupt(VOID)
return LOS_NOK; return LOS_NOK;
} }
/* 延时50个Ticks, 当有硬件中断发生时,会调用函数HwiUsrIrq*/ TSK_INIT_PARAM_S taskParam = { 0 };
UINT32 testTaskID;
/* 创建一个优先级低优先级的线程,用于验证触发中断 */
taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)InterruptTest;
taskParam.uwStackSize = OS_TSK_TEST_STACK_SIZE;
taskParam.pcName = "InterruptTest";
taskParam.usTaskPrio = TASK_PRIO_TEST - 1;
taskParam.uwResved = LOS_TASK_ATTR_JOINABLE;
ret = LOS_TaskCreate(&testTaskID, &taskParam);
if (LOS_OK != ret) {
PRINTF("InterruptTest task error\n");
}
/* 延时50 tick,让出当前线程的调度 */
LOS_TaskDelay(50); LOS_TaskDelay(50);
/*删除中断*/ /* 删除注册的中断 */
ret = HalHwiDelete(HWI_NUM_TEST); ret = LOS_HwiDelete(HWI_NUM_TEST, NULL);
if(ret == LOS_OK){ if(ret == LOS_OK){
printf("Hwi delete success!\n"); printf("Hwi delete success!\n");
} else { } else {
printf("Hwi delete failed!\n"); printf("Hwi delete failed!\n");
return LOS_NOK; return LOS_NOK;
} }
return LOS_OK; return LOS_OK;
} }
``` ```
...@@ -131,8 +165,9 @@ static UINT32 Example_Interrupt(VOID) ...@@ -131,8 +165,9 @@ static UINT32 Example_Interrupt(VOID)
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
Hwi create success! Hwi create success!
in the func UsrIrqEntry
Hwi delete success! Hwi delete success!
``` ```
...@@ -16,14 +16,12 @@ ...@@ -16,14 +16,12 @@
## 运行机制 ## 运行机制
### 事件控制块 ### 事件控制块
由事件初始化函数配置的一个结构体,在事件读写等操作时作为参数传入,用于标识不同的事件,控制块数据结构如下:
``` ```
/**
* 事件控制块数据结构
*/
typedef struct tagEvent { typedef struct tagEvent {
UINT32 uwEventID; /* 事件集合,表示已经处理(写入和清零)的事件集合 */ UINT32 uwEventID; /* 事件集合,表示已经处理(写入和清零)的事件集合 */
LOS_DL_LIST stEventList; /* 等待特定事件的任务链表 */ LOS_DL_LIST stEventList; /* 等待特定事件的任务链表 */
...@@ -33,7 +31,7 @@ typedef struct tagEvent { ...@@ -33,7 +31,7 @@ typedef struct tagEvent {
### 事件运作原理 ### 事件运作原理
**事件初始化**创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 **事件初始化**:创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。
**写事件**:会向事件控制块写入指定的事件,事件控制块更新事件集合,并遍历任务链表,根据任务等待具体条件满足情况决定是否唤醒相关任务。 **写事件**:会向事件控制块写入指定的事件,事件控制块更新事件集合,并遍历任务链表,根据任务等待具体条件满足情况决定是否唤醒相关任务。
...@@ -96,31 +94,29 @@ typedef struct tagEvent { ...@@ -96,31 +94,29 @@ typedef struct tagEvent {
### 实例描述 ### 实例描述
示例中,任务Example_TaskEntry创建一个任务Example_Event,Example_Event读事件阻塞,Example_TaskEntry向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 示例中,任务ExampleEvent创建一个任务EventReadTask,EventReadTask读事件阻塞,ExampleEvent向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。
1. 在任务Example_TaskEntry创建任务Example_Event,其中任务Example_Event优先级高于Example_TaskEntry 1. 在任务ExampleEvent创建任务EventReadTask,其中任务EventReadTask优先级高于ExampleEvent
2. 在任务Example_Event中读事件0x00000001,阻塞,发生任务切换,执行任务Example_TaskEntry 2. 在任务EventReadTask中读事件0x00000001,阻塞,发生任务切换,执行任务ExampleEvent
3. 在任务Example_TaskEntry向任务Example_Event写事件0x00000001,发生任务切换,执行任务Example_Event 3. 在任务ExampleEvent写事件0x00000001,发生任务切换,执行任务EventReadTask
4. Example_Event得以执行,直到任务结束。 4. EventReadTask得以执行,直到任务结束。
5. Example_TaskEntry得以执行,直到任务结束。 5. ExampleEvent得以执行,直到任务结束。
### 示例代码 ### 示例代码
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleEvent。
``` ```
#include "los_event.h" #include "los_event.h"
#include "los_task.h" #include "los_task.h"
#include "securec.h"
/* 任务ID */
UINT32 g_testTaskId;
/* 事件控制结构体 */ /* 事件控制结构体 */
EVENT_CB_S g_exampleEvent; EVENT_CB_S g_exampleEvent;
...@@ -128,8 +124,11 @@ EVENT_CB_S g_exampleEvent; ...@@ -128,8 +124,11 @@ EVENT_CB_S g_exampleEvent;
/* 等待的事件类型 */ /* 等待的事件类型 */
#define EVENT_WAIT 0x00000001 #define EVENT_WAIT 0x00000001
/* 等待超时时间 */
#define EVENT_TIMEOUT 100
/* 用例任务入口函数 */ /* 用例任务入口函数 */
VOID Example_Event(VOID) VOID EventReadTask(VOID)
{ {
UINT32 ret; UINT32 ret;
UINT32 event; UINT32 event;
...@@ -137,39 +136,39 @@ VOID Example_Event(VOID) ...@@ -137,39 +136,39 @@ VOID Example_Event(VOID)
/* 超时等待方式读事件,超时时间为100 ticks, 若100 ticks后未读取到指定事件,读事件超时,任务直接唤醒 */ /* 超时等待方式读事件,超时时间为100 ticks, 若100 ticks后未读取到指定事件,读事件超时,任务直接唤醒 */
printf("Example_Event wait event 0x%x \n", EVENT_WAIT); printf("Example_Event wait event 0x%x \n", EVENT_WAIT);
event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT);
if (event == EVENT_WAIT) { if (event == EVENT_WAIT) {
printf("Example_Event,read event :0x%x\n", event); printf("Example_Event, read event :0x%x\n", event);
} else { } else {
printf("Example_Event,read event timeout\n"); printf("Example_Event, read event timeout\n");
} }
} }
UINT32 Example_TaskEntry(VOID) UINT32 ExampleEvent(VOID)
{ {
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S task1; UINT32 taskId;
TSK_INIT_PARAM_S taskParam = { 0 };
/* 事件初始化 */ /* 事件初始化 */
ret = LOS_EventInit(&g_exampleEvent); ret = LOS_EventInit(&g_exampleEvent);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("init event failed .\n"); printf("init event failed .\n");
return -1; return LOS_NOK;
} }
/* 创建任务 */ /* 创建任务 */
(VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)EventReadTask;
task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Event; taskParam.pcName = "EventReadTask";
task1.pcName = "EventTsk1"; taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
task1.uwStackSize = OS_TSK_DEFAULT_STACK_SIZE; taskParam.usTaskPrio = 3;
task1.usTaskPrio = 5; ret = LOS_TaskCreate(&taskId, &taskParam);
ret = LOS_TaskCreate(&g_testTaskId, &task1);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task create failed.\n"); printf("task create failed.\n");
return LOS_NOK; return LOS_NOK;
} }
/* 写g_testTaskId 等待事件 */ /* 写事件 */
printf("Example_TaskEntry write event.\n"); printf("Example_TaskEntry write event.\n");
ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT);
...@@ -183,10 +182,10 @@ UINT32 Example_TaskEntry(VOID) ...@@ -183,10 +182,10 @@ UINT32 Example_TaskEntry(VOID)
LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID);
printf("EventMask:%d\n", g_exampleEvent.uwEventID); printf("EventMask:%d\n", g_exampleEvent.uwEventID);
/* 删除任务 */ /* 删除事件 */
ret = LOS_TaskDelete(g_testTaskId); ret = LOS_EventDestroy(&g_exampleEvent);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task delete failed.\n"); printf("destory event failed .\n");
return LOS_NOK; return LOS_NOK;
} }
...@@ -202,9 +201,9 @@ UINT32 Example_TaskEntry(VOID) ...@@ -202,9 +201,9 @@ UINT32 Example_TaskEntry(VOID)
``` ```
Example_Event wait event 0x1 Example_Event wait event 0x1
Example_TaskEntry write event. Example_TaskEntry write event.
Example_Event,read event :0x1 Example_Event, read event :0x1
EventMask:1 EventMask:1
EventMask:0 EventMask:0
``` ```
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
互斥锁又称互斥型信号量,是一种特殊的二值性信号量,用于实现对共享资源的独占式处理。 互斥锁又称互斥型信号量,是一种特殊的二值性信号量,用于实现对共享资源的独占式处理。
任意时刻互斥锁的状态只有两种,开锁或闭锁。当有任务持有时,互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放它时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 任意时刻互斥锁的状态只有两种,开锁或闭锁。当任务持有互斥锁时,该互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放互斥锁时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。
多任务环境下往往存在多个任务竞争同一共享资源的应用场景,互斥锁可被用于对共享资源的保护从而实现独占式访问。另外互斥锁可以解决信号量存在的优先级翻转问题。 多任务环境下往往存在多个任务竞争同一共享资源的应用场景,互斥锁可被用于对共享资源的保护从而实现独占式访问。另外互斥锁可以解决信号量存在的优先级翻转问题。
...@@ -24,10 +24,10 @@ ...@@ -24,10 +24,10 @@
**表1** 互斥锁模块接口 **表1** 互斥锁模块接口
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁<br/>LOS_MuxDelete:删除指定的互斥锁 | | 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁<br/>LOS_MuxDelete:删除指定的互斥锁。 |
| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁<br/>LOS_MuxPost:释放指定的互斥锁 | | 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁<br/>LOS_MuxPost:释放指定的互斥锁。 |
## 开发流程 ## 开发流程
...@@ -39,7 +39,7 @@ ...@@ -39,7 +39,7 @@
2. 申请互斥锁LOS_MuxPend。 2. 申请互斥锁LOS_MuxPend。
申请模式有三种:无阻塞模式、永久阻塞模式、定时阻塞模式。 申请模式有三种:无阻塞模式、永久阻塞模式、定时阻塞模式。
- 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。 - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。否则直接返回并继续运行当前任务,不会产生阻塞。
- 永久阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则,该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,直到有其他任务释放该互斥锁,阻塞任务才会重新得以执行。 - 永久阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则,该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,直到有其他任务释放该互斥锁,阻塞任务才会重新得以执行。
- 定时阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,指定时间超时前有其他任务释放该互斥锁,或者用户指定时间超时后,阻塞任务才会重新得以执行。 - 定时阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,指定时间超时前有其他任务释放该互斥锁,或者用户指定时间超时后,阻塞任务才会重新得以执行。
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
4. 删除互斥锁LOS_MuxDelete。 4. 删除互斥锁LOS_MuxDelete。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 两个任务不能对同一把互斥锁加锁。如果某任务对已被持有的互斥锁加锁,则该任务会被挂起,直到持有该锁的任务对互斥锁解锁,才能执行对这把互斥锁的加锁操作 > - 互斥锁支持嵌套,即申请该互斥锁的任务与已经持有该互斥锁的任务为同一个任务时会认为申请成功,按申请次数对应的去释放该锁即可
> >
> - 互斥锁不能在中断服务程序中使用。 > - 互斥锁不能在中断服务程序中使用。
> >
...@@ -66,67 +66,66 @@ ...@@ -66,67 +66,66 @@
本实例实现如下流程。 本实例实现如下流程。
1. 任务Example_TaskEntry创建一个互斥锁,锁任务调度,创建两个任务Example_MutexTask1、Example_MutexTask2。Example_MutexTask2优先级高于Example_MutexTask1,解锁任务调度。 1. 任务ExampleMutex创建一个互斥锁,锁任务调度,创建两个任务ExampleMutexTask1、ExampleMutexTask2。ExampleMutexTask2优先级高于ExampleMutexTask1,解锁任务调度。
2. Example_MutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,Example_MutexTask2挂起,Example_MutexTask1被唤醒。 2. ExampleMutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,ExampleMutexTask2挂起,ExampleMutexTask1被唤醒。
3. Example_MutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。10Tick超时时间到达后,Example_MutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。 3. ExampleMutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。10Tick超时时间到达后,ExampleMutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。
4. 100Tick休眠时间到达后,Example_MutexTask2被唤醒, 释放互斥锁,唤醒Example_MutexTask1。Example_MutexTask1成功获取到互斥锁后,释放,删除互斥锁。 4. 100Tick休眠时间到达后,ExampleMutexTask2被唤醒, 释放互斥锁,唤醒ExampleMutexTask1。ExampleMutexTask1成功获取到互斥锁后,释放并删除互斥锁。
### 示例代码 ### 示例代码
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleMutex。
``` ```
#include <string.h>
#include "los_mux.h" #include "los_mux.h"
/* 互斥锁句柄id */ /* 互斥锁句柄 */
UINT32 g_testMux; UINT32 g_testMux;
/* 任务ID */
UINT32 g_testTaskId01;
UINT32 g_testTaskId02;
VOID Example_MutexTask1(VOID) VOID ExampleMutexTask1(VOID)
{ {
UINT32 ret; UINT32 ret;
printf("task1 try to get mutex, wait 10 ticks.\n"); printf("task1 try to get mutex, wait 10 ticks.\n");
/* 申请互斥锁 */ /* 申请互斥锁 */
ret = LOS_MuxPend(g_testMux, 10); ret = LOS_MuxPend(g_testMux, 10);
if (ret == LOS_OK) { if (ret == LOS_OK) {
printf("task1 get mutex g_testMux.\n"); printf("task1 get mutex g_testMux.\n");
/* 释放互斥锁 */ /* 释放互斥锁,这个分支正常不应该进来 */
LOS_MuxPost(g_testMux); LOS_MuxPost(g_testMux);
LOS_MuxDelete(g_testMux);
return; return;
} }
if (ret == LOS_ERRNO_MUX_TIMEOUT ) { if (ret == LOS_ERRNO_MUX_TIMEOUT ) {
printf("task1 timeout and try to get mutex, wait forever.\n"); printf("task1 timeout and try to get mutex, wait forever.\n");
/* 申请互斥锁 */ /* 申请互斥锁 */
ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER);
if (ret == LOS_OK) { if (ret == LOS_OK) {
printf("task1 wait forever, get mutex g_testMux.\n"); printf("task1 wait forever, get mutex g_testMux.\n");
/* 释放互斥锁 */ /* 释放互斥锁 */
LOS_MuxPost(g_testMux); LOS_MuxPost(g_testMux);
/* 删除互斥锁 */ /* 删除互斥锁 */
LOS_MuxDelete(g_testMux); LOS_MuxDelete(g_testMux);
printf("task1 post and delete mutex g_testMux.\n"); printf("task1 post and delete mutex g_testMux.\n");
return; return;
} }
} }
return; return;
} }
VOID Example_MutexTask2(VOID) VOID ExampleMutexTask2(VOID)
{ {
printf("task2 try to get mutex, wait forever.\n"); printf("task2 try to get mutex, wait forever.\n");
/* 申请互斥锁 */ /* 申请互斥锁 */
(VOID)LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); (VOID)LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER);
printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); printf("task2 get mutex g_testMux and suspend 100 ticks.\n");
/* 任务休眠100Ticks */ /* 任务休眠100Ticks */
...@@ -138,11 +137,13 @@ VOID Example_MutexTask2(VOID) ...@@ -138,11 +137,13 @@ VOID Example_MutexTask2(VOID)
return; return;
} }
UINT32 Example_TaskEntry(VOID) UINT32 ExampleMutex(VOID)
{ {
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S task1 = { 0 };
TSK_INIT_PARAM_S task2; TSK_INIT_PARAM_S task2 = { 0 };
UINT32 taskId01;
UINT32 taskId02;
/* 创建互斥锁 */ /* 创建互斥锁 */
LOS_MuxCreate(&g_testMux); LOS_MuxCreate(&g_testMux);
...@@ -151,24 +152,22 @@ UINT32 Example_TaskEntry(VOID) ...@@ -151,24 +152,22 @@ UINT32 Example_TaskEntry(VOID)
LOS_TaskLock(); LOS_TaskLock();
/* 创建任务1 */ /* 创建任务1 */
memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask1;
task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1;
task1.pcName = "MutexTsk1"; task1.pcName = "MutexTsk1";
task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
task1.usTaskPrio = 5; task1.usTaskPrio = 5;
ret = LOS_TaskCreate(&g_testTaskId01, &task1); ret = LOS_TaskCreate(&taskId01, &task1);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task1 create failed.\n"); printf("task1 create failed.\n");
return LOS_NOK; return LOS_NOK;
} }
/* 创建任务2 */ /* 创建任务2 */
memset(&task2, 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask2;
task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2;
task2.pcName = "MutexTsk2"; task2.pcName = "MutexTsk2";
task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
task2.usTaskPrio = 4; task2.usTaskPrio = 4;
ret = LOS_TaskCreate(&g_testTaskId02, &task2); ret = LOS_TaskCreate(&taskId02, &task2);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task2 create failed.\n"); printf("task2 create failed.\n");
return LOS_NOK; return LOS_NOK;
...@@ -185,7 +184,7 @@ UINT32 Example_TaskEntry(VOID) ...@@ -185,7 +184,7 @@ UINT32 Example_TaskEntry(VOID)
### 结果验证 ### 结果验证
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
task2 try to get mutex, wait forever. task2 try to get mutex, wait forever.
task2 get mutex g_testMux and suspend 100 ticks. task2 get mutex g_testMux and suspend 100 ticks.
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 基本概念 ## 基本概念
队列又称消息队列,是一种常用于任务间通信的数据结构。队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 消息队列又称队列,是一种任务间通信的机制。消息队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。
任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。 任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。
...@@ -12,44 +12,40 @@ ...@@ -12,44 +12,40 @@
消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性: 消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性:
- 消息以先进先出的方式排队,支持异步读写。 - 消息以先进先出的方式排队,支持异步读写。
- 读队列和写队列都支持超时机制。 - 读队列和写队列都支持超时机制。
- 每读取一条消息,就会将该消息节点设置为空闲。 - 每读取一条消息,就会将该消息节点设置为空闲。
- 发送消息类型由通信双方约定,可以允许不同长度(不超过队列的消息节点大小)的消息。 - 发送消息类型由通信双方约定,可以允许不同长度(不超过队列的消息节点大小)的消息。
- 一个任务能够从任意一个消息队列接收和发送消息。 - 一个任务能够从任意一个消息队列接收和发送消息。
- 多个任务能够从同一个消息队列接收和发送消息。 - 多个任务能够从同一个消息队列接收和发送消息。
- 创建普通队列时所需的队列空间,由系统自行动态申请内存。
- 创建队列时所需的队列空间,接口内系统自行动态申请内存 - 创建静态队列时所需的队列空间,由用户传入。这块空间在队列删除之后也由用户去释放
## 运行机制 ## 运行机制
### 队列控制块 ### 队列控制块
队列会在初始化时给分配一个属于自己的控制块,控制块包含了队列的名称、状态等信息。删除队列时会释放该控制块。
队列控制块数据结构如下:
``` ```
/**
* 队列控制块数据结构
*/
typedef struct typedef struct
{ {
UINT8 *queue; /* 队列消息内存空间的指针 */ UINT8 *queue; /* 队列消息内存空间的指针 */
UINT16 queueState; /* 队列状态 */ UINT8 *queueName /* 队列名称 */
UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ UINT16 queueState; /* 队列状态 */
UINT16 queueSize; /* 消息节点大小 */ UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */
UINT16 queueID; /* 队列ID */ UINT16 queueSize; /* 消息节点大小 */
UINT16 queueHead; /* 消息头节点位置(数组下标)*/ UINT16 queueID; /* 队列ID */
UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ UINT16 queueHead; /* 消息头节点位置(数组下标)*/
UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, UINT16 queueTail; /* 消息尾节点位置(数组下标)*/
数组下标1的元素表示队列中可写消息数 */ UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数,
LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, 数组下标1的元素表示队列中可写消息数 */
下标0:读取链表,下标1:写入链表 */ LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表,
LOS_DL_LIST memList; /* 内存块链表 */ 下标0:读取链表,下标1:写入链表 */
LOS_DL_LIST memList; /* 内存块链表 */
} LosQueueCB; } LosQueueCB;
``` ```
...@@ -81,12 +77,12 @@ typedef struct ...@@ -81,12 +77,12 @@ typedef struct
## 接口说明 ## 接口说明
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 创建/删除消息队列 | -&nbsp;LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。<br/>-&nbsp;LOS_QueueDelete:根据队列ID删除一个指定队列。 | | 创建/删除消息队列 | &nbsp;LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。<br/>LOS_QueueCreateStatic:创建一个消息队列,由用户传入队列空间。<br/>&nbsp;LOS_QueueDelete:根据队列ID删除一个指定队列,静态消息队列删除后,队列空间需要用例自行处理。 |
| 读/写队列(不带拷贝) | -&nbsp;LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。<br/>-&nbsp;LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。<br/>-&nbsp;LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | | 读/写队列(不带拷贝) | &nbsp;LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。<br/>&nbsp;LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。<br/>&nbsp;LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 |
| 读/写队列(带拷贝) | -&nbsp;LOS_QueueReadCopy:读取指定队列头节点中的数据。<br/>-&nbsp;LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。<br/>-&nbsp;LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | | 读/写队列(带拷贝) | &nbsp;LOS_QueueReadCopy:读取指定队列头节点中的数据。<br/>&nbsp;LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。<br/>&nbsp;LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 |
| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | | 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 |
## 开发流程 ## 开发流程
...@@ -140,11 +136,14 @@ typedef struct ...@@ -140,11 +136,14 @@ typedef struct
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue。
``` ```
#include "los_task.h" #include "los_task.h"
#include "los_queue.h" #include "los_queue.h"
static UINT32 g_queue;
STATIC UINT32 g_queue;
#define BUFFER_LEN 50 #define BUFFER_LEN 50
VOID SendEntry(VOID) VOID SendEntry(VOID)
...@@ -154,7 +153,7 @@ VOID SendEntry(VOID) ...@@ -154,7 +153,7 @@ VOID SendEntry(VOID)
UINT32 len = sizeof(abuf); UINT32 len = sizeof(abuf);
ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0);
if(ret != LOS_OK) { if (ret != LOS_OK) {
printf("send message failure, error: %x\n", ret); printf("send message failure, error: %x\n", ret);
} }
} }
...@@ -165,17 +164,17 @@ VOID RecvEntry(VOID) ...@@ -165,17 +164,17 @@ VOID RecvEntry(VOID)
CHAR readBuf[BUFFER_LEN] = {0}; CHAR readBuf[BUFFER_LEN] = {0};
UINT32 readLen = BUFFER_LEN; UINT32 readLen = BUFFER_LEN;
//休眠1s /* 休眠1s */
usleep(1000000); usleep(1000000);
ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0);
if(ret != LOS_OK) { if (ret != LOS_OK) {
printf("recv message failure, error: %x\n", ret); printf("recv message failure, error: %x\n", ret);
} }
printf("recv message: %s\n", readBuf); printf("recv message: %s.\n", readBuf);
ret = LOS_QueueDelete(g_queue); ret = LOS_QueueDelete(g_queue);
if(ret != LOS_OK) { if (ret != LOS_OK) {
printf("delete the queue failure, error: %x\n", ret); printf("delete the queue failure, error: %x\n", ret);
} }
...@@ -186,25 +185,28 @@ UINT32 ExampleQueue(VOID) ...@@ -186,25 +185,28 @@ UINT32 ExampleQueue(VOID)
{ {
printf("start queue example.\n"); printf("start queue example.\n");
UINT32 ret = 0; UINT32 ret = 0;
UINT32 task1, task2; UINT32 task1;
TSK_INIT_PARAM_S initParam = {0}; UINT32 task2;
TSK_INIT_PARAM_S taskParam1 = { 0 };
initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; TSK_INIT_PARAM_S taskParam2 = { 0 };
initParam.usTaskPrio = 9;
initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
initParam.pcName = "SendQueue";
LOS_TaskLock(); LOS_TaskLock();
ret = LOS_TaskCreate(&task1, &initParam);
taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry;
taskParam1.usTaskPrio = 9;
taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
taskParam1.pcName = "SendQueue";
ret = LOS_TaskCreate(&task1, &taskParam1);
if(ret != LOS_OK) { if(ret != LOS_OK) {
printf("create task1 failed, error: %x\n", ret); printf("create task1 failed, error: %x\n", ret);
return ret; return ret;
} }
initParam.pcName = "RecvQueue"; taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry;
initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; taskParam2.usTaskPrio = 10;
initParam.usTaskPrio = 10; taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
ret = LOS_TaskCreate(&task2, &initParam); taskParam2.pcName = "RecvQueue";
ret = LOS_TaskCreate(&task2, &taskParam2);
if(ret != LOS_OK) { if(ret != LOS_OK) {
printf("create task2 failed, error: %x\n", ret); printf("create task2 failed, error: %x\n", ret);
return ret; return ret;
...@@ -227,7 +229,7 @@ UINT32 ExampleQueue(VOID) ...@@ -227,7 +229,7 @@ UINT32 ExampleQueue(VOID)
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
start queue example. start queue example.
create the queue success. create the queue success.
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
- 正值,表示该信号量当前可被获取。 - 正值,表示该信号量当前可被获取。
以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: 信号量可用于同步或者互斥。以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同:
- 用作互斥时,初始信号量计数值不为0,表示可用的共享资源个数。在需要使用共享资源前,先获取信号量,然后使用一个共享资源,使用完毕后释放信号量。这样在共享资源被取完,即信号量计数减至0时,其他需要获取信号量的任务将被阻塞,从而保证了共享资源的互斥访问。另外,当共享资源数为1时,建议使用二值信号量,一种类似于互斥锁的机制。 - 用作互斥时,初始信号量计数值不为0,表示可用的共享资源个数。在需要使用共享资源前,先获取信号量,然后使用一个共享资源,使用完毕后释放信号量。这样在共享资源被取完,即信号量计数减至0时,其他需要获取信号量的任务将被阻塞,从而保证了共享资源的互斥访问。另外,当共享资源数为1时,建议使用二值信号量,一种类似于互斥锁的机制。
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
### 信号量控制块 ### 信号量控制块
``` ```
/** /**
* 信号量控制块数据结构 * 信号量控制块数据结构
...@@ -40,7 +40,7 @@ typedef struct { ...@@ -40,7 +40,7 @@ typedef struct {
### 信号量运作原理 ### 信号量运作原理
信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现,按产品实际需要设定),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。
信号量创建,从未使用的信号量链表中获取一个信号量,并设定初值。 信号量创建,从未使用的信号量链表中获取一个信号量,并设定初值。
...@@ -58,10 +58,10 @@ typedef struct { ...@@ -58,10 +58,10 @@ typedef struct {
## 接口说明 ## 接口说明
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 创建/删除信号量 | -&nbsp;LOS_SemCreate:创建信号量,返回信号量ID<br/>-&nbsp;LOS_BinarySemCreate:创建二值信号量,其计数值最大为1<br/>-&nbsp;LOS_SemDelete:删除指定的信号量 | | 创建/删除信号量 | &nbsp;LOS_SemCreate:创建信号量,返回信号量ID。<br/>&nbsp;LOS_BinarySemCreate:创建二值信号量,其计数值最大为1。<br/>&nbsp;LOS_SemDelete:删除指定的信号量。 |
| 申请/释放信号量 | -&nbsp;LOS_SemPend:申请指定的信号量,并设置超时时间<br/>-&nbsp;LOS_SemPost:释放指定的信号量 | | 申请/释放信号量 | &nbsp;LOS_SemPend:申请指定的信号量,并设置超时时间。<br/>&nbsp;LOS_SemPost:释放指定的信号量。 |
## 开发流程 ## 开发流程
...@@ -101,17 +101,11 @@ typedef struct { ...@@ -101,17 +101,11 @@ typedef struct {
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSem。
```
#include "los_sem.h"
#include "securec.h"
/* 任务ID */
static UINT32 g_testTaskId01;
static UINT32 g_testTaskId02;
/* 测试任务优先级 */ ```
#define TASK_PRIO_TEST 5 #include "los_sem.h"
/* 信号量结构体id */ /* 信号量结构体id */
static UINT32 g_semId; static UINT32 g_semId;
...@@ -121,19 +115,17 @@ VOID ExampleSemTask1(VOID) ...@@ -121,19 +115,17 @@ VOID ExampleSemTask1(VOID)
UINT32 ret; UINT32 ret;
printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n");
/* 定时阻塞模式申请信号量,定时时间为10ticks */ /* 定时阻塞模式申请信号量,定时时间为10ticks */
ret = LOS_SemPend(g_semId, 10); ret = LOS_SemPend(g_semId, 10);
/* 申请到信号量 */ /* 申请到信号量 */
if (ret == LOS_OK) { if (ret == LOS_OK) {
LOS_SemPost(g_semId); LOS_SemPost(g_semId);
return; return;
} }
/* 定时时间到,未申请到信号量 */ /* 定时时间到,未申请到信号量 */
if (ret == LOS_ERRNO_SEM_TIMEOUT) { if (ret == LOS_ERRNO_SEM_TIMEOUT) {
printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n");
/*永久阻塞模式申请信号量*/ /*永久阻塞模式申请信号量*/
ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER);
printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); printf("ExampleSemTask1 wait_forever and get sem g_semId.\n");
...@@ -151,15 +143,14 @@ VOID ExampleSemTask2(VOID) ...@@ -151,15 +143,14 @@ VOID ExampleSemTask2(VOID)
/* 永久阻塞模式申请信号量 */ /* 永久阻塞模式申请信号量 */
ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER);
if (ret == LOS_OK) { if (ret == LOS_OK) {
printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n");
} }
/* 任务休眠20 ticks */ /* 任务休眠20 ticks */
LOS_TaskDelay(20); LOS_TaskDelay(20);
printf("ExampleSemTask2 post sem g_semId.\n"); printf("ExampleSemTask2 post sem g_semId.\n");
/* 释放信号量 */ /* 释放信号量 */
LOS_SemPost(g_semId); LOS_SemPost(g_semId);
return; return;
...@@ -168,8 +159,10 @@ VOID ExampleSemTask2(VOID) ...@@ -168,8 +159,10 @@ VOID ExampleSemTask2(VOID)
UINT32 ExampleSem(VOID) UINT32 ExampleSem(VOID)
{ {
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S task1 = { 0 };
TSK_INIT_PARAM_S task2; TSK_INIT_PARAM_S task2 = { 0 };
UINT32 taskId1;
UINT32 taskId2;
/* 创建信号量 */ /* 创建信号量 */
LOS_SemCreate(0, &g_semId); LOS_SemCreate(0, &g_semId);
...@@ -178,24 +171,22 @@ UINT32 ExampleSem(VOID) ...@@ -178,24 +171,22 @@ UINT32 ExampleSem(VOID)
LOS_TaskLock(); LOS_TaskLock();
/* 创建任务1 */ /* 创建任务1 */
(VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S));
task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1;
task1.pcName = "TestTask1"; task1.pcName = "TestTask1";
task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
task1.usTaskPrio = TASK_PRIO_TEST; task1.usTaskPrio = 5;
ret = LOS_TaskCreate(&g_testTaskId01, &task1); ret = LOS_TaskCreate(&taskId1, &task1);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task1 create failed.\n"); printf("task1 create failed.\n");
return LOS_NOK; return LOS_NOK;
} }
/* 创建任务2 */ /* 创建任务2 */
(VOID)memset_s(&task2, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S));
task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2;
task2.pcName = "TestTask2"; task2.pcName = "TestTask2";
task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
task2.usTaskPrio = (TASK_PRIO_TEST - 1); task2.usTaskPrio = 4;
ret = LOS_TaskCreate(&g_testTaskId02, &task2); ret = LOS_TaskCreate(&taskId2, &task2);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("task2 create failed.\n"); printf("task2 create failed.\n");
return LOS_NOK; return LOS_NOK;
...@@ -221,12 +212,11 @@ UINT32 ExampleSem(VOID) ...@@ -221,12 +212,11 @@ UINT32 ExampleSem(VOID)
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
ExampleSemTask2 try get sem g_semId wait forever. ExampleSemTask2 try get sem g_semId wait forever.
ExampleSemTask2 get sem g_semId and then delay 20 ticks.
ExampleSemTask1 try get sem g_semId, timeout 10 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks.
ExampleSemTask2 get sem g_semId and then delay 20 ticks.
ExampleSemTask1 timeout and try get sem g_semId wait forever. ExampleSemTask1 timeout and try get sem g_semId wait forever.
ExampleSemTask2 post sem g_semId. ExampleSemTask2 post sem g_semId.
ExampleSemTask1 wait_forever and get sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId.
......
...@@ -12,16 +12,16 @@ ...@@ -12,16 +12,16 @@
双向链表模块为用户提供下面几种功能,接口详细信息可以查看API参考。 双向链表模块为用户提供下面几种功能,接口详细信息可以查看API参考。
| | | | | |
| -------- | -------- | | -------- | -------- |
| **功能分类** | **接口描述** | | **功能分类** | **接口描述** |
| 初始化链表 | -&nbsp;LOS_ListInit:将指定双向链表节点初始化为双向链表<br/>-&nbsp;LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表 | | 初始化和删除链表 | &nbsp;LOS_ListInit:将指定双向链表节点初始化为双向链表。<br/>&nbsp;LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表。<br/> LOS_ListDelInit:删除指定的双向链表。 |
| 增加节点 | -&nbsp;LOS_ListAdd:将指定节点插入到双向链表头端<br/>-&nbsp;LOS_ListTailInsert:将指定节点插入到双向链表尾端 | | 增加节点 | &nbsp;LOS_ListAdd:将指定节点插入到双向链表头端。<br/>&nbsp;LOS_ListTailInsert:将指定节点插入到双向链表尾端。 |
| 删除节点 | -&nbsp;LOS_ListDelete:将指定节点从链表中删除<br/>-&nbsp;LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 | | 删除节点 | &nbsp;LOS_ListDelete:将指定节点从链表中删除。<br/>&nbsp;LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表。 |
| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空 | | 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空。 |
| 获取结构体信息 | -&nbsp;LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称<br/>-&nbsp;LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量 | | 获取结构体信息 | &nbsp;LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。<br/>&nbsp;LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量。 |
| 遍历双向链表 | -&nbsp;LOS_DL_LIST_FOR_EACH:遍历双向链表<br/>-&nbsp;LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 | | 遍历双向链表 | &nbsp;LOS_DL_LIST_FOR_EACH:遍历双向链表。<br/>&nbsp;LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验。 |
| 遍历包含双向链表的结构体 | -&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址<br/>-&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 | | 遍历包含双向链表的结构体 | &nbsp;LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址。<br/>&nbsp;LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址。 |
## 开发流程 ## 开发流程
...@@ -69,22 +69,24 @@ ...@@ -69,22 +69,24 @@
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleList。
``` ```
#include "stdio.h" #include "stdio.h"
#include "los_list.h" #include "los_list.h"
static UINT32 ListSample(VOID) STATIC UINT32 ExampleList(VOID)
{ {
LOS_DL_LIST listHead = {NULL,NULL}; LOS_DL_LIST listHead = {NULL,NULL};
LOS_DL_LIST listNode1 = {NULL,NULL}; LOS_DL_LIST listNode1 = {NULL,NULL};
LOS_DL_LIST listNode2 = {NULL,NULL}; LOS_DL_LIST listNode2 = {NULL,NULL};
//首先初始化链表 /* 初始化链表 */
printf("Initial head\n"); printf("Initial head\n");
LOS_ListInit(&listHead); LOS_ListInit(&listHead);
//添加节点1和节点2,并校验他们的相互关系 /* 添加节点1和节点2,并校验他们的相互关系 */
LOS_ListAdd(&listHead, &listNode1); LOS_ListAdd(&listHead, &listNode1);
if (listNode1.pstNext == &listHead && listNode1.pstPrev == &listHead) { if (listNode1.pstNext == &listHead && listNode1.pstPrev == &listHead) {
printf("Add listNode1 success\n"); printf("Add listNode1 success\n");
...@@ -95,11 +97,11 @@ static UINT32 ListSample(VOID) ...@@ -95,11 +97,11 @@ static UINT32 ListSample(VOID)
printf("Tail insert listNode2 success\n"); printf("Tail insert listNode2 success\n");
} }
//删除两个节点 /* 删除两个节点 */
LOS_ListDelete(&listNode1); LOS_ListDelete(&listNode1);
LOS_ListDelete(&listNode2); LOS_ListDelete(&listNode2);
//确认链表为空 /* 确认链表为空 */
if (LOS_ListEmpty(&listHead)) { if (LOS_ListEmpty(&listHead)) {
printf("Delete success\n"); printf("Delete success\n");
} }
...@@ -113,7 +115,7 @@ static UINT32 ListSample(VOID) ...@@ -113,7 +115,7 @@ static UINT32 ListSample(VOID)
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
Initial head Initial head
Add listNode1 success Add listNode1 success
......
...@@ -45,12 +45,12 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 ...@@ -45,12 +45,12 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接
**表1** 静态内存模块接口 **表1** 静态内存模块接口
| 功能分类 | 接口名 | | 功能分类 | 接口名 |
| -------- | -------- | | -------- | -------- |
| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | | 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 |
| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | | 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 |
| 申请、释放静态内存 | -&nbsp;LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。<br/>-&nbsp;LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | | 申请、释放静态内存 | &nbsp;LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。<br/>&nbsp;LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 |
| 获取、打印静态内存池信息 | -&nbsp;LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。<br/>-&nbsp;LOS_ShowBox:打印指定静态内存池所有节点信息(打印等级是LOS_INFO_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | | 获取、打印静态内存池信息 | &nbsp;LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。<br/>&nbsp;LOS_ShowBox:打印指定静态内存池所有节点信息,打印等级是LOG_INFO_LEVEL(当前打印等级配置是PRINT_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。 > 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。
...@@ -91,21 +91,26 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 ...@@ -91,21 +91,26 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接
6. 释放该内存块。 6. 释放该内存块。
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleStaticMem。
``` ```
#include "los_membox.h" #include "los_membox.h"
VOID Example_StaticMem(VOID) #define MEMBOX_POOL_SIZE 100
#define MEMBOX_BLOCK_SZIE 10
#define MEMBOX_WR_TEST_NUM 828
VOID ExampleStaticMem(VOID)
{ {
UINT32 *mem = NULL; UINT32 *mem = NULL;
UINT32 blkSize = 10; UINT32 blkSize = MEMBOX_BLOCK_SZIE;
UINT32 boxSize = 100; UINT32 poolSize = MEMBOX_POOL_SIZE;
UINT32 boxMem[1000]; UINT32 boxMem[MEMBOX_POOL_SIZE];
UINT32 ret; UINT32 ret;
/*内存池初始化*/ /* 内存池初始化 */
ret = LOS_MemboxInit(&boxMem[0], boxSize, blkSize); ret = LOS_MemboxInit(&boxMem[0], poolSize, blkSize);
if(ret != LOS_OK) { if(ret != LOS_OK) {
printf("Membox init failed!\n"); printf("Membox init failed!\n");
return; return;
...@@ -113,23 +118,23 @@ VOID Example_StaticMem(VOID) ...@@ -113,23 +118,23 @@ VOID Example_StaticMem(VOID)
printf("Membox init success!\n"); printf("Membox init success!\n");
} }
/*申请内存块*/ /* 申请内存块 */
mem = (UINT32 *)LOS_MemboxAlloc(boxMem); mem = (UINT32 *)LOS_MemboxAlloc(boxMem);
if (NULL == mem) { if (mem == NULL) {
printf("Mem alloc failed!\n"); printf("Mem alloc failed!\n");
return; return;
} }
printf("Mem alloc success!\n"); printf("Mem alloc success!\n");
/*赋值*/ /* 内存地址读写验证 */
*mem = 828; *mem = MEMBOX_WR_TEST_NUM;
printf("*mem = %d\n", *mem); printf("*mem = %d\n", *mem);
/*清除内存内容*/ /* 清除内存内容 */
LOS_MemboxClr(boxMem, mem); LOS_MemboxClr(boxMem, mem);
printf("Mem clear success \n *mem = %d\n", *mem); printf("Mem clear success \n*mem = %d\n", *mem);
/*释放内存*/ /* 释放内存 */
ret = LOS_MemboxFree(boxMem, mem); ret = LOS_MemboxFree(boxMem, mem);
if (LOS_OK == ret) { if (LOS_OK == ret) {
printf("Mem free success!\n"); printf("Mem free success!\n");
...@@ -139,6 +144,7 @@ VOID Example_StaticMem(VOID) ...@@ -139,6 +144,7 @@ VOID Example_StaticMem(VOID)
return; return;
} }
``` ```
...@@ -146,7 +152,7 @@ VOID Example_StaticMem(VOID) ...@@ -146,7 +152,7 @@ VOID Example_StaticMem(VOID)
输出结果如下: 输出结果如下:
``` ```
Membox init success! Membox init success!
Mem alloc success! Mem alloc success!
...@@ -197,7 +203,7 @@ OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分 ...@@ -197,7 +203,7 @@ OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分
2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。 2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。
3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize+ OS_MEM_NODE_HEAD_SIZE 3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize + OS_MEM_NODE_HEAD_SIZE(即sizeof(struct OsMemUsedNodeHead))
4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。 4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。
...@@ -218,14 +224,14 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 ...@@ -218,14 +224,14 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接
**表1** 动态内存模块接口 **表1** 动态内存模块接口
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 初始化和删除内存池 | -&nbsp;LOS_MemInit:初始化一块指定的动态内存池,大小为size。<br/>-&nbsp;LOS_MemDeInit:删除指定内存池,仅打开LOSCFG_MEM_MUL_POOL时有效。 | | 初始化和删除内存池 | &nbsp;LOS_MemInit:初始化一块指定的动态内存池,大小为size。<br/>&nbsp;LOS_MemDeInit:删除指定内存池,仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 |
| 申请、释放动态内存 | -&nbsp;LOS_MemAlloc:从指定动态内存池中申请size长度的内存。<br/>-&nbsp;LOS_MemFree:释放从指定动态内存中申请的内存。<br/>-&nbsp;LOS_MemRealloc:释放从指定动态内存中申请的内存。 | | 申请、释放动态内存 | &nbsp;LOS_MemAlloc:从指定动态内存池中申请size长度的内存。<br/>&nbsp;LOS_MemFree:释放从指定动态内存中申请的内存。<br/>&nbsp;LOS_MemRealloc:释放从指定动态内存中申请的内存。 |
| 获取内存池信息 | -&nbsp;LOS_MemPoolSizeGet:获取指定动态内存池的总大小。<br/>-&nbsp;LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。<br/>-&nbsp;LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。<br/>-&nbsp;LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开LOSCFG_MEM_MUL_POOL时有效。 | | 获取内存池信息 | &nbsp;LOS_MemPoolSizeGet:获取指定动态内存池的总大小。<br/>&nbsp;LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。<br/>&nbsp;LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。<br/>&nbsp;LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 |
| 获取内存块信息 | -&nbsp;LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。<br/>-&nbsp;LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | | 获取内存块信息 | &nbsp;LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。<br/>&nbsp;LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 |
| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | | 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开编译控制开关LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 |
| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | | 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。 > - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。
...@@ -265,18 +271,24 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 ...@@ -265,18 +271,24 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接
示例代码如下: 示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleDynMem。
``` ```
#include "los_memory.h" #include "los_memory.h"
#define TEST_POOL_SIZE (2*1024) #define TEST_POOL_SIZE (2*1024)
__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE]; #define MEMBOX_WR_TEST_NUM 828
VOID Example_DynMem(VOID)
__attribute__((aligned(4))) UINT8 g_testDynPool[TEST_POOL_SIZE];
VOID ExampleDynMem(VOID)
{ {
UINT32 *mem = NULL; UINT32 *mem = NULL;
UINT32 ret; UINT32 ret;
/*初始化内存池*/ /* 初始化内存池 */
ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE); ret = LOS_MemInit(g_testDynPool, TEST_POOL_SIZE);
if (LOS_OK == ret) { if (LOS_OK == ret) {
printf("Mem init success!\n"); printf("Mem init success!\n");
} else { } else {
...@@ -284,20 +296,20 @@ VOID Example_DynMem(VOID) ...@@ -284,20 +296,20 @@ VOID Example_DynMem(VOID)
return; return;
} }
/*分配内存*/ /* 申请内存块 */
mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4); mem = (UINT32 *)LOS_MemAlloc(g_testDynPool, 4);
if (NULL == mem) { if (mem == NULL) {
printf("Mem alloc failed!\n"); printf("Mem alloc failed!\n");
return; return;
} }
printf("Mem alloc success!\n"); printf("Mem alloc success!\n");
/*赋值*/ /* 内存地址读写验证 */
*mem = 828; *mem = MEMBOX_WR_TEST_NUM;
printf("*mem = %d\n", *mem); printf("*mem = %d\n", *mem);
/*释放内存*/ /* 释放内存 */
ret = LOS_MemFree(g_testPool, mem); ret = LOS_MemFree(g_testDynPool, mem);
if (LOS_OK == ret) { if (LOS_OK == ret) {
printf("Mem free success!\n"); printf("Mem free success!\n");
} else { } else {
...@@ -313,7 +325,7 @@ VOID Example_DynMem(VOID) ...@@ -313,7 +325,7 @@ VOID Example_DynMem(VOID)
输出结果如下: 输出结果如下:
``` ```
Mem init success! Mem init success!
Mem alloc success! Mem alloc success!
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
## 运行机制 ## 运行机制
软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置。 软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置,该值按产品实际需要设定
软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。 软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。
...@@ -64,11 +64,11 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 ...@@ -64,11 +64,11 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接
**表1** 软件定时器接口 **表1** 软件定时器接口
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 创建、删除定时器 | -&nbsp;LOS_SwtmrCreate:创建定时器<br/>-&nbsp;LOS_SwtmrDelete:删除定时器 | | 创建、删除定时器 | -&nbsp;LOS_SwtmrCreate:创建定时器<br/>-&nbsp;LOS_SwtmrDelete:删除定时器。 |
| 启动、停止定时器 | -&nbsp;LOS_SwtmrStart:启动定时器<br/>-&nbsp;LOS_SwtmrStop:停止定时器 | | 启动、停止定时器 | -&nbsp;LOS_SwtmrStart:启动定时器<br/>-&nbsp;LOS_SwtmrStop:停止定时器。 |
| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数 | | 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数。 |
## 开发流程 ## 开发流程
...@@ -130,86 +130,107 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 ...@@ -130,86 +130,107 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接
代码实现如下: 代码实现如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSwtmr。
``` ```
#include "los_swtmr.h" #include "los_swtmr.h"
/* Timer count */ /* 定时器间隔时间 */
UINT32 g_timerCount1 = 0; #define SWTMR_INTERVAL_LONG 1000
UINT32 g_timerCount2 = 0; #define SWTMR_INTERVAL_SHORT 100
/* 任务ID */ /* 定时器触发次数计数 */
UINT32 g_testTaskId01; UINT32 g_timerCount1 = 0;
UINT32 g_timerCount2 = 0;
void Timer1_Callback(UINT32 arg) // 回调函数1 /* 回调函数1,单次触发定时器的回调函数 */
void Timer1Callback(UINT32 arg)
{ {
UINT32 tick_last1;
g_timerCount1++; g_timerCount1++;
tick_last1 = (UINT32)LOS_TickCountGet(); // 获取当前Tick数 printf("g_timerCount1=%d\n", g_timerCount1);
printf("g_timerCount1=%d, tick_last1=%d\n", g_timerCount1, tick_last1); }
}
void Timer2_Callback(UINT32 arg) // 回调函数2 /* 回调函数2,多次触发定时器的回调函数 */
void Timer2Callback(UINT32 arg)
{ {
UINT32 tick_last2;
tick_last2 = (UINT32)LOS_TickCountGet();
g_timerCount2++; g_timerCount2++;
printf("g_timerCount2=%d tick_last2=%d\n", g_timerCount2, tick_last2); printf("g_timerCount2=%d\n", g_timerCount2);
} }
void Timer_example(void) void SwtmrTest(void)
{ {
UINT32 ret; UINT32 ret;
UINT32 id1; // timer id1 UINT32 id1; // 定时器id1,单次触发定时器
UINT32 id2; // timer id2 UINT32 id2; // 定时器id2,周期触发定时器
UINT32 tickCount; UINT32 tickCount;
/*创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ #if (LOSCFG_BASE_CORE_SWTMR_ALIGN == 1)
LOS_SwtmrCreate(1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1); /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */
LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0,
OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE);
/*创建周期性软件定时器,每100Tick数执行回调函数2 */ /* 创建周期性软件定时器,每100Tick数执行回调函数2 */
LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1); LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0,
printf("create Timer1 success\n"); OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE);
#else
/* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */
LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0);
LOS_SwtmrStart(id1); //启动单次软件定时器 /* 创建周期性软件定时器,每100Tick数执行回调函数2 */
printf("start Timer1 success\n"); LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0);
#endif
LOS_TaskDelay(200); //延时200Tick数 /* 启动单次软件定时器 */
LOS_SwtmrTimeGet(id1, &tickCount); // 获得单次软件定时器剩余Tick数 ret = LOS_SwtmrStart(id1);
printf("tickCount=%d\n", tickCount); printf("start Timer1 %s\n", (ret == LOS_OK) ? "success" : "failed");
LOS_SwtmrStop(id1); // 停止软件定时器 /* 短时间延时,定时器还未触发 */
printf("stop Timer1 success\n"); LOS_TaskDelay(SWTMR_INTERVAL_SHORT);
/* 单次定时器还未到时间触发,此时停止应该成功 */
ret = LOS_SwtmrStop(id1);
printf("stop timer1 %s\n", (ret == LOS_OK) ? "success" : "failed");
LOS_SwtmrStart(id1); LOS_SwtmrStart(id1);
LOS_TaskDelay(1000);
/* 长时间延时,定时器触发 */
LOS_TaskDelay(SWTMR_INTERVAL_LONG);
/* 单次定时器触发后自删除,此时停止失败才是正常 */
ret = LOS_SwtmrStop(id1);
printf("timer1 self delete test %s\n", (ret != LOS_OK) ? "success" : "failed");
/* 启动周期性软件定时器 */
ret = LOS_SwtmrStart(id2);
printf("start Timer2 %s\n", (ret == LOS_OK) ? "success" : "failed");
LOS_SwtmrStart(id2); // 启动周期性软件定时器 /* 长时间延时,定时器周期触发 */
printf("start Timer2\n"); LOS_TaskDelay(SWTMR_INTERVAL_LONG);
LOS_TaskDelay(1000);
LOS_SwtmrStop(id2); LOS_SwtmrStop(id2);
ret = LOS_SwtmrDelete(id2); // 删除软件定时器
ret = LOS_SwtmrDelete(id2);
if (ret == LOS_OK) { if (ret == LOS_OK) {
printf("delete Timer2 success\n"); printf("delete Timer2 success\n");
} }
} }
UINT32 Example_TaskEntry(VOID) UINT32 ExampleSwtmr(VOID)
{ {
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S taskParam = { 0 };
UINT32 taskId;
/* 锁任务调度 */ /* 锁任务调度 */
LOS_TaskLock(); LOS_TaskLock();
/* 创建任务1 */ /* 创建任务 */
(VOID)memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SwtmrTest;
task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Timer_example; taskParam.pcName = "TimerTsk";
task1.pcName = "TimerTsk"; taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; taskParam.usTaskPrio = 5;
task1.usTaskPrio = 5; ret = LOS_TaskCreate(&taskId, &taskParam);
ret = LOS_TaskCreate(&g_testTaskId01, &task1);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("TimerTsk create failed.\n"); printf("TimerTsk create failed.\n");
return LOS_NOK; return LOS_NOK;
...@@ -217,7 +238,6 @@ UINT32 Example_TaskEntry(VOID) ...@@ -217,7 +238,6 @@ UINT32 Example_TaskEntry(VOID)
/* 解锁任务调度 */ /* 解锁任务调度 */
LOS_TaskUnlock(); LOS_TaskUnlock();
return LOS_OK; return LOS_OK;
} }
``` ```
...@@ -227,24 +247,22 @@ UINT32 Example_TaskEntry(VOID) ...@@ -227,24 +247,22 @@ UINT32 Example_TaskEntry(VOID)
编译烧录运行,输出结果如下: 编译烧录运行,输出结果如下:
``` ```
create Timer1 success
start Timer1 success start Timer1 success
tickCount=798 stop timer1 success
stop Timer1 success g_timerCount1=1
g_timerCount1=1, tick_last1=1208 timer1 self delete test success
delete Timer1 success start Timer2 success
start Timer2 g_timerCount2=1
g_timerCount2=1 tick_last2=1313 g_timerCount2=2
g_timerCount2=2 tick_last2=1413 g_timerCount2=3
g_timerCount2=3 tick_last2=1513 g_timerCount2=4
g_timerCount2=4 tick_last2=1613 g_timerCount2=5
g_timerCount2=5 tick_last2=1713 g_timerCount2=6
g_timerCount2=6 tick_last2=1813 g_timerCount2=7
g_timerCount2=7 tick_last2=1913 g_timerCount2=8
g_timerCount2=8 tick_last2=2013 g_timerCount2=9
g_timerCount2=9 tick_last2=2113 g_timerCount2=10
g_timerCount2=10 tick_last2=2213
delete Timer2 success delete Timer2 success
``` ```
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 基本概念 ## 基本概念
从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,并独立于其它任务运行 从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,各任务的运行相互独立
OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任务间的切换,帮助用户管理业务程序流程。任务模块具有如下特性: OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任务间的切换,帮助用户管理业务程序流程。任务模块具有如下特性:
...@@ -40,7 +40,9 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ...@@ -40,7 +40,9 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任
![zh-cn_image_0000001200612002](figures/zh-cn_image_0000001200612002.png) ![zh-cn_image_0000001200612002](figures/zh-cn_image_0000001200612002.png)
**任务状态迁移说明:** 系统会同时存在多个任务,因此就绪态和阻塞态的任务分别会加入就绪队列和阻塞队列。队列只是相同状态任务的合集,加入队列的先后与任务状态迁移的顺序无关。运行态任务仅存在一个,不存在运行态队列。
**任务状态迁移说明**
- 就绪态→运行态 - 就绪态→运行态
任务创建后进入就绪态,发生任务切换时,就绪队列中最高优先级的任务被执行,从而进入运行态,同时该任务从就绪队列中移出。 任务创建后进入就绪态,发生任务切换时,就绪队列中最高优先级的任务被执行,从而进入运行态,同时该任务从就绪队列中移出。
...@@ -48,11 +50,11 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ...@@ -48,11 +50,11 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任
- 运行态→阻塞态 - 运行态→阻塞态
正在运行的任务发生阻塞(挂起、延时、读信号量等)时,将该任务插入到对应的阻塞队列中,任务状态由运行态变成阻塞态,然后发生任务切换,运行就绪队列中最高优先级任务。 正在运行的任务发生阻塞(挂起、延时、读信号量等)时,将该任务插入到对应的阻塞队列中,任务状态由运行态变成阻塞态,然后发生任务切换,运行就绪队列中最高优先级任务。
- 阻塞态→就绪态(阻塞态→运行态) - 阻塞态→就绪态(阻塞态→运行态的前置条件
阻塞的任务被恢复后(任务恢复、延时时间超时、读信号量超时或读到信号量等),此时被恢复的任务会被加入就绪队列,从而由阻塞态变成就绪态;此时如果被恢复任务的优先级高于正在运行任务的优先级,则会发生任务切换,该任务由就绪态变成运行态。 阻塞的任务被恢复后(任务恢复、延时时间超时、读信号量超时或读到信号量等),此时被恢复的任务会被加入就绪队列,从而由阻塞态变成就绪态;此时如果被恢复任务的优先级高于正在运行任务的优先级,则会发生任务切换,该任务由就绪态变成运行态。
- 就绪态→阻塞态 - 就绪态→阻塞态
任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中删除,不会参与任务调度,直到该任务被恢复。 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中移出,不会参与任务调度,直到该任务被恢复。
- 运行态→就绪态 - 运行态→就绪态
有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪队列中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,依然在就绪队列中。 有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪队列中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,依然在就绪队列中。
...@@ -65,7 +67,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ...@@ -65,7 +67,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任
**任务ID** **任务ID**
任务ID,在任务创建时通过参数返回给用户,是任务的重要标识。系统中的ID号是唯一的。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 在任务创建时通过参数返回给用户。系统中任务ID号是唯一的,是任务的重要标识。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。
**任务优先级** **任务优先级**
...@@ -83,7 +85,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ...@@ -83,7 +85,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任
任务在运行过程中使用的一些资源,如寄存器等,称为任务上下文。当这个任务挂起时,其他任务继续执行,可能会修改寄存器等资源中的值。如果任务切换时没有保存任务上下文,可能会导致任务恢复后出现未知错误。因此在任务切换时会将切出任务的任务上下文信息,保存在自身的任务栈中,以便任务恢复后,从栈空间中恢复挂起时的上下文信息,从而继续执行挂起时被打断的代码。 任务在运行过程中使用的一些资源,如寄存器等,称为任务上下文。当这个任务挂起时,其他任务继续执行,可能会修改寄存器等资源中的值。如果任务切换时没有保存任务上下文,可能会导致任务恢复后出现未知错误。因此在任务切换时会将切出任务的任务上下文信息,保存在自身的任务栈中,以便任务恢复后,从栈空间中恢复挂起时的上下文信息,从而继续执行挂起时被打断的代码。
**任务控制块TCB** **任务控制块(TCB)**
每个任务都含有一个任务控制块(TCB)。TCB包含了任务上下文栈指针(stack pointer)、任务状态、任务优先级、任务ID、任务名、任务栈大小等信息。TCB可以反映出每个任务运行情况。 每个任务都含有一个任务控制块(TCB)。TCB包含了任务上下文栈指针(stack pointer)、任务状态、任务优先级、任务ID、任务名、任务栈大小等信息。TCB可以反映出每个任务运行情况。
...@@ -103,15 +105,14 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 ...@@ -103,15 +105,14 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口
**表1** 任务管理模块接口 **表1** 任务管理模块接口
| 功能分类 | 接口描述 | | 功能分类 | 接口描述 |
| -------- | -------- | | -------- | -------- |
| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。<br/>LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。<br/>LOS_TaskDelete:删除指定的任务。 | | 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入suspend状态。<br/>LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。<br/>LOS_TaskDelete:删除指定的任务。 |
| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。<br/>LOS_TaskSuspend:挂起指定的任务,然后切换任务。<br/>LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源<br/>LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。<br/>LOS_Msleep:传入参数为毫秒数,转换为Tick数目,调用LOS_TaskDelay。<br/>LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | | 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。<br/>LOS_TaskSuspend:挂起指定的任务,然后切换任务。<br/>LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源<br/>LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。<br/>LOS_Msleep:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为毫秒数。<br/>LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 |
| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。<br/>LOS_TaskUnlock:解锁任务调度。<br/>LOS_Schedule:触发任务调度。 | | 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。<br/>LOS_TaskUnlock:解锁任务调度。<br/>LOS_Schedule:触发任务调度。 |
| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。<br/>LOS_TaskPriSet:设置指定任务的优先级。<br/>LOS_TaskPriGet:获取指定任务的优先级。 | | 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。<br/>LOS_TaskPriSet:设置指定任务的优先级。<br/>LOS_TaskPriGet:获取指定任务的优先级。 |
| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。<br/>LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。<br/>LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。<br/>LOS_CurTaskNameGet:获取当前任务的名称。<br/>LOS_TaskNameGet:获取指定任务的名称。<br/>LOS_TaskStatusGet:获取指定任务的状态。<br/>LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。<br/>LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | | 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。<br/>LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。<br/>LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。<br/>LOS_CurTaskNameGet:获取当前任务的名称。<br/>LOS_TaskNameGet:获取指定任务的名称。<br/>LOS_TaskStatusGet:获取指定任务的状态。<br/>LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。<br/>LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 |
| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启宏LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | | 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启编译控制宏:LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 |
## 开发流程 ## 开发流程
...@@ -161,20 +162,24 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 ...@@ -161,20 +162,24 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口
本实例介绍基本的任务操作方法,包含2个不同优先级任务的创建、任务延时、任务锁与解锁调度、挂起和恢复等操作,阐述任务优先级调度的机制以及各接口的应用。示例代码如下: 本实例介绍基本的任务操作方法,包含2个不同优先级任务的创建、任务延时、任务锁与解锁调度、挂起和恢复等操作,阐述任务优先级调度的机制以及各接口的应用。示例代码如下:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTask。
``` ```
#include "los_task.h"
UINT32 g_taskHiId; UINT32 g_taskHiId;
UINT32 g_taskLoId; UINT32 g_taskLoId;
#define TSK_PRIOR_HI 4 #define TSK_PRIOR_HI 3 /* 高优先级任务的优先级 */
#define TSK_PRIOR_LO 5 #define TSK_PRIOR_LO 4 /* 低优先级任务的优先级 */
UINT32 Example_TaskHi(VOID) UINT32 ExampleTaskHi(VOID)
{ {
UINT32 ret; UINT32 ret;
printf("Enter TaskHi Handler.\n"); printf("Enter TaskHi Handler.\n");
/* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(TaskLo任务) */ /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(TaskLo任务) */
ret = LOS_TaskDelay(100); ret = LOS_TaskDelay(100);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("Delay TaskHi Failed.\n"); printf("Delay TaskHi Failed.\n");
...@@ -195,7 +200,7 @@ UINT32 Example_TaskHi(VOID) ...@@ -195,7 +200,7 @@ UINT32 Example_TaskHi(VOID)
} }
/* 低优先级任务入口函数 */ /* 低优先级任务入口函数 */
UINT32 Example_TaskLo(VOID) UINT32 ExampleTaskLo(VOID)
{ {
UINT32 ret; UINT32 ret;
...@@ -220,24 +225,25 @@ UINT32 Example_TaskLo(VOID) ...@@ -220,24 +225,25 @@ UINT32 Example_TaskLo(VOID)
} }
/* 任务测试入口函数,创建两个不同优先级的任务 */ /* 任务测试入口函数,创建两个不同优先级的任务 */
UINT32 Example_TskCaseEntry(VOID) UINT32 ExampleTask(VOID)
{ {
UINT32 ret; UINT32 ret;
TSK_INIT_PARAM_S initParam; TSK_INIT_PARAM_S taskParam1 = { 0 };
TSK_INIT_PARAM_S taskParam2 = { 0 };
/* 锁任务调度,防止新创建的任务比本任务高而发生调度 */ /* 锁任务调度,防止新创建的任务比本任务高而发生调度 */
LOS_TaskLock(); LOS_TaskLock();
printf("LOS_TaskLock() Success!\n"); printf("LOS_TaskLock() Success!\n");
initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskHi; taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi;
initParam.usTaskPrio = TSK_PRIOR_HI; taskParam1.usTaskPrio = TSK_PRIOR_HI;
initParam.pcName = "TaskHi"; taskParam1.pcName = "TaskHi";
initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
initParam.uwResved = 0; /* detach 属性 */ taskParam1.uwResved = LOS_TASK_ATTR_JOINABLE; /* detach 属性 */
/* 创建高优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ /* 创建高优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */
ret = LOS_TaskCreate(&g_taskHiId, &initParam); ret = LOS_TaskCreate(&g_taskHiId, &taskParam1);
if (ret != LOS_OK) { if (ret != LOS_OK) {
LOS_TaskUnlock(); LOS_TaskUnlock();
...@@ -247,13 +253,13 @@ UINT32 Example_TskCaseEntry(VOID) ...@@ -247,13 +253,13 @@ UINT32 Example_TskCaseEntry(VOID)
printf("Example_TaskHi create Success!\n"); printf("Example_TaskHi create Success!\n");
initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskLo; taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo;
initParam.usTaskPrio = TSK_PRIOR_LO; taskParam2.usTaskPrio = TSK_PRIOR_LO;
initParam.pcName = "TaskLo"; taskParam2.pcName = "TaskLo";
initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
/* 创建低优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ /* 创建低优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */
ret = LOS_TaskCreate(&g_taskLoId, &initParam); ret = LOS_TaskCreate(&g_taskLoId, &taskParam2);
if (ret != LOS_OK) { if (ret != LOS_OK) {
LOS_TaskUnlock(); LOS_TaskUnlock();
printf("Example_TaskLo create Failed!\n"); printf("Example_TaskLo create Failed!\n");
...@@ -266,7 +272,7 @@ UINT32 Example_TskCaseEntry(VOID) ...@@ -266,7 +272,7 @@ UINT32 Example_TskCaseEntry(VOID)
LOS_TaskUnlock(); LOS_TaskUnlock();
ret = LOS_TaskJoin(g_taskHiId, NULL); ret = LOS_TaskJoin(g_taskHiId, NULL);
if (ret != LOS_OK) { if (ret != LOS_OK) {
printf("Join Example_TaskHi Failed!\n"); printf("Join Example_TaskHi Failed!, 0x%x\n", ret);
} else { } else {
printf("Join Example_TaskHi Success!\n"); printf("Join Example_TaskHi Success!\n");
} }
...@@ -279,8 +285,8 @@ UINT32 Example_TskCaseEntry(VOID) ...@@ -279,8 +285,8 @@ UINT32 Example_TskCaseEntry(VOID)
编译运行得到的结果为: 编译运行得到的结果为:
``` ```
LOS_TaskLock() Success! LOS_TaskLock() Success!
Example_TaskHi create Success! Example_TaskHi create Success!
Example_TaskLo create Success! Example_TaskLo create Success!
......
...@@ -29,8 +29,8 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 ...@@ -29,8 +29,8 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| LOS_MS2Tick | 毫秒转换成Tick | | LOS_MS2Tick | 毫秒转换成Tick |
| LOS_Tick2MS | Tick转化为毫秒 | | LOS_Tick2MS | Tick转化为毫秒 |
| OsCpuTick2MS | Cycle数目转化为毫秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | | OsCpuTick2MS | Cycle数目转化为毫秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 |
| OsCpuTick2US | Cycle数目转化为微秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | | OsCpuTick2US | Cycle数目转化为微秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 |
...@@ -38,10 +38,23 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 ...@@ -38,10 +38,23 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| LOS_SysClockGet | 获取系统时钟 | | LOS_SysClockGet | 获取系统时钟。 |
| LOS_TickCountGet | 获取自系统启动以来的Tick数 | | LOS_TickCountGet | 获取自系统启动以来的Tick数。 |
| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数 | | LOS_CyclePerTickGet | 获取每个Tick多少Cycle数。 |
| LOS_CurrNanosec | 获取当前的时间,单位纳秒。 |
**表3** 时间注册
| 接口名 | 描述 |
| --------------------- | ---------------------------------------------- |
| LOS_TickTimerRegister | 重新注册系统时钟的定时器和对应的中断处理函数。 |
**表4** 延时
| 接口名 | 描述 |
| ---------- | ------------------------ |
| LOS_MDelay | 延时函数,延时单位毫秒。 |
| LOS_UDelay | 延时函数,延时单位微秒。 |
## 开发流程 ## 开发流程
...@@ -56,7 +69,7 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 ...@@ -56,7 +69,7 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细
> >
> - 系统的Tick数在关中断的情况下不进行计数,故系统Tick数不能作为准确时间使用。 > - 系统的Tick数在关中断的情况下不进行计数,故系统Tick数不能作为准确时间使用。
> >
> - 配置选项维护在开发板工程的文件target_config.h > - 上文描述的配置选项维护在开发板工程 target_config.h 中,部分配置项未定义的缺省值定义在内核 los_config.h中
## 编程实例 ## 编程实例
...@@ -81,17 +94,22 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 ...@@ -81,17 +94,22 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细
时间转换: 时间转换:
本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTransformTime和ExampleGetTime。
``` ```
VOID Example_TransformTime(VOID) VOID ExampleTransformTime(VOID)
{ {
UINT32 ms; UINT32 ms;
UINT32 tick; UINT32 tick;
tick = LOS_MS2Tick(10000); // 10000ms转换为tick /* 10000ms转换为tick */
dprintf("tick = %d \n", tick); tick = LOS_MS2Tick(10000);
ms = LOS_Tick2MS(100); // 100tick转换为ms printf("tick = %d \n", tick);
dprintf("ms = %d \n", ms);
/* 100tick转换为ms */
ms = LOS_Tick2MS(100);
printf("ms = %d \n", ms);
} }
``` ```
...@@ -99,26 +117,21 @@ VOID Example_TransformTime(VOID) ...@@ -99,26 +117,21 @@ VOID Example_TransformTime(VOID)
``` ```
VOID Example_GetTime(VOID) VOID ExampleGetTime(VOID)
{ {
UINT32 cyclePerTick; UINT32 cyclePerTick;
UINT64 tickCount; UINT64 tickCountBefore;
UINT64 tickCountAfter;
cyclePerTick = LOS_CyclePerTickGet(); cyclePerTick = LOS_CyclePerTickGet();
if(0 != cyclePerTick) { if (0 != cyclePerTick) {
dprintf("LOS_CyclePerTickGet = %d \n", cyclePerTick); printf("LOS_CyclePerTickGet = %d \n", cyclePerTick);
}
tickCount = LOS_TickCountGet();
if(0 != tickCount) {
dprintf("LOS_TickCountGet = %d \n", (UINT32)tickCount);
} }
tickCountBefore = LOS_TickCountGet();
LOS_TaskDelay(200); LOS_TaskDelay(200);
tickCount = LOS_TickCountGet(); tickCountAfter = LOS_TickCountGet();
if(0 != tickCount) { printf("LOS_TickCountGet after delay rising = %d \n", (UINT32)(tickCountAfter - tickCountBefore));
dprintf("LOS_TickCountGet after delay = %d \n", (UINT32)tickCount);
}
} }
``` ```
...@@ -138,8 +151,7 @@ ms = 1000 ...@@ -138,8 +151,7 @@ ms = 1000
时间统计和时间延迟: 时间统计和时间延迟:
``` ```
LOS_CyclePerTickGet = 495000 LOS_CyclePerTickGet = 250000 (根据实际运行环境,数据会有差异)
LOS_TickCountGet = 1 LOS_TickCountGet after delay rising = 200
LOS_TickCountGet after delay = 201
``` ```
...@@ -715,7 +715,7 @@ board_ld_flags :链接选项,与Makefile中的LDFLAGS变量对应。 ...@@ -715,7 +715,7 @@ board_ld_flags :链接选项,与Makefile中的LDFLAGS变量对应。
### 内核基础功能适配 ### 内核基础功能适配
内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)****[任务管理](../kernel/kernel-mini-basic-task.md)****[内存管理](../kernel/kernel-mini-basic-memory.md)****[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)****[时间管理](../kernel/kernel-basic-mini-time.md)****[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)****[任务管理](../kernel/kernel-mini-basic-task.md)****[内存管理](../kernel/kernel-mini-basic-memory.md)****[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)****[时间管理](../kernel/kernel-mini-basic-time.md)****[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。
从上一节中打印信息输出时间间隔可以看出,`LOS_TaskDelay`函数的延时时间不准确,我们可以在`target_config.h`中定义如下宏进行内核时钟适配: 从上一节中打印信息输出时间间隔可以看出,`LOS_TaskDelay`函数的延时时间不准确,我们可以在`target_config.h`中定义如下宏进行内核时钟适配:
......
...@@ -166,8 +166,9 @@ ...@@ -166,8 +166,9 @@
- [互斥锁](kernel/kernel-mini-basic-ipc-mutex.md) - [互斥锁](kernel/kernel-mini-basic-ipc-mutex.md)
- [消息队列](kernel/kernel-mini-basic-ipc-queue.md) - [消息队列](kernel/kernel-mini-basic-ipc-queue.md)
- [信号量](kernel/kernel-mini-basic-ipc-sem.md) - [信号量](kernel/kernel-mini-basic-ipc-sem.md)
- [时间管理](kernel/kernel-basic-mini-time.md) - [时间管理](kernel/kernel-mini-basic-time.md)
- [软件定时器](kernel/kernel-mini-basic-soft.md) - [软件定时器](kernel/kernel-mini-basic-soft.md)
- [双向链表](kernel/kernel-mini-basic-list.md)
- 扩展组件 - 扩展组件
- [C++支持](kernel/kernel-mini-extend-support.md) - [C++支持](kernel/kernel-mini-extend-support.md)
- [CPU占用率](kernel/kernel-mini-extend-cpup.md) - [CPU占用率](kernel/kernel-mini-extend-cpup.md)
...@@ -180,7 +181,6 @@ ...@@ -180,7 +181,6 @@
- [LMS调测](kernel/kernel-mini-memory-lms.md) - [LMS调测](kernel/kernel-mini-memory-lms.md)
- 附录 - 附录
- [内核编码规范](kernel/kernel-mini-appx-code.md) - [内核编码规范](kernel/kernel-mini-appx-code.md)
- [双向链表](kernel/kernel-mini-appx-data-list.md)
- [标准库支持](kernel/kernel-mini-appx-lib.md) - [标准库支持](kernel/kernel-mini-appx-lib.md)
- 小型系统内核(LiteOS-A) - 小型系统内核(LiteOS-A)
- [小型系统内核概述](kernel/kernel-small-overview.md) - [小型系统内核概述](kernel/kernel-small-overview.md)
......
...@@ -170,7 +170,9 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 ...@@ -170,7 +170,9 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补
| Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。<br/>主要涉及如下需求:<br/>I5JPMG&nbsp;【request部件】【download】后台任务通知<br/>I5NXHK&nbsp;【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口<br/>I5NG2X&nbsp;【theme_screenlock部件】支持特定系统应用请求锁定屏幕<br/>I5IU1Z&nbsp;&nbsp;支持向剪贴板数据增加图片内容的数据项<br/>I5OGA3&nbsp;&nbsp;支持设备级的跨设备剪贴板开关<br/>I5NMKI&nbsp;【pasteboard部件】支持向剪贴板数据增加二进制数据<br/>I5MAMN&nbsp;&nbsp;支持剪贴板数据范围限制在应用内<br/>I5OX20&nbsp;【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | | Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。<br/>主要涉及如下需求:<br/>I5JPMG&nbsp;【request部件】【download】后台任务通知<br/>I5NXHK&nbsp;【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口<br/>I5NG2X&nbsp;【theme_screenlock部件】支持特定系统应用请求锁定屏幕<br/>I5IU1Z&nbsp;&nbsp;支持向剪贴板数据增加图片内容的数据项<br/>I5OGA3&nbsp;&nbsp;支持设备级的跨设备剪贴板开关<br/>I5NMKI&nbsp;【pasteboard部件】支持向剪贴板数据增加二进制数据<br/>I5MAMN&nbsp;&nbsp;支持剪贴板数据范围限制在应用内<br/>I5OX20&nbsp;【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA |
| ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。<br/>主要涉及如下需求:<br/>I5IZZ7&nbsp;【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius<br/>I5JQ1R&nbsp;【ace_engine_standard部件】支持图片复制粘贴<br/>I5JQ3F&nbsp;【ace_engine_standard部件】输入框能力增强<br/>I5JQ3J&nbsp;【ace_engine_standard部件】stack组件新增事件拓传机制<br/>I5JQ54&nbsp;【ace_engine_standard部件】指定控件获取焦点<br/>I5MX7J&nbsp;【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果<br/>I5MWS0&nbsp;【ace_engine_standard部件】panel组件弹出高度通知给开发者<br/>I5IZVY&nbsp;【ace_engine_standard部件】键鼠接入时支持组件刷新<br/>I5JQ5Y&nbsp;【ace_engine_standard部件】走焦能力增强<br/>I5IY7K&nbsp;【新增需求】【ace_engine_standard部件】主题能力支持<br/>I5MWTB&nbsp;【ace_engine_standard部件】媒体查询支持vp查询<br/>I5IZU9&nbsp;【ace_engine_standard部件】ui_service常驻内存优化<br/>I5JQ26&nbsp;【ace_engine_standard部件】Vsync请求机制流程优化<br/>I5JQ2O&nbsp;【ace_engine部件】公共资源预加载<br/>I5JQ2D&nbsp;【ace_engine_standard部件】Move事件重采样优化<br/>I5IZXS&nbsp;【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文<br/>I5IZYG&nbsp;【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文<br/>I5IZX0&nbsp;【toolchain部件】编译支持解析$r新增bundleName和moduleName参数<br/>I5J09I&nbsp;【toolchain部件】\@Builder&nbsp;支持export导出 | NA | | ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。<br/>主要涉及如下需求:<br/>I5IZZ7&nbsp;【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius<br/>I5JQ1R&nbsp;【ace_engine_standard部件】支持图片复制粘贴<br/>I5JQ3F&nbsp;【ace_engine_standard部件】输入框能力增强<br/>I5JQ3J&nbsp;【ace_engine_standard部件】stack组件新增事件拓传机制<br/>I5JQ54&nbsp;【ace_engine_standard部件】指定控件获取焦点<br/>I5MX7J&nbsp;【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果<br/>I5MWS0&nbsp;【ace_engine_standard部件】panel组件弹出高度通知给开发者<br/>I5IZVY&nbsp;【ace_engine_standard部件】键鼠接入时支持组件刷新<br/>I5JQ5Y&nbsp;【ace_engine_standard部件】走焦能力增强<br/>I5IY7K&nbsp;【新增需求】【ace_engine_standard部件】主题能力支持<br/>I5MWTB&nbsp;【ace_engine_standard部件】媒体查询支持vp查询<br/>I5IZU9&nbsp;【ace_engine_standard部件】ui_service常驻内存优化<br/>I5JQ26&nbsp;【ace_engine_standard部件】Vsync请求机制流程优化<br/>I5JQ2O&nbsp;【ace_engine部件】公共资源预加载<br/>I5JQ2D&nbsp;【ace_engine_standard部件】Move事件重采样优化<br/>I5IZXS&nbsp;【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文<br/>I5IZYG&nbsp;【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文<br/>I5IZX0&nbsp;【toolchain部件】编译支持解析$r新增bundleName和moduleName参数<br/>I5J09I&nbsp;【toolchain部件】\@Builder&nbsp;支持export导出 | NA |
API变更请参考:
[*API差异报告*](api-change/v3.2-beta3/Readme-CN.md)
### 芯片及开发板适配 ### 芯片及开发板适配
......
...@@ -36,4 +36,6 @@ OpenHarmony 3.2 Beta3版本相较于OpenHarmony 3.2 Beta2版本,电源服务 ...@@ -36,4 +36,6 @@ OpenHarmony 3.2 Beta3版本相较于OpenHarmony 3.2 Beta2版本,电源服务
| system.brightness | GetBrightnessOptions | complete?: () => void; | 废弃 | | system.brightness | GetBrightnessOptions | complete?: () => void; | 废弃 |
| system.brightness | GetBrightnessOptions | fail?: (data: string, code: number) => void; | 废弃 | | system.brightness | GetBrightnessOptions | fail?: (data: string, code: number) => void; | 废弃 |
| system.brightness | GetBrightnessOptions | success?: (data: BrightnessResponse) => void; | 废弃 | | system.brightness | GetBrightnessOptions | success?: (data: BrightnessResponse) => void; | 废弃 |
| system.brightness | BrightnessResponse | value: number; | 废弃 | | system.brightness | BrightnessResponse | value: number; | 废弃 |
\ No newline at end of file | ohos.batteryInfo | batteryInfo | ohos.batteryinfo -> ohos.batteryInfo | 模块名修改 |
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册