提交 deaa996b 编写于 作者: S shawn_he 提交者: Gitee

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

...@@ -24,11 +24,16 @@ zh-cn/device-dev/driver/ @li-yan339 ...@@ -24,11 +24,16 @@ zh-cn/device-dev/driver/ @li-yan339
zh-cn/device-dev/get-code/ @li-yan339 zh-cn/device-dev/get-code/ @li-yan339
zh-cn/device-dev/hpm-part/ @duangavin123_admin zh-cn/device-dev/hpm-part/ @duangavin123_admin
zh-cn/device-dev/reference/hdi-apis/ @li-yan339 zh-cn/device-dev/reference/hdi-apis/ @li-yan339
zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @li-yan339 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan
zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin
...@@ -46,7 +51,7 @@ zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23 ...@@ -46,7 +51,7 @@ zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23
zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23
zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23
......
# Data Request # Data Request
>![](public_sys-resources/icon-note.gif) **NOTE** This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**NOTE**
> >
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. >The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
...@@ -18,17 +20,17 @@ import http from '@ohos.net.http'; ...@@ -18,17 +20,17 @@ import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. // Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. // Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+ // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements. // You can add header fields based on service requirements.
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
...@@ -48,7 +50,7 @@ httpRequest.request( ...@@ -48,7 +50,7 @@ httpRequest.request(
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + data.cookies); // 8+
} else { } else {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
// Call the destroy() method to release resources after the call is complete. // Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy(); httpRequest.destroy();
} }
} }
...@@ -79,7 +81,7 @@ let httpRequest = http.createHttp(); ...@@ -79,7 +81,7 @@ let httpRequest = http.createHttp();
## HttpRequest ## HttpRequest
Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request ### request
...@@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback ...@@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | ----------------------- | | -------- | ---------------------------------------------- | ---- | ----------------------- |
| url | string | Yes | URL for initiating an HTTP request.| | url | string | Yes | URL for initiating an HTTP request.|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -169,15 +171,15 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the ...@@ -169,15 +171,15 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | -------------------------------------------------- | | ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. | | url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| | options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------------------- | | :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|
...@@ -225,8 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void ...@@ -225,8 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
Registers an observer for HTTP Response Header events. Registers an observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >![](public_sys-resources/icon-note.gif) **NOTE**
> >This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
> This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -308,7 +309,6 @@ off\(type: 'headersReceive', callback?: Callback<Object\>\): void ...@@ -308,7 +309,6 @@ off\(type: 'headersReceive', callback?: Callback<Object\>\): void
Unregisters the observer for HTTP Response Header events. Unregisters the observer for HTTP Response Header events.
>![](public_sys-resources/icon-note.gif) **NOTE** >![](public_sys-resources/icon-note.gif) **NOTE**
>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
...@@ -355,13 +355,13 @@ Specifies the type and value range of the optional parameters in the HTTP reques ...@@ -355,13 +355,13 @@ Specifies the type and value range of the optional parameters in the HTTP reques
**System capability**: SystemCapability.Communication.NetStack **System capability**: SystemCapability.Communication.NetStack
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | No | Request method. | | method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> | | extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> |
| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.| | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
## RequestMethod ## RequestMethod
...@@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request. ...@@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description | | Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ | | ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | | OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
| NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. | | NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. |
| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | | RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | | PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | | MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. |
| MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.| | MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.|
| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | | MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. |
...@@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request. ...@@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request.
| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | | REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. |
| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | | UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. |
| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | | INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | | NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| | BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | | UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. |
| GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | | GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. |
...@@ -433,6 +433,17 @@ Defines the response to an HTTP request. ...@@ -433,6 +433,17 @@ Defines the response to an HTTP request.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| | result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. | | cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
## Error Codes
| Error Code| Description |
| ------ | ------------------------------------------------------------ |
| -1 | Incorrect parameters. |
| 3 | Incorrect URL format. |
| 4 | Built-in request function, protocol, or option not found during build. |
| 5 | Unable to resolve the proxy. |
| 6 | Unable to resolve the host. |
| 7 | Unable to connect to the proxy or host. |
...@@ -2,46 +2,46 @@ ...@@ -2,46 +2,46 @@
## Overview ## Overview
Generate Ninja (GN) a meta-build system that generates build files for Ninja, which allows you to build your OpenHarmony projects with Ninja. Generate Ninja (GN) is a meta-build system that generates build files for Ninja. It is the front end of Ninja. GN and Ninja together complete OpenHarmony build tasks.
### Introduction to GN ### GN
- GN is currently used in several popular systems, including Chromium, Fuchsia, and OpenHarmony. - GN is used in large software systems such as Chromium, Fuchsia, and OpenHarmony.
- The GN syntax has limitations rooted in its design philosophy. For example, there is no way to get the length of a list and wildcards are not supported. To learn about the GN design philosophy, see https://gn.googlesource.com/gn/+/main/docs/language.md#Design-philosophy. Therefore, if you find that it is complex to implement something using GN, look it over and think about whether it is really necessary. - However, the GN syntax has limitations rooted in its [design philosophy](https://gn.googlesource.com/gn/+/main/docs/language.md#Design-philosophy). For example, it does not support wildcards and cannot get the length of a list. If you find it complex to implement something with GN, stop and consider whether it is necessary to do it.
- For details about GN, see the official GN document at https://gn.googlesource.com/gn/+/main/docs/. - For more details about GN, visit https://gn.googlesource.com/gn/+/main/docs/.
### Intended Audience and Scope ### Intended Audience and Purpose
This document is intended for OpenHarmony developers. Its focus is on the GN coding style and issues that may occur during the use of GN. The GN syntax is not covered here. For details about the basics of GN, see the GN reference document at https://gn.googlesource.com/gn/+/main/docs/reference.md. This document is intended for OpenHarmony developers. This document describes the GN coding style and practices. It does not cover the GN syntax. For details about the GN basics, see [GN Reference](https://gn.googlesource.com/gn/+/main/docs/reference.md).
### General Principles ### General Principles
On the premise that functions are available, scripts must be easy to read, easy to maintain, and exhibit good scalability and performance. Scripts must be easy to read and maintain, and have good scalability and performance while functioning well.
## Coding Style ## Coding Style
### Naming ### Naming
In general cases, the naming follows the Linux kernel coding style, that is, **lowercase letters+underscore**. Follow the Linux kernel naming style, that is, lowercase letters + underscores (_).
#### Local Variables #### Local Variables
For the purpose of this document, a local variable refers to a variable that is restricted to use in a certain scope and not passed down. A local variable is a variable restricted to use in a certain scope and cannot be passed down.
To better distinguish local variables from global variables, local variables start with an underscore (**_**). Different from global variables, local variables start with an underscore (_).
``` ```
# Example 1 # Example 1:
action("some_action") { action("some_action") {
... ...
# _output is a local variable. Hence, it starts with an underscore (_). # _output is a local variable.
_output = "${target_out_dir}/${target_name}.out" _output = "${target_out_dir}/${target_name}.out"
outputs = [ _output ] outputs = [ _output ]
args = [ args = [
... ...
"--output", "--output",
rebase_path(_output, root_build_dir), rebase_path(_output, root_build_dir),
... ...
] ]
... ...
} }
...@@ -49,32 +49,32 @@ action("some_action") { ...@@ -49,32 +49,32 @@ action("some_action") {
#### Global Variables #### Global Variables
A global variable starts with a **lowercase letter**. A global variable starts with a lowercase letter.
If you want a variable value to be modified by **gn args**, use **declare\_args**. Otherwise, do not use **declare\_args**. Use **declare_args** to declare the variable value only if the variable value can be modified by **gn args**.
``` ```
# Example 2 # Example 2
declare_args() { declare_args() {
# You can use gn args to change the value of some_feature. # The value of some_feature can be changed by gn args.
some_feature = false some_feature = false
} }
``` ```
#### Targets #### Targets
The target is named in the format of **lowercase letters+underscore**. Name the targets in the lowercase letters + underscores (_) format.
A subtarget in the template is named in the ${*target\_name*}\__*suffix* format. This naming convention has the following advantages:
- The ${*target\_name*} part can prevent duplicate subtarget names. Name the subtargets in templates in the ${target_name}+double underscores (__)+suffix format. This naming convention has the following advantages:
- The double underscores (\__) can help identify the module to which the subtarget belongs, thereby facilitating fault locating. - ${target_name} prevents duplicate subtarget names.
- The double underscores (__) help locate the module to which a subtarget belongs.
``` ```
# Example 3 # Example 3
template("ohos_shared_library") { template("ohos_shared_library") {
# "{target_name}" (primary target name) + "__" (double underscores) + "notice" (suffix) # "{target_name}" (Target name) + "__" (double underscores) + "notice" (suffix)
_notice_target = "${target_name}__notice" _notice_target = "${target_name}__notice"
collect_notice(_notice_target) { collect_notice(_notice_target) {
... ...
...@@ -87,7 +87,7 @@ A subtarget in the template is named in the ${*target\_name*}\__*suffix* format. ...@@ -87,7 +87,7 @@ A subtarget in the template is named in the ${*target\_name*}\__*suffix* format.
#### Custom Templates #### Custom Templates
Whenever possible, **use verbs** for template names. Name templates in the verb+object format.
``` ```
# Example 4 # Example 4
...@@ -99,15 +99,15 @@ template("compile_resources") { ...@@ -99,15 +99,15 @@ template("compile_resources") {
### Formatting ### Formatting
To maintain consistency in styles such as code alignment and line feed, a GN script needs to be formatted before being submitted. Use the format tool provided by GN to format your script. The command is as follows: GN scripts must be formatted before being submitted. Formatting ensures consistency in style, such as code alignment and line feed. Use the format tool provided by GN to format your scripts. The command is as follows:
```shell ```shell
$ gn format path-to-BUILD.gn $ gn format path-to-BUILD.gn
``` ```
**gn format** sorts imports in alphabetical order. To maintain the original sequence, you can add an empty comment line. **gn format** sorts the imported files in alphabetical order. To maintain the original sequence, add an empty comment line.
Assume that the original import sequence is as follows: For example, the original import sequence is as follows:
``` ```
# Example 5 # Example 5
...@@ -115,42 +115,42 @@ import("//b.gni") ...@@ -115,42 +115,42 @@ import("//b.gni")
import("//a.gni") import("//a.gni")
``` ```
After the format command is executed, the import sequence is changed as follows: **gn format** sorts the files as follows:
``` ```
import("//a.gni") import("//a.gni")
import("//b.gni") import("//b.gni")
``` ```
To maintain the original import sequence, add an empty comment line. To maintain the original sequence, add an empty comment line.
``` ```
import("//b.gni") import("//b.gni")
# Comment to maintain the original import sequence. # Comment to keep the original sequence
import("//a.gni") import("//a.gni")
``` ```
## Coding Practice ## Coding Practices
### Principles of Practice
The build script completes the following two tasks: ### Guidelines
1. **Describe the dependency between modules (deps).** The build script completes the following tasks:
In practice, the most frequent problem is **lack of dependency**. 1. Describes the dependency (deps) between modules.
In practice, the most common problem is lack of dependency.
2. **Describe the module compilation rules (rule).** 2. Defines the module build rules (rule).
In practice, unclear input and output are common problems.
In practice, common problems are **unclear input** and **unclear output**. Lack of dependency leads to the following problems:
Lack of dependency can result in the following:
- **Possible compilation error**
- Unexpected compilation error
``` ```
# Example 6 # Example 6
# The compilation is prone to errors as a result of lack of dependency. # Lack of dependency poses a possibility of compilation errors.
shared_library("a") { shared_library("a") {
... ...
} }
...@@ -164,35 +164,35 @@ Lack of dependency can result in the following: ...@@ -164,35 +164,35 @@ Lack of dependency can result in the following:
deps = [ ":b" ] deps = [ ":b" ]
} }
``` ```
In this example, **libb.so** is linked to **liba.so**, which means that **b** depends on **a**. However, the dependency of **b** on **a** is not declared in the dependency list (**deps**) of **b**. Compilation is performed concurrently. An error occurs if **liba.so** is not available when **libb.so** attempts to create a link to it.
If **liba.so** is available, the compilation is successful. Therefore, lack of dependency poses a possibility of compilation errors.
In the preceding example, **liba.so** is linked to **libb.so** when being linked. This means that **b** depends on **a**. However, the dependency list (**deps**) of **b** does not declare its dependency on **a**. As compilation is performed concurrently, a compilation error will occur if compilation of **liba.so** is not yet complete when **libb.so** is being linked. - Missing compilation of modules
From this example we can see that lack of dependency does not necessarily lead to a compilation error. It poses a possibility of errors. In example 6, images are the target to build. Since images depend only on **b**, **a** will not be compiled. However, as **b** depends on **a**, an error occurs when **b** is linked.
- **Missing involvement of dependent modules**
In the preceding example, because **images** depends on **b** only, **a** does not participate in the compilation of **images** using Ninja. However, as **b** depends on **a**, an error occurs when **b** is linked.
One less common problem is **too many dependencies**. **Too many dependencies can reduce concurrency and slow down compilation**. Another problem is unnecessary dependencies. Unnecessary dependencies reduce concurrency and slow down compilation. The following is an example:
In the example below, adding the unwanted **_compile\_resource\_target** dependency to **_compile\_js_target** means that **_compile\_js_target** can be compiled only after compilation of **_compile\_resource\_target** is complete. **_compile_js_target** does not necessarily depend on **_compile_resource_target**. If this dependency is added, **_compile_js_target** can be compiled only after **_compile_resource_target** is compiled.
``` ```
# Example 7 # Example 7:
# Too many dependencies slow down compilation. # Unnecessary dependencies slow down compilation.
template("too_much_deps") { template("too_much_deps") {
... ...
_gen_resource_target = "${target_name}__res" _gen_resource_target = "${target_name}__res"
action(_gen_resource_target) { action(_gen_resource_target) {
... ...
} }
_compile_resource_target = "${target_name}__compile_res" _compile_resource_target = "${target_name}__compile_res"
action(_compile_resource_target) { action(_compile_resource_target) {
deps = [":$_gen_resource_target"] deps = [":$_gen_resource_target"]
... ...
} }
_compile_js_target = "${target_name}__js" _compile_js_target = "${target_name}__js"
action(_compile_js_target) { action(_compile_js_target) {
# This deps is not required. # This deps is not required.
...@@ -201,15 +201,15 @@ template("too_much_deps") { ...@@ -201,15 +201,15 @@ template("too_much_deps") {
} }
``` ```
Unclear input can result in the following: Unclear input leads to the following problems:
- **Modified code is not compiled during the incremental compilation.** - Modified code is not compiled during incremental compilation.
- **After code changes, the cache being used is still hit.** - The cache being used is still hit after the code is changed.
In the following example, **foo.py** references functions in **bar.py**. This means that **bar.py** is the input of **foo.py** and must be added to the **input** or **depfile** of **implict_input_action**. Otherwise, if **bar.py** is modified, the **implict_input_action** module will not be recompiled. In the following example, **foo.py** references the functions in **bar.py**. This means **bar.py** is the input of **foo.py**. You need to add **bar.py** to **input** or **depfile** of **implict_input_action**. Otherwise, if **bar.py** is modified, **implict_input_action** will not be recompiled.
``` ```
# Example 8 # Example 8:
action("implict_input_action") { action("implict_input_action") {
script = "//path-to-foo.py" script = "//path-to-foo.py"
... ...
...@@ -218,19 +218,19 @@ action("implict_input_action") { ...@@ -218,19 +218,19 @@ action("implict_input_action") {
``` ```
#!/usr/bin/env #!/usr/bin/env
# Contents of foo.py # Content of foo.py
import bar import bar
... ...
bar.some_function() bar.some_function()
... ...
``` ```
Unclear output can result in the following: Unclear output leads to the following problems:
- **The output is implicit.** - Implicit output
- **When the cache is used, implicit output cannot be obtained from the cache.** - A failure to obtain the implicit output from the cache
In the following example, **foo.py** generates two files: **a.out** and **b.out**; the output of **implict_output_action** declares only **a.out**. In this case, **b.out** is an implicit output, and the cache stores **a.out** but not **b.out**. When the cache is hit, **b.out** cannot be compiled. In the following example, **foo.py** generates two files: **a.out** and **b.out**. However, the output of **implict_output_action** declares only **a.out**. In this case, **b.out** is an implicit output, and the cache stores only **a.out**. When the cache is hit, **b.out** cannot be compiled.
``` ```
# Example 9 # Example 9
...@@ -252,43 +252,40 @@ write_file("a.out") ...@@ -252,43 +252,40 @@ write_file("a.out")
### Templates ### Templates
**Do not use the GN native templates. Use the templates provided by the compilation system.** **Do not use GN native templates. Use the templates provided by the build system.**
The GN native templates are **source_set**, **shared_library**, **static_library**, **action**, **executable**, and **group**. The GN native templates include **source_set**, **shared_library**, **static_library**, **action**, **executable** and **group**.
These native templates are discouraged due to the following reasons: The native templates are not recommended due to the following reasons:
- **The native templates only provide minimum functions**. They do not provide extra functions such as external_deps parsing, notice collection, and installation information generation. These extra functions are generated during module compilation. Therefore, the native templates must be extended. - The native templates provide only the minimal build configuration. They cannot provide functions, such as parsing **external_deps**, collecting notice, and generating installation information.
- When the file on which the input file depends changes, the native template **action** cannot automatically detect the change and cannot be recompiled. See Example 8. - The native **action** template cannot automatically detect the changes in the dependencies of the input file, and cannot start recompilation. See Example 8.
The table below lists the mapping between the GN native templates and templates provided by the compilation system.
Mapping between native templates and templates provided by the compilation system: | Template Provided by the Compilation System | GN Native Template |
|:------------------- | -------------- |
| Template Provided by the Compilation System | Native Template | | ohos_shared_library | shared_library |
| :------------------------------------------ | --------------- | | ohos_source_set | source_set |
| ohos_shared_library | shared_library | | ohos_executable | executable |
| ohos_source_set | source_set | | ohos_static_library | static_library |
| ohos_executable | executable | | action_with_pydeps | action |
| ohos_static_library | static_library | | ohos_group | group |
| action_with_pydeps | action |
| ohos_group | group |
### Using Python Scripts ### Using Python Scripts
Prioritize the Python script over the shell script in **action**. The Python script has the following advantages over the shell script: You are advised to use Python scripts instead of shell scripts in **action**. Compared with shell scripts, Python scripts feature:
- More user-friendly syntax: It will not generate strange errors just because a space is missing. - More user-friendly syntax, which eliminates errors caused by lack of a space
- More readable. - Easier to read
- Higher maintainability and debugability. - Easier to maintain and debug
- Faster compilation: thanks to Python task caching by OpenHarmony. - Faster compilation due to caching of Python tasks
### rebase_path ### rebase_path
- Call **rebase_path** only in the **args** list of **action**. - Call **rebase_path** only in **args** of **action**.
``` ```
# Example 10 # Example 10
template("foo") { template("foo") {
...@@ -309,15 +306,15 @@ Prioritize the Python script over the shell script in **action**. The Python scr ...@@ -309,15 +306,15 @@ Prioritize the Python script over the shell script in **action**. The Python scr
} }
``` ```
- If **rebase_path** is executed twice for the same variable, unexpected results may occur. - If rebase_path is called twice for the same variable, unexpected results occur.
``` ```
# Example 11 # Example 11
template("foo") { template("foo") {
action(target_name) { action(target_name) {
... ...
args = [ args = [
# rebase_path is executed twice for bar, and the passed bar value is incorrect. # After rebase_path is called twice for bar, the bar value passed is incorrect.
"--bar=" + rebase_path(invoker.bar, root_build_dir), "--bar=" + rebase_path(invoker.bar, root_build_dir),
... ...
] ]
...@@ -334,14 +331,14 @@ Prioritize the Python script over the shell script in **action**. The Python scr ...@@ -334,14 +331,14 @@ Prioritize the Python script over the shell script in **action**. The Python scr
### Sharing Data Between Modules ### Sharing Data Between Modules
Data sharing between modules is common. For example, a module may want to know the **outputs** and **deps** of another module. It is common to share data between modules. For example, module A wants to know the output and **deps** of module B.
- Data sharing within the same **BUILD.gn** file
Data in the same **BUILD.gn** file can be shared by defining global variables.
In the following example, the output of module **a** is the input of module **b**. Module **a** shares data with module **b** by defining global variables.
- Data sharing within the same **BUILD.gn**
Data in the same **BUILD.gn** can be shared by defining global variables.
In the following example, the output of module **a** is the input of module **b**, and can be shared with module **b** via global variables.
``` ```
# Example 12 # Example 12
_output_a = get_label_info(":a", "out_dir") + "/a.out" _output_a = get_label_info(":a", "out_dir") + "/a.out"
...@@ -355,25 +352,25 @@ Data sharing between modules is common. For example, a module may want to know t ...@@ -355,25 +352,25 @@ Data sharing between modules is common. For example, a module may want to know t
} }
``` ```
- Data sharing between different **BUILD.gn** files - Data sharing between different **BUILD.gn**s
The best way to share data between different **BUILD.gn** files is to save the data as files and then transfer the files between modules. This scenario is complex. For details, see **write_meta_data** in the OpenHarmony HAP compilation process. The best way to share data between different **BUILD.gn** is to save the data as files and transfer the files between modules. You can refer to **write_meta_data** in the OpenHarmony HAP build process.
### forward_variable_from ### forward_variable_from
- To customize a template, you need to forward **testonly** first, since the target of the template may be depended on by that of **testonly**. - To customize a template, pass (**forward**) **testonly** first because the **testonly** target may depend on the template target.
``` ```
# Example 13 # Example 13
# Forward testonly for a custom template. # For a customized template, pass testonly first.
template("foo") { template("foo") {
forward_variable_from(invoker, ["testonly"]) forward_variable_from(invoker, ["testonly"])
... ...
} }
``` ```
- Do not use asterisks (*) to forward variables. Required variables should be explicitly forwarded one by one. - Do not use asterisks (*) to **forward** variables. Required variables must be explicitly forwarded one by one.
``` ```
# Example 14 # Example 14
# Bad. The asterisk (*) is used to forward the variable. # Bad. The asterisk (*) is used to forward the variable.
...@@ -382,25 +379,25 @@ Data sharing between modules is common. For example, a module may want to know t ...@@ -382,25 +379,25 @@ Data sharing between modules is common. For example, a module may want to know t
... ...
} }
# Good. Variables are explicitly forward one by one. # Good. Variables are explicitly forwarded one by one.
template("bar") { template("bar") {
# #
forward_variable_from(invoker, [ forward_variable_from(invoker, [
"testonly", "testonly",
"deps", "deps",
... ...
]) ])
... ...
} }
``` ```
### target_name ### target_name
The value of **target_name** varies according to the scope. The value of **target_name** varies with the scope.
``` ```
# Example 15 # Example 15
# The value of target_name varies according to the scope. # The value of target_name varies with the scope.
template("foo") { template("foo") {
# The displayed target_name is "${target_name}". # The displayed target_name is "${target_name}".
print(target_name) print(target_name)
...@@ -426,7 +423,7 @@ To export header files from a module, use **public_configs**. ...@@ -426,7 +423,7 @@ To export header files from a module, use **public_configs**.
``` ```
# Example 16 # Example 16
# b depends on a and inherits the headers of a. # b depends on a and inherits from the headers of a.
config("headers") { config("headers") {
include_dirs = ["//path-to-headers"] include_dirs = ["//path-to-headers"]
... ...
...@@ -443,11 +440,11 @@ executable("b") { ...@@ -443,11 +440,11 @@ executable("b") {
### template ### template
A custom template must contain a subtarget named *target_name*. This subtarget is used as the main target of the template. It should depend on other subtargets so that the subtargets can be compiled. A custom template must contain a subtarget named **target_name**. This subtarget is used as the target of the template and depends on other subtargets. Otherwise, the subtargets will not be compiled.
``` ```
# Example 17 # Example 17
# A custom template must contain a subtarget named target_name. # A custom template must have a subtarget named target_name.
template("foo") { template("foo") {
_code_gen_target = "${target_name}__gen" _code_gen_target = "${target_name}__gen"
code_gen(_code_gen_target) { code_gen(_code_gen_target) {
...@@ -462,7 +459,7 @@ template("foo") { ...@@ -462,7 +459,7 @@ template("foo") {
... ...
group(target_name) { group(target_name) {
deps = [ deps = [
# Since _compile_gen_target depends on _code_gen_target, the main target only needs to depend on _compile_gen_target. # _compile_gen_target depends on _code_gen_target. Therefore, target_name only needs to depend on _compile_gen_target.
":$_compile_gen_target" ":$_compile_gen_target"
] ]
} }
...@@ -471,11 +468,11 @@ template("foo") { ...@@ -471,11 +468,11 @@ template("foo") {
### set_source_assignment_filter ### set_source_assignment_filter
In addition to filtering **sources**, **set_source_assignment_filter** can also be used to filter other variables. After the filtering is complete, clear the filter and **sources** list. In addition to **sources**, **set_source_assignment_filter** can be used to filter other variables. After the filtering is complete, clear the filter and **sources**.
``` ```
# Example 18 # Example 18
# Use set_source_assignment_filter to filter dependencies and add the dependencies whose label matches *:*_res to the dependency list. # Use set_source_assignment_filter to filter dependencies and add the dependencies with labels matching *:*_res to the dependency list.
_deps = [] _deps = []
foreach(_possible_dep, invoker.deps) { foreach(_possible_dep, invoker.deps) {
set_source_assignment_filter(["*:*_res"]) set_source_assignment_filter(["*:*_res"])
...@@ -492,18 +489,20 @@ set_source_assignment_filter([]) ...@@ -492,18 +489,20 @@ set_source_assignment_filter([])
In the latest version, **set_source_assignment_filter** is replaced by **filter_include** and **filter_exclude**. In the latest version, **set_source_assignment_filter** is replaced by **filter_include** and **filter_exclude**.
### Using **deps** for Intra-part Dependencies and **external_deps** for Cross-part Dependencies ### Using deps and external_deps
- An OpenHarmony component is a group of modules that can provide a capability.
- In OpenHarmony, a part is a group of modules that can provide a certain capability. - When defining a module, you must specify **part_name** to indicate the component to which the module belongs.
- When defining a module, you can declare the **part_name** to signify the part to which the module belongs.
- Each part declares its inner-kit for other parts to invoke. For details about the declaration of inner-kit, see **ohos.build** in the source code. - You must also declare **inner-kit** of a component for other components to call. For details about the declaration of component **innerkit**, see **bundle.json** in the source code.
- Inter-part dependencies can only be inner-kit modules.
- If the values of **part_name** of modules **a** and **b** are the same, the two modules belong to the same part. In this case, the dependency between the modules can be declared using **deps**. - **inner-kit** applies only to dependent modules in different components.
- If the values of **part_name** of modules **a** and **b** are different, the two modules belong to different parts. In this case, the dependency between the modules must be declared using **external_deps** in the format of *componentName:moduleName*. See Example 19. - If modules **a** and **b** has the same **part_name**, modules **a** and **b** belong to the same component. In this case, declare the dependency between them using **deps**.
- If modules **a** and **b** have different **part_name**, modules **a** and **b** belong to different components. In this case, declare the dependency between them using **external_deps** in the Component name:Module name format. See Example 19.
``` ```
# Example 19 # Example 19
shared_library("a") { shared_library("a") {
...@@ -512,11 +511,3 @@ In the latest version, **set_source_assignment_filter** is replaced by **filter_ ...@@ -512,11 +511,3 @@ In the latest version, **set_source_assignment_filter** is replaced by **filter_
... ...
} }
``` ```
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
### Kconfig Visual Configuration ### Kconfig Visual Configuration
Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction). It allows customized configuration of OpenHarmony subsystem components. Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction). It allows customized configuration of OpenHarmony subsystem components.
This function has the following advantages: Kconfig visual configuration has the following advantages:
- Intuitive display of software component options - Intuitive display of software component options
- High reliability (Linux kernel and Buildroot use Kconfig for visualized configuration) - High reliability (Linux kernel and Buildroot use Kconfig for visualized configuration)
### Key Concepts ### Basic Concepts
- [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction): a visual configuration file format for Linux. - [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction): a visual configuration file format for Linux.
...@@ -22,20 +22,20 @@ This function has the following advantages: ...@@ -22,20 +22,20 @@ This function has the following advantages:
- [Config format conversion](https://gitee.com/openharmony/build/blob/master/tools/component_tools/parse_kconf.py): converts the **config** file generated on the GUI to the standard format for compilation and build. - [Config format conversion](https://gitee.com/openharmony/build/blob/master/tools/component_tools/parse_kconf.py): converts the **config** file generated on the GUI to the standard format for compilation and build.
## Procedure ## Operation Guide
1. Obtain the source code. 1. Obtain the source code.
For details, see [Obtaining Source Code](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/sourcecode-acquire.md). For details, see [Obtaining Source Code](../get-code/sourcecode-acquire.md).
2. Set up the environment. 2. Set up the environment.
The Kconfiglib required for environment configuration has been embedded in the OpenHarmony hb tool. For details about how to install the hb tool, see [Install hb](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-env-setup.md#install-hb). The Kconfiglib required for environment configuration has been embedded in the OpenHarmony hb tool. For details about how to install the hb tool, see [Installing hb](../quick-start/quickstart-lite-env-setup.md).
3. Open the Kconfig configuration interface. 3. Open the Kconfig configuration interface.
```shell ```shell
#Go to the build repository directory. # Go to the build repository directory.
cd build/tools/component_tools cd build/tools/component_tools
menuconfig kconfig menuconfig kconfig
``` ```
...@@ -68,7 +68,7 @@ This function has the following advantages: ...@@ -68,7 +68,7 @@ This function has the following advantages:
Example: Example:
1. Perform a global build. 1. Perform a full build.
```shell ```shell
cp productdefine/common/base/base_product.json productdefine/common/products/ohos-arm64.json cp productdefine/common/base/base_product.json productdefine/common/products/ohos-arm64.json
...@@ -91,23 +91,23 @@ This function has the following advantages: ...@@ -91,23 +91,23 @@ This function has the following advantages:
By default, the file **product.json** is generated in the current directory. You can also use `python3 parse_kconf.py --out="example/out.json"` to specify the file path. By default, the file **product.json** is generated in the current directory. You can also use `python3 parse_kconf.py --out="example/out.json"` to specify the file path.
For more operations, see `python3 parse_kconf.py -h`. For more operations, run `python3 parse_kconf.py -h`.
## FAQs ## FAQs
### The latest component information is missing from the menu. ### Latest Components Not Displayed in the Menu List
The component list [productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json) is updated with product updates and iterations. As a result, the Kconfig menu does not contain the latest components. The component list [productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json) is updated with product updates and iterations. The Kconfig menu does not contain the latest components.
Solution: **Solution**
- Update the [Kconfig file](https://gitee.com/openharmony/build/blob/master/tools/component_tools/kconfig). Update the [Kconfig file](https://gitee.com/openharmony/build/blob/master/tools/component_tools/kconfig).
```shell ```shell
cd build/tools/component_tools cd build/tools/component_tools
python3 generate_kconfig.py python3 generate_kconfig.py
``` ```
For more details, see `python3 generate_kconfig.py -h`. You can run `python3 generate_kconfig.py -h` to view more options.
...@@ -2,38 +2,33 @@ ...@@ -2,38 +2,33 @@
## Overview ## Overview
The Compilation and Building subsystem is a build framework that supports component-based OpenHarmony development using Generate Ninja \(GN\) and Ninja. You can use this subsystem to: The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
- Assemble components for a product and build the product. - Assemble components into a product and build the product.
- Build chipset source code independently. - Build chipset source code independently.
- Build a single component independently.
### Basic Concepts - Build a single component independently.
Learn the following concepts before you start compilation and building:
- Subsystem
A subsystem is a logical concept. It consists of one or more components. OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from bottom to top. System functions are developed by the level of system, subsystem, and component. In a multi-device deployment scenario, you can customize subsystems and components as required.
- Component
A component is a reusable, configurable, and tailorable function unit. Each component has an independent directory, and multiple components can be developed concurrently and built and tested independently.
- GN
Generate Ninja \(GN\) is used to generate Ninja files.
- Ninja
Ninja is a small high-speed build system.
- hb
hb is a command line tool for OpenHarmony to execute build commands. ### Basic Concepts
Learn the following basic concepts before you start:
- Subsystem
A subsystem, as a logical concept, consists of one or more components. OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are developed by levels, from system to subsystem and then to component. In a multi-device deployment scenario, you can customize subsystems and components as required.
- Component
A component is a reusable, configurable, and tailorable function unit. Each component has an independent directory, and can be built and tested independently and developed concurrently.
- GN
GN is short for Generate Ninja. It is used to build Ninja files.
- Ninja
Ninja is a small high-speed building system.
- hb
hb is an OpenHarmony command line tool used to execute build commands.
### Directory Structure ### Directory Structure
...@@ -42,8 +37,8 @@ build/lite ...@@ -42,8 +37,8 @@ build/lite
├── components # Component description file ├── components # Component description file
├── figures # Figures in the readme file ├── figures # Figures in the readme file
├── hb # hb pip installation package ├── hb # hb pip installation package
├── make_rootfs # Script used to create the file system image ├── make_rootfs # Script used to create a file system image
├── config # Build configuration ├── config # Build configurations
│ ├── component # Component-related template definition │ ├── component # Component-related template definition
│ ├── kernel # Kernel-related build configuration │ ├── kernel # Kernel-related build configuration
│ └── subsystem # Subsystem build configuration │ └── subsystem # Subsystem build configuration
...@@ -52,174 +47,197 @@ build/lite ...@@ -52,174 +47,197 @@ build/lite
└── toolchain # Build toolchain configuration, which contains the compiler directories, build options, and linking options └── toolchain # Build toolchain configuration, which contains the compiler directories, build options, and linking options
``` ```
### Build Process ### **Build Process**
The figure below shows the build process. The figure below shows the build process.
**Figure 1** Build process **Figure 1** Build process
![](figure/build-process.jpg "build-process")
![](figure/build-process.jpg)
1. Use **hb set** to set the OpenHarmony source code directory and the product to build.
2. Use **hb build** to build the product, development board, or component.
The procedure is as follows:
(1) Read the **config.gni** file of the development board selected. The file contains the build toolchain, linking commands, and build options.
1. Use **hb set** to set the OpenHarmony source code directory and the product to build. (2) Run the **gn gen** command to read the product configuration and generate the **out** directory and **ninja** files for the solution.
2. Use **hb build** to build the product, development board, or component. The procedure is as follows:
- Read the **config.gni** file of the development board selected. The file contains the build toolchain, linking commands, and build options.
- Run the **gn gen** command to read the product configuration and generate the **out** directory and **ninja** files for the solution.
- Run **ninja -C out/board/product** to start the build.
- Package the build result, set the file attributes and permissions, and create a file system image.
(3) Run **ninja -C out/board/product** to start the build.
(4) Package the files built, set file attributes and permissions, and create a file system image.
## Configuration Rules ## Configuration Rules
To ensure that the chipset and product solutions are pluggable and decoupled from OpenHarmony, the paths, directory trees, and configuration of components, chipset solutions, and product solutions must comply with the following rules: You can build a component, a chipset solution, and a product solution. To ensure that the chipset and product solutions are decoupled from OpenHarmony, follow the rules below:
### Component ### Component
The source code directory for a component is named in the _\{Domain\}/\{Subsystem\}/\{Component\}_ format. The component directory tree is as follows: The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows:
>![](../public_sys-resources/icon-caution.gif) **CAUTION**<br/> > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
>Define component attributes, such as the name, source code directory, function description, mandatory or not, build targets, RAM, ROM, build outputs, adapted kernels, configurable features, and dependencies, in the JSON file of the subsystem in the **build/lite/components** directory. When adding a component, add its definition to the JSON file of the corresponding subsystem. The component configured for a product must have been defined in a subsystem. Otherwise, the verification will fail. > The .json file of the subsystem in the **build/lite/components** directory contains component attributes, including the name, source code directory, function description, mandatory or not, build targets, RAM, ROM, build outputs, adapted kernels, configurable features, and dependencies of the component. When adding a component, add the component information in the .json file of the corresponding subsystem. The component configured for a product must have been defined in a subsystem. Otherwise, the verification will fail.
``` ```
component component
├── interfaces ├── interfaces
│ ├── innerkits # APIs exposed internally among components │ ├── innerkits # APIs exposed internally among components
│ └── kits # App APIs provided for app developers │ └── kits # APIs provided for application developers
├── frameworks # Framework implementation ├── frameworks # Framework implementation
├── services # Service implementation ├── services # Service implementation
── BUILD.gn # Build script ── BUILD.gn # Build script
``` ```
The following example shows how to define attributes of the sensor component of the pan-sensor subsystem: The following example shows how to configure attributes of the sensor service component of the pan-sensor subsystem:
```
{
"name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the @Organization/Component name format.
"description": "Sensor services", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Code restoration path (source code path) set when "publishAs is code-segment.
"dirs": {"base/sensors/sensor_lite"} # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "sensor_lite", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "92KB", # Size of the component's ROM.
"ram": "~200KB", # Size of the component's RAM.
"deps": {
"components": [ # Other components on which this component depends.
"samgr_lite"
],
"third_party": [ # Third-party open-source software on which this component depends.
"bounds_checking_function"
]
}
"build": { # Build-related configurations.
"sub_component": [
""//base/sensors/sensor_lite/services:sensor_service"", # Component build entry
], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components.
"test": [] # Entry for building the component's test cases.
}
}
}
```
Observe the following rules when writing the component's **BUILD.gn**:
- The build target name must be the same as the component name.
- Define the configurable features in the **BUILD.gn** file of the component. Name the configurable features in the ohos_{subsystem}*{component}*{feature} format. Define the features in component description and configure them in the **config.json** file.
- Define macros in the OHOS_{SUBSYSTEM}*{COMPONENT}*{FEATURE} format.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The component build script is written in GN. For details about how to use GN, see [GN Quick Start Guide](https://gn.googlesource.com/gn/+/master/docs/quick_start.md). The component is the build target, which can be a static library, a dynamic library, an executable file, or a group.
The following example shows the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component:
```
# Declare the configurable features of the component.
declare_args() {
enable_ohos_graphic_ui_animator = false # Whether to enable animation.
ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap.
}
``` # Basic component functions.
{ shared_library("base") {
"components": [ sources = [
{ ...
"component": "sensor_lite", # Component name ]
"description": "Sensor services", # Brief description of the component include_dirs = [
"optional": "true", # Whether the component is mandatory for the system ...
"dirs": [ # Source code directory of the component ]
"base/sensors/sensor_lite" }
],
"targets": [ # Build entry of the component # Build only when the animator is enabled.
"//base/sensors/sensor_lite/services:sensor_service" if(enable_ohos_graphic_ui_animator ) {
], shared_library("animator") {
"rom": "92KB", # Component ROM sources = [
"ram": "~200KB", # Component RAM (estimated) ...
"output": [ "libsensor_frameworks.so" ], # Component build outputs
"adapted_kernel": [ "liteos_a" ], # Adapted kernel for the component
"features": [], # Configurable features of the component
"deps": {
"components": [ # Other components on which the component depends
"samgr_lite"
],
"third_party": [ # Open-source third-party software on which the component depends
"bounds_checking_function"
] ]
include_dirs = [
...
]
deps = [ :base ]
} }
} }
] ...
} # It is recommended that the target name be the same as the name of the component, which can be an executable file (.bin), shared_library (.so file), static_library (.a file), or a group.
``` executable("ui") {
deps = [
Observe the following rules when configuring **BUILD.gn**: ":base"
]
- The build target name must be the same as the component name.
- Define the configurable features in the **BUILD.gn** file of the component. Name the configurable features in the **ohos\_**\{_subsystem_\}**\_**\{_component_\}**\_**\{_feature_\} format. Define the features in component description and configure them in the **config.json** file.
- Define macros in the **OHOS\_**\{_SUBSYSTEM_\}**\_**\{_COMPONENT_\}**\_**\{_FEATURE_\} format.
>![](../public_sys-resources/icon-note.gif) **NOTE**<br/> GN is used as the build script language for components. For details about how to use GN, see [GN Quick Start Guide](https://gn.googlesource.com/gn/+/master/docs/quick_start.md). In GN, a component is a target to build, which can be a static library, a dynamic library, an executable file, or a group.
# The animator feature is configured by the product.
if(enable_ohos_graphic_ui_animator ) {
deps += [
"animator"
]
}
}
```
The following example shows how to build the **foundation/graphic/ui/BUILD.gn** file for a graphics UI component: ### Chipset Solution
``` The chipset solution is a special component. It is built based on a development board, including the drivers, device API adaptation, and SDK.
# Declare the configurable features of the component
declare_args() {
enable_ohos_graphic_ui_animator = false # Animation switch
ohos_ohos_graphic_ui_font = "vector" # Configurable font type, which can be vector or bitmap
}
# Basic component functions
shared_library("base") {
sources = [
......
]
include_dirs = [
......
]
}
# Build only when the animator is enabled
if(enable_ohos_graphic_ui_animator ) {
shared_library("animator") {
sources = [
......
]
include_dirs = [
......
]
deps = [ :base ]
}
}
......
# It is recommended that the target name be the same as the component name, which can be an executable .bin file, shared_library (.so file), static_library (.a file), or a group.
executable("ui") {
deps = [
":base"
]
# The animator feature is configured by the product.
if(enable_ohos_graphic_ui_animator ) {
deps += [
"animator"
]
}
}
```
### Chipset The source code path is named in the **device/{Development board}/{Chipset solution vendor}** format.
- The chipset solution is a complete solution based on a development board. The solution includes the drivers, API adaptation, and SDK. The chipset solution component is built by default based on the development board selected.
- The chipset solution is a special component, whose source code directory is named in the _**device**/\{Chipset solution vendor\}/\{Development board\}_ format.
- The chipset component is built by default based on the development board selected by the product.
The chipset solution directory tree is as follows: The chipset solution directory structure is as follows:
``` ```
device device
└── company # Chipset solution vendor └── board # Chipset solution vendor
└── board # Name of the development board └── company # Development board name
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── hals # Southbound APIs for OS adaptation ├── hals # OS device API adaptation
├── linux # Linux kernel version (optional) ├── linux # (Optional) Linux kernel version
│ └── config.gni # Build options for the Linux version │ └── config.gni # Linux build configuration
└── liteos_a # LiteOS kernel version (optional) └── liteos_a # (Optional) LiteOS kernel version
└── config.gni # Build options for the LiteOS Cortex-A version └── config.gni # LiteOS_A build configuration
``` ```
>![](../public_sys-resources/icon-note.gif) **NOTE** <br/> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
>The **config.gni** file contains build-related configurations of the development board. The parameters in the file are globally visible to the system and can be used to build all OS components during the build process. > The **config.gni** file contains build-related configuration of the development board. The parameters in the file are used to build all OS components, and are globally visible to the system during the build process.
The **config.gni** file contains the following key parameters: - The **config.gni** file contains the following key parameters:
``` ```
kernel_type: kernel used by the development board, for example, liteos_a, liteos_m, or linux. kernel_type: Kernel used by the development board, for example, LiteOS_A, LiteOS_M, or Linux.
kernel_version: kernel version used by the development board, for example, 4.19. kernel_version: Kernel version of the development board, for example, 4.19.
board_cpu: CPU of the development board, for example, cortex-a7 or riscv32. board_cpu: CPU of the development board, for example, Cortex-A7 or RISCV32.
board_arch: chipset architecture of the development board, for example, armv7-a or rv32imac. board_arch: Chipset architecture of the development board, for example, ARMv7-A or RV32IMAC.
board_toolchain: name of the customized build toolchain used by the development board, for example, gcc-arm-none-eabi. If this field is not specified, ohos-clang will be used by default. board_toolchain: Name of the customized build toolchain used by the development board, for example, gcc-arm-none-eabi. If this field is not specified, ohos-clang will be used by default.
board_toolchain_prefix: prefix of the build toolchain, for example, gcc-arm-none-eabi. board_toolchain_prefix: Prefix of the toolchain, for example, gcc-arm-none-eabi.
board_toolchain_type: build toolchain type, for example, gcc or clang. Currently, only GCC and clang are supported. board_toolchain_type: Toolchain type. Currently, only GCC and clang are supported.
board_cflags: build options of the .c file configured for the development board. board_cflags: Build options of the .c file configured for the development board.
board_cxx_flags: build options of the .cpp file configured for the development board. board_cxx_flags: Build options of the .cpp file configured for the development board.
board_ld_flags: link options configured for the development board. board_ld_flags: Linking options configured for the development board.
``` ```
### Product ### Product Solution
The product solution is a complete product based on a development board. It includes the OS adaptation, component assembly configuration, startup configuration, and file system configuration. The source code directory of a product solution is named in the **vendor**/\{_Product solution vendor_\}/\{_Product name_\} format. A product solution is also a special component. The product solution is a special component. It is a product built based on a development board. It includes the OS adaptation, component assembly and configuration, startup configuration, and file system configuration. The source code directory is named in the **vendor**/{*Product solution vendor*}/{*Product name*} format.
The product solution directory tree is as follows: The product solution directory structure is as follows:
``` ```
vendor vendor
...@@ -232,172 +250,162 @@ vendor ...@@ -232,172 +250,162 @@ vendor
│ ├── BUILD.gn # Product build script │ ├── BUILD.gn # Product build script
│ └── config.json # Product configuration file │ └── config.json # Product configuration file
│ └── fs.yml # File system packaging configuration │ └── fs.yml # File system packaging configuration
└── ...... └── ...
``` ```
>![](../public_sys-resources/icon-caution.gif) **CAUTION**<br/> > ![icon-caution.gif](/public_sys-resources/icon-caution.gif) **CAUTION**<br/>
>Create directories and files based on the preceding rules for new products. The Compilation and Building subsystem scans the configured products based on the rules. > Follow the preceding rules to create directories and files for new products. The Compilation and Building subsystem scans the configured products based on the rules.
The key directories and files are described as follows: The key directories and files are described as follows:
- **vendor/company/product/init\_configs/etc** 1. **vendor/company/product/init_configs/etc**
This folder contains the **rcS**, **S**_xxx_, and **fstab** scripts. The **init** process runs the **rcS**, **fstab**, and **S**_00_-_xxx_ scripts in sequence before starting system services. The **S**_xxx_ script contains content related to the development board and product. It is used to create device nodes and directories, scan device nodes, and change file permissions. These scripts are copied from the **BUILD.gn** file to the **out** directory of the product as required and packaged into the **rootfs** image. This folder contains the rcS, Sxxx, and fstab scripts. The init process runs the rcS, fstab, and S00-xxx scripts in sequence before starting system services. The **S***xxx* script is used to create device nodes and directories, scan device nodes, and change file permissions for the development board and product. These scripts are copied from the **BUILD.gn** file to the **out** directory of the product as required and packaged into the **rootfs** image.
- **vendor/company/product/init\_configs/init.cfg** 2. **vendor/company/product/init_configs/init.cfg**
This file is the configuration file for the **init** process to start services. Currently, the following commands are supported: This file is the configuration file for the **init** process to start services. Currently, the following commands are supported:
- **start**: starts a service. - **start**: starts a service.
- **mkdir**: creates a folder. - **mkdir**: creates a folder.
- **chmod**: changes the permission on a specified directory or file.
- **chown**: changes the owner group of a specified directory or file. - **chmod**: changes the permission on a specified directory or file.
- **mount**: mounts a device. - **chown**: changes the owner group of a specified directory or file.
- **mount**: mounts a device.
The fields in the file are described as follows: The fields in the file are described as follows:
``` ```
{ {
"jobs" : [{ # Job array. A job corresponds to a command set. Jobs are executed in the following sequence: pre-init > init > post-init. "jobs" : [{ # Job array. A job corresponds to a command set. Jobs are executed in the following sequence: pre-init > init > post-init.
"name" : "pre-init", "name" : "pre-init",
"cmds" : [ "cmds" : [
"mkdir /storage/data", # Create a directory. "mkdir /storage/data", # Create a directory.
"chmod 0755 /storage/data", # Change the permission, which is in 0xxx format, for example, 0755. "chmod 0755 /storage/data", #Modify the permissions. The format of the permission value is 0xxx, for example, 0755.
"mkdir /storage/data/log", "mkdir /storage/data/log",
"chmod 0755 /storage/data/log", "chmod 0755 /storage/data/log",
"chown 4 4 /storage/data/log", # Change the owner group. The first number indicates the UID, and the second indicates the GID. "chown 4 4 /storage/data/log", # Change the owner group. The first number is the user ID (UID), and the second number is the group ID (GID).
...... ...
"mount vfat /dev/mmcblock0 /sdcard rw, umask=000" # The command is in the mount [File system type][source] [target] [flags] [data] format. "mount vfat /dev/mmcblock0 /sdcard rw,umask=000" # The command format is mount [File system type] [source] [target] [flags] [data].
# Currently, flags can only be nodev, noexec, nosuid, or rdonly. # The value of flags can be nodev, noexec, nosuid, or rdonly only.
] ]
}, { }, {
"name" : "init", "name" : "init",
"cmds" : [ # Start services based on the sequence of the cmds array. "cmds" : [ # Start services based on the sequence of the cmds array.
"start shell", # Note that there is only one space between start and the service name. "start shell", # There is only one space between start and the service name.
...... ...
"start service1" "start service1"
] ]
}, { }, {
"name" : "post-init", # Job that is finally executed. Operations performed after the init process is started, for example, mounting a device after the driver initialization. "name" : "post-init", # Job that is finally executed. Operations performed after the init process is started, for example, mounting a device after the driver initialization).
"cmds" : [] "cmds" : []
} }
], ],
"services" : [{ # Service array. A service corresponds to a process. "services" : [{ # Service array. A service corresponds to a process.
"name" : "shell", # Service name "name" : "shell", # Service name.
"path" : ["/sbin/getty", "-n", "-l", "/bin/sh", "-L", "115200", "ttyS000", "vt100"], # Full path of the executable file. It must start with "path". "path" : ["/sbin/getty", "-n", "-l", "/bin/sh", "-L", "115200", "ttyS000", "vt100"], # Full path of the executable file. It must start with "path".
"uid" : 0, # Process UID, which must be the same as that in the binary file. "uid" : 0, # Process UID, which must be the same as that in the binary file.
"gid" : 0, # Process GID, which must be the same as that in the binary file. "gid" : 0, # Process GID, which must be the same as that in the binary file.
"once" : 0, # Whether the process is a one-off process. 1: The proces is a one-off process. The init process does not restart it after the process exits. 0: The process is not a one-off process. The init process restarts it if the process exits. "once" : 0, # Whether the process is a one-off process. The value 1 indicates that process is a one-off process, and the value 0 indicates the opposite. The init process does not restart the one-off process after the process exits.
"importance" : 0, # Whether the process is a key process. 1: The process is a key process. If it exits, the init process restarts the board. 0: The process is not a key process. If it exits, the init process does not restart the board. "importance" : 0, # Whether the process is a key process. The value 1 indicates a key process, and the value 0 indicates the opposite. If a key process exits, the init process will restart the board.
"caps" : [4294967295] "caps" : [4294967295]
}, },
...... ...
] ]
} }
``` ```
- **vendor/company/product/init\_configs/hals** 3. **vendor/company/product/init_configs/hals**
This file stores the content related to OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component.
- **vendor/company/product/config.json**
The **config.json** file is the main entry for the build and contains configurations of the development board, OS components, and kernel.
The following example shows the **config.json** file of the IP camera developed based on the hispark\_taurus development board:
```
{
"product_name": "ipcamera", # Product name
"version": "3.0", # config.json version, which is 3.0
"type": "small", # System type, which can be mini, small, or standard
"ohos_version": "OpenHarmony 1.0", # OS version
"device_company": "hisilicon", # Chipset vendor
"board": "hispark_taurus", # Name of the development board
"kernel_type": "liteos_a", # Kernel type
"kernel_version": "3.0.0", # Kernel version
"subsystems": [
{
"subsystem": "aafwk", # Subsystem
"components": [
{ "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Component and its features
]
},
{
......
}
......
More subsystems and components
}
}
```
- **vendor/company/product/fs.yml**
This file packages the build result to create a configuration file system image, for example, **rootfs.img** \(user-space root file system\) and **userfs.img** \(readable and writable file\). It consists of multiple lists, and each list corresponds to a file system. The fields are described as follows:
```
fs_dir_name: (Mandatory) declares the name of the file system, for example, rootfs or userfs.
fs_dirs: (Optional) configures the mapping between the file directory in the out directory and the system file directory. Each file directory corresponds to a list.
source_dir: (Optional) specifies the target file directory in the out directory. If this field is missing, an empty directory will be created in the file system based on target_dir.
target_dir: (Mandatory) specifies the corresponding file directory in the file system.
ignore_files: (Optional) declares ignored files during the copy operation.
dir_mode: (Optional) specifies the file directory permission, which is set to 755 by default.
file_mode: (Optional) declares permissions of all files in the directory, which is set to 555 by default.
fs_filemode: (Optional) configures files that require special permissions. Each file corresponds to a list.
file_dir: (Mandatory) specifies the detailed file path in the file system.
file_mode: (Mandatory) declares file permissions.
fs_symlink: (Optional) configures the soft link of the file system.
fs_make_cmd: (Mandatory) creates the file system script. The script provided by the OS is stored in the build/lite/make_rootfs directory. Linux, LiteOS, ext4, jffs2, and vfat are supported. Chipset vendors can also customize the script as required.
fs_attr: (Optional) dynamically adjusts the file system based on configuration items.
```
The **fs\_symlink** and **fs\_make\_cmd** fields support the following variables:
- $\{root\_path\}
Code root directory, which corresponds to **$\{ohos\_root\_path\}** of GN
- $\{out\_path\}
**out** directory of the product, which corresponds to **$\{root\_out\_dir\}** of GN
- $\{fs\_dir\}
File system directory, which consists of the following variables
- $\{root\_path\}
- $\{fs\_dir\_name\}
>![](../public_sys-resources/icon-note.gif) **NOTE**<br/>
>**fs.yml** is optional and does not need to be configured for devices without a file system.
- **vendor/company/product/BUILD.gn** This file contains the OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component.
This file is the entry for building the source code of the solution vendor and copying the startup configuration file. The **BUILD.gn** file in the corresponding product directory will be built by default if a product is selected. The following example shows how to build the **BUILD.gn** file of a product: 4. **vendor/company/product/config.json**
``` The **config.json** file is the main entry for the build and contains configurations of the development board, OS, and kernel.
group("product") { # The target name must be the same as the product name (level-3 directory name under the product directory).
deps = []
# Copy the init configuration.
deps += [ "init_configs" ]
# Others
......
}
```
The following example shows the **config.json** file of the IP camera developed based on the hispark_taurus board:
## Usage Guidelines ```
{
"product_name": "ipcamera", # Product name
"version": "3.0", # Version of config.json. The value is 3.0.
"type": "small", # System type. The value can be mini, small, or standard.
"ohos_version": "OpenHarmony 1.0", # OS version
"device_company": "hisilicon", # Chipset vendor
"board": "hispark_taurus", # Name of the development board
"kernel_type": "liteos_a", # Kernel type
"kernel_version": "3.0.0", # Kernel version
"subsystems": [
{
"subsystem": "aafwk", # Subsystem
"components": [
{ "component": "ability", "features":[ "enable_ohos_appexecfwk_feature_ability = true" ] } # Selected component and feature configuration
]
},
{
...
}
...
More subsystems and components
}
}
```
5. **vendor/company/product/fs.yml**
This file defines the process for creating a file system image, for example, **rootfs.img** (user-space root file system) and **userfs.img** (readable and writable file). It consists of multiple lists, and each list corresponds to a file system. The fields are described as follows:
```
fs_dir_name: (Mandatory) specifies name of the file system, for example, rootfs or userfs.
fs_dirs: (Optional) specifies the mapping between the file directory in the out directory and the system file directory. Each file directory corresponds to a list.
source_dir: (Optional) specifies target file directory in the out directory. If this field is not specified, an empty directory will be created in the file system based on target_dir.
target_dir: (Mandatory) specifies the file directory in the file system.
ignore_files: (Optional) declares ignored files during the copy operation.
dir_mode: (Optional) specifies the file directory permissions. The default value is 755.
file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555.
fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list.
file_dir: (Mandatory) specifies the detailed file path in the file system.
file_mode: (Mandatory) declares file permissions.
fs_symlink: (Optional) specifies the soft link of the file system.
fs_make_cmd: (Mandatory) creates the file system script. The script provided by the OS is located in the build/lite/make_rootfs directory. Linux, LiteOS, ext4, jffs2, and vfat are supported. Chipset vendors can also customize the script as required.
fs_attr: (Optional) dynamically adjusts the file system based on configuration items.
```
The **fs_symlink** and **fs_make_cmd** fields support the following variables:
- ${root_path}: code root directory, which corresponds to **${ohos_root_path}** of GN.
- ${out_path}: **out** directory of the product, which corresponds to **${root_out_dir}** of GN.
- ${fs_dir}: file system directory, which consists of variables ${root_path} and ${fs_dir_name}.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> **fs.yml** is optional and not required for devices without a file system.
6. **vendor/company/product/BUILD.gn**
This file provides the product built entry. It is used to build the source code of the solution vendor and copy the startup configuration file. The **BUILD.gn** file in the corresponding product directory will be built by default if a product is selected.
The following is an example of the **BUILD.gn** file of a product:
```
group("product") { # The name must be the same as the product name (level-3 directory name under the product directory).
deps = []
# Copy the init configuration.
deps += [ "init_configs" ]
# Others
...
}
```
## Guidelines
### Prerequisites ### Prerequisites
The development environment has GN, Ninja, Python 3.7.4 or later, and hb available. For details about installation methods, see [Environment Setup](../quick-start/quickstart-lite-env-setup.md). The development environment has GN, Ninja, Python 3.9.2 or later, and hb available. For details about the installation method, see [Setting Up Environments for the Mini and Small Systems](../quick-start/quickstart-lite-env-setup.md).
### Using hb ### Using hb
**hb** is a command line tool for OpenHarmony to execute build commands. Common hb commands are described as follows: **hb** is an OpenHarmony command line tool for executing build commands. Common hb commands are described as follows:
**hb set** **hb set**
``` ```
hb set -h hb set -h
...@@ -410,13 +418,15 @@ optional arguments: ...@@ -410,13 +418,15 @@ optional arguments:
-p, --product Set OHOS board and kernel -p, --product Set OHOS board and kernel
``` ```
- **hb set** \(without argument\): starts the default setting process. - If you run **hb set** with no argument, the default setting process starts.
- **hb set -root** _dir_: sets the root directory of the code.
- **hb set -p**: sets the product to build. - You can run **hb set -root** *dir* to set the root directory of the source code.
- You can run **hb set -p** to set the product to build.
**hb env** **hb env**
Displays the current configuration. Displays the current settings.
``` ```
hb env hb env
...@@ -428,57 +438,66 @@ hb env ...@@ -428,57 +438,66 @@ hb env
[OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19 [OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19
``` ```
**hb build** **hb build**
``` ```
hb build -h hb build -h
usage: hb build [-h] [-b BUILD_TYPE] [-c COMPILER] [-t [TEST [TEST ...]]] usage: hb build [-h] [-b BUILD_TYPE] [-c COMPILER] [-t [TEST [TEST ...]]] [-cpu TARGET_CPU] [--dmverity] [--tee]
[--dmverity] [--tee] [-p PRODUCT] [-f] [-n] [-p PRODUCT] [-f] [-n] [-T [TARGET [TARGET ...]]] [-v] [-shs] [--patch] [--compact-mode]
[-T [TARGET [TARGET ...]]] [-v] [-shs] [--patch] [--gn-args GN_ARGS] [--keep-ninja-going] [--build-only-gn] [--log-level LOG_LEVEL] [--fast-rebuild]
[--device-type DEVICE_TYPE] [--build-variant BUILD_VARIANT]
[component [component ...]] [component [component ...]]
positional arguments: positional arguments:
component name of the component component name of the component, mini/small only
optional arguments: optional arguments:
-h, --help show this help message and exit -h, --help show this help message and exit
-b BUILD_TYPE, --build_type BUILD_TYPE -b BUILD_TYPE, --build_type BUILD_TYPE
release or debug version release or debug version, mini/small only
-c COMPILER, --compiler COMPILER -c COMPILER, --compiler COMPILER
specify compiler specify compiler, mini/small only
-t [TEST [TEST ...]], --test [TEST [TEST ...]] -t [TEST [TEST ...]], --test [TEST [TEST ...]]
compile test suit compile test suit
--dmverity Enable dmverity -cpu TARGET_CPU, --target-cpu TARGET_CPU
select cpu
--dmverity enable dmverity
--tee Enable tee --tee Enable tee
-p PRODUCT, --product PRODUCT -p PRODUCT, --product PRODUCT
build a specified product with build a specified product with {product_name}@{company}
{product_name}@{company}, eg: camera@huawei
-f, --full full code compilation -f, --full full code compilation
-n, --ndk compile ndk -n, --ndk compile ndk
-T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]] -T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]]
Compile single target compile single target
-v, --verbose show all command lines while building -v, --verbose show all command lines while building
-shs, --sign_haps_by_server -shs, --sign_haps_by_server
sign haps by server sign haps by server
--patch apply product patch before compiling --patch apply product patch before compiling
--compact-mode compatible with standard build system set to false if we use build.sh as build entrance
--dmverity Enable dmverity --gn-args GN_ARGS specifies gn build arguments, eg: --gn-args="foo="bar" enable=true blah=7"
-p PRODUCT, --product PRODUCT --keep-ninja-going keeps ninja going until 1000000 jobs fail
build a specified product with --build-only-gn only do gn parse, donot run ninja
{product_name}@{company}, eg: ipcamera@hisilcon --log-level LOG_LEVEL
-f, --full full code compilation specifies the log level during compilationyou can select three levels: debug, info and error
-T [TARGET [TARGET ...]], --target [TARGET [TARGET ...]] --fast-rebuild it will skip prepare, preloader, gn_gen steps so we can enable it only when there is no change
Compile single target for gn related script
--device-type DEVICE_TYPE
specifies device type
--build-variant BUILD_VARIANT
specifies device operating mode
``` ```
- **hb build** \(without argument\): builds the code based on the configured code directory, product, and options. The **-f** option deletes all products to be built, which is equivalent to running **hb clean** and **hb build**. - If you run **hb build** with no argument, the previously configured code directory, product, and options are used for the build. The **-f** option deletes all products to be built. It is equivalent to running **hb clean** and **hb build**.
- **hb build** _\{component\_name\}_: builds a product component separately based on the development board and kernel set for the product, for example, **hb build kv\_store**.
- **hb build -p ipcamera@hisilicon**: skips the **set** step and builds the product directly. - You can run **hb build** *{component_name}* to build product components separately based on the development board and kernel set for the product, for example, **hb build kv_store**.
- You can run **hb build** in **device/device\_company/board** to select the kernel and start the build based on the current development board and the selected kernel to generate an image that contains the kernel and driver only.
- You can run **hb build -p ipcamera@hisilicon** to skip the setting step and build the product directly.
- You can run **hb build** in **device/board/device_company** to select the kernel and build an image that contains the kernel and drivers only based on the current development board and the selected kernel.
**hb clean** **hb clean**
You can run **hb clean** to clear the build result of the product in the **out** directory and retain the **args.gn** and **build.log** files only. To clear files in a specified directory, add the directory parameter to the command, for example, **hb clean out/xxx/xxx**. You can run **hb clean** to delete all the files except **args.gn** and **build.log** in the **out** directory. To clear files in a specified directory, add the directory parameter to the command, for example, **hb clean out/board/product**. By default, the files in the **out** directory are cleared.
``` ```
hb clean hb clean
...@@ -495,477 +514,468 @@ optional arguments: ...@@ -495,477 +514,468 @@ optional arguments:
To add a component, determine the subsystem to which the component belongs and the component name, and then perform the following steps: To add a component, determine the subsystem to which the component belongs and the component name, and then perform the following steps:
1. Add the component build script after the source code development is complete. 1. Add the component build script after the source code development is complete.
The following example adds the **BUILD.gn** script \(stored in the **applications/sample/hello\_world** directory\) to build the **hello\_world** component \(as an executable file\). The following example shows the **BUILD.gn** script (in the **applications/sample/hello_world** directory) for the **hello_world** executable file.
``` ```
executable("hello_world") { executable("hello_world") {
include_dirs = [ include_dirs = [
"include", "include",
]
sources = [
"src/hello_world.c"
] ]
} sources = [
``` "src/hello_world.c"
]
The above script is used to build **hello\_world** that can run on OpenHarmony. }
```
To build the preceding component separately, select a product via the **hb set** command and run the **-T** command.
This script can be used to build a file named **hello_world** that can run on OpenHarmony.
```
hb build -f -T //applications/sample/hello_world To build the preceding component separately, run **hb set** to select a product and run the following command to build **hello_world** separately.
```
```
After the component functions are verified on the development board, perform steps 2 to 4 to configure the component to the product. hb build -f -T //applications/sample/hello_world
```
2. Add component description.
After the component functions are verified on the development board, perform steps 2 to 4 to add the component to the product.
The component description is stored in the **build/lite/components** directory. New components must be added to the JSON file of the corresponding subsystem. The component description must contain the following fields:
2. Add the component description.
- **component**: name of the component
- **description**: brief description of the component The component description is stored in the **build/lite/components** directory. Add the new component to the .json file of the corresponding subsystem. The component description must contain the following fields:
- **optional**: whether the component is optional
- **dirs**: source code directory of the component - **component**: component name.
- **targets**: component build entry - **description**: description of the component functions.
- **optional**: whether the component is optional.
For example, to add the **hello\_world** component to the application subsystem, add the **hello\_world** object to the **applications.json** file. - **dirs**: source code directory of the component.
- **targets**: component build entry.
```
{ The following is an example of adding the **hello_world** component to the **applications.json** file.
"components": [
{ ```
"component": "hello_world", {
"description": "Hello world.", "components": [
"optional": "true", {
"dirs": [ "component": "hello_world",
"applications/sample/hello_world" "description": "Hello world.",
], "optional": "true",
"targets": [ "dirs": [
"//applications/sample/hello_world" "applications/sample/hello_world"
] ],
}, "targets": [
... "//applications/sample/hello_world"
]
},
...
]
}
```
3. Add the component to the product.
The product configuration file **config.json** is located in the **vendor/company/product/** directory. This file contains the product name, OpenHarmony version, device vendor, development board, kernel type, kernel version, subsystems, and components. The following example adds **hello_world** to the **my_product.json** file:
```
{
"product_name": "hello_world_test",
"ohos_version": "OpenHarmony 1.0",
"device_company": "hisilicon",
"board": "hispark_taurus",
"kernel_type": "liteos_a",
"kernel_version": "1.0.0",
"subsystems": [
{
"subsystem": "applications",
"components": [
{ "component": "hello_world", "features":[] }
]
},
...
] ]
} }
``` ```
3. Configure the component for the product.
The **config.json** file is stored in the **vendor/company/product/** directory. The file must contain the product name, OpenHarmony version, device vendor, development board, kernel type, kernel version, and the subsystem and component to configure. The following example adds the **hello\_world** component to the **my\_product.json** configuration file:
```
{
"product_name": "hello_world_test",
"ohos_version": "OpenHarmony 1.0",
"device_company": "hisilicon",
"board": "hispark_taurus",
"kernel_type": "liteos_a",
"kernel_version": "1.0.0",
"subsystems": [
{
"subsystem": "applications",
"components": [
{ "component": "hello_world", "features":[] }
]
},
...
]
}
```
4. Build the product.
1. Run the **hb set** command in the root code directory and select the product.
2. Run the **hb build** command.
4. Build the product.
1. Run the **hb set** command in the root code directory and select the product.
2. Run the **hb build** command.
### Adding a Chipset Solution ### Adding a Chipset Solution
The following uses the RTL8720 development board provided by Realtek as an example. To a chipset solution, perform the following steps: The following uses the RTL8720 development board provided by Realtek as an example. To a chipset solution, perform the following steps:
1. Create a directory for the chipset solution. 1. Create a directory for the chipset solution based on the [configuration rules](#chipset-solution).
Run the following command in the root directory of the code:
To create a directory based on [Configuration Rules](#configuration-rules), run the following command in the root code directory:
```
``` mkdir -p device/board/realtek/rtl8720
mkdir -p device/realtek/rtl8720 ```
```
2. Create a directory for kernel adaptation and write the **config.gni** file of the development board.
2. Create a directory for kernel adaptation and build the **config.gni** file of the development board. For example, to adapt the LiteOS-A kernel to the RTL8720 development board, write the **device/realtek/rtl8720/liteo_a/config.gni** file as follows:
For example, to adapt the LiteOS-A kernel to the RTL8720 development board, configure the **device/realtek/rtl8720/liteos\_a/config.gni** file as follows: ```
# Kernel type, e.g. "linux", "liteos_a", "liteos_m".
``` kernel_type = "liteos_a"
# Kernel type, e.g. "linux", "liteos_a", "liteos_m".
kernel_type = "liteos_a" # Kernel version.
kernel_version = "3.0.0"
# Kernel version.
kernel_version = "3.0.0" # Board CPU type, e.g. "cortex-a7", "riscv32".
board_cpu = "real-m300"
# Board CPU type, e.g. "cortex-a7", "riscv32".
board_cpu = "real-m300" # Board arch, e.g. "armv7-a", "rv32imac".
board_arch = ""
# Board arch, e.g. "armv7-a", "rv32imac".
board_arch = "" # Toolchain name used for system compiling.
# E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf.
# Toolchain name used for system compiling. # Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain.
# E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. board_toolchain = "gcc-arm-none-eabi"
# Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain.
board_toolchain = "gcc-arm-none-eabi" # The toolchain path installed, it's not mandatory if you have added toolchain path to your ~/.bashrc.
board_toolchain_path =
# The toolchain path instatlled, it's not mandatory if you have added toolchian path to your ~/.bashrc. rebase_path("//prebuilts/gcc/linux-x86/arm/gcc-arm-none-eabi/bin",
board_toolchain_path = root_build_dir)
rebase_path("//prebuilts/gcc/linux-x86/arm/gcc-arm-none-eabi/bin",
root_build_dir) # Compiler prefix.
board_toolchain_prefix = "gcc-arm-none-eabi-"
# Compiler prefix.
board_toolchain_prefix = "gcc-arm-none-eabi-" # Compiler type, "gcc" or "clang".
board_toolchain_type = "gcc"
# Compiler type, "gcc" or "clang".
board_toolchain_type = "gcc" # Board related common compile flags.
board_cflags = []
# Board related common compile flags. board_cxx_flags = []
board_cflags = [] board_ld_flags = []
board_cxx_flags = [] ```
board_ld_flags = []
``` 3. Write the build script.
Create the **BUILD.gn** file in the development board directory. The target name must be the same as that of the development board. The following is an example of the **device/realtek/rtl8720/BUILD.gn** file for the RTL8720 development board:
3. Build the script.
```
Create the **BUILD.gn** file in the development board directory. The target name must be the same as that of the development board. The content in the **device/realtek/rtl8720/BUILD.gn** file is configured as follows: group("rtl8720") { # The build target can be shared_library, static_library, or an executable file.
# Content
``` ...
group("rtl8720") { # The target can be shared_library, static_library, or an executable file. }
# Content ```
......
} 4. Build the chipset solution.
```
Run the **hb build** command in the development board directory to start the build.
4. Build the chipset solution.
Run the **hb build** command in the development board directory to start the build.
### Adding a Product Solution ### Adding a Product Solution
You can use the Compilation and Building subsystem to customize product solutions by assembling chipset solutions and components. The procedure is as follows: You can customize a product solution by flexibly assembling a chipset solution and components. The procedure is as follows:
1. Create a product directory. 1. Create a product directory based on the [configuration rules](#product-solution).
The following uses the Wi-Fi IoT component on the RTL8720 development board as an example. Run the following command in the root code directory to create a product directory based on [Configuration Rules](#configuration-rules): The following uses the Wi-Fi IoT module on the RTL8720 development board as an example. Run the following command in the root directory to create a product directory:
``` ```
mkdir -p vendor/my_company/wifiiot mkdir -p vendor/my_company/wifiiot
``` ```
2. Assemble the product. 2. Assemble the product.
Create the **config.json** file in the product directory. The **vendor/my\_company/wifiiot/config.json** file is as follows: Create a **config.json** file, for example for wifiiot, in the product directory. The **vendor/my_company/wifiiot/config.json** file is as follows:
``` ```
{ {
"product_name": "wifiiot", # Product name "product_name": "wifiiot", # Product name
"version": "3.0", # config.json version, which is 3.0 "version": "3.0", # Version of config.json. The value is 3.0.
"type": "small", # System type, which can be mini, small, or standard "type": "small", # System type. The value can be mini, small, or standard.
"ohos_version": "OpenHarmony 1.0", # OS version "ohos_version": "OpenHarmony 1.0", # OS version
"device_company": "realtek", # Name of the chipset solution vendor "device_company": "realtek", # Name of the chipset solution vendor
"board": "rtl8720", # Name of the development board "board": "rtl8720", # Name of the development board
"kernel_type": "liteos_m", # Kernel type "kernel_type": "liteos_m", # Kernel type
"kernel_version": "3.0.0", # Kernel version "kernel_version": "3.0.0", # Kernel version
"subsystems": [ "subsystems": [
{ {
"subsystem": "kernel", # Subsystem "subsystem": "kernel", # Subsystem
"components": [ "components": [
{ "component": "liteos_m", "features":[] } # Component and its features { "component": "liteos_m", "features":[] } # Component and its features
] ]
}, },
... ...
{ {
More subsystems and components More subsystems and components
} }
] ]
} }
``` ```
Before the build, the Compilation and Building subsystem checks the validity of fields, including **device\_company**, **board**, **kernel\_type**, **kernel\_version**, **subsystem**, and **component**. The **device\_company**, **board**, **kernel\_type**, and **kernel\_version** fields must match the current chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file. > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
> Before the build, the Compilation and Building subsystem checks the validity of fields in **config.json**. The **device_company**, **board**, **kernel_type**, and **kernel_version** fields must match the fields of the chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file.
3. Implement adaptation to OS APIs.
3. Implement adaptation to OS APIs.
Create the **hals** directory in the product directory and store the source code as well as the build script for OS adaptation in this directory.
Create the **hals** directory in the product directory and save the source code as well as the build script for OS adaptation in this directory.
4. Configure the system service.
4. Configure system services.
Create the **init\_configs** directory in the product directory and then the **init.cfg** file in the newly created directory. Configure the system service to be started.
Create the **init_configs** directory in the product directory and then the **init.cfg** file in the **init_configs** directory, and configure the system services to be started.
5. \(Optional\) Configure the init process only for the Linux kernel.
5. (Optional) Configure the init process for the Linux kernel.
Create the **etc** directory in the **init\_configs** directory, and then the **init.d** folder and the **fstab** file in the newly created directory. Then, create the **rcS** and **S**_xxx_ files in the **init.d** file and edit them based on product requirements.
Create the **etc** directory in the **init_configs** directory, and then the **init.d** folder and the **fstab** file in the **etc** directory. Then, create the **rcS** and **S***xxx* files in the **init.d** file and edit them based on product requirements.
6. \(Optional\) Configure the file system image only for the development board that supports the file system.
6. (Optional) Configure the file system image for the development board that supports the file system.
Create the **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows:
Create a **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows:
```
- ```
fs_dir_name: rootfs # Image name -
fs_dirs: fs_dir_name: rootfs # Image name
- fs_dirs:
# Copy the files in the out/my_board/my_product/bin directory to the rootfs/bin directory and ignore the .bin files related to testing. -
source_dir: bin # Copy the files in the out/my_board/my_product/bin directory to the rootfs/bin directory and ignore the .bin files related to testing.
target_dir: bin source_dir: bin
ignore_files: target_dir: bin
- Test.bin ignore_files:
- TestSuite.bin - Test.bin
- - TestSuite.bin
# Copy the files in the out/my_board/my_product/libs directory to the rootfs/lib directory, ignore all .a files, and set the file permissions to 644 and folder permissions 755. -
source_dir: libs # Copy the files in the out/my_board/my_product/libs directory to the rootfs/lib directory, ignore all .a files, and set the file permissions to 644 and folder permissions 755.
target_dir: lib source_dir: libs
ignore_files: target_dir: lib
- .a ignore_files:
dir_mode: 755 - .a
file_mode: 644 dir_mode: 755
- file_mode: 644
source_dir: usr/lib -
target_dir: usr/lib source_dir: usr/lib
ignore_files: target_dir: usr/lib
- .a ignore_files:
dir_mode: 755 - .a
file_mode: 644 dir_mode: 755
- file_mode: 644
source_dir: config -
target_dir: etc source_dir: config
- target_dir: etc
source_dir: system -
target_dir: system source_dir: system
- target_dir: system
source_dir: sbin -
target_dir: sbin source_dir: sbin
- target_dir: sbin
source_dir: usr/bin -
target_dir: usr/bin source_dir: usr/bin
- target_dir: usr/bin
source_dir: usr/sbin -
target_dir: usr/sbin source_dir: usr/sbin
- target_dir: usr/sbin
# Create an empty proc directory. -
target_dir: proc # Create an empty proc directory.
- target_dir: proc
target_dir: mnt -
- target_dir: mnt
target_dir: opt -
- target_dir: opt
target_dir: tmp -
- target_dir: tmp
target_dir: var -
- target_dir: var
target_dir: sys -
- target_dir: sys
source_dir: etc -
target_dir: etc source_dir: etc
- target_dir: etc
source_dir: vendor -
target_dir: vendor source_dir: vendor
- target_dir: vendor
target_dir: storage -
target_dir: storage
fs_filemode:
- fs_filemode:
file_dir: lib/ld-uClibc-0.9.33.2.so -
file_mode: 555 file_dir: lib/ld-uClibc-0.9.33.2.so
- file_mode: 555
file_dir: lib/ld-2.24.so -
file_mode: 555 file_dir: lib/ld-2.24.so
- file_mode: 555
file_dir: etc/init.cfg -
file_mode: 400 file_dir: etc/init.cfg
fs_symlink: file_mode: 400
- fs_symlink:
# Create the soft link ld-musl-arm.so.1 -> libc.so in the rootfs/lib directory. -
source: libc.so # Create the soft link ld-musl-arm.so.1 -> libc.so in the rootfs/lib directory.
link_name: ${fs_dir}/lib/ld-musl-arm.so.1 source: libc.so
- link_name: ${fs_dir}/lib/ld-musl-arm.so.1
source: mksh -
link_name: ${fs_dir}/bin/sh source: mksh
- link_name: ${fs_dir}/bin/sh
source: mksh -
link_name: ${fs_dir}/bin/shell source: mksh
fs_make_cmd: link_name: ${fs_dir}/bin/shell
# Create an ext4 image for the rootfs directory using the script. fs_make_cmd:
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 # Run the script to create an ext4 image from rootfs.
- - ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4
fs_dir_name: userfs -
fs_dirs: fs_dir_name: userfs
- fs_dirs:
source_dir: storage/etc -
target_dir: etc source_dir: storage/etc
- target_dir: etc
source_dir: data -
target_dir: data source_dir: data
fs_make_cmd: target_dir: data
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4 fs_make_cmd:
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4
```
```
7. \(Optional\) Configure patches if the product and components need to be patched.
7. (Optional) Configure patches if the product and components need to be patched.
Create the **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows:
Create a **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows:
```
# Directory in which the patch is to be installed ```
foundation/communication/dsoftbus: # Directory in which the patch is to be installed
# Directory in which the patch is stored foundation/communication/dsoftbus:
- foundation/communication/dsoftbus/1.patch # Directory in which the patch is stored.
- foundation/communication/dsoftbus/2.patch - foundation/communication/dsoftbus/1.patch
third_party/wpa_supplicant: - foundation/communication/dsoftbus/2.patch
- third_party/wpa_supplicant/1.patch third_party/wpa_supplicant:
- third_party/wpa_supplicant/2.patch - third_party/wpa_supplicant/1.patch
- third_party/wpa_supplicant/3.patch - third_party/wpa_supplicant/2.patch
... - third_party/wpa_supplicant/3.patch
``` ...
```
If you add **--patch** when running the **hb build** command, the patch file can be added to the specified directory before the build.
Add **--patch** when running the **hb build** command. Then, the patch files can be added to the specified directory before the build.
```
hb build -f --patch ```
``` hb build -f --patch
```
8. Build the script.
8. Write the build script.
Create the **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT component in [1](#li1970321162111) as an example:
Create a **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT module in step 1 as an example:
```
group("wifiiot") { # The target name must be the same as the product name. ```
deps = [] group("wifiiot") { # The target name must be the same as the product name.
# Copy the init configuration. deps = []
deps += [ "init_configs" ] # Copy the init configuration.
# Build the hals directory. deps += [ "init_configs" ]
deps += [ "hals" ] # Add **hals**.
# Others deps += [ "hals" ]
...... # Others
} ...
``` }
```
9. Build the product.
9. Build the product.
Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command.
Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command.
## Troubleshooting ## Troubleshooting
### Invalid -- w Option ### "usr/sbin/ninja: invalid option -- w" Displayed During the Build Process
- **Symptom**
The build fails, and "usr/sbin/ninja: invalid option -- w" is displayed.
- **Cause**
The Ninja version in the build environment is outdated and does not support the **--w** option.
- **Solution**
Uninstall Ninja and GN and follow the instructions provided in [IDE](../get-code/gettools-ide.md) to install Ninja and GN of the required version.
### Library ncurses Not Found
- **Symptom**
The build fails, and "/usr/bin/ld: cannot find -lncurses" is displayed.
- **Cause**
The ncurses library is not installed.
- **Solution**
```
sudo apt-get install lib32ncurses5-dev
```
### mcopy not Found
- **Symptom**
The build fails, and "line 77: mcopy: command not found" is displayed.
- **Cause**
mcopy is not installed.
- **Solution**
```
sudo apt-get install dosfstools mtools
```
### No riscv File or Directory
- **Symptom**
The build fails, and the following information is displayed:
riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory. - **Symptom**
The build fails, and **usr/sbin/ninja: invalid option -- w** is displayed.
- **Cause** - **Possible Causes**
The Ninja version in use does not support the **--w** option.
Permission is required to access files in the **riscv** compiler directory. - **Solution**
Uninstall Ninja and GN, and [install Ninja and GN of the required version](../get-code/gettools-ide.md).
- **Solution** ### "/usr/bin/ld: cannot find -lncurses" Displayed During the Build Process
Run the following command to query the directory where **gcc\_riscv32** is located: - **Symptom**
The build fails, and **/usr/bin/ld: cannot find -lncurses** is displayed.
``` - **Possible Causes**
which riscv32-unknown-elf-gcc
``` The ncurses library is not installed.
- **Solution**
```
sudo apt-get install lib32ncurses5-dev
```
Run the **chmod** command to change the directory permission to **755**. ### "line 77: mcopy: command not found" Displayed During the Build Process
- **Symptom**
The build fails, and **line 77: mcopy: command not found** is displayed.
### No Crypto - **Possible Causes**
mcopy is not installed.
- **Symptom** - **Solution**
```
sudo apt-get install dosfstools mtools
```
The build fails, and "No component named 'Crypto'" is displayed. ### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" Displayed During the Build Process
- **Cause** - **Symptom**
The build fails, and the following information is displayed: <br>**riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory**
Crypto is not installed in Python 3. - **Possible Causes**
Permission is required to access files in the RISC-V compiler directory.
- **Solution** - **Solution**
1. Run the following command to query the Python version:
``` 1. Run the following command to locate **gcc_riscv32**:
python3 --version
```
2. Ensure that Python 3.7 or later is installed, and then run the following command to install pycryptodome: ```
which riscv32-unknown-elf-gcc
```
``` 2. Run the **chmod** command to change the directory permission to **755**.
sudo pip3 install pycryptodome
```
### Unexpected Operator ### "No module named 'Crypto'" Displayed During the Build Process
- **Symptom** - **Symptom**
The build fails, and **No module named 'Crypto'** is displayed.
The build fails, and "xx.sh \[: xx unexpected operator" is displayed. - **Possible Causes**
Crypto is not installed in Python 3.
- **Cause** - **Solution**
1. Run the following command to query the Python version:
```
python3 --version
```
2. Ensure that Python 3.9.2 or later is installed, and then run the following command to install PyCryptodome:
```
sudo pip3 install pycryptodome
```
The build environment is shell, not bash. ### "xx.sh : xx unexpected operator" Displayed During the Build Process
- **Solution** - **Symptom**
The build fails, and **xx.sh [: xx unexpected operator** is displayed.
``` - **Possible Causes**
sudo rm -rf /bin/sh
sudo ln -s /bin/bash /bin/sh The build environment shell is not bash.
```
- **Solution**
```
sudo rm -rf /bin/sh
sudo ln -s /bin/bash /bin/sh
```
# Building the Standard System<a name="EN-US_TOPIC_0000001076490572"></a> # Building the Standard System
## Overview<a name="section17466112012244"></a> ## Overview
The compilation and building subsystem provides a framework based on Generate Ninja \(GN\) and Ninja. This subsystem allows you to: The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
- Build products based on different chipset platforms, for example, Hi3516D V300. - Build products based on different chipset platforms, for example, hispark_taurus_standard.
- Package capabilities required by a product by assembling modules based on the product configuration. - Package capabilities required by a product by assembling components based on the product configuration.
### Basic Concepts<a name="section445513507246"></a> ### Basic Concepts
It is considered best practice to learn the following basic concepts before you start building: Learn the following basic concepts before you start:
- **Platform** - Platform
A platform consists of the development board and kernel. The supported subsystems and components vary with the platform.
A platform is a combination of development boards and kernels. - Subsystem
OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are developed by levels, from system to subsystem and then to component. In a multi-device deployment scenario, you can customize subsystems and components as required. A subsystem, as a logical concept, consists of the least required components.
Supported subsystems and modules vary according to the platform. - Component
A component is a reusable software unit that contains source code, configuration files, resource files, and build scripts. Integrated in binary mode, a component can be built and tested independently.
- **Subsystems** - GN
GN is short for Generate Ninja. It is used to build Ninja files.
OpenHarmony is designed with a layered architecture, which from bottom to top consists of the kernel layer, system service layer, framework layer, and application layer. System functions are expanded by levels, from system to subsystem, and further to module. In a multi-device deployment scenario, unnecessary subsystems and modules can be excluded from the system as required. A subsystem is a logical concept and is a flexible combination of functions. - Ninja
Ninja is a small high-speed building system.
- **Module** ### Working Principles
A module is a reusable software binary unit that contains source code, configuration files, resource files, and build scripts. A module can be built independently, integrated in binary mode, and then tested independently. The process for building an OpenHarmony system is as follows:
- **GN** - Parsing commands: Parse the name of the product to build and load related configurations.
GN is short for Generate Ninja, which is used to generate Ninja files. - Running GN: Configure the toolchain and global options based on the product name and compilation type.
- **Ninja** - Running Ninja: Start building and generate a product distribution.
Ninja is a small high-speed build system. ### Constraints
- You need to obtain the source code using method 3 described in [Obtaining Source Code](../get-code/sourcecode-acquire.md).
### Working Principles<a name="section12541217142510"></a> - Ubuntu 18.04 or later must be used.
The process to build OpenHarmony is as follows: - You must install the software packages required for build.
The command is as follows:
```
# Run the script in the home directory.
# ./build/build_scripts/env_setup.sh
# Do not run the command as the **root** user. Otherwise, the environment variables will be added to the **root** user. If your **shell** is not **bash** or **Zsh**, you need to manually configure the following content to your environment variables after the execution. To view your environment variables, run the **cd** command to go to your home directory and view the hidden files.
# export PATH=/home/tools/llvm/bin:$PATH
# export PATH=/home/tools/hc-gen:$PATH
# export PATH=/home/tools/gcc_riscv32/bin:$PATH
# export PATH=/home/tools/ninja:$PATH
# export PATH=/home/tools/node-v12.20.0-linux-x64/bin:$PATH
# export PATH=/home/tools/gn:$PATH
# export PATH=/root/.local/bin:$PATH
# If you do not need to run the script, you need to install the following:
apt-get update -y
apt-get install -y apt-utils binutils bison flex bc build-essential make mtd-utils gcc-arm-linux-gnueabi u-boot-tools python3.9.2 python3-pip git zip unzip curl wget gcc g++ ruby dosfstools mtools default-jre default-jdk scons python3-distutils perl openssl libssl-dev cpio git-lfs m4 ccache zlib1g-dev tar rsync liblz4-tool genext2fs binutils-dev device-tree-compiler e2fsprogs git-core gnupg gnutls-bin gperf lib32ncurses5-dev libffi-dev zlib* libelf-dev libx11-dev libgl1-mesa-dev lib32z1-dev xsltproc x11proto-core-dev libc6-dev-i386 libxml2-dev lib32z-dev libdwarf-dev
apt-get install -y grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5 libncurses5-dev libncursesw5 libstdc++6 python2.7 gcc-arm-none-eabi vim ssh locales doxygen
# Install the following modules for Python:
chmod +x /usr/bin/repo
pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple requests setuptools pymongo kconfiglib pycryptodome ecdsa ohos-build pyyaml prompt_toolkit==1.0.14 redis json2html yagmail python-jenkins
pip3 install esdk-obs-python --trusted-host pypi.org
pip3 install six --upgrade --ignore-installed six
#You also need to install LLVM, hc-gen, gcc_riscv32, Ninja, node-v14.15.4-linux-x64, and GN, and import the non-bash or non-Zsh configuration in the shell to your environment variables.
```
- Parsing commands: Parse the name of the product to build and load related configurations.
- Running GN: Configure toolchains and global options based on the parsed product name and compilation type.
- Running Ninja: Start building and generate a product distribution.
### Limitations and Constraints<a name="section886933762513"></a>
- You must download the source code using method 3 described in [Source Code Acquisition](../get-code/sourcecode-acquire.md). ## Building Guidelines
- The build environment must be Ubuntu 18.04 or later.
- You must install the software package required for build.
The installation command is as follows: ### Directory Structure
``` ```
sudo apt-get install binutils git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4
```
/build # Directory for build
## Compilation and Building Guidelines<a name="section16901215262"></a> ├── __pycache__
├── build_scripts/ # Python scripts for build
├── common/
├── config/ # Build-related configurations
├── core
│ └── gn/ # BUILD.gn configuration
└── build_scripts/
├── docs
gn_helpers.py*
lite/ # hb and preloader entry
misc/
├── ohos # Process for building and packaging OpenHarmony
│ ├── kits # Kits build and packaging templates and processing
│ ├── ndk # NDK templates and processing
│ ├── notice # Notice templates and processing
│ ├── packages # Distribution packaging templates and processing
│ ├── sa_profile # SA profiles and processing
│ ├── sdk # SDK templates and processing, which contains the module configuration in the SDK
│ └── testfwk # Testing-related processing
├── ohos.gni* # Common .gni files for importing a module at a time.
├── ohos_system.prop
├── ohos_var.gni*
├── prebuilts_download.sh*
├── print_python_deps.py*
├── scripts/
├── subsystem_config.json
├── subsystem_config_example.json
├── templates/ # C/C++ build templates
├── test.gni*
├── toolchain # Build toolchain configuration
├── tools # Common tools
├── version.gni
├── zip.py*
### Directory Structure<a name="section109065332264"></a>
```
/build # Primary directory
├── config # Build configuration items
├── core
│ └── gn # Build entry BUILD.gn configuration
├── loader # Loader of module configuration, which also generates a template for the module
├── ohos # Configuration of the process for building and packaging OpenHarmony
│ ├── kits # Build and packaging templates and processing flow for kits
│ ├── ndk # NDK template and processing flow
│ ├── notice # Notice template and processing flow
│ ├── packages # Distribution packaging template and processing flow
│ ├── sa_profile # SA template and processing flow
│ ├── sdk # SDK template and processing flow, which contains the module configuration in the SDK
│ └── testfwk # Processing flow related to the test
├── scripts # Build-related Python script
├── templates # C/C++ build templates
└── toolchain # Toolchain configuration
``` ```
### Build Command<a name="section123265539266"></a> ### Build Command
- Run the following command in the root directory of the source code to build the full distribution: - Run the following command in the root directory of the source code to build a full distribution:
``` ```
./build.sh --product-name {product_name}
```
**product\_name** indicates the product supported by the current distribution, for example, hispark_taurus_standard. ./build.sh --product-name {product_name}
```
The image generated after build is stored in the **out/{device_name}/packages/phone/images/** directory. **{product_name}** specifies the product platform supported by the current distribution, for example, **hispark_taurus_standard**.
- The build command supports the following options: The image generated is stored in the **out/{device_name}/packages/phone/images/** directory.
``` - The **./build.sh** command supports the following options:
--product-name # (Mandatory) Name of the product to build, for example, Hi3516D V300
--build-target # (Optional) One or more build targets
--gn-args # (Optional) One or more gn parameters
--ccache # (Optional) Use of Ccache for build. This option takes effect only when Ccache is installed on the local PC.
```
```
-h, --help # Display help information and exit.
--source-root-dir=SOURCE_ROOT_DIR # Specify the path.
--product-name=PRODUCT_NAME # Specify the product name.
--device-name=DEVICE_NAME # Specify the device name.
--target-cpu=TARGET_CPU # Specify the CPU.
--target-os=TARGET_OS # Specify the operating system.
-T BUILD_TARGET, --build-target=BUILD_TARGET # specifies one or more targets to build.
--gn-args=GN_ARGS # Specify GN parameters.
--ninja-args=NINJA_ARGS # Specify Ninja parameters.
-v, --verbose # Display all commands used.
--keep-ninja-going # Keep Ninja going until 1,000,000 jobs fail.
--sparse-image
--jobs=JOBS
--export-para=EXPORT_PARA
--build-only-gn # Perform GN parsing and does not run Ninja.
--ccache # (Optional) Use ccache for build. You need to install ccache locally.
--fast-rebuild # Whether to use fast rebuild. The default value is False.
--log-level=LOG_LEVEL # Specify the log level during the build. The options are debug, info, and error. The default value is info.
--device-type=DEVICE_TYPE # Specify the device type. The default value is default.
--build-variant=BUILD_VARIANT # Specify the device operation mode. The default value is user.
### How to Develop<a name="section591084422719"></a> ```
1. Add a module. ### How to Develop
The following steps use a custom module as an example to describe how to build the module, including build a library, an executable file, and a configuration file. 1. Add a component.
The following use a custom component as an example to describe how to write .gn scripts for a library, an executable file, and a configuration file.
In this example, **partA** consists of **feature1**, **feature2**, and **feature3**, which represent a dynamic library, an executable file, and an etc configuration file, respectively.
Add **partA** to a subsystem, for example, **subsystem_examples** (defined in the **test/examples/** directory).
The example module **partA** consists of **feature1**, **feature2**, and **feature3**. The target is a dynamic library for **feature1**, an executable file for **feature2**, and an etc configuration file for **feature3**. The directory structure of **partA** is as follows:
Add **partA** to a subsystem, for example, **subsystem\_examples** \(defined in the **test/examples/** directory\). ```
test/examples/partA
├── feature1
│ ├── BUILD.gn
│ ├── include
│ │ └── helloworld1.h
│ └── src
│ └── helloworld1.cpp
├── feature2
│ ├── BUILD.gn
│ ├── include
│ │ └── helloworld2.h
│ └── src
│ └── helloworld2.cpp
└── feature3
├── BUILD.gn
└── src
└── config.conf
```
The complete directory structure of **partA** is as follows: (a) Write **test/examples/partA/feature1/BUILD.gn** for the dynamic library.
``` ```
test/examples/partA
├── feature1 config("helloworld_lib_config") {
│ ├── BUILD.gn include_dirs = [ "include" ]
│ ├── include }
│ │ └── helloworld1.h
│ └── src ohos_shared_library("helloworld_lib") {
│ └── helloworld1.cpp sources = [
├── feature2 "include/helloworld1.h",
│ ├── BUILD.gn "src/helloworld1.cpp",
│ ├── include ]
│ │ └── helloworld2.h public_configs = [ ":helloworld_lib_config" ]
│ └── src part_name = "partA"
│ └── helloworld2.cpp }
└── feature3
├── BUILD.gn ```
└── src
└── config.conf
```
Example 1: GN script \(**test/examples/partA/feature1/BUILD.gn**\) for building a dynamic library (b) Write **test/examples/partA/feature2/BUILD.gn** for the executable file.
``` ```
config("helloworld_lib_config") {
ohos_executable("helloworld_bin") {
sources = [
"src/helloworld2.cpp"
]
include_dirs = [ "include" ] include_dirs = [ "include" ]
} deps = [ # Dependent modules in the component
"../feature1:helloworld_lib"
ohos_shared_library("helloworld_lib") { ]
sources = [ external_deps = [ "partB:module1" ] # (Optional) Dependent modules of another component are named in Component name:Module name format.
"include/helloworld1.h", install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation.
"src/helloworld1.cpp", part_name = "partA"
}
```
(c) Write **test/examples/partA/feature3/BUILD.gn** for the etc module.
```
ohos_prebuilt_etc("feature3_etc") {
source = "src/config.conf"
relative_install_dir = "init" # (Optional) Relative directory for installing the module. The default installation directory is **/system/etc**.
part_name = "partA"
}
```
(d) Add the module configuration **test/examples/bundle.json** to the **bundle.json** file of the component. Each component has a **bundle.json** file in the root directory of the component. The sample code is as follows:
```
{
"name": "@ohos/<component_name>, # OpenHarmony Package Manager (HPM) component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Set the code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING", # Path of the module's license.
"readmePath": {
"en": "README.rst"
}, # Path of module's reademe.opensource.
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations.
"sub_component": [], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components.
"test": [] # Entry for building the component's test cases.
}
}
}
```
2. Add the component to the product configuration file.
Add the component to **//vendor/{*product_company*}/{*product-name*}/config.json**.
For example, add "subsystem_examples:partA" to the product **config.json** file. **partA** will be built and packaged into the distribution.
3. Start the build.
For example, run the following command to build **hispark_taurus_standard**:
```
./build.sh --product-name hispark_taurus_standard --ccache
```
4. Obtain the build result.
You can obtain the generated files from the **out/hispark_taurus/** directory and the image in the **out/hispark_taurus/packages/phone/images/** directory.
## FAQs
### How Do I Build a Module and Package It into a Distribution?
- Set **part_name** for the module. A module can belong to only one part.
- Add the module to **component.build.sub_component** of the component, or define the dependency between the module and the modules in **component.build.sub_component**.
- Add the component to the component list of the product.
### How Do I Set deps and external_deps?
When adding a module, you need to declare its dependencies in **BUILD.gn**. **deps** specifies dependent modules in the same component, and **external_deps** specifies dependent modules between components.
The dependency between modules can be classified into:
**deps**: The dependent module to be added belongs to the same component with the current module. For example, module 2 depends on module 1, and modules 1 and 2 belong to the same component.
**external_deps**: The dependent module to be added belongs to another component. For example, module 2 depends on module 1, and modules 1 and 2 belong to different components.
- Example of **deps**:
```
import("//build/ohos.gni")
ohos_shared_library("module1") {
...
part_name = "part1" # (Mandatory) Name of the component to which the module belongs.
...
}
```
```
import("//build/ohos.gni")
ohos_shared_library("module2") {
...
deps = [
"GN target of module 1",
...
] # Intra-component dependency
part_name = "part1" # (Mandatory) Name of the part to which the module belongs.
}
```
- Example of **external_deps**:
```
import("//build/ohos.gni")
ohos_shared_library("module1") {
...
part_name = "part1" # (Mandatory) Name of the component to which the module belongs.
...
}
```
- **bundle.json** file of the component to which module 1 belongs
```
{
"name": "@ohos/<component_name>", # HPM component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath "licensePath": "COPYING",
": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations.
"sub_component": ["part1"], # Component build entry. All modules of the component are listed here.
"inner_kits": [], # APIs between components.
{
"header": {
"header_base": "Header file directory", # Directory of the header files.
"header_files": [
"Header file name"
] # List of header file names.
},
"name": "GN target of module 1"
},
],
"test": [] # Entry for building the component's test cases.
}
}
}
```
```
import("//build/ohos.gni")
ohos_shared_library("module2") {
...
external_deps = [
"part1:module1",
...
] # Inter-component dependency. The dependent module must be declared in **inner_kits** by the dependent component.
part_name = "part2" # (Mandatory) Name of the component to which the module belongs.
}
```
> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
> The values of **external_deps** are in the *Component name*:*Module name* format. The module name must exist in **inner_kits** of the dependent component.
### How Do I Add a Module to a Standard System?
You may need to:
- Add a module to an existing component.
- Add a module to a new component.
- Add a module to a new subsystem.
#### Adding a Module to an Existing Component
1. Configure the **BUILD.gn** file in the module directory and select the corresponding template.
Follow the procedure for adding a module to an existing component. Note that **part_name** in the **BUILD.gn** file is the name of the existing component.
2. Modify the **bundle.json** file. "GN target of the module in the component"
```
{
"name": "@ohos/<component_name>, # HPM component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": "third_party/nghttp2"
}, # Code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations
"sub_component": [
"//foundation/arkui/napi:napi_packages", # Existing module 1
"//foundation/arkui/napi:napi_packages_ndk" # Existing module 2
"//foundation/arkui/napi:new" # Module to add
], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components
"test": [] # Entry for building the component's test cases.
}
}
}
```
Note that the **bundle.json** file must be in the folder of the corresponding subsystem.
#### Creating a Component and Adding a Module
1. Configure the **BUILD.gn** file in the module directory and select the corresponding template. Note that **part_name** in the **BUILD.gn** file is the name of the newly added component.
2. Create a **bundle.json** file in the folder of the corresponding subsystem.
The **bundle.json** file consists of two parts: **subsystem** and **parts**. Add the component information to **parts**. When adding a component, you need to specify the **sub_component** of the component. If there are APIs provided for other components, add them in **inner_kits**. If there are test cases, add them in **test**.
3. Add the new component to the end of existing components in **//vendor/{product_company}/{product-name}/config.json**.
```
"subsystems": [
{
"subsystem": "Name of the subsystem to which the component belongs",
"components": [
{"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem
{ "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem
{"component": "New component name", "features":[]} # New component in the subsystem
]
},
...
]
```
#### Creating a Subsystem and Adding a Module
1. Configure the **BUILD.gn** file in the module directory and select the corresponding template.
Note that **part_name** in the **BUILD.gn** file is the name of the newly added component.
2. Create a **bundle.json** file in the folder of the component of the subsystem.
This step is the same as the step in "Creating a Component and Adding a Module."
3. Modify the **subsystem_config.json** file in the **build** directory.
```
{
"Subsystem 1 name": { # Existing subsystem 1
"path": "Subsystem 1 directory",
"name": "Subsystem 1 name"
},
"Subsystem 2 name": { # Existing subsystem 2
"path": "Subsystem 2 directory",
"name": "Subsystem 2 name"
},
"Subsystem name new": { # Subsystem to add
"path": "New subsystem directory",
"name": "New subsystem name"
},
...
}
```
This file defines the subsystems and their paths. To add a subsystem, specify **path** and **name** for the subsystem.
4. If **product-name** in the **//vendor/{product_company}/{product-name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file.
```
"subsystems": [
{
"subsystem": "arkui", # Name of the existing subsystem
"components": [ # All components of the subsystem
{
"component": "ace_engine_standard", # Name of the existing component
"features": []
},
{
"component": "napi", # Name of the existing component
"features": []
}
{
"component": "component_new1", # Name of the new component added to the existing subsystem
"features": []
}
]
},
{
"subsystem": "subsystem_new", # Name of the new subsystem to add
"components": [
{
"component": "component_new2", # Name of the component added to the new subsystem
"features": []
}
]
},
...
]
```
Verification:
- Check that **module_list** in the **BUILD.gn** file in the component directory under the corresponding subsystem directory contains the target defined in the **BUILD.gn** file of the new module.
- Check the .so file or binary file generated in the image created.
#### Configuration Files
There are four OpenHarmony configuration files.
1. **vendor\Product vendor\Product name\config.json**
```
{
"product_name": "MyProduct",
"version": "3.0",
"type": "standard",
"target_cpu": "arm",
"ohos_version": "OpenHarmony 1.0",
"device_company": "MyProductVendor",
"board": "MySOC",
"enable_ramdisk": true,
"subsystems": [
{
"subsystem": "ace",
"components": [
{ "component": "ace_engine_lite", "features":[""] }
]
},
...
] ]
public_configs = [ ":helloworld_lib_config" ] }
part_name = "partA"
```
This file specifies the name, manufacturer, device, version, type of system to be built, and subsystems of the product.
2. **subsystem_config.json** in the **build** directory
```
{
"arkui": {
"path": "foundation/arkui",
"name": "arkui"
},
"ai": {
"path": "foundation/ai",
"name": "ai"
},
......
} }
``` ```
This file contains subsystem information. You need to configure **name** and **path** for each subsystem.
3. **bundle.json** of a subsystem
```
{
"name": "@ohos/<component_name>, # HPM component name, in the "@Organization/Component name" format.
"description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions.
"version": "3.1", # Version, which must be the same as the version of OpenHarmony.
"license": "MIT", # Component license.
"publishAs": "code-segment", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
}, # Code restoration path (source code path) when publishAs is code-segment.
"dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty.
"scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty.
"licensePath": "COPYING",
"readmePath": {
"en": "README.rst"
},
"component": { # Component attributes.
"name": "<component_name>", # Component name.
"subsystem": "", # Subsystem to which the component belongs.
"syscap": [], # System capabilities provided by the component for applications.
"features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
"adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
"rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value.
"ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value.
"deps": {
"components": [], # Other components on which this component depends.
"third_party": [] # Third-party open-source software on which this component depends.
},
"build": { # Build-related configurations.
"sub_component": ["gn target of the module"], # Component build entry
"inner_kits": [], # APIs between components.
"test": [] # Entry for building the component's test cases.
}
}
}
```
The **bundle.json** file defines the components of a subsystem.
Each component contains the module's target **component.build.sub_component**, **component.build.inner_kits** for interaction between components, and test cases **component.build.test_list**. The **component.build.sub_component** is mandatory.
4. **BUILD.gn** of each module
You can create **BUILD.gn** from a template or using the GN syntax.
### How Do I Build a HAP?
#### **HAP Description**
An OpenHarmony Ability Package (HAP) includes resources, raw assets, JS assets, native libraries, and **config.json**.
#### **Templates**
Example 2: GN script \(**test/examples/partA/feature2/BUILD.gn**\) for building an executable file The compilation and build subsystem provides four templates for building HAPs. The templates are integrated in **ohos.gni**. Before using the templates, import **build/ohos.gni**.
1. **ohos_resources**
This template declares resource targets. After a target is built by restool, an index file is generated. The resource source file and index file are both packaged into the HAP.
A **ResourceTable.h** file is also generated after resource building. This header file can be referenced if the resource target is relied on.
The resource target name must end with **resources**, **resource**, or **res**. Otherwise, a build error may occur.
The following variables are supported:
- **sources**: a list of resource paths.
- **hap_profile**: **config.json** of the HAP required for resource building.
- **deps**: (optional) dependency of the current target.
2. **ohos_assets**
This template declares asset targets.
Beware that the spelling is "assets" as opposed to "assert".
The asset target name must end with **assets** or **asset**.
The following variables are supported:
- **sources**: a list for raw asset paths.
- **deps**: (optional) dependency of the current target.
3. **ohos_js_assets**
This template declares a JS resource target. The JS resource is the executable part of an L2 HAP.
The JS asset target name must end with **assets** or **asset**.
The following variables are supported:
- **source_dir**: JS resource path, which is of the string type.
- **deps**: (optional) dependency of the current target.
4. **ohos_hap**
This template declares a HAP target. A HAP that will be generated and packaged into the system image.
The following variables are supported:
- **hap_profile**: **config.json** of the HAP.
- **deps**: dependency of the current target.
- **shared_libraries**: native libraries on which the current target depends.
- **hap_name**: (optional) name of the HAP. The default value is the target name.
- **final_hap_path**: (optional) destination path of the HAP. It takes precedence over **hap_name**.
- **subsystem_name**: name of the subsystem to which the HAP belongs. The value must be the same as that in **bundle.json**. Otherwise, the HAP will fail to be installed in the system image.
- **part_name**: name of the component to which the HAP belongs. The value must be the same as that in **bundle.json**.
- **js2abc**: whether to convert the HAP into ARK bytecode.
- **certificate_profile**: certificate profile of the HAP, which is used for signature. For details about signatures, see [Configuring Signature Information](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section17660437768).
- **certificate_file**: Certificate file. You must apply for the certificate and its profile from the official OpenHarmony website.
- **keystore_path**: keystore file, which is used for signature.
- **keystore_password**: keystore password, which is used for signature.
- **key_alias**: key alias.
- **module_install_name**: name of the HAP used during installation.
- **module_install_dir**: installation path. The default path is **system/app**.
**HAP Example**
``` ```
ohos_executable("helloworld_bin") { import("//build/ohos.gni") # Import **ohos.gni**.
sources = [ ohos_hap("clock") {
"src/helloworld2.cpp" hap_profile = "./src/main/config.json" # config.json
deps = [
":clock_js_assets", # JS assets
":clock_resources", # Resources
] ]
include_dirs = [ "include" ] shared_libraries = [
deps = [ # Dependent submodule "//third_party/libpng:libpng", # Native library
"../feature1:helloworld_lib"
] ]
external_deps = [ "partB:module1" ] # (Optional) If there is a cross-module dependency, the format is "module name: submodule name" certificate_profile = "../signature/systemui.p7b" # Certificate profile
install_enable = true # By default, the executable file is not installed. You need to set this parameter to true for installation. hap_name = "SystemUI-NavigationBar" # HAP name
part_name = "partA" part_name = "prebuilt_hap"
subsystem_name = "applications"
}
ohos_js_assets("clock_js_assets") {
source_dir = "./src/main/js/default"
}
ohos_resources("clock_resources") {
sources = [ "./src/main/resources" ]
hap_profile = "./src/main/config.json"
} }
``` ```
Example 3: GN script \(**test/examples/partA/feature3/BUILD.gn**\) for building the etc configuration file \(submodule\). ### What Does an Open-Source Software Notice Collect?
``` #### Information to Collect
ohos_prebuilt_etc("feature3_etc") {
source = "src/config.conf"
relative_install_dir = "init" # (Optional) Directory for installing the submodule, which is relative to the default installation directory (/system/etc)
part_name = "partA"
}
```
Example 4: Adding the module configuration file **test/examples/ohos.build** to the **ohos.build** file of this subsystem. Each subsystem has an **ohos.build** file in its root directory. Example: The notice collects only the licenses of the modules packaged in the image. For example, the licenses of the tools (such as Clang, Python, and Ninja) used during the build process are not collected.
``` A static library itself is not packaged. However, if it is packaged into the system as part of a dynamic library or executable file, the license of the static library will be collected for completeness.
"partA": {
"module_list": [
"//test/examples/partA/feature1:helloworld_lib",
"//test/examples/partA/feature2:helloworld_bin",
"//test/examples/partA/feature3:feature3_etc",
],
"inner_kits": [
],
"system_kits": [
],
"test_list": [
]
}
```
The declaration of a module contains the following parts: The final **Notice.txt** file must include all licenses used by the files in the image and the mapping between modules and licenses.
- **module\_list**: submodule list of the module The **Notice.txt** file is located in the **/system/etc/** directory.
- **inner\_kits**: APIs for other modules that depend on this module through **external\_deps**
- **system\_kits**: APIs for developers
- **test\_list**: test cases for the submodules of the module
2. Add the module to the product configuration file. #### Rules for Collecting Information
Add the module to the product configuration file **//vendor/{product_company}/{product-name}/config.json**. Licenses are collected by priority.
Add "subsystem\_examples:partA" to the product configuration file. **partA** will be built and packaged into the distribution. 1. Licenses that are directly declared in a module's **BUILD.gn** are given the top priority. The following is an example:
3. Build the module. ```
ohos_shared_library("example") {
...
license_file = "path-to-license-file"
...
}
```
For example, run the following command to build hispark_taurus_standard: 2. If there is no explicitly declared license, the build script searches for the **Readme.OpenSource** file in the directory of **BUILD.gn**, parses the file, and collects the obtained licenses.
If the **Readme.OpenSource** file does not contain license information, an error will be reported.
``` 3. If the **Readme.OpenSource** file does not exist, the build script searches for the **License**, **Copyright**, and **Notice** files from the current directory to the root directory of the source code by default. If obtained license information will be used as the licenses of the module.
./build.sh --product-name hispark_taurus_standard --ccache
``` 4. If no license is found, the default license (Apache License 2.0) will be used.
4. Obtain the build result. Check items:
Files generated during the build process are stored in the **out/hispark_taurus/** directory, and the generated image is stored in the **out/hispark_taurus/packages/phone/images/** directory. 1. For third-party open-source software, such as OpenSSL and ICU, **Readme.OpenSource** must be configured in the source code directory. Check whether **Readme.OpenSource** is in the same directory as **BUILD.gn** and whether the license configured in **Readme.OpenSource** is valid.
2. If the source code is not licensed under the Apache License 2.0, the corresponding license file must be provided in the source code directory or declared by **license_file** for the module.
3. If the source code file added to **BUILD.gn** is not from the current directory, check whether the license in the repository where the source code file is located is the same as that in the repository of **BUILD.gn**. License inconsistency entails follow-up operations.
# HiSysEvent Logging<a name="EN-US_TOPIC_0000001231373947"></a> # HiSysEvent Logging
## Overview<a name="section77571101789"></a> ## Overview
### Introduction<a name="section123133332175224"></a> ### Introduction
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics. HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running. Besides, it supports shielding of event logging by event domain, helping you to evaluate the impact of event logging.
### Constraints<a name="section123181432175224"></a> ### Working Principles
Before logging system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md). Before logging system events, you need to complete HiSysEvent logging configuration. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## Development Guidelines<a name="section314416685113"></a> ## Development Guidelines
### Available APIs<a name="section13480315886"></a> ### When to Use
The following table lists the C++ APIs provided by the HiSysEvent class. Use HiSysEvent logging to flush logged event data to disks.
For details about the HiSysEvent class, see the API reference. ### Available APIs
**Table 1** C++ APIs provided by HiSysEvent #### C++ Event Logging APIs
| API| Description| HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the API Reference.
| -------- | --------- |
| template&lt;typename... Types&gt; static int Write(const std::string &amp;domain, const std::string &amp;eventName, EventType type, Types... keyValues) | Logs system events. <br><br>Input arguments: <ul><li>**domain**: Indicates the domain related to the event. You can use a preconfigured domain or customize a domain as needed. The name of a custom domain can contain a maximum of 16 characters, including digits (0-9) and uppercase letters (A-Z). It must start with a letter. </li><li>**eventName**: Indicates the event name. The value contains a maximum of 32 characters, including digits (0 to 9), letters (A-Z), and underscores (&#95;). It must start with a letter and cannot end with an underscore. </li><li>**type**: Indicates the event type. For details, see EventType. </li><li>**keyValues**: Indicates the key-value pairs of event parameters. It can be in the format of the basic data type, std::string, std::vector&lt;basic data type&gt;, or std:vector&lt;std::string&gt;. The value contains a maximum of 48 characters, including digits (0 to 9), letters (A-Z), and underscores (&#95;). It must start with a letter and cannot end with an underscore. The number of parameter names cannot exceed 32. </li></ul>Return value: <ul><li>**0**: The logging is successful. </li><li>Negative value: The logging has failed.</li></ul> | > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> In OpenHarmony-3.2-Beta3, HiSysEvent logging is open for restricted use to avoid event storms. The **HiSysEvent::Write** API in Table 1 is replaced by the **HiSysEventWrite** API in Table 2. The **HiSysEvent::Write** API has been deprecated. Use the **HiSysEventWrite** API instead for HiSysEvent logging.
**Table 2** Description of HiSysEvent::Domain APIs
**Table 1** C++ event logging API (deprecated)
| API| Description|
| -------- | --------- | | API | Description |
| static const std::string AAFWK | Atomic ability subsystem| | ------------------------------------------------------------ | ---------------------- |
| static const std::string APPEXECFWK | User program framework subsystem| | template&lt;typename...&nbsp;Types&gt;&nbsp;<br>static&nbsp;int&nbsp;Write(const&nbsp;std::string&nbsp;&amp;domain,&nbsp;const&nbsp;std::string&nbsp;&amp;eventName,&nbsp;EventType&nbsp;type,&nbsp;Types...&nbsp;keyValues) | Flushes logged event data to disks.|
| static const std::string ACCOUNT | Account subsystem|
| static const std::string ARKUI | ARKUI subsystem| **Table 2** C++ event logging API (in use)
| static const std::string AI | AI subsystem| | API | Description |
| static const std::string BARRIER_FREE | Accessibility subsystem| | ------------------------------------------------------------ | ---------------------- |
| static const std::string BIOMETRICS | Biometric recognition subsystem| | HiSysEventWrite(domain, eventName, type, ...) | Flushes logged event data to disks.|
| static const std::string CCRUNTIME |C/C++ operating environment subsystem|
| static const std::string COMMUNICATION | Public communication subsystem| **Table 3** Event types
| static const std::string DEVELOPTOOLS | Development toolchain subsystem|
| static const std::string DISTRIBUTED_DATAMGR | Distributed data management subsystem| | Event | Description |
| static const std::string DISTRIBUTED_SCHEDULE | Distributed Scheduler subsystem| | --------- | ------------ |
| static const std::string GLOBAL | Globalization subsystem| | FAULT | Fault event|
| static const std::string GRAPHIC | Graphics subsystem| | STATISTIC | Statistical event|
| static const std::string HIVIEWDFX | DFX subsystem| | SECURITY | Security event|
| static const std::string IAWARE | Scheduling and resource management subsystem| | BEHAVIOR | Behavior event|
| static const std::string INTELLI_ACCESSORIES | Smart accessory subsystem|
| static const std::string INTELLI_TV | Smart TV subsystem| #### Kernel Event Logging APIs
| static const std::string IVI_HARDWARE | IVI-dedicated hardware subsystem|
| static const std::string LOCATION | LBS subsystem| The following table describes the kernel event logging APIs.
| static const std::string MSDP | MSDP subsystem|
| static const std::string MULTI_MEDIA | Media subsystem| **Table 4** Description of kernel event logging APIs
| static const std::string MULTI_MODAL_INPUT | Multimode input subsystem|
| static const std::string NOTIFICATION | Common event and notification subsystem| | API | Description |
| static const std::string POWERMGR | Power management subsystem| | ------------------------------------------------------------ | ------------------------------------ |
| static const std::string ROUTER | Router subsystem| | struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | Creates a **hisysevent** object. |
| static const std::string SECURITY | Security subsystem| | void hisysevent_destroy(struct hiview_hisysevent *event); | Destroys a **hisysevent** object. |
| static const std::string SENSORS | Pan-sensor subsystem| | int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | Adds event parameters of the integer type to a **hisysevent** object. |
| static const std::string SOURCE_CODE_TRANSFORMER | Application porting subsystem| | int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | Adds event parameters of the string type to a **hisysevent** object.|
| static const std::string STARTUP | Startup subsystem| | int hisysevent_write(struct hiview_hisysevent *event); | Flushes **hisysevent** object data to disks. |
| static const std::string TELEPHONY | Telephony subsystem|
| static const std::string UPDATE | Update subsystem| Table 5 Kernel event types
| static const std::string USB | USB subsystem|
| static const std::string WEARABLE_HARDWARE | Wearable-dedicated hardware subsystem| | Event | Description |
| static const std::string WEARABLE_HARDWARE | Wearable-dedicated service subsystem| | --------- | ------------ |
| static const std::string OTHERS | Others| | FAULT | Fault event|
**Table 3** Description of HiSysEvent::EventType
| Name| Description|
| -------- | --------- |
| FAULT | Fault event|
| STATISTIC | Statistical event| | STATISTIC | Statistical event|
| SECURITY | Security event| | SECURITY | Security event|
| BEHAVIOR | System behavior event| | BEHAVIOR | Behavior event|
### How to Develop
#### C++ Event Logging
1. Call the event logging API wherever needed, with required event parameters passed to the API.
```c++
HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo");
```
#### Kernel Event Logging
1. Create a **hisysevent** object based on the specified event domain, event name, and event type.
```c
struct hiview_hisysevent *event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR);
```
2. Pass the customized event parameters to the **hisysevent** object.
### Development Example<a name="section112771171317"></a> ```c
// Add a parameter of the integer type.
hisysevent_put_integer(event, "BOOT_TIME", 100);
C++ // Add a parameter of the string type.
hisysevent_put_string(event, "MSG", "This is a test message");
```
1. Develop the source code. 3. Trigger reporting of the **hisysevent** event.
Include the HiSysEvent header file in the class definition header file or class implementation source file. For example: ```c
hisysevent_write(event);
```
4. Manually destroy the **hisysevent** object.
```c
hisysevent_destroy(&event);
```
#### Shielding of Event Logging by Event Domain
1. In the corresponding file, define the **DOMAIN_MASKS** macro with content similar to DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n. There are three scenarios:
- Shielding only event logging for the event domains configured in the current source code file: Define the **DOMAIN_MASKS** macro before importing the **.cpp** file to the **hisysevent.h** file.
```c++
#define DOMAIN_MASKS "DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n"
#include "hisysevent.h"
```
- Shielding event logging for event domains of the entire module: Define the **DOMAIN_MASKS** macro in the **BUILD.gn** file of the module.
```gn
config("module_a"){
cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""]
}
```
- Shielding event logging for event domains globally: Define the **DOMAIN_MASKS** macro in **/build/config/compiler/BUILD.gn**.
```gn
cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""]
```
2. Perform event logging by using the **HiSysEventWrite** API.
```c++
constexpr char DOMAIN[] = "DOMAIN_NAME_1";
const std::string eventName = "EVENT_NAME1";
OHOS:HiviewDFX::HiSysEvent::EventType eventType = OHOS:HiviewDFX::HiSysEvent::EventType::FAULT;
HiSysEventWrite(domain, eventName, eventType); // Event logging is shielded for DOMAIN_NAME_1 because it has been defined in the DOMAIN_MASKS macro.
```
### Development Examples
#### C++ Event Logging
Assume that a service module needs to trigger event logging during application startup to record the application startup event and application bundle name. The following is the complete sample code:
1. Add the HiSysEvent component dependency to the **BUILD.gn** file of the service module.
```c++
external_deps = [ "hisysevent_native:libhisysevent" ]
```
2. In the application startup function **StartAbility()** of the service module, call the event logging API with the event parameters passed in.
```c++
#include "hisysevent.h"
int StartAbility()
{
... // Other service logic
int ret = HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo");
... // Other service logic
}
```
#### Kernel Event Logging
Assume that the kernel service module needs to trigger event logging during device startup to record the device startup event. The following is the complete sample code:
1. In the device startup function **device_boot()**, construct a **hisysevent** object. After that, trigger event reporting, and then destroy the **hisysevent** object.
```c
#include <dfx/hiview_hisysevent.h>
#include <linux/errno.h>
#include <linux/printk.h>
int device_boot()
{
... // Other service logic
struct hiview_hisysevent *event = NULL;
int ret = 0;
event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR);
if (!event) {
pr_err("failed to create event");
return -EINVAL;
}
ret = hisysevent_put_string(event, "MSG", "This is a test message");
if (ret != 0) {
pr_err("failed to put sting to event, ret=%d", ret);
goto hisysevent_end;
}
ret = hisysevent_write(event);
hisysevent_end:
hisysevent_destroy(&event);
... // Other service logic
}
``` ```
#### Shielding of Event Logging by Event Domain
- If you want to shield event logging for the **AAFWK** and **POWER** domains in a **.cpp** file, define the **DOMAIN_MASKS** macro before including the **hisysevent.h** header file to the **.cpp** file.
```c++
#define DOMAIN_MASKS "AAFWK|POWER"
#include "hisysevent.h" #include "hisysevent.h"
``` ... // Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "MODULE", "com.ohos.module"); // HiSysEvent logging is not performed.
... // Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::POWER, "POWER_RUNNINGLOCK", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "NAME", "com.ohos.module"); // HiSysEvent logging is not performed.
Add the event logging code. For example, if you want to log events specific to the app start time (start\_app), then add the following code to the service implementation source file: ```
- If you want to shield event logging for the **AAFWK** and **POWER** domains of the entire service module, define the **DOMAIN_MASKS** macro as follows in the **BUILG.gn** file of the service module.
```gn
config("module_a") {
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
}
``` ```
HiSysEvent::Write(HiSysEvent::Domain::AAFWK, "start_app", HiSysEvent::EventType::FAULT, "app_name", "com.demo");
- If you want to shield event logging for the **AAFWK** and **POWER** domains globally, define the **DOMAIN_MASKS** macro as follows in **/build/config/compiler/BUILD.gn**.
```gn
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
``` ```
2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**. # Reference
``` The HiSysEvent module writes the logged event data to the node file, and the Hiview module parses and processes the event data in a unified manner. For details, see the [Hiview Development Guide](subsys-dfx-hiview.md).
external_deps = [ "hisysevent_native:libhisysevent" ]
```
# HiSysEvent Tool Usage<a name="EN-US_TOPIC_0000001231614021"></a> # HiSysEvent Tool Usage
## Overview<a name="section1886702718521"></a>
## Overview
The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** directory of the system. You can use this tool to subscribe to real-time system events or query historical system vents. The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** directory of the system. You can use this tool to subscribe to real-time system events or query historical system vents.
## Subscribing to Real-Time System Events<a name="section1210623418527"></a> ## Subscribing to Real-Time System Events
- Command for subscribing to real-time system events: - Command for subscribing to real-time system events:
``` ```
hisysevent -r hisysevent -r
...@@ -15,10 +16,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -15,10 +16,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -r&nbsp; | Subscribes to real-time system events based on the default settings. When this option is specified, any real-time system event will be printed on the console.| | -r | Subscribes to real-time system events based on the default settings. When this option is specified, any real-time system event will be printed on the console.|
- Command for enabling the debugging mode: - Command for enabling the debugging mode:
``` ```
hisysevent -r -d hisysevent -r -d
...@@ -27,10 +28,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -27,10 +28,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -d | Subscribes to real-time system events in debugging mode.| | -d | Subscribes to real-time system events in debugging mode.|
- Command for subscribing to real-time system events by event tag: - Command for subscribing to real-time system events by event tag:
``` ```
hisysevent -r -t <tag> [-c [WHOLE_WORD|PREFIX|REGULAR]] hisysevent -r -t <tag> [-c [WHOLE_WORD|PREFIX|REGULAR]]
...@@ -39,24 +40,22 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -39,24 +40,22 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -t&nbsp; | Event tag used to filter subscribed real-time system events.| | -t | Event tag used to filter subscribed real-time system events.|
| -c&nbsp; | Matching rule for event tags. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| | -c | Matching rule for event tags. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.|
Example: Example:
``` ```
# hisysevent -r -t "TAG" -c PREFIX # hisysevent -r -t "STA" -c PREFIX
{"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963670809,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200750","HAPPEN_TIME":1501963670809,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"4973863135535405472","info_":""}
# hisysevent -r -t "TA\w{0,1}" -c REGULAR # hisysevent -r -t "STAw{0,6}" -c REGULAR
{"domain_":"WINDOWMANAGER","name_":"NO_FOCUS_WINDOW","type_":1,"time_":1501940269802,"tz_":"+0000","tag_":"TAG","pid_":1428,"tid_":1433,"uid_":10001,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963793206,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200953","HAPPEN_TIME":1501963793206,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""}
{"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} # hisysevent -r -t "STA\w+" -c REGULAR
# hisysevent -r -t "TA\w+" -c REGULAR {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963863393,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201103","HAPPEN_TIME":1501963863393,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"5522352691813553392","info_":""}
{"domain_":"WINDOWMANAGER","name_":"NO_FOCUS_WINDOW","type_":1,"time_":1501940269802,"tz_":"+0000","tag_":"TAG","pid_":1428,"tid_":1433,"uid_":10001,"level_":"CRITICAL","info_":""}
{"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""}
``` ```
- Command for subscribing to real-time system events by event domain and event name: - Command for subscribing to real-time system events by event domain and event name:
``` ```
hisysevent -r -o <domain> -n <eventName> [-c [WHOLE_WORD|PREFIX|REGULAR]] hisysevent -r -o <domain> -n <eventName> [-c [WHOLE_WORD|PREFIX|REGULAR]]
...@@ -65,31 +64,29 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -65,31 +64,29 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -o | Event domain used to filter subscribed real-time system events.| | -o | Event domain used to filter subscribed real-time system events.|
| -n | Event name used to filter subscribed real-time system events.| | -n | Event name used to filter subscribed real-time system events.|
| -c | Matching rule for event domains and event names. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| | -c | Matching rule for event domains and event names. The options can be **WHOLE_WORD**, PREFIX, or **REGULAR**.|
Example: Example:
``` ```
# hisysevent -r -o "DOMAINA" -n "EVENTNAMEA" # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE"
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""}
# hisysevent -r -o "DOMA\w{0,10}" -n "EVENT\w+" -c REULAR # hisysevent -r -o "RELIABI\w{0,8}" -n "APP_FREEZE" -c REGULAR
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964144383,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501964144383,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""}
{"domain_":"DOMAINABC","name_":"EVENTNAMEABC","type_":1,"time_":1501940269938,"tz_":"+0000","pid_":1428,"tid_":1336,"uid_":10002,"level_":"CRITICAL","info_":""} # hisysevent -r -o "RELIABI\w+" -c REGULAR
# hisysevent -r -o "DOMA\w{0,10}" -c REGULAR {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964193466,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501964193466,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""}
{"domain_":"DOMAINABC","name_":"EVENTNAMEABC","type_":1,"time_":1501940269938,"tz_":"+0000","pid_":1428,"tid_":1336,"uid_":10002,"level_":"CRITICAL","info_":""}
{"domain_":"DOMAINABC","name_":"EVENTNAMEB","type_":1,"time_":1501940279938,"tz_":"+0000","pid_":1428,"tid_":1344,"uid_":10002,"level_":"CRITICAL","info_":""}
``` ```
>![](../public_sys-resources/icon-note.gif) **NOTE:** > **NOTE**
>If **-t**, **-o**, and **-n** are specified, the system checks whether the configured event tag is null. If the event tag is not null, the system filters system events based on the matching rules for the event tag. Otherwise, the system filters system events based on the matching rules for the event domain and event name. > If **-t**, **-o**, and **-n** are specified, the system checks whether the configured event tag is null. If the event tag is not null, the system filters system events based on the matching rules for the event tag. Otherwise, the system filters system events based on the matching rules for the event domain and event name.
## Querying Historical System Events<a name="section1210623418539"></a> ## Querying Historical System Events
- Command for querying historical system events: - Command for querying historical system events:
``` ```
hisysevent -l hisysevent -l
...@@ -98,10 +95,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -98,10 +95,10 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -l | Queries historical system events based on the default settings. A maximum of 1,000 latest system events will be returned.| | -l | Queries historical system events based on the default settings. A maximum of 1,000 latest system events will be returned.|
- Command for querying historical system events within the specified period of time: - Command for querying historical system events within the specified period of time:
``` ```
hisysevent -l -s <begin time> -e <end time> hisysevent -l -s <begin time> -e <end time>
...@@ -110,21 +107,20 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -110,21 +107,20 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -s | Start time for querying historical system events. Only system events generated after the start time are returned.| | -s | Start time for querying historical system events. Only system events generated after the start time are returned.|
| -e | End time for querying historical system events. Only system events generated before the end time are returned.| | -e | End time for querying historical system events. Only system events generated before the end time are returned.|
Example: Example:
``` ```
# hisysevent -l -s 20207388633 -e 20207389000 # hisysevent -l -s 1501964222980 -e 1501964222996
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388633,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"GRAPHIC","name_":"NO_DRAW","type_":1,"time_":1501964222980,"tz_":"+0000","pid_":1505,"tid_":1585,"uid_":10002,"PID":1505,"UID":10002,"ABILITY_NAME":"","MSG":"It took 1957104259905ns to draw, UI took 0ns to draw, RSRenderThread took 8962625ns to draw, RSRenderThread dropped 0 UI Frames","level_":"MINOR","id_":"1708287249901948387","info_":"isResolved,eventId:0"}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388900,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222994,"tz_":"+0000","pid_":623,"tid_":1445,"uid_":1201,"SUB_EVENT_TYPE":"NO_DRAW","EVENT_TIME":"20170805201702","MODULE":"NO_DRAW","PNAME":"NO_DRAW","REASON":"NO_DRAW","DIAG_INFO":"","STACK":"SUMMARY:\n","HIVIEW_LOG_FILE_PATHS":["/data/log/faultlog/faultlogger/appfreeze-NO_DRAW-10002-20170805201702"],"DOMAIN":"GRAPHIC","STRING_ID":"NO_DRAW","PID":1505,"UID":10002,"PACKAGE_NAME":"NO_DRAW","PROCESS_NAME":"","MSG":"It took 1956945826265ns to draw, UI took 0ns to draw, RSRenderThread took 9863293ns to draw, RSRenderThread dropped 0 UI Frames\n","level_":"CRITICAL","tag_":"STABILITY","id_":"10448522101019619655","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207389000,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""}
``` ```
- Command for setting the maximum number of historical events that can be queried: - Command for setting the maximum number of historical events that can be queried:
``` ```
hisysevent -l -m <max hisysevent count> hisysevent -l -m <max hisysevent count>
...@@ -133,18 +129,36 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -133,18 +129,36 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
Description of command options: Description of command options:
| Option| Description| | Option| Description|
| -------- | --------- | | -------- | -------- |
| -m | Maximum number of historical system events that can be queried. The value ranges from **0** to **1000**. The number of returned system events is not more than the value of this parameter.| | -m | Maximum number of historical system events that can be queried. The value ranges from **0** to **1000**. The number of returned system events is not more than the value of this parameter.|
Example: Example:
``` ```
# hisysevent -l -s 20207388633 -e 20207389000 -m 3 # hisysevent -l -s 1501964222980 -e 1501964222996 -m 1
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388900,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} ```
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207389000,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""}
# hisysevent -l -m 2 ## System Event Validity Check
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388633,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} - Enabling system event validity check
```
hisysevent -v
``` ```
Description of command options:
| Option| Description|
| -------- | -------- |
| -v | Used with the subscription command **-r** and query command **-l**. If system event validity check is enabled, invalid content contained in system events will be highlighted in red.|
Example:
```
# hisysevent -v -l -s 1501964222980 -e 1501964222996
# The **HAPPEN_TIME** and **VERSION** fields are not configured in the YAML file for the **APP_FREEZE** event that belongs to the **RELIABILITY** domain. Therefore, the two fields are highlighted in red.
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""}
# hisysevent -v -r -o "RELIABILITY" -n "APP_FREEZE"
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964644584,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805202404","HAPPEN_TIME":1501964644584,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"11097868872446282676","info_":""}
```
# HiSysEvent Development<a name="EN-US_TOPIC_0000001195021448"></a> # HiSysEvent Development<a name="EN-US_TOPIC_0000001195021448"></a>
- **[HiSysEvent Overview](subsys-dfx-hisysevent-overview.md)**
- **[HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md)** - **[HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md)**
- **[HiSysEvent Logging](subsys-dfx-hisysevent-logging.md)** - **[HiSysEvent Logging](subsys-dfx-hisysevent-logging.md)**
......
# Hiview Development Guide
## Introduction
### Function Overview
Hiview is a module that provides toolkits for device maintenance across different platforms. It consists of the plugin management platform and the service plugins running on the platform. Hiview works in event-driven mode. The core of Hiview is a collection of HiSysEvent stubs distributed in the system. Formatted events are reported to Hiview through the HiSysEvent API for processing. The following figure shows the data interaction process.
**Figure 1** Data interaction between Hiview modules
![Hiview_module_data_interaction](figure/Hiview_module_data_interaction.png)
1. The service process calls the event logging API to report logged event information and writes the information to the node file.
2. SysEventSource of the Hiview process asynchronously reads event information from the node file and distributes the event to SysEventPipeline for processing.
- The SysEventService plugin verifies events and flushes them to disks.
- The Faultlogger plugin processes fault-related events.
- The EventLogger plugin collects event-related log information.
3. On completion of event processing, SysEventPipeline sends the events to the event subscription queue and then dispatches the events to the subscription plugin for processing.
- FreezeDetectorPlugin processes screen freezing events.
- HiCollieCollector processes suspension events.
### Basic Concepts
Before you get started, familiarize yourself with the following concepts:
- Plug-in
An independent module running in the Hiview process. A plugin is delivered with the Hiview binary file to implement maintenance and fault management functions independently. Plug-ins can be disassembled independently during compilation, and can be hosted on the platform during running and dynamically configured.
- Pipeline
An ordered set of event processing plugins. Events entering the pipeline are processed by plugins on the pipeline in sequence.
- Event source
A special plugin that can produce events. Different from common plugins, a special plugin can be bound to a pipeline, and can produce events and distribute them to the pipeline.
- Pipeline group
A group of pipelines configured on the same event source.
### Working Principles
Hiview supports plugin development on the plugin management platform and provides the required plugin development capabilities. You can add plugins to the Hiview platform to implement HiSysEvent event processing. Before you get started, you're expected to have a basic understanding of plugin working principles.
#### Plug-in Registration
A plugin can be registered in any of the following modes.
| Mode | Description |
| ------------------ | ------------------------------------------------------------ |
| Static registration | Use the **REGISTER(xxx);** macro to register the plugin. Such a plugin cannot be unloaded.|
| Proxy registration | Use the **REGISTER_PROXY(xxx);** macro to register the plugin. Such a plugin is not loaded upon startup and can be loaded and unloaded dynamically during system running.|
| Proxy registration and loading upon startup| Use the **REGISTER_PROXY_WITH_LOADED(xxx);** macro to register the plugin. Such a plugin is loaded upon startup and can be unloaded and loaded dynamically during system running.|
#### Plug-in Event-Driven Modes
There are two event-driven modes available for plugins: pipeline-driven and subscription-driven. The differences are as follows:
- Pipeline-driven plugins need to be configured on the pipeline. After an event is distributed from an event source to the pipeline, the event traverses the plugins configured on the pipeline in sequence for processing.
- Subscription-driven plugins do not need to be configured on the pipeline. However, a listener needs to be registered with the Hiview platform upon plugin startup, and the plugin needs to implement the event listener function.
#### Plug-in Loading
Depending on your service demand, you can compile all or some plugins into the Hiview binary file.
Multiple plugins can be built into an independent plugin package and preset in the system as an independent **.so** file. One **.so** file corresponds to one **plugin_config** file. For example, **libxxx.z.so** corresponds to the** xxx_plugin_config** file. When the Hiview process starts, it scans for the plugin package (**.so** file) and the corresponding configuration file and loads the plugins in the plugin package.
The plugin package is described as follows:
1. The plugin package runs on the plugin management platform as an independent entity. The plugins, pipelines, or event sources in it provide the same functions as the plugins in the Hiview binary.
2. Plug-ins in the plugin package can be inserted into the Hiview binary pipeline.
3. Subscribers, wherever they are located, can receive events sent by the platform based on the subscription rules.
## Plug-in Development Guide
### When to Use
You can deploy a plugin on the Hiview platform if you want to perform specific service processing on the HiSysEvent events distributed from the event source. The following table describes the APIs used for plugin development.
### Available APIs
The following table lists the APIs related to plugin development. For details about the APIs, see the API Reference.
Table 1 Description of Plugin APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| virtual void OnLoad() | Loads plugins. After plugins are loaded, you can call this API to initialize data.|
| virtual void OnUnload() | Unloads plugins. Before plugins are unloaded, you can call this API to reclaim data. |
| virtual bool ReadyToLoad() | Checks whether the current plugin can be loaded when the Hiview starts plugin loading. |
| virtual bool OnEvent(std::shared_ptr\<Event\>& event) | Implements event processing. You can call this API to receive events distributed by the pipeline or platform perform service processing.|
| virtual bool CanProcessEvent(std::shared_ptr\<Event\> event) | Checks whether an event can traverse backward throughout the entire pipeline. This function takes effect only when the plugin is the first one in the pipeline.|
| HiviewContext* GetHiviewContext() | Obtains the context of the Hiview plugin management platform. |
**Table 2** Description of Event APIs
| API | Description |
| ---------------------- | ---------------------------- |
| domain_ | Event domain. |
| eventName_ | Event name. |
| happenTime_ | Time when an event occurs. |
| jsonExtraInfo_ | Event data in JSON format. |
| bool IsPipelineEvent() | Whether an event is a pipeline event. |
| bool HasFinish() | Whether an event can continue to traverse backward.|
### How to Develop
1. Define a service plugin class, namely, **PluginExample**, which inherits from the **Plugin** class.
```c++
#include "event.h"
#include "plugin.h"
class PluginExample : public Plugin {
public:
bool OnEvent(std::shared_ptr<Event>& event) override;
void OnLoad() override;
void OnUnload() override;
};
```
2. In the plugin class implementation code, register the plugin and overwrite the corresponding functions based on the service requirements.
```c++
#include "plugin_factory.h"
// Register the plugin in static registration mode.
REGISTER(PluginExample);
void PluginExample::OnLoad()
{
... // Initialize plugin resources while the plugin is loaded.
printf("PluginExample OnLoad \n");
}
void PluginExample::OnUnload()
{
... // Release plugin resources while the plugin is unloaded.
printf("PluginExample OnUnload \n");
}
bool PluginExample::OnEvent(std::shared_ptr<Event>& event)
{
... // Perform specific service processing on the event using the event processing function.
printf("PluginExample OnEvent \n");
// If the plugin focuses only on events of a certain domain, log only the events of this domain.
if (event->domain_ == "TEST_DOMAIN") {
printf("The event data received is %s \n", event->jsonExtraInfo_);
return true;
}
return false;
}
```
3. Configure the plugin in the **plugin_build.json** file and compile the plugin with the Hiview binary file.
```json
{
"plugins": {
"PluginExample": {
"path": "plugins/PluginExample",
"name": "PluginExample"
}
},
"rules": [
{
"info": {
"loadorder": {
"PluginExample": {
"loadtime": 0
}
},
"pipelines": {
"SysEventPipeline": [
PluginExample
]
}
}
}
]
}
```
## Reference
For more information about the source code and usage of HiSysEvent, access the Hiview code repository(https://gitee.com/openharmony/hiviewdfx_hiview).
...@@ -12,6 +12,7 @@ The DFX subsystem provides the following functions: ...@@ -12,6 +12,7 @@ The DFX subsystem provides the following functions:
- HiChecker: implements defect scanning. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). - HiChecker: implements defect scanning. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
- HiDumper: exports system information. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). - HiDumper: exports system information. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
- FaultLogger: implements crash detection. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\). - FaultLogger: implements crash detection. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
- Hiview: implements device maintenance across different platforms. It is applicable to standard-system devices \(reference memory ≥ 128 MiB\).
## Basic Concepts<a name="section5635178134811"></a> ## Basic Concepts<a name="section5635178134811"></a>
......
...@@ -8,3 +8,4 @@ ...@@ -8,3 +8,4 @@
- **[HiSysEvent Development](subsys-dfx-hisysevent.md)** - **[HiSysEvent Development](subsys-dfx-hisysevent.md)**
- **[HiDumper Development](subsys-dfx-hidumper.md)** - **[HiDumper Development](subsys-dfx-hidumper.md)**
- **[HiChecker Development](subsys-dfx-hichecker.md)** - **[HiChecker Development](subsys-dfx-hichecker.md)**
- **[Hiview Development](subsys-dfx-hiview.md)**
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
在工程中,通过 "$r('app.type.name')" 的形式引用应用资源。app代表是应用内resources目录中定义的资源;type 代表资源类型(或资源的存放位置),可以取 color、float、string、plural和media,name代表资源命名,由开发者定义资源时确定。 在工程中,通过 "$r('app.type.name')" 的形式引用应用资源。app代表是应用内resources目录中定义的资源;type 代表资源类型(或资源的存放位置),可以取 color、float、string、plural和media,name代表资源命名,由开发者定义资源时确定。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 可以查看[声明式开发范式资源访问](../../ui/ts-application-resource-access.md),了解资源访问的更多细节。 > - 可以查看[声明式开发范式资源访问](../../ui/ts-resource-access.md),了解资源访问的更多细节。
> >
> - 类Web开发范式的资源文件路径及资源限定词的使用与声明式范式不同,详情请参考[类Web开发范式资源限定与访问](../../ui/js-framework-resource-restriction.md)及[类Web开发范式文件组织](../../ui/js-framework-file.md)。 > - 类Web开发范式的资源文件路径及资源限定词的使用与声明式范式不同,详情请参考[类Web开发范式资源限定与访问](../../ui/js-framework-resource-restriction.md)及[类Web开发范式文件组织](../../ui/js-framework-file.md)。
......
...@@ -104,7 +104,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ...@@ -104,7 +104,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
授予应用user grant权限,使用Promise方式异步返回结果。 授予应用user grant权限,使用Promise方式异步返回结果。
此接口为系统接口,三方应用不支持调用 此接口为系统接口。
**需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS **需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS
...@@ -142,7 +142,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ...@@ -142,7 +142,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
授予应用user grant权限,使用callback回调异步返回结果。 授予应用user grant权限,使用callback回调异步返回结果。
此接口为系统接口,三方应用不支持调用 此接口为系统接口。
**需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS **需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS
...@@ -178,7 +178,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ...@@ -178,7 +178,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
撤销应用user grant权限,使用Promise方式异步返回结果。 撤销应用user grant权限,使用Promise方式异步返回结果。
此接口为系统接口,三方应用不支持调用 此接口为系统接口。
**需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
...@@ -216,7 +216,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ...@@ -216,7 +216,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
撤销应用user grant权限,使用callback回调异步返回结果。 撤销应用user grant权限,使用callback回调异步返回结果。
此接口为系统接口,三方应用不支持调用 此接口为系统接口。
**需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
...@@ -252,7 +252,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise&lt;number&g ...@@ -252,7 +252,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise&lt;number&g
获取指定应用的指定权限的flag,使用Promise方式异步返回结果。 获取指定应用的指定权限的flag,使用Promise方式异步返回结果。
此接口为系统接口,三方应用不支持调用 此接口为系统接口。
**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS or ohos.permission.GRANT_SENSITIVE_PERMISSIONS or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS or ohos.permission.GRANT_SENSITIVE_PERMISSIONS or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
......
...@@ -25,9 +25,9 @@ abilitymanager.getAbilityRunningInfos((err,data) => { ...@@ -25,9 +25,9 @@ abilitymanager.getAbilityRunningInfos((err,data) => {
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | 是 | 否 | Ability匹配信息 | | ability | ElementName | 是 | 否 | Ability匹配信息 |
| pid | number | 是 | 否 | 进程ID。 | | pid | number | 是 | 否 | 进程ID。 |
| uid | number | 是 | 否 | 用户ID。 | | uid | number | 是 | 否 | 用户ID。 |
| processName | string | 是 | 否 | 进程名称。 | | processName | string | 是 | 否 | 进程名称。 |
| startTime | number | 是 | 否 | Ability启动时间。 | | startTime | number | 是 | 否 | Ability启动时间。 |
| abilityState | [abilityManager.AbilityState](js-apis-abilityManager.md#abilityState) | 是 | 否 | Ability状态。 | | abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | 是 | 否 | Ability状态。 |
\ No newline at end of file \ No newline at end of file
...@@ -1952,11 +1952,11 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac ...@@ -1952,11 +1952,11 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------- | ---- | ----------------- | | -------------------- | -------------- | ----- | ---------------- |
| authType | string | 是 | 令牌的鉴权类型。 | | authType | string | 是 | 令牌的鉴权类型。 |
| token | string | 是 | 令牌的取值。 | | token | string | 是 | 令牌的取值。 |
| account | AppAccountInfo | 否 | 令牌所属的帐号信息。| | account<sup>9+</sup> | AppAccountInfo | 否 | 令牌所属的帐号信息。|
## AuthenticatorInfo<sup>8+</sup> ## AuthenticatorInfo<sup>8+</sup>
......
...@@ -74,31 +74,30 @@ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\<Audi ...@@ -74,31 +74,30 @@ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\<Audi
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
audio.createAudioRenderer(audioRendererOptions,(err, data) => { audio.createAudioRenderer(audioRendererOptions,(err, data) => {
if (err) { if (err) {
console.error(`AudioRenderer Created : Error: ${err.message}`); console.error(`AudioRenderer Created: Error: ${err.message}`);
} } else {
else { console.info('AudioRenderer Created: Success: SUCCESS');
console.info('AudioRenderer Created : Success : SUCCESS'); let audioRenderer = data;
let audioRenderer = data; }
}
}); });
``` ```
...@@ -128,29 +127,29 @@ createAudioRenderer(options: AudioRendererOptions): Promise<AudioRenderer\> ...@@ -128,29 +127,29 @@ createAudioRenderer(options: AudioRendererOptions): Promise<AudioRenderer\>
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
var audioRenderer; var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => { audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data; audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS');
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created : ERROR : '+err.message); console.info('AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ' + err.message);
}); });
``` ```
...@@ -174,30 +173,29 @@ createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback<Audio ...@@ -174,30 +173,29 @@ createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback<Audio
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2, channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioCapturerInfo = { var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC, source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 1 capturerFlags: 0
} }
var audioCapturerOptions = { var audioCapturerOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo capturerInfo: audioCapturerInfo
} }
audio.createAudioCapturer(audioCapturerOptions,(err, data) => { audio.createAudioCapturer(audioCapturerOptions, (err, data) => {
if (err) { if (err) {
console.error(`AudioCapturer Created : Error: ${err.message}`); console.error(`AudioCapturer Created : Error: ${err.message}`);
} } else {
else { console.info('AudioCapturer Created : Success : SUCCESS');
console.info('AudioCapturer Created : Success : SUCCESS'); let audioCapturer = data;
let audioCapturer = data; }
}
}); });
``` ```
...@@ -227,28 +225,28 @@ createAudioCapturer(options: AudioCapturerOptions): Promise<AudioCapturer\> ...@@ -227,28 +225,28 @@ createAudioCapturer(options: AudioCapturerOptions): Promise<AudioCapturer\>
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2, channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioCapturerInfo = { var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC, source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 1 capturerFlags: 0
} }
var audioCapturerOptions = { var audioCapturerOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo capturerInfo: audioCapturerInfo
} }
var audioCapturer; var audioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) => { audio.createAudioCapturer(audioCapturerOptions).then((data) => {
audioCapturer = data; audioCapturer = data;
console.info('AudioCapturer Created : Success : Stream Type: SUCCESS'); console.info('AudioCapturer Created : Success : Stream Type: SUCCESS');
}).catch((err) => { }).catch((err) => {
console.info('AudioCapturer Created : ERROR : '+err.message); console.info('AudioCapturer Created : ERROR : ' + err.message);
}); });
``` ```
...@@ -719,11 +717,11 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l ...@@ -719,11 +717,11 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l
``` ```
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => {
if (err) { if (err) {
console.error('Failed to set the volume. ${err.message}'); console.error('Failed to set the volume. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate a successful volume setting.'); console.log('Callback invoked to indicate a successful volume setting.');
}); });
``` ```
...@@ -754,7 +752,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt; ...@@ -754,7 +752,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt;
``` ```
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
console.log('Promise returned to indicate a successful volume setting.'); console.log('Promise returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -777,11 +775,11 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;): v ...@@ -777,11 +775,11 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;): v
``` ```
audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the volume. ${err.message}'); console.error('Failed to obtain the volume. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the volume is obtained.'); console.log('Callback invoked to indicate that the volume is obtained.');
}); });
``` ```
...@@ -809,7 +807,7 @@ getVolume(volumeType: AudioVolumeType): Promise&lt;number&gt; ...@@ -809,7 +807,7 @@ getVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
``` ```
audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => {
console.log('Promise returned to indicate that the volume is obtained.' + value); console.log('Promise returned to indicate that the volume is obtained.' + value);
}); });
``` ```
...@@ -832,11 +830,11 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;) ...@@ -832,11 +830,11 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;)
``` ```
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the minimum volume. ${err.message}'); console.error('Failed to obtain the minimum volume. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the minimum volume is obtained.' + value); console.log('Callback invoked to indicate that the minimum volume is obtained.' + value);
}); });
``` ```
...@@ -864,7 +862,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise&lt;number&gt; ...@@ -864,7 +862,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
``` ```
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => {
console.log('Promised returned to indicate that the minimum volume is obtained.' + value); console.log('Promised returned to indicate that the minimum volume is obtained.' + value);
}); });
``` ```
...@@ -887,11 +885,11 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;) ...@@ -887,11 +885,11 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;)
``` ```
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the maximum volume. ${err.message}'); console.error('Failed to obtain the maximum volume. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the maximum volume is obtained.' + value); console.log('Callback invoked to indicate that the maximum volume is obtained.' + value);
}); });
``` ```
...@@ -919,7 +917,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise&lt;number&gt; ...@@ -919,7 +917,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
``` ```
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => {
console.log('Promised returned to indicate that the maximum volume is obtained.'); console.log('Promised returned to indicate that the maximum volume is obtained.');
}); });
``` ```
...@@ -945,11 +943,11 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback&lt;void ...@@ -945,11 +943,11 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback&lt;void
``` ```
audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
if (err) { if (err) {
console.error('Failed to mute the stream. ${err.message}'); console.error('Failed to mute the stream. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the stream is muted.'); console.log('Callback invoked to indicate that the stream is muted.');
}); });
``` ```
...@@ -981,7 +979,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise&lt;void&gt; ...@@ -981,7 +979,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise&lt;void&gt;
``` ```
audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
console.log('Promise returned to indicate that the stream is muted.'); console.log('Promise returned to indicate that the stream is muted.');
}); });
``` ```
...@@ -1005,11 +1003,11 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): voi ...@@ -1005,11 +1003,11 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): voi
``` ```
audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the mute status. ${err.message}'); console.error('Failed to obtain the mute status. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the mute status of the stream is obtained.' + value); console.log('Callback invoked to indicate that the mute status of the stream is obtained.' + value);
}); });
``` ```
...@@ -1038,7 +1036,7 @@ isMute(volumeType: AudioVolumeType): Promise&lt;boolean&gt; ...@@ -1038,7 +1036,7 @@ isMute(volumeType: AudioVolumeType): Promise&lt;boolean&gt;
``` ```
audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => {
console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value); console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value);
}); });
``` ```
...@@ -1061,11 +1059,11 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): v ...@@ -1061,11 +1059,11 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): v
``` ```
audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the active status of the stream. ${err.message}'); console.error('Failed to obtain the active status of the stream. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the active status of the stream is obtained.' + value); console.log('Callback invoked to indicate that the active status of the stream is obtained.' + value);
}); });
``` ```
...@@ -1093,7 +1091,7 @@ isActive(volumeType: AudioVolumeType): Promise&lt;boolean&gt; ...@@ -1093,7 +1091,7 @@ isActive(volumeType: AudioVolumeType): Promise&lt;boolean&gt;
``` ```
audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => {
console.log('Promise returned to indicate that the active status of the stream is obtained.' + value); console.log('Promise returned to indicate that the active status of the stream is obtained.' + value);
}); });
``` ```
...@@ -1118,11 +1116,11 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void ...@@ -1118,11 +1116,11 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void
``` ```
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => {
if (err) { if (err) {
console.error('Failed to set the ringer mode.​ ${err.message}'); console.error('Failed to set the ringer mode.​ ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate a successful setting of the ringer mode.'); console.log('Callback invoked to indicate a successful setting of the ringer mode.');
}); });
``` ```
...@@ -1152,7 +1150,7 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt; ...@@ -1152,7 +1150,7 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt;
``` ```
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => {
console.log('Promise returned to indicate a successful setting of the ringer mode.'); console.log('Promise returned to indicate a successful setting of the ringer mode.');
}); });
``` ```
...@@ -1175,11 +1173,11 @@ getRingerMode(callback: AsyncCallback&lt;AudioRingMode&gt;): void ...@@ -1175,11 +1173,11 @@ getRingerMode(callback: AsyncCallback&lt;AudioRingMode&gt;): void
``` ```
audioManager.getRingerMode((err, value) => { audioManager.getRingerMode((err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the ringer mode.​ ${err.message}'); console.error('Failed to obtain the ringer mode.​ ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the ringer mode is obtained.' + value); console.log('Callback invoked to indicate that the ringer mode is obtained.' + value);
}); });
``` ```
...@@ -1202,7 +1200,7 @@ getRingerMode(): Promise&lt;AudioRingMode&gt; ...@@ -1202,7 +1200,7 @@ getRingerMode(): Promise&lt;AudioRingMode&gt;
``` ```
audioManager.getRingerMode().then((value) => { audioManager.getRingerMode().then((value) => {
console.log('Promise returned to indicate that the ringer mode is obtained.' + value); console.log('Promise returned to indicate that the ringer mode is obtained.' + value);
}); });
``` ```
...@@ -1230,11 +1228,11 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback&lt;void&gt ...@@ -1230,11 +1228,11 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback&lt;void&gt
``` ```
audioManager.setAudioParameter('key_example', 'value_example', (err) => { audioManager.setAudioParameter('key_example', 'value_example', (err) => {
if (err) { if (err) {
console.error('Failed to set the audio parameter. ${err.message}'); console.error('Failed to set the audio parameter. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate a successful setting of the audio parameter.'); console.log('Callback invoked to indicate a successful setting of the audio parameter.');
}); });
``` ```
...@@ -1267,7 +1265,7 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt; ...@@ -1267,7 +1265,7 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt;
``` ```
audioManager.setAudioParameter('key_example', 'value_example').then(() => { audioManager.setAudioParameter('key_example', 'value_example').then(() => {
console.log('Promise returned to indicate a successful setting of the audio parameter.'); console.log('Promise returned to indicate a successful setting of the audio parameter.');
}); });
``` ```
...@@ -1292,11 +1290,11 @@ getAudioParameter(key: string, callback: AsyncCallback&lt;string&gt;): void ...@@ -1292,11 +1290,11 @@ getAudioParameter(key: string, callback: AsyncCallback&lt;string&gt;): void
``` ```
audioManager.getAudioParameter('key_example', (err, value) => { audioManager.getAudioParameter('key_example', (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the value of the audio parameter. ${err.message}'); console.error('Failed to obtain the value of the audio parameter. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the value of the audio parameter is obtained.' + value); console.log('Callback invoked to indicate that the value of the audio parameter is obtained.' + value);
}); });
``` ```
...@@ -1326,7 +1324,7 @@ getAudioParameter(key: string): Promise&lt;string&gt; ...@@ -1326,7 +1324,7 @@ getAudioParameter(key: string): Promise&lt;string&gt;
``` ```
audioManager.getAudioParameter('key_example').then((value) => { audioManager.getAudioParameter('key_example').then((value) => {
console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value); console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value);
}); });
``` ```
...@@ -1348,11 +1346,11 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback&lt;AudioDeviceDescrip ...@@ -1348,11 +1346,11 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback&lt;AudioDeviceDescrip
**示例:** **示例:**
``` ```
audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the device list. ${err.message}'); console.error('Failed to obtain the device list. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the device list is obtained.'); console.log('Callback invoked to indicate that the device list is obtained.');
}); });
``` ```
...@@ -1380,7 +1378,7 @@ getDevices(deviceFlag: DeviceFlag): Promise&lt;AudioDeviceDescriptors&gt; ...@@ -1380,7 +1378,7 @@ getDevices(deviceFlag: DeviceFlag): Promise&lt;AudioDeviceDescriptors&gt;
``` ```
audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
console.log('Promise returned to indicate that the device list is obtained.'); console.log('Promise returned to indicate that the device list is obtained.');
}); });
``` ```
...@@ -1404,11 +1402,11 @@ setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCa ...@@ -1404,11 +1402,11 @@ setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCa
``` ```
audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => {
if (err) { if (err) {
console.error('Failed to set the active status of the device. ${err.message}'); console.error('Failed to set the active status of the device. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the device is set to the active status.'); console.log('Callback invoked to indicate that the device is set to the active status.');
}); });
``` ```
...@@ -1438,7 +1436,7 @@ setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise&lt;void& ...@@ -1438,7 +1436,7 @@ setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise&lt;void&
``` ```
audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => {
console.log('Promise returned to indicate that the device is set to the active status.'); console.log('Promise returned to indicate that the device is set to the active status.');
}); });
``` ```
...@@ -1461,11 +1459,11 @@ isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback&lt;boolean& ...@@ -1461,11 +1459,11 @@ isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback&lt;boolean&
``` ```
audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the active status of the device. ${err.message}'); console.error('Failed to obtain the active status of the device. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the active status of the device is obtained.'); console.log('Callback invoked to indicate that the active status of the device is obtained.');
}); });
``` ```
...@@ -1494,7 +1492,7 @@ isDeviceActive(deviceType: ActiveDeviceType): Promise&lt;boolean&gt; ...@@ -1494,7 +1492,7 @@ isDeviceActive(deviceType: ActiveDeviceType): Promise&lt;boolean&gt;
``` ```
audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => {
console.log('Promise returned to indicate that the active status of the device is obtained.' + value); console.log('Promise returned to indicate that the active status of the device is obtained.' + value);
}); });
``` ```
...@@ -1519,11 +1517,11 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void ...@@ -1519,11 +1517,11 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void
``` ```
audioManager.setMicrophoneMute(true, (err) => { audioManager.setMicrophoneMute(true, (err) => {
if (err) { if (err) {
console.error('Failed to mute the microphone. ${err.message}'); console.error('Failed to mute the microphone. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the microphone is muted.'); console.log('Callback invoked to indicate that the microphone is muted.');
}); });
``` ```
...@@ -1553,7 +1551,7 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt; ...@@ -1553,7 +1551,7 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt;
``` ```
audioManager.setMicrophoneMute(true).then(() => { audioManager.setMicrophoneMute(true).then(() => {
console.log('Promise returned to indicate that the microphone is muted.'); console.log('Promise returned to indicate that the microphone is muted.');
}); });
``` ```
...@@ -1577,11 +1575,11 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -1577,11 +1575,11 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void
``` ```
audioManager.isMicrophoneMute((err, value) => { audioManager.isMicrophoneMute((err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the mute status of the microphone. ${err.message}'); console.error('Failed to obtain the mute status of the microphone. ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the mute status of the microphone is obtained.' + value); console.log('Callback invoked to indicate that the mute status of the microphone is obtained.' + value);
}); });
``` ```
...@@ -1606,7 +1604,7 @@ isMicrophoneMute(): Promise&lt;boolean&gt; ...@@ -1606,7 +1604,7 @@ isMicrophoneMute(): Promise&lt;boolean&gt;
``` ```
audioManager.isMicrophoneMute().then((value) => { audioManager.isMicrophoneMute().then((value) => {
console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value); console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value);
}); });
``` ```
...@@ -1633,9 +1631,9 @@ on(type: 'volumeChange', callback: Callback\<VolumeEvent>): void ...@@ -1633,9 +1631,9 @@ on(type: 'volumeChange', callback: Callback\<VolumeEvent>): void
``` ```
audioManager.on('volumeChange', (volumeEvent) => { audioManager.on('volumeChange', (volumeEvent) => {
console.log('VolumeType of stream: ' + volumeEvent.volumeType); console.log('VolumeType of stream: ' + volumeEvent.volumeType);
console.log('Volume level: ' + volumeEvent.volume); console.log('Volume level: ' + volumeEvent.volume);
console.log('Whether to updateUI: ' + volumeEvent.updateUi); console.log('Whether to updateUI: ' + volumeEvent.updateUi);
}); });
``` ```
...@@ -1660,7 +1658,7 @@ on(type: 'ringerModeChange', callback: Callback\<AudioRingMode>): void ...@@ -1660,7 +1658,7 @@ on(type: 'ringerModeChange', callback: Callback\<AudioRingMode>): void
``` ```
audioManager.on('ringerModeChange', (ringerMode) => { audioManager.on('ringerModeChange', (ringerMode) => {
console.log('Updated ringermode: ' + ringerMode); console.log('Updated ringermode: ' + ringerMode);
}); });
``` ```
...@@ -1683,10 +1681,10 @@ on(type: 'deviceChange', callback: Callback<DeviceChangeAction\>): void ...@@ -1683,10 +1681,10 @@ on(type: 'deviceChange', callback: Callback<DeviceChangeAction\>): void
``` ```
audioManager.on('deviceChange', (deviceChanged) => { audioManager.on('deviceChange', (deviceChanged) => {
console.info("device change type : " + deviceChanged.type); console.info("device change type : " + deviceChanged.type);
console.info("device descriptor size : " + deviceChanged.deviceDescriptors.length); console.info("device descriptor size : " + deviceChanged.deviceDescriptors.length);
console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceRole); console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceRole);
console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceType); console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceType);
}); });
``` ```
...@@ -1709,7 +1707,7 @@ off(type: 'deviceChange', callback?: Callback<DeviceChangeAction\>): void ...@@ -1709,7 +1707,7 @@ off(type: 'deviceChange', callback?: Callback<DeviceChangeAction\>): void
``` ```
audioManager.off('deviceChange', (deviceChanged) => { audioManager.off('deviceChange', (deviceChanged) => {
console.log("Should be no callback."); console.log("Should be no callback.");
}); });
``` ```
...@@ -1733,19 +1731,19 @@ on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\<InterruptAc ...@@ -1733,19 +1731,19 @@ on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\<InterruptAc
``` ```
var interAudioInterrupt = { var interAudioInterrupt = {
streamUsage:2, streamUsage:2,
contentType:0, contentType:0,
pauseWhenDucked:true pauseWhenDucked:true
}; };
audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => {
if (InterruptAction.actionType === 0) { if (InterruptAction.actionType === 0) {
console.log("An event to gain the audio focus starts."); console.log("An event to gain the audio focus starts.");
console.log("Focus gain event:" + JSON.stringify(InterruptAction)); console.log("Focus gain event:" + JSON.stringify(InterruptAction));
} }
if (InterruptAction.actionType === 1) { if (InterruptAction.actionType === 1) {
console.log("An audio interruption event starts."); console.log("An audio interruption event starts.");
console.log("Audio interruption event:" + JSON.stringify(InterruptAction)); console.log("Audio interruption event:" + JSON.stringify(InterruptAction));
} }
}); });
``` ```
...@@ -1769,15 +1767,15 @@ off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\<Interrupt ...@@ -1769,15 +1767,15 @@ off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\<Interrupt
``` ```
var interAudioInterrupt = { var interAudioInterrupt = {
streamUsage:2, streamUsage:2,
contentType:0, contentType:0,
pauseWhenDucked:true pauseWhenDucked:true
}; };
audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => {
if (InterruptAction.actionType === 0) { if (InterruptAction.actionType === 0) {
console.log("An event to release the audio focus starts."); console.log("An event to release the audio focus starts.");
console.log("Focus release event:" + JSON.stringify(InterruptAction)); console.log("Focus release event:" + JSON.stringify(InterruptAction));
} }
}); });
``` ```
...@@ -1802,11 +1800,11 @@ setAudioScene\(scene: AudioScene, callback: AsyncCallback<void\>\): void ...@@ -1802,11 +1800,11 @@ setAudioScene\(scene: AudioScene, callback: AsyncCallback<void\>\): void
``` ```
audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => {
if (err) { if (err) {
console.error('Failed to set the audio scene mode.​ ${err.message}'); console.error('Failed to set the audio scene mode.​ ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate a successful setting of the audio scene mode.'); console.log('Callback invoked to indicate a successful setting of the audio scene mode.');
}); });
``` ```
...@@ -1836,9 +1834,9 @@ setAudioScene\(scene: AudioScene\): Promise<void\> ...@@ -1836,9 +1834,9 @@ setAudioScene\(scene: AudioScene\): Promise<void\>
``` ```
audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => {
console.log('Promise returned to indicate a successful setting of the audio scene mode.'); console.log('Promise returned to indicate a successful setting of the audio scene mode.');
}).catch ((err) => { }).catch ((err) => {
console.log('Failed to set the audio scene mode'); console.log('Failed to set the audio scene mode');
}); });
``` ```
...@@ -1860,11 +1858,11 @@ getAudioScene\(callback: AsyncCallback<AudioScene\>\): void ...@@ -1860,11 +1858,11 @@ getAudioScene\(callback: AsyncCallback<AudioScene\>\): void
``` ```
audioManager.getAudioScene((err, value) => { audioManager.getAudioScene((err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the audio scene mode.​ ${err.message}'); console.error('Failed to obtain the audio scene mode.​ ${err.message}');
return; return;
} }
console.log('Callback invoked to indicate that the audio scene mode is obtained.' + value); console.log('Callback invoked to indicate that the audio scene mode is obtained.' + value);
}); });
``` ```
...@@ -1887,9 +1885,9 @@ getAudioScene\(\): Promise<AudioScene\> ...@@ -1887,9 +1885,9 @@ getAudioScene\(\): Promise<AudioScene\>
``` ```
audioManager.getAudioScene().then((value) => { audioManager.getAudioScene().then((value) => {
console.log('Promise returned to indicate that the audio scene mode is obtained.' + value); console.log('Promise returned to indicate that the audio scene mode is obtained.' + value);
}).catch ((err) => { }).catch ((err) => {
console.log('Failed to obtain the audio scene mode'); console.log('Failed to obtain the audio scene mode');
}); });
``` ```
...@@ -1914,36 +1912,34 @@ getCurrentAudioRendererInfoArray(callback: AsyncCallback&lt;AudioRendererChangeI ...@@ -1914,36 +1912,34 @@ getCurrentAudioRendererInfoArray(callback: AsyncCallback&lt;AudioRendererChangeI
**示例:** **示例:**
``` ```
audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => {
console.info('[GET_RENDERER_STATE_1_CALLBACK] **** Get Callback Called ****'); console.info('[GET_RENDERER_STATE_1_CALLBACK] **** Get Callback Called ****');
if (err) { if (err) {
console.log('getCurrentAudioRendererInfoArray :ERROR: '+err.message); console.log('getCurrentAudioRendererInfoArray :ERROR: '+ err.message);
resultFlag = false; resultFlag = false;
} } else {
else { if (AudioRendererChangeInfoArray != null) {
if (AudioRendererChangeInfoArray !=null) { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
for (let i=0;i<AudioRendererChangeInfoArray.length;i++) { AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; console.info('StreamId for' + i + 'is:' + AudioRendererChangeInfo.streamId);
console.info('StreamId for '+i+' is:'+AudioRendererChangeInfo.streamId); console.info('ClientUid for' + i + 'is:' + AudioRendererChangeInfo.clientUid);
console.info('ClientUid for '+i+' is:'+AudioRendererChangeInfo.clientUid); console.info('Content' + i + 'is:' + AudioRendererChangeInfo.rendererInfo.content);
console.info('Content '+i+' is:'+AudioRendererChangeInfo.rendererInfo.content); console.info('Stream'+ i + 'is:' + AudioRendererChangeInfo.rendererInfo.usage);
console.info('Stream'+i+' is:'+AudioRendererChangeInfo.rendererInfo.usage); console.info('Flag'+ i +' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
console.info('Flag'+i+' is:'+AudioRendererChangeInfo.rendererInfo.rendererFlags); console.info('State for' + i +' is:' + AudioRendererChangeInfo.rendererState);
console.info('State for '+i+' is:'+AudioRendererChangeInfo.rendererState); var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; console.info('Id:' + i +':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
for (let j=0;j<AudioRendererChangeInfo.deviceDescriptors.length; j++) { console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
console.info('Id:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].id); console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
console.info('Type:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].deviceType); console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
console.info('Role:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
console.info('Name:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].name); console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
console.info('Address:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].address); console.info('ChannelCount' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
console.info('SampleRates:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
console.info('ChannelCount'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
console.info('ChannelMask:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
}
}
} }
}
} }
}
}); });
``` ```
...@@ -1964,33 +1960,32 @@ getCurrentAudioRendererInfoArray(): Promise&lt;AudioRendererChangeInfoArray&gt; ...@@ -1964,33 +1960,32 @@ getCurrentAudioRendererInfoArray(): Promise&lt;AudioRendererChangeInfoArray&gt;
**示例:** **示例:**
``` ```
await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) {
console.info('[GET_RENDERER_STATE_3_PROMISE] ######### Get Promise is called ##########'); console.info('[GET_RENDERER_STATE_3_PROMISE] ######### Get Promise is called ##########');
if (AudioRendererChangeInfoArray!=null) { if (AudioRendererChangeInfoArray != null) {
for (let i=0;i<AudioRendererChangeInfoArray.length;i++) { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
console.info('StreamId for '+i+' is:'+AudioRendererChangeInfo.streamId); console.info('StreamId for ' + i +' is:' + AudioRendererChangeInfo.streamId);
console.info('ClientUid for '+i+' is:'+AudioRendererChangeInfo.clientUid); console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
console.info('Content '+i+' is:'+AudioRendererChangeInfo.rendererInfo.content); console.info('Content ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
console.info('Stream'+i+' is:'+AudioRendererChangeInfo.rendererInfo.usage); console.info('Stream' + i +' is:' + AudioRendererChangeInfo.rendererInfo.usage);
console.info('Flag'+i+' is:'+AudioRendererChangeInfo.rendererInfo.rendererFlags); console.info('Flag' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
console.info('State for '+i+' is:'+AudioRendererChangeInfo.rendererState); console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
for (let j=0;j<AudioRendererChangeInfo.deviceDescriptors.length; j++) { console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
console.info('Id:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].id); console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
console.info('Type:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].deviceType); console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
console.info('Role:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
console.info('Name:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].name); console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
console.info('Address:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].address); console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
console.info('SampleRates:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
console.info('ChannelCounts'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); console.info('ChannnelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
console.info('ChannnelMask:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); }
}
}
} }
}
}).catch((err) => { }).catch((err) => {
console.log('getCurrentAudioRendererInfoArray :ERROR: '+err.message); console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message);
resultFlag = false; resultFlag = false;
}); });
``` ```
...@@ -2011,34 +2006,32 @@ getCurrentAudioCapturerInfoArray(callback: AsyncCallback&lt;AudioCapturerChangeI ...@@ -2011,34 +2006,32 @@ getCurrentAudioCapturerInfoArray(callback: AsyncCallback&lt;AudioCapturerChangeI
**示例:** **示例:**
``` ```
audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => {
console.info('[GET_CAPTURER_STATE_1_CALLBACK] **** Get Callback Called ****'); console.info('[GET_CAPTURER_STATE_1_CALLBACK] **** Get Callback Called ****');
if (err) { if (err) {
console.log('getCurrentAudioCapturerInfoArray :ERROR: '+err.message); console.log('getCurrentAudioCapturerInfoArray :ERROR: '+err.message);
resultFlag = false; resultFlag = false;
} } else {
else { if (AudioCapturerChangeInfoArray != null) {
if (AudioCapturerChangeInfoArray !=null) { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
for (let i=0;i<AudioCapturerChangeInfoArray.length;i++) { console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
console.info('StreamId for '+i+'is:'+AudioCapturerChangeInfoArray[i].streamId); console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
console.info('ClientUid for '+i+'is:'+AudioCapturerChangeInfoArray[i].clientUid); console.info('Source for '+ i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
console.info('Source for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.source); console.info('Flag ' + i +'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
console.info('Flag '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
console.info('State for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerState); var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
for (let j=0;j<AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info('Id:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info('Type:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name);
console.info('Role:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
console.info('Name:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info('Address:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info('SampleRates:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
console.info('ChannelCounts'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info('ChannelMask:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
}
}
} }
}
} }
}
}); });
``` ```
...@@ -2059,31 +2052,30 @@ getCurrentAudioCapturerInfoArray(): Promise&lt;AudioCapturerChangeInfoArray&gt; ...@@ -2059,31 +2052,30 @@ getCurrentAudioCapturerInfoArray(): Promise&lt;AudioCapturerChangeInfoArray&gt;
**示例:** **示例:**
``` ```
await audioStreamManagerCB.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { await audioStreamManagerCB.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) {
console.info('AFCapturerChangeLog: [GET_CAP_STA_1_PR] **** Get Promise Called ****'); console.info('AFCapturerChangeLog: [GET_CAP_STA_1_PR] **** Get Promise Called ****');
if (AudioCapturerChangeInfoArray!=null) { if (AudioCapturerChangeInfoArray != null) {
for (let i=0;i<AudioCapturerChangeInfoArray.length;i++) { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
console.info('StreamId for '+i+'is:'+AudioCapturerChangeInfoArray[i].streamId); console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
console.info('ClientUid for '+i+'is:'+AudioCapturerChangeInfoArray[i].clientUid); console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
console.info('Source for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.source); console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
console.info('Flag '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
console.info('State for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerState); console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
for (let j=0;j<AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
console.info('Id:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info('Type:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info('Role:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name)
console.info('Name:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name) console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
console.info('Address:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info('SampleRates:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info('ChannelCounts'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
console.info('ChannelMask:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); }
}
}
} }
}
}).catch((err) => { }).catch((err) => {
console.log('getCurrentAudioCapturerInfoArray :ERROR: '+err.message); console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message);
resultFlag = false; resultFlag = false;
}); });
``` ```
...@@ -2105,28 +2097,27 @@ on(type: "audioRendererChange", callback: Callback&lt;AudioRendererChangeInfoArr ...@@ -2105,28 +2097,27 @@ on(type: "audioRendererChange", callback: Callback&lt;AudioRendererChangeInfoArr
**示例:** **示例:**
``` ```
audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => { audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
for (let i=0;i<AudioRendererChangeInfoArray.length;i++) { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
console.info('## RendererChange on is called for '+i+' ##'); console.info('## RendererChange on is called for ' + i + ' ##');
console.info('StreamId for '+i+' is:'+AudioRendererChangeInfo.streamId); console.info('StreamId for ' + i + ' is:' + AudioRendererChangeInfo.streamId);
console.info('ClientUid for '+i+' is:'+AudioRendererChangeInfo.clientUid); console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
console.info('Content for '+i+' is:'+AudioRendererChangeInfo.rendererInfo.content); console.info('Content for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
console.info('Stream for '+i+' is:'+AudioRendererChangeInfo.rendererInfo.usage); console.info('Stream for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.usage);
console.info('Flag '+i+' is:'+AudioRendererChangeInfo.rendererInfo.rendererFlags); console.info('Flag ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
console.info('State for '+i+' is:'+AudioRendererChangeInfo.rendererState); console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
for (let j=0;j<AudioRendererChangeInfo.deviceDescriptors.length; j++) { console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
console.info('Id:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].id); console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
console.info('Type:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].deviceType); console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
console.info('Role:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
console.info('Name:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].name); console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
console.info('Address:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].address); console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
console.info('SampleRates:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
console.info('ChannelCounts'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
console.info('ChannelMask:'+i+':'+AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
}
} }
}
}); });
``` ```
...@@ -2168,25 +2159,24 @@ on(type: "audioCapturerChange", callback: Callback&lt;AudioCapturerChangeInfoArr ...@@ -2168,25 +2159,24 @@ on(type: "audioCapturerChange", callback: Callback&lt;AudioCapturerChangeInfoArr
**示例:** **示例:**
``` ```
audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
for (let i=0;i<AudioCapturerChangeInfoArray.length;i++) { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
console.info(' ## CapChange on is called for element '+i+' ##'); console.info(' ## CapChange on is called for element ' + i + ' ##');
console.info('StreamId for '+i+'is:'+AudioCapturerChangeInfoArray[i].streamId); console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
console.info('ClientUid for '+i+'is:'+AudioCapturerChangeInfoArray[i].clientUid); console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
console.info('Source for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.source); console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
console.info('Flag '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
console.info('State for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerState); console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
for (let j=0;j<AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
console.info('Id:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info('Type:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info('Role:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name);
console.info('Name:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
console.info('Address:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info('SampleRates:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info('ChannelCounts'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
console.info('ChannelMask:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
}
} }
}
}); });
``` ```
...@@ -2232,15 +2222,15 @@ isAudioRendererLowLatencySupported(streaminfo: AudioStreamInfo, callback: Callba ...@@ -2232,15 +2222,15 @@ isAudioRendererLowLatencySupported(streaminfo: AudioStreamInfo, callback: Callba
var audioManager = audio.getAudioManager(); var audioManager = audio.getAudioManager();
var AudioStreamInfo = { var AudioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var streamManagerCB = audioManager.getStreamManager(); var streamManagerCB = audioManager.getStreamManager();
streamManagerCB.isAudioRendererLowLatencySupported(AudioStreamInfo, (result) => { streamManagerCB.isAudioRendererLowLatencySupported(AudioStreamInfo, (result) => {
console.info('isAudioRendererLowLatencySupported success var = ' + result); console.info('isAudioRendererLowLatencySupported success var = ' + result);
}); });
``` ```
...@@ -2270,10 +2260,10 @@ isAudioRendererLowLatencySupported(streaminfo: AudioStreamInfo): Promise&lt;bool ...@@ -2270,10 +2260,10 @@ isAudioRendererLowLatencySupported(streaminfo: AudioStreamInfo): Promise&lt;bool
var audioManager = audio.getAudioManager(); var audioManager = audio.getAudioManager();
var AudioStreamInfo = { var AudioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var streamManager = await audioManager.getStreamManager(); var streamManager = await audioManager.getStreamManager();
...@@ -2307,49 +2297,49 @@ import audio from '@ohos.multimedia.audio'; ...@@ -2307,49 +2297,49 @@ import audio from '@ohos.multimedia.audio';
var audioStreamManager; var audioStreamManager;
var audioStreamManagerCB; var audioStreamManagerCB;
var Tag = "AFCapLog : ";
await audioManager.getStreamManager().then(async function (data) { await audioManager.getStreamManager().then(async function (data) {
audioStreamManager = data; audioStreamManager = data;
console.info(Tag+'Get AudioStream Manager : Success '); console.info(Tag + 'Get AudioStream Manager : Success ');
}).catch((err) => { }).catch((err) => {
console.info(Tag+'Get AudioStream Manager : ERROR : '+err.message); console.info(Tag + 'Get AudioStream Manager : ERROR : ' + err.message);
}); });
audioManager.getStreamManager((err, data) => { audioManager.getStreamManager((err, data) => {
if (err) { if (err) {
console.error(Tag+'Get AudioStream Manager : ERROR : '+err.message); console.error(Tag + 'Get AudioStream Manager : ERROR : ' + err.message);
} } else {
else { audioStreamManagerCB = data;
audioStreamManagerCB = data; console.info(Tag + 'Get AudioStream Manager : Success ');
console.info(Tag+'Get AudioStream Manager : Success '); }
} });
});
audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => { audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
for (let i=0;i<AudioRendererChangeInfoArray.length;i++) { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
console.info(Tag+'## RendererChange on is called for '+i+' ##'); console.info(Tag+'## RendererChange on is called for ' + i + ' ##');
console.info(Tag+'StreamId for '+i+' is:'+AudioRendererChangeInfoArray[i].streamId); console.info(Tag+'StreamId for ' + i + 'is:' + AudioRendererChangeInfoArray[i].streamId);
console.info(Tag+'ClientUid for '+i+' is:'+AudioRendererChangeInfoArray[i].clientUid); console.info(Tag+'ClientUid for ' + i + 'is:' + AudioRendererChangeInfoArray[i].clientUid);
console.info(Tag+'Content for '+i+' is:'+AudioRendererChangeInfoArray[i].rendererInfo.content); console.info(Tag+'Content for ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererInfo.content);
console.info(Tag+'Stream for '+i+' is:'+AudioRendererChangeInfoArray[i].rendererInfo.usage); console.info(Tag+'Stream for ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererInfo.usage);
console.info(Tag+'Flag '+i+' is:'+AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags); console.info(Tag+'Flag ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags);
console.info(Tag+'State for '+i+' is:'+AudioRendererChangeInfoArray[i].rendererState); console.info(Tag+'State for ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererState);
var devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; var devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors;
for (let j=0;j<AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) {
console.info(Tag+'Id:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].id); console.info(Tag+'Id:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].id);
console.info(Tag+'Type:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType); console.info(Tag+'Type:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info(Tag+'Role:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole); console.info(Tag+'Role:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info(Tag+'Name:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].name); console.info(Tag+'Name:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].name);
console.info(Tag+'Addr:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].address); console.info(Tag+'Addr:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].address);
console.info(Tag+'SR:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); console.info(Tag+'SR:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info(Tag+'C'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); console.info(Tag+'C' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info(Tag+'CM:'+i+':'+AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks); console.info(Tag+'CM:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks);
} }
if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) {
resultFlag = true; resultFlag = true;
console.info(Tag+'[RENDERER-CHANGE-ON-001] ResultFlag for '+i+' is:'+resultFlag); console.info(Tag + '[RENDERER-CHANGE-ON-001] ResultFlag for '+ i +' is:'+ resultFlag);
}
} }
}
}); });
``` ```
...@@ -2378,30 +2368,31 @@ AudioCapturerChangeInfo数组,只读。 ...@@ -2378,30 +2368,31 @@ AudioCapturerChangeInfo数组,只读。
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
const audioManager = audio.getAudioManager(); const audioManager = audio.getAudioManager();
var Tag = "AFCapLog : ";
audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
for (let i=0;i<AudioCapturerChangeInfoArray.length;i++) { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
console.info(Tag+' ## CapChange on is called for element '+i+' ##'); console.info(Tag + ' ## CapChange on is called for element ' + i + ' ##');
console.info(Tag+'StrId for '+i+'is:'+AudioCapturerChangeInfoArray[i].streamId); console.info(Tag + 'StrId for ' + i +'is:' + AudioCapturerChangeInfoArray[i].streamId);
console.info(Tag+'CUid for '+i+'is:'+AudioCapturerChangeInfoArray[i].clientUid); console.info(Tag + 'CUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
console.info(Tag+'Src for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.source); console.info(Tag + 'Src for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
console.info(Tag+'Flag '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); console.info(Tag + 'Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
console.info(Tag+'State for '+i+'is:'+AudioCapturerChangeInfoArray[i].capturerState); console.info(Tag + 'State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
for (let j=0;j<AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
console.info(Tag+'Id:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); console.info(Tag + 'Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
console.info(Tag+'Type:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); console.info(Tag + 'Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
console.info(Tag+'Role:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); console.info(Tag + 'Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
console.info(Tag+'Name:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); console.info(Tag + 'Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name);
console.info(Tag+'Addr:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); console.info(Tag + 'Addr:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
console.info(Tag+'SR:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); console.info(Tag + 'SR:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
console.info(Tag+'C'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); console.info(Tag + 'C' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
console.info(Tag+'CM:'+i+':'+AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); console.info(Tag + 'CM:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
}
if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) {
resultFlag = true;
console.info(Tag+'[CAPTURER-CHANGE-ON-001] ResultFlag for element '+i +' is: '+ resultFlag);
}
} }
if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) {
resultFlag = true;
console.info(Tag + '[CAPTURER-CHANGE-ON-001] ResultFlag for element ' + i + ' is: ' + resultFlag);
}
}
}); });
``` ```
...@@ -2432,23 +2423,21 @@ audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => ...@@ -2432,23 +2423,21 @@ audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) =>
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
function displayDeviceProp(value) { function displayDeviceProp(value) {
deviceRoleValue = value.deviceRole; deviceRoleValue = value.deviceRole;
deviceTypeValue = value.deviceType; deviceTypeValue = value.deviceType;
} }
var deviceRoleValue = null; var deviceRoleValue = null;
var deviceTypeValue = null; var deviceTypeValue = null;
const promise = audio.getAudioManager().getDevices(1); const promise = audio.getAudioManager().getDevices(1);
promise.then(function (value) { promise.then(function (value) {
console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG');
value.forEach(displayDeviceProp); value.forEach(displayDeviceProp);
if (deviceTypeValue != null && deviceRoleValue != null){ if (deviceTypeValue != null && deviceRoleValue != null){
console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS');
} } else {
else{ console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL');
console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); }
}
}); });
``` ```
...@@ -2488,10 +2477,10 @@ getRendererInfo(callback: AsyncCallback<AudioRendererInfo\>): void ...@@ -2488,10 +2477,10 @@ getRendererInfo(callback: AsyncCallback<AudioRendererInfo\>): void
``` ```
audioRenderer.getRendererInfo((err, rendererInfo) => { audioRenderer.getRendererInfo((err, rendererInfo) => {
console.log('Renderer GetRendererInfo:'); console.log('Renderer GetRendererInfo:');
console.log('Renderer content:' + rendererInfo.content); console.log('Renderer content:' + rendererInfo.content);
console.log('Renderer usage:' + rendererInfo.usage); console.log('Renderer usage:' + rendererInfo.usage);
console.log('Renderer flags:' + rendererInfo.rendererFlags); console.log('Renderer flags:' + rendererInfo.rendererFlags);
}); });
``` ```
...@@ -2514,13 +2503,13 @@ getRendererInfo(): Promise<AudioRendererInfo\> ...@@ -2514,13 +2503,13 @@ getRendererInfo(): Promise<AudioRendererInfo\>
``` ```
var resultFlag = true; var resultFlag = true;
audioRenderer.getRendererInfo().then((rendererInfo) => { audioRenderer.getRendererInfo().then((rendererInfo) => {
console.log('Renderer GetRendererInfo:'); console.log('Renderer GetRendererInfo:');
console.log('Renderer content:' + rendererInfo.content); console.log('Renderer content:' + rendererInfo.content);
console.log('Renderer usage:' + rendererInfo.usage); console.log('Renderer usage:' + rendererInfo.usage);
console.log('Renderer flags:' + rendererInfo.rendererFlags); console.log('Renderer flags:' + rendererInfo.rendererFlags);
}).catch((err) => { }).catch((err) => {
console.log('AudioFrameworkRenderLog: RendererInfo :ERROR: '+err.message); console.log('AudioFrameworkRenderLog: RendererInfo :ERROR: ' + err.message);
resultFlag = false; resultFlag = false;
}); });
``` ```
...@@ -2542,11 +2531,11 @@ getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void ...@@ -2542,11 +2531,11 @@ getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void
``` ```
audioRenderer.getStreamInfo((err, streamInfo) => { audioRenderer.getStreamInfo((err, streamInfo) => {
console.log('Renderer GetStreamInfo:'); console.log('Renderer GetStreamInfo:');
console.log('Renderer sampling rate:' + streamInfo.samplingRate); console.log('Renderer sampling rate:' + streamInfo.samplingRate);
console.log('Renderer channel:' + streamInfo.channels); console.log('Renderer channel:' + streamInfo.channels);
console.log('Renderer format:' + streamInfo.sampleFormat); console.log('Renderer format:' + streamInfo.sampleFormat);
console.log('Renderer encoding type:' + streamInfo.encodingType); console.log('Renderer encoding type:' + streamInfo.encodingType);
}); });
``` ```
...@@ -2568,13 +2557,13 @@ getStreamInfo(): Promise<AudioStreamInfo\> ...@@ -2568,13 +2557,13 @@ getStreamInfo(): Promise<AudioStreamInfo\>
``` ```
audioRenderer.getStreamInfo().then((streamInfo) => { audioRenderer.getStreamInfo().then((streamInfo) => {
console.log('Renderer GetStreamInfo:'); console.log('Renderer GetStreamInfo:');
console.log('Renderer sampling rate:' + streamInfo.samplingRate); console.log('Renderer sampling rate:' + streamInfo.samplingRate);
console.log('Renderer channel:' + streamInfo.channels); console.log('Renderer channel:' + streamInfo.channels);
console.log('Renderer format:' + streamInfo.sampleFormat); console.log('Renderer format:' + streamInfo.sampleFormat);
console.log('Renderer encoding type:' + streamInfo.encodingType); console.log('Renderer encoding type:' + streamInfo.encodingType);
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+err.message);
}); });
``` ```
...@@ -2596,11 +2585,11 @@ start(callback: AsyncCallback<void\>): void ...@@ -2596,11 +2585,11 @@ start(callback: AsyncCallback<void\>): void
``` ```
audioRenderer.start((err) => { audioRenderer.start((err) => {
if (err) { if (err) {
console.error('Renderer start failed.'); console.error('Renderer start failed.');
} else { } else {
console.info('Renderer start success.'); console.info('Renderer start success.');
} }
}); });
``` ```
...@@ -2622,9 +2611,9 @@ start(): Promise<void\> ...@@ -2622,9 +2611,9 @@ start(): Promise<void\>
``` ```
audioRenderer.start().then(() => { audioRenderer.start().then(() => {
console.log('Renderer started'); console.log('Renderer started');
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: ' + err.message);
}); });
``` ```
...@@ -2646,11 +2635,11 @@ pause(callback: AsyncCallback\<void>): void ...@@ -2646,11 +2635,11 @@ pause(callback: AsyncCallback\<void>): void
``` ```
audioRenderer.pause((err) => { audioRenderer.pause((err) => {
if (err) { if (err) {
console.error('Renderer pause failed'); console.error('Renderer pause failed');
} else { } else {
console.log('Renderer paused.'); console.log('Renderer paused.');
} }
}); });
``` ```
...@@ -2672,9 +2661,9 @@ pause(): Promise\<void> ...@@ -2672,9 +2661,9 @@ pause(): Promise\<void>
``` ```
audioRenderer.pause().then(() => { audioRenderer.pause().then(() => {
console.log('Renderer paused'); console.log('Renderer paused');
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+err.message);
}); });
``` ```
...@@ -2696,11 +2685,11 @@ drain(callback: AsyncCallback\<void>): void ...@@ -2696,11 +2685,11 @@ drain(callback: AsyncCallback\<void>): void
``` ```
audioRenderer.drain((err) => { audioRenderer.drain((err) => {
if (err) { if (err) {
console.error('Renderer drain failed'); console.error('Renderer drain failed');
} else { } else {
console.log('Renderer drained.'); console.log('Renderer drained.');
} }
}); });
``` ```
...@@ -2722,9 +2711,9 @@ drain(): Promise\<void> ...@@ -2722,9 +2711,9 @@ drain(): Promise\<void>
``` ```
audioRenderer.drain().then(() => { audioRenderer.drain().then(() => {
console.log('Renderer drained successfully'); console.log('Renderer drained successfully');
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+ err.message);
}); });
``` ```
...@@ -2746,11 +2735,11 @@ stop(callback: AsyncCallback\<void>): void ...@@ -2746,11 +2735,11 @@ stop(callback: AsyncCallback\<void>): void
``` ```
audioRenderer.stop((err) => { audioRenderer.stop((err) => {
if (err) { if (err) {
console.error('Renderer stop failed'); console.error('Renderer stop failed');
} else { } else {
console.log('Renderer stopped.'); console.log('Renderer stopped.');
} }
}); });
``` ```
...@@ -2772,9 +2761,9 @@ stop(): Promise\<void> ...@@ -2772,9 +2761,9 @@ stop(): Promise\<void>
``` ```
audioRenderer.stop().then(() => { audioRenderer.stop().then(() => {
console.log('Renderer stopped successfully'); console.log('Renderer stopped successfully');
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: ' + err.message);
}); });
``` ```
...@@ -2796,11 +2785,11 @@ release(callback: AsyncCallback\<void>): void ...@@ -2796,11 +2785,11 @@ release(callback: AsyncCallback\<void>): void
``` ```
audioRenderer.release((err) => { audioRenderer.release((err) => {
if (err) { if (err) {
console.error('Renderer release failed'); console.error('Renderer release failed');
} else { } else {
console.log('Renderer released.'); console.log('Renderer released.');
} }
}); });
``` ```
...@@ -2822,9 +2811,9 @@ release(): Promise\<void> ...@@ -2822,9 +2811,9 @@ release(): Promise\<void>
``` ```
audioRenderer.release().then(() => { audioRenderer.release().then(() => {
console.log('Renderer released successfully'); console.log('Renderer released successfully');
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+ err.message);
}); });
``` ```
...@@ -2851,49 +2840,49 @@ import fileio from '@ohos.fileio'; ...@@ -2851,49 +2840,49 @@ import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels: audio.AudioChannel.CHANNEL_2, channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION
rendererFlags: 1 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
var audioRenderer; var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data)=> { audio.createAudioRenderer(audioRendererOptions).then((data)=> {
audioRenderer = data; audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ' + err.message);
}); });
var bufferSize; var bufferSize;
audioRenderer.getBufferSize().then((data)=> { audioRenderer.getBufferSize().then((data)=> {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS ' + data);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: ' + err.message);
}); });
console.info('Buffer size:'+bufferSize); console.info('Buffer size:'+bufferSize);
var context = featureAbility.getContext(); var context = featureAbility.getContext();
var path = await context.getCacheDir(); var path = await context.getCacheDir();
var filePath = path+"/StarWars10s-2C-48000-4SW.wav" var filePath = path + "/StarWars10s-2C-48000-4SW.wav";
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf); ss.readSync(buf);
audioRenderer.write(buf, (err, writtenbytes) => { audioRenderer.write(buf, (err, writtenbytes) => {
if (writtenbytes < 0) { if (writtenbytes < 0) {
console.error('write failed.'); console.error('write failed.');
} else { } else {
console.log('Actual written bytes: ' + writtenbytes); console.log('Actual written bytes: ' + writtenbytes);
} }
}); });
``` ```
...@@ -2919,36 +2908,36 @@ import fileio from '@ohos.fileio'; ...@@ -2919,36 +2908,36 @@ import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = { var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2, channels:audio.AudioChannel.CHANNEL_2,
sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
var audioRenderer; var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => { audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data; audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ' + err.message);
}); });
var bufferSize; var bufferSize;
audioRenderer.getBufferSize().then((data) => { audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS ' + data);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: ' + err.message);
}); });
console.info('BufferSize: ' + bufferSize); console.info('BufferSize: ' + bufferSize);
var context = featureAbility.getContext(); var context = featureAbility.getContext();
var path = await context.getCacheDir(); var path = await context.getCacheDir();
...@@ -2957,13 +2946,13 @@ let ss = fileio.createStreamSync(filePath, 'r'); ...@@ -2957,13 +2946,13 @@ let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf); ss.readSync(buf);
audioRenderer.write(buf).then((writtenbytes) => { audioRenderer.write(buf).then((writtenbytes) => {
if (writtenbytes < 0) { if (writtenbytes < 0) {
console.error('write failed.'); console.error('write failed.');
} else { } else {
console.log('Actual written bytes: ' + writtenbytes); console.log('Actual written bytes: ' + writtenbytes);
} }
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+ err.message);
}); });
``` ```
...@@ -2985,7 +2974,7 @@ getAudioTime(callback: AsyncCallback\<number>): void ...@@ -2985,7 +2974,7 @@ getAudioTime(callback: AsyncCallback\<number>): void
``` ```
audioRenderer.getAudioTime((err, timestamp) => { audioRenderer.getAudioTime((err, timestamp) => {
console.log('Current timestamp: ' + timestamp); console.log('Current timestamp: ' + timestamp);
}); });
``` ```
...@@ -3007,9 +2996,9 @@ getAudioTime(): Promise\<number> ...@@ -3007,9 +2996,9 @@ getAudioTime(): Promise\<number>
``` ```
audioRenderer.getAudioTime().then((timestamp) => { audioRenderer.getAudioTime().then((timestamp) => {
console.log('Current timestamp: ' + timestamp); console.log('Current timestamp: ' + timestamp);
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+err.message);
}); });
``` ```
...@@ -3031,9 +3020,9 @@ getBufferSize(callback: AsyncCallback\<number>): void ...@@ -3031,9 +3020,9 @@ getBufferSize(callback: AsyncCallback\<number>): void
``` ```
var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => {
if (err) { if (err) {
console.error('getBufferSize error'); console.error('getBufferSize error');
} }
}); });
``` ```
...@@ -3058,35 +3047,35 @@ import audio from '@ohos.multimedia.audio'; ...@@ -3058,35 +3047,35 @@ import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
var audioStreamInfo = { var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2, channels: audio.AudioChannel.CHANNEL_2,
sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH, content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
var audioRenderer; var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => { audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data; audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ' + err.message);
}); });
var bufferSize; var bufferSize;
audioRenderer.getBufferSize().then((data) => { audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS ' + data);
bufferSize=data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: ' + err.message);
}); });
``` ```
...@@ -3109,11 +3098,11 @@ setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\<void>): void ...@@ -3109,11 +3098,11 @@ setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\<void>): void
``` ```
audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => {
if (err) { if (err) {
console.error('Failed to set params'); console.error('Failed to set params');
} else { } else {
console.log('Callback invoked to indicate a successful render rate setting.'); console.log('Callback invoked to indicate a successful render rate setting.');
} }
}); });
``` ```
...@@ -3141,9 +3130,9 @@ setRenderRate(rate: AudioRendererRate): Promise\<void> ...@@ -3141,9 +3130,9 @@ setRenderRate(rate: AudioRendererRate): Promise\<void>
``` ```
audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => {
console.log('setRenderRate SUCCESS'); console.log('setRenderRate SUCCESS');
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+ err.message);
}); });
``` ```
...@@ -3165,7 +3154,7 @@ getRenderRate(callback: AsyncCallback\<AudioRendererRate>): void ...@@ -3165,7 +3154,7 @@ getRenderRate(callback: AsyncCallback\<AudioRendererRate>): void
``` ```
audioRenderer.getRenderRate((err, renderrate) => { audioRenderer.getRenderRate((err, renderrate) => {
console.log('getRenderRate: ' + renderrate); console.log('getRenderRate: ' + renderrate);
}); });
``` ```
...@@ -3187,9 +3176,9 @@ getRenderRate(): Promise\<AudioRendererRate> ...@@ -3187,9 +3176,9 @@ getRenderRate(): Promise\<AudioRendererRate>
``` ```
audioRenderer.getRenderRate().then((renderRate) => { audioRenderer.getRenderRate().then((renderRate) => {
console.log('getRenderRate: ' + renderRate); console.log('getRenderRate: ' + renderRate);
}).catch((err) => { }).catch((err) => {
console.log('ERROR: '+err.message); console.log('ERROR: '+ err.message);
}); });
``` ```
### setInterruptMode<sup>9+</sup> ### setInterruptMode<sup>9+</sup>
...@@ -3216,26 +3205,26 @@ setInterruptMode(mode: InterruptMode): Promise&lt;void&gt; ...@@ -3216,26 +3205,26 @@ setInterruptMode(mode: InterruptMode): Promise&lt;void&gt;
``` ```
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_MUSIC, content: audio.ContentType.CONTENT_TYPE_MUSIC,
usage: audio.StreamUsage.STREAM_USAGE_MEDIA, usage: audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags: 0 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
let mode = 0; let mode = 0;
audioRenderer.setInterruptMode(mode).then(data=>{ audioRenderer.setInterruptMode(mode).then(data=>{
console.log("setInterruptMode Success!"); console.log("setInterruptMode Success!");
}).catch(err=>{ }).catch(err=>{
console.log("setInterruptMode Fail:" + err.message); console.log("setInterruptMode Fail:" + err.message);
}); });
``` ```
### setInterruptMode<sup>9+</sup> ### setInterruptMode<sup>9+</sup>
...@@ -3257,27 +3246,27 @@ setInterruptMode(mode: InterruptMode, callback: Callback\<void>): void ...@@ -3257,27 +3246,27 @@ setInterruptMode(mode: InterruptMode, callback: Callback\<void>): void
``` ```
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioRendererInfo = { var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_MUSIC, content: audio.ContentType.CONTENT_TYPE_MUSIC,
usage: audio.StreamUsage.STREAM_USAGE_MEDIA, usage: audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags: 0 rendererFlags: 0
} }
var audioRendererOptions = { var audioRendererOptions = {
streamInfo: audioStreamInfo, streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo rendererInfo: audioRendererInfo
} }
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
let mode = 1; let mode = 1;
audioRenderer.setInterruptMode(mode,(err,data)=>{ audioRenderer.setInterruptMode(mode, (err, data)=>{
if(err){ if(err){
console.log("setInterruptMode Fail:" + err.message); console.log("setInterruptMode Fail:" + err.message);
} }
console.log("setInterruptMode Success!"); console.log("setInterruptMode Success!");
}); });
``` ```
### on('interrupt')<sup>9+</sup> ### on('interrupt')<sup>9+</sup>
...@@ -3301,48 +3290,47 @@ on(type: 'interrupt', callback: Callback\<InterruptEvent>): void ...@@ -3301,48 +3290,47 @@ on(type: 'interrupt', callback: Callback\<InterruptEvent>): void
var isPlay; var isPlay;
var started; var started;
audioRenderer.on('interrupt', async(interruptEvent) => { audioRenderer.on('interrupt', async(interruptEvent) => {
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
switch (interruptEvent.hintType) { switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_PAUSE: case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.log('Force paused. Stop writing'); console.log('Force paused. Stop writing');
isPlay = false; isPlay = false;
break; break;
case audio.InterruptHint.INTERRUPT_HINT_STOP: case audio.InterruptHint.INTERRUPT_HINT_STOP:
console.log('Force stopped. Stop writing'); console.log('Force stopped. Stop writing');
isPlay = false; isPlay = false;
break; break;
}
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
console.log('Resume force paused renderer or ignore');
await audioRenderer.start().then(async function () {
console.info('AudioInterruptMusic: renderInstant started :SUCCESS ');
started = true;
}).catch((err) => {
console.info('AudioInterruptMusic: renderInstant start :ERROR : ' + err.message);
started = false;
});
if (started) {
isPlay = true;
console.info('AudioInterruptMusic Renderer started : isPlay : ' + isPlay);
} else {
console.error('AudioInterruptMusic Renderer start failed');
} }
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { break;
switch (interruptEvent.hintType) { case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
case audio.InterruptHint.INTERRUPT_HINT_RESUME: console.log('Choose to pause or ignore');
console.log('Resume force paused renderer or ignore'); if (isPlay == true) {
await audioRenderer.start().then(async function () { isPlay == false;
console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); console.info('AudioInterruptMusic: Media PAUSE : TRUE');
started = true; } else {
}).catch((err) => { isPlay = true;
console.info('AudioInterruptMusic: renderInstant start :ERROR : '+err.message); console.info('AudioInterruptMusic: Media PLAY : TRUE');
started = false;
});
if (started) {
isPlay = true;
console.info('AudioInterruptMusic Renderer started : isPlay : '+isPlay);
} else {
console.error('AudioInterruptMusic Renderer start failed');
}
break;
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.log('Choose to pause or ignore');
if (isPlay == true) {
isPlay == false;
console.info('AudioInterruptMusic: Media PAUSE : TRUE');
}
else {
isPlay = true;
console.info('AudioInterruptMusic: Media PLAY : TRUE');
}
break;
} }
break;
} }
}
}); });
``` ```
...@@ -3366,9 +3354,9 @@ on(type: 'markReach', frame: number, callback: (position: number) => {}): void ...@@ -3366,9 +3354,9 @@ on(type: 'markReach', frame: number, callback: (position: number) => {}): void
``` ```
audioRenderer.on('markReach', 1000, (position) => { audioRenderer.on('markReach', 1000, (position) => {
if (position == 1000) { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
``` ```
...@@ -3413,9 +3401,9 @@ on(type: "periodReach", frame: number, callback: (position: number) => {}): void ...@@ -3413,9 +3401,9 @@ on(type: "periodReach", frame: number, callback: (position: number) => {}): void
``` ```
audioRenderer.on('periodReach', 1000, (position) => { audioRenderer.on('periodReach', 1000, (position) => {
if (position == 1000) { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
``` ```
...@@ -3458,12 +3446,12 @@ on(type: 'stateChange', callback: Callback<AudioState\>): void ...@@ -3458,12 +3446,12 @@ on(type: 'stateChange', callback: Callback<AudioState\>): void
``` ```
audioRenderer.on('stateChange', (state) => { audioRenderer.on('stateChange', (state) => {
if (state == 1) { if (state == 1) {
console.log("audio renderer state is: STATE_PREPARED"); console.log("audio renderer state is: STATE_PREPARED");
} }
if (state == 2) { if (state == 2) {
console.log("audio renderer state is: STATE_RUNNING"); console.log("audio renderer state is: STATE_RUNNING");
} }
}); });
``` ```
...@@ -3485,15 +3473,15 @@ on(type: "dataRequest", callback: Callback<AudioRendererDataInfo>): void; ...@@ -3485,15 +3473,15 @@ on(type: "dataRequest", callback: Callback<AudioRendererDataInfo>): void;
**示例:** **示例:**
``` ```
const path = '/data/storage/el2/ba se/haps/entry/cache/PinkPanther60-44100-1c.wav'; const path = '/data/storage/el2/ba se/haps/entry/cache/PinkPanther60-44100-1c.wav';
let ss = fileio.createStreamSync(path, 'r'); let ss = fileio.createStreamSync(path, 'r');
let discardHeader = new ArrayBuffer(44); let discardHeader = new ArrayBuffer(44);
ss.readSync(discardHeader); ss.readSync(discardHeader);
let rlen = 0; let rlen = 0;
audioRenderer.on('dataRequest', (audioRendererDataInfo) => { audioRenderer.on('dataRequest', (audioRendererDataInfo) => {
var viewObject = new DataView(audioRendererDataInfo.buffer); var viewObject = new DataView(audioRendererDataInfo.buffer);
rlen += ss.readSync(viewObject.buffer); rlen += ss.readSync(viewObject.buffer);
console.info('AudioRenderLog: bytes read from file: ' + rlen); console.info('AudioRenderLog: bytes read from file: ' + rlen);
}) })
``` ```
## AudioCapturer<sup>8+</sup> ## AudioCapturer<sup>8+</sup>
...@@ -3532,13 +3520,13 @@ getCapturerInfo(callback: AsyncCallback<AudioCapturerInfo\>): void ...@@ -3532,13 +3520,13 @@ getCapturerInfo(callback: AsyncCallback<AudioCapturerInfo\>): void
``` ```
audioCapturer.getCapturerInfo((err, capturerInfo) => { audioCapturer.getCapturerInfo((err, capturerInfo) => {
if (err) { if (err) {
console.error('Failed to get capture info'); console.error('Failed to get capture info');
} else { } else {
console.log('Capturer getCapturerInfo:'); console.log('Capturer getCapturerInfo:');
console.log('Capturer source:' + capturerInfo.source); console.log('Capturer source:' + capturerInfo.source);
console.log('Capturer flags:' + capturerInfo.capturerFlags); console.log('Capturer flags:' + capturerInfo.capturerFlags);
} }
}); });
``` ```
...@@ -3561,16 +3549,16 @@ getCapturerInfo(): Promise<AudioCapturerInfo\> ...@@ -3561,16 +3549,16 @@ getCapturerInfo(): Promise<AudioCapturerInfo\>
``` ```
audioCapturer.getCapturerInfo().then((audioParamsGet) => { audioCapturer.getCapturerInfo().then((audioParamsGet) => {
if (audioParamsGet != undefined) { if (audioParamsGet != undefined) {
console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); console.info('AudioFrameworkRecLog: Capturer CapturerInfo:');
console.info('AudioFrameworkRecLog: Capturer SourceType:' + audioParamsGet.source); console.info('AudioFrameworkRecLog: Capturer SourceType:' + audioParamsGet.source);
console.info('AudioFrameworkRecLog: Capturer capturerFlags:' + audioParamsGet.capturerFlags); console.info('AudioFrameworkRecLog: Capturer capturerFlags:' + audioParamsGet.capturerFlags);
}else { } else {
console.info('AudioFrameworkRecLog: audioParamsGet is : '+audioParamsGet); console.info('AudioFrameworkRecLog: audioParamsGet is : '+ audioParamsGet);
console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect: '); console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect: ');
} }
}).catch((err) => { }).catch((err) => {
console.log('AudioFrameworkRecLog: CapturerInfo :ERROR: '+err.message); console.log('AudioFrameworkRecLog: CapturerInfo :ERROR: '+ err.message);
}); });
``` ```
...@@ -3592,15 +3580,15 @@ getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void ...@@ -3592,15 +3580,15 @@ getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void
``` ```
audioCapturer.getStreamInfo((err, streamInfo) => { audioCapturer.getStreamInfo((err, streamInfo) => {
if (err) { if (err) {
console.error('Failed to get stream info'); console.error('Failed to get stream info');
} else { } else {
console.log('Capturer GetStreamInfo:'); console.log('Capturer GetStreamInfo:');
console.log('Capturer sampling rate:' + streamInfo.samplingRate); console.log('Capturer sampling rate:' + streamInfo.samplingRate);
console.log('Capturer channel:' + streamInfo.channels); console.log('Capturer channel:' + streamInfo.channels);
console.log('Capturer format:' + streamInfo.sampleFormat); console.log('Capturer format:' + streamInfo.sampleFormat);
console.log('Capturer encoding type:' + streamInfo.encodingType); console.log('Capturer encoding type:' + streamInfo.encodingType);
} }
}); });
``` ```
...@@ -3622,13 +3610,13 @@ getStreamInfo(): Promise<AudioStreamInfo\> ...@@ -3622,13 +3610,13 @@ getStreamInfo(): Promise<AudioStreamInfo\>
``` ```
audioCapturer.getStreamInfo().then((audioParamsGet) => { audioCapturer.getStreamInfo().then((audioParamsGet) => {
console.info('getStreamInfo:'); console.info('getStreamInfo:');
console.info('sampleFormat:' + audioParamsGet.sampleFormat); console.info('sampleFormat:' + audioParamsGet.sampleFormat);
console.info('samplingRate:' + audioParamsGet.samplingRate); console.info('samplingRate:' + audioParamsGet.samplingRate);
console.info('channels:' + audioParamsGet.channels); console.info('channels:' + audioParamsGet.channels);
console.info('encodingType:' + audioParamsGet.encodingType); console.info('encodingType:' + audioParamsGet.encodingType);
}).catch((err) => { }).catch((err) => {
console.log('getStreamInfo :ERROR: ' + err.message); console.log('getStreamInfo :ERROR: ' + err.message);
}); });
``` ```
...@@ -3650,11 +3638,11 @@ start(callback: AsyncCallback<void\>): void ...@@ -3650,11 +3638,11 @@ start(callback: AsyncCallback<void\>): void
``` ```
audioCapturer.start((err) => { audioCapturer.start((err) => {
if (err) { if (err) {
console.error('Capturer start failed.'); console.error('Capturer start failed.');
} else { } else {
console.info('Capturer start success.'); console.info('Capturer start success.');
} }
}); });
``` ```
...@@ -3680,36 +3668,36 @@ import audio from '@ohos.multimedia.audio'; ...@@ -3680,36 +3668,36 @@ import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2, channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
} }
var audioCapturerInfo = { var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC, source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 1 capturerFlags: 0
} }
var audioCapturer; var audioCapturer;
var stateFlag; var stateFlag;
audio.createAudioCapturer(audioCapturerOptions).then((data) => { audio.createAudioCapturer(audioCapturerOptions).then((data) => {
audioCapturer = data; audioCapturer = data;
console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS');
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message); console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: ' + err.message);
}); });
audioCapturer.start().then(() => { audioCapturer.start().then(() => {
console.info('AudioFrameworkRecLog: ---------START---------'); console.info('AudioFrameworkRecLog: ---------START---------');
console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer: STATE: ' + audioCapturer.state);
console.info('AudioFrameworkRecLog: Capturer started: SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS ');
if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer start :ERROR : ' + err.message);
stateFlag=false; stateFlag = false;
}); });
``` ```
...@@ -3731,11 +3719,11 @@ stop(callback: AsyncCallback<void\>): void ...@@ -3731,11 +3719,11 @@ stop(callback: AsyncCallback<void\>): void
``` ```
audioCapturer.stop((err) => { audioCapturer.stop((err) => {
if (err) { if (err) {
console.error('Capturer stop failed'); console.error('Capturer stop failed');
} else { } else {
console.log('Capturer stopped.'); console.log('Capturer stopped.');
} }
}); });
``` ```
...@@ -3758,13 +3746,13 @@ stop(): Promise<void\> ...@@ -3758,13 +3746,13 @@ stop(): Promise<void\>
``` ```
audioCapturer.stop().then(() => { audioCapturer.stop().then(() => {
console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
console.info('AudioFrameworkRecLog: State is Stopped': '); console.info('AudioFrameworkRecLog: State is Stopped': ');
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+ err.message);
}); });
``` ```
...@@ -3786,11 +3774,11 @@ release(callback: AsyncCallback<void\>): void ...@@ -3786,11 +3774,11 @@ release(callback: AsyncCallback<void\>): void
``` ```
audioCapturer.release((err) => { audioCapturer.release((err) => {
if (err) { if (err) {
console.error('capturer release failed'); console.error('capturer release failed');
} else { } else {
console.log('capturer released.'); console.log('capturer released.');
} }
}); });
``` ```
...@@ -3814,12 +3802,12 @@ release(): Promise<void\> ...@@ -3814,12 +3802,12 @@ release(): Promise<void\>
``` ```
var stateFlag; var stateFlag;
audioCapturer.release().then(() => { audioCapturer.release().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : ' + audioCapturer.state);
console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); console.info('AudioFrameworkRecLog: stateFlag : ' + stateFlag);
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: ' + err.message);
}); });
``` ```
...@@ -3845,15 +3833,15 @@ read(size: number, isBlockingRead: boolean, callback: AsyncCallback<ArrayBuffer\ ...@@ -3845,15 +3833,15 @@ read(size: number, isBlockingRead: boolean, callback: AsyncCallback<ArrayBuffer\
``` ```
var bufferSize; var bufferSize;
audioCapturer.getBufferSize().then((data) => { audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS ' + data);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message); console.info('AudioFrameworkRecLog: getBufferSize: EROOR: ' + err.message);
}); });
audioCapturer.read(bufferSize, true, async(err, buffer) => { audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) { if (!err) {
console.log("Success in reading the buffer data"); console.log("Success in reading the buffer data");
} }
}); });
``` ```
...@@ -3884,16 +3872,16 @@ read(size: number, isBlockingRead: boolean): Promise<ArrayBuffer\> ...@@ -3884,16 +3872,16 @@ read(size: number, isBlockingRead: boolean): Promise<ArrayBuffer\>
``` ```
var bufferSize; var bufferSize;
audioCapturer.getBufferSize().then((data) => { audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS ' + data);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message); console.info('AudioFrameworkRecLog: getBufferSize: ERROR ' + err.message);
}); });
console.info('Buffer size: ' + bufferSize); console.info('Buffer size: ' + bufferSize);
audioCapturer.read(bufferSize, true).then((buffer) => { audioCapturer.read(bufferSize, true).then((buffer) => {
console.info('buffer read successfully'); console.info('buffer read successfully');
}).catch((err) => { }).catch((err) => {
console.info('ERROR : '+err.message); console.info('ERROR : ' + err.message);
}); });
``` ```
...@@ -3916,7 +3904,7 @@ getAudioTime(callback: AsyncCallback<number\>): void ...@@ -3916,7 +3904,7 @@ getAudioTime(callback: AsyncCallback<number\>): void
``` ```
audioCapturer.getAudioTime((err, timestamp) => { audioCapturer.getAudioTime((err, timestamp) => {
console.log('Current timestamp: ' + timestamp); console.log('Current timestamp: ' + timestamp);
}); });
``` ```
...@@ -3939,9 +3927,9 @@ getAudioTime(): Promise<number\> ...@@ -3939,9 +3927,9 @@ getAudioTime(): Promise<number\>
``` ```
audioCapturer.getAudioTime().then((audioTime) => { audioCapturer.getAudioTime().then((audioTime) => {
console.info('AudioFrameworkRecLog: AudioCapturer getAudioTime : Success' + audioTime ); console.info('AudioFrameworkRecLog: AudioCapturer getAudioTime : Success' + audioTime );
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : '+err.message); console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : ' + err.message);
}); });
``` ```
...@@ -3964,14 +3952,14 @@ getBufferSize(callback: AsyncCallback<number\>): void ...@@ -3964,14 +3952,14 @@ getBufferSize(callback: AsyncCallback<number\>): void
``` ```
audioCapturer.getBufferSize((err, bufferSize) => { audioCapturer.getBufferSize((err, bufferSize) => {
if (!err) { if (!err) {
console.log('BufferSize : ' + bufferSize); console.log('BufferSize : ' + bufferSize);
audioCapturer.read(bufferSize, true).then((buffer) => { audioCapturer.read(bufferSize, true).then((buffer) => {
console.info('Buffer read is ' + buffer ); console.info('Buffer read is ' + buffer );
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : '+err.message); console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : ' + err.message);
}); });
} }
}); });
``` ```
...@@ -3995,10 +3983,10 @@ getBufferSize(): Promise<number\> ...@@ -3995,10 +3983,10 @@ getBufferSize(): Promise<number\>
``` ```
var bufferSize; var bufferSize;
audioCapturer.getBufferSize().then((data) => { audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data); console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS ' + data);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message); console.info('AudioFrameworkRecLog: getBufferSize :ERROR : ' + err.message);
}); });
``` ```
...@@ -4023,9 +4011,9 @@ on(type: 'markReach', frame: number, callback: (position: number) => {}): void ...@@ -4023,9 +4011,9 @@ on(type: 'markReach', frame: number, callback: (position: number) => {}): void
``` ```
audioCapturer.on('markReach', 1000, (position) => { audioCapturer.on('markReach', 1000, (position) => {
if (position == 1000) { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
``` ```
...@@ -4069,9 +4057,9 @@ on(type: "periodReach", frame: number, callback: (position: number) => {}): void ...@@ -4069,9 +4057,9 @@ on(type: "periodReach", frame: number, callback: (position: number) => {}): void
``` ```
audioCapturer.on('periodReach', 1000, (position) => { audioCapturer.on('periodReach', 1000, (position) => {
if (position == 1000) { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
``` ```
...@@ -4114,11 +4102,11 @@ on(type: 'stateChange', callback: Callback<AudioState\>): void ...@@ -4114,11 +4102,11 @@ on(type: 'stateChange', callback: Callback<AudioState\>): void
``` ```
audioCapturer.on('stateChange', (state) => { audioCapturer.on('stateChange', (state) => {
if (state == 1) { if (state == 1) {
console.log("audio capturer state is: STATE_PREPARED"); console.log("audio capturer state is: STATE_PREPARED");
} }
if (state == 2) { if (state == 2) {
console.log("audio capturer state is: STATE_RUNNING"); console.log("audio capturer state is: STATE_RUNNING");
} }
}); });
``` ```
\ No newline at end of file
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
本模块主要用于操作及管理NFC卡模拟。 本模块主要用于操作及管理NFC卡模拟。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
......
...@@ -94,7 +94,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall ...@@ -94,7 +94,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall
**系统能力:** SystemCapability.Account.OsAccount **系统能力:** SystemCapability.Account.OsAccount
**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS,该权限仅供系统应用使用 **需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -119,7 +119,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise&lt;void&gt ...@@ -119,7 +119,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise&lt;void&gt
**系统能力:** SystemCapability.Account.OsAccount **系统能力:** SystemCapability.Account.OsAccount
**需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS,该权限仅供系统应用使用 **需要权限:** ohos.permission.MANAGE_LOCAL_ACCOUNTS。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
......
# 数据请求 # 数据请求
本模块提供http数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
>**说明:** >**说明:**
> >
...@@ -18,15 +18,15 @@ import http from '@ohos.net.http'; ...@@ -18,15 +18,15 @@ import http from '@ohos.net.http';
```js ```js
import http from '@ohos.net.http'; import http from '@ohos.net.http';
// 每一个httpRequest对应一个http请求任务,不可复用 // 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// 用于订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// 填写http请求的url地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
...@@ -38,14 +38,14 @@ httpRequest.request( ...@@ -38,14 +38,14 @@ httpRequest.request(
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
connectTimeout: 60000, // 可选,默认为60s connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60s readTimeout: 60000, // 可选,默认为60000ms
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
// data.result为http响应内容,可根据业务需要进行解析 // data.result为HTTP响应内容,可根据业务需要进行解析
console.info('Result:' + data.result); console.info('Result:' + data.result);
console.info('code:' + data.responseCode); console.info('code:' + data.responseCode);
// data.header为http响应头,可根据业务需要进行解析 // data.header为HTTP响应头,可根据业务需要进行解析
console.info('header:' + JSON.stringify(data.header)); console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+ console.info('cookies:' + data.cookies); // 8+
} else { } else {
...@@ -61,7 +61,7 @@ httpRequest.request( ...@@ -61,7 +61,7 @@ httpRequest.request(
createHttp\(\): HttpRequest createHttp\(\): HttpRequest
创建一个http,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header 事件。每一个HttpRequest对象对应一个Http请求。如需发起多个Http请求,须为每个Http请求创建对应HttpRequest对象。 创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -81,7 +81,7 @@ let httpRequest = http.createHttp(); ...@@ -81,7 +81,7 @@ let httpRequest = http.createHttp();
## HttpRequest ## HttpRequest
http请求任务。在调用HttpRequest的方法前,需要先通过[createHttp\(\)](#httpcreatehttp)创建一个任务。 HTTP请求任务。在调用HttpRequest的方法前,需要先通过[createHttp\(\)](#httpcreatehttp)创建一个任务。
### request ### request
...@@ -432,9 +432,9 @@ request方法回调函数的返回值类型。 ...@@ -432,9 +432,9 @@ request方法回调函数的返回值类型。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | 是 | Http请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需Http响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string | | result | string \| Object \| ArrayBuffer<sup>8+</sup> | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码)。 | | responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码)。 |
| header | Object | 是 | 发起http请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; | | header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; |
| cookies<sup>8+</sup> | Array\<string\> | 是 | 服务器返回的 cookies。 | | cookies<sup>8+</sup> | Array\<string\> | 是 | 服务器返回的 cookies。 |
## Response常用错误码 ## Response常用错误码
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
InputConsumer模块提供对按键事件的监听。 InputConsumer模块提供对按键事件的监听。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
> >
> - 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> >
...@@ -32,7 +32,7 @@ on(type: "key", keyOptions: KeyOptions, callback: Callback&lt;KeyOptions&gt;): v ...@@ -32,7 +32,7 @@ on(type: "key", keyOptions: KeyOptions, callback: Callback&lt;KeyOptions&gt;): v
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | 是 | 监听输入事件类型,只支持“key”。 | | type | string | 是 | 监听输入事件类型,只支持“key”。 |
| keyOptions | [keyOptions](#keyOptions) | 是 | 组合键选项,用来指定组合键输入时应该符合的条件。 | | keyOptions | [keyOptions](#keyoptions) | 是 | 组合键选项,用来指定组合键输入时应该符合的条件。 |
| callback | Callback&lt;KeyOptions&gt; | 是 | 回调函数。当满足条件的按键输入产生时,回调到此函数,以传入的KeyOptions为入参。 | | callback | Callback&lt;KeyOptions&gt; | 是 | 回调函数。当满足条件的按键输入产生时,回调到此函数,以传入的KeyOptions为入参。 |
**示例:** **示例:**
...@@ -62,7 +62,7 @@ off(type: "key", keyOptions: KeyOptions, callback?: Callback&lt;KeyOptions&gt;): ...@@ -62,7 +62,7 @@ off(type: "key", keyOptions: KeyOptions, callback?: Callback&lt;KeyOptions&gt;):
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | 是 | 监听输入事件类型,只支持“key”。 | | type | string | 是 | 监听输入事件类型,只支持“key”。 |
| keyOptions | [keyOptions](#keyOptions) | 是 | 开始监听时传入的keyOptions。 | | keyOptions | [keyOptions](#keyoptions) | 是 | 开始监听时传入的keyOptions。 |
| callback | Callback&lt;KeyOptions&gt; | 是 | 开始监听时与KeyOption一同传入的回调函数&nbsp;。 | | callback | Callback&lt;KeyOptions&gt; | 是 | 开始监听时与KeyOption一同传入的回调函数&nbsp;。 |
**示例:** **示例:**
...@@ -77,13 +77,13 @@ inputConsumer.off('key', keyOptions, callback); ...@@ -77,13 +77,13 @@ inputConsumer.off('key', keyOptions, callback);
``` ```
## KeyOption ## KeyOptions
组合键输入事件发生时,组合键满足的选项。 组合键输入事件发生时,组合键满足的选项。
此接口为系统接口。 此接口为系统接口。
**系统能力:**SystemCapability.MultimodalInput.Input.InputConsumer **系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
......
...@@ -4,7 +4,8 @@ ...@@ -4,7 +4,8 @@
输入设备管理模块,用于监听输入设备连接、断开和变化,并查看输入设备相关信息。比如监听鼠标插拔,并获取鼠标的id、name和指针移动速度等信息。 输入设备管理模块,用于监听输入设备连接、断开和变化,并查看输入设备相关信息。比如监听鼠标插拔,并获取鼠标的id、name和指针移动速度等信息。
> **说明**:<br> > **说明**:
>
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -28,7 +29,7 @@ on(type: “change”, listener: Callback&lt;DeviceListener&gt;): void ...@@ -28,7 +29,7 @@ on(type: “change”, listener: Callback&lt;DeviceListener&gt;): void
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ----------- | | -------- | ---------------------------------------- | ---- | ----------- |
| type | string | 是 | 输入设备的事件类型。 | | type | string | 是 | 输入设备的事件类型。 |
| listener | Callback&lt;[DeviceListener](#devicelistener<sup>9+</sup>)&gt; | 是 | 可上报的输入设备事件。 | | listener | Callback&lt;[DeviceListener](#devicelistener9)&gt; | 是 | 可上报的输入设备事件。 |
**示例** **示例**
...@@ -63,7 +64,7 @@ off(type: “change”, listener?: Callback&lt;DeviceListener&gt;): void ...@@ -63,7 +64,7 @@ off(type: “change”, listener?: Callback&lt;DeviceListener&gt;): void
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ----------- | | -------- | ---------------------------------------- | ---- | ----------- |
| type | string | 是 | 输入设备的事件类型。 | | type | string | 是 | 输入设备的事件类型。 |
| listener | Callback&lt;[DeviceListener](#devicelistener<sup>9+</sup>)&gt; | 否 | 可上报的输入设备事件。 | | listener | Callback&lt;[DeviceListener](#devicelistener9)&gt; | 否 | 可上报的输入设备事件。 |
**示例** **示例**
...@@ -245,7 +246,7 @@ getKeyboardType(deviceId: number, callback: AsyncCallback&lt;KeyboardType&gt;): ...@@ -245,7 +246,7 @@ getKeyboardType(deviceId: number, callback: AsyncCallback&lt;KeyboardType&gt;):
| 参数 | 类型 | 必填 | 说明 | | 参数 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------------------------------- | | -------- | ---------------------------------------- | ---- | --------------------------------- |
| deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 | | deviceId | number | 是 | 输入设备的唯一标识,同一个物理设备反复插拔,其设备id会发生变化。 |
| callback | AsyncCallback&lt;[KeyboardType](#keyboardtype)&gt; | 是 | 回调函数,异步返回查询结果。 | | callback | AsyncCallback&lt;[KeyboardType](#keyboardtype9)&gt; | 是 | 回调函数,异步返回查询结果。 |
**示例** **示例**
...@@ -268,7 +269,7 @@ getKeyboardType(deviceId: number): Promise&lt;KeyboardType&gt; ...@@ -268,7 +269,7 @@ getKeyboardType(deviceId: number): Promise&lt;KeyboardType&gt;
| 参数 | 说明 | | 参数 | 说明 |
| ---------------------------------------- | ------------------- | | ---------------------------------------- | ------------------- |
| Promise&lt;[KeyboardType](#keyboardtype)&gt; | Promise实例,用于异步获取结果。 | | Promise&lt;[KeyboardType](#keyboardtype9)&gt; | Promise实例,用于异步获取结果。 |
**示例** **示例**
...@@ -336,7 +337,7 @@ inputDevice.getKeyboardType(1).then((ret)=>{ ...@@ -336,7 +337,7 @@ inputDevice.getKeyboardType(1).then((ret)=>{
| 名称 | 参数类型 | 说明 | | 名称 | 参数类型 | 说明 |
| ----------------------- | ------------------------- | -------- | | ----------------------- | ------------------------- | -------- |
| source | [SourceType](#sourcetype) | 轴的输入源类型。 | | source | [SourceType](#sourcetype) | 轴的输入源类型。 |
| axis | [AxisType](#axistype) | 轴的类型。 | | axis | [AxisType](#axistype9) | 轴的类型。 |
| max | number | 轴的最大值。 | | max | number | 轴的最大值。 |
| min | number | 轴的最小值。 | | min | number | 轴的最小值。 |
| fuzz<sup>9+</sup> | number | 轴的模糊值。 | | fuzz<sup>9+</sup> | number | 轴的模糊值。 |
...@@ -358,7 +359,7 @@ inputDevice.getKeyboardType(1).then((ret)=>{ ...@@ -358,7 +359,7 @@ inputDevice.getKeyboardType(1).then((ret)=>{
| touchpad | string | 表示输入设备是触摸板。 | | touchpad | string | 表示输入设备是触摸板。 |
| joystick | string | 表示输入设备是操纵杆。 | | joystick | string | 表示输入设备是操纵杆。 |
## ChangeType ## ChangedType
定义监听设备热插拔事件。 定义监听设备热插拔事件。
......
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
本模块提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框。 本模块提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
>
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -111,7 +112,7 @@ switchInputMethod(target: InputmethodProperty): Promise&lt;boolean&gt; ...@@ -111,7 +112,7 @@ switchInputMethod(target: InputmethodProperty): Promise&lt;boolean&gt;
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------------------------------- | ---------------------------- | | ----------------------------------------- | ---------------------------- |
| [Promise](#Promise) | 回调返回切换后的输入法。 | | Promise\<boolean> | 回调返回切换后的输入法。 |
**示例:** **示例:**
...@@ -123,7 +124,7 @@ switchInputMethod(target: InputmethodProperty): Promise&lt;boolean&gt; ...@@ -123,7 +124,7 @@ switchInputMethod(target: InputmethodProperty): Promise&lt;boolean&gt;
``` ```
## InputMethodController ## InputMethodController
下列API示例中都需使用[getInputMethodController](#getInputMethodController)回调获取到InputMethodController实例,再通过此实例调用对应方法。 下列API示例中都需使用[getInputMethodController](#getinputmethodcontroller)回调获取到InputMethodController实例,再通过此实例调用对应方法。
### stopInput ### stopInput
...@@ -171,7 +172,7 @@ stopInput(): Promise&lt;boolean&gt; ...@@ -171,7 +172,7 @@ stopInput(): Promise&lt;boolean&gt;
## InputMethodSetting<sup>8+</sup> ## InputMethodSetting<sup>8+</sup>
下列API示例中都需使用[getInputMethodSetting](#getInputMethodSetting)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。 下列API示例中都需使用[getInputMethodSetting](#getinputmethodsetting)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。
### listInputMethod ### listInputMethod
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
本模块主要用于操作及管理NFC。 本模块主要用于操作及管理NFC。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## **导入模块** ## **导入模块**
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
本模块主要用于操作及管理NFC Tag。 本模块主要用于操作及管理NFC Tag。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## **导入模块** ## **导入模块**
...@@ -75,4 +75,4 @@ getNfcVTag(tagInfo: TagInfo): NfcVTag ...@@ -75,4 +75,4 @@ getNfcVTag(tagInfo: TagInfo): NfcVTag
| **类型** | **说明** | | **类型** | **说明** |
| -------- | ---------------- | | -------- | ---------------- |
| NfcVTag | NFC V类型Tag对象 | | NfcVTag | NFC V类型Tag对象 |
\ No newline at end of file
...@@ -18,7 +18,7 @@ import request from '@ohos.request'; ...@@ -18,7 +18,7 @@ import request from '@ohos.request';
在开发FA模型下的应用程序时,需要在config.json配置文件中对应用结构进行声明,在config.json文件中增加network标签,属性标识 "cleartextTraffic": true。即: 在开发FA模型下的应用程序时,需要在config.json配置文件中对应用结构进行声明,在config.json文件中增加network标签,属性标识 "cleartextTraffic": true。即:
``` ```js
var config = { var config = {
"deviceConfig": { "deviceConfig": {
"default": { "default": {
...@@ -341,6 +341,8 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -341,6 +341,8 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void
## UploadConfig ## UploadConfig
**需要权限**:ohos.permission.INTERNET
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
...@@ -354,7 +356,9 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -354,7 +356,9 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void
## File ## File
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。 **需要权限**:ohos.permission.INTERNET
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -366,8 +370,9 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -366,8 +370,9 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void
## RequestData ## RequestData
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。 **需要权限**:ohos.permission.INTERNET
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | 是 | 表示表单元素的名称。 | | name | string | 是 | 表示表单元素的名称。 |
...@@ -939,6 +944,8 @@ resume(callback: AsyncCallback&lt;void&gt;): void ...@@ -939,6 +944,8 @@ resume(callback: AsyncCallback&lt;void&gt;): void
## DownloadConfig ## DownloadConfig
**需要权限**:ohos.permission.INTERNET
**系统能力**: SystemCapability.MiscServices.Download **系统能力**: SystemCapability.MiscServices.Download
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
...@@ -955,6 +962,8 @@ resume(callback: AsyncCallback&lt;void&gt;): void ...@@ -955,6 +962,8 @@ resume(callback: AsyncCallback&lt;void&gt;): void
## DownloadInfo<sup>7+</sup> ## DownloadInfo<sup>7+</sup>
**需要权限**:ohos.permission.INTERNET
**系统能力**: SystemCapability.MiscServices.Download **系统能力**: SystemCapability.MiscServices.Download
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
......
...@@ -68,29 +68,30 @@ save(options?: ScreenshotOptions, callback: AsyncCallback&lt;image.PixelMap&gt;) ...@@ -68,29 +68,30 @@ save(options?: ScreenshotOptions, callback: AsyncCallback&lt;image.PixelMap&gt;)
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [ScreenshotOptions](#screenshotoptions) | 否 | 该类型的参数包含screenRect,imageSize,rotation, displayId四个参数,可以分别设置这四个参数。 | | options | [ScreenshotOptions](#screenshotoptions) | 否 | 该类型的参数包含screenRect,imageSize,rotation, displayId四个参数,可以分别设置这四个参数。 |
| callback | AsyncCallback&lt;image.PixelMap&gt; | 是 | 回调函数。返回一个PixelMap对象。 | | callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | 是 | 回调函数。返回一个PixelMap对象。 |
**示例:** **示例:**
```js ```js
var ScreenshotOptions = { var screenshotOptions = {
"screenRect": { "screenRect": {
"left": 200, "left": 200,
"top": 100, "top": 100,
"width": 200, "width": 200,
"height": 200}, "height": 200},
"imageSize": { "imageSize": {
"width": 300, "width": 300,
"height": 300}, "height": 300},
"rotation": 0, "rotation": 0,
"displayId": 0 "displayId": 0
}; };
screenshot.save(ScreenshotOptions, (err, data) => { screenshot.save(screenshotOptions, (err, pixelMap) => {
if (err) { if (err) {
console.error('Failed to save the screenshot. Error: ' + JSON.stringify(err)); console.log('Failed to save screenshot: ' + JSON.stringify(err));
return; return;
} }
console.info('Screenshot saved. Data: ' + JSON.stringify(data)); console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // PixelMap使用完后及时释放内存
}); });
``` ```
...@@ -114,12 +115,12 @@ save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt; ...@@ -114,12 +115,12 @@ save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt;
| 类型 | 说明 | | 类型 | 说明 |
| ----------------------------- | ----------------------------------------------- | | ----------------------------- | ----------------------------------------------- |
| Promise&lt;image.PixelMap&gt; | Promise对象。返回一个PixelMap对象。 | | Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise对象。返回一个PixelMap对象。 |
**示例:** **示例:**
```js ```js
var ScreenshotOptions = { var screenshotOptions = {
"screenRect": { "screenRect": {
"left": 200, "left": 200,
"top": 100, "top": 100,
...@@ -131,10 +132,11 @@ save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt; ...@@ -131,10 +132,11 @@ save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt;
"rotation": 0, "rotation": 0,
"displayId": 0 "displayId": 0
}; };
let promise = screenshot.save(ScreenshotOptions); let promise = screenshot.save(screenshotOptions);
promise.then(() => { promise.then((pixelMap) => {
console.log('screenshot save success'); console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // PixelMap使用完后及时释放内存
}).catch((err) => { }).catch((err) => {
console.log('screenshot save fail: ' + JSON.stringify(err)); console.log('Failed to save screenshot: ' + JSON.stringify(err));
}); });
``` ```
...@@ -23,7 +23,7 @@ import {UiDriver, BY, MatchPattern, ResizeDirection, WindowMode} from '@ohos.uit ...@@ -23,7 +23,7 @@ import {UiDriver, BY, MatchPattern, ResizeDirection, WindowMode} from '@ohos.uit
## By ## By
UiTest框架通过By类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。<br> UiTest框架通过By类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。<br>
By提供的API能力具有以下几个特点:<br>1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。<br>2、控件属性支持多种匹配模式。<br>3、支持控件绝对定位,相对定位,可通过[By.isBefore](#byisbefore)[By.isAfter](#byisafter)等API限定邻近控件特征进行辅助定位。<br>By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象。 By提供的API能力具有以下几个特点:<br>1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。<br>2、控件属性支持多种匹配模式。<br>3、支持控件绝对定位,相对定位,可通过[By.isBefore](#isbefore)[By.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。<br>By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象。
```js ```js
BY.text('123').type('button') BY.text('123').type('button')
...@@ -1566,7 +1566,7 @@ getWindowMode(): Promise\<WindowMode> ...@@ -1566,7 +1566,7 @@ getWindowMode(): Promise\<WindowMode>
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------------------ | ------------------------------------- | | ------------------------------------------------ | ------------------------------------- |
| Promise\<[WindowMode](#WindowMode<sup>9+</sup>)> | 以Promise形式返回窗口的窗口模式信息。 | | Promise\<[WindowMode](#windowmode9)> | 以Promise形式返回窗口的窗口模式信息。 |
**示例:** **示例:**
...@@ -1695,7 +1695,7 @@ resize(wide: number, height: number, direction: ResizeDirection): Promise\<bool> ...@@ -1695,7 +1695,7 @@ resize(wide: number, height: number, direction: ResizeDirection): Promise\<bool>
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| wide | number | 是 | 以number的形式传入调整后窗口的宽度。 | | wide | number | 是 | 以number的形式传入调整后窗口的宽度。 |
| height | number | 是 | 以number的形式传入调整后窗口的高度。 | | height | number | 是 | 以number的形式传入调整后窗口的高度。 |
| direction | [ResizeDirection](#resizedirection<sup>9+</sup>) | 是 | 以[ResizeDirection](#ResizeDirection<sup>9+</sup>)的形式传入窗口调整的方向。 | | direction | [ResizeDirection](#resizedirection9) | 是 | 以[ResizeDirection](#resizedirection9)的形式传入窗口调整的方向。 |
**返回值:** **返回值:**
......
...@@ -389,7 +389,7 @@ reset(wallpaperType: WallpaperType): Promise&lt;void&gt; ...@@ -389,7 +389,7 @@ reset(wallpaperType: WallpaperType): Promise&lt;void&gt;
移除指定类型的壁纸,恢复为默认显示的壁纸。 移除指定类型的壁纸,恢复为默认显示的壁纸。
**需要权限:**ohos.permission.SET_WALLPAPER **需要权限**ohos.permission.SET_WALLPAPER
**系统能力**: SystemCapability.MiscServices.Wallpaper **系统能力**: SystemCapability.MiscServices.Wallpaper
...@@ -422,7 +422,7 @@ setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, call ...@@ -422,7 +422,7 @@ setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, call
将指定资源设置为指定类型的壁纸。 将指定资源设置为指定类型的壁纸。
**需要权限:** ohos.permission.SET_WALLPAPER **需要权限**ohos.permission.SET_WALLPAPER
**系统能力**: SystemCapability.MiscServices.Wallpaper **系统能力**: SystemCapability.MiscServices.Wallpaper
...@@ -530,7 +530,7 @@ getFile(wallpaperType: WallpaperType, callback: AsyncCallback&lt;number&gt;): vo ...@@ -530,7 +530,7 @@ getFile(wallpaperType: WallpaperType, callback: AsyncCallback&lt;number&gt;): vo
获取指定类型的壁纸文件。 获取指定类型的壁纸文件。
**需要权限**:ohos.permission.SET_WALLPAPER、ohos.permission.READ_USER_STORAGE **需要权限**:ohos.permission.GET_WALLPAPER 和 ohos.permission.READ_USER_STORAGE
**系统能力**: SystemCapability.MiscServices.Wallpaper **系统能力**: SystemCapability.MiscServices.Wallpaper
...@@ -559,7 +559,7 @@ getFile(wallpaperType: WallpaperType): Promise&lt;number&gt; ...@@ -559,7 +559,7 @@ getFile(wallpaperType: WallpaperType): Promise&lt;number&gt;
获取指定类型的壁纸文件。 获取指定类型的壁纸文件。
**需要权限:** ohos.permission.SET_WALLPAPER、ohos.permission.READ_USER_STORAGE **需要权限**:ohos.permission.GET_WALLPAPER 和 ohos.permission.READ_USER_STORAGE
**系统能力**: SystemCapability.MiscServices.Wallpaper **系统能力**: SystemCapability.MiscServices.Wallpaper
...@@ -592,10 +592,12 @@ getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback&lt;image.Pixel ...@@ -592,10 +592,12 @@ getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback&lt;image.Pixel
获取壁纸图片的像素图。 获取壁纸图片的像素图。
**需要权限**:ohos.permission.GET_WALLPAPERohos.permission.READ_USER_STORAGE **需要权限**:ohos.permission.GET_WALLPAPERohos.permission.READ_USER_STORAGE
**系统能力**: SystemCapability.MiscServices.Wallpaper **系统能力**: SystemCapability.MiscServices.Wallpaper
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -619,10 +621,12 @@ getPixelMap(wallpaperType: WallpaperType): Promise&lt;image.PixelMap&gt; ...@@ -619,10 +621,12 @@ getPixelMap(wallpaperType: WallpaperType): Promise&lt;image.PixelMap&gt;
获取壁纸图片的像素图。 获取壁纸图片的像素图。
**需要权限**:ohos.permission.GET_WALLPAPERohos.permission.READ_USER_STORAGE **需要权限**:ohos.permission.GET_WALLPAPERohos.permission.READ_USER_STORAGE
**系统能力**: SystemCapability.MiscServices.Wallpaper **系统能力**: SystemCapability.MiscServices.Wallpaper
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
......
...@@ -1970,6 +1970,57 @@ off(type: 'touchOutside', callback?: Callback&lt;void&gt;): void ...@@ -1970,6 +1970,57 @@ off(type: 'touchOutside', callback?: Callback&lt;void&gt;): void
windowClass.off('touchOutside'); windowClass.off('touchOutside');
``` ```
### on('screenshot')<sup>9+</sup>
on(type: 'screenshot', callback: Callback&lt;void&gt;): void
开启截屏事件的监听。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'screenshot',即截屏事件。 |
| callback | Callback&lt;void&gt; | 是 | 回调函数。发生截屏事件时的回调。 |
**示例:**
```js
windowClass.on('screenshot', () => {
console.info('screenshot happened');
});
```
### off('screenshot')<sup>9+</sup>
off(type: 'screenshot', callback?: Callback&lt;void&gt;): void
关闭截屏事件的监听。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'screenshot',即截屏事件。 |
| callback | Callback&lt;void&gt; | 否 | 回调函数。发生截屏事件时的回调。 |
**示例:**
```js
var callback = ()=>{
console.info('screenshot happened');
}
windowClass.on('screenshot', callback)
windowClass.off('screenshot', callback)
// 如果通过on开启多个callback进行监听,同时关闭所有监听:
windowClass.off('screenshot');
```
### isSupportWideGamut<sup>8+</sup> ### isSupportWideGamut<sup>8+</sup>
isSupportWideGamut(callback: AsyncCallback&lt;boolean&gt;): void isSupportWideGamut(callback: AsyncCallback&lt;boolean&gt;): void
...@@ -2689,6 +2740,59 @@ promise.then((data)=> { ...@@ -2689,6 +2740,59 @@ promise.then((data)=> {
}); });
``` ```
### snapshot<sup>9+</sup>
snapshot(callback: AsyncCallback&lt;image.PixelMap&gt;): void
获取窗口截图,使用callback异步回调。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------------------------- | ---- | -------------------- |
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | 是 | 回调函数。 |
**示例:**
```js
windowClass.snapshot((err, data) => {
if (err.code) {
console.error('Failed to snapshot window. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
data.release(); // PixelMap使用完后及时释放内存
});
```
### snapshot<sup>9+</sup>
snapshot(): Promise&lt;image.PixelMap&gt;
获取窗口截图,使用Promise异步回调。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise对象。返回当前窗口截图。 |
**示例:**
```js
let promise = windowClass.snapshot();
promise.then((pixelMap)=> {
console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // PixelMap使用完后及时释放内存
}).catch((err)=>{
console.error('Failed to snapshot window. Cause:' + JSON.stringify(err));
});
```
## WindowStageEventType<sup>9+</sup> ## WindowStageEventType<sup>9+</sup>
WindowStage生命周期。 WindowStage生命周期。
......
...@@ -45,7 +45,7 @@ Image(src: string | PixelMap | Resource) ...@@ -45,7 +45,7 @@ Image(src: string | PixelMap | Resource)
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 默认值 | 描述 |
| --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- | | --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- |
| alt | string \| [Resource](../../ui/ts-types.md#resource类型) | - | 加载时显示的占位图,支持本地图片和网络图片。 | | alt | string \| [Resource](../../ui/ts-types.md#resource类型) | - | 加载时显示的占位图,支持本地图片和网络图片。 |
| objectFit | [ImageFit](#imagefit枚举说明) | ImageFit.Cover | 设置图片的缩放类型。 | | objectFit | ImageFit | ImageFit.Cover | 设置图片的缩放类型。 |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | 设置图片的重复样式。<br/>> **说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。 | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | 设置图片的重复样式。<br/>> **说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。 |
| interpolation | [ImageInterpolation](#imageinterpolation) | ImageInterpolation.None | 设置图片的插值效果,仅针对图片放大插值。<br/>>&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。<br/>>&nbsp;-&nbsp;PixelMap资源不支持该属性。 | | interpolation | [ImageInterpolation](#imageinterpolation) | ImageInterpolation.None | 设置图片的插值效果,仅针对图片放大插值。<br/>>&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。<br/>>&nbsp;-&nbsp;PixelMap资源不支持该属性。 |
| renderMode | [ImageRenderMode](#imagerendermode) | ImageRenderMode.Original | 设置图片渲染的模式。<br/>>&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。 | | renderMode | [ImageRenderMode](#imagerendermode) | ImageRenderMode.Original | 设置图片渲染的模式。<br/>>&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。 |
......
...@@ -41,34 +41,20 @@ ohos.permission.INTEGRATED_INTERIOR_WINDOW ...@@ -41,34 +41,20 @@ ohos.permission.INTEGRATED_INTERIOR_WINDOW
## 接口 ## 接口
AbilityComponent(value: {want : Want, controller? : AbilityController}) AbilityComponent(value: {want : Want})
- 参数 - 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| want | [Want](../../reference/apis/js-apis-application-Want.md) | 是 | - | 默认加载的Ability描述。 | | want | [Want](../../reference/apis/js-apis-application-Want.md) | 是 | - | 默认加载的Ability描述。 |
| controller | [AbilityController](#abilityController) | 否 | - | Ability控制器。 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| -------- | -------- | | -------- | -------- |
| onReady()&nbsp;=&gt;&nbsp;void | AbilityComponent环境启动完成时的回调,之后可使用AbilityComponent的方法。 | | onConnect()&nbsp;=&gt;&nbsp;void | AbilityComponent环境启动完成时的回调,之后可使用AbilityComponent的方法。 |
| onDestroy()&nbsp;=&gt;&nbsp;void | AbilityComponent环境销毁时的回调。 | | onDisconnect()&nbsp;=&gt;&nbsp;void | AbilityComponent环境销毁时的回调。 |
| onAbilityCreated(name:&nbsp;string)&nbsp;=&gt;&nbsp;void | 加载Ability时触发,name为Ability名。 |
| onAbilityMoveToFont()&nbsp;=&gt;&nbsp;void | 当Ability移动到前台时触发。 |
| onAbilityWillRemove()&nbsp;=&gt;&nbsp;void | Ability移除之前触发。 |
## AbilityController
Ability控制器,提供AbilityComponent的控制接口。
| 名称 | 功能描述 |
| --------------------------------------- | ------------------------------------------------------------ |
| startAbility()&nbsp;=&gt;&nbsp;want | 在AbilityComponent内部加载Ability。<br>want:要加载的Ability描述信息。 |
| preformBackPress()&nbsp;=&gt;&nbsp;void | 在AbilityComponent内部执行返回操作。 |
| getStackCount()&nbsp;=&gt;&nbsp;void | 获取AbilityComponent内部任务栈中任务的个数。 |
## 示例 ## 示例
...@@ -78,7 +64,6 @@ Ability控制器,提供AbilityComponent的控制接口。 ...@@ -78,7 +64,6 @@ Ability控制器,提供AbilityComponent的控制接口。
@Entry @Entry
@Component @Component
struct MyComponent { struct MyComponent {
@State controller: AbilityController = new AbilityController()
build() { build() {
Column() { Column() {
...@@ -87,26 +72,12 @@ struct MyComponent { ...@@ -87,26 +72,12 @@ struct MyComponent {
bundleName: '', bundleName: '',
abilityName: '' abilityName: ''
}, },
controller: this.controller
})
.onReady(() => {
console.log('AbilityComponent ready');
}) })
.onDestory(() => { .onConnect(() => {
console.log('AbilityComponent destory'); console.log('AbilityComponent connect');
})
Button("Start New")
.onClick(() => {
this.controller.startAbility({
bundleName: '',
abilityName: ''
});
}) })
Button("Back") .onDisconnect(() => {
.onClick(() => { console.log('AbilityComponent disconnect');
if (this.controller.getStacjCount() > 1) {
this.controller.preformBackPress();
}
}) })
} }
} }
......
...@@ -23,9 +23,9 @@ Column(value:{space?: Length}) ...@@ -23,9 +23,9 @@ Column(value:{space?: Length})
- 参数 - 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| space | Length | 否 | 0 | 纵向布局元素间距。 | | space | Length | 否 | 0 | 纵向布局元素间距。 |
## 属性 ## 属性
...@@ -33,13 +33,13 @@ Column(value:{space?: Length}) ...@@ -33,13 +33,13 @@ Column(value:{space?: Length})
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| alignItems | HorizontalAlign | HorizontalAlign.Center | 设置子组件在水平方向上的对齐格式。 | | alignItems | HorizontalAlign | HorizontalAlign.Center | 设置子组件在水平方向上的对齐格式。 |
| justifyContent8+ | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | 设置子组件在垂直方向上的对齐格式。 | | justifyContent<sup>8+</sup> | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | 设置子组件在垂直方向上的对齐格式。 |
- HorizontalAlign枚举说明 - HorizontalAlign枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| Start | 按照语言方向起始端对齐。 | | Start | 按照语言方向起始端对齐。 |
| Center | 居中对齐,默认对齐方式。 | | Center | 居中对齐,默认对齐方式。 |
| End | 按照语言方向末端对齐。 | | End | 按照语言方向末端对齐。 |
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
> **说明:** > **说明:**
> - 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > - 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> - Flex组件在设置flexShrink、flexGrow时存在二次布局过程,因此在对性能有严格要求的场景下建议使用[Column](reference/arkui-ts/ts-container-column.md)、[Row](reference/arkui-ts/ts-container-row.md)代替。 > - Flex组件在设置flexShrink、flexGrow时存在二次布局过程,因此在对性能有严格要求的场景下建议使用[Column](ts-container-column.md)、[Row](ts-container-row.md)代替。
## 权限列表 ## 权限列表
...@@ -48,14 +48,14 @@ Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: F ...@@ -48,14 +48,14 @@ Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: F
| WrapReverse | Flex容器的元素反向多行/列排布,子项允许超出容器。 | | WrapReverse | Flex容器的元素反向多行/列排布,子项允许超出容器。 |
- FlexAlign枚举说明 - FlexAlign枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| ------------ | ---------------------------------------- | | ------------ | ------------------------------------------------------------ |
| Start | 元素在主轴方向首端对齐,&nbsp;第一个元素与行首对齐,同时后续的元素与前一个对齐。 | | Start | 元素在主轴方向首端对齐第一个元素与行首对齐,同时后续的元素与前一个对齐。 |
| Center | 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 | | Center | 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 |
| End | 元素在主轴方向尾部对齐,&nbsp;&nbsp;最后一个元素与行尾对齐,其他元素与后一个对齐。 | | End | 元素在主轴方向尾部对齐最后一个元素与行尾对齐,其他元素与后一个对齐。 |
| SpaceBetween | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。&nbsp;第一个元素与行首对齐,最后一个元素与行尾对齐。 | | SpaceBetween | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素与行首对齐,最后一个元素与行尾对齐。 |
| SpaceAround | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。&nbsp;第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 | | SpaceAround | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 |
| SpaceEvenly | Flex主轴方向元素等间距布局,&nbsp;相邻元素之间的间距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 | | SpaceEvenly | Flex主轴方向元素等间距布局,相邻元素之间的间距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 |
## 示例 ## 示例
......
...@@ -29,10 +29,10 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro ...@@ -29,10 +29,10 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro
| controller | [TabsController](#tabscontroller) | 否 | - | 设置Tabs控制器。 | | controller | [TabsController](#tabscontroller) | 否 | - | 设置Tabs控制器。 |
- BarPosition枚举说明 - BarPosition枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| Start | vertical属性方法设置为true时,页签位于容器左侧;vertical属性方法设置为false时,页签位于容器顶部。 | | Start | vertical属性方法设置为true时,页签位于容器左侧;vertical属性方法设置为false时,页签位于容器顶部。 |
| End | vertical属性方法设置为true时,页签位于容器右侧;vertical属性方法设置为false时,页签位于容器底部。 | | End | vertical属性方法设置为true时,页签位于容器右侧;vertical属性方法设置为false时,页签位于容器底部。 |
## 属性 ## 属性
...@@ -41,25 +41,25 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro ...@@ -41,25 +41,25 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| vertical | boolean | 是否为纵向Tab,默认为false。 | 是否为纵向Tab,默认为false。 | | vertical | boolean | false | 是否为纵向Tab,默认为false。 |
| scrollable | boolean | 是否可以通过左右滑动进行页面切换,默认为true。 | 是否可以通过左右滑动进行页面切换,默认为true。 | | scrollable | boolean | true | 是否可以通过左右滑动进行页面切换,默认为true。 |
| barMode | BarMode | TabBar布局模式。 | TabBar布局模式。 | | barMode | BarMode | BarMode.Fixed | TabBar布局模式。 |
| barWidth | number | TabBar的宽度值,不设置时使用系统主题中的默认值。 | TabBar的宽度值,不设置时使用系统主题中的默认值。 | | barWidth | number | - | TabBar的宽度值,不设置时使用系统主题中的默认值。 |
| barHeight | number | TabBar的高度值,不设置时使用系统主题中的默认值。 | TabBar的高度值,不设置时使用系统主题中的默认值。 | | barHeight | number | - | TabBar的高度值,不设置时使用系统主题中的默认值。 |
| animationDuration | number | 200 | TabContent滑动动画时长。 | | animationDuration | number | 200 | TabContent滑动动画时长。 |
- BarMode枚举说明 - BarMode枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| Scrollable | TabBar使用实际布局宽度,&nbsp;超过总长度后可滑动。 | | Scrollable | TabBar使用实际布局宽度,&nbsp;超过总长度后可滑动。 |
| Fixed | 所有TabBar平均分配宽度。 | | Fixed | 所有TabBar平均分配宽度。 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| -------- | -------- | | -------- | -------- |
| onChange(callback:&nbsp;(index:&nbsp;number)&nbsp;=&gt;&nbsp;void) | Tab页签切换后触发的事件。 | | onChange(callback:&nbsp;(index:&nbsp;number)&nbsp;=&gt;&nbsp;void) | Tab页签切换后触发的事件。 |
## TabsController ## TabsController
...@@ -79,7 +79,7 @@ changeIndex(value: number): void ...@@ -79,7 +79,7 @@ changeIndex(value: number): void
控制Tabs切换到指定页签。 控制Tabs切换到指定页签。
- 参数 - 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | number | 是 | - | 页签在Tabs里的索引值,索引值从0开始。 | | value | number | 是 | - | 页签在Tabs里的索引值,索引值从0开始。 |
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| visibility | Visibility | Visibility.Visible | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用if语句代替。| | visibility | Visibility | Visibility.Visible | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../ui/ts-rending-control-syntax-if-else.md)代替。|
- Visibility枚举说明 - Visibility枚举说明
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
组件可见区域变化事件指组件在屏幕中显示的面积变化,提供了判断组件是否完全或部分显示在屏幕中的能力,通常适用于像广告曝光埋点之类的场景。 组件可见区域变化事件指组件在屏幕中显示的面积变化,提供了判断组件是否完全或部分显示在屏幕中的能力,通常适用于像广告曝光埋点之类的场景。
> **说明:**从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > **说明:** 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表 ## 权限列表
......
...@@ -37,8 +37,8 @@ ...@@ -37,8 +37,8 @@
| -------------- | -------------------------- | ------------------- | | -------------- | -------------------------- | ------------------- |
| width | number | 目标元素的宽度,单位为vp。 | | width | number | 目标元素的宽度,单位为vp。 |
| height | number | 目标元素的高度,单位为vp。 | | height | number | 目标元素的高度,单位为vp。 |
| position | [Position](#position8对象说明) | 目标元素左上角相对父元素左上角的位置。 | | position | Position | 目标元素左上角相对父元素左上角的位置。 |
| globalPosition | [Position](#position8对象说明) | 目标元素左上角相对页面左上角的位置。 | | globalPosition | Position | 目标元素左上角相对页面左上角的位置。 |
## Position<sup>8+</sup>对象说明 ## Position<sup>8+</sup>对象说明
| 属性名称 | 参数类型 | 描述 | | 属性名称 | 参数类型 | 描述 |
......
...@@ -26,6 +26,6 @@ FA应用的eTS模块(entry/src/main)的典型开发目录结构如下: ...@@ -26,6 +26,6 @@ FA应用的eTS模块(entry/src/main)的典型开发目录结构如下:
> **说明:** > **说明:**
> >
> - 资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源文件的分类](basic-resource-file-categories.md)。 > - 资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源文件的分类](ui-ts-basic-resource-file-categories.md)。
> >
> - 页面支持导入TypeScript和JavaScript文件。 > - 页面支持导入TypeScript和JavaScript文件。
# 循环渲染 # 循环渲染
开发框架提供循环渲染(ForEach组件)来迭代数组,并为每个数组项创建相应的组件。当循环渲染的元素较多时,会出现页面加载变慢的情况,出于性能考虑,建议使用[LazyForEach](ui/ts-rending-control-syntax-lazyforeach.md)代替。ForEach定义如下: 开发框架提供循环渲染(ForEach组件)来迭代数组,并为每个数组项创建相应的组件。当循环渲染的元素较多时,会出现页面加载变慢的情况,出于性能考虑,建议使用[LazyForEach](ts-rending-control-syntax-lazyforeach.md)代替。ForEach定义如下:
```ts ```ts
......
...@@ -60,7 +60,7 @@ ...@@ -60,7 +60,7 @@
资源引用类型,用于设置组件属性的值。 资源引用类型,用于设置组件属性的值。
可以通过`$r`或者`$rawfile`创建Resource类型对象,详见[资源访问](ts-application-resource-access.md) 可以通过`$r`或者`$rawfile`创建Resource类型对象,详见[资源访问](ts-resource-access.md)
- `$r('belonging.type.name')` - `$r('belonging.type.name')`
......
...@@ -638,7 +638,7 @@ export default { ...@@ -638,7 +638,7 @@ export default {
img.src = 'common/images/2.png'; img.src = 'common/images/2.png';
// 设置图片宽度 // 设置图片宽度
img.width= 150; img.width= 150;
// 设置图高度 // 设置图高度
img.height=150; img.height=150;
// 图片平铺容器 // 图片平铺容器
var pat = ctx.createPattern(img, 'repeat');ctx.fillStyle = pat; var pat = ctx.createPattern(img, 'repeat');ctx.fillStyle = pat;
......
# Sensor # Sensor
## 概述 ## 概述
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
Sensor驱动模型屏蔽硬件器件差异,为上层Sensor服务系统提供稳定的Sensor基础能力接口,包括Sensor列表查询、Sensor启停、Sensor订阅及取消订阅,Sensor参数配置等功能。Sensor设备驱动的开发是基于HDF驱动框架基础上,结合操作系统适配层(OSAL)和平台驱动接口(比如I2C/SPI/UART总线等平台资源)能力,屏蔽不同操作系统和平台总线资源差异,实现Sensor驱动“一次开发,多系统部署”的目标。Sensor驱动模型如图1所示。 Sensor驱动模型屏蔽硬件器件差异,为上层Sensor服务系统提供稳定的Sensor基础能力接口,包括Sensor列表查询、Sensor启停、Sensor订阅及取消订阅,Sensor参数配置等功能。Sensor设备驱动的开发是基于HDF驱动框架基础上,结合操作系统适配层(OSAL)和平台驱动接口(比如I2C/SPI/UART总线等平台资源)能力,屏蔽不同操作系统和平台总线资源差异,实现Sensor驱动“一次开发,多系统部署”的目标。Sensor驱动模型如图1所示。
**图 1** Sensor驱动模型图 **图 1** Sensor驱动模型图
![Sensor驱动模型图](figures/Sensor驱动模型图.png) ![Sensor驱动模型图](figures/Sensor驱动模型图.png)
### 基本概念 ### 基本概念
...@@ -64,16 +64,16 @@ Sensor驱动模型对外开放的API接口能力的具体实现请参考: ...@@ -64,16 +64,16 @@ Sensor驱动模型对外开放的API接口能力的具体实现请参考:
**表 1** Sensor驱动模型对外API接口功能介绍 **表 1** Sensor驱动模型对外API接口功能介绍
| 接口名 | 功能描述 | | 接口名 | 功能描述 |
| ----- | -------- | | ----- | -------- |
| int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | 获取系统中注册的所有传感器信息,一组完整传感器信息包括传感器名字、设备厂商、固件版本号、硬件版本号、传感器类型编号、传感器标识、最大量程、精度、功耗。 | | int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | 获取系统中注册的所有传感器信息,一组完整传感器信息包括传感器名字、设备厂商、固件版本号、硬件版本号、传感器类型编号、传感器标识、最大量程、精度、功耗。 |
| int32_t Enable(int32_t sensorId) | 使能指定传感器设备,只有数据订阅者使能传感器后,才能获取订阅的传感器数据。 | | int32_t Enable(int32_t sensorId) | 使能指定传感器设备,只有数据订阅者使能传感器后,才能获取订阅的传感器数据。 |
| int32_t Disable(int32_t sensorId) | 去使能指定传感器设备。 | | int32_t Disable(int32_t sensorId) | 去使能指定传感器设备。 |
| int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | 设置指定传感器的数据采样间隔和数据上报间隔。 | | int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | 设置指定传感器的数据采样间隔和数据上报间隔。 |
| int32_t SetMode(int32_t sensorId, int32_t mode) | 设置指定传感器的工作模式,不同的工作模式,上报数据方式不同。 | | int32_t SetMode(int32_t sensorId, int32_t mode) | 设置指定传感器的工作模式,不同的工作模式,上报数据方式不同。 |
| int32_t SetOption(int32_t sensorId, uint32_t option) | 设置指定传感器量程,精度等可选配置。 | | int32_t SetOption(int32_t sensorId, uint32_t option) | 设置指定传感器量程,精度等可选配置。 |
| int32_t Register(int32_t groupId, RecordDataCallback cb) | 订阅者根据不同groupId注册传感器数据回调函数,系统会将获取到的传感器数据上报给订阅者。 | | int32_t Register(int32_t groupId, RecordDataCallback cb) | 订阅者根据不同groupId注册传感器数据回调函数,系统会将获取到的传感器数据上报给订阅者。 |
| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | 订阅者根据groupId和回调函数注销对应订阅者的传感器数据回调函数。 | | int32_t Unregister(int32_t groupId, RecordDataCallback cb) | 订阅者根据groupId和回调函数注销对应订阅者的传感器数据回调函数。 |
...@@ -81,7 +81,7 @@ Sensor驱动模型对驱动开发者开放的功能接口,驱动开发者无 ...@@ -81,7 +81,7 @@ Sensor驱动模型对驱动开发者开放的功能接口,驱动开发者无
**表2** Sensor驱动模型对驱动开发者开放的功能接口列表 **表2** Sensor驱动模型对驱动开发者开放的功能接口列表
| 接口名 | 功能描述 | | 接口名 | 功能描述 |
| ----- | -------- | | ----- | -------- |
| int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | 添加当前类型的传感器设备到传感器设备管理。 | | int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | 添加当前类型的传感器设备到传感器设备管理。 |
| int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | 删除传感器设备管理里指定的传感器设备。 | | int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | 删除传感器设备管理里指定的传感器设备。 |
...@@ -101,7 +101,7 @@ Sensor驱动模型要求驱动开发者实现的接口功能,请参考: ...@@ -101,7 +101,7 @@ Sensor驱动模型要求驱动开发者实现的接口功能,请参考:
**表 3** Sensor驱动模型要求驱动开发者实现的接口列表 **表 3** Sensor驱动模型要求驱动开发者实现的接口列表
| 接口名 | 功能描述 | | 接口名 | 功能描述 |
| ----- | -------- | | ----- | -------- |
| int32_t init(void) | 传感器设备探测成功后,需要对传感器设备初始化配置。 | | int32_t init(void) | 传感器设备探测成功后,需要对传感器设备初始化配置。 |
| int32_t Enable(void) | 根据当前传感器设备的HCS配置,下发传感器设备使能操作组的寄存器配置。 | | int32_t Enable(void) | 根据当前传感器设备的HCS配置,下发传感器设备使能操作组的寄存器配置。 |
...@@ -545,7 +545,7 @@ void HdfSensorTest::SetUpTestCase() ...@@ -545,7 +545,7 @@ void HdfSensorTest::SetUpTestCase()
{ {
g_sensorDev = NewSensorInterfaceInstance(); g_sensorDev = NewSensorInterfaceInstance();
if (g_sensorDev == nullptr) { if (g_sensorDev == nullptr) {
printf("test sensorHdi get Module instance failed\n\r"); printf("test sensor get module instance failed\n\r");
} }
} }
/* 用例资源释放 */ /* 用例资源释放 */
......
...@@ -18,7 +18,7 @@ OpenHarmony整体工程较为复杂,目录及实现为系统本身功能,如 ...@@ -18,7 +18,7 @@ OpenHarmony整体工程较为复杂,目录及实现为系统本身功能,如
| /build/lite | OpenHarmony基础编译构建框架 | | /build/lite | OpenHarmony基础编译构建框架 |
| /kernel/liteos_m | 基础内核,其中芯片架构相关实现在arch目录下 | | /kernel/liteos_m | 基础内核,其中芯片架构相关实现在arch目录下 |
| /device | 板级相关实现,各个三方厂商按照OpenHarmony规范适配实现,device下具体目录结构及移植过程参见[板级系统移植](../porting/porting-chip-board-overview.md) | | /device | 板级相关实现,各个三方厂商按照OpenHarmony规范适配实现,device下具体目录结构及移植过程参见[板级系统移植](../porting/porting-chip-board-overview.md) |
| /vendor | 产品级相关实现,主要由华为或者产品厂商贡献 | | /vendor | 产品级相关实现,主要由产品厂商贡献 |
device目录规则:device/{芯片解决方案厂商}/{开发板}。以hisilicon的hispark_taurus为例: device目录规则:device/{芯片解决方案厂商}/{开发板}。以hisilicon的hispark_taurus为例:
...@@ -37,7 +37,7 @@ device ...@@ -37,7 +37,7 @@ device
``` ```
vendor目录规则:vendor/{产品解决方案厂商}/{产品名称}。以华为的wifiiot产品为例: vendor目录规则:vendor/{产品解决方案厂商}/{产品名称}。以wifiiot产品为例:
......
...@@ -122,7 +122,6 @@ ...@@ -122,7 +122,6 @@
- [CompVerInfo](_comp_ver_info.md) - [CompVerInfo](_comp_ver_info.md)
- [CredentialInfo](_credential_info.md) - [CredentialInfo](_credential_info.md)
- [DeviceFuncs](_device_funcs.md) - [DeviceFuncs](_device_funcs.md)
- [DeviceInfo](_device_info.md)
- [DisplayCapability](_display_capability.md) - [DisplayCapability](_display_capability.md)
- [DisplayInfo](_display_info.md) - [DisplayInfo](_display_info.md)
- [DisplayModeInfo](_display_mode_info.md) - [DisplayModeInfo](_display_mode_info.md)
...@@ -130,7 +129,6 @@ ...@@ -130,7 +129,6 @@
- [EnrollParam](_enroll_param.md) - [EnrollParam](_enroll_param.md)
- [EnrollResultInfo](_enroll_resultinfo.md) - [EnrollResultInfo](_enroll_resultinfo.md)
- [EventInfo](_event_info.md) - [EventInfo](_event_info.md)
- [EventPackage](_event_package.md)
- [ExecutorInfo](_executor_info.md) - [ExecutorInfo](_executor_info.md)
- [ExecutorInfo](_user_executor_info.md) - [ExecutorInfo](_user_executor_info.md)
- [ExecutorRegisterInfo](_executor_register_info.md) - [ExecutorRegisterInfo](_executor_register_info.md)
...@@ -154,10 +152,19 @@ ...@@ -154,10 +152,19 @@
- [IInputInterface](_i_input_interface.md) - [IInputInterface](_i_input_interface.md)
- [ILine](_i_line.md) - [ILine](_i_line.md)
- [InputController](_input_controller.md) - [InputController](_input_controller.md)
- [InputDevAbility](_input_dev_ability.md)
- [InputDevAttr](_input_dev_attr.md)
- [InputDevDesc](_input_dev_desc.md)
- [InputDevIdentify](_input_dev_identify.md)
- [InputDeviceInfo](_device_info.md)
- [InputDimensionInfo](_input_dimension_info.md)
- [InputEventCb](_input_report_event_cb.md)
- [InputEventPackage](_event_package.md)
- [InputExtraCmd](_input_extra_cmd.md) - [InputExtraCmd](_input_extra_cmd.md)
- [InputHostCb](_input_host_cb.md)
- [InputHotPlugEvent](_input_hotplug_event.md)
- [InputManager](_input_manager.md) - [InputManager](_input_manager.md)
- [InputReporter](_input_reporter.md) - [InputReporter](_input_reporter.md)
- [InputReportEventCb](_input_report_event_cb.md)
- [IPinAuthInterface](interface_i_pin_auth_interface.md) - [IPinAuthInterface](interface_i_pin_auth_interface.md)
- [IPowerHdiCallback](interface_i_power_hdi_callback.md) - [IPowerHdiCallback](interface_i_power_hdi_callback.md)
- [IPowerInterface](interface_i_power_interface.md) - [IPowerInterface](interface_i_power_interface.md)
......
# DeviceInfo # InputDeviceInfo
## **概述** ## **概述**
...@@ -15,180 +15,104 @@ ...@@ -15,180 +15,104 @@
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| [devIndex](#devindex) | 设备索引 | | [devIndex](#devindex) | 设备索引 |
| [fd](#fd) | 设备对应的文件描述符 | | [devType](#devtype) | 设备类型 |
| [service](#service) | 设备对应的服务 |
| [listener](#listener) | 设备对应的事件监听器 |
| [devType](#devtype) | 设备类型 |
| [powerStatus](#powerstatus) | 电源状态 |
| [chipInfo](#chipinfo)&nbsp;[CHIP_INFO_LEN] | 驱动芯片编码信息 | | [chipInfo](#chipinfo)&nbsp;[CHIP_INFO_LEN] | 驱动芯片编码信息 |
| [vendorName](#vendorname)&nbsp;[VENDOR_NAME_LEN] | 模组厂商名 | | [vendorName](#vendorname)&nbsp;[VENDOR_NAME_LEN] | 模组厂商名 |
| [chipName](#chipname)&nbsp;[CHIP_NAME_LEN] | 驱动芯片型号 | | [chipName](#chipname)&nbsp;[CHIP_NAME_LEN] | 驱动芯片型号 |
| [devNodePath](#devnodepath)&nbsp;[MAX_NODE_PATH_LEN] | 设备文件路径 | | [attrSet](#attrset)| 设备属性。 |
| [solutionX](#solutionx) | x方向分辨率 | | [abilitySet](#abilityset)| 设备能力属性。|
| [solutionY](#solutiony) | y方向分辨率 |
| [callback](#callback) | 数据上报回调函数&nbsp;[InputReportEventCb](_input_report_event_cb.md) |
## **详细描述** ## **详细描述**
input设备基础设备信息 Input设备基础设备信息。
## **类成员变量说明** ## **类成员变量说明**
### callback
```
InputReportEventCb* DeviceInfo::callback
```
**描述:**
数据上报回调函数 [InputReportEventCb](_input_report_event_cb.md)
### chipInfo ### chipInfo
``` ```
char DeviceInfo::chipInfo[CHIP_INFO_LEN] char InputDeviceInfo::chipInfo[CHIP_INFO_LEN]
``` ```
**描述:** **描述:**
驱动芯片编码信息 驱动芯片编码信息
### chipName ### chipName
``` ```
char DeviceInfo::chipName[CHIP_NAME_LEN] char InputDeviceInfo::chipName[CHIP_NAME_LEN]
``` ```
**描述:** **描述:**
驱动芯片型号 驱动芯片型号
### devIndex ### devIndex
``` ```
uint32_t DeviceInfo::devIndex uint32_t InputDeviceInfo::devIndex
``` ```
**描述:** **描述:**
设备索引 设备索引。
### devNodePath
```
char DeviceInfo::devNodePath[MAX_NODE_PATH_LEN]
```
**描述:**
设备文件路径
### devType ### devType
``` ```
uint32_t DeviceInfo::devType uint32_t InputDeviceInfo::devType
```
**描述:**
设备类型
### fd
```
int32_t DeviceInfo::fd
```
**描述:**
设备对应的文件描述符
### listener
```
void* DeviceInfo::listener
```
**描述:**
设备对应的事件监听器
### powerStatus
```
uint32_t DeviceInfo::powerStatus
```
**描述:**
电源状态
### service
```
void* DeviceInfo::service
``` ```
**描述:** **描述:**
设备对应的服务 设备类型。
### solutionX ### vendorName
``` ```
uint32_t DeviceInfo::solutionX char InputDeviceInfo::vendorName[VENDOR_NAME_LEN]
``` ```
**描述:** **描述:**
x方向分辨率 模组厂商名。
### solutionY ### attrSet
``` ```
uint32_t DeviceInfo::solutionY InputDevAttr InputDeviceInfo::attrSet
``` ```
**描述:** **描述:**
y方向分辨率 设备属性。
### vendorName ### abilitySet
``` ```
char DeviceInfo::vendorName[VENDOR_NAME_LEN] InputDevAbility InputDeviceInfo::abilitySet
``` ```
**描述:** **描述:**
模组厂商名 设备能力属性。
\ No newline at end of file
...@@ -23,8 +23,15 @@ ...@@ -23,8 +23,15 @@
| [IInputInterface](_i_input_interface.md) | 定义用于提供输入设备驱动能力的接口。[更多...](_i_input_interface.md) | | [IInputInterface](_i_input_interface.md) | 定义用于提供输入设备驱动能力的接口。[更多...](_i_input_interface.md) |
| [InputReporter](_input_reporter.md) | 提供Input设备数据上报相关的接口。&nbsp;[更多...](_input_reporter.md) | | [InputReporter](_input_reporter.md) | 提供Input设备数据上报相关的接口。&nbsp;[更多...](_input_reporter.md) |
| [InputEventPackage](_event_package.md) | Input事件数据包结构。&nbsp;[更多...](_event_package.md) | | [InputEventPackage](_event_package.md) | Input事件数据包结构。&nbsp;[更多...](_event_package.md) |
| [InputReportEventCb](_input_report_event_cb.md) | 此结构体定义了输入事件回调函数并提供给Input服务使用。&nbsp;[更多...](_input_report_event_cb.md) | | [InputHotPlugEvent](_input_hotplug_event.md) | 热插拔事件数据包结构。&nbsp;[更多...](_input_hotplug_event.md) |
| [DeviceInfo](_device_info.md) | Input设备基础设备信息。&nbsp;[更多...](_device_info.md) | | [InputDevDesc](_input_dev_desc.md) | Input设备描述信息。&nbsp;[更多...](_input_dev_desc.md) |
| [InputEventCb](_input_report_event_cb.md) | 此结构体定义了输入事件回调函数并提供给Input服务使用。&nbsp;[更多...](_input_report_event_cb.md) |
| [InputHostCb](_input_host_cb.md) | 此结构体定义了热插拔事件上报回调函数并提供给Input服务使用。&nbsp;[更多...](_input_host_cb.md) |
| [InputDevAbility](_input_dev_ability.md) | Input设备的能力属性,存储支持事件的位图。&nbsp;[更多...](_input_dev_ability.md) |
| [InputDimensionInfo](_input_dimension_info.md) | Input设备的维度信息。&nbsp;[更多...](_input_dimension_info.md) |
| [InputDevIdentify](_input_dev_identify.md) | Input设备的识别信息。&nbsp;[更多...](_input_dev_identify.md) |
| [InputDevAttr](_input_dev_attr.md) | Input设备属性。&nbsp;[更多...](_input_dev_attr.md) |
| [InputDeviceInfo](_device_info.md) | Input设备基础设备信息。&nbsp;[更多...](_device_info.md) |
| [InputExtraCmd](_input_extra_cmd.md) | 扩展指令的数据结构。&nbsp;[更多...](_input_extra_cmd.md) | | [InputExtraCmd](_input_extra_cmd.md) | 扩展指令的数据结构。&nbsp;[更多...](_input_extra_cmd.md) |
...@@ -49,10 +56,10 @@ ...@@ -49,10 +56,10 @@
| 枚举 | 描述 | | 枚举 | 描述 |
| -------- | -------- | | -------- | -------- |
| [RetStatus](#retstatus)&nbsp;{&nbsp;INPUT_SUCCESS&nbsp;=&nbsp;0,&nbsp;INPUT_FAILURE&nbsp;=&nbsp;-1,&nbsp;INPUT_INVALID_PARAM&nbsp;=&nbsp;-2,&nbsp;INPUT_NOMEM&nbsp;=&nbsp;-3,&nbsp;&nbsp;&nbsp;INPUT_NULL_PTR&nbsp;=&nbsp;-4,&nbsp;INPUT_TIMEOUT&nbsp;=&nbsp;-5,&nbsp;INPUT_UNSUPPORTED&nbsp;=&nbsp;-6&nbsp;} | 定义返回值类型&nbsp;[更多...](#retstatus) | | [RetStatus](#retstatus)&nbsp;{&nbsp;INPUT_SUCCESS&nbsp;=&nbsp;0,&nbsp;INPUT_FAILURE&nbsp;=&nbsp;-1,&nbsp;INPUT_INVALID_PARAM&nbsp;=&nbsp;-2,&nbsp;INPUT_NOMEM&nbsp;=&nbsp;-3,&nbsp;&nbsp;&nbsp;INPUT_NULL_PTR&nbsp;=&nbsp;-4,&nbsp;INPUT_TIMEOUT&nbsp;=&nbsp;-5,&nbsp;INPUT_UNSUPPORTED&nbsp;=&nbsp;-6&nbsp;} | 定义返回值类型&nbsp;[更多...](#retstatus) |
| [InputDevType](#inputdevtype)&nbsp;{&nbsp;INDEV_TYPE_TOUCH,&nbsp;INDEV_TYPE_KEY,&nbsp;INDEV_TYPE_KEYBOARD,&nbsp;INDEV_TYPE_MOUSE,&nbsp;&nbsp;&nbsp;INDEV_TYPE_BUTTON,&nbsp;INDEV_TYPE_CROWN,&nbsp;INDEV_TYPE_ENCODER,&nbsp;INDEV_TYPE_UNKNOWN&nbsp;} | 定义Input设备类型&nbsp;[更多...](#inputdevtype) | | [InputDevType](#inputdevtype)&nbsp;{&nbsp;INDEV_TYPE_TOUCH,&nbsp;INDEV_TYPE_KEY,&nbsp;INDEV_TYPE_KEYBOARD,&nbsp;INDEV_TYPE_MOUSE,&nbsp;&nbsp;&nbsp;INDEV_TYPE_BUTTON,&nbsp;INDEV_TYPE_CROWN,&nbsp;INDEV_TYPE_ENCODER,&nbsp;INDEV_TYPE_UNKNOWN&nbsp;} | 定义Input设备类型&nbsp;[更多...](#inputdevtype) |
| [PowerStatus](#powerstatus)&nbsp;{&nbsp;INPUT_RESUME,&nbsp;INPUT_SUSPEND,&nbsp;INPUT_LOW_POWER,&nbsp;INPUT_POWER_STATUS_UNKNOWN&nbsp;} | 定义电源状态&nbsp;[更多...](#powerstatus) | | [PowerStatus](#powerstatus)&nbsp;{&nbsp;INPUT_RESUME,&nbsp;INPUT_SUSPEND,&nbsp;INPUT_LOW_POWER,&nbsp;INPUT_POWER_STATUS_UNKNOWN&nbsp;} | 定义电源状态&nbsp;[更多...](#powerstatus) |
| [CapacitanceTest](#capacitancetest)&nbsp;{&nbsp;BASE_TEST,&nbsp;FULL_TEST,&nbsp;MMI_TEST,&nbsp;RUNNING_TEST,&nbsp;&nbsp;&nbsp;TEST_TYPE_UNKNOWN&nbsp;} | 定义容值测试类型&nbsp;[更多...](#capacitancetest) | | [CapacitanceTest](#capacitancetest)&nbsp;{&nbsp;BASE_TEST,&nbsp;FULL_TEST,&nbsp;MMI_TEST,&nbsp;RUNNING_TEST,&nbsp;&nbsp;&nbsp;TEST_TYPE_UNKNOWN&nbsp;} | 定义容值测试类型&nbsp;[更多...](#capacitancetest) |
### 函数 ### 函数
......
# InputReportEventCb # InputEventCb
## **概述** ## **概述**
...@@ -15,8 +15,7 @@ ...@@ -15,8 +15,7 @@
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| (&nbsp;[ReportEventPkgCallback](#reporteventpkgcallback)&nbsp;)(const&nbsp;[InputEventPackage](_event_package.md)&nbsp;\*\*pkgs,&nbsp;uint32_t&nbsp;count,&nbsp;uint32_t&nbsp;devIndex) | 输入事件数据上报的回调函数。&nbsp;[更多...](#reporteventpkgcallback) | | (&nbsp;[EventPkgCallback](#eventpkgcallback)&nbsp;)(const&nbsp;[InputEventPackage](_event_package.md)&nbsp;\*\*pkgs,&nbsp;uint32_t&nbsp;count,&nbsp;uint32_t&nbsp;devIndex) | 输入事件数据上报的回调函数。&nbsp;[更多...](#eventpkgcallback) |
| (&nbsp;[ReportHotPlugEventCallback](#reporthotplugeventcallback)&nbsp;)(const&nbsp;HotPlugEvent&nbsp;\*event) | 热插拔事件上报的回调函数。&nbsp;[更多...](#reporthotplugeventcallback) |
## **详细描述** ## **详细描述**
...@@ -27,11 +26,11 @@ ...@@ -27,11 +26,11 @@
## **类成员变量说明** ## **类成员变量说明**
### ReportEventPkgCallback ### EventPkgCallback
``` ```
void(* InputReportEventCb::ReportEventPkgCallback) (const InputEventPackage **pkgs, uint32_t count, uint32_t devIndex) void (* InputEventCb::EventPkgCallback)(const InputEventPackage **pkgs, uint32_t count, uint32_t devIndex);
``` ```
**描述:** **描述:**
...@@ -42,24 +41,7 @@ void(* InputReportEventCb::ReportEventPkgCallback) (const InputEventPackage **pk ...@@ -42,24 +41,7 @@ void(* InputReportEventCb::ReportEventPkgCallback) (const InputEventPackage **pk
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| eventData | 驱动上报的Input事件数据。 | | pkgs| 驱动上报的Input事件数据。 |
| count | Input事件数据包的个数。 | | count | Input事件数据包的个数。 |
| devIndex | Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 | | devIndex | Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 |
### ReportHotPlugEventCallback
```
void(* InputReportEventCb::ReportHotPlugEventCallback) (const HotPlugEvent *event)
```
**描述:**
热插拔事件上报的回调函数。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| event | 上报的热插拔事件数据 |
...@@ -13,10 +13,10 @@ ...@@ -13,10 +13,10 @@
### Public 属性 ### Public 属性
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| [lightBrightness](#lightbrightness) | 亮度值。 | | [lightBrightness](#lightbrightness) | 亮度值。 |
| [flashEffect](#flasheffect) | 闪烁模式。 | | [flashEffect](#flasheffect) | 闪烁模式。 |
## **详细描述** ## **详细描述**
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
### flashEffect ### flashEffect
``` ```
struct LightFlashEffect LightEffect::flashEffect struct LightFlashEffect LightEffect::flashEffect
``` ```
...@@ -47,11 +47,11 @@ struct LightFlashEffect LightEffect::flashEffect ...@@ -47,11 +47,11 @@ struct LightFlashEffect LightEffect::flashEffect
### lightBrightness ### lightBrightness
``` ```
int32_t LightEffect::lightBrightness int32_t LightEffect::lightBrightness
``` ```
**描述:** **描述:**
亮度值:Bits 24–31为扩展位,Bits 16–23为红色,bits 8–15为绿色,bits 0–7为蓝色。 如果字节段不等于0,指示打开相应颜色的灯。 亮度值:Bits 24–31为扩展位,Bits 16–23为红色,Bits 8–15为绿色,Bits 0–7为蓝色。 如果相对应的字节段不等于0,表示打开相应颜色的灯。
...@@ -13,18 +13,18 @@ ...@@ -13,18 +13,18 @@
### Public 属性 ### Public 属性
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| (&nbsp;[GetLightInfo](#getlightinfo)&nbsp;)([out]&nbsp;struct&nbsp;[LightInfo](_light_info.md)&nbsp;\*\*lightInfo,&nbsp;[out]&nbsp;uint32_t&nbsp;\*count) | 获取当前系统中所有类型的灯信息。&nbsp;[更多...](#getlightinfo) | | (&nbsp;[GetLightInfo](#getlightinfo)&nbsp;)([out]&nbsp;struct&nbsp;[LightInfo](_light_info.md)&nbsp;\*\*lightInfo,&nbsp;[out]&nbsp;uint32_t&nbsp;\*count) | 获取当前系统中所有类型的灯信息。&nbsp;[更多...](#getlightinfo) |
| (&nbsp;[TurnOnLight](#turnonlight)&nbsp;)([in]&nbsp;uint32_t&nbsp;lightId,&nbsp;[in]&nbsp;struct&nbsp;[LightEffect](_light_effect.md)&nbsp;\*effect) | 根据指定的灯ID打开列表中的可用灯。&nbsp;[更多...](#turnonlight) | | (&nbsp;[TurnOnLight](#turnonlight)&nbsp;)([in]&nbsp;uint32_t&nbsp;lightId,&nbsp;[in]&nbsp;struct&nbsp;[LightEffect](_light_effect.md)&nbsp;\*effect) | 根据指定的灯ID打开列表中的可用灯。&nbsp;[更多...](#turnonlight) |
| (&nbsp;[TurnOffLight](#turnofflight)&nbsp;)([in]&nbsp;uint32_t&nbsp;lightId) | 根据指定的灯ID关闭列表中的可用灯。&nbsp;[更多...](#turnofflight) | | (&nbsp;[TurnOffLight](#turnofflight)&nbsp;)([in]&nbsp;uint32_t&nbsp;lightId) | 根据指定的灯ID关闭列表中的可用灯。&nbsp;[更多...](#turnofflight) |
## **详细描述** ## **详细描述**
定义可以在灯上执行的基本操作。 定义可以在灯上执行的基本操作。
操作包括获取灯的信息、打开或关闭灯、设置灯的亮度闪烁模式。 操作包括获取灯的信息、打开或关闭灯、设置灯的亮度闪烁模式。
## **类成员变量说明** ## **类成员变量说明**
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
### GetLightInfo ### GetLightInfo
``` ```
int32_t(* LightInterface::GetLightInfo) ([out] struct LightInfo **lightInfo,[out] uint32_t *count) int32_t(* LightInterface::GetLightInfo) ([out] struct LightInfo **lightInfo,[out] uint32_t *count)
``` ```
...@@ -43,10 +43,10 @@ int32_t(* LightInterface::GetLightInfo) ([out] struct LightInfo **lightInfo,[out ...@@ -43,10 +43,10 @@ int32_t(* LightInterface::GetLightInfo) ([out] struct LightInfo **lightInfo,[out
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| lightInfo | 表示指向灯信息的二级指针,详见[LightInfo](_light_info.md)。 | | lightInfo | 表示指向灯信息的二级指针,详见[LightInfo](_light_info.md)。 |
| count | 表示指向灯数量的指针。 | | count | 表示指向灯数量的指针。 |
**返回:** **返回:**
...@@ -57,7 +57,7 @@ int32_t(* LightInterface::GetLightInfo) ([out] struct LightInfo **lightInfo,[out ...@@ -57,7 +57,7 @@ int32_t(* LightInterface::GetLightInfo) ([out] struct LightInfo **lightInfo,[out
### TurnOffLight ### TurnOffLight
``` ```
int32_t(* LightInterface::TurnOffLight) ([in] uint32_t lightId) int32_t(* LightInterface::TurnOffLight) ([in] uint32_t lightId)
``` ```
...@@ -68,9 +68,9 @@ int32_t(* LightInterface::TurnOffLight) ([in] uint32_t lightId) ...@@ -68,9 +68,9 @@ int32_t(* LightInterface::TurnOffLight) ([in] uint32_t lightId)
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| lightId | 表示灯ID,详见[LightId](_light.md#lightid)。 | | lightId | 表示灯ID,详见[LightId](_light.md#lightid)。 |
**返回:** **返回:**
...@@ -81,7 +81,7 @@ int32_t(* LightInterface::TurnOffLight) ([in] uint32_t lightId) ...@@ -81,7 +81,7 @@ int32_t(* LightInterface::TurnOffLight) ([in] uint32_t lightId)
### TurnOnLight ### TurnOnLight
``` ```
int32_t(* LightInterface::TurnOnLight) ([in] uint32_t lightId,[in] struct LightEffect *effect) int32_t(* LightInterface::TurnOnLight) ([in] uint32_t lightId,[in] struct LightEffect *effect)
``` ```
...@@ -92,10 +92,10 @@ int32_t(* LightInterface::TurnOnLight) ([in] uint32_t lightId,[in] struct LightE ...@@ -92,10 +92,10 @@ int32_t(* LightInterface::TurnOnLight) ([in] uint32_t lightId,[in] struct LightE
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| lightId | 表示灯ID,详见[LightId](_light.md#lightid)。 | | lightId | 表示灯ID,详见[LightId](_light.md#lightid)。 |
| effect | 表示指向灯效果的指针,如果lightbrightness字段为0时,&nbsp;灯的亮度根据HCS配置的默认亮度进行设置,详见[LightEffect](_light_effect.md)。 | | effect | 表示指向灯效果的指针,如果lightbrightness字段为0时,&nbsp;灯的亮度根据HCS配置的默认亮度进行设置,详见[LightEffect](_light_effect.md)。 |
**返回:** **返回:**
...@@ -105,4 +105,5 @@ int32_t(* LightInterface::TurnOnLight) ([in] uint32_t lightId,[in] struct LightE ...@@ -105,4 +105,5 @@ int32_t(* LightInterface::TurnOnLight) ([in] uint32_t lightId,[in] struct LightE
如果不支持闪烁设置,则返回-2。 如果不支持闪烁设置,则返回-2。
如果不支持亮度设置,则返回3。 如果不支持亮度设置,则返回-3。
...@@ -6,61 +6,61 @@ ...@@ -6,61 +6,61 @@
### 文件 ### 文件
| 文件 | 描述 | | 文件 | 描述 |
| -------- | -------- | | -------- | -------- |
| [sensor_if.h](sensor__if_8h.md) | Sensor模块对外通用的接口声明文件,提供获取传感器设备信息、订阅/去订阅传感器数据、&nbsp;使能/去使能传感器、设置传感器模式、设置传感器精度,量程等可选配置接口定义。 | | [sensor_if.h](sensor__if_8h.md) | Sensor模块对外通用的接口声明文件,提供获取传感器设备信息、订阅/取消订阅传感器数据、&nbsp;使能/去使能传感器、设置传感器模式、设置传感器精度,量程等可选配置接口定义。 |
| [sensor_type.h](sensor__type_8h.md) | 定义传感器模块所使用的传感器类型,传感器信息,传感器数据结构等数据类型。 | | [sensor_type.h](sensor__type_8h.md) | 定义传感器模块所使用的传感器类型,传感器信息,传感器数据结构等数据类型。 |
### 类 ### 类
| 类 | 描述 | | 类 | 描述 |
| -------- | -------- | | -------- | -------- |
| [SensorInterface](_sensor_interface.md) | 提供sensor设备基本控制操作接口。&nbsp;[更多...](_sensor_interface.md) | | [SensorInterface](_sensor_interface.md) | 提供sensor设备基本控制操作接口。&nbsp;[更多...](_sensor_interface.md) |
| [SensorInformation](_sensor_information.md) | 定义传感器基本信息。&nbsp;[更多...](_sensor_information.md) | | [SensorInformation](_sensor_information.md) | 定义传感器基本信息。&nbsp;[更多...](_sensor_information.md) |
| [SensorEvents](_sensor_events.md) | 上报传感器数据结构。&nbsp;[更多...](_sensor_events.md) | | [SensorEvents](_sensor_events.md) | 上报传感器数据结构。&nbsp;[更多...](_sensor_events.md) |
### 宏定义 ### 宏定义
| 宏定义 | 描述 | | 宏定义 | 描述 |
| -------- | -------- | | -------- | -------- |
| [SENSOR_NAME_MAX_LEN](#sensornamemaxlen)&nbsp;&nbsp;&nbsp;32 | Sensor名称的最大长度。 | | [SENSOR_NAME_MAX_LEN](#sensornamemaxlen)&nbsp;&nbsp;&nbsp;32 | Sensor名称的最大长度。 |
| [SENSOR_VERSION_MAX_LEN](#sensorversionmaxlen)&nbsp;&nbsp;&nbsp;16 | Sensor版本号的最大长度。 | | [SENSOR_VERSION_MAX_LEN](#sensorversionmaxlen)&nbsp;&nbsp;&nbsp;16 | Sensor版本号的最大长度。 |
### 类型定义 ### 类型定义
| 类型定义 | 描述 | | 类型定义 | 描述 |
| -------- | -------- | | -------- | -------- |
| ([RecordDataCallback](#recorddatacallback))&nbsp;(const&nbsp;struct&nbsp;[SensorEvents](_sensor_events.md)&nbsp;\*) | 传感器上报数据回调函数的定义,传感器服务用户在订阅传感器时,&nbsp;需要注册上报数据回调函数,传感器使能后,传感器服务用户可以接受到传感器数据,详见[SensorInterface](_sensor_interface.md)。&nbsp;[更多...](#recorddatacallback) | | ([RecordDataCallback](#recorddatacallback))&nbsp;(const&nbsp;struct&nbsp;[SensorEvents](_sensor_events.md)&nbsp;\*) | 传感器上报数据回调函数的定义,传感器服务用户在订阅传感器时,&nbsp;需要注册上报数据回调函数,传感器使能后,传感器服务用户可以接受到传感器数据,详见[SensorInterface](_sensor_interface.md)。&nbsp;[更多...](#recorddatacallback) |
### 枚举 ### 枚举
| 枚举 | 描述 | | 枚举 | 描述 |
| -------- | -------- | | -------- | -------- |
| [SensorStatus](#sensorstatus)&nbsp;{&nbsp;SENSOR_SUCCESS&nbsp;=&nbsp;0,&nbsp;SENSOR_FAILURE&nbsp;=&nbsp;-1,&nbsp;SENSOR_NOT_SUPPORT&nbsp;=&nbsp;-2,&nbsp;SENSOR_INVALID_PARAM&nbsp;=&nbsp;-3,&nbsp;&nbsp;&nbsp;SENSOR_INVALID_SERVICE&nbsp;=&nbsp;-4,&nbsp;SENSOR_NULL_PTR&nbsp;=&nbsp;-5&nbsp;} | 定义传感器模块返回值类型。&nbsp;[更多...](#sensorstatus) | | [SensorStatus](#sensorstatus)&nbsp;{&nbsp;SENSOR_SUCCESS&nbsp;=&nbsp;0,&nbsp;SENSOR_FAILURE&nbsp;=&nbsp;-1,&nbsp;SENSOR_NOT_SUPPORT&nbsp;=&nbsp;-2,&nbsp;SENSOR_INVALID_PARAM&nbsp;=&nbsp;-3,&nbsp;&nbsp;&nbsp;SENSOR_INVALID_SERVICE&nbsp;=&nbsp;-4,&nbsp;SENSOR_NULL_PTR&nbsp;=&nbsp;-5&nbsp;} | 定义传感器模块返回值类型。&nbsp;[更多...](#sensorstatus) |
| [SensorTypeTag](#sensortypetag)&nbsp;{&nbsp;SENSOR_TYPE_NONE&nbsp;=&nbsp;0,&nbsp;SENSOR_TYPE_ACCELEROMETER&nbsp;=&nbsp;1,&nbsp;SENSOR_TYPE_GYROSCOPE&nbsp;=&nbsp;2,&nbsp;SENSOR_TYPE_PHOTOPLETHYSMOGRAPH&nbsp;=&nbsp;3,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_ELECTROCARDIOGRAPH&nbsp;=&nbsp;4,&nbsp;SENSOR_TYPE_AMBIENT_LIGHT&nbsp;=&nbsp;5,&nbsp;SENSOR_TYPE_MAGNETIC_FIELD&nbsp;=&nbsp;6,&nbsp;SENSOR_TYPE_CAPACITIVE&nbsp;=&nbsp;7,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_BAROMETER&nbsp;=&nbsp;8,&nbsp;SENSOR_TYPE_TEMPERATURE&nbsp;=&nbsp;9,&nbsp;SENSOR_TYPE_HALL&nbsp;=&nbsp;10,&nbsp;SENSOR_TYPE_GESTURE&nbsp;=&nbsp;11,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_PROXIMITY&nbsp;=&nbsp;12,&nbsp;SENSOR_TYPE_HUMIDITY&nbsp;=&nbsp;13,&nbsp;SENSOR_TYPE_MEDICAL_BEGIN&nbsp;=&nbsp;128,&nbsp;SENSOR_TYPE_MEDICAL_END&nbsp;=&nbsp;160,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_PHYSICAL_MAX&nbsp;=&nbsp;255,&nbsp;SENSOR_TYPE_ORIENTATION&nbsp;=&nbsp;256,&nbsp;SENSOR_TYPE_GRAVITY&nbsp;=&nbsp;257,&nbsp;SENSOR_TYPE_LINEAR_ACCELERATION&nbsp;=&nbsp;258,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_ROTATION_VECTOR&nbsp;=&nbsp;259,&nbsp;SENSOR_TYPE_AMBIENT_TEMPERATURE&nbsp;=&nbsp;260,&nbsp;SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED&nbsp;=&nbsp;261,&nbsp;SENSOR_TYPE_GAME_ROTATION_VECTOR&nbsp;=&nbsp;262,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_GYROSCOPE_UNCALIBRATED&nbsp;=&nbsp;263,&nbsp;SENSOR_TYPE_SIGNIFICANT_MOTION&nbsp;=&nbsp;264,&nbsp;SENSOR_TYPE_PEDOMETER_DETECTION&nbsp;=&nbsp;265,&nbsp;SENSOR_TYPE_PEDOMETER&nbsp;=&nbsp;266,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR&nbsp;=&nbsp;277,&nbsp;SENSOR_TYPE_HEART_RATE&nbsp;=&nbsp;278,&nbsp;SENSOR_TYPE_DEVICE_ORIENTATION&nbsp;=&nbsp;279,&nbsp;SENSOR_TYPE_WEAR_DETECTION&nbsp;=&nbsp;280,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED&nbsp;=&nbsp;281,&nbsp;SENSOR_TYPE_MAX&nbsp;} | 定义传感器类型标识。&nbsp;[更多...](#sensortypetag) | | [SensorTypeTag](#sensortypetag)&nbsp;{&nbsp;SENSOR_TYPE_NONE&nbsp;=&nbsp;0,&nbsp;SENSOR_TYPE_ACCELEROMETER&nbsp;=&nbsp;1,&nbsp;SENSOR_TYPE_GYROSCOPE&nbsp;=&nbsp;2,&nbsp;SENSOR_TYPE_PHOTOPLETHYSMOGRAPH&nbsp;=&nbsp;3,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_ELECTROCARDIOGRAPH&nbsp;=&nbsp;4,&nbsp;SENSOR_TYPE_AMBIENT_LIGHT&nbsp;=&nbsp;5,&nbsp;SENSOR_TYPE_MAGNETIC_FIELD&nbsp;=&nbsp;6,&nbsp;SENSOR_TYPE_CAPACITIVE&nbsp;=&nbsp;7,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_BAROMETER&nbsp;=&nbsp;8,&nbsp;SENSOR_TYPE_TEMPERATURE&nbsp;=&nbsp;9,&nbsp;SENSOR_TYPE_HALL&nbsp;=&nbsp;10,&nbsp;SENSOR_TYPE_GESTURE&nbsp;=&nbsp;11,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_PROXIMITY&nbsp;=&nbsp;12,&nbsp;SENSOR_TYPE_HUMIDITY&nbsp;=&nbsp;13,&nbsp;SENSOR_TYPE_MEDICAL_BEGIN&nbsp;=&nbsp;128,&nbsp;SENSOR_TYPE_MEDICAL_END&nbsp;=&nbsp;160,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_PHYSICAL_MAX&nbsp;=&nbsp;255,&nbsp;SENSOR_TYPE_ORIENTATION&nbsp;=&nbsp;256,&nbsp;SENSOR_TYPE_GRAVITY&nbsp;=&nbsp;257,&nbsp;SENSOR_TYPE_LINEAR_ACCELERATION&nbsp;=&nbsp;258,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_ROTATION_VECTOR&nbsp;=&nbsp;259,&nbsp;SENSOR_TYPE_AMBIENT_TEMPERATURE&nbsp;=&nbsp;260,&nbsp;SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED&nbsp;=&nbsp;261,&nbsp;SENSOR_TYPE_GAME_ROTATION_VECTOR&nbsp;=&nbsp;262,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_GYROSCOPE_UNCALIBRATED&nbsp;=&nbsp;263,&nbsp;SENSOR_TYPE_SIGNIFICANT_MOTION&nbsp;=&nbsp;264,&nbsp;SENSOR_TYPE_PEDOMETER_DETECTION&nbsp;=&nbsp;265,&nbsp;SENSOR_TYPE_PEDOMETER&nbsp;=&nbsp;266,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR&nbsp;=&nbsp;277,&nbsp;SENSOR_TYPE_HEART_RATE&nbsp;=&nbsp;278,&nbsp;SENSOR_TYPE_DEVICE_ORIENTATION&nbsp;=&nbsp;279,&nbsp;SENSOR_TYPE_WEAR_DETECTION&nbsp;=&nbsp;280,&nbsp;&nbsp;&nbsp;SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED&nbsp;=&nbsp;281,&nbsp;SENSOR_TYPE_MAX&nbsp;} | 定义传感器类型标识。&nbsp;[更多...](#sensortypetag) |
| [SensorAccuracyType](#sensoraccuracytype)&nbsp;{&nbsp;SENSOR_NO_ACCURACY&nbsp;=&nbsp;0,&nbsp;SENSOR_LOW_ACCURACY&nbsp;=&nbsp;1,&nbsp;SENSOR_MEDIUM_ACCURACY&nbsp;=&nbsp;2,&nbsp;SENSOR_HIGH_ACCURACY&nbsp;=&nbsp;3,&nbsp;&nbsp;&nbsp;SENSOR_MAX_ACCURACY&nbsp;} | 传感器的精度类型。&nbsp;[更多...](#sensoraccuracytype) | | [SensorAccuracyType](#sensoraccuracytype)&nbsp;{&nbsp;SENSOR_NO_ACCURACY&nbsp;=&nbsp;0,&nbsp;SENSOR_LOW_ACCURACY&nbsp;=&nbsp;1,&nbsp;SENSOR_MEDIUM_ACCURACY&nbsp;=&nbsp;2,&nbsp;SENSOR_HIGH_ACCURACY&nbsp;=&nbsp;3,&nbsp;&nbsp;&nbsp;SENSOR_MAX_ACCURACY&nbsp;} | 传感器的精度类型。&nbsp;[更多...](#sensoraccuracytype) |
| [SensorRangeType](#sensorrangetype)&nbsp;{&nbsp;SENSOR_RANGE_LEVEL1&nbsp;=&nbsp;0,&nbsp;SENSOR_RANGE_LEVEL2&nbsp;=&nbsp;1,&nbsp;SENSOR_RANGE_LEVEL3&nbsp;=&nbsp;2,&nbsp;SENSOR_RANGE_LEVEL_MAX&nbsp;} | 传感器的量程级别。&nbsp;[更多...](#sensorrangetype) | | [SensorRangeType](#sensorrangetype)&nbsp;{&nbsp;SENSOR_RANGE_LEVEL1&nbsp;=&nbsp;0,&nbsp;SENSOR_RANGE_LEVEL2&nbsp;=&nbsp;1,&nbsp;SENSOR_RANGE_LEVEL3&nbsp;=&nbsp;2,&nbsp;SENSOR_RANGE_LEVEL_MAX&nbsp;} | 传感器的量程级别。&nbsp;[更多...](#sensorrangetype) |
| [SensorModeType](#sensormodetype)&nbsp;{&nbsp;SENSOR_MODE_DEFAULT&nbsp;=&nbsp;0,&nbsp;SENSOR_MODE_REALTIME&nbsp;=&nbsp;1,&nbsp;SENSOR_MODE_ON_CHANGE&nbsp;=&nbsp;2,&nbsp;SENSOR_MODE_ONE_SHOT&nbsp;=&nbsp;3,&nbsp;&nbsp;&nbsp;SENSOR_MODE_FIFO_MODE&nbsp;=&nbsp;4,&nbsp;SENSOR_MODE_MAX&nbsp;} | 传感器的工作模式。&nbsp;[更多...](#sensormodetype) | | [SensorModeType](#sensormodetype)&nbsp;{&nbsp;SENSOR_MODE_DEFAULT&nbsp;=&nbsp;0,&nbsp;SENSOR_MODE_REALTIME&nbsp;=&nbsp;1,&nbsp;SENSOR_MODE_ON_CHANGE&nbsp;=&nbsp;2,&nbsp;SENSOR_MODE_ONE_SHOT&nbsp;=&nbsp;3,&nbsp;&nbsp;&nbsp;SENSOR_MODE_FIFO_MODE&nbsp;=&nbsp;4,&nbsp;SENSOR_MODE_MAX&nbsp;} | 传感器的工作模式。&nbsp;[更多...](#sensormodetype) |
| [SensorGroupType](#sensorgrouptype)&nbsp;{&nbsp;TRADITIONAL_SENSOR_TYPE&nbsp;=&nbsp;0,&nbsp;MEDICAL_SENSOR_TYPE&nbsp;=&nbsp;1,&nbsp;SENSOR_GROUP_TYPE_MAX&nbsp;} | 枚举传感器的硬件服务组。&nbsp;[更多...](#sensorgrouptype) | | [SensorGroupType](#sensorgrouptype)&nbsp;{&nbsp;TRADITIONAL_SENSOR_TYPE&nbsp;=&nbsp;0,&nbsp;MEDICAL_SENSOR_TYPE&nbsp;=&nbsp;1,&nbsp;SENSOR_GROUP_TYPE_MAX&nbsp;} | 枚举传感器的硬件服务组。&nbsp;[更多...](#sensorgrouptype) |
### 函数 ### 函数
| 函数 | 描述 | | 函数 | 描述 |
| -------- | -------- | | -------- | -------- |
| [NewSensorInterfaceInstance](#newsensorinterfaceinstance)&nbsp;(void) | 创建传感器接口实例。&nbsp;[更多...](#newsensorinterfaceinstance) | | [NewSensorInterfaceInstance](#newsensorinterfaceinstance)&nbsp;(void) | 创建传感器接口实例。&nbsp;[更多...](#newsensorinterfaceinstance) |
| [FreeSensorInterfaceInstance](#freesensorinterfaceinstance)&nbsp;(void) | 释放传感器接口实例。&nbsp;[更多...](#freesensorinterfaceinstance) | | [FreeSensorInterfaceInstance](#freesensorinterfaceinstance)&nbsp;(void) | 释放传感器接口实例。&nbsp;[更多...](#freesensorinterfaceinstance) |
## **详细描述** ## **详细描述**
传感器设备驱动对传感器服务提供通用的接口能力。 传感器设备驱动对传感器服务提供通用的接口能力。
模块提供传感器服务对传感器驱动访问统一接口,服务获取驱动对象或者代理后, 通过其提供的各类方法,以传感器id区分访问不同类型传感器设备,实现获取传感器设备信息、订阅/订阅传感器数据、 使能/去使能传感器、设置传感器模式、设置传感器精度、量程等可选配置等。 模块提供传感器服务对传感器驱动访问统一接口,服务获取驱动对象或者代理后, 通过其提供的各类方法,以传感器id区分访问不同类型传感器设备,实现获取传感器设备信息、订阅/取消订阅传感器数据、 使能/去使能传感器、设置传感器模式、设置传感器精度、量程等可选配置等。
**Since:** **Since:**
...@@ -76,7 +76,7 @@ ...@@ -76,7 +76,7 @@
### SENSOR_NAME_MAX_LEN ### SENSOR_NAME_MAX_LEN
``` ```
#define SENSOR_NAME_MAX_LEN 32 #define SENSOR_NAME_MAX_LEN 32
``` ```
...@@ -88,7 +88,7 @@ Sensor名称的最大长度。 ...@@ -88,7 +88,7 @@ Sensor名称的最大长度。
### SENSOR_VERSION_MAX_LEN ### SENSOR_VERSION_MAX_LEN
``` ```
#define SENSOR_VERSION_MAX_LEN 16 #define SENSOR_VERSION_MAX_LEN 16
``` ```
...@@ -103,7 +103,7 @@ Sensor版本号的最大长度。 ...@@ -103,7 +103,7 @@ Sensor版本号的最大长度。
### RecordDataCallback ### RecordDataCallback
``` ```
typedef int32_t(* RecordDataCallback) (const struct SensorEvents *) typedef int32_t(* RecordDataCallback) (const struct SensorEvents *)
``` ```
...@@ -118,7 +118,7 @@ typedef int32_t(* RecordDataCallback) (const struct SensorEvents *) ...@@ -118,7 +118,7 @@ typedef int32_t(* RecordDataCallback) (const struct SensorEvents *)
### SensorAccuracyType ### SensorAccuracyType
``` ```
enum SensorAccuracyType enum SensorAccuracyType
``` ```
...@@ -127,18 +127,18 @@ enum SensorAccuracyType ...@@ -127,18 +127,18 @@ enum SensorAccuracyType
传感器的精度类型。 传感器的精度类型。
| 枚举值 | 描述 | | 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| SENSOR_NO_ACCURACY | 无精度类型。 | | SENSOR_NO_ACCURACY | 无精度类型。 |
| SENSOR_LOW_ACCURACY | 低精度类型。 | | SENSOR_LOW_ACCURACY | 低精度类型。 |
| SENSOR_MEDIUM_ACCURACY | 中等精度类型。 | | SENSOR_MEDIUM_ACCURACY | 中等精度类型。 |
| SENSOR_HIGH_ACCURACY | 高精度类型。 | | SENSOR_HIGH_ACCURACY | 高精度类型。 |
| SENSOR_MAX_ACCURACY | 最大精度类型。 | | SENSOR_MAX_ACCURACY | 最大精度类型。 |
### SensorGroupType ### SensorGroupType
``` ```
enum SensorGroupType enum SensorGroupType
``` ```
...@@ -147,16 +147,16 @@ enum SensorGroupType ...@@ -147,16 +147,16 @@ enum SensorGroupType
枚举传感器的硬件服务组。 枚举传感器的硬件服务组。
| 枚举值 | 描述 | | 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| TRADITIONAL_SENSOR_TYPE | 传统传感器类型,传感器ID枚举值范围为128-160。 | | TRADITIONAL_SENSOR_TYPE | 传统传感器类型,传感器ID枚举值范围为128-160。 |
| MEDICAL_SENSOR_TYPE | 医疗传感器类型,传感器ID枚举值范围不在128-160之间。 | | MEDICAL_SENSOR_TYPE | 医疗传感器类型,传感器ID枚举值范围不在128-160之间。 |
| SENSOR_GROUP_TYPE_MAX | 最大传感器类型。 | | SENSOR_GROUP_TYPE_MAX | 最大传感器类型。 |
### SensorModeType ### SensorModeType
``` ```
enum SensorModeType enum SensorModeType
``` ```
...@@ -165,19 +165,19 @@ enum SensorModeType ...@@ -165,19 +165,19 @@ enum SensorModeType
传感器的工作模式。 传感器的工作模式。
| 枚举值 | 描述 | | 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| SENSOR_MODE_DEFAULT | 传感器默认工作模式状态。 | | SENSOR_MODE_DEFAULT | 传感器默认工作模式状态。 |
| SENSOR_MODE_REALTIME | 传感器实时工作模式状态,一组数据上报一次。 | | SENSOR_MODE_REALTIME | 传感器实时工作模式状态,一组数据上报一次。 |
| SENSOR_MODE_ON_CHANGE | 传感器实时工作模式状态,状态变更上报一次。 | | SENSOR_MODE_ON_CHANGE | 传感器实时工作模式状态,状态变更上报一次。 |
| SENSOR_MODE_ONE_SHOT | 传感器实时工作模式状态,只上报一次。 | | SENSOR_MODE_ONE_SHOT | 传感器实时工作模式状态,只上报一次。 |
| SENSOR_MODE_FIFO_MODE | 传感器缓存工作模式状态,根据配置的缓存大小上报。 | | SENSOR_MODE_FIFO_MODE | 传感器缓存工作模式状态,根据配置的缓存大小上报。 |
| SENSOR_MODE_MAX | 传感器最大类型标识。 | | SENSOR_MODE_MAX | 传感器最大类型标识。 |
### SensorRangeType ### SensorRangeType
``` ```
enum SensorRangeType enum SensorRangeType
``` ```
...@@ -186,17 +186,17 @@ enum SensorRangeType ...@@ -186,17 +186,17 @@ enum SensorRangeType
传感器的量程级别。 传感器的量程级别。
| 枚举值 | 描述 | | 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| SENSOR_RANGE_LEVEL1 | 量程级别1。 | | SENSOR_RANGE_LEVEL1 | 量程级别1。 |
| SENSOR_RANGE_LEVEL2 | 量程级别2。 | | SENSOR_RANGE_LEVEL2 | 量程级别2。 |
| SENSOR_RANGE_LEVEL3 | 量程级别3。 | | SENSOR_RANGE_LEVEL3 | 量程级别3。 |
| SENSOR_RANGE_LEVEL_MAX | 量程最大级别。 | | SENSOR_RANGE_LEVEL_MAX | 量程最大级别。 |
### SensorStatus ### SensorStatus
``` ```
enum SensorStatus enum SensorStatus
``` ```
...@@ -205,19 +205,19 @@ enum SensorStatus ...@@ -205,19 +205,19 @@ enum SensorStatus
定义传感器模块返回值类型。 定义传感器模块返回值类型。
| 枚举值 | 描述 | | 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| SENSOR_SUCCESS | 传感器执行成功。 | | SENSOR_SUCCESS | 传感器执行成功。 |
| SENSOR_FAILURE | 传感器执行失败。 | | SENSOR_FAILURE | 传感器执行失败。 |
| SENSOR_NOT_SUPPORT | 传感器不支持。 | | SENSOR_NOT_SUPPORT | 传感器不支持。 |
| SENSOR_INVALID_PARAM | 传感器无效参数。 | | SENSOR_INVALID_PARAM | 传感器无效参数。 |
| SENSOR_INVALID_SERVICE | 传感器无效服务。 | | SENSOR_INVALID_SERVICE | 传感器无效服务。 |
| SENSOR_NULL_PTR | 传感器空指针。 | | SENSOR_NULL_PTR | 传感器空指针。 |
### SensorTypeTag ### SensorTypeTag
``` ```
enum SensorTypeTag enum SensorTypeTag
``` ```
...@@ -226,42 +226,42 @@ enum SensorTypeTag ...@@ -226,42 +226,42 @@ enum SensorTypeTag
定义传感器类型标识。 定义传感器类型标识。
| 枚举值 | 描述 | | 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| SENSOR_TYPE_NONE | 空传感器类型,用于测试。 | | SENSOR_TYPE_NONE | 空传感器类型,用于测试。 |
| SENSOR_TYPE_ACCELEROMETER | 加速度传感器。 | | SENSOR_TYPE_ACCELEROMETER | 加速度传感器。 |
| SENSOR_TYPE_GYROSCOPE | 陀螺仪传感器。 | | SENSOR_TYPE_GYROSCOPE | 陀螺仪传感器。 |
| SENSOR_TYPE_PHOTOPLETHYSMOGRAPH | 心率传感器。 | | SENSOR_TYPE_PHOTOPLETHYSMOGRAPH | 心率传感器。 |
| SENSOR_TYPE_ELECTROCARDIOGRAPH | 心电传感器。 | | SENSOR_TYPE_ELECTROCARDIOGRAPH | 心电传感器。 |
| SENSOR_TYPE_AMBIENT_LIGHT | 环境光传感器。 | | SENSOR_TYPE_AMBIENT_LIGHT | 环境光传感器。 |
| SENSOR_TYPE_MAGNETIC_FIELD | 地磁传感器。 | | SENSOR_TYPE_MAGNETIC_FIELD | 地磁传感器。 |
| SENSOR_TYPE_CAPACITIVE | 电容传感器。 | | SENSOR_TYPE_CAPACITIVE | 电容传感器。 |
| SENSOR_TYPE_BAROMETER | 气压计传感器。 | | SENSOR_TYPE_BAROMETER | 气压计传感器。 |
| SENSOR_TYPE_TEMPERATURE | 温度传感器。 | | SENSOR_TYPE_TEMPERATURE | 温度传感器。 |
| SENSOR_TYPE_HALL | 霍尔传感器。 | | SENSOR_TYPE_HALL | 霍尔传感器。 |
| SENSOR_TYPE_GESTURE | 手势传感器。 | | SENSOR_TYPE_GESTURE | 手势传感器。 |
| SENSOR_TYPE_PROXIMITY | 接近光传感器。 | | SENSOR_TYPE_PROXIMITY | 接近光传感器。 |
| SENSOR_TYPE_HUMIDITY | 湿度传感器。 | | SENSOR_TYPE_HUMIDITY | 湿度传感器。 |
| SENSOR_TYPE_MEDICAL_BEGIN | 医疗传感器ID枚举值范围的开始。 | | SENSOR_TYPE_MEDICAL_BEGIN | 医疗传感器ID枚举值范围的开始。 |
| SENSOR_TYPE_MEDICAL_END | 医疗传感器ID枚举值范围的结束。 | | SENSOR_TYPE_MEDICAL_END | 医疗传感器ID枚举值范围的结束。 |
| SENSOR_TYPE_PHYSICAL_MAX | 物理传感器最大类型。 | | SENSOR_TYPE_PHYSICAL_MAX | 物理传感器最大类型。 |
| SENSOR_TYPE_ORIENTATION | 方向传感器。 | | SENSOR_TYPE_ORIENTATION | 方向传感器。 |
| SENSOR_TYPE_GRAVITY | 重力传感器。 | | SENSOR_TYPE_GRAVITY | 重力传感器。 |
| SENSOR_TYPE_LINEAR_ACCELERATION | 线性加速度传感器。 | | SENSOR_TYPE_LINEAR_ACCELERATION | 线性加速度传感器。 |
| SENSOR_TYPE_ROTATION_VECTOR | 旋转矢量传感器。 | | SENSOR_TYPE_ROTATION_VECTOR | 旋转矢量传感器。 |
| SENSOR_TYPE_AMBIENT_TEMPERATURE | 环境温度传感器 | | SENSOR_TYPE_AMBIENT_TEMPERATURE | 环境温度传感器 |
| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | 未校准磁场传感器。 | | SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | 未校准磁场传感器。 |
| SENSOR_TYPE_GAME_ROTATION_VECTOR | 游戏旋转矢量传感器。 | | SENSOR_TYPE_GAME_ROTATION_VECTOR | 游戏旋转矢量传感器。 |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | 未校准陀螺仪传感器。 | | SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | 未校准陀螺仪传感器。 |
| SENSOR_TYPE_SIGNIFICANT_MOTION | 大幅度动作传感器。 | | SENSOR_TYPE_SIGNIFICANT_MOTION | 大幅度动作传感器。 |
| SENSOR_TYPE_PEDOMETER_DETECTION | 计步器检测传感器。 | | SENSOR_TYPE_PEDOMETER_DETECTION | 计步器检测传感器。 |
| SENSOR_TYPE_PEDOMETER | 计步器传感器。 | | SENSOR_TYPE_PEDOMETER | 计步器传感器。 |
| SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR | 地磁旋转矢量传感器。 | | SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR | 地磁旋转矢量传感器。 |
| SENSOR_TYPE_HEART_RATE | 心率传感器。 | | SENSOR_TYPE_HEART_RATE | 心率传感器。 |
| SENSOR_TYPE_DEVICE_ORIENTATION | 设备方向传感器。 | | SENSOR_TYPE_DEVICE_ORIENTATION | 设备方向传感器。 |
| SENSOR_TYPE_WEAR_DETECTION | 佩戴检测传感器。 | | SENSOR_TYPE_WEAR_DETECTION | 佩戴检测传感器。 |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | 未校准加速度传感器。 | | SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | 未校准加速度传感器。 |
| SENSOR_TYPE_MAX | 传感器类型最大个数标识。 | | SENSOR_TYPE_MAX | 传感器类型最大个数标识。 |
## **函数说明** ## **函数说明**
...@@ -269,7 +269,7 @@ enum SensorTypeTag ...@@ -269,7 +269,7 @@ enum SensorTypeTag
### FreeSensorInterfaceInstance() ### FreeSensorInterfaceInstance()
``` ```
int32_t FreeSensorInterfaceInstance (void ) int32_t FreeSensorInterfaceInstance (void )
``` ```
...@@ -295,7 +295,7 @@ int32_t FreeSensorInterfaceInstance (void ) ...@@ -295,7 +295,7 @@ int32_t FreeSensorInterfaceInstance (void )
### NewSensorInterfaceInstance() ### NewSensorInterfaceInstance()
``` ```
const struct SensorInterface* NewSensorInterfaceInstance (void ) const struct SensorInterface* NewSensorInterfaceInstance (void )
``` ```
...@@ -306,10 +306,10 @@ const struct SensorInterface* NewSensorInterfaceInstance (void ) ...@@ -306,10 +306,10 @@ const struct SensorInterface* NewSensorInterfaceInstance (void )
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorId | 表示传感器ID。有关详细信息,详见[SensorTypeTag](#sensortypetag)。 | | sensorId | 表示传感器ID。有关详细信息,详见[SensorTypeTag](#sensortypetag)。 |
| cb | 表示要注册的回调函数。有关详细信息,详见[RecordDataCallback](#recorddatacallback)。 | | cb | 表示要注册的回调函数。有关详细信息,详见[RecordDataCallback](#recorddatacallback)。 |
**返回:** **返回:**
......
...@@ -13,17 +13,17 @@ ...@@ -13,17 +13,17 @@
### Public 属性 ### Public 属性
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| [sensorName](#sensorname)&nbsp;[[SENSOR_NAME_MAX_LEN](_sensor.md#sensornamemaxlen)] | 传感器名称。 | | [sensorName](#sensorname)&nbsp;[[SENSOR_NAME_MAX_LEN](_sensor.md#sensornamemaxlen)] | 传感器名称。 |
| [vendorName](#vendorname)&nbsp;[[SENSOR_NAME_MAX_LEN](_sensor.md#sensornamemaxlen)] | 传感器设备厂商。 | | [vendorName](#vendorname)&nbsp;[[SENSOR_NAME_MAX_LEN](_sensor.md#sensornamemaxlen)] | 传感器设备厂商。 |
| [firmwareVersion](#firmwareversion)&nbsp;[[SENSOR_VERSION_MAX_LEN](_sensor.md#sensorversionmaxlen)] | 传感器固件版本号。 | | [firmwareVersion](#firmwareversion)&nbsp;[[SENSOR_VERSION_MAX_LEN](_sensor.md#sensorversionmaxlen)] | 传感器固件版本号。 |
| [hardwareVersion](#hardwareversion)<br/>[[SENSOR_VERSION_MAX_LEN](_sensor.md#sensorversionmaxlen)] | 传感器硬件版本号。 | | [hardwareVersion](#hardwareversion)<br/>[[SENSOR_VERSION_MAX_LEN](_sensor.md#sensorversionmaxlen)] | 传感器硬件版本号。 |
| [sensorTypeId](#sensortypeid) | 传感器类型编号, | | [sensorTypeId](#sensortypeid) | 传感器类型编号。 |
| [sensorId](#sensorid) | 传感器的标识号,有传感器驱动开发者定义。 | | [sensorId](#sensorid) | 传感器的标识号,由传感器驱动开发者定义。 |
| [maxRange](#maxrange) | 传感器的最大量程。 | | [maxRange](#maxrange) | 传感器的最大量程。 |
| [accuracy](#accuracy) | 传感器的精度。 | | [accuracy](#accuracy) | 传感器的精度。 |
| [power](#power) | 传感器的功耗。 | | [power](#power) | 传感器的功耗。 |
## **详细描述** ## **详细描述**
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
### accuracy ### accuracy
``` ```
float SensorInformation::accuracy float SensorInformation::accuracy
``` ```
...@@ -54,7 +54,7 @@ float SensorInformation::accuracy ...@@ -54,7 +54,7 @@ float SensorInformation::accuracy
### firmwareVersion ### firmwareVersion
``` ```
char SensorInformation::firmwareVersion[SENSOR_VERSION_MAX_LEN] char SensorInformation::firmwareVersion[SENSOR_VERSION_MAX_LEN]
``` ```
...@@ -66,7 +66,7 @@ char SensorInformation::firmwareVersion[SENSOR_VERSION_MAX_LEN] ...@@ -66,7 +66,7 @@ char SensorInformation::firmwareVersion[SENSOR_VERSION_MAX_LEN]
### hardwareVersion ### hardwareVersion
``` ```
char SensorInformation::hardwareVersion[SENSOR_VERSION_MAX_LEN] char SensorInformation::hardwareVersion[SENSOR_VERSION_MAX_LEN]
``` ```
...@@ -78,7 +78,7 @@ char SensorInformation::hardwareVersion[SENSOR_VERSION_MAX_LEN] ...@@ -78,7 +78,7 @@ char SensorInformation::hardwareVersion[SENSOR_VERSION_MAX_LEN]
### maxRange ### maxRange
``` ```
float SensorInformation::maxRange float SensorInformation::maxRange
``` ```
...@@ -90,19 +90,19 @@ float SensorInformation::maxRange ...@@ -90,19 +90,19 @@ float SensorInformation::maxRange
### sensorId ### sensorId
``` ```
int32_t SensorInformation::sensorId int32_t SensorInformation::sensorId
``` ```
**描述:** **描述:**
传感器的标识号,传感器驱动开发者定义。 传感器的标识号,传感器驱动开发者定义。
### sensorName ### sensorName
``` ```
char SensorInformation::sensorName[SENSOR_NAME_MAX_LEN] char SensorInformation::sensorName[SENSOR_NAME_MAX_LEN]
``` ```
...@@ -114,7 +114,7 @@ char SensorInformation::sensorName[SENSOR_NAME_MAX_LEN] ...@@ -114,7 +114,7 @@ char SensorInformation::sensorName[SENSOR_NAME_MAX_LEN]
### sensorTypeId ### sensorTypeId
``` ```
int32_t SensorInformation::sensorTypeId int32_t SensorInformation::sensorTypeId
``` ```
...@@ -126,7 +126,7 @@ int32_t SensorInformation::sensorTypeId ...@@ -126,7 +126,7 @@ int32_t SensorInformation::sensorTypeId
### vendorName ### vendorName
``` ```
char SensorInformation::vendorName[SENSOR_NAME_MAX_LEN] char SensorInformation::vendorName[SENSOR_NAME_MAX_LEN]
``` ```
...@@ -138,7 +138,7 @@ char SensorInformation::vendorName[SENSOR_NAME_MAX_LEN] ...@@ -138,7 +138,7 @@ char SensorInformation::vendorName[SENSOR_NAME_MAX_LEN]
### power ### power
``` ```
char SensorInformation::power char SensorInformation::power
``` ```
......
...@@ -13,23 +13,23 @@ ...@@ -13,23 +13,23 @@
### Public 属性 ### Public 属性
| Public&nbsp;属性 | 描述 | | Public&nbsp;属性 | 描述 |
| -------- | -------- | | -------- | -------- |
| (&nbsp;[GetAllSensors](#getallsensors)&nbsp;)([out]&nbsp;struct&nbsp;[SensorInformation](_sensor_information.md)&nbsp;\*\*sensorInfo,&nbsp;[out]&nbsp;int32_t&nbsp;\*count) | 获取当前系统中所有类型的传感器信息。&nbsp;[更多...](#getallsensors) | | (&nbsp;[GetAllSensors](#getallsensors)&nbsp;)([out]&nbsp;struct&nbsp;[SensorInformation](_sensor_information.md)&nbsp;\*\*sensorInfo,&nbsp;[out]&nbsp;int32_t&nbsp;\*count) | 获取当前系统中所有类型的传感器信息。&nbsp;[更多...](#getallsensors) |
| (&nbsp;[Enable](#enable)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId) | 根据传感器设备类型标识使能传感器信息列表里存在的设备,只有数据订阅者使能传感器后,才能获取订阅的传感器数据。&nbsp;[更多...](#enable) | | (&nbsp;[Enable](#enable)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId) | 根据传感器设备类型标识使能传感器信息列表里存在的设备,只有数据订阅者使能传感器后,才能获取订阅的传感器数据。&nbsp;[更多...](#enable) |
| (&nbsp;[Disable](#disable)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId) | 根据传感器设备类型标识去使能传感器信息列表里存在的设备。&nbsp;[更多...](#disable) | | (&nbsp;[Disable](#disable)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId) | 根据传感器设备类型标识去使能传感器信息列表里存在的设备。&nbsp;[更多...](#disable) |
| (&nbsp;[SetBatch](#setbatch)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId,&nbsp;[in]&nbsp;int64_t&nbsp;samplingInterval,&nbsp;[in]&nbsp;int64_t&nbsp;reportInterval) | 设置指定传感器的数据采样间隔和数据上报间隔。&nbsp;[更多...](#setbatch) | | (&nbsp;[SetBatch](#setbatch)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId,&nbsp;[in]&nbsp;int64_t&nbsp;samplingInterval,&nbsp;[in]&nbsp;int64_t&nbsp;reportInterval) | 设置指定传感器的数据采样间隔和数据上报间隔。&nbsp;[更多...](#setbatch) |
| (&nbsp;[SetMode](#setmode)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId,&nbsp;[in]&nbsp;int32_t&nbsp;mode) | 设置指定传感器的数据上报模式,不同的工作模式,上报数据的方式不同。&nbsp;[更多...](#setmode) | | (&nbsp;[SetMode](#setmode)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId,&nbsp;[in]&nbsp;int32_t&nbsp;mode) | 设置指定传感器的数据上报模式,不同的工作模式,上报数据的方式不同。&nbsp;[更多...](#setmode) |
| (&nbsp;[SetOption](#setoption)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId,&nbsp;[in]&nbsp;uint32_t&nbsp;option) | 设置指定传感器量程、精度等可选配置。&nbsp;[更多...](#setoption) | | (&nbsp;[SetOption](#setoption)&nbsp;)([in]&nbsp;int32_t&nbsp;sensorId,&nbsp;[in]&nbsp;uint32_t&nbsp;option) | 设置指定传感器量程、精度等可选配置。&nbsp;[更多...](#setoption) |
| (&nbsp;[Register](#register)&nbsp;)([in]&nbsp;int32_t&nbsp;groupId,&nbsp;[in]&nbsp;[RecordDataCallback](_sensor.md#recorddatacallback)&nbsp;cb) | 订阅者注册传感器数据回调函数,系统会将获取到的传感器数据上报给订阅者。&nbsp;[更多...](#register) | | (&nbsp;[Register](#register)&nbsp;)([in]&nbsp;int32_t&nbsp;groupId,&nbsp;[in]&nbsp;[RecordDataCallback](_sensor.md#recorddatacallback)&nbsp;cb) | 订阅者注册传感器数据回调函数,系统会将获取到的传感器数据上报给订阅者。&nbsp;[更多...](#register) |
| (&nbsp;[Unregister](#unregister)&nbsp;)([in]&nbsp;int32_t&nbsp;groupId,&nbsp;[in]&nbsp;[RecordDataCallback](_sensor.md#recorddatacallback)&nbsp;cb) | 订阅者去注册传感器数据回调函数。&nbsp;[更多...](#unregister) | | (&nbsp;[Unregister](#unregister)&nbsp;)([in]&nbsp;int32_t&nbsp;groupId,&nbsp;[in]&nbsp;[RecordDataCallback](_sensor.md#recorddatacallback)&nbsp;cb) | 订阅者取消注册传感器数据回调函数。&nbsp;[更多...](#unregister) |
## **详细描述** ## **详细描述**
提供sensor设备基本控制操作接口。 提供sensor设备基本控制操作接口。
结构体提供获取传感器设备信息、订阅/订阅传感器数据、使能/去使能传感器、设置传感器模式、设置传感器精度、量程等可选配置接口定义。 结构体提供获取传感器设备信息、订阅/取消订阅传感器数据、使能/去使能传感器、设置传感器模式、设置传感器精度、量程等可选配置接口定义。
## **类成员变量说明** ## **类成员变量说明**
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
### Disable ### Disable
``` ```
int32_t(* SensorInterface::Disable) ([in] int32_t sensorId) int32_t(* SensorInterface::Disable) ([in] int32_t sensorId)
``` ```
...@@ -48,9 +48,9 @@ int32_t(* SensorInterface::Disable) ([in] int32_t sensorId) ...@@ -48,9 +48,9 @@ int32_t(* SensorInterface::Disable) ([in] int32_t sensorId)
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 | | sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 |
**返回:** **返回:**
...@@ -61,7 +61,7 @@ int32_t(* SensorInterface::Disable) ([in] int32_t sensorId) ...@@ -61,7 +61,7 @@ int32_t(* SensorInterface::Disable) ([in] int32_t sensorId)
### Enable ### Enable
``` ```
int32_t(* SensorInterface::Enable) ([in] int32_t sensorId) int32_t(* SensorInterface::Enable) ([in] int32_t sensorId)
``` ```
...@@ -72,9 +72,9 @@ int32_t(* SensorInterface::Enable) ([in] int32_t sensorId) ...@@ -72,9 +72,9 @@ int32_t(* SensorInterface::Enable) ([in] int32_t sensorId)
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 | | sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 |
**返回:** **返回:**
...@@ -85,7 +85,7 @@ int32_t(* SensorInterface::Enable) ([in] int32_t sensorId) ...@@ -85,7 +85,7 @@ int32_t(* SensorInterface::Enable) ([in] int32_t sensorId)
### GetAllSensors ### GetAllSensors
``` ```
int32_t(* SensorInterface::GetAllSensors) ([out] struct SensorInformation **sensorInfo,[out] int32_t *count) int32_t(* SensorInterface::GetAllSensors) ([out] struct SensorInformation **sensorInfo,[out] int32_t *count)
``` ```
...@@ -96,10 +96,10 @@ int32_t(* SensorInterface::GetAllSensors) ([out] struct SensorInformation **sens ...@@ -96,10 +96,10 @@ int32_t(* SensorInterface::GetAllSensors) ([out] struct SensorInformation **sens
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorInfo | 输出系统中注册的所有传感器信息,一种类型传感器信息包括传感器名字、设备厂商、&nbsp;固件版本号、硬件版本号、传感器类型编号、传感器标识、最大量程、精度、功耗,详见[SensorInformation](_sensor_information.md)。 | | sensorInfo | 输出系统中注册的所有传感器信息,一种类型传感器信息包括传感器名字、设备厂商、&nbsp;固件版本号、硬件版本号、传感器类型编号、传感器标识、最大量程、精度、功耗,详见[SensorInformation](_sensor_information.md)。 |
| count | 输出系统中注册的传感器数量。 | | count | 输出系统中注册的传感器数量。 |
**返回:** **返回:**
...@@ -110,7 +110,7 @@ int32_t(* SensorInterface::GetAllSensors) ([out] struct SensorInformation **sens ...@@ -110,7 +110,7 @@ int32_t(* SensorInterface::GetAllSensors) ([out] struct SensorInformation **sens
### Register ### Register
``` ```
int32_t(* SensorInterface::Register) ([in] int32_t groupId,[in] RecordDataCallback cb) int32_t(* SensorInterface::Register) ([in] int32_t groupId,[in] RecordDataCallback cb)
``` ```
...@@ -121,10 +121,10 @@ int32_t(* SensorInterface::Register) ([in] int32_t groupId,[in] RecordDataCallba ...@@ -121,10 +121,10 @@ int32_t(* SensorInterface::Register) ([in] int32_t groupId,[in] RecordDataCallba
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| groupId | 传感器组ID。&nbsp;sensorId枚举值范围为128-160,表示已订阅医疗传感器服务,只需成功订阅一次,无需重复订阅。&nbsp;sensorId枚举值范围不在128-160之间,这意味着传统传感器已订阅,只需成功订阅一次,无需重复订阅。 | | groupId | 传感器组ID。&nbsp;sensorId枚举值范围为128-160,表示已订阅医疗传感器服务,只需成功订阅一次,无需重复订阅。&nbsp;sensorId枚举值范围不在128-160之间,这意味着传统传感器已订阅,只需成功订阅一次,无需重复订阅。 |
| cb | 要注册的回调函数,详见[RecordDataCallback](_sensor.md#recorddatacallback)。 | | cb | 要注册的回调函数,详见[RecordDataCallback](_sensor.md#recorddatacallback)。 |
**返回:** **返回:**
...@@ -135,7 +135,7 @@ int32_t(* SensorInterface::Register) ([in] int32_t groupId,[in] RecordDataCallba ...@@ -135,7 +135,7 @@ int32_t(* SensorInterface::Register) ([in] int32_t groupId,[in] RecordDataCallba
### SetBatch ### SetBatch
``` ```
int32_t(* SensorInterface::SetBatch) ([in] int32_t sensorId,[in] int64_t samplingInterval,[in] int64_t reportInterval) int32_t(* SensorInterface::SetBatch) ([in] int32_t sensorId,[in] int64_t samplingInterval,[in] int64_t reportInterval)
``` ```
...@@ -146,11 +146,11 @@ int32_t(* SensorInterface::SetBatch) ([in] int32_t sensorId,[in] int64_t samplin ...@@ -146,11 +146,11 @@ int32_t(* SensorInterface::SetBatch) ([in] int32_t sensorId,[in] int64_t samplin
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 | | sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 |
| samplingInterval | 设置指定传感器的数据采样间隔,单位纳秒。 | | samplingInterval | 设置指定传感器的数据采样间隔,单位纳秒。 |
| reportInterval | 表示传感器数据上报间隔,单位纳秒。 | | reportInterval | 表示传感器数据上报间隔,单位纳秒。 |
**返回:** **返回:**
...@@ -161,7 +161,7 @@ int32_t(* SensorInterface::SetBatch) ([in] int32_t sensorId,[in] int64_t samplin ...@@ -161,7 +161,7 @@ int32_t(* SensorInterface::SetBatch) ([in] int32_t sensorId,[in] int64_t samplin
### SetMode ### SetMode
``` ```
int32_t(* SensorInterface::SetMode) ([in] int32_t sensorId,[in] int32_t mode) int32_t(* SensorInterface::SetMode) ([in] int32_t sensorId,[in] int32_t mode)
``` ```
...@@ -172,10 +172,10 @@ int32_t(* SensorInterface::SetMode) ([in] int32_t sensorId,[in] int32_t mode) ...@@ -172,10 +172,10 @@ int32_t(* SensorInterface::SetMode) ([in] int32_t sensorId,[in] int32_t mode)
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 | | sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 |
| mode | 传感器的数据上报模式,详见[SensorModeType](_sensor.md#sensormodetype)。 | | mode | 传感器的数据上报模式,详见[SensorModeType](_sensor.md#sensormodetype)。 |
**返回:** **返回:**
...@@ -186,7 +186,7 @@ int32_t(* SensorInterface::SetMode) ([in] int32_t sensorId,[in] int32_t mode) ...@@ -186,7 +186,7 @@ int32_t(* SensorInterface::SetMode) ([in] int32_t sensorId,[in] int32_t mode)
### SetOption ### SetOption
``` ```
int32_t(* SensorInterface::SetOption) ([in] int32_t sensorId,[in] uint32_t option) int32_t(* SensorInterface::SetOption) ([in] int32_t sensorId,[in] uint32_t option)
``` ```
...@@ -197,10 +197,10 @@ int32_t(* SensorInterface::SetOption) ([in] int32_t sensorId,[in] uint32_t optio ...@@ -197,10 +197,10 @@ int32_t(* SensorInterface::SetOption) ([in] int32_t sensorId,[in] uint32_t optio
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 | | sensorId | 唯一标识一个传感器设备类型,详见[SensorTypeTag](_sensor.md#sensortypetag)。 |
| option | 传感器的量程、精度等配置。 | | option | 传感器的量程、精度等配置。 |
**返回:** **返回:**
...@@ -211,21 +211,21 @@ int32_t(* SensorInterface::SetOption) ([in] int32_t sensorId,[in] uint32_t optio ...@@ -211,21 +211,21 @@ int32_t(* SensorInterface::SetOption) ([in] int32_t sensorId,[in] uint32_t optio
### Unregister ### Unregister
``` ```
int32_t(* SensorInterface::Unregister) ([in] int32_t groupId,[in] RecordDataCallback cb) int32_t(* SensorInterface::Unregister) ([in] int32_t groupId,[in] RecordDataCallback cb)
``` ```
**描述:** **描述:**
订阅者注册传感器数据回调函数。 订阅者取消注册传感器数据回调函数。
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| groupId | 传感器组ID。&nbsp;sensorId枚举值范围为128-160,表示已订阅医疗传感器服务。只需成功取消订阅一次,无需重复取消订阅。&nbsp;sensorId枚举值范围不在128-160之间,这意味着传统传感器已订阅。并且成功取消订阅。 | | groupId | 传感器组ID。&nbsp;sensorId枚举值范围为128-160,表示已订阅医疗传感器服务。只需成功取消订阅一次,无需重复取消订阅。&nbsp;sensorId枚举值范围不在128-160之间,这意味着传统传感器已订阅。并且成功取消订阅。 |
| cb | 要注册的回调函数,详见[RecordDataCallback](_sensor.md#recorddatacallback)。 | | cb | 要取消注册的回调函数,详见[RecordDataCallback](_sensor.md#recorddatacallback)。 |
**返回:** **返回:**
......
...@@ -15,10 +15,17 @@ ...@@ -15,10 +15,17 @@
| 类 | 描述 | | 类 | 描述 |
| -------- | -------- | | -------- | -------- |
| [EventPackage](_event_package.md) | Input事件数据包结构&nbsp;[更多...](_event_package.md) | | [InputEventPackage](_event_package.md) | Input事件数据包结构。&nbsp;[更多...](_event_package.md) |
| [InputReportEventCb](_input_report_event_cb.md) | 此结构体定义了输入事件回调函数并提供给Input服务使用&nbsp;[更多...](_input_report_event_cb.md) | | [InputHotPlugEvent](_input_hotplug_event.md) | 热插拔事件数据包结构。&nbsp;[更多...](_input_hotplug_event.md) |
| [DeviceInfo](_device_info.md) | Input设备基础设备信息&nbsp;[更多...](_device_info.md) | | [InputDevDesc](_input_dev_desc.md) | Input设备描述信息。&nbsp;[更多...](_input_dev_desc.md) |
| [InputExtraCmd](_input_extra_cmd.md) | 扩展指令的数据结构&nbsp;[更多...](_input_extra_cmd.md) | | [InputEventCb](_input_report_event_cb.md) | 此结构体定义了输入事件回调函数并提供给Input服务使用。&nbsp;[更多...](_input_report_event_cb.md) |
| [InputHostCb](_input_host_cb.md) | 此结构体定义了热插拔事件上报回调函数并提供给Input服务使用。&nbsp;[更多...](_input_host_cb.md) |
| [InputDevAbility](_input_dev_ability.md) | Input设备的能力属性,存储支持事件的位图。&nbsp;[更多...](_input_dev_ability.md) |
| [InputDimensionInfo](_input_dimension_info.md) | Input设备的维度信息。&nbsp;[更多...](_input_dimension_info.md) |
| [InputDevIdentify](_input_dev_identify.md) | Input设备的识别信息。&nbsp;[更多...](_input_dev_identify.md) |
| [InputDevAttr](_input_dev_attr.md) | Input设备属性。&nbsp;[更多...](_input_dev_attr.md) |
| [InputDeviceInfo](_device_info.md) | Input设备基础设备信息。&nbsp;[更多...](_device_info.md) |
| [InputExtraCmd](_input_extra_cmd.md) | 扩展指令的数据结构。&nbsp;[更多...](_input_extra_cmd.md) |
### 宏定义 ### 宏定义
...@@ -42,10 +49,10 @@ ...@@ -42,10 +49,10 @@
| 枚举 | 描述 | | 枚举 | 描述 |
| -------- | -------- | | -------- | -------- |
| [RetStatus](_input.md#retstatus)&nbsp;{&nbsp;INPUT_SUCCESS&nbsp;=&nbsp;0,&nbsp;INPUT_FAILURE&nbsp;=&nbsp;-1,&nbsp;INPUT_INVALID_PARAM&nbsp;=&nbsp;-2,&nbsp;INPUT_NOMEM&nbsp;=&nbsp;-3,&nbsp;&nbsp;&nbsp;INPUT_NULL_PTR&nbsp;=&nbsp;-4,&nbsp;INPUT_TIMEOUT&nbsp;=&nbsp;-5,&nbsp;INPUT_UNSUPPORTED&nbsp;=&nbsp;-6&nbsp;} | 定义返回值类型&nbsp;[更多...](_input.md#retstatus) | | [RetStatus](_input.md#retstatus)&nbsp;{&nbsp;INPUT_SUCCESS&nbsp;=&nbsp;0,&nbsp;INPUT_FAILURE&nbsp;=&nbsp;-1,&nbsp;INPUT_INVALID_PARAM&nbsp;=&nbsp;-2,&nbsp;INPUT_NOMEM&nbsp;=&nbsp;-3,&nbsp;&nbsp;&nbsp;INPUT_NULL_PTR&nbsp;=&nbsp;-4,&nbsp;INPUT_TIMEOUT&nbsp;=&nbsp;-5,&nbsp;INPUT_UNSUPPORTED&nbsp;=&nbsp;-6&nbsp;} | 定义返回值类型&nbsp;[更多...](_input.md#retstatus) |
| [InputDevType](_input.md#inputdevtype)&nbsp;{&nbsp;INDEV_TYPE_TOUCH,&nbsp;INDEV_TYPE_KEY,&nbsp;INDEV_TYPE_KEYBOARD,&nbsp;INDEV_TYPE_MOUSE,&nbsp;&nbsp;&nbsp;INDEV_TYPE_BUTTON,&nbsp;INDEV_TYPE_CROWN,&nbsp;INDEV_TYPE_ENCODER,&nbsp;INDEV_TYPE_UNKNOWN&nbsp;} | 定义Input设备类型&nbsp;[更多...](_input.md#inputdevtype) | | [InputDevType](_input.md#inputdevtype)&nbsp;{&nbsp;INDEV_TYPE_TOUCH,&nbsp;INDEV_TYPE_KEY,&nbsp;INDEV_TYPE_KEYBOARD,&nbsp;INDEV_TYPE_MOUSE,&nbsp;&nbsp;&nbsp;INDEV_TYPE_BUTTON,&nbsp;INDEV_TYPE_CROWN,&nbsp;INDEV_TYPE_ENCODER,&nbsp;INDEV_TYPE_UNKNOWN&nbsp;} | 定义Input设备类型&nbsp;[更多...](_input.md#inputdevtype) |
| [PowerStatus](_input.md#powerstatus)&nbsp;{&nbsp;INPUT_RESUME,&nbsp;INPUT_SUSPEND,&nbsp;INPUT_LOW_POWER,&nbsp;INPUT_POWER_STATUS_UNKNOWN&nbsp;} | 定义电源状态&nbsp;[更多...](_input.md#powerstatus) | | [PowerStatus](_input.md#powerstatus)&nbsp;{&nbsp;INPUT_RESUME,&nbsp;INPUT_SUSPEND,&nbsp;INPUT_LOW_POWER,&nbsp;INPUT_POWER_STATUS_UNKNOWN&nbsp;} | 定义电源状态&nbsp;[更多...](_input.md#powerstatus) |
| [CapacitanceTest](_input.md#capacitancetest)&nbsp;{&nbsp;BASE_TEST,&nbsp;FULL_TEST,&nbsp;MMI_TEST,&nbsp;RUNNING_TEST,&nbsp;&nbsp;&nbsp;TEST_TYPE_UNKNOWN&nbsp;} | 定义容值测试类型&nbsp;[更多...](_input.md#capacitancetest) | | [CapacitanceTest](_input.md#capacitancetest)&nbsp;{&nbsp;BASE_TEST,&nbsp;FULL_TEST,&nbsp;MMI_TEST,&nbsp;RUNNING_TEST,&nbsp;&nbsp;&nbsp;TEST_TYPE_UNKNOWN&nbsp;} | 定义容值测试类型&nbsp;[更多...](_input.md#capacitancetest) |
## **详细描述** ## **详细描述**
......
...@@ -13,11 +13,11 @@ ...@@ -13,11 +13,11 @@
### 类 ### 类
| 类 | 描述 | | 类 | 描述 |
| -------- | -------- | | -------- | -------- |
| LightFlashEffect | 定义闪烁参数。&nbsp;[更多...](_light_flash_effect.md) | | LightFlashEffect | 定义闪烁参数。&nbsp;[更多...](_light_flash_effect.md) |
| LightEffect | 定义灯的效果参数。&nbsp;[更多...](_light_effect.md) | | LightEffect | 定义灯的效果参数。&nbsp;[更多...](_light_effect.md) |
| LightInfo | 定义灯的基本信息。&nbsp;[更多...](_light_info.md) | | LightInfo | 定义灯的基本信息。&nbsp;[更多...](_light_info.md) |
## **详细描述** ## **详细描述**
...@@ -27,3 +27,7 @@ ...@@ -27,3 +27,7 @@
**Since:** **Since:**
3.1 3.1
**Version:**
1.0
\ No newline at end of file
...@@ -13,23 +13,28 @@ ...@@ -13,23 +13,28 @@
### 类 ### 类
| 类 | 描述 | | 类 | 描述 |
| -------- | -------- | | -------- | -------- |
| [LightInterface](_light_interface.md) | 定义可以在灯上执行的基本操作。&nbsp;[更多...](_light_interface.md) | | [LightInterface](_light_interface.md) | 定义可以在灯上执行的基本操作。&nbsp;[更多...](_light_interface.md) |
### 函数 ### 函数
| 函数 | 描述 | | 函数 | 描述 |
| -------- | -------- | | -------- | -------- |
| [NewLightInterfaceInstance](_light.md#newlightinterfaceinstance)&nbsp;(void) | 创建LightInterface实例。&nbsp;[更多...](_light.md#newlightinterfaceinstance) | | [NewLightInterfaceInstance](_light.md#newlightinterfaceinstance)&nbsp;(void) | 创建LightInterface实例。&nbsp;[更多...](_light.md#newlightinterfaceinstance) |
| [FreeLightInterfaceInstance](_light.md#freelightinterfaceinstance)&nbsp;(void) | 释放LightInterface实例和相关资源。&nbsp;[更多...](_light.md#freelightinterfaceinstance) | | [FreeLightInterfaceInstance](_light.md#freelightinterfaceinstance)&nbsp;(void) | 释放LightInterface实例和相关资源。&nbsp;[更多...](_light.md#freelightinterfaceinstance) |
## **详细描述** ## **详细描述**
声明light模块的通用API,可用于获取灯ID、打开或关闭灯、并设置灯光亮度和闪烁模式。 声明light模块的通用API,可用于获取灯ID、打开或关闭灯、并设置灯光亮度和闪烁模式。
**Sinc[更多...](_light_flash_effect.md)e更多...[更多...](_light_info.md):** **Since:**
3.1 3.1
**Version:**
1.0
...@@ -13,22 +13,22 @@ ...@@ -13,22 +13,22 @@
### 类 ### 类
| 类 | 描述 | | 类 | 描述 |
| -------- | -------- | | -------- | -------- |
| [SensorInterface](_sensor_interface.md) | 提供sensor设备基本控制操作接口。&nbsp;[更多...](_sensor_interface.md) | | [SensorInterface](_sensor_interface.md) | 提供sensor设备基本控制操作接口。&nbsp;[更多...](_sensor_interface.md) |
### 函数 ### 函数
| 函数 | 描述 | | 函数 | 描述 |
| -------- | -------- | | -------- | -------- |
| [NewSensorInterfaceInstance](_sensor.md#newsensorinterfaceinstance)&nbsp;(void) | 创建传感器接口实例。&nbsp;[更多...](_sensor.md#newsensorinterfaceinstance) | | [NewSensorInterfaceInstance](_sensor.md#newsensorinterfaceinstance)&nbsp;(void) | 创建传感器接口实例。&nbsp;[更多...](_sensor.md#newsensorinterfaceinstance) |
| [FreeSensorInterfaceInstance](_sensor.md#freesensorinterfaceinstance)&nbsp;(void) | 释放传感器接口实例。&nbsp;[更多...](_sensor.md#freesensorinterfaceinstance) | | [FreeSensorInterfaceInstance](_sensor.md#freesensorinterfaceinstance)&nbsp;(void) | 释放传感器接口实例。&nbsp;[更多...](_sensor.md#freesensorinterfaceinstance) |
## **详细描述** ## **详细描述**
Sensor模块对外通用的接口声明文件,提供获取传感器设备信息、订阅/订阅传感器数据、 使能/去使能传感器、设置传感器模式、设置传感器精度,量程等可选配置接口定义。 Sensor模块对外通用的接口声明文件,提供获取传感器设备信息、订阅/取消订阅传感器数据、 使能/去使能传感器、设置传感器模式、设置传感器精度,量程等可选配置接口定义。
**Since:** **Since:**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册