提交 38815321 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 a77a2f35
......@@ -63,7 +63,7 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
});
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
......@@ -88,7 +88,7 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
});
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
......@@ -107,7 +107,7 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
......@@ -118,7 +118,7 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
});
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
......
......@@ -190,7 +190,7 @@ TLS Socket connection process on the client:
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
......@@ -200,10 +200,10 @@ TLS Socket connection process on the client:
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
tlsTwoWay.on('close', () => {
console.log("on close")
});
......@@ -246,23 +246,23 @@ TLS Socket connection process on the client:
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tcp.on('message', value => {
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
......@@ -272,10 +272,10 @@ TLS Socket connection process on the client:
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
tlsTwoWay.on('close', () => {
console.log("on close")
});
......@@ -307,16 +307,16 @@ TLS Socket connection process on the client:
console.log(data);
});
// Enable the TLS Socket connection to be automatically closed after use. Then, disable listening for TLS Socket connection events.
tls.close((err) => {
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tls.off('message');
tls.off('connect');
tls.off('close');
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
```
......
# Development of Application Recovery
# Application Recovery Development
## When to Use
......@@ -15,11 +15,11 @@ The application recovery APIs are provided by the **appRecovery** module, which
### Available APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. |
| saveAppState(): boolean; | Saves the ability status of an application. |
| restartApp(): void; | Restarts the current process. If there is saved ability status, it will be passed to the **want** parameter's **wantParam** attribute of the **onCreate** lifecycle callback of the ability.|
| API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- |
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function.|
| saveAppState(): boolean; | Saves the ability status of an application. |
| restartApp(): void; | Restarts the current process. If there is saved ability status, it will be passed to the **want** parameter's **wantParam** attribute of the **onCreate** lifecycle callback of the ability.|
The APIs are used for troubleshooting and do not return any exception. Therefore, you need to be familiar with when they are used.
......@@ -40,21 +40,24 @@ Fault management is an important way for applications to deliver a better user e
- Fault query indicates that [faultLogger](../reference/apis/js-apis-faultLogger.md) obtains the fault information using its query API.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to [LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query the information about the last fault.
![Fault rectification process](./figures/fault_rectification.png)
It is recommended that you call [errorManager](../reference/apis/js-apis-app-ability-errorManager.md) to process the exception. After the processing is complete, you can call the status saving API and restart the application.
If you do not register [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen.
If you have enabled application recovery, the framework first checks whether a fault allows for ability status saving and whether you have configured ability status saving. If so, [onSaveState](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](../reference/apis/js-apis-app-ability-uiAbility.md) is called back. Finally, the application is restarted.
### Scenarios Supported by Application Fault Management APIs
Common fault types include JavaScript application crash, application freezing, and C++ application crash. Generally, an application is closed when a crash occurs. Application freezing occurs when the application does not respond. The fault type can be ignored for the upper layer of an application. The recovery framework implements fault management in different scenarios based on the fault type.
| Fault | Fault Listening| Status Saving| Automatic Restart| Log Query|
| ------------------------------------------------------------ | -------- | -------- | -------- | -------- |
| [JS_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Supported | Supported | Supported | Supported |
| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported | Not supported | Supported | Supported |
| [CPP_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported | Not supported | Not supported | Supported |
| Fault | Fault Listening | Status Saving| Automatic Restart| Log Query|
| ----------|--------- |--------- |--------- |--------- |
| [JS_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Supported|Supported|Supported|Supported|
| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported|Not supported|Supported|Supported|
| [CPP_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported|Not supported|Not supported|Supported|
**Status Saving** in the table header means status saving when a fault occurs. To protect user data as much as possible in the application freezing fault, you can adopt either the periodic or automatic way, and the latter will save user data when an ability is switched to the background.
......@@ -95,7 +98,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
#### Actively Saving Status and Restoring Data
- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback.
- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback.
```ts
var registerId = -1;
......@@ -108,7 +111,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
}
onWindowStageCreate(windowStage) {
// Main window is created. Set a main page for this ability.
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate")
globalThis.registerObserver = (() => {
......@@ -125,7 +128,7 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
```ts
onSaveState(state, wantParams) {
// Save application data.
// Ability has called to save app data
console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
......@@ -150,11 +153,11 @@ onCreate(want, launchParam) {
}
```
- Deregister **ErrorObserver callback**.
- Unregister **ErrorObserver callback**.
```ts
onWindowStageDestroy() {
// Main window is destroyed to release UI resources.
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => {
......@@ -184,7 +187,7 @@ export default class MainAbility extends Ability {
}
onSaveState(state, wantParams) {
// Save application data.
// Ability has called to save app data
console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
......
......@@ -2,7 +2,7 @@
The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. For more details about APIs and their usage, see [intl](../reference/apis/js-apis-intl.md).
The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
The [i18n](../reference/apis/js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
## Setting Locale Information
......@@ -111,7 +111,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
let dateTimeFormat = new Intl.DateTimeFormat();
```
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions).
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions9).
```js
let options = {dateStyle: "full", timeStyle: "full"};
......@@ -150,7 +150,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
let resolvedOptions = dateTimeFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "calendar": "gregorian", "dateStyle":"full", "timeStyle":"full", "timeZone": "CST"}
```
## Number Formatting
## Formatting Numbers
[NumberFormat](../reference/apis/js-apis-intl.md#numberformat) provides APIs to implement the number formatting specific to a locale.
......@@ -181,7 +181,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
let numberFormat = new Intl.NumberFormat();
```
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions).
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions9).
```js
let options = {compactDisplay: "short", notation: "compact"};
......@@ -209,7 +209,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
let resolvedOptions = numberFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "compactDisplay": "short", "notation": "compact", "numberingSystem": "Latn"}
```
## String Sorting
## Sorting Strings
Users in different regions have different requirements for string sorting. [Collator](../reference/apis/js-apis-intl.md#collator8) provides APIs to sort character strings specific to a locale.
......@@ -317,7 +317,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let categoryResult = pluralRules.select(number); // categoryResult = "other"
```
## Formatting Relative Time
## Formatting the Relative Time
[RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) provides APIs to format the relative time for a specific locale.
......
......@@ -148,7 +148,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal
## ServiceExtensionAbility.onDisconnect
onDisconnect(want: Want): void | Promise<void>;
onDisconnect(want: Want): void | Promise\<void>;
Called when a client is disconnected from this ServiceExtensionAbility.
......
......@@ -5,7 +5,7 @@ The **fileio** module provides APIs for file storage and management, including b
> **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 APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.fs](./js-apis-file-fs.md).
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.fs](js-apis-file-fs.md).
## Modules to Import
......
# @ohos.hiAppEvent (Application Event Logging)
The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
The **hiAppEvent** module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE**
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
......@@ -19,7 +19,7 @@ Before using application event logging, you need to understand the requirements
**Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
**Event Type**
......@@ -30,9 +30,10 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
- The parameter value is a string, number, boolean, or array.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated.
- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The parameter value can be of the string, number, boolean, or array type.
- If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded.
- If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated.
- If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.
**Event Callback**
......
......@@ -69,7 +69,7 @@ DEBUG logs are not recorded in official versions by default. They are available
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example**
......@@ -100,7 +100,7 @@ Prints INFO logs.
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example**
......@@ -131,7 +131,7 @@ Prints WARN logs.
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example**
......@@ -162,7 +162,7 @@ Prints ERROR logs.
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example**
......@@ -193,7 +193,7 @@ Prints FATAL logs.
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
**Example**
......
......@@ -2,7 +2,8 @@
The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -119,12 +120,12 @@ Defines parameters for an **AppEventInfo** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ---------- |
| domain | string | Yes | Event domain.|
| name | string | Yes | Event name.|
| eventType | [EventType](#eventtype) | Yes | Event type.|
| params | object | Yes | Event parameters.|
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| eventType | [EventType](#eventtype) | Yes | Event type. |
| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<br>- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).<br>- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
## hiAppEvent.configure
......@@ -447,27 +448,27 @@ Enumerates event types.
| BEHAVIOR | 4 | Behavior event.|
## Event
## event
Provides constants that define the names of all predefined events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Readable| Writable| Description |
| ------------------------- | ------ | ---- | ---- | -------------------- |
| USER_LOGIN | string | Yes | No | User login event. |
| USER_LOGOUT | string | Yes | No | User logout event. |
| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.|
| Name | Type | Description |
| ------------------------- | ------ | -------------------- |
| USER_LOGIN | string | User login event. |
| USER_LOGOUT | string | User logout event. |
| DISTRIBUTED_SERVICE_START | string | Distributed service startup event.|
## Param
## param
Provides constants that define the names of all predefined event parameters.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Readable| Writable| Description |
| ------------------------------- | ------ | ---- | ---- | ------------------ |
| USER_ID | string | Yes | No | Custom user ID. |
| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.|
| Name | Type | Description |
| ------------------------------- | ------ | ------------------ |
| USER_ID | string | Custom user ID. |
| DISTRIBUTED_SERVICE_NAME | string | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID.|
......@@ -88,7 +88,7 @@ export default class EntryAbility extends UIAbility {
}
```
## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback<void>)
## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\<void>)
off(type: 'abilityLifecycle', callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
......@@ -202,7 +202,7 @@ export default class EntryAbility extends UIAbility {
}
```
## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback<void>)
## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback\<void>)
off(type: 'environment', callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
......@@ -327,7 +327,7 @@ applicationContext.getRunningProcessInformation((err, data) => {
## ApplicationContext.killProcessesBySelf<sup>9+</sup>
killProcessesBySelf(): Promise<void>;
killProcessesBySelf(): Promise\<void>;
Kills all the processes where the application is located. This API uses a promise to return the result.
......@@ -352,7 +352,7 @@ applicationContext.killProcessesBySelf().then((data) => {
## ApplicationContext.killProcessesBySelf<sup>9+</sup>
killProcessesBySelf(callback: AsyncCallback<void>);
killProcessesBySelf(callback: AsyncCallback\<void>);
Kills all the processes where the application is located. This API uses an asynchronous callback to return the result.
......
......@@ -106,7 +106,7 @@ Represents combination key options.
| Name | Type | Readable | Writable | Description |
| --------- | ------ | ---- | ---- | ------- |
| preKeys | Array<number> | Yes | No| Front key set. The number of front keys ranges from 0 to 4. There is no requirement on the sequence of the keys.|
| preKeys | Array\<number> | Yes | No| Front key set. The number of front keys ranges from 0 to 4. There is no requirement on the sequence of the keys.|
| finalKey | number | Yes | No| Final key. This parameter is mandatory. A callback function is triggered by the final key.|
| isFinalKeyDown | boolean | Yes | No| Whether the final key is pressed.|
| finalKeyDownDuration | number | Yes | No| Duration within which the final key is pressed. If the value is **0**, the callback function is triggered immediately. If the value is greater than **0** and the value of **isFinalKeyDown** is **true**, the callback function is triggered when the key press duration is longer than the value of this parameter. If the value of **isFinalKeyDown** is **false**, the callback function is triggered when the duration from key press to key release is less than the value of this parameter. |
......@@ -114,9 +114,9 @@ ethernet.setIfaceConfig("eth0", {
dnsServers: "1.1.1.1",
domain: "2.2.2.2"
}).then(() => {
console.log("setIfaceConfig promiss ok ");
console.log("setIfaceConfig promise ok ");
}).catch(error => {
console.log("setIfaceConfig promiss error = " + JSON.stringify(error));
console.log("setIfaceConfig promise error = " + JSON.stringify(error));
});
```
......@@ -207,15 +207,15 @@ Obtains the configuration of a network interface. This API uses a promise to ret
```js
ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promiss mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promiss ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promiss route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promiss gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promiss netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promiss dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promiss domain = " + JSON.stringify(data.domain));
console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => {
console.log("getIfaceConfig promiss error = " + JSON.stringify(error));
console.log("getIfaceConfig promise error = " + JSON.stringify(error));
});
```
......@@ -300,9 +300,9 @@ Checks whether a network interface is active. This API uses a promise to return
```js
ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promiss = " + JSON.stringify(data));
console.log("isIfaceActive promise = " + JSON.stringify(data));
}).catch(error => {
console.log("isIfaceActive promiss error = " + JSON.stringify(error));
console.log("isIfaceActive promise error = " + JSON.stringify(error));
});
```
......@@ -377,12 +377,12 @@ Obtains the list of all active network interfaces. This API uses a promise to re
```js
ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promiss data.length = " + JSON.stringify(data.length));
console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promiss = " + JSON.stringify(data[i]));
console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
}
}).catch(error => {
console.log("getAllActiveIfaces promiss error = " + JSON.stringify(error));
console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
});
```
......
......@@ -15,6 +15,7 @@ This error code is reported if the **write** API is called to perform applicatio
The application event logging function is disabled.
**Solution**
Invoke the **configure** API to enable the application event logging function.
```js
......@@ -41,6 +42,7 @@ The specified event domain name does not comply with the following rules:
- The event domain name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid event domain name.
## 11101002 Invalid Event Name
......
......@@ -26,15 +26,15 @@ Your feedback matters. Submit issues and leave as detailed information as possib
1. On the Gitee page, click the **Issues** tab. On the displayed page, click **New issue**. Then enter the issue title and issue details.
2. Click **New** to submit the issue. The Docs team will confirm the issue.
>![](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
>**How can I provide a high-quality issue?**
>
>- Provide a clear description of the issue, including the missing, outdated, incorrect, or to-be-improved content.
>- Explain the impact of this issue on users.
>- Limit the scope of the given issue to a specific task. If multiple fields are involved, break the issue down into smaller ones. For example, "Documents need to be optimized" is a broad issue, whereas "XX development guide lacks introduction to step XXX" is specific and operable.
>- Search the list of existing issues to see if any related or similar issues have been submitted.
>- If an issue is associated with another issue or a pull request (PR), you can use its full URL or the combination of the number sign (#) and PR number to reference it.
> **How can I provide a high-quality issue?**
>
> - Provide a clear description of the issue, including the missing, outdated, incorrect, or to-be-improved content.
> - Explain the impact of this issue on users.
> - Limit the scope of the given issue to a specific task. If multiple fields are involved, break the issue down into smaller ones. For example, "Documents need to be optimized" is a broad issue, whereas "XX development guide lacks introduction to step XXX" is specific and operable.
> - Search the list of existing issues to see if any related or similar issues have been submitted.
> - If an issue is associated with another issue or a pull request (PR), you can use its full URL or the combination of the number sign (#) and PR number to reference it.
### Editing Existing Documents
......
......@@ -60,8 +60,8 @@ Pictures used in **OpenHarmony\_DOCUMENTS/docs/quick-start/writing-instructions
Use relative paths to reference pictures in the document.
>![](public_sys-resources/icon-caution.gif) **CAUTION:**
>Use the original pictures to avoid intellectual property infringement risks.
> **CAUTION**
> Use the original pictures to avoid intellectual property infringement risks.
- Pictures are clear and complete. For example, a flowchart has a start and an end.
- The graphics has clear logic and are provided with text descriptions. Do not separate the graphics from the text.
......@@ -69,9 +69,9 @@ Use relative paths to reference pictures in the document.
- The text on pictures should be Chinese in Chinese documents and English in English documents.
- It is recommended that pictures be named based on the content. Using only a number is difficult for picture inheritance.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Reference:
>!\[\]\(./pic/pic-standard.png\)
> **NOTE**
> Reference:
> !\[\]\(./pic/pic-standard.png\)
If a self-made picture is used, refer to the following figure to configure the color. The format can be **png**, **jpg**, **gif**, and so on.
......
......@@ -53,10 +53,6 @@
- [Sensor Overview](subsys-sensor-overview.md)
- [Sensor Usage Guidelines](subsys-sensor-guide.md)
- [Sensor Usage Example](subsys-sensor-demo.md)
- USB
- [USB Overview](subsys-usbservice-overview.md)
- [USB Usage Guidelines](subsys-usbservice-guide.md)
- [USB Usage Example](subsys-usbservice-demo.md)
- Application Framework
- [Application Framework Overview](subsys-application-framework-overview.md)
- [Setting Up a Development Environment](subsys-application-framework-envbuild.md)
......
# USB Usage Example<a name="EN-US_TOPIC_0000001092792986"></a>
```cpp
#include <cstdio>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <sys/time.h>
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iremote_object.h"
#include "iservice_registry.h"
#include "iusb_srv.h"
#include "string_ex.h"
#include "system_ability_definition.h"
#include "usb_common.h"
#include "usb_device.h"
#include "usb_errors.h"
#include "usb_request.h"
#include "usb_server_proxy.h"
#include "usb_srv_client.h"
const int32_t REQUESTYPE = ((1 << 7) | (0 << 5) | (0 & 0x1f));
const int32_t REQUESTCMD = 6;
const int32_t VALUE = (2 << 8) + 0;
const int32_t TIMEOUT = 5000;
const int32_t ITFCLASS = 10;
const int32_t PRAMATYPE = 2;
const int32_t BUFFERLENGTH = 21;
void GetType(OHOS::USB::USBEndpoint &tep, OHOS::USB::USBEndpoint &outEp, bool &outEpFlg)
{
if ((tep.GetType() == PRAMATYPE)) {
if (tep.GetDirection() == 0) {
outEp = tep;
outEpFlg = true;
}
}
}
bool SelectEndpoint(OHOS::USB::USBConfig config,
std::vector<OHOS::USB::UsbInterface> interfaces,
OHOS::USB::UsbInterface &interface,
OHOS::USB::USBEndpoint &outEp,
bool &outEpFlg)
{
for (int32_t i = 0; i < config.GetInterfaceCount(); ++i) {
OHOS::USB::UsbInterface tif = interfaces[i];
std::vector<OHOS::USB::USBEndpoint> mEndpoints = tif.GetEndpoints();
for (int32_t j = 0; j < tif.GetEndpointCount(); ++j) {
OHOS::USB::USBEndpoint tep = mEndpoints[j];
if ((tif.GetClass() == ITFCLASS) && (tif.GetSubClass() == 0) && (tif.GetProtocol() == PRAMATYPE)) {
GetType(tep, outEp, outEpFlg);
}
}
if (outEpFlg) {
interface = interfaces[i];
return true;
}
std::cout << std::endl;
}
return false;
}
int OpenDeviceTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::UsbDevice device, OHOS::USB::USBDevicePipe &pip)
{
int ret = Instran.RequestRight(device.GetName());
std::cout << "device RequestRight ret = " << ret << std::endl;
if (0 != ret) {
std::cout << "device RequestRight failed = " << ret << std::endl;
}
ret = Instran.OpenDevice(device, pip);
return ret;
}
int CtrTransferTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::USBDevicePipe &pip)
{
std::cout << "usb_device_test : << Control Transfer >> " << std::endl;
std::vector<uint8_t> vData;
const OHOS::USB::UsbCtrlTransfer tctrl = {REQUESTYPE, REQUESTCMD, VALUE, 0, TIMEOUT};
int ret = Instran.ControlTransfer(pip, tctrl, vData);
if (ret != 0) {
std::cout << "control message read failed width ret = " << ret << std::endl;
} else {
}
std::cout << "control message read success" << std::endl;
return ret;
}
int ClaimTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::UsbInterface &interface,
bool interfaceFlg)
{
if (interfaceFlg) {
std::cout << "ClaimInterface InterfaceInfo:" << interface.ToString() << std::endl;
int ret = Instran.ClaimInterface(pip, interface, true);
if (ret != 0) {
std::cout << "ClaimInterface failed width ret = " << ret << std::endl;
} else {
std::cout << "ClaimInterface success" << std::endl;
}
}
return 0;
}
int BulkTransferTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::USBEndpoint &outEp,
bool interfaceFlg,
bool outEpFlg)
{
if (interfaceFlg) {
std::cout << "usb_device_test : << Bulk transfer start >> " << std::endl;
if (outEpFlg) {
uint8_t buffer[50] = "hello world 123456789";
std::vector<uint8_t> vData(buffer, buffer + BUFFERLENGTH);
int ret = Instran.BulkTransfer(pip, outEp, vData, TIMEOUT);
if (ret != 0) {
std::cout << "Bulk transfer write failed width ret = " << ret << std::endl;
} else {
std::cout << "Bulk transfer write success" << std::endl;
}
return ret;
}
}
return 0;
}
int main(int argc, char **argv)
{
std::cout << "usb_device_test " << std::endl;
static OHOS::USB::UsbSrvClient &Instran = OHOS::USB::UsbSrvClient::GetInstance();
// GetDevices
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = Instran.GetDevices(deviceList);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
if (deviceList.empty()) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
OHOS::USB::UsbDevice device = deviceList[0];
std::vector<OHOS::USB::USBConfig> configs = device.GetConfigs();
OHOS::USB::USBConfig config = configs[0];
std::vector<OHOS::USB::UsbInterface> interfaces = config.GetInterfaces();
OHOS::USB::UsbInterface interface;
OHOS::USB::USBEndpoint outEp;
bool interfaceFlg = false;
bool outEpFlg = false;
interfaceFlg = SelectEndpoint(config, interfaces, interface, outEp, outEpFlg);
// OpenDevice
std::cout << "usb_device_test : << OpenDevice >> test begin -> " << std::endl;
OHOS::USB::USBDevicePipe pip;
ret = OpenDeviceTest(Instran, device, pip);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
// ControlTransfer
CtrTransferTest(Instran, pip);
// ClaimInterface
ClaimTest(Instran, pip, interface, interfaceFlg);
// BulkTransferWrite
BulkTransferTest(Instran, pip, outEp, interfaceFlg, outEpFlg);
// CloseDevice
std::cout << "usb_device_test : << Close Device >> " << std::endl;
ret = Instran.Close(pip);
if (ret == 0) {
std::cout << "Close device failed width ret = " << ret << std::endl;
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
} else {
std::cout << "Close Device success" << std::endl;
}
return 0;
}
```
# USB Usage Guidelines<a name="EN-US_TOPIC_0000001077367159"></a>
The following procedure uses bulk transfer as an example.
## Procedure<a name="section18816105182315"></a>
1. Obtain a USB service instance.
```cpp
static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance();
```
2. Obtain the USB device list.
```cpp
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = g_usbClient.GetDevices(deviceList);
```
3. Apply for device access permissions.
```cpp
int32_t ret = g_usbClient.RequestRight(device.GetName());
```
4. Open the USB device.
```cpp
USBDevicePipe pip;
int32_t et = g_usbClient.OpenDevice(device, pip);
```
5. Configure the USB interface.
```cpp
ret = g_usbClient.ClaimInterface(pip, interface, true); // **interface** indicates an interface of the USB device in **deviceList**.
```
6. Transfer data.
```cpp
srvClient.BulkTransfer(pipe, endpoint, vdata, timeout);
```
Parameter description:
- **pipe**: pipe for data transfer of the USB device opened.
- **endpoint**: endpoint for data transfer on the USB device.
- **vdata**: binary data block to be transferred or read.
- **timeout**: timeout duration of data transfer.
7. Close the USB device.
```cpp
ret = g_usbClient.Close(pip);
```
# USB
## Introduction
### Function Description
USB devices are classified into two types: USB host and USB device. On OpenHarmony, you can use the port service to switch between the host mode and device mode. In host mode, you can obtain the list of connected USB devices, manage device access permissions, and perform bulk transfer or control transfer between the host and connected devices. In device mode, you can switch between functions including HDC (debugging), ACM (serial port), and ECM (Ethernet port).
### Basic Concepts
- USB service
An abstraction of underlying hardware-based USB devices. Your application can access the USB devices via the USB service. With the APIs provided by the USB service, you can obtain the list of connected USB devices, manage device access permissions, and perform data transfer or control transfer between the host and connected devices.
- USB API
A collection of JS APIs provided for the upper layer through NAPI. Your application can use USB APIs to implement various basic functions, for example, query of the USB device list, USB device plug notification, USB host and device mode switching, bulk transfer, control transfer, right management, and function switching in device mode.
- USB Service layer
A layer implemented by using the C++ programming language. It consists of four modules: Host, Device, Port, and Right. HDI-based APIs provided by USB Service are mainly used to implement management of USB device list, USB functions, USB ports, and USB device access permissions. The USB Service layer interacts with the HAL layer to receive, parse, and distribute data, manages foreground and background policies, and performs USB device management and right control.
- USB HAL layer
A layer implemented by using the C programming language. Based on the Host Driver Development Kit (SDK) and Device DDK, USB HAL encapsulates basic USB device operations, provides C++ APIs for the upper layer, and receives information from the kernel through the Hardware Driver Foundation (HDF) framework.
### Working Principles
The USB subsystem logically consists of three parts: USB API, USB Service, and USB HAL. The following figure shows how the USB service is implemented.
**Figure 1** USB service architecture
![USB service architecture](figures/en-us_image_0000001267088285.png)
- USB API: provides USB APIs that implement various basic functions, for example, query of the USB device list, bulk data transfer, control transfer, and right management.
- USB Service: receives, parses, and distributes Hardware Abstraction Layer (HAL) data, manages and controls foreground and background policies, and manages devices.
- USB HAL: provides driver capability APIs that can be directly called in user mode.
## Usage Guidelines
### When to Use
In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
### APIs
**Table 1** Host-specific APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); | Opens a USB device to set up a connection. |
| bool HasRight(std::string deviceName); | Checks whether the application has the permission to access the device. |
| int32_t RequestRight(std::string deviceName); | Requests the temporary permission for a given application to access the USB device. |
| int32_t GetDevices(std::vector &deviceList); | Obtains the USB device list. |
| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); | Claims a USB interface exclusively. This must be done before data transfer. |
| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); | Releases a USB interface. This is usually done after data transfer. |
| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector &vdata, int32_t timeout); | Performs a bulk transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction.|
| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector &vdata); | Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. |
| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); | Sets the current configuration of the USB device. |
| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); | Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings.|
| int32_t GetRawDescriptors(std::vector &vdata); | Obtains the raw USB descriptor. |
| int32_t GetFileDescriptor(); | Obtains the file descriptor. |
| bool Close(const USBDevicePipe &pip); | Closes a USB device to release all system resources related to the device. |
| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); | Obtains the isochronous transfer result. |
| int32_t RequestInitialize(UsbRequest &request); | Initializes the isochronous transfer request. |
| int32_t RequestFree(UsbRequest &request); | Frees the isochronous transfer request. |
| int32_t RequestAbort(UsbRequest &request); | Cancels the data transfer request to be processed. |
| int32_t RequestQueue(UsbRequest &request); | Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction.|
| int32_t RegBulkCallback(USBDevicePipe &pip, const USBEndpoint &endpoint, const sptr<IRemoteObject> &cb); | Registers an asynchronous callback for bulk transfer. |
| int32_t UnRegBulkCallback(USBDevicePipe &pip, const USBEndpoint &endpoint); | Unregisters the asynchronous callback for bulk transfer. |
| int32_t BulkRead(USBDevicePipe &pip, const USBEndpoint &endpoint, sptr<Ashmem> &ashmem); | Reads data asynchronously during bulk transfer. |
| int32_t BulkWrite(USBDevicePipe &pip, const USBEndpoint &endpoint, sptr<Ashmem> &ashmem); | Writes data asynchronously during bulk transfer. |
| int32_t BulkCancel(USBDevicePipe &pip, const USBEndpoint &endpoint); | Cancels bulk transfer. The asynchronous read and write operations on the current USB interface will be cancelled. |
**Table 2** Device-specific APIs
| API | Description |
| -------------------------------------------------- | ------------------------------------------------------ |
| int32_t GetCurrentFunctions(int32_t &funcs); | Obtains the numeric mask combination for the current USB function list in Device mode. |
| int32_t SetCurrentFunctions(int32_t funcs); | Sets the current USB function list in Device mode. |
| int32_t UsbFunctionsFromString(std::string funcs); | Converts the string descriptor of a given USB function list to a numeric mask combination.|
| std::string UsbFunctionsToString(int32_t funcs); | Converts the numeric mask combination of a given USB function list to a string descriptor.|
**Table 3** Port-specific APIs
| API | Description |
| ------------------------------------------------------------ | -------------------------------------------------------- |
| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); | Obtains the mask combination for the supported mode list of a given port. |
| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer).|
| int32_t GetPorts(std::vector &usbPorts); | Obtains the USB port descriptor list. |
### How to Use
The following uses bulk transfer as an example to illustrate the development procedure.
1. Obtain a USB service instance.
```cpp
static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance();
```
2. Obtain the USB device list.
```cpp
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = g_usbClient.GetDevices(deviceList);
```
3. Apply for device access permissions.
```cpp
int32_t ret = g_usbClient.RequestRight(device.GetName());
```
4. Open a camera device.
```cpp
USBDevicePipe pip;
int32_t et = g_usbClient.OpenDevice(device, pip);
```
5. Configure the USB interface.
```cpp
// interface indicates an interface of the USB device in deviceList.
ret = g_usbClient.ClaimInterface(pip, interface, true);
```
6. Perform data transfer.
```cpp
// pipe indicates the pipe for data transfer after the USB device is opened. endpoint indicates the endpoint for data transfer on the USB device. vdata indicates the binary data block to be transferred or read. timeout indicates the timeout duration of data transfer.
srvClient.BulkTransfer(pipe, endpoint, vdata, timeout);
```
7. Closes a device.
```cpp
ret = g_usbClient.Close(pip);
```
### Sample Code
```cpp
#include <cstdio>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <sys/time.h>
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iremote_object.h"
#include "iservice_registry.h"
#include "iusb_srv.h"
#include "string_ex.h"
#include "system_ability_definition.h"
#include "usb_common.h"
#include "usb_device.h"
#include "usb_errors.h"
#include "usb_request.h"
#include "usb_server_proxy.h"
#include "usb_srv_client.h"
const int32_t REQUESTYPE = ((1 << 7) | (0 << 5) | (0 & 0x1f));
const int32_t REQUESTCMD = 6;
const int32_t VALUE = (2 << 8) + 0;
const int32_t TIMEOUT = 5000;
const int32_t ITFCLASS = 10;
const int32_t PRAMATYPE = 2;
const int32_t BUFFERLENGTH = 21;
void GetType(OHOS::USB::USBEndpoint &tep, OHOS::USB::USBEndpoint &outEp, bool &outEpFlg)
{
if ((tep.GetType() == PRAMATYPE)) {
if (tep.GetDirection() == 0) {
outEp = tep;
outEpFlg = true;
}
}
}
bool SelectEndpoint(OHOS::USB::USBConfig config,
std::vector<OHOS::USB::UsbInterface> interfaces,
OHOS::USB::UsbInterface &interface,
OHOS::USB::USBEndpoint &outEp,
bool &outEpFlg)
{
for (int32_t i = 0; i < config.GetInterfaceCount(); ++i) {
OHOS::USB::UsbInterface tif = interfaces[i];
std::vector<OHOS::USB::USBEndpoint> mEndpoints = tif.GetEndpoints();
for (int32_t j = 0; j < tif.GetEndpointCount(); ++j) {
OHOS::USB::USBEndpoint tep = mEndpoints[j];
if ((tif.GetClass() == ITFCLASS) && (tif.GetSubClass() == 0) && (tif.GetProtocol() == PRAMATYPE)) {
GetType(tep, outEp, outEpFlg);
}
}
if (outEpFlg) {
interface = interfaces[i];
return true;
}
std::cout << std::endl;
}
return false;
}
int OpenDeviceTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::UsbDevice device, OHOS::USB::USBDevicePipe &pip)
{
int ret = Instran.RequestRight(device.GetName());
std::cout << "device RequestRight ret = " << ret << std::endl;
if (0 != ret) {
std::cout << "device RequestRight failed = " << ret << std::endl;
}
ret = Instran.OpenDevice(device, pip);
return ret;
}
int CtrTransferTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::USBDevicePipe &pip)
{
std::cout << "usb_device_test : << Control Transfer >> " << std::endl;
std::vector<uint8_t> vData;
const OHOS::USB::UsbCtrlTransfer tctrl = {REQUESTYPE, REQUESTCMD, VALUE, 0, TIMEOUT};
int ret = Instran.ControlTransfer(pip, tctrl, vData);
if (ret != 0) {
std::cout << "control message read failed width ret = " << ret << std::endl;
} else {
}
std::cout << "control message read success" << std::endl;
return ret;
}
int ClaimTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::UsbInterface &interface,
bool interfaceFlg)
{
if (interfaceFlg) {
std::cout << "ClaimInterface InterfaceInfo:" << interface.ToString() << std::endl;
int ret = Instran.ClaimInterface(pip, interface, true);
if (ret != 0) {
std::cout << "ClaimInterface failed width ret = " << ret << std::endl;
} else {
std::cout << "ClaimInterface success" << std::endl;
}
}
return 0;
}
int BulkTransferTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::USBEndpoint &outEp,
bool interfaceFlg,
bool outEpFlg)
{
if (interfaceFlg) {
std::cout << "usb_device_test : << Bulk transfer start >> " << std::endl;
if (outEpFlg) {
uint8_t buffer[50] = "hello world 123456789";
std::vector<uint8_t> vData(buffer, buffer + BUFFERLENGTH);
int ret = Instran.BulkTransfer(pip, outEp, vData, TIMEOUT);
if (ret != 0) {
std::cout << "Bulk transfer write failed width ret = " << ret << std::endl;
} else {
std::cout << "Bulk transfer write success" << std::endl;
}
return ret;
}
}
return 0;
}
int main(int argc, char **argv)
{
std::cout << "usb_device_test " << std::endl;
static OHOS::USB::UsbSrvClient &Instran = OHOS::USB::UsbSrvClient::GetInstance();
// GetDevices
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = Instran.GetDevices(deviceList);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
if (deviceList.empty()) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
OHOS::USB::UsbDevice device = deviceList[0];
std::vector<OHOS::USB::USBConfig> configs = device.GetConfigs();
OHOS::USB::USBConfig config = configs[0];
std::vector<OHOS::USB::UsbInterface> interfaces = config.GetInterfaces();
OHOS::USB::UsbInterface interface;
OHOS::USB::USBEndpoint outEp;
bool interfaceFlg = false;
bool outEpFlg = false;
interfaceFlg = SelectEndpoint(config, interfaces, interface, outEp, outEpFlg);
// OpenDevice
std::cout << "usb_device_test : << OpenDevice >> test begin -> " << std::endl;
OHOS::USB::USBDevicePipe pip;
ret = OpenDeviceTest(Instran, device, pip);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
// ControlTransfer
CtrTransferTest(Instran, pip);
// ClaimInterface
ClaimTest(Instran, pip, interface, interfaceFlg);
// BulkTransferWrite
BulkTransferTest(Instran, pip, outEp, interfaceFlg, outEpFlg);
// CloseDevice
std::cout << "usb_device_test : << Close Device >> " << std::endl;
ret = Instran.Close(pip);
if (ret == 0) {
std::cout << "Close device failed width ret = " << ret << std::endl;
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
} else {
std::cout << "Close Device success" << std::endl;
}
return 0;
}
```
### Repositories Involved
[Driver subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/driver.md)
[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README_zh.md)
[drivers\_framework](https://gitee.com/openharmony/drivers_framework/blob/master/README_zh.md)
[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README_zh.md)
[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README_zh.md)
......@@ -195,9 +195,9 @@ The HCTest framework is used to support test cases developed with the C language
Test suites are built along with version build. The ACTS is built together with the debug version.
>![](public_sys-resources/icon-note.gif) **NOTE**
>
>The ACTS build middleware is a static library, which will be linked to the image.
> **NOTE**
>
> The ACTS build middleware is a static library, which will be linked to the image.
### C-based Test Case Execution \(for the Mini System\)
......@@ -334,9 +334,9 @@ The HCPPTest framework is enhanced and adapted based on the open-source framewor
Test suites are built along with the version build. The ACTS is built together with the debug version.
>![](public_sys-resources/icon-note.gif) **NOTE**
>
>The ACTS for the small system is independently built to an executable file \(.bin\) and archived in the **suites\\acts** directory of the build result.
> **NOTE**
>
> The ACTS for the small system is independently built to an executable file \(.bin\) and archived in the **suites\\acts** directory of the build result.
### C++-based Test Case Execution \(for Standard and Small Systems\)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册