提交 c1f82d5c 编写于 作者: zyjhandsome's avatar zyjhandsome

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

# Conflicts:
#	zh-cn/application-dev/security/accesstoken-guidelines.md
......@@ -3,30 +3,18 @@
## When to Use
- Data provided by the compass sensor denotes the current orientation of the user device, which helps your application accurately navigate for the user.
With the sensor module, a device can obtain sensor data. For example, the device can subscribe to data of the orientation sensor to detect its own orientation, and data of the pedometer sensor to learn the number of steps the user walks every day.
- Data provided by the proximity sensor denotes the distance between the device and a visible object, which enables the device to automatically turn on or off its screen accordingly to prevent accidental touch on the screen.
- Data provided by the barometer sensor helps your application accurately determine the altitude of the device.
- Data provided by the ambient light sensor helps your device automatically adjust its backlight.
- Data provided by the Hall effect sensor implements the smart cover mode of your device.
- Data provided by the heart rate sensor helps your application track the heart health of a user.
- Data provided by the pedometer sensor helps your application obtain the number of steps a user has walked.
- Data provided by the wear detection sensor helps your application detect whether a user is wearing a wearable device.
For details about the APIs, see [Sensor](../reference/apis/js-apis-sensor.md).
## Available APIs
| Module| API| Description|
| -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorType, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes.|
| ohos.sensor | sensor.on(sensorId, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorId, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorId, callback?:AsyncCallback<void>): void | Unsubscribes from sensor data changes.|
## How to Develop
......@@ -43,52 +31,46 @@
For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Subscribe to data changes of a type of sensor.
2. Subscribe to data changes of a type of sensor. The following uses the acceleration sensor as an example.
```
```js
import sensor from "@ohos.sensor";
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){
sensor.on(sensor.SensorId.ACCELEROMETER, function(data){
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
![en-us_image_0000001241693881](figures/en-us_image_0000001241693881.png)
![171e6f30-a8d9-414c-bafa-b430340305fb](figures/171e6f30-a8d9-414c-bafa-b430340305fb.png)
3. Unsubscribe from sensor data changes.
```
```js
import sensor from "@ohos.sensor";
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER);
sensor.off(sensor.SensorId.ACCELEROMETER);
```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
![en-us_image_0000001196654004](figures/en-us_image_0000001196654004.png)
![65d69983-29f6-4381-80a3-f9ef2ec19e53](figures/65d69983-29f6-4381-80a3-f9ef2ec19e53.png)
4. Subscribe to only one data change of a type of sensor.
```
```js
import sensor from "@ohos.sensor";
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
sensor.once(sensor.SensorId.ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
![en-us_image_0000001241733907](figures/en-us_image_0000001241733907.png)
![db5d017d-6c1c-4a71-a2dd-f74b7f23239e](figures/db5d017d-6c1c-4a71-a2dd-f74b7f23239e.png)
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
```
```js
import sensor from "@ohos.sensor";
try {
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
sensor.once(sensor.SensorId.ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
});
} catch (error) {
console.error("Failed to get sensor data");
console.error("Get sensor data error. data:" + error.data, " msg:", error.message);
}
```
......@@ -3,32 +3,29 @@
Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications.
A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows:
| Type | Name | Description | Usage |
| --------------------------------------- | --------- | ---------------------------------------- | -------------------- |
| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation |
| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis |
| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity |
| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity |
| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device |
| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step |
| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked |
| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature |
| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass |
| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation |
| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity |
| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar.| Measuring the barometric pressure |
| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad. | Providing the three orientation angles of the screen |
| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor. | Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system |
| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call |
| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top|
| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
| --------------------------- | ------------------ | ------------------------------------------------------------ | ---------------------------------------- |
| ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status |
| ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation |
| LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis |
| GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity |
| GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity |
| GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity |
| SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device |
| PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step |
| PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked |
| AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature |
| MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass |
| MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation |
| HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity |
| BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure |
| ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad.| Providing the three orientation angles of the screen |
| ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor.| Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system |
| PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call |
| AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top|
| HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
## Working Principles
......@@ -60,4 +57,3 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting.
......@@ -11,41 +11,54 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
## Available APIs
| Module | API | Description |
| ------------- | ---------------------------------------- | ------------------------------- |
| ohos.vibrator | vibrate(duration: number): Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified duration. This API uses a callback to return the result. |
| ohos.vibrator | vibrate(effectId: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified effect. This API uses a callback to return the result.|
| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise&lt;void&gt;| Stops vibration. This API uses a promise to return the result. |
| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result. |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise&lt;void&gt; | Starts vibration with the specified effect and attribute. This API uses a promise to return the result.|
| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback&lt;void&gt;): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.|
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration in the specified mode. This API uses a promise to return the result. |
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback&lt;void&gt;): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. |
## How to Develop
1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Trigger the device to vibrate.
2. Start vibration with the specified effect and attribute.
```
import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error) => {
if (error) { // The call fails, and error.code and error.message are printed.
console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
} else { // The call is successful, and the device starts to vibrate.
console.log("Promise returned to indicate a successful vibration.")
```js
import vibrator from '@ohos.vibrator';
try {
vibrator.startVibration({
type: 'time',
duration: 1000,
}, {
id: 0,
usage: 'alarm'
}, (error) => {
if (error) {
console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message);
return;
}
console.log('Callback returned to indicate a successful vibration.');
});
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
})
```
3. Stop the vibration.
3. Stop vibration in the specified mode.
```
import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => {
if (error) { // The call fails, and error.code and error.message are printed.
console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
} else { // The call is successful, and the device stops vibrating.
console.log("Promise returned to indicate successful.");
```js
import vibrator from '@ohos.vibrator';
try {
// Stop vibration in VIBRATOR_STOP_MODE_TIME mode.
vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) {
if (error) {
console.log('error.code' + error.code + 'error.message' + error.message);
return;
}
console.log('Callback returned to indicate successful.');
})
} catch (err) {
console.info('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
......@@ -45,7 +45,7 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim
```js
var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: "pinyin"};
var options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"};
var localeObj = new intl.Locale(locale, options);
```
......@@ -347,4 +347,4 @@ The following sample is provided to help you better understand how to develop in
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International)
-[`International`: Internationalization (eTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International)
-[`International`: Internationalization (ArkTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International)
......@@ -5,3 +5,4 @@
- [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
- [Using MindSpore Lite for Model Inference](mindspore-lite-guidelines.md)
- [Connecting the Neural Network Runtime to an AI Inference Framework](neural-network-runtime-guidelines.md)
# Connecting the Neural Network Runtime to an AI Inference Framework
## When to Use
As a bridge between the AI inference engine and acceleration chip, the Neural Network Runtime provides simplified Native APIs for the AI inference engine to perform end-to-end inference through the acceleration chip.
This document uses the `Add` single-operator model shown in Figure 1 as an example to describe the development process of Neural Network Runtime. The `Add` operator involves two inputs, one parameter, and one output. Wherein, the `activation` parameter is used to specify the type of the activation function in the `Add` operator.
**Figure 1** Add single-operator model
!["Add single-operator model"](figures/neural_network_runtime.png)
## Preparing the Environment
### Environment Requirements
The environment requirements for the Neural Network Runtime are as follows:
- System version: OpenHarmony master branch.
- Development environment: Ubuntu 18.04 or later.
- Access device: a standard device running OpenHarmony. The built-in hardware accelerator driver has been connected to the Neural Network Runtime through an HDI API.
The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. You can download the **ohos-sdk** package of the corresponding version from [Daily Build](http://ci.openharmony.cn/dailys/dailybuilds) in the OpenHarmony community and then decompress the package to obtain the Native development suite of the corresponding platform. Take Linux as an example. The package of the Native development suite is named `native-linux-{version number}.zip`.
### Environment Setup
1. Start the Ubuntu server.
2. Copy the downloaded package of the Native development suite to the root directory of the current user.
3. Decompress the package of the Native development suite.
```shell
unzip native-linux-{version number}.zip
```
The directory structure after decompression is as follows. The content in the directory may vary depending on version iteration. Use the Native APIs of the latest version.
```text
native/
─ ─ build // Cross-compilation toolchain
─ ─ build-tools // Compilation and build tools
├── docs
├── llvm
├── nativeapi_syscap_config.json
├── ndk_system_capability.json
├── NOTICE.txt
├── oh-uni-package.json
── sysroot // Native API header files and libraries
```
## Available APIs
This section describes the common APIs used in the development process of the Neural Network Runtime.
### Structure
| Name| Description|
| --------- | ---- |
| typedef struct OH_NNModel OH_NNModel | Model handle of the Neural Network Runtime. It is used to construct a model.|
| typedef struct OH_NNCompilation OH_NNCompilation | Compiler handle of the Neural Network Runtime. It is used to compile an AI model.|
| typedef struct OH_NNExecutor OH_NNExecutor | Executor handle of the Neural Network Runtime. It is used to perform inference computing on a specified device.|
### Model Construction APIs
| Name| Description|
| ------- | --- |
| OH_NNModel_Construct() | Creates a model instance of the OH_NNModel type.|
| OH_NN_ReturnCode OH_NNModel_AddTensor(OH_NNModel *model, const OH_NN_Tensor *tensor) | Adds a tensor to a model instance.|
| OH_NN_ReturnCode OH_NNModel_SetTensorData(OH_NNModel *model, uint32_t index, const void *dataBuffer, size_t length) | Sets the tensor value.|
| OH_NN_ReturnCode OH_NNModel_AddOperation(OH_NNModel *model, OH_NN_OperationType op, const OH_NN_UInt32Array *paramIndices, const OH_NN_UInt32Array *inputIndices, const OH_NN_UInt32Array *outputIndices) | Adds an operator to a model instance.|
| OH_NN_ReturnCode OH_NNModel_SpecifyInputsAndOutputs(OH_NNModel *model, const OH_NN_UInt32Array *inputIndices, const OH_NN_UInt32Array *outputIndices) | Specifies the model input and output.|
| OH_NN_ReturnCode OH_NNModel_Finish(OH_NNModel *model) | Completes model composition.|
| void OH_NNModel_Destroy(OH_NNModel **model) | Destroys a model instance.|
### Model Compilation APIs
| Name| Description|
| ------- | --- |
| OH_NNCompilation *OH_NNCompilation_Construct(const OH_NNModel *model) | Creates a compilation instance of the OH_NNCompilation type.|
| OH_NN_ReturnCode OH_NNCompilation_SetDevice(OH_NNCompilation *compilation, size_t deviceID) | Specifies the device for model compilation and computing.|
| OH_NN_ReturnCode OH_NNCompilation_SetCache(OH_NNCompilation *compilation, const char *cachePath, uint32_t version) | Sets the cache directory and version of the compiled model.|
| OH_NN_ReturnCode OH_NNCompilation_Build(OH_NNCompilation *compilation) | Performs model compilation.|
| void OH_NNCompilation_Destroy(OH_NNCompilation **compilation) | Destroys the OH_NNCompilation instance.|
### Inference Execution APIs
| Name| Description|
| ------- | --- |
| OH_NNExecutor *OH_NNExecutor_Construct(OH_NNCompilation *compilation) | Creates an executor instance of the OH_NNExecutor type.|
| OH_NN_ReturnCode OH_NNExecutor_SetInput(OH_NNExecutor *executor, uint32_t inputIndex, const OH_NN_Tensor *tensor, const void *dataBuffer, size_t length) | Sets the single input data for a model.|
| OH_NN_ReturnCode OH_NNExecutor_SetOutput(OH_NNExecutor *executor, uint32_t outputIndex, void *dataBuffer, size_t length) | Sets the buffer for a single output of a model.|
| OH_NN_ReturnCode OH_NNExecutor_Run(OH_NNExecutor *executor) | Executes model inference.|
| void OH_NNExecutor_Destroy(OH_NNExecutor **executor) | Destroys the OH_NNExecutor instance to release the memory occupied by the instance.|
### Device Management APIs
| Name| Description|
| ------- | --- |
| OH_NN_ReturnCode OH_NNDevice_GetAllDevicesID(const size_t **allDevicesID, uint32_t *deviceCount) | Obtains the ID of the device connected to the Neural Network Runtime.|
## How to Develop
The development process of the Neural Network Runtime consists of three phases: model construction, model compilation, and inference execution. The following uses the `Add` single-operator model as an example to describe how to call Neural Network Runtime APIs during application development.
1. Create an application sample file.
Create the source file of the Neural Network Runtime application sample. Run the following commands in the project directory to create the `nnrt_example/` directory and create the `nnrt_example.cpp` source file in the directory:
```shell
mkdir ~/nnrt_example && cd ~/nnrt_example
touch nnrt_example.cpp
```
2. Import the Neural Network Runtime module.
Add the following code at the beginning of the `nnrt_example.cpp` file to import the Neural Network Runtime module:
```cpp
#include <cstdint>
#include <iostream>
#include <vector>
#include "neural_network_runtime/neural_network_runtime.h"
// Constant, used to specify the byte length of the input and output data.
const size_t DATA_LENGTH = 4 * 12;
```
3. Construct a model.
Use Neural Network Runtime APIs to construct an `Add` single-operator sample model.
```cpp
OH_NN_ReturnCode BuildModel(OH_NNModel** pModel)
{
// Create a model instance and construct a model.
OH_NNModel* model = OH_NNModel_Construct();
if (model == nullptr) {
std::cout << "Create model failed." << std::endl;
return OH_NN_MEMORY_ERROR;
}
// Add the first input tensor of the float32 type for the Add operator. The tensor shape is [1, 2, 2, 3].
int32_t inputDims[4] = {1, 2, 2, 3};
OH_NN_Tensor input1 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR};
OH_NN_ReturnCode ret = OH_NNModel_AddTensor(model, &input1);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, add Tensor of first input failed." << std::endl;
return ret;
}
// Add the second input tensor of the float32 type for the Add operator. The tensor shape is [1, 2, 2, 3].
OH_NN_Tensor input2 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR};
ret = OH_NNModel_AddTensor(model, &input2);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, add Tensor of second input failed." << std::endl;
return ret;
}
// Add the Tensor parameter of the Add operator. This parameter is used to specify the type of the activation function. The data type of the Tensor parameter is int8.
int32_t activationDims = 1;
int8_t activationValue = OH_NN_FUSED_NONE;
OH_NN_Tensor activation = {OH_NN_INT8, 1, &activationDims, nullptr, OH_NN_ADD_ACTIVATIONTYPE};
ret = OH_NNModel_AddTensor(model, &activation);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, add Tensor of activation failed." << std::endl;
return ret;
}
// Set the type of the activation function to OH_NN_FUSED_NONE, indicating that no activation function is added to the operator.
ret = OH_NNModel_SetTensorData(model, 2, &activationValue, sizeof(int8_t));
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, set value of activation failed." << std::endl;
return ret;
}
// Set the output of the Add operator. The data type is float32 and the tensor shape is [1, 2, 2, 3].
OH_NN_Tensor output = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR};
ret = OH_NNModel_AddTensor(model, &output);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, add Tensor of output failed." << std::endl;
return ret;
}
// Specify the input, parameter, and output indexes of the Add operator.
uint32_t inputIndicesValues[2] = {0, 1};
uint32_t paramIndicesValues = 2;
uint32_t outputIndicesValues = 3;
OH_NN_UInt32Array paramIndices = {&paramIndicesValues, 1};
OH_NN_UInt32Array inputIndices = {inputIndicesValues, 2};
OH_NN_UInt32Array outputIndices = {&outputIndicesValues, 1};
// Add the Add operator to the model instance.
ret = OH_NNModel_AddOperation(model, OH_NN_OPS_ADD, &paramIndices, &inputIndices, &outputIndices);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, add operation failed." << std::endl;
return ret;
}
// Set the input and output indexes of the model instance.
ret = OH_NNModel_SpecifyInputsAndOutputs(model, &inputIndices, &outputIndices);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, specify inputs and outputs failed." << std::endl;
return ret;
}
// Complete the model instance construction.
ret = OH_NNModel_Finish(model);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed, error happened when finishing model construction." << std::endl;
return ret;
}
*pModel = model;
return OH_NN_SUCCESS;
}
```
4. Query the acceleration chip connected to the Neural Network Runtime.
The Neural Network Runtime can connect to multiple acceleration chips through HDI APIs. Before model compilation, you need to query the acceleration chips connected to the Neural Network Runtime on the current device. Each acceleration chip has a unique ID. In the compilation phase, you need to specify the chip for model compilation based on the device ID.
```cpp
void GetAvailableDevices(std::vector<size_t>& availableDevice)
{
availableDevice.clear();
// Obtain the available hardware ID.
const size_t* devices = nullptr;
uint32_t deviceCount = 0;
OH_NN_ReturnCode ret = OH_NNDevice_GetAllDevicesID(&devices, &deviceCount);
if (ret != OH_NN_SUCCESS) {
std::cout << "GetAllDevicesID failed, get no available device." << std::endl;
return;
}
for (uint32_t i = 0; i < deviceCount; i++) {
availableDevice.emplace_back(devices[i]);
}
}
```
5. Compile a model on the specified device.
The Neural Network Runtime uses abstract model expressions to describe the topology structure of an AI model. Before inference execution on an acceleration chip, the compilation module provided by Neural Network Runtime needs to deliver the abstract model expression to the chip driver layer and convert the abstract model expression into a format that supports inference and computing.
```cpp
OH_NN_ReturnCode CreateCompilation(OH_NNModel* model, const std::vector<size_t>& availableDevice, OH_NNCompilation** pCompilation)
{
// Create a compilation instance to pass the model to the underlying hardware for compilation.
OH_NNCompilation* compilation = OH_NNCompilation_Construct(model);
if (compilation == nullptr) {
std::cout << "CreateCompilation failed, error happended when creating compilation." << std::endl;
return OH_NN_MEMORY_ERROR;
}
// Set compilation options, such as the compilation hardware, cache path, performance mode, computing priority, and whether to enable float16 low-precision computing.
// Choose to perform model compilation on the first device.
OH_NN_ReturnCode ret = OH_NNCompilation_SetDevice(compilation, availableDevice[0]);
if (ret != OH_NN_SUCCESS) {
std::cout << "CreateCompilation failed, error happened when setting device." << std::endl;
return ret;
}
// Have the model compilation result cached in the /data/local/tmp directory, with the version number set to 1.
ret = OH_NNCompilation_SetCache(compilation, "/data/local/tmp", 1);
if (ret != OH_NN_SUCCESS) {
std::cout << "CreateCompilation failed, error happened when setting cache path." << std::endl;
return ret;
}
// Start model compilation.
ret = OH_NNCompilation_Build(compilation);
if (ret != OH_NN_SUCCESS) {
std::cout << "CreateCompilation failed, error happened when building compilation." << std::endl;
return ret;
}
*pCompilation = compilation;
return OH_NN_SUCCESS;
}
```
6. Create an executor.
After the model compilation is complete, you need to call the execution module of the Neural Network Runtime to create an inference executor. In the execution phase, operations such as setting the model input, obtaining the model output, and triggering inference computing are performed through the executor.
```cpp
OH_NNExecutor* CreateExecutor(OH_NNCompilation* compilation)
{
// Create an executor instance.
OH_NNExecutor* executor = OH_NNExecutor_Construct(compilation);
return executor;
}
```
7. Perform inference computing and print the computing result.
The input data required for inference computing is passed to the executor through the API provided by the execution module. This way, the executor is triggered to perform inference computing once to obtain the inference computing result.
```cpp
OH_NN_ReturnCode Run(OH_NNExecutor* executor)
{
// Construct sample data.
float input1[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
float input2[12] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
int32_t inputDims[4] = {1, 2, 2, 3};
OH_NN_Tensor inputTensor1 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR};
OH_NN_Tensor inputTensor2 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR};
// Set the execution input.
// Set the first input for execution. The input data is specified by input1.
OH_NN_ReturnCode ret = OH_NNExecutor_SetInput(executor, 0, &inputTensor1, input1, DATA_LENGTH);
if (ret != OH_NN_SUCCESS) {
std::cout << "Run failed, error happened when setting first input." << std::endl;
return ret;
}
// Set the second input for execution. The input data is specified by input2.
ret = OH_NNExecutor_SetInput(executor, 1, &inputTensor2, input2, DATA_LENGTH);
if (ret != OH_NN_SUCCESS) {
std::cout << "Run failed, error happened when setting second input." << std::endl;
return ret;
}
// Set the output data cache. After the OH_NNExecutor_Run instance performs inference computing, the output result is stored in the output.
float output[12];
ret = OH_NNExecutor_SetOutput(executor, 0, output, DATA_LENGTH);
if (ret != OH_NN_SUCCESS) {
std::cout << "Run failed, error happened when setting output buffer." << std::endl;
return ret;
}
// Perform inference computing.
ret = OH_NNExecutor_Run(executor);
if (ret != OH_NN_SUCCESS) {
std::cout << "Run failed, error doing execution." << std::endl;
return ret;
}
// Print the output result.
for (uint32_t i = 0; i < 12; i++) {
std::cout << "Output index: " << i << ", value is: " << output[i] << "." << std::endl;
}
return OH_NN_SUCCESS;
}
```
8. Build an end-to-end process from model construction to model compilation and execution.
Steps 3 to 7 implement the model construction, compilation, and execution processes and encapsulates them into four functions to facilitate modular development. The following sample code shows how to concatenate the four functions into a complete Neural Network Runtime the development process.
```cpp
int main()
{
OH_NNModel* model = nullptr;
OH_NNCompilation* compilation = nullptr;
OH_NNExecutor* executor = nullptr;
std::vector<size_t> availableDevices;
// Perform model construction.
OH_NN_ReturnCode ret = BuildModel(&model);
if (ret != OH_NN_SUCCESS) {
std::cout << "BuildModel failed." << std::endl;
OH_NNModel_Destroy(&model);
return -1;
}
// Obtain the available devices.
GetAvailableDevices(availableDevices);
if (availableDevices.empty()) {
std::cout << "No available device." << std::endl;
OH_NNModel_Destroy(&model);
return -1;
}
// Perform model compilation.
ret = CreateCompilation(model, availableDevices, &compilation);
if (ret != OH_NN_SUCCESS) {
std::cout << "CreateCompilation failed." << std::endl;
OH_NNModel_Destroy(&model);
OH_NNCompilation_Destroy(&compilation);
return -1;
}
// Create an inference executor for the model.
executor = CreateExecutor(compilation);
if (executor == nullptr) {
std::cout << "CreateExecutor failed, no executor is created." << std::endl;
OH_NNModel_Destroy(&model);
OH_NNCompilation_Destroy(&compilation);
return -1;
}
// Use the created executor to perform single-step inference computing.
ret = Run(executor);
if (ret != OH_NN_SUCCESS) {
std::cout << "Run failed." << std::endl;
OH_NNModel_Destroy(&model);
OH_NNCompilation_Destroy(&compilation);
OH_NNExecutor_Destroy(&executor);
return -1;
}
// Destroy the model to release occupied resources.
OH_NNModel_Destroy(&model);
OH_NNCompilation_Destroy(&compilation);
OH_NNExecutor_Destroy(&executor);
return 0;
}
```
## Verification
1. Prepare the compilation configuration file of the application sample.
Create a `CMakeLists.txt` file, and add compilation configurations to the application sample file `nnrt_example.cpp`. The following is a simple example of the `CMakeLists.txt` file:
```text
cmake_minimum_required(VERSION 3.16)
project(nnrt_example C CXX)
add_executable(nnrt_example
./nnrt_example.cpp
)
target_link_libraries(nnrt_example
neural_network_runtime.z
)
```
2. Compile the application sample.
Create the **build/** directory in the current directory, and compile `nnrt\_example.cpp` in the **build/** directory to obtain the binary file `nnrt\_example`:
```shell
mkdir build && cd build
cmake -DCMAKE_TOOLCHAIN_FILE={Path of the cross-compilation tool chain }/build/cmake/ohos.toolchain.cmake -DOHOS_ARCH=arm64-v8a -DOHOS_PLATFORM=OHOS -DOHOS_STL=c++_static ..
make
```
3. Push the application sample to the device for execution.
```shell
# Push the `nnrt_example` obtained through compilation to the device, and execute it.
hdc_std file send ./nnrt_example /data/local/tmp/.
# Grant required permissions to the executable file of the test case.
hdc_std shell "chmod +x /data/local/tmp/nnrt_example"
# Execute the test case.
hdc_std shell "/data/local/tmp/nnrt_example"
```
If the execution is normal, information similar to the following is displayed:
```text
Output index: 0, value is: 11.000000.
Output index: 1, value is: 13.000000.
Output index: 2, value is: 15.000000.
Output index: 3, value is: 17.000000.
Output index: 4, value is: 19.000000.
Output index: 5, value is: 21.000000.
Output index: 6, value is: 23.000000.
Output index: 7, value is: 25.000000.
Output index: 8, value is: 27.000000.
Output index: 9, value is: 29.000000.
Output index: 10, value is: 31.000000.
Output index: 11, value is: 33.000000.
```
4. (Optional) Check the model cache.
If the HDI service connected to the Neural Network Runtime supports the model cache function, you can find the generated cache file in the `/data/local/tmp` directory after the `nnrt_example` is executed successfully.
> **NOTE**
>
> The IR graphs of the model need to be passed to the hardware driver layer, so that the HDI service compiles the IR graphs into a computing graph dedicated to hardware. The compilation process is time-consuming. The Neural Network Runtime supports the computing graph cache feature. It can cache the computing graphs compiled by the HDI service to the device storage. If the same model is compiled on the same acceleration chip next time, you can specify the cache path so that the Neural Network Runtime can directly load the computing graphs in the cache file, reducing the compilation time.
Check the cached files in the cache directory.
```shell
ls /data/local/tmp
```
The command output is as follows:
```text
# 0.nncache cache_info.nncache
```
If the cache is no longer used, manually delete the cache files.
```shell
rm /data/local/tmp/*nncache
```
## Samples
The following sample is provided to help you understand how to connect a third-party AI inference framework to the Neural Network Runtime:
- [Development Guide for Connecting TensorFlow Lite to NNRt Delegate](https://gitee.com/openharmony/neural_network_runtime/tree/master/example/deep_learning_framework)
<!--no_check-->
# Development References
- [SystemCapability](syscap.md)
- [SysCap List](syscap-list.md)
- [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md)
- [API Reference (JS and TS APIs)](apis/Readme-EN.md)
- [JS Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md)
- [API Reference (ArkTS and JS APIs)](apis/Readme-EN.md)
- [Error Codes](errorcodes/Readme-EN.md)
- API Reference (Native APIs)
- [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md)
......@@ -112,6 +112,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
**Example**
```js
let sinkDeviceDescriptor = "descriptor";
let srcInputDeviceId = 0;
try {
inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => {
if (error) {
......@@ -160,6 +162,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
**Example**
```js
let sinkDeviceDescriptor = "descriptor";
let srcInputDeviceId = 0;
try {
inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => {
console.log(`Start Keyboard mouse crossing success.`);
......@@ -249,6 +253,7 @@ Checks whether screen hopping is enabled. This API uses an asynchronous callback
**Example**
```js
let deviceDescriptor = "descriptor";
try {
inputDeviceCooperate.getState(deviceDescriptor, (error, data) => {
if (error) {
......@@ -324,7 +329,7 @@ try {
inputDeviceCooperate.on('cooperation', (data) => {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`);
});
} catch (err) {
} catch (error) {
console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
......@@ -342,7 +347,7 @@ Disables listening for screen hopping events.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. The value is **cooperation**. |
| callback | AsyncCallback<void> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
| callback | AsyncCallback\<void> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
......@@ -350,25 +355,25 @@ Disables listening for screen hopping events.
```js
// Unregister a single callback.
callback: function(event) {
function callback(event) {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`);
return false;
}
try {
inputDeviceCooperate.on('cooperation', this.callback);
inputDeviceCooperate.off("cooperation", this.callback);
inputDeviceCooperate.on('cooperation', callback);
inputDeviceCooperate.off("cooperation", callback);
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
```js
// Unregister all callbacks.
callback: function(event) {
function callback(event) {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`);
return false;
}
try {
inputDeviceCooperate.on('cooperation', this.callback);
inputDeviceCooperate.on('cooperation', callback);
inputDeviceCooperate.off("cooperation");
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
......
......@@ -197,12 +197,12 @@ Disables listening for hot swap events of an input device.
**Example**
```js
function callback(data) {
callback: function(data) {
console.log("type: " + data.type + ", deviceId: " + data.deviceId);
}
try {
inputDevice.on("change", callback);
inputDevice.on("change", this.callback);
} catch (error) {
console.info("oninputdevcie " + error.code + " " + error.message)
}
......@@ -212,7 +212,7 @@ inputDevice.on("change", listener);
// Disable this listener.
try {
inputDevice.off("change", callback);
inputDevice.off("change", this.callback);
} catch (error) {
console.info("offinputdevcie " + error.code + " " + error.message)
}
......@@ -333,7 +333,7 @@ inputDevice.getDevice(1).then((inputDevice)=>{
## inputDevice.supportKeys<sup>9+</sup>
supportKeys(deviceId: number, keys: Array&lt;KeyCode&gt;, callback: Callback&lt;Array&lt;boolean&gt;&gt;): void
supportKeys(deviceId: number, keys: Array&lt;KeyCode&gt;, callback: AsyncCallback &lt;Array&lt;boolean&gt;&gt;): void
Obtains the key codes supported by the input device. This API uses an asynchronous callback to return the result.
......@@ -345,7 +345,7 @@ Obtains the key codes supported by the input device. This API uses an asynchrono
| -------- | ------------------------------------ | ---- | --------------------------------- |
| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
| keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. |
| callback | Callback&lt;Array&lt;boolean&gt;&gt; | Yes | Callback used to return the result. |
| callback | AsyncCallback&lt;Array&lt;boolean&gt;&gt; | Yes | Callback used to return the result. |
**Example**
......
# MediaLibrary
# @ohos.multimedia.medialibrary (Media Library Management)
> **NOTE**
>
> The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -193,7 +192,7 @@ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) {
### on<sup>8+</sup>
on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback&lt;void&gt;): void
on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback: Callback&lt;void&gt;): void
Subscribes to the media library changes. This API uses an asynchronous callback to return the result.
......@@ -215,7 +214,7 @@ media.on('imageChange', () => {
```
### off<sup>8+</sup>
off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback&lt;void&gt;): void
off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback?: Callback&lt;void&gt;): void
Unsubscribes from the media library changes. This API uses an asynchronous callback to return the result.
......@@ -885,7 +884,7 @@ Obtains information about online peer devices. This API uses a promise to return
| Type | Description |
| ------------------- | -------------------- |
| Promise\<Array\<PeerInfo>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
| Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
**Example**
......@@ -921,7 +920,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal
| Type | Description |
| ------------------- | -------------------- |
| callback: AsyncCallback\<Array\<PeerInfo>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
**Example**
......@@ -956,7 +955,7 @@ Obtains information about all peer devices. This API uses a promise to return th
| Type | Description |
| ------------------- | -------------------- |
| Promise\<Array\<PeerInfo>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
| Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
**Example**
......@@ -992,7 +991,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal
| Type | Description |
| ------------------- | -------------------- |
| callback: AsyncCallback\<Array\<PeerInfo>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
**Example**
......@@ -1014,6 +1013,11 @@ async function example() {
Provides APIs for encapsulating file asset attributes.
> **NOTE**
>
> 1. The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices.
> 2. Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module.
### Attributes
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
......@@ -1025,7 +1029,7 @@ Provides APIs for encapsulating file asset attributes.
| mimeType | string | Yes | No | Extended file attributes. |
| mediaType<sup>8+</sup> | [MediaType](#mediatype8) | Yes | No | Media type. |
| displayName | string | Yes | Yes | Display file name, including the file name extension. |
| title | string | Yes | Yes | Title in the file. |
| title | string | Yes | Yes | Title in the file. By default, it carries the file name without extension. |
| relativePath<sup>8+</sup> | string | Yes | Yes | Relative public directory of the file. |
| parent<sup>8+</sup> | number | Yes | No | Parent directory ID. |
| size | number | Yes | No | File size, in bytes. |
......@@ -2486,29 +2490,33 @@ Enumerates media types.
Enumerates key file information.
> **NOTE**
>
> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Value | Description |
| ------------- | ------------------- | ---------------------------------------------------------- |
| ID | file_id | File ID. |
| RELATIVE_PATH | relative_path | Relative public directory of the file. |
| DISPLAY_NAME | display_name | Display file name. |
| PARENT | parent | Parent directory ID. |
| MIME_TYPE | mime_type | Extended file attributes. |
| MEDIA_TYPE | media_type | Media type. |
| SIZE | size | File size, in bytes. |
| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) |
| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) |
| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) |
| TITLE | title | Title in the file. |
| ARTIST | artist | Artist of the file. |
| AUDIOALBUM | audio_album | Audio album. |
| DURATION | duration | Duration, in ms. |
| WIDTH | width | Image width, in pixels. |
| HEIGHT | height | Image height, in pixels. |
| ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
| ALBUM_ID | bucket_id | ID of the album to which the file belongs. |
| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. |
| ID | "file_id" | File ID. |
| RELATIVE_PATH | "relative_path" | Relative public directory of the file. |
| DISPLAY_NAME | "display_name" | Display file name. |
| PARENT | "parent" | Parent directory ID. |
| MIME_TYPE | "mime_type" | Extended file attributes. |
| MEDIA_TYPE | "media_type" | Media type. |
| SIZE | "size" | File size, in bytes. |
| DATE_ADDED | "date_added" | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) |
| DATE_MODIFIED | "date_modified" | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) |
| DATE_TAKEN | "date_taken" | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) |
| TITLE | "title" | Title in the file. |
| ARTIST | "artist" | Artist of the file. |
| AUDIOALBUM | "audio_album" | Audio album. |
| DURATION | "duration" | Duration, in ms. |
| WIDTH | "width" | Image width, in pixels. |
| HEIGHT | "height" | Image height, in pixels. |
| ORIENTATION | "orientation" | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
| ALBUM_ID | "bucket_id" | ID of the album to which the file belongs. |
| ALBUM_NAME | "bucket_display_name" | Name of the album to which the file belongs. |
## DirectoryType<sup>8+</sup>
......@@ -2573,8 +2581,6 @@ Describes the image size.
Implements the media asset option.
> **NOTE**
>
> This API is deprecated since API version 9.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
......@@ -2598,5 +2604,5 @@ Describes media selection option.
| Name | Type | Readable| Writable| Description |
| ----- | ------ | ---- | ---- | -------------------- |
| type | string | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
| type | 'image' &#124; 'video' &#124; 'media' | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
| count | number | Yes | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected. |
......@@ -2,10 +2,9 @@
The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data.
> **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.
> - API version 9 is a canary version for trial use. The APIs of this version may be unstable.
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......
......@@ -39,6 +39,14 @@ Obtains an **OnlineUpdater** object.
| ------------------- | ---- |
| [Updater](#updater) | **OnlineUpdater** object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -71,6 +79,14 @@ Obtains a **Restorer** object for restoring factory settings.
| --------------------- | ------ |
| [Restorer](#restorer) | **Restorer** object for restoring factory settings.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -95,6 +111,14 @@ Obtains a **LocalUpdater** object.
| ----------------------------- | ------ |
| [LocalUpdater](#localupdater) | **LocalUpdater** object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -102,7 +126,7 @@ try {
let localUpdater = update.getLocalUpdater();
} catch(error) {
console.error(`Fail to get localUpdater error: ${error}`);
}
};
```
## Updater
......@@ -123,6 +147,14 @@ Checks whether a new version is available. This API uses an asynchronous callbac
| -------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<[CheckResult](#checkresult)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -147,6 +179,14 @@ Checks whether a new version is available. This API uses a promise to return the
| ------------------------------------- | ------------------- |
| Promise\<[CheckResult](#checkresult)> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -175,6 +215,14 @@ Obtains information about the new version. This API uses an asynchronous callbac
| -------- | ---------------------------------------- | ---- | --------------- |
| callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -200,6 +248,14 @@ Obtains information about the new version. This API uses a promise to return the
| ---------------------------------------- | -------------------- |
| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -227,7 +283,15 @@ Obtains the description file of the new version. This API uses an asynchronous c
| ------------------ | ---------------------------------------- | ---- | -------------- |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file. |
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>>) | Yes | Callback used to return the result.|
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -272,6 +336,14 @@ Obtains the description file of the new version. This API uses a promise to retu
| ---------------------------------------- | ------------------- |
| Promise\<Array\<[ComponentDescription](#componentdescription)>> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -309,6 +381,14 @@ Obtains information about the current version. This API uses an asynchronous cal
| -------- | ---------------------------------------- | ---- | ---------------- |
| callback | AsyncCallback\<[CurrentVersionInfo](#currentversioninfo)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -335,6 +415,14 @@ Obtains information about the current version. This API uses a promise to return
| ---------------------------------------- | ------------------- |
| Promise\<[CurrentVersionInfo](#currentversioninfo)> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -362,7 +450,15 @@ Obtains the description file of the current version. This API uses an asynchrono
| Name | Type | Mandatory | Description |
| ------------------ | ---------------------------------------- | ---- | --------------- |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file. |
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>>) | Yes | Callback used to return the result.|
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -401,6 +497,14 @@ Obtains the description file of the current version. This API uses a promise to
| ---------------------------------------- | -------------------- |
| Promise\<Array\<[ComponentDescription](#componentdescription)>> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -433,6 +537,14 @@ Obtains information about the update task. This API uses an asynchronous callbac
| -------- | ------------------------------------- | ---- | ---------------- |
| callback | AsyncCallback\<[TaskInfo](#taskinfo)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -457,6 +569,14 @@ Obtains information about the update task. This API uses a promise to return the
| ------------------------------- | ------------------- |
| Promise\<[TaskInfo](#taskinfo)> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -483,7 +603,15 @@ Downloads the new version. This API uses an asynchronous callback to return the
| ----------------- | --------------------------------------- | ---- | ---------------------------------- |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. |
| downloadOptions | [DownloadOptions](#downloadoptions) | Yes | Download options. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -526,6 +654,14 @@ Downloads the new version. This API uses a promise to return the result.
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -562,7 +698,15 @@ Resumes download of the new version. This API uses an asynchronous callback to r
| --------------------- | ---------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. |
| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | Yes | Options for resuming download. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -604,6 +748,14 @@ Resumes download of the new version. This API uses a promise to return the resul
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -639,7 +791,15 @@ Pauses download of the new version. This API uses an asynchronous callback to re
| -------------------- | ---------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. |
| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | Yes | Options for pausing download. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -681,6 +841,14 @@ Resumes download of the new version. This API uses a promise to return the resul
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -716,7 +884,15 @@ Updates the version. This API uses an asynchronous callback to return the result
| ----------------- | --------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. |
| upgradeOptions | [UpgradeOptions](#upgradeoptions) | Yes | Update options. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -758,6 +934,14 @@ Updates the version. This API uses a promise to return the result.
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -793,7 +977,15 @@ Clears errors. This API uses an asynchronous callback to return the result.
| ----------------- | --------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. |
| clearOptions | [ClearOptions](#clearoptions) | Yes | Clear options. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -835,6 +1027,14 @@ Clears errors. This API uses a promise to return the result.
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -844,7 +1044,7 @@ const versionDigestInfo = {
};
// Options for clearing errors
lconstet clearOptions = {
const clearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL,
};
updater.clearError(versionDigestInfo, clearOptions).then(() => {
......@@ -870,6 +1070,14 @@ Obtains the update policy. This API uses an asynchronous callback to return the
| -------- | ---------------------------------------- | ---- | --------------- |
| callback | AsyncCallback\<[UpgradePolicy](#upgradepolicy)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -895,6 +1103,14 @@ Obtains the update policy. This API uses a promise to return the result.
| ---------------------------------------- | --------------------- |
| Promise\<[UpgradePolicy](#upgradepolicy)> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -923,6 +1139,14 @@ Sets the update policy. This API uses an asynchronous callback to return the res
| policy | [UpgradePolicy](#upgradepolicy) | Yes | Update policy. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -930,7 +1154,7 @@ const policy = {
downloadStrategy: false,
autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes
}
};
updater.setUpgradePolicy(policy, (err) => {
console.log(`setUpgradePolicy result: ${err}`);
});
......@@ -958,6 +1182,14 @@ Sets the update policy. This API uses a promise to return the result.
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -965,7 +1197,7 @@ const policy = {
downloadStrategy: false,
autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes
}
};
updater.setUpgradePolicy(policy).then(() => {
console.log(`setUpgradePolicy success`);
}).catch(err => {
......@@ -987,7 +1219,15 @@ Terminates the update. This API uses an asynchronous callback to return the resu
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -1013,6 +1253,14 @@ Terminates the update. This API uses a promise to return the result.
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1038,6 +1286,14 @@ Enables listening for update events. This API uses an asynchronous callback to r
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.|
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1065,6 +1321,14 @@ Disables listening for update events. This API uses an asynchronous callback to
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.|
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | No | Event callback.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1084,7 +1348,7 @@ updater.off(eventClassifyInfo, (eventInfo) => {
factoryReset(callback: AsyncCallback\<void>): void
Restore the device to its factory settings. This API uses an asynchronous callback to return the result.
Restores the scale to its factory settings. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Update.UpdateService
......@@ -1094,7 +1358,15 @@ Restore the device to its factory settings. This API uses an asynchronous callba
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -1108,7 +1380,7 @@ restorer.factoryReset((err) => {
factoryReset(): Promise\<void>
Restore the device to its factory settings. This API uses a promise to return the result.
Restores the scale to its factory settings. This API uses a promise to return the result.
**System capability**: SystemCapability.Update.UpdateService
......@@ -1120,6 +1392,14 @@ Restore the device to its factory settings. This API uses a promise to return th
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1150,6 +1430,14 @@ Verifies the update package. This API uses an asynchronous callback to return th
| certsFile | string | Yes | Path of the certificate file. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1186,6 +1474,14 @@ Verifies the update package. This API uses a promise to return the result.
| -------------- | ---------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1214,7 +1510,15 @@ Installs the update package. This API uses an asynchronous callback to return th
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------- | ---- | --------------------------------------- |
| upgradeFile | Array<[UpgradeFile](#upgradefile)> | Yes | Update file. |
| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -1245,10 +1549,18 @@ Installs the update package. This API uses a promise to return the result.
| -------------- | -------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
localUpdater upgradeFiles = [{
const upgradeFiles = [{
fileType: update.ComponentType.OTA, // OTA package
filePath: "path" // Path of the local update package
}];
......@@ -1273,6 +1585,14 @@ Enables listening for update events. This API uses an asynchronous callback to r
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.|
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
```ts
......@@ -1300,7 +1620,15 @@ Disables listening for update events. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description |
| ----------------- | ---------------------------------------- | ---- | ---- |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.|
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.|
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | No | Event callback.|
**Error codes**
For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md).
| ID | Error Message |
| ------- | ---------------------------------------------------- |
| 11500104 | BusinessError 11500104: IPC error. |
**Example**
......@@ -1337,7 +1665,7 @@ Enumerates update service types.
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ---- |
| vendor | [BusinessVendor](#businessvendor) | Yes | Application vendor. |
| subType | [BusinessSubType](#businesssubtype) | Yes | Type |
| subType | [BusinessSubType](#businesssubtype) | Yes | Update service type. |
## CheckResult
......@@ -1377,7 +1705,7 @@ Represents a version component.
**System capability**: SystemCapability.Update.UpdateService
| Parameter | Type | Mandatory | Description |
| Name | Type | Mandatory | Description |
| --------------- | ----------------------------------- | ---- | -------- |
| componentId | string | Yes | Component ID. |
| componentType | [ComponentType](#componenttype) | Yes | Component type. |
......@@ -1498,7 +1826,7 @@ Represents an update policy.
## UpgradePeriod
Represents a period for automatic update.
Represents an automatic update period.
**System capability**: SystemCapability.Update.UpdateService
......@@ -1509,7 +1837,7 @@ Represents a period for automatic update.
## TaskInfo
Represents task information.
Task information.
**System capability**: SystemCapability.Update.UpdateService
......@@ -1520,7 +1848,7 @@ Represents task information.
## EventInfo
Represents event type information.
Represents event information.
**System capability**: SystemCapability.Update.UpdateService
......@@ -1554,7 +1882,7 @@ Represents an error message.
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | ---- |
| errorCode | number | Yes | Error code. |
| errorMessage | string | Yes | Error description.|
| errorMessage | string | Yes | Error message.|
## EventClassifyInfo
......@@ -1592,11 +1920,11 @@ Represents an event callback.
## BusinessVendor
Device vendor.
Represents a device vendor.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ------ | -------- | ---- |
| PUBLIC | "public" | Open source. |
......@@ -1606,7 +1934,7 @@ Represents an update type.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| -------- | ---- | ---- |
| FIRMWARE | 1 | Firmware. |
......@@ -1616,7 +1944,7 @@ Represents a component type.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ---- | ---- | ---- |
| OTA | 1 | Firmware. |
......@@ -1626,7 +1954,7 @@ Represents an update mode.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| -------- | ---------- | ---- |
| UPGRADE | "upgrade" | Differential package. |
| RECOVERY | "recovery" | Recovery package. |
......@@ -1637,7 +1965,7 @@ Represents an effective mode.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ------------- | ---- | ---- |
| COLD | 1 | Cold update. |
| LIVE | 2 | Live update. |
......@@ -1649,7 +1977,7 @@ Represents a description file type.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ------- | ---- | ---- |
| CONTENT | 0 | Content. |
| URI | 1 | Link. |
......@@ -1660,18 +1988,18 @@ Represents a description file format.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ---------- | ---- | ---- |
| STANDARD | 0 | Standard format.|
| SIMPLIFIED | 1 | Simple format.|
## NetType
Enumerates network types.
Represents a network type.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ----------------- | ---- | --------- |
| CELLULAR | 1 | Data network. |
| METERED_WIFI | 2 | Wi-Fi hotspot. |
......@@ -1685,7 +2013,7 @@ Represents an update command.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| -------------------- | ---- | ----- |
| DOWNLOAD | 1 | Download. |
| INSTALL | 2 | Install. |
......@@ -1699,7 +2027,7 @@ Enumerates update states.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ---------------- | ---- | ---- |
| WAITING_DOWNLOAD | 20 | Waiting for download. |
| DOWNLOADING | 21 | Downloading. |
......@@ -1718,7 +2046,7 @@ Represents an event type.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ---- | ---------- | ---- |
| TASK | 0x01000000 | Task event.|
......@@ -1728,22 +2056,22 @@ Enumerates event IDs.
**System capability**: SystemCapability.Update.UpdateService
| Name | Default Value | Description |
| Name | Value | Description |
| ---------------------- | ---------- | ------ |
| EVENT_TASK_BASE | 0x01000000 | Indicates a task event. |
| EVENT_TASK_RECEIVE | 0x01000001 | Indicates that a task is received. |
| EVENT_TASK_CANCEL | 0x01000010 | Indicates that a task is cancelled. |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | Indicates the state of waiting for the download. |
| EVENT_DOWNLOAD_START | 0x01000100 | Indicates that the download starts. |
| EVENT_DOWNLOAD_UPDATE | 0x01000101 | Indicates the download progress update.|
| EVENT_DOWNLOAD_PAUSE | 0x01000110 | Indicates that the download is paused. |
| EVENT_DOWNLOAD_RESUME | 0x01000111 | Indicates that the download is resumed. |
| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | Indicates that the download succeeded. |
| EVENT_DOWNLOAD_FAIL | 0x01001001 | Indicates that the download failed. |
| EVENT_UPGRADE_WAIT | 0x01001010 | Indicates the state of waiting for the update. |
| EVENT_UPGRADE_START | 0x01001011 | Indicates that the update starts. |
| EVENT_UPGRADE_UPDATE | 0x01001100 | Indicates that the update is in progress. |
| EVENT_APPLY_WAIT | 0x01001101 | Indicates the state of waiting for applying the update. |
| EVENT_APPLY_START | 0x01001110 | Indicates the state of applying the update. |
| EVENT_UPGRADE_SUCCESS | 0x01001111 | Indicates that the update succeeded. |
| EVENT_UPGRADE_FAIL | 0x01010000 | Indicates that the update failed. |
| EVENT_TASK_BASE | 0x01000000 | Task event. |
| EVENT_TASK_RECEIVE | 0x01000001 | Task received. |
| EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. |
| EVENT_DOWNLOAD_START | 0x01000100 | Download started. |
| EVENT_DOWNLOAD_UPDATE | 0x01000101 | Download progress update.|
| EVENT_DOWNLOAD_PAUSE | 0x01000110 | Download paused. |
| EVENT_DOWNLOAD_RESUME | 0x01000111 | Download resumed. |
| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | Download succeeded. |
| EVENT_DOWNLOAD_FAIL | 0x01001001 | Download failed. |
| EVENT_UPGRADE_WAIT | 0x01001010 | Waiting for update. |
| EVENT_UPGRADE_START | 0x01001011 | Update started. |
| EVENT_UPGRADE_UPDATE | 0x01001100 | Update in progress. |
| EVENT_APPLY_WAIT | 0x01001101 | Waiting for applying the update. |
| EVENT_APPLY_START | 0x01001110 | Applying the update. |
| EVENT_UPGRADE_SUCCESS | 0x01001111 | Update succeeded. |
| EVENT_UPGRADE_FAIL | 0x01010000 | Update failed. |
......@@ -23,7 +23,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and
| Name | Type | Mandatory| Description |
| ------- | ------- | ---- | -------------------------- |
| context | [Context](#../apis/js-apis-Context.md) | Yes | Context of the ability instance.|
| context | [Context](../apis/js-apis-inner-app-context.md) | Yes | Context of the ability instance.|
**Return value**
......@@ -1210,7 +1210,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---------------- |
| callback | AsyncCallback&lt;[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.|
| callback | AsyncCallback&lt;[image.PixelMap](../apis/js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.|
**Example**
......@@ -1248,7 +1248,7 @@ Obtains the file thumbnail of the given size. This API uses an asynchronous call
| Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---------------- |
| size | [Size](#size) | Yes | Size of the thumbnail to obtain. |
| callback | AsyncCallback&lt;[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.|
| callback | AsyncCallback&lt;[image.PixelMap](../apis/js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.|
**Example**
......@@ -1292,7 +1292,7 @@ Obtains the file thumbnail of the given size. This API uses a promise to return
| Type | Description |
| ----------------------------- | --------------------- |
| Promise&lt;[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)&gt; | Promise used to return the pixel map of the thumbnail.|
| Promise&lt;[image.PixelMap](../apis/js-apis-image.md#pixelmap7)&gt; | Promise used to return the pixel map of the thumbnail.|
**Example**
......
......@@ -52,7 +52,7 @@ Not supported
```
![zh-cn_image_0000001173324703](figures/zh-cn_image_0000001173324703.gif)
![zh-cn_image_0000001173324703](figures/en-us_image_0000001173324703.gif)
```html
......@@ -68,7 +68,7 @@ Not supported
```
![zh-cn_image_0000001167662852](figures/zh-cn_image_0000001167662852.gif)
![zh-cn_image_0000001167662852](figures/en-us_image_0000001167662852.gif)
```html
......@@ -83,7 +83,7 @@ Not supported
```
![zh-cn_image_0000001127284938](figures/zh-cn_image_0000001127284938.gif)
![zh-cn_image_0000001127284938](figures/en-us_image_0000001127284938.gif)
```html
......
# Update Error Codes
## 11500104 IPC Error
**Error Message**
BusinessError 11500104: IPC error.
**Description**
This error code is reported if an exception is thrown during an IPC call.
**Possible Causes**
An IPC API call failed.
**Solution**
1. Check whether the update system ability has started. If not, start it.
2. Check whether IPC data conversion is normal. If not, check the conversion process.
# SysCap
# SystemCapability
## Overview
### System Capabilities and APIs
SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association.
SysCap is short for SystemCapability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association.
![image-20220326064841782](figures/image-20220326064841782.png)
For details about the SysCap sets in OpenHarmony, see [SysCap List](../reference/syscap-list.md).
### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set
The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps.
......@@ -20,8 +18,6 @@ The associated SysCap set covers the system capabilities of associated APIs that
![image-20220326064913834](figures/image-20220326064913834.png)
### Devices and Supported SysCap Sets
Each device provides a SysCap set that matches its hardware capability.
......@@ -29,24 +25,18 @@ The SDK classifies devices into general devices and custom devices. The general
![image-20220326064955505](figures/image-20220326064955505.png)
### Mapping Between Devices and SDK Capabilities
The SDK provides a full set of APIs for DevEco Studio. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input).
The SDK provides a full set of APIs for DevEco Studio. DevEco Studio identifies the supported SysCap set based on the devices selected for the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input).
![image-20220326065043006](figures/image-20220326065043006.png)
## How to Develop
### Obtaining the PCID
The Product Compatibility ID (PCID) contains the SysCap information supported by the current device. For the moment, you can obtain the PCID of a device from the device vendor. In the future, you'll be able to obtain the PCIDs of all devices from the authentication center, which is in development.
### Importing the PCID
DevEco Studio allows Product Compatibility ID (PCID) imports for projects. After the imported PCID file is decoded, the SysCap is output and written into the **syscap.json** file.
......@@ -55,8 +45,6 @@ Right-click the project directory and choose **Import Product Compatibility ID**
![20220329-103626](figures/20220329-103626.gif)
### Configuring the Associated SysCap Set and Required SysCap Set
DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary.
......@@ -91,51 +79,44 @@ Exercise caution when modifying the required SysCap set. Incorrect modifications
}
```
### Single-Device Application Development
By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set.
![image-20220326065124911](figures/image-20220326065124911.png)
### Cross-Device Application Development
By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets.
![image-20220326065201867](figures/image-20220326065201867.png)
### Checking Whether an API Is Available
Use **canIUse** if you want to check whether a project supports a specific SysCap.
- Method 1: Use the **canIUse** API predefined in OpenHarmony.
```
if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) {
```
if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) {
console.log("This application supports SystemCapability.ArkUI.ArkUI.Full.");
} else {
} else {
console.log("This application does not support SystemCapability.ArkUI.ArkUI.Full".);
}
```
}
```
You can import a module using the **import** API. If the current device does not support the module, the import result is **undefined**. Before using an API, you must make sure the API is available.
- Method 2: Import a module using the **import** API. If the current device does not support the module, the import result is **undefined**. Before using an API, you must make sure the API is available.
```
import geolocation from '@ohos.geolocation';
```
import geolocation from '@ohos.geolocation';
if (geolocation) {
if (geolocation) {
geolocation.getCurrentLocation((location) => {
console.log(location.latitude, location.longitude);
});
} else {
} else {
console.log('This device does not support location information.');
}
```
}
```
You can also find out the SysCap to which an API belongs by referring to the API reference document.
### Checking the Differences Between Devices with a Specific SysCap
......@@ -159,7 +140,6 @@ authenticator.execute('FACE_ONLY', 'S1', (err, result) => {
})
```
### How Do SysCap Differences Arise Between Devices
The device SysCaps in product solutions vary according to the component combination defined by the product solution vendor. The following figure shows the overall process.
......
......@@ -19,7 +19,6 @@ Typical operations involve the following:
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
......@@ -172,7 +171,6 @@ Typical operations involve the following:
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
......@@ -320,7 +318,6 @@ You need to use the certificate chain validator in certificate chain verificatio
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
......@@ -432,7 +429,6 @@ Typical operations involve the following:
**Available APIs**
For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md).
The table below describes the APIs used in this guide.
......
......@@ -7,7 +7,7 @@ This document describes how code contributors, committers, and PMC members in th
3. Copyright and license header
## Scope
This document applies only to the OpenHarmony community. It is not applicable to the scenario where the OpenHarmony project is used by individuals or enterprises to develop their products or the scenario where third-party open-source software is introduced. For details, see [Introducing Third-Party Open-Source Software](introducing-third-party-open-source-software.md).
This document applies only to the OpenHarmony community. It is not applicable to the scenario where the OpenHarmony project is used by individuals or enterprises to develop their products or the scenario where third-party open-source software is introduced.
## Improvements and Revisions
1. This document is drafted and maintained by the OpenHarmony PMC. What you are reading now is the latest version of this document.
......
......@@ -5,22 +5,22 @@
### WLAN
The Wireless Local Area Network (WLAN) Driver module in OpenHarmony is developed based on the Hardware Driver Foundation (HDF). It provides cross-OS porting, self-adaptation to component differences, and module assembly and building.
The Wireless Local Area Network (WLAN) driver module is developed based on OpenHarmony Hardware Driver Foundation (HDF). It supports modular assembly and building, automatic adaptation to device differences, and cross-OS porting.
### Working Principles
You can adapt your driver code based on the unified interfaces provided by the WLAN module. The WLAN module provides:
You can modify your driver code based on the unified APIs provided by the WLAN module. The WLAN module provides:
- A unified underlying interface to implement capabilities, such as setting up or closing a WLAN hotspot, scanning hotspots, and connecting to or disconnecting from a hotspot.
- A unified interface to the Hardware Device Interface (HDI) layer to implement capabilities, such as setting or obtaining the device Media Access Control (MAC) address and setting the transmit power.
- APIs for the underlying layer to implement capabilities, such as opening or closing a WLAN hotspot, scanning hotspots, and connecting to or disconnecting from a hotspot.
- APIs for the Hardware Device Interface (HDI) layer to implement capabilities, such as setting or obtaining the device Media Access Control (MAC) address and setting the transmit power.
The figure below shows the WLAN architecture. The WLAN Driver module implements startup loading, parses configuration files, and provides bus abstraction APIs. The WLAN Chip Driver module provides the MAC Sublayer Management Entity (MLME).
The following figure shows the WLAN architecture. The WLAN driver module implements startup loading, parses configuration files, and provides bus abstraction APIs. The WLAN chip driver module provides the MAC Sublayer Management Entity (MLME).
**Figure 1** WLAN architecture
![image](figures/WLAN_architecture.png "WLAN architecture")
The figure below shows the WLAN driver architecture.
The following figure shows the WLAN driver architecture.
**Figure 2** WLAN driver architecture
......@@ -32,11 +32,11 @@ The WLAN driver consists of the following modules:
2. WLAN Configuration Core: parses WLAN configuration files.
3. Access point (AP): provides a WLAN access interface for devices.
3. Access point (AP): allows devices to connect to the WLAN.
4. Station (STA): a terminal that accesses the WLAN system.
4. Station (STA): a device that has access to the WLAN system and allows transmission and reception of data.
5. mac80211: defines MAC-layer interfaces for underlying drivers.
5. mac80211: defines MAC-layer APIs for underlying drivers.
6. Bus: provides a unified bus abstract interface for the upper layer. It shields the differences between different kernels by calling the Secure Digital Input Output (SDIO) interfaces provided by the platform layer and encapsulating the adapted USB and PCIe interfaces. It also encapsulates different types of bus operations in a unified manner to shield differences between different chipsets. The complete bus driving capabilities provided by the bus module help simplify and streamline the development of different chip vendors.
......@@ -58,13 +58,13 @@ The relationships between the main modules are as follows:
4. The protocol stack works with the NetDevice, NetBuf, and FlowCtl modules to exchange data flows.
## Development Guidelines
## How to Develop
### Available APIs
The WLAN module provides the following types of APIs:
1. Hardware Device Interface (HDI) and Hardware Abstraction Layer (HAL) APIs for upper-layer services
1. HDI and Hardware Abstraction Layer (HAL) APIs for upper-layer services
2. APIs for vendors
......@@ -75,7 +75,7 @@ The WLAN module provides the following types of APIs:
![image](figures/WLAN_driver_APIs.png "WLAN Driver APIs")
- The WLAN module provides HAL APIs for upper-layer services (applicable to small and mini systems). **Table 2** and **Table 3** describe some APIs.
- The WLAN module provides HAL APIs for upper-layer services (applicable to small and mini systems). **Table 1** and **Table 2** describe some APIs.
**Table 1** wifi_hal.h
......@@ -95,7 +95,7 @@ The WLAN module provides the following types of APIs:
| int32_t (\*getDeviceMacAddress)(const struct IWiFiBaseFeature \*, unsigned char \*, uint8_t)| Obtains the device MAC address.|
| int32_t (\*setTxPower)(const struct IWiFiBaseFeature \*, int32_t)| Sets the transmit power.|
- The WLAN Driver module also provides APIs that you need to fill in the implementation. **Table 4** describes some APIs.
- The WLAN Driver module also provides APIs that you need to fill in the implementation. **Table 3** describes some APIs.
**Table 3** net_device.h
......@@ -110,7 +110,7 @@ The WLAN module provides the following types of APIs:
- The WLAN Driver module provides APIs that you can directly use to create or release a **WifiModule**, connect to or disconnect from a WLAN hotspot, request or release a **NetBuf**, and convert between the **pbuf** structure of Lightweight IP (lwIP) and a **NetBuf**.
Tables 5 to 7 describe the APIs.
The following tables describe the APIs.
**Table 4** wifi_module.h
......@@ -119,7 +119,7 @@ The WLAN module provides the following types of APIs:
| struct WifiModule \*WifiModuleCreate(const struct HdfConfigWifiModuleConfig \*config)| Creates a **WifiModule**.|
| void WifiModuleDelete(struct WifiModule \*module)| Deletes a **WifiModule** and releases its data.|
| int32_t DelFeature(struct WifiModule \*module, uint16_t featureType)| Deletes a feature from a **WifiModule**.|
| int32_t AddFeature(struct WifiModule \*module, uint16_t featureType, struct WifiFeature \*featureData)| Adds a feature to a **WifiModule**.|
| int32_t AddFeature(struct WifiModule \*module, uint16_t featureType,<br> struct WifiFeature \*featureData)| Adds a feature to a **WifiModule**.|
**Table 5** wifi_mac80211_ops.h
......@@ -136,11 +136,11 @@ The WLAN module provides the following types of APIs:
| -------- | -------- |
| static inline void NetBufQueueInit(struct NetBufQueue \*q)| Initializes a **NetBuf** queue.|
| struct NetBuf \*NetBufAlloc(uint32_t size)| Allocates a **NetBuf**.|
| void NetBufFree(struct NetBuf \*nb) | Releases a **NetBuf**.|
| void NetBufFree(struct NetBuf \*nb)| Releases a **NetBuf**.|
| struct NetBuf \*Pbuf2NetBuf(const struct NetDevice \*netdev, struct pbuf \*lwipBuf)| Converts the **pbuf** structure of lwIP to a **NetBuf**.|
| struct pbuf \*NetBuf2Pbuf(const struct NetBuf \*nb)| Converts a **NetBuf** to the **pbuf** structure of lwIP.|
### How to Develop
### Development Procedure
#### WLAN Framework Adaptation
The WLAN driver framework developed based on the HDF and Platform framework provides a unified driver model regardless of the OS and system on a chip (SoC). When developing your WLAN driver, you need to configure data based on the WLAN driver framework.
......@@ -546,11 +546,7 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial
}
```
4. Invoke the event reporting APIs.
The WLAN framework provides the event reporting APIs. For details, see **hdf_wifi_event.c**.
For example, call **HdfWiFiEventNewSta AP** to report information about the newly associated STA.
4. Invoke the event reporting APIs. <br>The WLAN framework provides the event reporting APIs. For details, see hdf_wifi_event.c. <br>For example, call **HdfWiFiEventNewSta AP** to report information about the newly associated STA.
```c
hi_u32 oal_cfg80211_new_sta(oal_net_device_stru *net_device, const hi_u8 *mac_addr, hi_u8 addr_len,
......@@ -571,8 +567,6 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial
return HI_SUCCESS;
}
```
**Verification**
Develop test cases in the WLAN module unit test to verify the basic features of the WLAN module. The following uses Hi3516D V300 standard system as an example.
......@@ -650,7 +644,7 @@ Develop test cases in the WLAN module unit test to verify the basic features of
exit 0
```
- Create a **udhcpd.conf** file (used to start the **udhcpd**) and copy the following content to the file. In the following, **opt dns** *x.x.x.x* *x.x.x.x* indicates two DNS servers configured. You can configure DNS servers as required.
- Create a **udhcpd.conf** file (used to start the **udhcpd**) and copy the following content to the file. <br>In the following, **opt dns** *x.x.x.x* *x.x.x.x* indicates two DNS servers configured. You can configure DNS servers as required.
```text
start 192.168.12.2
......@@ -704,9 +698,7 @@ Develop test cases in the WLAN module unit test to verify the basic features of
busybox udhcpd /vendor/etc/udhcpd.conf
```
4. On the mobile phone, select the network named **test** in the available Wi-Fi list and enter the password.
The network name and password are configured in the **hostapd.conf** file. You can see that network name in the connected Wi-Fi list if the connection is successful.
4. On the mobile phone, select the network named **test** in the available Wi-Fi list and enter the password. <br>The network name and password are configured in the **hostapd.conf** file. You can see that network name in the connected Wi-Fi list if the connection is successful.
5. Ping the test terminal from the development board.
......@@ -714,15 +706,11 @@ Develop test cases in the WLAN module unit test to verify the basic features of
busybox ping xxx.xxx.xxx.xxx
```
In the command, xxx.xxx.xxx.xxx indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally.
In the command, *xxx.xxx.xxx.xxx* indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally.
- Verify basic STA features.
1. Start the STA on the development board, and enable the hotspot on the test terminal.
The hotspot name and password are configured in the **hostapd.conf** file. The hotspot name is **test**, and the password is **12345678**.
1. Start the STA on the development board, and enable the hotspot on the test terminal. <br>The hotspot name and password are configured in the **hostapd.conf** file. The hotspot name is **test**, and the password is **12345678**.
2. Run the following command in the **cmd** window:
......@@ -731,8 +719,6 @@ Develop test cases in the WLAN module unit test to verify the basic features of
wpa_supplicant -i wlan0 -d -c wpa_supplicant.conf
```
3. Run the following commands in another **cmd** window:
```shell
......@@ -741,7 +727,6 @@ Develop test cases in the WLAN module unit test to verify the basic features of
mount -o rw,remount /vendor
busybox udhcpc -i wlan0 -s system/lib/dhcpc.sh
```
The IP addresses of the board and test terminal are displayed if the command is successful.
4. Ping the test terminal from the development board.
......@@ -750,8 +735,7 @@ Develop test cases in the WLAN module unit test to verify the basic features of
busybox ping xxx.xxx.xxx.xxx
```
In the command, *xxx.xxx.xxx.xxx* indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally.
In the command, xxx.xxx.xxx.xxx indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally.
#### **API Invocation**
The WLAN driver module provides two types of capability interfaces for the upper layer: HDI interface and HAL interface.
......@@ -963,19 +947,17 @@ The WLAN driver module provides two types of capability interfaces for the upper
- Code paths:
- Adaptation of WLAN FlowCtl component on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network/wifi**
- Adaptation of HDF network model on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network**
- Adaptation of WLAN FlowCtl component on Linux, build of the HDF WLAN model, and build of the vendor's WLAN driver: **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi**
- Core code for implementing the WLAN module: **//drivers/hdf_core/framework/model/network/wifi**
- External APIs of the WLAN module: **//drivers/hdf_core/framework/include/wifi**
- HDF network model APIs: **//drivers/hdf_core/framework/include/net**
- WLAN HDI server implementation: **//drivers/peripheral/wlan**
Adaptation of WLAN FlowCtl component on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network/wifi**
Adaptation of HDF network model on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network**
Adaptation of WLAN FlowCtl component on Linux, build of the HDF WLAN model, and build of the vendor's WLAN driver: **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi**
Core code for implementing the WLAN module: **//drivers/hdf_core/framework/model/network/wifi**
External APIs of the WLAN module: **//drivers/hdf_core/framework/include/wifi**
HDF network model APIs: **//drivers/hdf_core/framework/include/net**
WLAN HDI server implementation: **//drivers/peripheral/wlan**
# Touchscreen<a name="EN-US_TOPIC_0000001052857350"></a>
# Touchscreen
## Overview<a name="section175431838101617"></a>
- **Functions of the Touchscreen driver**
## Overview
The touchscreen driver is used to power on its integrated circuit \(IC\), configure and initialize hardware pins, register interrupts, configure Inter-Integrated Circuit \(I2C\) or SPI APIs, set input-related configurations, and download and update firmware.
### Function Introduction
The touchscreen driver powers on its integrated circuit (IC), initializes hardware pins, registers interrupts, configures the communication (I2C or SPI) interface, sets input configurations, and downloads and updates firmware.
- **Layers of the Touchscreen driver**
The touchscreen driver is developed based on the OpenHarmony input driver model, which applies basic APIs of the operating system abstraction layer (OSAL) and platform interface layer on the OpenHarmony Hardware Driver Foundation [(HDF)](../driver/driver-hdf-development.md). Common APIs include the bus communication APIs and OS native APIs (such as memory, lock, thread, and timer APIs). The OSAL and platform APIs shield the differences of underlying hardware. This allows the use of the touchscreen driver across platforms and OSs. In this regard, you can develop the touchscreen driver only once and deploy it on multiple devices.
This section describes how to develop the touchscreen driver based on the input driver model. [Figure 1](#fig6251184817261) shows an overall architecture of the touchscreen driver.
### Working Principles
The input driver is developed based on the hardware driver foundation \(HDF\), platform APIs, and operating system abstraction layer \(OSAL\) APIs. It provides hardware driver capabilities through the input Hardware Device Interfaces \(HDIs\) for upper-layer input services to control the touchscreen.
The input driver model is developed based on the HDF and APIs of the platform and OSAL. It provides hardware driver capabilities through the input Hardware Driver Interface (HDI) for upper-layer input services to control the touchscreen. The following figure shows the architecture of the input driver model.
**Figure 1** Input driver model
**Figure 1** Architecture of the input driver model<a name="fig6251184817261"></a>
![](figures/architecture-of-the-input-driver-model.png "architecture-of-the-input-driver-model")
![image](figures/architecture-of-the-input-driver-model.png)
- **Input driver model**
The input driver model consists of the following:
The input driver model mainly consists of the device manager, common drivers, and chip drivers. The platform data channel provides capabilities for sending data generated by the touchscreen from the kernel to the user space. The driver model adapts to different touchscreen devices and hardware platforms via the configuration file, improving the efficiency of the touchscreen development. The description for each part of the input driver model is as follows:
- Input Device Manager: provides APIs for input device drivers to register and deregister input devices and manages the input device list in a unified manner.
- Common input drivers: provide common APIs that are applicable to different input devices (such as the common driver APIs for touchscreens). The APIs can be used to initialize board-specific hardware, handle hardware interrupts, and register input devices with the Input Device Manager.
- Input chip drivers: provide differentiated APIs for the drivers form different vendors. You can use these APIs to develop your drivers with minimum modification.
- Event Hub: provides a unified channel for different input devices to report input events.
- HDF input config: parses and manages the board-specific and private configuration of input devices.
- Input device manager: provides input device drivers with the APIs for registering or unregistering input devices and manages the input device list.
The input driver model provides configuration files to help you quickly develop your drivers.
- Input common driver: provides common abstract drivers \(such as the touchscreen common driver\) of various input devices for initializing the board-level hardware, processing hardware interrupts, and registering input devices with the input device manager.
- Input chip driver: provides different chip drivers of each vendor. You can minimize the workload for the input chip driver development by calling differentiated APIs reserved by the input platform driver.
## How to Develop
- Event hub: provides a unified data reporting channel, which enables input devices to report input events.
### When to Use
- HDF input config: parses and manages the board-level configuration as well as the private configuration of input devices.
The input module provides APIs for powering on the touchscreen driver IC, configuring and initializing hardware pins, registering interrupts, configuring the communication (I2C or SPI) interface, setting input configurations, and downloading and updating firmware.
### Available APIs
- **Advantages of developing drivers based on the HDF**
#### Hardware Interfaces
The touchscreen driver is developed based on the [HDF](driver-hdf-development.md) and is implemented via calls to the OSAL and platform APIs, including bus APIs and OS native APIs \(such as memory, lock, thread, and timer\). The OSAL and platform APIs hide the differences of underlying hardware, so that the touchscreen driver can be migrated across platforms and OSs. In this regard, you can develop the touchscreen driver only once but deploy it on multiple devices.
The hardware interfaces for touchscreens can be classified into the following types based on the pin attributes:
- Power interfaces
## Available APIs<a name="section105459441659"></a>
- I/O control interfaces
Based on the attributes of the pins, interfaces on the touchscreens can be classified into the following types:
- Communication interfaces
- Power interfaces
- I/O control interfaces
- Communications interfaces
**Figure 2** Common touchscreen pins
**Figure 2** Common pins of the touchscreen<a name="fig1290384314416"></a>
![](figures/common-pins-of-the-touchscreen.png "common-pins-of-the-touchscreen")
The interfaces shown in the figure are described as follows:
The interfaces shown in the preceding figure are described as follows:
1. **Power interfaces**
- **LDO_1P8**: 1.8 V digital circuit
- **LDO_3P3**: 3.3 V analog circuit
If the touchscreen driver and ICD driver have its own IC, the touchscreen driver IC requires 1.8 V and 3.3 V power supplies. If the touchscreen driver and LCD driver have an integrated IC, you only need to care about the 1.8 V power supply for the touchscreen. The 3.3 V power supply required can be provided by the LCD VSP power (typically 5.5 V) in the driver IC.
2. **I/O control interfaces**
- **RESET**: pin used to reset the driver IC on the host when the kernel is put into hibernation or waken up.
- **INT**: interrupt pin, which must be set to the input pull-up state during driver initialization. After detecting an external touch signal, the driver triggers an interrupt by operating the interrupt pin. Then, the driver reads the touch reporting data in an interrupt handler.
3. **Communication interfaces**
- **Power interfaces**
- LDO\_1P8: 1.8 V digital circuits
- LDO\_3P3: 3.3 V analog circuits
- I2C: I2C is used if a small amount of data is reported by the touchscreen. For details about the I2C protocol and related operation APIs, see [I2C](../driver/driver-platform-i2c-des.md).
- SPI: SPI is used if a large amount of data is reported by the touchscreen. For details about the SPI protocol and related operation APIs, see [SPI](../driver/driver-platform-spi-des.md).
Generally, the touchscreen driver IC is separated from the LCD driver IC. In this case, the touchscreen driver IC requires both 1.8 V and 3.3 V power supplies. Nowadays, the touchscreen driver IC and LCD driver IC can be integrated. Therefore, the touchscreen, requires only the 1.8 V power supply, and the 3.3 V power required internally is supplied by the LCD VSP power \(typical value: 5.5 V\) in the driver IC.
#### Software Interfaces
- **I/O control interfaces**
- RESET: reset pin, which is used to reset the driver IC on the host when suspending or resuming the system.
- INT: interrupt pin, which needs to be set to the input direction and pull-up status during driver initialization. After detecting an external touch signal, the driver triggers the interrupt by operating the interrupt pin. The driver reads the touch reporting data in the ISR function.
The HDI driver APIs provided for the input service can be classified into the input manager module, input reporter module, and input controller module. The following tables describe the available APIs.
- **Communications interfaces**
- I2C: Since only a small amount of touch data is reported by the touchscreen, I2C is used to transmit the reported data. For details about the I2C protocol and interfaces, see [I2C](driver-platform-i2c-des.md#section5361140416).
- SPI: In addition to touch reporting data coordinates, some vendors need to obtain basic capacitance data. Therefore, Serial Peripheral Interface \(SPI\) is used to transmit such huge amount of data. For details about the SPI protocol and interfaces, see [SPI](driver-platform-spi-des.md#overview).
- input_manager.h
| API | Description |
| ------------------------------------------------------------------------------------- | -------------------|
| int32_t (*OpenInputDevice)(uint32_t devIndex); | Opens an input device. |
| int32_t (*CloseInputDevice)(uint32_t devIndex); | Closes an input device. |
| int32_t (*GetInputDevice)(uint32_t devIndex, DeviceInfo **devInfo); | Obtains information about an input device.|
| int32_t (*GetInputDeviceList)(uint32_t *devNum, DeviceInfo **devList, uint32_t size); | Obtains the input device list.|
## How to Develop<a name="section65745222184"></a>
- input_reporter.h
Regardless of the OS and system on a chip \(SoC\), the input driver is developed based on the HDF, platform, and OSAL APIs to provide a unified driver model for touchscreen devices.
| API | Description |
| ----------------------------------------------------------------------------------- | ------------------ |
| int32_t (*RegisterReportCallback)(uint32_t devIndex, InputReportEventCb *callback); | Registers a callback for an input device.|
| int32_t (*UnregisterReportCallback)(uint32_t devIndex); | Unregisters the callback for an input device.|
| void (*ReportEventPkgCallback)(const EventPackage **pkgs, uint32_t count); | Called to report input event data. |
The following uses the touchscreen driver as an example to describe the loading process of the input driver model:
- input_controller.h
1. Complete the device description configuration, such as the loading priority, board-level hardware information, and private data, by referring to the existing template.
| API | Description |
| --------------------------------------------------------------------------------------------------- |--------------- |
| int32_t (*SetPowerStatus)(uint32_t devIndex, uint32_t status); | Sets the power status. |
| int32_t (*GetPowerStatus)(uint32_t devIndex, uint32_t *status); | Obtains the power status. |
| int32_t (*GetDeviceType)(uint32_t devIndex, uint32_t *deviceType); | Obtains the device type. |
| int32_t (*GetChipInfo)(uint32_t devIndex, char *chipInfo, uint32_t length); | Obtains the chip information of a device.|
| int32_t (*GetVendorName)(uint32_t devIndex, char *vendorName, uint32_t length); | Obtains the module vendor name of a device. |
| int32_t (*GetChipName)(uint32_t devIndex, char *chipName, uint32_t length); | Obtains the driver chip name of a device. |
| int32_t (*SetGestureMode)(uint32_t devIndex, uint32_t gestureMode); | Sets the gesture mode. |
| int32_t (*RunCapacitanceTest)(uint32_t devIndex, uint32_t testType, char *result, uint32_t length); | Performs a capacitance test.|
| int32_t (*RunExtraCommand)(uint32_t devIndex, InputExtraCmd *cmd); | Executes the specified command. |
2. Load the input device management driver. The input management driver is loaded automatically by the HDF to create and initialize the device manager.
For more information, see [input](https://gitee.com/openharmony/drivers_peripheral/tree/master/input).
3. Load the platform driver. The platform driver is loaded automatically by the HDF to parse the board-level configuration, initialize the hardware, and provide the API for registering the touchscreen.
### Development Procedure
4. Load the touchscreen driver. The touchscreen driver is loaded automatically by the HDF to instantiate the touchscreen device, parse the private data, and implement differentiated APIs provided by the platform.
The load process of the input driver model (for the touchscreen driver) is as follows:
5. Register the instantiated touchscreen device with the platform driver. Then bind this device to the platform driver, and complete touchscreen initialization such as interrupt registration and power-on and power-off.
1. The device configuration, including the driver loading priority, board-specific hardware information, and private data, is complete.
6. Instantiate the input device and register it with the input manager after the touchscreen is initialized.
2. The HDF driver loads the input device manager driver to create and initialize the device manager.
3. The HDF loads the platform driver to parse the board-specific configuration, initialize the hardware, and provide the API for registering the touchscreen.
Perform the following steps:
4. The HDF loads the touchscreen driver to instantiate the touchscreen device, parse the private data, and implement the differentiated APIs for the platform.
1. Add the touchscreen driver-related descriptions.
5. The instantiated touchscreen device registers with the platform driver to bind the device and the driver and complete the device initialization, including interrupt registration and device power-on and power-off.
Currently, the input driver is developed based on the HDF and is loaded and started by the HDF. Register the driver information, such as whether to load the driver and the loading priority in the configuration file. Then, the HDF starts the registered driver modules one by one. For details about the driver configuration, see [How to Develop](driver-hdf-development.md).
6. The instantiated input device registers with the input device manager for unified management.
2. Complete the board-level configuration and private data configuration of the touchscreen.
Configure the required I/O pins. For example, configure a register for the I2C pin reserved for the touchscreen to use I2C for transmitting data.
The development process of the touchscreen driver is as follows:
3. Implement differentiated adaptation APIs of the touchscreen.
1. Configure device information. <br>The input driver is developed based on the HDF. The HDF loads and starts the driver in a unified manner. You need to configure the driver information, such as whether to load the driver and the loading priority, in the configuration file. Then, the HDF starts the registered driver modules one by one. For details about how to configure the driver, see [Driver Development](../driver/driver-hdf-development.md#how-to-develop).
Use the platform APIs to perform operations for the reset pins, interrupt pins, and power based on the communications interfaces designed for boards. For details about the GPIO-related operations, see [GPIO](driver-platform-gpio-des.md#overview).
2. Configure board-specific information and touchscreen private information.<br>Configure the I/O pin functions. For example, set registers for the I2C pins on the board for the touchscreen to enable I2C communication.
3. Implement device-specific APIs.<br>Based on the communication interfaces designed for the board, use the pin operation APIs provided by the platform interface layer to configure the corresponding reset pin, interrupt pin, and power operations. For details about GPIO operations, see [GPIO](../driver/driver-platform-gpio-des.md).
## Development Example<a name="section263714411191"></a>
This example describes how to develop the touchscreen driver.
### Development Example
### Adding the Touchscreen Driver-related Description<a name="section18249155619195"></a>
The following example describes how to develop the touchscreen driver for an RK3568 development board.
The information about modules of the input driver model is shown as follows and enables the HDF to load the modules in sequence. For details, see [Driver Development](driver-hdf-development.md).
1. Configure device information.
```
input :: host {
Configure the modules of the input driver model in **drivers/adapter/khdf/linux/hcs/device_info/device_info.hcs**. For details, see [Driver Development](../driver/driver-hdf-development.md). Then, the HDF loads the modules of the input model in sequence based on the configuration information.
```c
input :: host {
hostName = "input_host";
priority = 100;
device_input_manager :: device {
device0 :: deviceNode {
policy = 2; // Publish services externally.
priority = 100; // Loading priority. The input device manager in the input driver has the highest priority.
preload = 0; // Value 0 indicates that the driver is to be loaded, and value 1 indicates the opposite.
policy = 2; // The driver provides services externally.
priority = 100; // Loading priority. In the input model, the manager module has the highest priority.
preload = 0; // Whether to load the driver. The value 0 means to load the driver; 1 means the opposite.
permission = 0660;
moduleName = "HDF_INPUT_MANAGER";
serviceName = "input_dev_manager";
......@@ -145,44 +178,44 @@ input :: host {
deviceMatchAttr = "zsj_sample_5p5";
}
}
}
```
}
```
### Adding Board Configuration and Touchscreen Private Configuration<a name="section3571192072014"></a>
2. Configure board-specific and private data for the touchscreen.
The following describes the configuration of the board-level hardware and private data of the touchscreen. You can modify the configuration based on service requirements.
Configure the data in **drivers/adapter/khdf/linux/hcs/input/input_config.hcs**. The following is an example. You can modify the configuration as required.
```
root {
```c
root {
input_config {
touchConfig {
touch0 {
boardConfig {
match_attr = "touch_device1";
inputAttr {
inputType = 0; // Value 0 indicates that the input device is a touchscreen.
inputType = 0; // 0 indicates touchscreen.
solutionX = 480;
solutionY = 960;
devName = "main_touch"; // Device name
devName = "main_touch"; // Device name.
}
busConfig {
busType = 0; // Value 0 indicates the I2C bus.
busType = 0; // 0 indicates I2C.
busNum = 6;
clkGpio = 86;
dataGpio = 87;
i2cClkIomux = [0x114f0048, 0x403]; // Register configuration of the i2c_clk pin
i2cDataIomux = [0x114f004c, 0x403]; // Register configuration of the i2c_data pin
i2cClkIomux = [0x114f0048, 0x403]; // Register of the I2C_CLK pin.
i2cDataIomux = [0x114f004c, 0x403]; // Register of the I2C_DATA pin.
}
pinConfig {
rstGpio = 3;
intGpio = 4;
rstRegCfg = [0x112f0094, 0x400]; // Register configuration of the reset pin
intRegCfg = [0x112f0098, 0x400]; // Register configuration of the interrupt pin
rstRegCfg = [0x112f0094, 0x400]; // Register of the reset pin.
intRegCfg = [0x112f0098, 0x400]; // Register of the interrupt pin.
}
powerConfig {
vccType = 2; // Values 1, 2, and 3 indicate the low-dropout regulator (LDO), GPIO, and PMIC, respectively.
vccNum = 20; // The GPIO number is 20.
vccValue = 1800; // The voltage amplitude is 1800 mV.
vccType = 2; // The value 1 stands for LDO, 2 for GPIO, and 3 for PMIC.
vccNum = 20; // Set the GPIO number to 20.
vccValue = 1800; // Set the voltage amplitude to 1800 mV.
vciType = 1;
vciNum = 12;
vciValue = 3300;
......@@ -201,19 +234,19 @@ root {
match_attr = "";
chipName = "sample";
vendorName = "zsj";
chipInfo = "AAAA11222"; // The first four characters indicate the product name. The fifth and sixth characters indicate the IC model. The last three characters indicate the chip model.
chipInfo = "AAAA11222"; // The first four characters indicate the product name. The fifth and sixth characters indicate the IC model. The last three characters indicate the model number.
busType = 0;
deviceAddr = 0x5D;
irqFlag = 2; // Values 1 and 2 indicate that the interrupt is triggered on the rising and falling edges, respectively. Values 4 and 8 indicate that the interrupt is triggered by the high and low levels, respectively.
irqFlag = 2; // The value 1 means to trigger an interrupt on the rising edge, 2 means to trigger an interrupt on the falling edge, 4 means to trigger an interrupt by the high level, and 8 means to trigger an interrupt by the low level.
maxSpeed = 400;
chipVersion = 0;
powerSequence {
/* Power-on sequence is described as follows:
[Type, status, direction, delay]
<type> Value 0 indicates the power or pin is empty. Values 1 and 2 indicate the VCC (1.8 V) and VCI (3.3 V) power, respectively. Values 3 and 4 indicate the reset and interrupt pins, respectively.
<status> Values 0 and 1 indicate the power-off or pull-down, and the power-on or pull-up, respectively. Value 2 indicates that no operation is performed.
<dir> Values 0 and 1 indicate the input and output directions, respectively. Value 2 indicates that no operation is performed.
<delay> Delay time, in milliseconds.
/* Description of the power-on sequence:
[type, status, direction, delay]
<type> 0 stands for null; 1 for VCC power (1.8 V); 2 for VCI power (3.3 V); 3 for reset pin; 4 for interrupt pin.
<status> 0 stands for power-off or pull-down; 1 for power-on or pull-up; 2 for no operation.
<dir> 0 stands for input; 1 for output; 2 for no operation.
<delay> indicates the delay, in milliseconds. For example, 20 indicates 20 ms delay.
*/
powerOnSeq = [4, 0, 1, 0,
3, 0, 1, 10,
......@@ -234,17 +267,17 @@ root {
}
}
}
}
```
}
```
### Adding the Touchscreen Driver<a name="section6356758162015"></a>
3. Add the touchscreen driver.
The following example shows how to implement the differentiated APIs provided by the platform driver to obtain and parse the touchscreen data. You can adjust the development process based on the board and touchscreen in use.
Implement the touchscreen-specific APIs in **divers/framework/model/input/driver/touchscreen/touch_gt911.c**. The following uses the APIs for obtaining and parsing device data as an example. You can implement the related APIs to match your development.
```
/* Parse the touch reporting data read from the touchscreen into coordinates. */
static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, uint8_t pointNum)
{
```c
/* Parse the touch reporting data read from the touchscreen into coordinates. */
static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, uint8_t pointNum)
{
int32_t resX = device->driver->boardCfg->attr.resolutionX;
int32_t resY = device->driver->boardCfg->attr.resolutionY;
......@@ -255,10 +288,10 @@ static void ParsePointData(ChipDevice *device, FrameData *frame, uint8_t *buf, u
((buf[GT_POINT_SIZE * i + GT_Y_HIGH] & ONE_BYTE_MASK) << ONE_BYTE_OFFSET);
frame->fingers[i].valid = true;
}
}
/* Obtain the touch reporting data from the chip. */
static int32_t ChipDataHandle(ChipDevice *device)
{
}
/* Obtain the touch reporting data from the device. */
static int32_t ChipDataHandle(ChipDevice *device)
{
int32_t ret;
uint8_t touchStatus = 0;
uint8_t pointNum;
......@@ -294,41 +327,41 @@ static int32_t ChipDataHandle(ChipDevice *device)
(void)InputI2cRead(i2cClient, reg, GT_ADDR_LEN, buf, GT_POINT_SIZE * pointNum);
/* Parse the touch reporting data. */
ParsePointData(device, frame, buf, pointNum);
exit:
exit:
OsalMutexUnlock(&device->driver->mutex);
if (ChipCleanBuffer(i2cClient) != HDF_SUCCESS) {
return HDF_FAILURE;
}
return HDF_SUCCESS;
}
}
static struct TouchChipOps g_sampleChipOps = {
static struct TouchChipOps g_sampleChipOps = {
.Init = ChipInit,
.Detect = ChipDetect,
.Resume = ChipResume,
.Suspend = ChipSuspend,
.DataHandle = ChipDataHandle,
};
};
static TouchChipCfg *ChipConfigInstance(struct HdfDeviceObject *device)
{
static TouchChipCfg *ChipConfigInstance(struct HdfDeviceObject *device)
{
TouchChipCfg *chipCfg = (TouchChipCfg *)OsalMemAlloc(sizeof(TouchChipCfg));
if (chipCfg == NULL) {
HDF_LOGE("%s: instance chip config failed", __func__);
return NULL;
}
(void)memset_s(chipCfg, sizeof(TouchChipCfg), 0, sizeof(TouchChipCfg));
/* Parse the private configuration of the touchscreen. */
/* Parse the touchscreen private configuration. */
if (ParseTouchChipConfig(device->property, chipCfg) != HDF_SUCCESS) {
HDF_LOGE("%s: parse chip config failed", __func__);
OsalMemFree(chipCfg);
chipCfg = NULL;
}
return chipCfg;
}
}
static ChipDevice *ChipDeviceInstance(void)
{
static ChipDevice *ChipDeviceInstance(void)
{
ChipDevice *chipDev = (ChipDevice *)OsalMemAlloc(sizeof(ChipDevice));
if (chipDev == NULL) {
HDF_LOGE("%s: instance chip device failed", __func__);
......@@ -336,10 +369,10 @@ static ChipDevice *ChipDeviceInstance(void)
}
(void)memset_s(chipDev, sizeof(ChipDevice), 0, sizeof(ChipDevice));
return chipDev;
}
}
static void FreeChipConfig(TouchChipCfg *config)
{
static void FreeChipConfig(TouchChipCfg *config)
{
if (config->pwrSeq.pwrOn.buf != NULL) {
OsalMemFree(config->pwrSeq.pwrOn.buf);
}
......@@ -347,17 +380,17 @@ static void FreeChipConfig(TouchChipCfg *config)
OsalMemFree(config->pwrSeq.pwrOff.buf);
}
OsalMemFree(config);
}
}
static int32_t HdfSampleChipInit(struct HdfDeviceObject *device)
{
static int32_t HdfSampleChipInit(struct HdfDeviceObject *device)
{
TouchChipCfg *chipCfg = NULL;
ChipDevice *chipDev = NULL;
HDF_LOGE("%s: enter", __func__);
if (device == NULL) {
return HDF_ERR_INVALID_PARAM;
}
/* Parse the private configuration of the touchscreen. */
/* Parse the touchscreen private configuration. */
chipCfg = ChipConfigInstance(device);
if (chipCfg == NULL) {
return HDF_ERR_MALLOC_FAIL;
......@@ -379,19 +412,97 @@ static int32_t HdfSampleChipInit(struct HdfDeviceObject *device)
HDF_LOGI("%s: exit succ, chipName = %s", __func__, chipCfg->chipName);
return HDF_SUCCESS;
freeDev:
freeDev:
OsalMemFree(chipDev);
freeCfg:
freeCfg:
FreeChipConfig(chipCfg);
return HDF_FAILURE;
}
}
struct HdfDriverEntry g_touchSampleChipEntry = {
struct HdfDriverEntry g_touchSampleChipEntry = {
.moduleVersion = 1,
.moduleName = "HDF_TOUCH_SAMPLE",
.Init = HdfSampleChipInit,
};
};
HDF_INIT(g_touchSampleChipEntry);
```
HDF_INIT(g_touchSampleChipEntry);
```
4. Call the Input HDI APIs.
The following sample code shows how an upper-layer input system service calls Input HDI APIs.
```c
#include "input_manager.h"
#define DEV_INDEX 1
IInputInterface *g_inputInterface;
InputReportEventCb g_callback;
/* Define the callback for data reporting. */
static void ReportEventPkgCallback(const EventPackage **pkgs, uint32_t count)
{
if (pkgs == NULL || count > MAX_PKG_NUM) {
return;
}
for (uint32_t i = 0; i < count; i++) {
HDF_LOGI("%s: pkgs[%d] = 0x%x, 0x%x, %d", __func__, i, pkgs[i]->type, pkgs[i]->code, pkgs[i]->value);
}
}
int InputServiceSample(void)
{
uint32_t devType = INIT_DEFAULT_VALUE;
/* Obtain the input driver APIs. */
int ret = GetInputInterface(&g_inputInterface);
if (ret != INPUT_SUCCESS) {
HDF_LOGE("%s: get input interfaces failed, ret = %d", __func__, ret);
return ret;
}
INPUT_CHECK_NULL_POINTER(g_inputInterface, INPUT_NULL_PTR);
INPUT_CHECK_NULL_POINTER(g_inputInterface->iInputManager, INPUT_NULL_PTR);
/* Open an input device. */
ret = g_inputInterface->iInputManager->OpenInputDevice(DEV_INDEX);
if (ret) {
HDF_LOGE("%s: open input device failed, ret = %d", __func__, ret);
return ret;
}
INPUT_CHECK_NULL_POINTER(g_inputInterface->iInputController, INPUT_NULL_PTR);
/* Obtain the type of the input device. */
ret = g_inputInterface->iInputController->GetDeviceType(DEV_INDEX, &devType);
if (ret) {
HDF_LOGE("%s: get device type failed, ret: %d", __FUNCTION__, ret);
return ret;
}
HDF_LOGI("%s: device1's type is %u\n", __FUNCTION__, devType);
/* Register the data reporting callback for the input device. */
g_callback.ReportEventPkgCallback = ReportEventPkgCallback;
INPUT_CHECK_NULL_POINTER(g_inputInterface->iInputReporter, INPUT_NULL_PTR);
ret = g_inputInterface->iInputReporter->RegisterReportCallback(DEV_INDEX, &g_callback);
if (ret) {
HDF_LOGE("%s: register callback failed, ret: %d", __FUNCTION__, ret);
return ret;
}
HDF_LOGI("%s: wait 10s for testing, pls touch the panel now", __FUNCTION__);
OsalMSleep(KEEP_ALIVE_TIME_MS);
/* Unregister the callback for the input device. */
ret = g_inputInterface->iInputReporter->UnregisterReportCallback(DEV_INDEX);
if (ret) {
HDF_LOGE("%s: unregister callback failed, ret: %d", __FUNCTION__, ret);
return ret;
}
/* Close the input device. */
ret = g_inputInterface->iInputManager->CloseInputDevice(DEV_INDEX);
if (ret) {
HDF_LOGE("%s: close device failed, ret: %d", __FUNCTION__, ret);
return ret;
}
return 0;
}
```
......@@ -108,7 +108,7 @@ To keep pace with the rapid development of the IoT industry, the OpenHarmony lig
**Figure 4** LiteOS-A kernel architecture
![](figures/architecture-of-the-openharmony-liteos-a-kernel.png "architecture-of-the-openharmony-liteos-a-kernel")
![](figures/Liteos-a-architecture.png "Liteos-a-architecture.png")
### How to Use
......
# Test
OpenHarmony provides a comprehensive auto-test framework for designing test cases. Detecting defects in the development process can improve code quality.
This document describes how to use the OpenHarmony test framework.
## Setting Up the Environment
- The test framework depends on Python. Before using the test framework, you need to set up the environment.
- For details about how to obtain the source code, see [Obtaining Source Code](../get-code/sourcecode-acquire.md).
### Environment Configuration
#### Basic Test Framework Environment
|Environment|Version|Description|
|------------|------------|------------|
|Operating system|Ubuntu 18.04 or later|Provides the build environment.|
|Linux extend component|libreadline-dev|Allows users to edit command lines.|
|Python|3.7.5 or later|Provides the programming language for the test framework.|
|Python Plug-ins|pyserial 3.3 or later<br>paramiko 2.7.1 or later<br>setuptools 40.8.0 or later<br>RSA 4.0 or later|- pyserial: supports serial port communication in Python.<br>- paramiko: allows SSH in Python.<br>- setuptools: allows creation and distribution of Python packages.<br>-RSA: implements RSA encryption in Python.|
|NFS Server|haneWIN NFS Server 1.2.50 or later or NFS v4 or later|Allows devices to be connected over a serial port.|
|HDC|1.1.0 or later|Allows devices to be connected by using the OpenHarmony Device Connector (HDC).|
#### Installation Process
1. Run the following command to install the Linux extended component libreadline:
```
sudo apt-get install libreadline-dev
```
The installation is successful if the following information is displayed:
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
libreadline-dev is already the newest version (7.0-3).
0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded.
```
2. Run the following command to install the setuptools plug-in:
```
pip3 install setuptools
```
The installation is successful if the following information is displayed:
```
Requirement already satisfied: setuptools in d:\programs\python37\lib\site-packages (41.2.0)
```
3. Run the following command to install the paramiko plug-in:
```
pip3 install paramiko
```
The installation is successful if the following information is displayed:
```
Installing collected packages: pycparser, cffi, pynacl, bcrypt, cryptography, paramiko
Successfully installed bcrypt-3.2.0 cffi-1.14.4 cryptography-3.3.1 paramiko-2.7.2 pycparser-2.20 pynacl-1.4.0
```
4. Run the following command to install the rsa plug-in:
```
pip3 install rsa
```
The installation is successful if the following information is displayed:
```
Installing collected packages: pyasn1, rsa
Successfully installed pyasn1-0.4.8 rsa-4.7
```
5. Run the following command to install the pyserial plug-in:
```
pip3 install pyserial
```
The installation is successful if the following information is displayed:
```
Requirement already satisfied: pyserial in d:\programs\python37\lib\site-packages\pyserial-3.4-py3.7.egg (3.4)
```
6. Install the NFS server if the device outputs results only through the serial port.
- For Windows, install, for example, haneWIN NFS Server 1.2.50.
- For Linux, run the following command to install the NFS server:
```
sudo apt install nfs-kernel-server
```
The installation is successful if the following information is displayed:
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
nfs-kernel-server is already the newest version (1:1.3.4-2.1ubuntu5.3).
0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded.
```
7. Install the HDC tool if the device supports HDC connections.
For details, see https://gitee.com/openharmony/developtools_hdc_standard/blob/master/README.md
## Checking the Installation Environment
| Check Item|Operation |Requirements |
| --- | --- | --- |
| Check whether Python is installed successfully.|Run the **python --version** command. |The Python version is 3.7.5 or later.|
| Check whether Python plug-ins are successfully installed.|Go to the **test/developertest** directory and run **start.bat** or **start.sh**.| The **>>>** prompt is displayed.|
|Check the NFS server status (for the devices that support only serial port output). |Log in to the development board through the serial port and run the **mount** command to mount the NFS. |The file directory can be mounted. |
|Check whether the HDC is successfully installed. |Run the **hdc_std -v** command.|The HDC version is 1.1.0 or later.|
## Directory Structure
The directory structure of the test framework is as follows:
```
test # Test subsystem
├── developertest # Developer test module
│ ├── aw # Static library of the test framework
│ ├── config # Test framework configuration
│ │ │ ...
│ │ └── user_config.xml # User configuration
│ ├── examples # Examples of test cases
│ ├── src # Source code of the test framework
│ ├── third_party # Adaptation code for third-party components on which the test framework depends
│ ├── reports # Test reports
│ ├── BUILD.gn # Build entry of the test framework
│ ├── start.bat # Test entry for Windows
│ └── start.sh # Test entry for Linux
└── xdevice # Modules on which the test framework depends
```
## Writing Test Cases
### Designing the Test Case Directory
Design the test case directory as follows:
```
subsystem # Subsystem
├── partA # Part A
│ ├── moduleA # Module A
│ │ ├── include
│ │ ├── src # Service code
│ │ └── test # Test directory
│ │ ├── unittest # Unit test
│ │ │ ├── common # Common test cases
│ │ │ │ ├── BUILD.gn # Build file of test cases
│ │ │ │ └── testA_test.cpp # Source code of unit test cases
│ │ │ ├── phone # Test cases for mobile phones
│ │ │ ├── ivi # Test cases for head units
│ │ │ └── liteos-a # Test cases for IP cameras using LiteOS
│ │ ├── moduletest # Module test
│ │ ...
│ │
│ ├── moduleB # Module B
│ ├── test
│ │ └── resource # Dependency resources
│ │ ├── moduleA # Module A
│ │ │ ├── ohos_test.xml # Resource configuration file
│ │ ... └── 1.txt # Resource file
│ │
│ ├── ohos_build # Build entry configuration
│ ...
...
```
> **CAUTION**<br>Test cases are classified into common test cases and device-specific test cases. You are advised to place common test cases in the **common** directory and device-specific test cases in the directories of the related devices.
### Writing Test Cases
This test framework supports test cases written in multiple programming languages and provides different templates for different languages.
**C++ Test Case Example**
- Naming rules for source files
The source file name of test cases must be the same as that of the test suite. The file names must use lowercase letters and in the [Function]\_[Sub-function]\_**test** format. More specific sub-functions can be added as required.
Example:
```
calculator_sub_test.cpp
```
- Test case example
```
/*
* Copyright (c) 2022 XXXX Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "calculator.h"
#include <gtest/gtest.h>
using namespace testing::ext;
class CalculatorSubTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void CalculatorSubTest::SetUpTestCase(void)
{
// Set a setup function, which will be called before all test cases.
}
void CalculatorSubTest::TearDownTestCase(void)
{
// Set a teardown function, which will be called after all test cases.
}
void CalculatorSubTest::SetUp(void)
{
// Set a setup function, which will be called before each test case.
}
void CalculatorSubTest::TearDown(void)
{
// Set a teardown function, which will be called after each test case.
}
/**
* @tc.name: integer_sub_001
* @tc.desc: Verify the sub function.
* @tc.type: FUNC
* @tc.require: Issue Number
*/
HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1)
{
// Step 1 Call the function to obtain the result.
int actual = Sub(4, 0);
// Step 2 Use an assertion to compare the obtained result with the expected result.
EXPECT_EQ(4, actual);
}
```
The procedure is as follows:
1. Add comment information to the test case file header.
```
/*
* Copyright (c) 2022 XXXX Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
```
2. Add the test framework header file and namespace.
```
#include <gtest/gtest.h>
using namespace testing::ext;
```
3. Add the header file of the test class.
```
#include "calculator.h"
```
4. Define the test suite (test class).
```
class CalculatorSubTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void CalculatorSubTest::SetUpTestCase(void)
{
// Set a setup function, which will be called before all test cases.
}
void CalculatorSubTest::TearDownTestCase(void)
{
// Set a teardown function, which will be called after all test cases.
}
void CalculatorSubTest::SetUp(void)
{
// Set a setup function, which will be called before each test case.
}
void CalculatorSubTest::TearDown(void)
{
// Set a teardown function, which will be called after each test case.
}
```
> **CAUTION**:<br>When defining a test suite, ensure that the test suite name is the same as the target to build and uses the upper camel case style.
5. Add implementation of the test cases, including test case comments and logic.
```
/**
* @tc.name: integer_sub_001
* @tc.desc: Verify the sub function.
* @tc.type: FUNC
* @tc.require: Issue Number
*/
HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1)
{
// Step 1 Call the function to obtain the test result.
int actual = Sub(4, 0);
// Step 2 Use an assertion to compare the obtained result with the expected result.
EXPECT_EQ(4, actual);
}
```
The following test case templates are provided for your reference.
| Type| Description|
| ------------| ------------|
| HWTEST(A,B,C)| Use this template if the test case execution does not depend on setup or teardown.|
| HWTEST_F(A,B,C)| Use this template if the test case execution (excluding parameters) depends on setup and teardown.|
| HWTEST_P(A,B,C)| Use this template if the test case execution (including parameters) depends on setup and teardown.|
In the template names:
- *A* indicates the test suite name.
- *B* indicates the test case name, which is in the *Function*\_*No.* format. The *No.* is a three-digit number starting from **001**.
- *C* indicates the test case level. There are five test case levels: guard-control level 0 and non-guard-control level 1 to level 4. Of levels 1 to 4, a smaller value indicates a more important function verified by the test case.
**CAUTION**<br>
- The expected result of each test case must have an assertion.
- The test case level must be specified.
- It is recommended that the test be implemented step by step according to the template.
- The comment must contain the test case name, description, type, and requirement number, which are in the @tc.*xxx*: *value* format. The test case type @**tc.type** can be any of the following:
| Test Case Type|Code|
| ------------|------------|
|Function test |FUNC|
|Performance Test |PERF|
|Reliability test |RELI|
|Security test |SECU|
|Fuzzing |FUZZ|
**JavaScript Test Case Example**
- Naming rules for source files
The source file name of a test case must be in the [Function]\[Sub-function]Test format, and each part must use the upper camel case style. More specific sub-functions can be added as required.
Example:
```
AppInfoTest.js
```
- Test case example
```
/*
* Copyright (C) 2022 XXXX Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import app from '@system.app'
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
describe("AppInfoTest", function () {
beforeAll(function() {
// Set a setup function, which will be called before all test cases.
console.info('beforeAll called')
})
afterAll(function() {
// Set a teardown function, which will be called after all test cases.
console.info('afterAll called')
})
beforeEach(function() {
// Set a setup function, which will be called before each test case.
console.info('beforeEach called')
})
afterEach(function() {
// Set a teardown function, which will be called after each test case.
console.info('afterEach called')
})
/*
* @tc.name:appInfoTest001
* @tc.desc:verify app info is not null
* @tc.type: FUNC
* @tc.require: Issue Number
*/
it("appInfoTest001", 0, function () {
// Step 1 Call the function to obtain the test result.
var info = app.getInfo()
// Step 2 Use an assertion to compare the obtained result with the expected result.
expect(info != null).assertEqual(true)
})
})
```
The procedure is as follows:
1. Add comment information to the test case file header.
```
/*
* Copyright (C) 2022 XXXX Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
```
2. Import the APIs and JSUnit test library to test.
```
import app from '@system.app'
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'
```
3. Define the test suite (test class).
```
describe("AppInfoTest", function () {
beforeAll(function() {
// Set a setup function, which will be called before all test cases.
console.info('beforeAll called')
})
afterAll(function() {
// Set a teardown function, which will be called after all test cases.
console.info('afterAll called')
})
beforeEach(function() {
// Set a setup function, which will be called before each test case.
console.info('beforeEach called')
})
afterEach(function() {
// Set a teardown function, which will be called after each test case.
console.info('afterEach called')
})
```
4. Add implementation of the test cases.
```
/*
* @tc.name:appInfoTest001
* @tc.desc:verify app info is not null
* @tc.type: FUNC
* @tc.require: Issue Number
*/
it("appInfoTest001", 0, function () {
// Step 1 Call the function to obtain the test result.
var info = app.getInfo()
// Step 2 Use an assertion to compare the obtained result with the expected result.
expect(info != null).assertEqual(true)
})
```
### Writing the Build File for Test Cases
When a test case is executed, the test framework searches for the build file of the test case in the test case directory and builds the test case located. The following describes how to write build files (GN files) in different programming languages.
#### Writing Build Files for Test Cases
The following provides templates for different languages for your reference.
- **Test case build file example (C++)**
```
# Copyright (c) 2022 XXXX Device Co., Ltd.
import("//build/test.gni")
module_output_path = "subsystem_examples/calculator"
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [ "../../../include" ]
}
ohos_unittest("CalculatorSubTest") {
module_out_path = module_output_path
sources = [
"../../../include/calculator.h",
"../../../src/calculator.cpp",
]
sources += [ "calculator_sub_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [ "//third_party/googletest:gtest_main" ]
}
group("unittest") {
testonly = true
deps = [":CalculatorSubTest"]
}
```
The procedure is as follows:
1. Add comment information for the file header.
```
# Copyright (c) 2022 XXXX Device Co., Ltd.
```
2. Import the build template.
```
import("//build/test.gni")
```
3. Specify the file output path.
```
module_output_path = "subsystem_examples/calculator"
```
> **NOTE**<br>The output path is ***Part_name*/*Module_name***.
4. Configure the directories for dependencies.
```
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [ "../../../include" ]
}
```
> **NOTE**<br>Generally, the dependency directories are configured here and directly referenced in the build script of the test case.
5. Set the output build file for the test cases.
```
ohos_unittest("CalculatorSubTest") {
}
```
6. Write the build script (add the source file, configuration, and dependencies) for the test cases.
```
ohos_unittest("CalculatorSubTest") {
module_out_path = module_output_path
sources = [
"../../../include/calculator.h",
"../../../src/calculator.cpp",
"../../../test/calculator_sub_test.cpp"
]
sources += [ "calculator_sub_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [ "//third_party/googletest:gtest_main" ]
}
```
> **NOTE**<br>Set the test type based on actual requirements. The following test types are available:
> - **ohos_unittest**: unit test
> - **ohos_moduletest**: module test
> - **ohos_systemtest**: system test
> - **ohos_performancetest**: performance test
> - **ohos_securitytest**: security test
> - **ohos_reliabilitytest**: reliability test
> - **ohos_distributedtest**: distributed test
7. Group the test case files by test type.
```
group("unittest") {
testonly = true
deps = [":CalculatorSubTest"]
}
```
> **NOTE**<br>Grouping test cases by test type allows you to execute a specific type of test cases when required.
- Test case build file example (JavaScript)
```
# Copyright (C) 2022 XXXX Device Co., Ltd.
import("//build/test.gni")
module_output_path = "subsystem_examples/app_info"
ohos_js_unittest("GetAppInfoJsTest") {
module_out_path = module_output_path
hap_profile = "./config.json"
certificate_profile = "//test/developertest/signature/openharmony_sx.p7b"
}
group("unittest") {
testonly = true
deps = [ ":GetAppInfoJsTest" ]
}
```
The procedure is as follows:
1. Add comment information for the file header.
```
# Copyright (C) 2022 XXXX Device Co., Ltd.
```
2. Import the build template.
```
import("//build/test.gni")
```
3. Specify the file output path.
```
module_output_path = "subsystem_examples/app_info"
```
> **NOTE**<br>The output path is ***Part_name*/*Module_name***.
4. Set the output build file for the test cases.
```
ohos_js_unittest("GetAppInfoJsTest") {
}
```
> **NOTE**<br>
>- Use the **ohos\_js\_unittest** template to define the JavaScript test suite. Pay attention to the difference between JavaScript and C++.
>- The file generated for the JavaScript test suite must be in .hap format and named after the test suite name defined here. The test suite name must end with **JsTest**.
5. Configure the **config.json** file and signature file, which are mandatory.
```
ohos_js_unittest("GetAppInfoJsTest") {
module_out_path = module_output_path
hap_profile = "./config.json"
certificate_profile = "//test/developertest/signature/openharmony_sx.p7b"
}
```
**config.json** is the configuration file required for HAP build. You need to set **target** based on the tested SDK version. Default values can be retained for other items. The following is an example:
```
{
"app": {
"bundleName": "com.example.myapplication",
"vendor": "example",
"version": {
"code": 1,
"name": "1.0"
},
"apiVersion": {
"compatible": 4,
"target": 5 // Set it based on the tested SDK version. In this example, SDK5 is used.
}
},
"deviceConfig": {},
"module": {
"package": "com.example.myapplication",
"name": ".MyApplication",
"deviceType": [
"phone"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "entry",
"moduleType": "entry"
},
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"name": "com.example.myapplication.MainAbility",
"icon": "$media:icon",
"description": "$string:mainability_description",
"label": "MyApplication",
"type": "page",
"launchType": "standard"
}
],
"js": [
{
"pages": [
"pages/index/index"
],
"name": "default",
"window": {
"designWidth": 720,
"autoDesignWidth": false
}
}
]
}
}
```
6. Group the test case files by test type.
```
group("unittest") {
testonly = true
deps = [ ":GetAppInfoJsTest" ]
}
```
> **NOTE**<br>Grouping test cases by test type allows you to execute a specific type of test cases when required.
#### Configuring ohos.build
Configure the part build file to associate with specific test cases.
```
"partA": {
"module_list": [
],
"inner_list": [
],
"system_kits": [
],
"test_list": [
"//system/subsystem/partA/calculator/test:unittest" // Configure test under calculator.
]
}
```
> **NOTE**<br>**test_list** contains the test cases of the corresponding module.
### Configuring Test Case Resources
Test case resources include external file resources, such as image files, video files, and third-party libraries, required for test case execution.
Perform the following steps:
1. Create the **resource** directory in the **test** directory of the part, and create a directory for the module in the **resource** directory to store resource files of the module.
2. In the module directory under **resource**, create the **ohos_test.xml** file in the following format:
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration ver="2.0">
<target name="CalculatorSubTest">
<preparer>
<option name="push" value="test.jpg -> /data/test/resource" src="res"/>
<option name="push" value="libc++.z.so -> /data/test/resource" src="out"/>
</preparer>
</target>
</configuration>
```
3. In the build file of the test cases, configure **resource_config_file** to point to the resource file **ohos_test.xml**.
```
ohos_unittest("CalculatorSubTest") {
resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml"
}
```
>**NOTE**
>- **target_name** indicates the test suite name defined in the **BUILD.gn** file in the **test** directory.
>- **preparer** indicates the action to perform before the test suite is executed.
>- **src="res"** indicates that the test resources are in the **resource** directory under the **test** directory.
>- **src="out"** indicates that the test resources are in the **out/release/$(*part*)** directory.
## Executing Test Cases
Before executing test cases, you need to modify the configuration based on the device used.
### Modifying user_config.xml
```
<user_config>
<build>
<!-- Whether to build a demo case. The default value is false. If a demo case is required, change the value to true. -->
<example>false</example>
<!-- Whether to build the version. The default value is false. -->
<version>false</version>
<!-- Whether to build the test cases. The default value is true. If the build is already complete, change the value to false before executing the test cases.-->
<testcase>true</testcase>
</build>
<environment>
<!-- Configure the IP address and port number of the remote server to support connection to the device through the HDC.-->
<device type="usb-hdc">
<ip></ip>
<port></port>
<sn></sn>
</device>
<!-- Configure the serial port information of the device to enable connection through the serial port.-->
<device type="com" label="ipcamera">
<serial>
<com></com>
<type>cmd</type>
<baud_rate>115200</baud_rate>
<data_bits>8</data_bits>
<stop_bits>1</stop_bits>
<timeout>1</timeout>
</serial>
</device>
</environment>
<!-- Configure the test case path. If the test cases have not been built (<testcase> is true), leave this parameter blank. If the build is complete, enter the path of the test cases.-->
<test_cases>
<dir></dir>
</test_cases>
<!-- Configure the coverage output path.-->
<coverage>
<outpath></outpath>
</coverage>
<!-- Configure the NFS mount information when the tested device supports only the serial port connection. Specify the NFS mapping path. host_dir indicates the NFS directory on the PC, and board_dir indicates the directory created on the board. -->
<NFS>
<host_dir></host_dir>
<mnt_cmd></mnt_cmd>
<board_dir></board_dir>
</NFS>
</user_config>
```
>**NOTE**<br>If HDC is connected to the device before the test cases are executed, you only need to configure the device IP address and port number, and retain the default settings for other parameters.
### Executing Test Cases on Windows
#### Building Test Cases
Test cases cannot be built on Windows. You need to run the following command to build test cases on Linux:
```
./build.sh --product-name hispark_taurus_standard --build-target make_test
```
>**NOTE**
>
>- **product-name**: specifies the name of the product to build, for example, **hispark_taurus_standard**.
>- **build-target**: specifies the test case to build. **make_test** indicates all test cases. You can specify the test cases based on requirements.
When the build is complete, the test cases are automatically saved in **out/hispark_taurus/packages/phone/tests**.
#### Setting Up the Execution Environment
1. On Windows, create the **Test** directory in the test framework and then create the **testcase** directory in the **Test** directory.
2. Copy **developertest** and **xdevice** from the Linux environment to the **Test** directory on Windows, and copy the test cases to the **testcase** directory.
>**NOTE**<br>Port the test framework and test cases from the Linux environment to the Windows environment for subsequent execution.
3. Modify the **user_config.xml** file.
```
<build>
<!-- Because the test cases have been built, change the value to false. -->
<testcase>false</testcase>
</build>
<test_cases>
<!-- The test cases are copied to the Windows environment. Change the test case output path to the path of the test cases in the Windows environment.-->
<dir>D:\Test\testcase\tests</dir>
</test_cases>
```
>**NOTE**<br>**<testcase>** indicates whether to build test cases. **<dir>** indicates the path for searching for test cases.
#### Executing Test Cases
1. Start the test framework.
```
start.bat
```
2. Select the product.
After the test framework starts, you are asked to select a product. Select the development board to test, for example, **Hi3516DV300**.
3. Execute test cases.
Run the following command to execute test cases:
```
run -t UT -ts CalculatorSubTest -tc integer_sub_00l
```
In the command:
```
-t [TESTTYPE]: specifies the test case type, which can be UT, MST, ST, or PERF. This parameter is mandatory.
-tp [TESTPART]: specifies the part to test. This parameter can be used independently.
-tm [TESTMODULE]: specifies the module to test. This parameter must be specified together with -tp.
-ts [TESTSUITE]: specifies the test suite. This parameter can be used independently.
-tc [TESTCASE]: specifies the test case. This parameter must be specified together with -ts.
You can run h to display help information.
```
### Executing Test Cases on Linux
#### Mapping the Remote Port
To enable test cases to be executed on a remote Linux server or a Linux VM, map the port to enable communication between the device and the remote server or VM. Configure port mapping as follows:
1. On the HDC server, run the following commands:
```
hdc_std kill
hdc_std -m -s 0.0.0.0:8710
```
>**NOTE**<br>The IP address and port number are default values.
2. On the HDC client, run the following command:
```
hdc_std -s xx.xx.xx.xx:8710 list targets
```
>**NOTE**<br>Enter the IP address of the device to test.
#### Executing Test Cases
1. Start the test framework.
```
./start.sh
```
2. Select the product.
After the test framework starts, you are asked to select a product. Select the development board to test, for example, **Hi3516DV300**.
3. Execute test cases.
The test framework locates the test cases based on the command, and automatically builds and executes the test cases.
```
run -t UT -ts CalculatorSubTest -tc integer_sub_00l
```
In the command:
```
-t [TESTTYPE]: specifies the test case type, which can be UT, MST, ST, or PERF. This parameter is mandatory.
-tp [TESTPART]: specifies the part to test. This parameter can be used independently.
-tm [TESTMODULE]: specifies the module to test. This parameter must be specified together with -tp.
-ts [TESTSUITE]: specifies the test suite. This parameter can be used independently.
-tc [TESTCASE]: specifies the test case. This parameter must be specified together with -ts.
You can run h to display help information.
```
## Viewing the Test Report
After the test cases are executed, the test result will be automatically generated. You can view the detailed test result in the related directory.
### Test Result
You can obtain the test result in the following directory:
```
test/developertest/reports/xxxx_xx_xx_xx_xx_xx
```
>**NOTE**<br>The folder for test reports is automatically generated.
The folder contains the following files:
| Type| Description|
| ------------ | ------------ |
| result/ |Test cases in standard format.|
| log/plan_log_xxxx_xx_xx_xx_xx_xx.log | Test case logs.|
| summary_report.html | Test report summary.|
| details_report.html | Detailed test report.|
### Test Framework Logs
```
reports/platform_log_xxxx_xx_xx_xx_xx_xx.log
```
### Latest Test Report
```
reports/latest
```
# XTS Test Case Development
## Introduction
The X test suite (XTS) subsystem contains a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite (ACTS) and the device compatibility test suite (DCTS) that will be supported in the future.
This subsystem contains the ACTS and **tools** software package.
- The **acts** directory stores the source code and configuration files of ACTS test cases. The ACTS helps device vendors detect the software incompatibility as early as possible and ensures that the software is compatible to OpenHarmony during the entire development process.
- The **tools** software package stores the test case development framework related to **acts**.
## System Types
OpenHarmony supports the following systems:
- Mini system
A mini system runs on a device that comes with memory greater than or equal to 128 KiB and MCU such as ARM Cortex-M and 32-bit RISC-V. It provides multiple lightweight network protocols and graphics frameworks, and a wide range of read/write components for the IoT bus. Typical products include connection modules, sensors, and wearables for smart home.
- Small system
A small system runs on a device that comes with memory greater than or equal to 1 MiB and application processors such as ARM Cortex-A. It provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders (EDRs) for smart travel.
- Standard system
A standard system runs on a device that comes with memory greater than or equal to 128 MiB and application processors such as ARM Cortex-A. It provides a complete application framework supporting the enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. This system applies to high-end refrigerator displays.
## Directory Structure
```
/test/xts
├── acts # Test code
│ └── subsystem # Source code of subsystem test cases for the standard system
│ └── subsystem_lite # Source code of subsystems test cases for mini and small systems
│ └── BUILD.gn # Build configuration of test cases for the standard system
│ └── build_lite # Build configuration of test cases for the mini and small systems.
│ └── BUILD.gn # Build configuration of test cases for mini and small systems
└── tools # Test tool code
```
## Constraints
Test cases for the mini system must be developed in C, and those for the small system must be developed in C++.
## Usage Guidelines
**Table 1** Test case levels
| Level | Definition | Scope |
| ----- | ----------- | ------- |
| Level0 | Smoke | Verifies basic functionalities of key features and basic DFX attributes with the most common input. The pass result indicates that the features are runnable. |
| Level1 | Basic | Verifies basic functionalities of key features and basic DFX attributes with common input. The pass result indicates that the features are testable. |
| Level2 | Major | Verifies basic functionalities of key features and basic DFX attributes with common input and errors. The pass result indicates that the features are functional and ready for beta testing. |
| Level3 | Regular | Verifies functionalities of all key features, and all DFX attributes with common and uncommon input combinations or normal and abnormal preset conditions. |
| Level4 | Rare | Verifies functionalities of key features under extremely abnormal presets and uncommon input combinations. |
**Table 2** Test case granularities
| Test Scale | Test Objects | Test Environment |
| ----- | ----------- | ------- |
| LargeTest | Service functionalities, all-scenario features, and mechanical power environment (MPE) and scenario-level DFX | Devices close to real devices. |
| MediumTest | Modules, subsystem functionalities after module integration, and DFX | Single device that is actually used. You can perform message simulation, but do not mock functions. |
| SmallTest | Modules, classes, and functions | Local PC. Use a large number of mocks to replace dependencies with other modules. |
**Table 3** Test types
| Type | Definition |
| ----------- | ------- |
| Function | Tests the correctness of both service and platform functionalities provided by the tested object for end users or developers. |
| Performance | Tests the processing capability of the tested object under specific preset conditions and load models. The processing capability is measured by the service volume that can be processed in a unit time, for example, call per second, frame per second, or event processing volume per second. |
| Power | Tests the power consumption of the tested object in a certain period of time under specific preset conditions and load models. |
| Reliability | Tests the service performance of the tested object under common and uncommon input conditions, or specified service volume pressure and long-term continuous running pressure. The test covers stability, pressure handling, fault injection, and Monkey test times. |
| Security | Tests the capability of defending against security threats, including but not limited to unauthorized access, use, disclosure, damage, modification, and destruction, to ensure information confidentiality, integrity, and availability.<br/>Tests the privacy protection capability to ensure that the collection, use, retention, disclosure, and disposal of users' private data comply with laws and regulations.<br/> Tests the compliance with various security specifications, such as security design, security requirements, and security certification of the Ministry of Industry and Information Technology (MIIT). |
| Global | Tests the internationalized data and localization capabilities of the tested object, including multi-language display, various input/output habits, time formats, and regional features, such as currency, time, and culture taboos. |
| Compatibility | Tests backward compatibility of an application with its own data, the forward and backward compatibility with the system, and the compatibility with different user data, such as audio file content of the player and smart SMS messages.<br/>Tests system backward compatibility with its own data and the compatibility of common applications in the ecosystem.<br/>Tests software compatibility with related hardware. |
| User | Tests user experience of the object in real user scenarios. All conclusions and comments should come from the users, which are all subjective evaluation in this case. |
| Standard | Tests the compliance with industry and company-specific standards, protocols, and specifications. The standards here do not include any security standards that should be classified into the security test. |
| Safety | Tests the safety property of the tested object to avoid possible hazards to personal safety, health, and the object itself. |
| Resilience | Tests the resilience property of the tested object to ensure that it can withstand and maintain the defined running status (including downgrading) when being attacked, and recover from and adapt defense to the attacks to approach mission assurance. |
## Test Case Development Guidelines
The test framework and programming language vary with the system type.
**Table 4** Test frameworks and test case languages for different systems
| System | Test Framework | Language |
| ----- | ----------- | ------- |
| Mini | HCTest | C |
| Small | HCPPTest | C++ |
| Standard | HJSUnit and HCPPTest | JavaScript and C++ |
### Developing Test Cases in C (for the Mini System)
**Developing Test Cases for the Mini System**
HCTest and the C language are used to develop test cases. HCTest is enhanced and adapted based on the open-source test framework Unity.
1. Define the test case directory. The test cases are stored to **test/xts/acts**.
```
├── acts
│ └──subsystem_lite
│ │ └── module_hal
│ │ │ └── BUILD.gn
│ │ │ └── src
│ └──build_lite
│ │ └── BUILD.gn
```
2. Write the test case in the **src** directory.
(1) Include the test framework header file.
```
#include "hctest.h"
```
(2) Use the **LITE_TEST_SUIT** macro to define names of the subsystem, module, and test suite.
```
/**
* @brief register a test suite named "IntTestSuite"
* @param test subsystem name
* @param example module name
* @param IntTestSuite test suite name
*/
LITE_TEST_SUIT(test, example, IntTestSuite);
```
(3) Define Setup and TearDown.
​ Format: Test suite name+Setup, Test suite name+TearDown.
​ The Setup and TearDown functions must exist, but function bodies can be empty.
(4) Use the **LITE_TEST_CASE** macro to write the test case.
​ Three parameters are involved: test suite name, test case name, and test case properties (including type, granularity, and level).
```
LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1)
{
// Do something.
};
```
(5) Use the **RUN_TEST_SUITE** macro to register the test suite.
```
RUN_TEST_SUITE(IntTestSuite);
```
3. Create the configuration file (**BUILD.gn**) of the test module.
Create a **BUILD.gn** (example) file in each test module directory, and specify the name of the built static library and its dependent header files and libraries.
The format is as follows:
```
import("//test/xts/tools/lite/build/suite_lite.gni")
hctest_suite("ActsDemoTest") {
suite_name = "acts"
sources = [
"src/test_demo.c",
]
include_dirs = [ ]
cflags = [ "-Wno-error" ]
}
```
4. Add build options to the **BUILD.gn** file in the **acts** directory.
You need to add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
```
lite_component("acts") {
...
if(board_name == "liteos_m") {
features += [
...
"//xts/acts/subsystem_lite/module_hal:ActsDemoTest"
]
}
}
```
5. Run build commands.
Test suites are built along with the OS version. The ACTS is built together with the debug version.
>![](../public_sys-resources/icon-note.gif) **NOTE**<br/> The ACTS build middleware is a static library, which will be linked to the image.
### Executing Test Cases in C (for the Mini System)
**Executing Test Cases for the Mini System**
Burn the image into the development board.
**Executing the Test**
1. Use a serial port tool to log in to the development board and save information about the serial port.
2. Restart the device and view serial port logs.
**Analyzing the Test Result**
View the serial port logs in the following format:
The log for each test suite starts with "Start to run test suite:" and ends with "xx Tests xx Failures xx Ignored".
### Developing Test Cases in C++ (for Standard and Small Systems)
**Developing Test Cases for Small-System Devices** (for the standard system, see the **global/i18n_standard directory**.)
The HCPPTest framework, an enhanced version based on the open-source framework Googletest, is used.
1. Define the test case directory. The test cases are stored to **test/xts/acts**.
```
├── acts
│ └──subsystem_lite
│ │ └── module_posix
│ │ │ └── BUILD.gn
│ │ │ └── src
│ └──build_lite
│ │ └── BUILD.gn
```
2. Write the test case in the **src** directory.
(1) Include the test framework.
Include **gtest.h**.
```
#include "gtest/gtest.h"
```
(2) Define Setup and TearDown.
```
using namespace std;
using namespace testing::ext;
class TestSuite: public testing::Test {
protected:
// Preset action of the test suite, which is executed before the first test case
static void SetUpTestCase(void){
}
// Test suite cleanup action, which is executed after the last test case
static void TearDownTestCase(void){
}
// Preset action of the test case
virtual void SetUp()
{
}
// Cleanup action of the test case
virtual void TearDown()
{
}
};
```
(3) Use the **HWTEST** or **HWTEST_F** macro to write the test case.
**HWTEST**: definition of common test cases, including the test suite name, test case name, and case annotation.
**HWTEST_F**: definition of SetUp and TearDown test cases, including the test suite name, test case name, and case annotation.
Three parameters are involved: test suite name, test case name, and test case properties (including type, granularity, and level).
```
HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) {
// Do something
```
3. Create a configuration file (**BUILD.gn**) of the test module.
Create a **BUILD.gn** file in each test module directory, and specify the name of the built static library and its dependent header files and libraries. Each test module is independently built into a **.bin** executable file, which can be directly pushed to the development board for testing.
Example:
```
import("//test/xts/tools/lite/build/suite_lite.gni")
hcpptest_suite("ActsDemoTest") {
suite_name = "acts"
sources = [
"src/TestDemo.cpp"
]
include_dirs = [
"src",
...
]
deps = [
...
]
cflags = [ "-Wno-error" ]
}
```
4. Add build options to the **BUILD.gn** file in the **acts** directory.
Add the test module to the **test/xts/acts/build_lite/BUILD.gn** script in the **acts** directory.
```
lite_component("acts") {
...
else if(board_name == "liteos_a") {
features += [
...
"//xts/acts/subsystem_lite/module_posix:ActsDemoTest"
]
}
}
```
5. Run build commands.
Test suites are built along with the OS version. The ACTS is built together with the debug version.
>![](../public_sys-resources/icon-note.gif) **NOTE**
>
>The ACTS for the small system is independently built to an executable file (.bin) and archived in the **suites\acts** directory of the build result.
### Executing Test Cases in C++ (for Standard and Small Systems)
**Executing Test Cases for the Small System**
Currently, test cases are shared by the NFS and mounted to the development board for execution.
**Setting Up the Environment**
1. Use a network cable or wireless network to connect the development board to your PC.
2. Configure the IP address, subnet mask, and gateway for the development board. Ensure that the development board and the PC are in the same network segment.
3. Install and register the NFS server on the PC and start the NFS service.
4. Run the **mount** command for the development board to ensure that the development board can access NFS shared files on the PC.
Format: **mount** _NFS server IP address_**:/**_NFS shared directory_ **/**_development board directory_ **nfs**
Example:
```
mount 192.168.1.10:/nfs /nfs nfs
```
**Executing Test Cases**
Execute **ActsDemoTest.bin** to trigger test case execution, and analyze serial port logs generated after the execution is complete.
### Developing Test Cases in JavaScript (for the Standard System)
The HJSUnit framework is used to support automated test of OpenHarmony apps that are developed using the JavaScript language based on the JS application framework.
**Basic Syntax of Test Cases**
The test cases are developed with the JavaScript language and must meet the programming specifications of the language.
**Table 5** Basic syntax of test cases
| Syntax | Description | Mandatory |
| ------- | ------------- | ------------ |
| beforeAll | Presets a test-suite-level action executed only once before all test cases are executed. You can pass the action function as the only parameter. | No |
| afterAll | Presets a test-suite-level clear action executed only once after all test cases are executed. You can pass the clear function as the only parameter. | No |
| beforeEach | Presets a test-case-level action executed before each test case is executed. The number of execution times is the same as the number of test cases defined by it. You can pass the action function as the only parameter. | No |
| afterEach | Presets a test-case-level clear action executed after each test case is executed. The number of execution times is the same as the number of test cases defined by it. You can pass the clear function as the only parameter. | No |
| describe | Defines a test suite. You can pass two parameters: test suite name and test suite function. The describe statement supports nesting. You can use beforeall, beforeEach, afterEach, and afterAll in each describe statement. | Yes |
| it | Defines a test case. You can pass three parameters: test case name, filter parameter, and test case function. <br>**Filter parameter:** <br/>The value is a 32-bit integer. Setting different bits to 1 means different configurations.<br/> - Setting bit 0 to **1** means bypassing the filter. <br>- Setting bits 0-10 to **1** specifies the test case type, which can be FUNCTION (function test), PERFORMANCE (performance test), POWER (power consumption test), RELIABILITY (reliability test), SECURITY (security compliance test), GLOBAL (integrity test), COMPATIBILITY (compatibility test), USER (user test), STANDARD (standard test), SAFETY (security feature test), and RESILIENCE (resilience test), respectively.<br>- Setting bits 16-18 to **1** specifies the test case scale, which can be SMALL (small-scale test), MEDIUM (medium-scale test), and LARGE (large-scale test), respectively.<br>- Setting bits 24-28 to **1** specifies the test level, which can be LEVEL0 (level-0 test), LEVEL1 (level-1 test), LEVEL2 (level-2 test), LEVEL3 (level-3 test), and LEVEL4 (level-4 test), respectively.<br> | Yes |
Use the standard syntax of Jasmine to write test cases. The ES6 specification is supported.
1. Define the test case directory. The test cases are stored in the **entry/src/main/js/test** directory.
```
├── BUILD.gn
│ └──entry
│ │ └──src
│ │ │ └──main
│ │ │ │ └──js
│ │ │ │ │ └──default
│ │ │ │ │ │ └──pages
│ │ │ │ │ │ │ └──index
│ │ │ │ │ │ │ │ └──index.js # Entry file
│ │ │ │ │ └──test # Test code directory
│ │ │ └── resources # HAP resources
│ │ │ └── config.json # HAP configuration file
```
2. Start the JS test framework and load test cases.
The following is an example for **index.js**.
```
// Start the JS test framework and load test cases.
import {Core, ExpectExtend} from 'deccjsunit/index'
export default {
data: {
title: ""
},
onInit() {
this.title = this.$t('strings.world');
},
onShow() {
console.info('onShow finish')
const core = Core.getInstance()
const expectExtend = new ExpectExtend({
'id': 'extend'
})
core.addService('expect', expectExtend)
core.init()
const configService = core.getDefaultService('config')
configService.setConfig(this)
require('../../../test/List.test')
core.execute()
},
onReady() {
},
}
```
3. Write a unit test case.
The following is an example:
```
// Example 1: Use HJSUnit to perform a unit test.
describe('appInfoTest', function () {
it('app_info_test_001', 0, function () {
var info = app.getInfo()
expect(info.versionName).assertEqual('1.0')
expect(info.versionCode).assertEqual('3')
})
})
```
### Packaging Test Cases in JavaScript (for the Standard System)
For details about how to build a HAP, see the JS application development guide of the standard system [Building and Creating HAPs](https://developer.harmonyos.com/en/docs/documentation/doc-guides/build_overview-0000001055075201).
## Performing a Full Build (for the Standard System)
Run the following command:
```
./build.sh suite=acts system_size=standard
```
Test case directory: **out/release/suites/acts/testcases**
Test framework and test case directory: **out/release/suites/acts** \(the test suite execution framework is compiled during the build process)
## Executing Test Cases in a Full Build (for Small and Standard Systems)
**Setting Up a Test Environment**
Install Python 3.7 or a later version on a Windows environment and ensure that the Windows environment is properly connected to the test device.
**Test execution directory** \(corresponding to the **out/release/suites/acts** directory generated in the build)
```
├── testcase # Directory for storing test suite files
│ └──xxx.hap # HAP file executed by the test suite
│ └──xxx.json # Execution configuration file of the test suite
├── tools # Test framework tool directory
├── run.bat # File for starting the test suite on the Windows platform
├── report # Directory for storing the test reports
```
**Executing Test Cases**
1. On the Windows environment, locate the directory in which the test cases are stored \(**out/release/suites/acts**, copied from the Linux server), go to the directory in the Windows command window, and run **acts\\run.bat**.
2. Enter the command for executing the test case.
- Execute all test cases.
```
run acts
```
![](figure/en-us_image_0000001119924146.gif)
- Execute the test cases of a module \(view specific module information in **\acts\testcases\**).
```
run –l ActsSamgrTest
```
![](figure/en-us_image_0000001166643927.jpg)
You can view specific module information in **\acts\testcases\**.
Wait until the test cases are complete.
3. View the test report.
Go to **acts\reports**, obtain the current execution record, and open **summary_report.html** to view the test report.
# BundleStatusCallback
> **说明:**
> 从API version 9开始不再支持。建议使用[bundleMonitor](js-apis-bundleMonitor.md)替代
> 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本
应用状态回调的信息,通过接口[innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md)获取。
应用状态发生变化时回调的信息,通过接口[innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md)获取。
## BundleStatusCallback<sup>(deprecated)<sup>
......
......@@ -587,7 +587,7 @@ requestPermissionsFromUser(context: Context, permissions: Array&lt;Permissions&g
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.MANAGE_DISPOSED_APP_STATUS"], (err, data)=>{
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"], (err, data)=>{
console.info("data:" + JSON.stringify(data));
console.info("data permissions:" + data.permissions);
console.info("data authResults:" + data.authResults);
......@@ -633,7 +633,7 @@ requestPermissionsFromUser(context: Context, permissions: Array&lt;Permissions&g
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.MANAGE_DISPOSED_APP_STATUS"]).then((data) => {
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => {
console.info("data:" + JSON.stringify(data));
console.info("data permissions:" + data.permissions);
console.info("data authResults:" + data.authResults);
......
......@@ -16,14 +16,14 @@
| 名称 | 类型 | 可读 | 可写 | 说明 |
|----------------------------|------------------------------------------------------------------------|-----|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| name | string | 是 | 否 | 应用程序的名称。 |
| description | string | 是 | 否 | 应用程序的描述。 |
| descriptionId | number | 是 | 否 | 应用程序的描述id。 |
| description | string | 是 | 否 | 应用程序的描述信息。 |
| descriptionId | number | 是 | 否 | 应用程序的描述信息的资源id。 |
| systemApp | boolean | 是 | 否 | 判断是否为系统应用程序,默认为false。 |
| enabled | boolean | 是 | 否 | 判断应用程序是否可以使用,默认为true。 |
| label | string | 是 | 否 | 应用程序显示的标签。 |
| labelId | string | 是 | 否 | 应用程序的标签id。 |
| labelId | string | 是 | 否 | 应用程序的标签的资源id值。 |
| icon | string | 是 | 否 | 应用程序的图标。 |
| iconId | string | 是 | 否 | 应用程序的图标id。 |
| iconId | string | 是 | 否 | 应用程序图标的资源id值。 |
| process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称。 |
| supportedModes | number | 是 | 否 | 标识应用支持的运行模式,当前只定义了驾驶模式(drive)。该标签只适用于车机。 |
| moduleSourceDirs | Array\<string> | 是 | 否 | 应用程序的资源存放的相对路径。 |
......
......@@ -7,7 +7,7 @@
## BundleInstaller.install<sup>(deprecated)<sup>
> 从API version 9开始不再维护,建议使用[install](js-apis-installer.md)替代。
> 从API version 9开始不再维护,建议使用[@ohos.bundle.installer.install](js-apis-installer.md)替代。
install(bundleFilePaths: Array&lt;string&gt;, param: InstallParam, callback: AsyncCallback&lt;InstallStatus&gt;): void;
......@@ -42,7 +42,7 @@ let installParam = {
installFlag: 1,
};
bundle.getBundleInstaller().then(installer=>{
bundle.getBundleInstaller().then(installer => {
installer.install(hapFilePaths, installParam, err => {
if (err) {
console.error('install failed:' + JSON.stringify(err));
......@@ -92,7 +92,7 @@ let installParam = {
installFlag: 1,
};
bundle.getBundleInstaller().then(installer=>{
bundle.getBundleInstaller().then(installer => {
installer.uninstall(bundleName, installParam, err => {
if (err) {
console.error('uninstall failed:' + JSON.stringify(err));
......@@ -142,7 +142,7 @@ let installParam = {
installFlag: 1,
};
bundle.getBundleInstaller().then(installer=>{
bundle.getBundleInstaller().then(installer => {
installer.recover(bundleName, installParam, err => {
if (err) {
console.error('recover failed:' + JSON.stringify(err));
......@@ -165,9 +165,9 @@ bundle.getBundleInstaller().then(installer=>{
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------- | ------- | ---- | ---- | ------------------ |
| userId | number | 是 | 否 | 指示用户id |
| installFlag | number | 是 | 否 | 指示安装标志 |
| isKeepData | boolean | 是 | 否 | 指示参数是否有数据 |
| userId | number | 是 | 否 | 指示用户id, 默认值:调用方的userId |
| installFlag | number | 是 | 否 | 指示安装标志, 默认值:1, 取值范围:</br>1: 覆盖安装, </br>16: 免安装|
| isKeepData | boolean | 是 | 否 | 指示参数是否有数据,默认值:false |
## InstallStatus<sup>(deprecated)<sup>
......@@ -179,8 +179,8 @@ bundle.getBundleInstaller().then(installer=>{
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ |
| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | 是 | 否 | 表示安装或卸载错误状态码。 |
| statusMessage | string | 是 | 否 | 表示安装或卸载的字符串结果信息。 |
| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | 是 | 否 | 表示安装或卸载错误状态码。取值范围:枚举值[InstallErrorCode](js-apis-Bundle.md#installerrorcode) |
| statusMessage | string | 是 | 否 | 表示安装或卸载的字符串结果信息。取值范围包括:<br/> "SUCCESS" : 安装成功,</br> "STATUS_INSTALL_FAILURE": 安装失败(不存在安装文件), </br> "STATUS_INSTALL_FAILURE_ABORTED": 安装中止, </br> "STATUS_INSTALL_FAILURE_INVALID": 安装参数无效, </br> "STATUS_INSTALL_FAILURE_CONFLICT": 安装冲突(常见于升级和已有应用基本信息不一致), </br> "STATUS_INSTALL_FAILURE_STORAGE": 存储包信息失败, </br> "STATUS_INSTALL_FAILURE_INCOMPATIBLE": 安装不兼容(常见于版本降级安装或者签名信息错误), </br> "STATUS_UNINSTALL_FAILURE": 卸载失败(不存在卸载的应用), </br> "STATUS_UNINSTALL_FAILURE_ABORTED": 卸载中止(没有使用), </br> "STATUS_UNINSTALL_FAILURE_ABORTED": 卸载冲突(卸载系统应用失败, 结束应用进程失败), </br> "STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT": 安装失败(下载超时), </br> "STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED": 安装失败(下载失败), </br> "STATUS_RECOVER_FAILURE_INVALID": 恢复预置应用失败, </br> "STATUS_ABILITY_NOT_FOUND": Ability未找到, </br> "STATUS_BMS_SERVICE_ERROR": BMS服务错误, </br> "STATUS_FAILED_NO_SPACE_LEFT": 设备空间不足, </br> "STATUS_GRANT_REQUEST_PERMISSIONS_FAILED": 应用授权失败, </br> "STATUS_INSTALL_PERMISSION_DENIED": 缺少安装权限, </br> "STATUS_UNINSTALL_PERMISSION_DENIED": 缺少卸载权限|
## 获取应用的沙箱路径
对于FA模型,应用的沙箱路径可以通过[Context](js-apis-inner-app-context.md)中的方法获取;对于Stage模型,应用的沙箱路径可以通过[Context](js-apis-ability-context.md#abilitycontext)中的属性获取。下面以获取沙箱文件路径为例。
......
......@@ -10,6 +10,7 @@
```ts
import bundleManager from '@ohos.bundle.bundleManager'
```
## 权限列表
| 权限 | 权限等级 | 描述 |
......@@ -27,7 +28,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
包信息标志,指示需要获取的包信息的内容。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 | 值 | 说明 |
| ----------------------------------------- | ---------- | ------------------------------------------------------------ |
......@@ -45,7 +46,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
应用信息标志,指示需要获取的应用信息的内容。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统接口:** 系统接口,不支持三方应用调用。
......@@ -58,9 +59,9 @@ import bundleManager from '@ohos.bundle.bundleManager'
### AbilityFlag
功能组件信息标志,指示需要获取的功能组件信息的内容。
Ability组件信息标志,指示需要获取的Ability组件信息的内容。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统接口:** 系统接口,不支持三方应用调用。
......@@ -77,7 +78,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
扩展组件信息标志,指示需要获取的扩展组件信息的内容。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统接口:** 系统接口,不支持三方应用调用。
......@@ -92,7 +93,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
指示扩展组件的类型。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 | 值 | 说明 |
|:----------------:|:---:|-----|
......@@ -115,9 +116,9 @@ import bundleManager from '@ohos.bundle.bundleManager'
### PermissionGrantState
指示权限授予信息
指示权限授予状态
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 | 值 | 说明 |
|:----------------:|:---:|:---:|
......@@ -128,7 +129,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
标识该组件所支持的窗口模式。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 | 值 | 说明 |
|:----------------:|:---:|:---:|
......@@ -140,21 +141,21 @@ import bundleManager from '@ohos.bundle.bundleManager'
指示组件的启动方式。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 | 值 | 说明 |
|:----------------:|:---:|:---:|
| SINGLETON | 0 | ability的启动模式,表示单实例。 |
| STANDARD | 1 | ability的启动模式,表示普通多实例。 |
| SPECIFIED | 2 | ability的启动模式,表示该ability内部根据业务自己置顶多实例。 |
| SINGLETON | 0 | ability的启动模式表示单实例。 |
| STANDARD | 1 | ability的启动模式表示普通多实例。 |
| SPECIFIED | 2 | ability的启动模式表示该ability内部根据业务自己置顶多实例。 |
### AbilityType
指示Ability组件的类型。
**模型约束:** 仅可在FA模型下使用
**模型约束** 仅可在FA模型下使用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 | 值 | 说明 |
| :-----: | ---- | :--------------------------------------------------------: |
......@@ -166,7 +167,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
标识该Ability的显示模式。该标签仅适用于page类型的Ability。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
**系统能力** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。
| 名称 |值 |说明 |
|:----------------------------------|---|---|
......@@ -184,7 +185,7 @@ import bundleManager from '@ohos.bundle.bundleManager'
| AUTO_ROTATION_PORTRAIT_RESTRICTED |11|表示受开关控制的自动竖向旋转模式。|
| LOCKED |12|表示锁定模式。|
## 方法
## 接口
### bundleManager.getBundleInfoForSelf
......@@ -614,7 +615,7 @@ try {
getAllBundleInfo(bundleFlags: [number](#bundleflag), userId: number, callback: AsyncCallback<Array\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>>): void;
以异步方法根据给定的bundleFlags和userId获取多个BundleInfo,使用callback形式返回结果。
以异步方法根据给定的bundleFlags和userId获取系统中所有的BundleInfo,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -662,7 +663,7 @@ try {
getAllBundleInfo(bundleFlags: [number](#bundleflag), callback: AsyncCallback<Array\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>>): void;
以异步方法根据给定的bundleFlags获取多个BundleInfo,使用callback形式返回结果。
以异步方法根据给定的bundleFlags获取系统中所有的BundleInfo,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -708,7 +709,7 @@ try {
getAllBundleInfo(bundleFlags: [number](#bundleflag), userId?: number): Promise<Array\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>>;
以异步方法根据给定的bundleFlags和userId获取多个BundleInfo,使用Promise形式返回结果。
以异步方法根据给定的bundleFlags和userId获取系统中所有的BundleInfo,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -758,7 +759,7 @@ try {
getAllApplicationInfo(appFlags: [number](#applicationflag), userId: number, callback: AsyncCallback<Array\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>>): void;
以异步方法根据给定的appFlags和userId获取多个ApplicationInfo,使用callback形式返回结果。
以异步方法根据给定的appFlags和userId获取系统中所有的ApplicationInfo,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -806,7 +807,7 @@ try {
getAllApplicationInfo(appFlags: [number](#applicationflag), callback: AsyncCallback<Array\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>>): void;
以异步方法根据给定的appFlags获取多个ApplicationInfo,使用callback形式返回结果。
以异步方法根据给定的appFlags获取系统中所有的ApplicationInfo,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -852,7 +853,7 @@ try {
getAllApplicationInfo(appFlags: [number](#applicationflag), userId?: number): Promise<Array\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>>;
以异步方法根据给定的appFlags和userId获取多个ApplicationInfo,使用Promise形式返回结果。
以异步方法根据给定的appFlags和userId获取系统中所有的ApplicationInfo,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1290,7 +1291,7 @@ try {
getBundleNameByUid(uid: number, callback: AsyncCallback\<string>): void;
以异步方法根据给定的uid获取bundleName,使用callback形式返回结果。
以异步方法根据给定的uid获取对应的bundleName,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1335,7 +1336,7 @@ try {
getBundleNameByUid(uid: number): Promise\<string>;
以异步方法根据给定的uid获取bundleName,使用Promise形式返回结果。
以异步方法根据给定的uid获取对应的bundleName,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1482,7 +1483,7 @@ try {
cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\<void>): void;
以异步方法根据给定的bundleName清理BundleCache,并获取清理结果,使用callback形式返回结果。
以异步方法根据给定的bundleName清理BundleCache,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1529,7 +1530,7 @@ try {
cleanBundleCacheFiles(bundleName: string): Promise\<void>;
以异步方法根据给定的bundleName清理BundleCache,并获取清理结果,使用Promise形式返回结果。
以异步方法根据给定的bundleName清理BundleCache,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1547,7 +1548,7 @@ cleanBundleCacheFiles(bundleName: string): Promise\<void>;
| 类型 | 说明 |
| -------------- | ------------------------------------------------------------ |
| Promise\<void> | Promise对象,返回true表示清理应用缓存目录数据成功,返回false表示清理应用缓存目录数据失败。 |
| Promise\<void> | 无返回结果的Promise对象。当清理应用缓存目录数据失败会抛出错误对象。 |
**错误码:**
......@@ -1565,9 +1566,9 @@ import bundleManager from '@ohos.bundle.bundleManager'
let bundleName = "com.ohos.myapplication";
try {
bundleManager.cleanBundleCacheFiles(bundleName).then(()=> {
bundleManager.cleanBundleCacheFiles(bundleName).then(() => {
console.info('cleanBundleCacheFiles successfully.');
}).catch(err=> {
}).catch(err => {
console.error('cleanBundleCacheFiles failed:' + err.message);
});
} catch (err) {
......@@ -1579,7 +1580,7 @@ try {
setApplicationEnabled(bundleName: string, isEnabled: boolean, callback: AsyncCallback\<void>): void;
设置指定应用的禁用使能状态,使用callback形式返回结果。
设置指定应用的禁用使能状态,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1593,7 +1594,7 @@ setApplicationEnabled(bundleName: string, isEnabled: boolean, callback: AsyncCal
| ---------- | ------- | ---- | ------------------------------------- |
| bundleName | string | 是 | 指定应用的bundleName。 |
| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,当设置应用禁用使能状态成功时,err为null,否则为错误对象。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,当设置应用禁用使能状态成功时,err为null,否则为错误对象。 |
**错误码:**
......@@ -1626,7 +1627,7 @@ try {
setApplicationEnabled(bundleName: string, isEnabled: boolean): Promise\<void>;
设置指定应用的禁用使能状态,使用Promise形式返回结果。
设置指定应用的禁用使能状态,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1662,9 +1663,9 @@ import bundleManager from '@ohos.bundle.bundleManager'
let bundleName = "com.ohos.myapplication";
try {
bundleManager.setApplicationEnabled(bundleName, false).then(()=> {
bundleManager.setApplicationEnabled(bundleName, false).then(() => {
console.info('setApplicationEnabled successfully.');
}).catch(err=> {
}).catch(err => {
console.error('setApplicationEnabled failed:' + err.message);
});
} catch (err) {
......@@ -1676,7 +1677,7 @@ try {
setAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), isEnabled: boolean, callback: AsyncCallback\<void>): void;
设置指定组件的禁用使能状态,使用callback形式返回结果。
设置指定组件的禁用使能状态,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1690,7 +1691,7 @@ setAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), isE
| -------- | ----------- | ---- | ------------------------------------- |
| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 需要被设置的组件。 |
| isEnabled| boolean | 是 | 值为true表示使能,值为false表示禁用。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,当设置组件禁用使能状态成功时,err为null,否则为错误对象。 |
| callback | AsyncCallback\<void> | 是 | 回调函数,当设置组件禁用使能状态成功时,err为null,否则为错误对象。 |
**错误码:**
......@@ -1737,7 +1738,7 @@ try {
setAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), isEnabled: boolean): Promise\<void>;
设置指定组件的禁用使能状态,使用Promise形式返回结果。
设置指定组件的禁用使能状态,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1784,9 +1785,9 @@ try {
console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo));
info = abilitiesInfo[0];
bundleManager.setAbilityEnabled(info, false).then(()=> {
bundleManager.setAbilityEnabled(info, false).then(() => {
console.info('setAbilityEnabled successfully.');
}).catch(err=> {
}).catch(err => {
console.error('setAbilityEnabled failed:' + err.message);
});
}).catch(error => {
......@@ -1801,7 +1802,7 @@ try {
isApplicationEnabled(bundleName: string, callback: AsyncCallback\<boolean>): void;
以异步的方法获取指定应用的禁用使能状态,使用callback形式返回结果。
以异步的方法获取指定应用的禁用使能状态,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1845,7 +1846,7 @@ try {
isApplicationEnabled(bundleName: string): Promise\<boolean>;
以异步的方法获取指定应用的禁用使能状态,使用Promise形式返回结果。
以异步的方法获取指定应用的禁用使能状态,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1892,7 +1893,7 @@ try {
isAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), callback: AsyncCallback\<boolean>): void;
以异步的方法获取指定组件的禁用使能状态,使用callback形式返回结果。
以异步的方法获取指定组件的禁用使能状态,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -1950,7 +1951,7 @@ try {
isAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md)): Promise\<boolean>;
以异步的方法获取指定组件的禁用使能状态,使用Promise形式返回结果。
以异步的方法获取指定组件的禁用使能状态,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -2011,7 +2012,7 @@ try {
getLaunchWantForBundle(bundleName: string, userId: number, callback: AsyncCallback\<Want>): void;
以异步方法根据给定的bundleName和userId获取用于启动应用程序主要功能,使用callback形式返回结果。
以异步方法根据给定的bundleName和userId获取用于启动应用程序的Want参数,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -2061,7 +2062,7 @@ try {
getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\<Want>): void;
以异步方法根据给定的bundleName获取用于启动应用程序主要功能,使用callback形式返回结果。
以异步方法根据给定的bundleName获取用于启动应用程序的Want参数,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -2109,7 +2110,7 @@ try {
getLaunchWantForBundle(bundleName: string, userId?: number): Promise\<Want>;
以异步方法根据给定的bundleName和userId获取用于启动应用程序主要功能,使用Promise形式返回结果。
以异步方法根据给定的bundleName和userId获取用于启动应用程序的Want参数,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -2391,7 +2392,7 @@ try {
getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void;
以异步方法根据给定的permissionName获取PermissionDef,使用callback形式返回结果。
以异步方法根据给定的permissionName获取权限定义结构体PermissionDef信息,使用callback形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -2436,7 +2437,7 @@ try {
getPermissionDef(permissionName: string): Promise\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>;
以异步方法根据给定的permissionName获取PermissionDef,使用Promise形式返回结果。
以异步方法根据给定的permissionName获取权限定义结构体PermissionDef信息,使用Promise形式返回结果。
**系统接口:** 此接口为系统接口。
......@@ -2706,13 +2707,13 @@ try {
getApplicationInfoSync(bundleName: string, applicationFlags: number, userId: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md);
以同步方法根据给定的bundleName、applicationFlags和userId获取ApplicationInfo
以同步方法根据给定的bundleName、applicationFlags和userId获取ApplicationInfo
**系统接口:** 此接口为系统接口。
**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO
**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
**参数:**
......@@ -2758,7 +2759,7 @@ try {
getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md);
以同步方法根据给定的bundleName和applicationFlags获取ApplicationInfo
以同步方法根据给定的bundleName和applicationFlags获取ApplicationInfo
**系统接口:** 此接口为系统接口。
......
......@@ -171,7 +171,7 @@ popFirst(): T
| 类型 | 说明 |
| -------- | -------- |
| T | 返回被删除的元素。 |
| T | 返回被删除的元素。 |
**错误码:**
......@@ -205,7 +205,7 @@ popLast(): T
| 类型 | 说明 |
| -------- | -------- |
| T | 返回被删除的元素。 |
| T | 返回被删除的元素。 |
**错误码:**
......
......@@ -4361,7 +4361,7 @@ registerInputer(authType: AuthType, inputer: IInputer): void;
let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]);
try {
InputerMgr.registerInputer(authType, {
inputerMgr.registerInputer(authType, {
onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password);
}
......
......@@ -25,7 +25,7 @@
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.MANAGE_DISPOSED_APP_STATUS"]).then((data) => {
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => {
console.info("data:" + JSON.stringify(data));
console.info("data permissions:" + data.permissions);
console.info("data authResults:" + data.authResults);
......
# @ohos.wallpaper (壁纸)
壁纸管理服务是OpenHarmony中系统服务,是主题框架的部分组成,主要为系统提供壁纸管理服务能力,支持系统显示、设置、切换壁纸等功能。
壁纸管理服务是OpenHarmony中的系统服务,主要为系统提供壁纸管理服务能力,支持系统显示、设置、切换壁纸等功能。
> **说明:**
>
......@@ -197,7 +197,7 @@ restore(wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,移除壁纸成功,error为undefined 否则返回error信息。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,移除壁纸成功,error为undefined否则返回error信息。 |
**示例:**
......@@ -231,7 +231,7 @@ restore(wallpaperType: WallpaperType): Promise&lt;void&gt;
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
......@@ -259,7 +259,7 @@ setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | JPEG或PNG文件的Uri路径,或者PNG格式文件的位图。 |
| wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,设置壁纸成功,error为undefined 否则返回error信息。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,设置壁纸成功,error为undefined否则返回error信息。 |
**示例:**
......@@ -317,7 +317,7 @@ setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
......@@ -900,7 +900,7 @@ reset(wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,移除壁纸成功,error为undefined 否则返回error信息。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,移除壁纸成功,error为undefined否则返回error信息。 |
**示例:**
......@@ -938,7 +938,7 @@ reset(wallpaperType: WallpaperType): Promise&lt;void&gt;
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
......@@ -970,7 +970,7 @@ setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, call
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | JPEG或PNG文件的Uri路径,或者PNG格式文件的位图。 |
| wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,设置壁纸成功,error为undefined 否则返回error信息。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,设置壁纸成功,error为undefined否则返回error信息。 |
**示例:**
......@@ -1032,7 +1032,7 @@ setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Pro
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
......
......@@ -16,7 +16,7 @@
* 子组件可以将容器或者其他子组件设为锚点:
* 参与相对布局的容器内组件必须设置id,不设置id的组件不显示,容器id固定为__container__。
* 此子组件某一方向上的三个位置可以将容器或其他子组件的同方向三个位置为锚点,同方向上两个以上位置设置锚点以后会跳过第三个。
* 前端页面设置的子组件尺寸大小不会受到相对布局规则的影响。
* 前端页面设置的子组件尺寸大小不会受到相对布局规则的影响。子组件某个方向上设置两个或以上alignRules时不建议设置此方向尺寸大小。
* 对齐后需要额外偏移可设置offset。
* 特殊情况
* 互相依赖,环形依赖时容器内子组件全部不绘制。
......@@ -37,64 +37,67 @@ RelativeContainer()
@Entry
@Component
struct Index {
build() {
@Entry
@Component
struct Index {
build() {
Row() {
Button("Extra button").width(100).height(50)
RelativeContainer() {
Button("Button 1")
.width(120)
.height(30)
Row().width(100).height(100)
.backgroundColor("#FF3333")
.alignRules({
middle: { anchor: "__container__", align: HorizontalAlign.Center },
top: {anchor: "__container__", align: VerticalAlign.Top},
left: {anchor: "__container__", align: HorizontalAlign.Start}
})
.id("bt1")
.borderWidth(1)
.borderColor(Color.Black)
.id("row1")
Text("This is text 2")
.fontSize(20)
.padding(10)
Row().width(100).height(100)
.backgroundColor("#FFCC00")
.alignRules({
bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
top: { anchor: "bt1", align: VerticalAlign.Bottom },
right: { anchor: "bt1", align: HorizontalAlign.Center }
top: {anchor: "__container__", align: VerticalAlign.Top},
right: {anchor: "__container__", align: HorizontalAlign.End}
})
.id("tx2")
.borderWidth(1)
.borderColor(Color.Black)
.height(30)
Button("Button 3")
.width(100)
.height(100)
.id("row2")
Row().height(100)
.backgroundColor("#FF6633")
.alignRules({
left: { anchor: "bt1", align: HorizontalAlign.End },
top: { anchor: "tx2", align: VerticalAlign.Center },
bottom: { anchor: "__container__", align: VerticalAlign.Bottom }
top: {anchor: "row1", align: VerticalAlign.Bottom},
left: {anchor: "row1", align: HorizontalAlign.End},
right: {anchor: "row2", align: HorizontalAlign.Start}
})
.id("bt3")
.borderWidth(1)
.borderColor(Color.Black)
.id("row3")
Text("This is text 4")
.fontSize(20)
.padding(10)
Row()
.backgroundColor("#FF9966")
.alignRules({
left: { anchor: "tx2", align: HorizontalAlign.End },
right: { anchor: "__container__", align: HorizontalAlign.End },
top: { anchor: "__container__", align: VerticalAlign.Top },
bottom: { anchor: "bt3", align: VerticalAlign.Top }
top: {anchor: "row3", align: VerticalAlign.Bottom},
bottom: {anchor: "__container__", align: VerticalAlign.Bottom},
left: {anchor: "__container__", align: HorizontalAlign.Start},
right: {anchor: "row1", align: HorizontalAlign.End}
})
.id("tx4")
.borderWidth(1)
.borderColor(Color.Black)
.id("row4")
Row()
.backgroundColor("#FF66FF")
.alignRules({
top: {anchor: "row3", align: VerticalAlign.Bottom},
bottom: {anchor: "__container__", align: VerticalAlign.Bottom},
left: {anchor: "row2", align: HorizontalAlign.Start},
right: {anchor: "__container__", align: HorizontalAlign.End}
})
.id("row5")
}
.width(200).height(200)
.backgroundColor(Color.Orange)
.width(300).height(300)
.margin({left: 100})
.border({width:2, color: "#6699FF"})
}
.height('100%')
}
}
}
}
```
![relative container](figures/relativecontainer.png)
\ No newline at end of file
......@@ -43,11 +43,11 @@ The specified ability name is not found.
**可能原因**<br/>
1. 输入的abilityName有误。
2. 系统中对应的应用没有安装
2. 系统中对应的应用不存在该abilityName对应的ability
**处理步骤**<br/>
1. 检查abilityName拼写是否正确。
2. 确认对应的应用是否安装该组件
2. 确认对应的应用是否存在该abilityName对应的ability
## 17700004 指定的用户不存在
......@@ -58,16 +58,17 @@ The specified user ID is not found.
调用与用户相关接口时,传入的用户不存在。
**可能原因**<br/>
输入的用户名有误,系统中没有该用户。
1. 输入的用户名有误。
2. 系统中没有该用户。
**处理步骤**<br/>
1. 检查用户名拼写是否正确。
2. 确认系统中存在该用户。
## 17700005 指定的appId不存在
## 17700005 指定的appId为空字符串
**错误信息**<br/>
The specified app ID is not found.
The specified app ID is empty string.
**错误描述**<br/>
调用appControl模块中的相关接口时,传入的appId为空字符串。
......@@ -144,9 +145,10 @@ Failed to install the HAP because the HAP signature fails to be verified.
4. 多个hap的签名信息不一致。
**处理步骤**<br/>
1. 确认hap是否签名成功。
2. 确认多个hap签名时使用的证书相同。
3. 确认升级的hap签名证书与已安装的hap相同。
1. 确认hap包是否签名成功。
2. 确认hap包的签名证书是从应用市场申请。
3. 确认多个hap包签名时使用的证书相同。
4. 确认升级的ha包p签名证书与已安装的hap包相同。
## 17700012 安装包路径无效或者文件过大导致应用安装失败
......@@ -175,7 +177,7 @@ Failed to install the HAPs because they have different configuration information
调用installer模块中的install接口时,多个HAP配置信息不同导致应用安装失败。
**可能原因**<br/>
多个HAP中配置文件app下面的字段不一致。
多个hap包中配置文件中app标签下面的字段信息不一致。
**处理步骤**<br/>
确认多个HAP中配置文件app下面的字段是否一致。
......@@ -206,7 +208,7 @@ Failed to install the HAP since the version of the HAP to install is too early.
新安装的应用版本号低于已安装的版本号。
**处理步骤**<br/>
确认新安装的应用版本号是否比已安装的同应用版本号高
确认新安装的应用版本号是否不低于已安装的同应用版本号
## 17700020 预置应用无法卸载
......@@ -299,7 +301,8 @@ The specified type is invalid.
2. 输入的type不存在。
**处理步骤**<br/>
确认输入的type是否拼写正确。
1. 确认输入的type是否拼写正确。
2. 确认输入的type是否存在。
## 17700026 指定应用被禁用
......
......@@ -218,8 +218,38 @@ onWindowStageCreate() {
- `app_signature`字段配置为应用的指纹信息。指纹信息的配置参见[应用特权配置指南](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#install_list_capabilityjson中配置)
- `permissions`字段中name配置为需要预授权的`user_grant`类型的权限名;`permissions`字段中`userCancellable`表示为用户是否能够取消该预授权,配置为true,表示支持用户取消授权,为false则表示不支持用户取消授权。
<<<<<<< .mine
> 说明:当前仅支持预置应用配置该文件。
=======
//ability的onWindowStageCreate生命周期
onWindowStageCreate() {
var context = this.context
var AtManager = abilityAccessCtrl.createAtManager();
//requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
AtManager.requestPermissionsFromUser(context, ["ohos.permission.CAMERA"]).then((data) => {
console.log("data type:" + typeof(data));
console.log("data:" + data);
console.log("data permissions:" + data.permissions);
console.log("data result:" + data.authResults);
}).catch((err) => {
console.error('Failed to start ability', err.code);
})
}
>>>>>>> .theirs
```json
[
// ...
......
......@@ -183,4 +183,4 @@ ar-AE.json
## 获取语言
获取语言功能请参考[应用配置](../reference/apis/js-apis-application-configuration.md)
获取语言功能请参考[应用配置](../reference/apis/js-apis-app-ability-configuration.md)
......@@ -191,7 +191,7 @@ XTS子系统当前包括acts与tools软件包:
5. 测试套件编译命令。
随版本编译,debug版本编译时会同步编译acts测试套件。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **说明:**
> acts测试套件编译中间件为静态库,最终链接到版本镜像中 。
### C语言用例执行指导(适用于轻量系统产品用例开发)
......@@ -324,7 +324,7 @@ XTS子系统当前包括acts与tools软件包:
5. 测试套件编译命令。
随版本编译,debug版本编译时会同步编译acts测试套件
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **说明:**
> 小型系统acts独立编译成可执行文件(bin格式), 在编译产物的suites\acts目录下归档。
......
......@@ -149,6 +149,8 @@
- 标准系统芯片移植案例
- [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md)
- [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md)
- [标准系统方案之扬帆移植案例](porting/porting-yangfan-on_standard-demo.md)
- 子系统开发
......@@ -217,6 +219,7 @@
- [虚拟文件系统](kernel/kernel-small-bundles-fs-virtual.md)
- [支持的文件系统](kernel/kernel-small-bundles-fs-support.md)
- [适配新的文件系统](kernel/kernel-small-bundles-fs-new.md)
- [Plimitsfs文件系统](kernel/kernel-small-plimits.md)
- 调测与工具
- Shell
- [Shell介绍](kernel/kernel-small-debug-shell-overview.md)
......@@ -383,6 +386,7 @@
- [产品配置规则](subsystems/subsys-build-product.md)
- [子系统配置规则](subsystems/subsys-build-subsystem.md)
- [部件配置规则](subsystems/subsys-build-component.md)
- [部件编译构建规范](subsystems/subsys-build-component-building-rules.md)
- [模块配置规则](subsystems/subsys-build-module.md)
- [芯片解决方案配置规则](subsystems/subsys-build-chip_solution.md)
- [特性配置规则](subsystems/subsys-build-feature.md)
......@@ -393,6 +397,7 @@
- [查看NinjaTrace](subsystems/subsys-build-reference.md)
- [HAP编译构建指导](subsystems/subsys-build-gn-hap-compilation-guide.md)
- [常见问题](subsystems/subsys-build-FAQ.md)
- [ArkCompiler](subsystems/subsys-arkcompiler-guide.md)
- [分布式远程启动](subsystems/subsys-remote-start.md)
- 图形图像
- [图形图像概述](subsystems/subsys-graphics-overview.md)
......@@ -457,6 +462,8 @@
- [系统参数](subsystems/subsys-boot-init-sysparam.md)
- [沙盒管理](subsystems/subsys-boot-init-sandbox.md)
- [插件](subsystems/subsys-boot-init-plugin.md)
- [组件化启动](subsystems/subsys-boot-init-sub-unit.md)
- [init运行日志规范化](subsystems/subsys-boot-init-log.md)
- [appspawn应用孵化组件](subsystems/subsys-boot-appspawn.md)
- [bootstrap服务启动组件](subsystems/subsys-boot-bootstrap.md)
- [常见问题](subsystems/subsys-boot-faqs.md)
......
......@@ -73,7 +73,7 @@
- ### FA模型
Ability框架提供的一种开发模型。API version 8及更早版本的应用开发仅支持FA模型。FA模型将Ability分为[FA(Feature Ability)](#fa)和[PA(Particle Ability)](#pa)两种类型,其中FA支持Page Ability模板,PA支持Service ability、Data ability、以及Form ability模板。详情可参考[FA模型综述](application-dev/ability/fa-brief.md)。
Ability框架提供的一种开发模型。API version 8及更早版本的应用开发仅支持FA模型。FA模型将Ability分为[FA(Feature Ability)](#fa)和[PA(Particle Ability)](#pa)两种类型,其中FA支持Page Ability模板,PA支持Service ability、Data ability、以及Form ability模板。详情可参考[FA模型综述](application-dev/application-models/fa-model-development-overview.md)。
## H
......
......@@ -4,7 +4,7 @@ OpenHarmony为开发者提供了一套全面的自测试框架,开发者可根
本文从基础环境构建,用例开发,编译以及执行等方面介绍OpenHarmony测试框架如何运行和使用。
## 基础环境构建
测试框架依赖于python运行环境,在使用测试框架之前可参阅以下方式进行配置。
- [环境配置](../device-dev/subsystems/subsys-testguide-envbuild.md)
- [环境配置](../device-dev/device-test/xdevice.md)
- [源码获取](../device-dev/get-code/sourcecode-acquire.md)
......
# 媒体子系统JS API变更Changelog
OpenHarmony3.2 Beta4版本相较于OpenHarmony3.2 Beta3版本,媒体子系统camera部件API变更如下
## camera接口变更
基于以下原因新增部分功能接口以及废弃部分接口:
1. 提升开发者使用相机接口的便利。
2. 帮助开发者快速掌握相机开发接口,快速投入到开发当中。
3. 易于后续版本中框架功能的扩展,降低框架模块之间的耦合度。
具体参考下方变更内容,开发者需要根据以下说明对应用进行适配。
**变更影响**
影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。
**关键的接口/组件变更**
| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 |
| ---------------------- | ----------------------- | ------------------------------------------------------------ | -------- |
| ohos.multimedia.camera | Profile | readonly format:CameraFormat; | 新增 |
| ohos.multimedia.camera | Profile | readonly size: Size; | 新增 |
| ohos.multimedia.camera | FrameRateRange | readonly min: number; | 新增 |
| ohos.multimedia.camera | FrameRateRange | readonly max: number; | 新增 |
| ohos.multimedia.camera | VideoProfile | readonly frameRateRange: FrameRateRange; | 新增 |
| ohos.multimedia.camera | CameraOutputCapability | readonly previewProfiles: Array<Profile>; | 新增 |
| ohos.multimedia.camera | CameraOutputCapability | readonly photoProfiles: Array<Profile>; | 新增 |
| ohos.multimedia.camera | CameraOutputCapability | readonly videoProfiles: Array<VideoProfile>; | 新增 |
| ohos.multimedia.camera | CameraOutputCapability | readonly supportedMetadataObjectTypes: Array<MetadataObjectType>; | 新增 |
| ohos.multimedia.camera | CameraManager | getSupportedCameras(callback: AsyncCallback<Array<CameraDevice>>): void;<br/>getSupportedCameras(): Promise<Array<CameraDevice>>; | 新增 |
| ohos.multimedia.camera | CameraManager | getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback<CameraOutputCapability>): void;<br/>getSupportedOutputCapability(camera: CameraDevice): Promise<CameraOutputCapability>; | 新增 |
| ohos.multimedia.camera | CameraManager | isCameraMuted(): boolean; | 新增 |
| ohos.multimedia.camera | CameraManager | isCameraMuteSupported(): boolean; | 新增 |
| ohos.multimedia.camera | CameraManager | muteCamera(mute: boolean): void; | 新增 |
| ohos.multimedia.camera | CameraManager | createCameraInput(camera: CameraDevice, callback: AsyncCallback<CameraInput>): void;<br/>createCameraInput(camera: CameraDevice): Promise<CameraInput>; | 新增 |
| ohos.multimedia.camera | CameraManager | createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PreviewOutput>): void;<br/>createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput>; | 新增 |
| ohos.multimedia.camera | CameraManager | createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PhotoOutput>): void;<br/>createPhotoOutput(profile: Profile, surfaceId: string): Promise<PhotoOutput>; | 新增 |
| ohos.multimedia.camera | CameraManager | createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback<VideoOutput>): void;<br/>createVideoOutput(profile: VideoProfile, surfaceId: string): Promise<VideoOutput>; | 新增 |
| ohos.multimedia.camera | CameraManager | createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>, callback: AsyncCallback<MetadataOutput>): void;<br/>createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>): Promise<MetadataOutput>; | 新增 |
| ohos.multimedia.camera | CameraManager | createCaptureSession(callback: AsyncCallback<CaptureSession>): void;<br/>createCaptureSession(): Promise<CaptureSession>; | 新增 |
| ohos.multimedia.camera | CameraManager | on(type: 'cameraMute', callback: AsyncCallback<boolean>): void; | 新增 |
| ohos.multimedia.camera | CameraManager | getCameras(callback: AsyncCallback<Array<Camera>>): void;<br/>getCameras(): Promise<Array<Camera>>; | 废弃 |
| ohos.multimedia.camera | CameraManager | createCameraInput(cameraId: string, callback: AsyncCallback<CameraInput>): void;<br/>createCameraInput(cameraId: string): Promise<CameraInput>; | 废弃 |
| ohos.multimedia.camera | CameraManager | createCaptureSession(context: Context, callback: AsyncCallback<CaptureSession>): void;<br/>createCaptureSession(context: Context): Promise<CaptureSession>; | 废弃 |
| ohos.multimedia.camera | CameraManager | createPreviewOutput(surfaceId: string, callback: AsyncCallback<PreviewOutput>): void;<br/>createPreviewOutput(surfaceId: string): Promise<PreviewOutput>; | 废弃 |
| ohos.multimedia.camera | CameraManager | CreatePhotoOutput(surfaceId: string, callback: AsyncCallback<PhotoOutput>): void;<br/>CreatePhotoOutput(surfaceId: string): Promise<PhotoOutput>; | 废弃 |
| ohos.multimedia.camera | CameraManager | createVideoOutput(surfaceId: string, callback: AsyncCallback<VideoOutput>): void;<br/>createVideoOutput(surfaceId: string): Promise<VideoOutput>; | 废弃 |
| ohos.multimedia.camera | CameraManager | createMetadataOutput(callback: AsyncCallback<MetadataOutput>): void;<br/>createVideoOutput(): Promise<MetadataOutput>; | 废弃 |
| ohos.multimedia.camera | CameraStatusInfo | camera: CameraDevice; | 新增 |
| ohos.multimedia.camera | CameraStatusInfo | camera: Camera; | 废弃 |
| ohos.multimedia.camera | CameraDevice | interface CameraDevice | 新增 |
| ohos.multimedia.camera | Camera | interface Camera | 废弃 |
| ohos.multimedia.camera | CameraInput | open(callback: AsyncCallback<void>): void;<br/>open(): Promise<void>; | 新增 |
| ohos.multimedia.camera | CameraInput | close(callback: AsyncCallback<void>): void;<br/>close(): Promise<void>; | 新增 |
| ohos.multimedia.camera | CameraInput | on(type: 'error', camera: CameraDevice, callback: ErrorCallback<CameraInputError>): void; | 新增 |
| ohos.multimedia.camera | CameraInput | isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean>): void;<br/>isFocusModeSupported(afMode: FocusMode): Promise<boolean>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getFocusMode(callback: AsyncCallback<FocusMode>): void;<br/>getFocusMode(): Promise<FocusMode>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setFocusMode(afMode: FocusMode, callback: AsyncCallback<void>): void;<br/>setFocusMode(afMode: FocusMode): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getZoomRatioRange(callback: AsyncCallback<Array<number>>): void;<br/>getZoomRatioRange(): Promise<Array<number>>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getZoomRatio(callback: AsyncCallback<number>): void;<br/>getZoomRatio(): Promise<number>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setZoomRatio(zoomRatio: number, callback: AsyncCallback<void>): void;<br/>setZoomRatio(zoomRatio: number): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getCameraId(callback: AsyncCallback<string>): void;<br/>getCameraId(): Promise<string>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getExposurePoint(callback: AsyncCallback<Point>): void;<br/>getExposurePoint(): Promise<Point>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setExposurePoint(exposurePoint: Point, callback: AsyncCallback<void>): void;<br/>setExposurePoint(exposurePoint: Point): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | hasFlash(callback: AsyncCallback<boolean>): void;<br/>hasFlash(): Promise<boolean>; | 废弃 |
| ohos.multimedia.camera | CameraInput | isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean>): void;<br/>isFlashModeSupported(flashMode: FlashMode): Promise<boolean>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getFlashMode(callback: AsyncCallback<FlashMode>): void;<br/>getFlashMode(): Promise<FlashMode>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void>): void;<br/>setFlashMode(flashMode: FlashMode): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback<boolean>): void;<br/>isExposureModeSupported(aeMode: ExposureMode): Promise<boolean>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getExposureMode(callback: AsyncCallback<ExposureMode>): void;<br/>getExposureMode(): Promise<ExposureMode>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void>): void;<br/>setExposureMode(aeMode: ExposureMode): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getMeteringPoint(callback: AsyncCallback<Point>): void;<br/>getMeteringPoint(): Promise<Point>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setMeteringPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setMeteringPoint(point: Point): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getExposureBiasRange(callback: AsyncCallback<Array<number>>): void;<br/>getExposureBiasRange(): Promise<Array<number>>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setExposureBias(exposureBias: number, callback: AsyncCallback<void>): void;<br/>setExposureBias(exposureBias: number): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getExposureValue(callback: AsyncCallback<number>): void;<br/>getExposureValue(): Promise<number>; | 废弃 |
| ohos.multimedia.camera | CameraInput | isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean>): void;<br/>isFocusModeSupported(afMode: FocusMode): Promise<boolean>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getFocusMode(callback: AsyncCallback<FocusMode>): void;<br/>getFocusMode(): Promise<FocusMode>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setFocusMode(afMode: FocusMode, callback: AsyncCallback<void>): void;<br/>setFocusMode(afMode: FocusMode): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setFocusPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setFocusPoint(point: Point): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getFocusPoint(callback: AsyncCallback<Point>): void;<br/>getFocusPoint(): Promise<Point>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getFocalLength(callback: AsyncCallback<number>): void;<br/>getFocalLength(): Promise<number>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getZoomRatioRange(callback: AsyncCallback<Array<number>>): void;<br/>getZoomRatioRange(): Promise<Array<number>>; | 废弃 |
| ohos.multimedia.camera | CameraInput | getZoomRatio(callback: AsyncCallback<number>): void;<br/>getZoomRatio(): Promise<number>; | 废弃 |
| ohos.multimedia.camera | CameraInput | setZoomRatio(zoomRatio: number, callback: AsyncCallback<void>): void;<br/>setZoomRatio(zoomRatio: number): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CameraInput | on(type: 'focusStateChange', callback: AsyncCallback<FocusState>): void; | 废弃 |
| ohos.multimedia.camera | CameraInput | on(type: 'exposureStateChange', callback: AsyncCallback<ExposureState>): void; | 废弃 |
| ohos.multimedia.camera | CameraInput | on(type: 'error', callback: ErrorCallback<CameraInputError>): void; | 废弃 |
| ohos.multimedia.camera | CameraInputErrorCode | ERROR_NO_PERMISSION = 0 | 新增 |
| ohos.multimedia.camera | CameraInputErrorCode | ERROR_DEVICE_PREEMPTED = 1 | 新增 |
| ohos.multimedia.camera | CameraInputErrorCode | ERROR_DEVICE_DISCONNECTED = 2 | 新增 |
| ohos.multimedia.camera | CameraInputErrorCode | ERROR_DEVICE_IN_USE = 3 | 新增 |
| ohos.multimedia.camera | CameraInputErrorCode | ERROR_DRIVER_ERROR = 4 | 新增 |
| ohos.multimedia.camera | CameraFormat | CAMERA_FORMAT_RGBA_8888 = 3 | 新增 |
| ohos.multimedia.camera | ExposureMode | EXPOSURE_MODE_AUTO = 1 | 新增 |
| ohos.multimedia.camera | ExposureMode | EXPOSURE_MODE_CONTINUOUS_AUTO = 2 | 新增 |
| ohos.multimedia.camera | ExposureMode | EXPOSURE_MODE_AUTO | 废弃 |
| ohos.multimedia.camera | ExposureMode | EXPOSURE_MODE_CONTINUOUS_AUTO | 废弃 |
| ohos.multimedia.camera | VideoStabilizationMode | LOW = 1 | 新增 |
| ohos.multimedia.camera | VideoStabilizationMode | MIDDLE = 2 | 新增 |
| ohos.multimedia.camera | VideoStabilizationMode | HIGH = 3 | 新增 |
| ohos.multimedia.camera | VideoStabilizationMode | AUTO = 4 | 新增 |
| ohos.multimedia.camera | VideoStabilizationMode | LOW | 废弃 |
| ohos.multimedia.camera | VideoStabilizationMode | MIDDLE | 废弃 |
| ohos.multimedia.camera | VideoStabilizationMode | HIGH | 废弃 |
| ohos.multimedia.camera | VideoStabilizationMode | AUTO | 废弃 |
| ohos.multimedia.camera | CaptureSession | addOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void;<br/>addOutput(cameraOutput: CameraOutput): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(cameraOutput: CameraOutput): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback<boolean>): void;<br/>isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise<boolean>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getActiveVideoStabilizationMode(callback: AsyncCallback<VideoStabilizationMode>): void;<br/>getActiveVideoStabilizationMode(): Promise<VideoStabilizationMode>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback<void>): void;<br/>setVideoStabilizationMode(mode: VideoStabilizationMode): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | on(type: 'focusStateChange', callback: AsyncCallback<FocusState>): void; | 新增 |
| ohos.multimedia.camera | CaptureSession | hasFlash(callback: AsyncCallback<boolean>): void;<br/>hasFlash(): Promise<boolean>; | 新增 |
| ohos.multimedia.camera | CaptureSession | isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean>): void;<br/>isFlashModeSupported(flashMode: FlashMode): Promise<boolean>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getFlashMode(callback: AsyncCallback<FlashMode>): void;<br/>getFlashMode(): Promise<FlashMode>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void>): void;<br/>setFlashMode(flashMode: FlashMode): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback<boolean>): void;<br/>isExposureModeSupported(aeMode: ExposureMode): Promise<boolean>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getExposureMode(callback: AsyncCallback<ExposureMode>): void;<br/>getExposureMode(): Promise<ExposureMode>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void>): void;<br/>setExposureMode(aeMode: ExposureMode): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getMeteringPoint(callback: AsyncCallback<Point>): void;<br/>getMeteringPoint(): Promise<Point>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setMeteringPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setMeteringPoint(point: Point): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getExposureBiasRange(callback: AsyncCallback<Array<number>>): void;<br/>getExposureBiasRange(): Promise<Array<number>>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setExposureBias(exposureBias: number, callback: AsyncCallback<void>): void;<br/>setExposureBias(exposureBias: number): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getExposureValue(callback: AsyncCallback<number>): void;<br/>getExposureValue(): Promise<number>; | 新增 |
| ohos.multimedia.camera | CaptureSession | isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean>): void;<br/>isFocusModeSupported(afMode: FocusMode): Promise<boolean>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getFocusMode(callback: AsyncCallback<FocusMode>): void;<br/>getFocusMode(): Promise<FocusMode>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setFocusMode(afMode: FocusMode, callback: AsyncCallback<void>): void;<br/>setFocusMode(afMode: FocusMode): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setFocusPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setFocusPoint(point: Point): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getFocusPoint(callback: AsyncCallback<Point>): void;<br/>getFocusPoint(): Promise<Point>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getFocalLength(callback: AsyncCallback<number>): void;<br/>getFocalLength(): Promise<number>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getZoomRatioRange(callback: AsyncCallback<Array<number>>): void;<br/>getZoomRatioRange(): Promise<Array<number>>; | 新增 |
| ohos.multimedia.camera | CaptureSession | getZoomRatio(callback: AsyncCallback<number>): void;<br/>getZoomRatio(): Promise<number>; | 新增 |
| ohos.multimedia.camera | CaptureSession | setZoomRatio(zoomRatio: number, callback: AsyncCallback<void>): void;<br/>setZoomRatio(zoomRatio: number): Promise<void>; | 新增 |
| ohos.multimedia.camera | CaptureSession | addOutput(previewOutput: PreviewOutput, callback: AsyncCallback<void>): void;<br/>addOutput(previewOutput: PreviewOutput): Promise<void>;<br/>addOutput(photoOutput: PhotoOutput, callback: AsyncCallback<void>): void;<br/>addOutput(photoOutput: PhotoOutput): Promise<void>;<br/>addOutput(videoOutput: VideoOutput, callback: AsyncCallback<void>): void;<br/>addOutput(videoOutput: VideoOutput): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CaptureSession | removeOutput(previewOutput: PreviewOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(previewOutput: PreviewOutput): Promise<void>;<br/>removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(photoOutput: PhotoOutput): Promise<void>;removeOutput(videoOutput: VideoOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(videoOutput: VideoOutput): Promise<void>;<br/>removeOutput(metadataOutput: MetadataOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(metadataOutput: MetadataOutput): Promise<void>; | 废弃 |
| ohos.multimedia.camera | CaptureSessionErrorCode | ERROR_INSUFFICIENT_RESOURCES = 0 | 新增 |
| ohos.multimedia.camera | CaptureSessionErrorCode | ERROR_TIMEOUT = 1 | 新增 |
| ohos.multimedia.camera | CameraOutput | release(callback: AsyncCallback<void>): void;<br/>release(): Promise<void>; | 新增 |
| ohos.multimedia.camera | PreviewOutput | start(callback: AsyncCallback<void>): void;<br/>start(): Promise<void>; | 新增 |
| ohos.multimedia.camera | PreviewOutput | stop(callback: AsyncCallback<void>): void;<br/>stop(): Promise<void>; | 新增 |
| ohos.multimedia.camera | PreviewOutput | release(callback: AsyncCallback<void>): void;<br/>release(): Promise<void>; | 废弃 |
| ohos.multimedia.camera | PhotoOutput | release(callback: AsyncCallback<void>): void;<br/>release(): Promise<void>; | 废弃 |
| ohos.multimedia.camera | VideoOutput | release(callback: AsyncCallback<void>): void;<br/>release(): Promise<void>; | 废弃 |
| ohos.multimedia.camera | PhotoCaptureSetting | mirror?: boolean; | 新增 |
| ohos.multimedia.camera | PhotoOutputErrorCode | ERROR_DRIVER_ERROR = 0 | 新增 |
| ohos.multimedia.camera | PhotoOutputErrorCode | ERROR_INSUFFICIENT_RESOURCES = 1 | 新增 |
| ohos.multimedia.camera | PhotoOutputErrorCode | ERROR_TIMEOUT = 2 | 新增 |
| ohos.multimedia.camera | VideoOutputErrorCode | ERROR_DRIVER_ERROR = 0 | 新增 |
| ohos.multimedia.camera | MetadataObjectType | FACE_DETECTION = 0 | 新增 |
| ohos.multimedia.camera | MetadataObjectType | FACE = 0 | 废弃 |
| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback<MetadataOutputError>): void; | 新增 |
| ohos.multimedia.camera | MetadataOutput | setCapturingMetadataObjectTypes(metadataObjectTypes: Array<MetadataObjectType>, callback: AsyncCallback<void>): void;<br/>setCapturingMetadataObjectTypes(metadataObjectTypes: Array<MetadataObjectType>): Promise<void>; | 废弃 |
| ohos.multimedia.camera | MetadataOutput | getSupportedMetadataObjectTypes(callback: AsyncCallback<Array<MetadataObjectType>>): void;<br/>getSupportedMetadataObjectTypes(): Promise<Array<MetadataObjectType>>; | 废弃 |
| ohos.multimedia.camera | MetadataOutputErrorCode | ERROR_UNKNOWN = -1 | 新增 |
| ohos.multimedia.camera | MetadataOutputErrorCode | ERROR_INSUFFICIENT_RESOURCES = 0 | 新增 |
| ohos.multimedia.camera | MetadataOutputError | code: MetadataOutputErrorCode; | 新增 |
**适配指导**
除新增接口,和废弃接口之外,开发者需要关注变更的接口的适配:
从Beta4版本开始,对以下接口进行调整:
**新增接口**
1. Profile接口
属性1:readonly format,类型:CameraFormat;
属性2:readonly size,类型:Size;
2. FrameRateRange接口
属性1:readonly min,类型:number;
属性2:readonly max,类型:number;
3. VideoProfile接口,继承自Profile
属性:readonly frameRateRange,类型:FrameRateRange;
4. CameraOutputCapability接口
属性1:readonly previewProfiles,类型:Array<Profile>;
属性2:readonly photoProfiles,类型:Array<Profile>;
属性3:readonly videoProfiles,类型:Array<VideoProfile>;
属性4:readonly supportedMetadataObjectTypes,类型:Array<MetadataObjectType>;
5. CameraManager中新增
getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback<CameraOutputCapability>): void;
getSupportedOutputCapability(camera: CameraDevice): Promise<CameraOutputCapability>;
参考代码如下:
```
cameraManager.getSupportedCameras().then((cameras) => {
let cameraDevice = cameras[0];
cameraManager.getSupportedOutputCapability(cameraDevice, (err, CameraOutputCapability) => {
if (err) {
console.error(`Failed to get the outputCapability. ${err.message}`);
return;
}
console.log('Callback returned with an array of supported outputCapability');
})
})
```
```
cameraManager.getSupportedCameras().then((cameras) => {
let cameraDevice = cameras[0];
cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => {
console.log('Promise returned with an array of supported outputCapability');
})
})
```
6. CameraManager中新增isCameraMuted(): boolean;
参考代码如下:
```
let ismuted = cameraManager.isCameraMuted();
```
7. CameraManager中新增isCameraMuteSupported(): boolean;
参考代码如下:
```
let ismutesuppotred = cameraManager.isCameraMuteSupported();
```
8. CameraManager中新增muteCamera(mute: boolean): void;
参考代码如下:
```
let mute = true;
cameraManager.muteCamera(mute);
```
9. CameraManager中新增on(type: 'cameraMute', callback: AsyncCallback<boolean>): void;
参考代码如下:
```
cameraManager.on('cameraMute', (err, curMuetd) => {
if (err) {
console.error(`Failed to get cameraMute callback. ${err.message}`);
return;
}
})
```
10. CameraInput中新增open(callback: AsyncCallback<void>): void;以及open(): Promise<void>;
参考代码如下:
```
cameraInput.open((err) => {
if (err) {
console.error(`Failed to open the camera. ${err.message}`);
return;
}
console.log('Callback returned with camera opened.');
})
```
```
cameraInput.open().then(() => {
console.log('Promise returned with camera opened.');
})
```
11. CameraInput中新增close(callback: AsyncCallback<void>): void;以及close(): Promise<void>;
参考代码如下:
```
cameraInput.close((err) => {
if (err) {
console.error(`Failed to close the cameras. ${err.message}`);
return;
}
console.log('Callback returned with camera closed.');
})
```
```
cameraInput.close().then(() => {
console.log('Promise returned with camera closed.');
})
```
12. 枚举CameraInputErrorCode中新增
枚举值名称:ERROR_NO_PERMISSION,值:0;
枚举值名称:ERROR_DEVICE_PREEMPTED,值:1;
枚举值名称:ERROR_DEVICE_DISCONNECTED,值:2;
枚举值名称:ERROR_DEVICE_IN_USE,值:3;
枚举值名称:ERROR_DRIVER_ERROR,值:4;
13. 枚举CameraFormat中新增
枚举值名称:CAMERA_FORMAT_RGBA_8888,值:3;
14. CaptureSession中新增getMeteringPoint(callback: AsyncCallback<Point>): void;以及getMeteringPoint(): Promise<Point>;
参考代码如下:
```
captureSession.getMeteringPoint((err, exposurePoint) => {
if (err) {
console.log(`Failed to get the current exposure point ${err.message}`);
return ;
}
console.log(`Callback returned with current exposure point: ${exposurePoint}`);
})
```
```
captureSession.getMeteringPoint().then((exposurePoint) => {
console.log(`Promise returned with current exposure point : ${exposurePoint}`);
})
```
15. CaptureSession中新增setMeteringPoint(point: Point, callback: AsyncCallback<void>): void;以及setMeteringPoint(point: Point): Promise<void>;
参考代码如下:
```
const Point1 = {x: 1, y: 1};
captureSession.setMeteringPoint(Point1,(err) => {
if (err) {
console.log(`Failed to set the exposure point ${err.message}`);
return ;
}
console.log('Callback returned with the successful execution of setMeteringPoint');
})
```
```
const Point2 = {x: 2, y: 2};
captureSession.setMeteringPoint(Point2).then(() => {
console.log('Promise returned with the successful execution of setMeteringPoint');
})
```
16. 枚举CaptureSessionErrorCode中新增
枚举值名称:ERROR_INSUFFICIENT_RESOURCES,值:0;
枚举值名称:ERROR_TIMEOUT,值:1;
17. 新增接口CameraOutput,接口下有release(callback: AsyncCallback<void>): void;以及release(): Promise<void>;方法
参考代码如下:用previewOutput做示例
```
previewOutput.release((err) => {
if (err) {
console.error(`Failed to release the PreviewOutput instance ${err.message}`);
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
});
```
```
previewOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
})
```
18. PreviewOutput中新增start(callback: AsyncCallback<void>): void;以及start(): Promise<void>;
参考代码如下
```
previewOutput.start((err) => {
if (err) {
console.error(`Failed to start the previewOutput. ${err.message}`);
return;
}
console.log('Callback returned with previewOutput started.');
})
```
```
previewOutput.start().then(() => {
console.log('Promise returned with previewOutput started.');
})
```
19. PreviewOutput中新增stop(callback: AsyncCallback<void>): void;以及stop(): Promise<void>;
参考代码如下
```
previewOutput.stop((err) => {
if (err) {
console.error(`Failed to stop the previewOutput. ${err.message}`);
return;
}
console.log('Callback returned with previewOutput stopped.');
})
```
```
previewOutput.stop().then(() => {
console.log('Callback returned with previewOutput stopped.');
})
```
20. PhotoCaptureSetting接口
属性1:mirror?,类型:boolean;
21. 枚举PhotoOutputErrorCode中新增
枚举值名称:ERROR_DRIVER_ERROR,值:0;
枚举值名称:ERROR_INSUFFICIENT_RESOURCES,值:1;
枚举值名称:ERROR_TIMEOUT,值:2;
22. 枚举VideoOutputErrorCode中新增
枚举值名称:ERROR_DRIVER_ERROR,值:0;
23. MetadataOutput中新增on(type: 'error', callback: ErrorCallback<MetadataOutputError>): void;
参考代码如下
```
metadataOutput.on('error', (metadataOutputError) => {
console.log(`Metadata output error code: ${metadataOutputError.code}`);
})
```
24. MetadataOutputErrorCode枚举
枚举值名称:ERROR_UNKNOWN,值:-1;
枚举值名称:ERROR_INSUFFICIENT_RESOURCES,值:0;
25. MetadataOutputError接口
属性名称:code,值:MetadataOutputErrorCode
**废弃接口**
1. CameraInput中废弃接口on(type: 'exposureStateChange', callback: AsyncCallback<ExposureState>): void;
2. previewOutput中废弃接口release(callback: AsyncCallback<void>): void;以及release(): Promise<void>;
3. metadataOutput中废弃接口
setCapturingMetadataObjectTypes(metadataObjectTypes: Array<MetadataObjectType>, callback: AsyncCallback<void>): void;<br/>setCapturingMetadataObjectTypes(metadataObjectTypes: Array<MetadataObjectType>): Promise<void>;
4. metadataOutput中废弃接口
getSupportedMetadataObjectTypes(callback: AsyncCallback<Array<MetadataObjectType>>): void;<br/>getSupportedMetadataObjectTypes(): Promise<Array<MetadataObjectType>>;
5. PreviewOutput中废弃接口release(callback: AsyncCallback<void>): void;以及release(): Promise<void>;
6. PhotoOutput中废弃接口release(callback: AsyncCallback<void>): void;以及release(): Promise<void>;
7. VideoOutput中废弃接口release(callback: AsyncCallback<void>): void;以及release(): Promise<void>;
8. CameraInput中废弃接口getCameraId(callback: AsyncCallback<string>): void;以及getCameraId(): Promise<string>;
9. CameraInput中废弃接口getExposurePoint(callback: AsyncCallback<Point>): void;以及getExposurePoint(): Promise<Point>;
10. CameraInput中废弃接口setExposurePoint(exposurePoint: Point, callback: AsyncCallback<void>): void;以及setExposurePoint(exposurePoint: Point): Promise<void>;
**接口变更**
1. CameraManager中接口getCameras返回值由Array<Camera>变更为Array<CameraDevice>,接口名由getCameras 更换为 getSupportedCameras,因此旧接口getCameras(callback: AsyncCallback<Array<Camera>>): void;以及getCameras(): Promise<Array<Camera>>;变更为getSupportedCameras(callback: AsyncCallback<Array<CameraDevice>>): void和getSupportedCameras(): Promise<Array<CameraDevice>>;
参考代码如下:
```
cameraManager.getSupportedCameras((err, cameras) => {
if (err) {
console.error(`Failed to get the cameras. ${err.message}`);
return;
}
console.log(`Callback returned with an array of supported cameras: ${cameras.length}`);
})
```
```
cameraManager.getSupportedCameras().then((cameras) => {
console.log(`Promise returned with an array of supported cameras: ${cameras.length}`);
})
```
2. CameraManager中接口createCameraInput传递参数由原来cameraId: string变更为camera: CameraDevice,因此旧接口createCameraInput(cameraId: string, callback: AsyncCallback<CameraInput>): void;以及createCameraInput(cameraId: string): Promise<CameraInput>;变更为createCameraInput(camera: CameraDevice, callback: AsyncCallback<CameraInput>): void;和createCameraInput(camera: CameraDevice): Promise<CameraInput>;
参考代码如下:
```
let cameraDevice = cameras[0];
cameraManager.createCameraInput(cameraDevice, (err, cameraInput) => {
if (err) {
console.error(`Failed to create the CameraInput instance. ${err.message}`);
return;
}
console.log('Callback returned with the CameraInput instance.');
})
```
```
let cameraDevice = cameras[0];
cameraManager.createCameraInput(cameraDevice).then((cameraInput) => {
console.log('Promise returned with the CameraInput instance');
})
```
3. CameraManager中接口createPreviewOutput新增传递参数profile: Profile,profile参数由getSupportedOutputCapability接口获取,因此旧接口createPreviewOutput(surfaceId: string, callback: AsyncCallback<PreviewOutput>): void;以及createPreviewOutput(surfaceId: string): Promise<PreviewOutput>;变更为createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PreviewOutput>): void;createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput>;
参考代码如下:
```
let profile = cameraoutputcapability.previewProfiles[0];
cameraManager.createPreviewOutput(profile, surfaceId, (err, previewOutput) => {
if (err) {
console.error(`Failed to gcreate previewOutput. ${err.message}`);
return;
}
console.log('Callback returned with previewOutput created.');
})
```
```
let profile = cameraoutputcapability.previewProfiles[0];
cameraManager.createPreviewOutput(profile, surfaceId).then((previewOutput) => {
console.log('Promise returned with previewOutput created.');
})
```
4. CameraManager中接口createPhotoOutput新增传递参数profile: Profile,profile参数由getSupportedOutputCapability接口获取,因此旧接口CreatePhotoOutput(surfaceId: string, callback: AsyncCallback<PhotoOutput>): void;以及CreatePhotoOutput(surfaceId: string): Promise<PhotoOutput>;变更为createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PhotoOutput>): void;和createPhotoOutput(profile: Profile, surfaceId: string): Promise<PhotoOutput>;
参考代码如下:
```
let profile = cameraoutputcapability.photoProfiles[0];
cameraManager.createPhotoOutput(profile, surfaceId, (err, photoOutput) => {
if (err) {
console.error(`Failed to create photoOutput. ${err.message}`);
return;
}
console.log('Callback returned with photoOutput created.');
})
```
```
let profile = cameraoutputcapability.photoProfiles[0];
cameraManager.createPhotoOutput(profile, surfaceId).then((photoOutput) => {
console.log('Promise returned with photoOutput created.');
})
```
5. CameraManager中接口createVideoOutput新增传递参数profile: Profile,profile参数由getSupportedOutputCapability接口获取,因此旧接口createVideoOutput(surfaceId: string, callback: AsyncCallback<VideoOutput>): void;以及createVideoOutput(surfaceId: string): Promise<VideoOutput>;变更为createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback<VideoOutput>): void;和createVideoOutput(profile: VideoProfile, surfaceId: string): Promise<VideoOutput>;
参考代码如下:
```
let profile = cameraoutputcapability.videoProfiles[0];
cameraManager.createVideoOutput(profile, surfaceId, (err, videoOutput) => {
if (err) {
console.error(`Failed to create videoOutput. ${err.message}`);
return;
}
console.log('Callback returned with an array of supported outputCapability' );
})
```
```
let profile = cameraoutputcapability.videoProfiles[0];
cameraManager.createVideoOutput(profile, surfaceId).then((videoOutput) => {
console.log('Promise returned with videoOutput created.');
})
```
6. CameraManager中接口createMetadataOutput新增传递参数metadataObjectTypes: Array<MetadataObjectType>,metadataObjectTypes参数由getSupportedOutputCapability接口获取,因此旧接口function createMetadataOutput(callback: AsyncCallback<MetadataOutput>): void;以及function createMetadataOutput(): Promise<MetadataOutput>;变更为createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>, callback: AsyncCallback<MetadataOutput>): void;和createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>): Promise<MetadataOutput>;
参考代码如下:
```
let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataOutput) => {
if (err) {
console.error(`Failed to create metadataOutput. ${err.message}`);
return;
}
console.log('Callback returned with metadataOutput created.');
})
```
```
let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataOutput) => {
console.log('Promise returned with metadataOutput created.');
})
```
7. CameraManager中createCaptureSession不需要考虑context属性,因此旧接口createCaptureSession(context: Context, callback: AsyncCallback<CaptureSession>): void;以及createCaptureSession(context: Context): Promise<CaptureSession>;改为createCaptureSession(callback: AsyncCallback<CaptureSession>): void;和createCaptureSession(): Promise<CaptureSession>;
参考代码如下:
```typescript
cameraManager.createCaptureSession((err, captureSession) => {
if (err) {
console.error(`Failed to create captureSession. ${err.message}`);
return;
}
console.log('Callback returned with captureSession created.');
})
```
```
cameraManager.createCaptureSession().then((captureSession) => {
console.log('Promise returned with captureSession created.');
})
```
8. CameraStatusInfo接口下属性camera类型由Camera变更为CameraDevice
9. CameraInput中接口on(type: 'error')新增传递参数camera: CameraDevice,因此旧接口on(type: 'error', callback: ErrorCallback<CameraInputError>): void;变更为on(type: 'error', camera: CameraDevice, callback: ErrorCallback<CameraInputError>): void;
参考代码如下:
```
let cameraDevice = cameras[0];
cameraInput.on('error', cameraDevice, (cameraInputError) => {
console.log(`Camera input error code: ${cameraInputError.code}`);
})
```
10. CameraInput中以下接口调整到CaptureSession中
hasFlash(callback: AsyncCallback<boolean>): void;<br/>hasFlash(): Promise<boolean>;<br/>
isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean>): void;<br/>isFlashModeSupported(flashMode: FlashMode): Promise<boolean>;<br/>
getFlashMode(callback: AsyncCallback<FlashMode>): void;<br/>getFlashMode(): Promise<FlashMode>;<br/>
setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void>): void;<br/>setFlashMode(flashMode: FlashMode): Promise<void>;<br/>
isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback<boolean>): void;<br/>isExposureModeSupported(aeMode: ExposureMode): Promise<boolean>;<br/>
getExposureMode(callback: AsyncCallback<ExposureMode>): void;<br/>getExposureMode(): Promise<ExposureMode>;<br/>
setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void>): void;<br/>setExposureMode(aeMode: ExposureMode): Promise<void>;<br/>
getMeteringPoint(callback: AsyncCallback<Point>): void;<br/>getMeteringPoint(): Promise<Point>;<br/>
setMeteringPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setMeteringPoint(point: Point): Promise<void>;<br/>
getExposureBiasRange(callback: AsyncCallback<Array<number>>): void;<br/>getExposureBiasRange(): Promise<Array<number>>;<br/>
setExposureBias(exposureBias: number, callback: AsyncCallback<void>): void;<br/>setExposureBias(exposureBias: number): Promise<void>;<br/>
getExposureValue(callback: AsyncCallback<number>): void;<br/>getExposureValue(): Promise<number>;<br/>
isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean>): void;<br/>isFocusModeSupported(afMode: FocusMode): Promise<boolean>;<br/>
getFocusMode(callback: AsyncCallback<FocusMode>): void;<br/>getFocusMode(): Promise<FocusMode>;<br/>
setFocusMode(afMode: FocusMode, callback: AsyncCallback<void>): void;<br/>setFocusMode(afMode: FocusMode): Promise<void>;<br/>
setFocusPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setFocusPoint(point: Point): Promise<void>;<br/>
getFocusPoint(callback: AsyncCallback<Point>): void;<br/>getFocusPoint(): Promise<Point>;<br/>
getFocalLength(callback: AsyncCallback<number>): void;<br/>getFocalLength(): Promise<number>;<br/>
getZoomRatioRange(callback: AsyncCallback<Array<number>>): void;<br/>getZoomRatioRange(): Promise<Array<number>>;<br/>
getZoomRatio(callback: AsyncCallback<number>): void;<br/>getZoomRatio(): Promise<number>;<br/>
setZoomRatio(zoomRatio: number, callback: AsyncCallback<void>): void;<br/>setZoomRatio(zoomRatio: number): Promise<void>;
11. CameraInput中接口on(type: 'focusStateChange', callback: AsyncCallback<FocusState>): void;调整到CaptureSession中,对应接口on(type: 'focusStateChange', callback: AsyncCallback<FocusState>): void;
参考代码如下:
```
captureSession.on('focusStateChange', (focusState) => {
console.log(`Focus state : ${focusState}`);
})
```
12. 枚举ExposureMode中
枚举值名称:EXPOSURE_MODE_AUTO,初值由默认变更为1;
枚举值名称:EXPOSURE_MODE_CONTINUOUS_AUTO,初值由默认变更为2;
13. 枚举VideoStabilizationMode中
枚举值名称:LOW,初值由默认变更为1;
枚举值名称:MIDDLE,初值由默认变更为2;
枚举值名称:HIGH,初值由默认变更为3;
枚举值名称:AUTO,初值由默认变更为4;
14. CaptureSession中接口addOutput参数由原来子类类型(PreviewOutput,PhotoOutput,VideoOutput,MetadataOutput)统一修改为基类类型(CameraOutput),变更后由原来8个接口缩减为2个接口。
改变前接口为:
addOutput(previewOutput: PreviewOutput, callback: AsyncCallback<void>): void;<br/>addOutput(previewOutput: PreviewOutput): Promise<void>;<br/>addOutput(photoOutput: PhotoOutput, callback: AsyncCallback<void>): void;<br/>addOutput(photoOutput: PhotoOutput): Promise<void>;<br/>addOutput(videoOutput: VideoOutput, callback: AsyncCallback<void>): void;<br/>addOutput(videoOutput: VideoOutput): Promise<void>;<br/>addOutput(metadataOutput: MetadataOutput, callback: AsyncCallback<void>): void;<br/>addOutput(metadataOutput: MetadataOutput): Promise<void>;
改变后接口为:
addOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void;<br/>addOutput(cameraOutput: CameraOutput): Promise<void>;
参考代码如下:以PreviewOutput为例
```
captureSession.addOutput(previewOutput, (err) => {
if (err) {
console.error(`Failed to add output. ${err.message}`);
return;
}
console.log('Callback returned with output added.');
})
```
```
captureSession.addOutput(previewOutput).then(() => {
console.log('Promise returned with cameraOutput added.');
})
```
15. CaptureSession中接口removeOutput参数由原来子类类型(PreviewOutput,PhotoOutput,VideoOutput,MetadataOutput)统一修改为基类类型(CameraOutput),变更后由原来8个接口缩减为2个接口。
改变前接口为:
removeOutput(previewOutput: PreviewOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(previewOutput: PreviewOutput): Promise<void>;<br/>removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(photoOutput: PhotoOutput): Promise<void>;<br/>removeOutput(videoOutput: VideoOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(videoOutput: VideoOutput): Promise<void>;<br/>removeOutput(metadataOutput: MetadataOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(metadataOutput: MetadataOutput): Promise<void>;
改变后接口为:
removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(cameraOutput: CameraOutput): Promise<void>;
参考代码如下:以PreviewOutput为例
```
captureSession.removeOutput(previewOutput, (err) => {
if (err) {
console.error(`Failed to remove the CameraOutput instance. ${err.message}`);
return;
}
console.log('Callback invoked to indicate that the CameraOutput instance is removed.');
});
```
```
captureSession.removeOutput(previewOutput).then(() => {
console.log('Promise returned to indicate that the CameraOutput instance is removed.');
})
```
16. 枚举MetadataObjectType中
枚举值名称由FACE变更为FACE_DETECTION;
17. 接口Camera名称更改为CameraDevice
# 时间时区子系统ChangeLog
## cl.time.1 接口异常抛出变更
时间时区子系统定时器接口异常抛出:202非系统应用异常和401参数无效异常。
**变更影响**
该接口变更前向兼容,基于此前版本开发的应用可继续使用接口,增加相应的异常处理,原有功能不受影响。
**关键接口/组件变更**
变更前:
- 接口异常抛出message,无错误码。
变更后:
- 接口异常抛出message和code,包括202非系统应用异常和401参数无效异常。
| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 |
| ----------------- | ----------- | ------------------------------------------------------------ | -------- |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions, callback: AsyncCallback<number>): void | 变更 |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions): Promise<number> | 变更 |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void | 变更 |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number): Promise<void> | 变更 |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number, callback: AsyncCallback<void>): void | 变更 |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number): Promise<void> | 变更 |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number, callback: AsyncCallback<void>): void | 变更 |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number): Promise<void> | 变更 |
# 全球化子系统ChangeLog
## cl.global.1 国际化模块系统接口添加运行时鉴权
全球化子系统国际化组件在如下场景中提供的系统接口添加运行时鉴权。从API9开始作以下变更:
- 设置系统语言、系统国家或地区、系统区域
- 设置系统24小时制
- 添加、移除系统偏好语言
- 设置本地化数字
开发者需要根据以下说明对应用进行适配。
**变更影响**
上述场景涉及的国际化系统接口添加运行时鉴权,只有具有UPDATE_CONFIGURATION权限的系统应用可以正常调用。
**关键的接口/组件变更**
- 涉及接口
- setSystemLanguage(language: string): void;
- setSystemRegion(region: string): void;
- setSystemLocale(locale: string): void;
- set24HourClock(option: boolean): void;
- addPreferredLanguage(language: string, index?: number): void;
- removePreferredLanguage(index: number): void;
- setUsingLocalDigit(flag: boolean): void;
**适配指导**
确保应用为系统应用,非系统应用禁止调用上述接口。
当前权限不足或非系统应用调用该接口时会抛出异常,可以通过try-catch来捕获异常。
```js
import I18n from '@ohos.i18n'
try {
I18n.System.setSystemLanguage('zh');
} catch(error) {
console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`)
}
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册