未验证 提交 b8fcd58a 编写于 作者: O openharmony_ci 提交者: Gitee

!12357 翻译已完成10599+10646+10711+10687+10449

Merge pull request !12357 from shawn_he/10599-a
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## 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. In Host mode, you can obtain the list of connected USB devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
## APIs ## APIs
...@@ -16,6 +16,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -16,6 +16,7 @@ The following table lists the USB APIs currently available. For details, see the
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | | hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. | | requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| removeRight(deviceName: string): boolean | Removes the permission for a given application to access the USB device. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. | | connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. | | getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
......
...@@ -8,7 +8,7 @@ The event logging function helps applications log various information generated ...@@ -8,7 +8,7 @@ The event logging function helps applications log various information generated
JS application event logging APIs are provided by the **hiAppEvent** module. JS application event logging APIs are provided by the **hiAppEvent** module.
The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiappevent.md). The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiviewdfx-hiappevent.md).
**Table 1** APIs for application event logging **Table 1** APIs for application event logging
...@@ -17,17 +17,11 @@ The following table provides only a brief description of related APIs. For detai ...@@ -17,17 +17,11 @@ The following table provides only a brief description of related APIs. For detai
| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| | write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. | | write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. |
When an asynchronous callback is used, the return value can be processed directly in the callback.
If a promise is used, the return value can also be processed in the promise in a similar way.
For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
**Table 2** APIs for event logging configuration **Table 2** APIs for event logging configuration
| API | Description | | API | Description |
| --------------------------------------- | ---------------------------------------------------- | | ------------------------------------ | ---------------------------------------------------- |
| configure(ConfigOption config): boolean | Sets the configuration options for application event logging.| | configure(ConfigOption config): void | Sets the configuration options for application event logging.|
**Table 3** APIs for watcher management **Table 3** APIs for watcher management
...@@ -42,32 +36,14 @@ For details about the result codes, see [Event Verification Result Codes](#event ...@@ -42,32 +36,14 @@ For details about the result codes, see [Event Verification Result Codes](#event
| ----------------- | -------------------- | | ----------------- | -------------------- |
| clearData(): void | Clears local logging data.| | clearData(): void | Clears local logging data.|
### Event Verification Result Codes ## How to Develop
| Result Code| Cause | Verification Rules | Handling Method |
| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| 0 | N/A | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The name is not empty and contains a maximum of 48 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -2 | Invalid event parameter type | The event name must be a string.<br>The event type must be a number.<br>The event parameter must be an object.| Ignore this event and do not perform logging. |
| -4 | Invalid event domain name | The name is not empty and contains a maximum of 32 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -99 | Application event logging disabled | Application event logging is disabled. | Ignore this event and do not perform logging. |
| -100 | Unknown error | None. | Ignore this event and do not perform logging. |
| 1 | Invalid key name | The name is not empty and contains a maximum of 16 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).<br>The name does not end with an underscore \(_).| Ignore the key-value pair and continue to perform logging. |
| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. |
| 3 | Invalid value type | The supported value types vary depending on the programming language:<br>boolean, number, string, or Array [basic element]| Ignore the key-value pair and continue to perform logging. |
| 4 | Invalid length for values of the string type| For a value of the string type, the maximum length is 8*1024 characters. | Truncate the value with the first 8*1024 characters retained, and continue to perform logging.|
| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. |
| 6 | Invalid number of elements in values of the array type | For a value of the array type, the number of elements must be less than or equal to 100. | Truncate the array with the first 100 elements retained, and continue to perform logging. |
| 7 | Invalid parameters in values of the array type | For a value of the array type, all the parameters must be of the same type, which can only be boolean, number, or string.| Ignore the key-value pair and continue to perform logging. |
## Development Procedure
The following uses a one-time event watcher as an example to illustrate the development procedure. The following uses a one-time event watcher as an example to illustrate the development procedure.
1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows: 1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows:
```ts ```ts
import hiAppEvent from '@ohos.hiAppEvent'; import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
@Entry @Entry
@Component @Component
...@@ -91,10 +67,10 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -91,10 +67,10 @@ The following uses a one-time event watcher as an example to illustrate the deve
int_data: 100, int_data: 100,
str_data: "strValue" str_data: "strValue"
} }
}).then((value) => { }).then(() => {
console.log(`HiAppEvent success to write event: ${value}`); console.log(`HiAppEvent success to write event`);
}).catch((err) => { }).catch((err) => {
console.error(`HiAppEvent failed to write event because ${err.code}`); console.error(`code: ${err.code}, message: ${err.message}`);
}); });
}) })
...@@ -120,12 +96,12 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -120,12 +96,12 @@ The following uses a one-time event watcher as an example to illustrate the deve
// Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained. // Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained.
while ((eventPkg = holder.takeNext()) != null) { while ((eventPkg = holder.takeNext()) != null) {
// Parse the obtained event package and display the result on the Log page. // Parse the obtained event package and display the result on the Log page.
console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId); console.info(`HiAppEvent eventPkg.packageId=${eventPkg.packageId}`);
console.info('HiAppEvent eventPkg.row=' + eventPkg.row); console.info(`HiAppEvent eventPkg.row=${eventPkg.row}`);
console.info('HiAppEvent eventPkg.size=' + eventPkg.size); console.info(`HiAppEvent eventPkg.size=${eventPkg.size}`);
// Traverse and parse event string arrays in the obtained event package. // Traverse and parse event string arrays in the obtained event package.
for (const eventInfo of eventPkg.data) { for (const eventInfo of eventPkg.data) {
console.info('HiAppEvent eventPkg.data=' + eventInfo); console.info(`HiAppEvent eventPkg.data=${eventInfo}`);
} }
} }
} }
...@@ -169,4 +145,4 @@ The following uses a one-time event watcher as an example to illustrate the deve ...@@ -169,4 +145,4 @@ The following uses a one-time event watcher as an example to illustrate the deve
The following sample is provided to help you better understand how to develop the application event logging feature: The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest` (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest) - [`JsDotTest`: Event Logging (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest)
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE** > **NOTE**
> > - The 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.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -17,13 +17,9 @@ import hiAppEvent from '@ohos.hiAppEvent'; ...@@ -17,13 +17,9 @@ import hiAppEvent from '@ohos.hiAppEvent';
Before using application event logging, you need to understand the requirements for related parameters. Before using application event logging, you need to understand the requirements for related parameters.
**Event Domain**
An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_).
**Event Name** **Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).
**Event Type** **Event Type**
...@@ -33,7 +29,7 @@ An event type is an enumerated value of [EventType](#eventtype). ...@@ -33,7 +29,7 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_). - 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. - The parameter value is a string, number, boolean, or array.
- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated.
- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
...@@ -47,20 +43,10 @@ Event callback can be a callback or promise that carries the return value obtain ...@@ -47,20 +43,10 @@ Event callback can be a callback or promise that carries the return value obtain
- If the return value is greater than **0**, invalid parameters are present in the event, and the event will be written to the event file after the invalid parameters are ignored. - If the return value is greater than **0**, invalid parameters are present in the event, and the event will be written to the event file after the invalid parameters are ignored.
- If the return value is smaller than **0**, the event parameter verification fails, and the event will not be written to the event file. - If the return value is smaller than **0**, the event parameter verification fails, and the event will not be written to the event file.
**Subscription Callback** ## hiAppEvent.write
A subscription callback carries the subscription data obtained by invoking the watcher API. The input parameters are defined as follows:
- **curRow**: number of events.
- **curSize**: event data size, in bytes.
- **holder**: event data holder, which can be used for processing subscription events.
## hiAppEvent.write<sup>(deprecated)</sup>
write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback&lt;void&gt;): void write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback&lt;void&gt;): void
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9) instead.
Writes event information to the event file of the current day. This API uses an asynchronous callback to return the result. Writes event information to the event file of the current day. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
...@@ -72,7 +58,7 @@ Writes event information to the event file of the current day. This API uses an ...@@ -72,7 +58,7 @@ Writes event information to the event file of the current day. This API uses an
| eventName | string | Yes | Event name. | | eventName | string | Yes | Event name. |
| eventType | [EventType](#eventtype) | Yes | Event type. | | eventType | [EventType](#eventtype) | Yes | Event type. |
| keyValues | object | Yes | Event parameters. | | keyValues | object | Yes | Event parameters. |
| callback | AsyncCallback&lt;void&gt; | No | Event callback.| | callback | AsyncCallback&lt;void&gt; | Yes | Event callback.|
**Example** **Example**
...@@ -90,12 +76,10 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str ...@@ -90,12 +76,10 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str
``` ```
## hiAppEvent.write<sup>(deprecated)</sup> ## hiAppEvent.write
write(eventName: string, eventType: EventType, keyValues: object): Promise&lt;void&gt; write(eventName: string, eventType: EventType, keyValues: object): Promise&lt;void&gt;
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9-1) instead.
Writes event information to the event file of the current day. This API uses a promise to return the result. Writes event information to the event file of the current day. This API uses a promise to return the result.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
...@@ -127,97 +111,6 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str ...@@ -127,97 +111,6 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str
}); });
``` ```
## hiAppEvent.write<sup>9+</sup>
write(info: [AppEventInfo](#appeventinfo9), callback: AsyncCallback&lt;void&gt;): void
Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | -------------- |
| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.|
| callback | AsyncCallback&lt;void&gt; | No | Event callback.|
**Example**
```js
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
}
}, (err, value) => {
if (err) {
// Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
console.error(`failed to write event because ${err.code}`);
return;
}
// Event writing success
console.log(`success to write event: ${value}`);
});
```
## hiAppEvent.write<sup>9+</sup>
write(info: [AppEventInfo](#appeventinfo9)): Promise&lt;void&gt;
Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses a promise to return the result.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | -------------- |
| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.|
**Return value**
| Type | Description |
| ------------------- | ------------------------------------------------------------ |
| Promise&lt;void&gt; | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.|
**Example**
```js
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
}
}).then((value) => {
// Event writing success
console.log(`success to write event: ${value}`);
}).catch((err) => {
// Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
console.error(`failed to write event because ${err.code}`);
});
```
## AppEventInfo<sup>9+</sup>
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.|
## hiAppEvent.configure ## hiAppEvent.configure
configure(config: ConfigOption): boolean configure(config: ConfigOption): boolean
...@@ -258,230 +151,11 @@ Provides the configuration items for application event logging. ...@@ -258,230 +151,11 @@ Provides the configuration items for application event logging.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------- | ---- | ------------------------------------------------------------ | | ---------- | ------- | ---- | ------------------------------------------------------------ |
| disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.| | disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.|
| maxStorage | string | No | Maximum size of the event file storage directory. The default value is <strong>10M</strong>. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.| | maxStorage | string | No | Maximum size of the event file storage directory. The default value is <strong>10M</strong>. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.|
## hiAppEvent.addWatcher<sup>9+</sup>
addWatcher(watcher: [Watcher](#watcher9)): [AppEventPackageHolder](#appeventpackageholder9)
Adds an event watcher.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher9) | Yes | Event watcher.|
**Return value**
| Type | Description |
| ------------------------------------------------ | ------------------------------------ |
| [AppEventPackageHolder](#appeventpackageholder9) | Subscription data holder. If the subscription fails, **null** will be returned.|
**Example**
```js
// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered.
hiAppEvent.addWatcher({
name: "watcher1",
appEventFilters: [
{
domain: "domain_test1",
eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
}
],
triggerCondition: {
row: 10,
size: 1000,
timeOut: 1
},
onTrigger: function (curRow, curSize, holder) {
if (holder == null) {
console.error("holder is null");
return;
}
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info("eventPkg.packageId=" + eventPkg.packageId);
console.info("eventPkg.row=" + eventPkg.row);
console.info("eventPkg.size=" + eventPkg.size);
for (const eventInfo of eventPkg.data) {
console.info("eventPkg.data=" + eventInfo);
}
}
}
});
// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder.
let holder = hiAppEvent.addWatcher({
name: "watcher2",
});
if (holder != null) {
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info("eventPkg.packageId=" + eventPkg.packageId);
console.info("eventPkg.row=" + eventPkg.row);
console.info("eventPkg.size=" + eventPkg.size);
for (const eventInfo of eventPkg.data) {
console.info("eventPkg.data=" + eventInfo);
}
}
}
```
## hiAppEvent.removeWatcher<sup>9+</sup>
removeWatcher(watcher: [Watcher](#watcher9)): void
Removes an event watcher.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher9) | Yes | Event watcher.|
**Example**
```js
// 1. Define a watcher.
let watcher = {
name: "watcher1",
}
// 2. Add the watcher to subscribe to application events.
hiAppEvent.addWatcher(watcher);
// 3. Remove the watcher to unsubscribe from application events.
hiAppEvent.removeWatcher(watcher);
```
## Watcher<sup>9+</sup>
Defines parameters for a **Watcher** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- |
| name | string | Yes | Unique watcher name.|
| triggerCondition | [TriggerCondition](#triggercondition9) | No | Subscription callback trigger condition. |
| appEventFilters | [AppEventFilter](#appeventfilter9)[] | No | Application event filter criteria. |
| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder9)) => void | No | Subscription callback. |
## TriggerCondition<sup>9+</sup>
Defines parameters for a **TriggerCondition** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type| Mandatory| Description |
| ------- | -------- | ---- | -------------------------------------- |
| row | number | No | Number of events. |
| size | number | No | Event data size, in bytes.|
| timeOut | number | No | Timeout interval, in unit of 30s. |
## AppEventFilter<sup>9+</sup>
Defines parameters for an **AppEventFilter** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| ---------- | ------------------------- | ---- | ------------------------ |
| domain | string | Yes | Event domain. |
| eventTypes | [EventType](#eventtype)[] | No | Event types.|
## AppEventPackageHolder<sup>9+</sup>
Defines a subscription data holder for processing subscription events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
### constructor<sup>9+</sup>
constructor(watcherName: string);
A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
```
### setSize<sup>9+</sup>
setSize(size: number): void
Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
holder.setSize(1000);
```
### takeNext<sup>9+</sup>
takeNext(): [AppEventPackage](#appeventpackage9)
Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
let eventPkg = holder.takeNext();
```
## AppEventPackage<sup>9+</sup>
Defines parameters for an **AppEventPackage** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type| Description |
| --------- | -------- | ------------------------------ |
| packageId | number | Event package ID, which is named from **0** in ascending order. |
| row | number | Number of events in the event package. |
| size | number | Data size of the event package, in bytes.|
| data | string[] | Event data in the event package. |
## hiAppEvent.clearData<sup>9+</sup>
clearData(): void
Clears local logging data.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
hiAppEvent.clearData();
```
## EventType ## EventType
...@@ -489,12 +163,12 @@ Enumerates event types. ...@@ -489,12 +163,12 @@ Enumerates event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Default Value| Description | | Name | Value | Description |
| --------- | ------ | -------------- | | --------- | ---- | -------------- |
| FAULT | 1 | Fault event.| | FAULT | 1 | Fault event.|
| STATISTIC | 2 | Statistical event.| | STATISTIC | 2 | Statistical event.|
| SECURITY | 3 | Security event.| | SECURITY | 3 | Security event.|
| BEHAVIOR | 4 | Behavior event.| | BEHAVIOR | 4 | Behavior event.|
## Event ## Event
...@@ -503,11 +177,11 @@ Provides constants that define the names of all predefined events. ...@@ -503,11 +177,11 @@ Provides constants that define the names of all predefined events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type| Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------- | -------- | ---- | ---- | -------------------- | | ------------------------- | ------ | ---- | ---- | -------------------- |
| USER_LOGIN | string | Yes | No | User login event. | | USER_LOGIN | string | Yes | No | User login event. |
| USER_LOGOUT | string | Yes | No | User logout event. | | USER_LOGOUT | string | Yes | No | User logout event. |
| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| | DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.|
## Param ## Param
...@@ -516,8 +190,8 @@ Provides constants that define the names of all predefined event parameters. ...@@ -516,8 +190,8 @@ Provides constants that define the names of all predefined event parameters.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type| Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------------- | -------- | ---- | ---- | ------------------ | | ------------------------------- | ------ | ---- | ---- | ------------------ |
| USER_ID | string | Yes | No | Custom user ID. | | USER_ID | string | Yes | No | Custom user ID. |
| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | | DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| | DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.|
# HiDebug # HiDebug
> **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. This module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
## Modules to Import ## Modules to Import
...@@ -17,7 +16,7 @@ import hidebug from '@ohos.hidebug'; ...@@ -17,7 +16,7 @@ import hidebug from '@ohos.hidebug';
getNativeHeapSize(): bigint getNativeHeapSize(): bigint
Obtains the total size of the heap memory of this application. Obtains the total heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release. This API is defined but not implemented in OpenHarmony 3.1 Release.
...@@ -27,7 +26,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -27,7 +26,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
| Type | Description | | Type | Description |
| ------ | --------------------------- | | ------ | --------------------------- |
| bigint | Total size of the heap memory of this application, in kB.| | bigint | Total heap memory size of the application, in KB.|
**Example** **Example**
...@@ -40,17 +39,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -40,17 +39,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
getNativeHeapAllocatedSize(): bigint getNativeHeapAllocatedSize(): bigint
Obtains the size of the allocated heap memory of this application. Obtains the allocated heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release. This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------------------------------- | | ------ | --------------------------------- |
| bigint | Size of the allocated heap memory of this application, in kB.| | bigint | Allocated heap memory of the application, in KB.|
**Example** **Example**
...@@ -63,18 +62,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -63,18 +62,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
getNativeHeapFreeSize(): bigint getNativeHeapFreeSize(): bigint
Obtains the size of the free heap memory of this application. Obtains the free heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release. This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------------- | | ------ | ------------------------------- |
| bigint | Size of the free heap memory of this application, in kB.| | bigint | Free heap memory size of the application, in KB.|
**Example** **Example**
```js ```js
...@@ -86,16 +84,15 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -86,16 +84,15 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
getPss(): bigint getPss(): bigint
Obtains the size of the used physical memory of this process. Obtains the size of the physical memory actually used by the application process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------- | | ------ | ------------------------- |
| bigint | Used physical memory of this process, in kB.| | bigint | Size of the physical memory actually used by the application process, in KB.|
**Example** **Example**
```js ```js
...@@ -107,15 +104,15 @@ Obtains the size of the used physical memory of this process. ...@@ -107,15 +104,15 @@ Obtains the size of the used physical memory of this process.
getSharedDirty(): bigint getSharedDirty(): bigint
Obtains the size of the shared dirty memory of this process. Obtains the size of the shared dirty memory of a process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| bigint | Size of the shared dirty memory of this process, in kB.| | bigint | Size of the shared dirty memory of the process, in KB.|
**Example** **Example**
...@@ -127,15 +124,15 @@ Obtains the size of the shared dirty memory of this process. ...@@ -127,15 +124,15 @@ Obtains the size of the shared dirty memory of this process.
getPrivateDirty(): bigint getPrivateDirty(): bigint
Obtains the size of the private dirty memory of this process. Obtains the size of the private dirty memory of a process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| bigint | Size of the private dirty memory of this process, in kB.| | bigint | Size of the private dirty memory of the process, in KB.|
**Example** **Example**
...@@ -147,17 +144,17 @@ Obtains the size of the private dirty memory of this process. ...@@ -147,17 +144,17 @@ Obtains the size of the private dirty memory of this process.
getCpuUsage(): number getCpuUsage(): number
Obtains the CPU usage of this process. Obtains the CPU usage of a process.
For example, if the CPU usage is **50%**, **0.5** is returned. For example, if the CPU usage is **50%**, **0.5** is returned.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| number | CPU usage of this process.| | number | CPU usage of the process.|
**Example** **Example**
...@@ -165,11 +162,13 @@ For example, if the CPU usage is **50%**, **0.5** is returned. ...@@ -165,11 +162,13 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
let cpuUsage = hidebug.getCpuUsage(); let cpuUsage = hidebug.getCpuUsage();
``` ```
## hidebug.startProfiling ## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void startProfiling(filename : string) : void
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead.
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
...@@ -191,11 +190,13 @@ hidebug.stopProfiling(); ...@@ -191,11 +190,13 @@ hidebug.stopProfiling();
## hidebug.stopProfiling ## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void stopProfiling() : void
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead.
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
...@@ -209,17 +210,19 @@ hidebug.startProfiling("cpuprofiler-20220216"); ...@@ -209,17 +210,19 @@ hidebug.startProfiling("cpuprofiler-20220216");
hidebug.stopProfiling(); hidebug.stopProfiling();
``` ```
## hidebug.dumpHeapData ## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void dumpHeapData(filename : string) : void
Exports data from the specified heap file. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead.
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| | filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
...@@ -231,11 +234,11 @@ hidebug.dumpHeapData("heap-20220216"); ...@@ -231,11 +234,11 @@ hidebug.dumpHeapData("heap-20220216");
## hidebug.getServiceDump<sup>9+<sup> ## hidebug.getServiceDump<sup>9+<sup>
getServiceDump(serviceid : number) : string getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void
Obtains information on the specified system service. Obtains system service information.
This is a system API and cannot be called by third-party applications. **Required permissions**: ohos.permission.DUMP
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
...@@ -243,16 +246,116 @@ This is a system API and cannot be called by third-party applications. ...@@ -243,16 +246,116 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| serviceid | number | Yes | ID of the system service. | | serviceid | number | Yes | Obtains the system service information based on the specified service ID.|
| fd | number | Yes | File descriptor to which data is written by the API.|
| args | Array\<string> | Yes | Parameter list corresponding to the **Dump** API of the system service.|
**Return value**
| Type | Description |
| ------ | -------------------------- |
| string | Absolute path of the file that contains the service information to dump. |
**Example** **Example**
```js ```js
let serviceId = 10; import fileio from '@ohos.fileio'
let pathName = hidebug.getServiceDump(serviceId); import hidebug from '@ohos.hidebug'
import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
var path = data + "/serviceInfo.txt"
console.info("output path: " + path)
let fd = fileio.openSync(path, 0o102, 0o666)
var serviceId = 10
var args = new Array("allInfo")
try {
hidebug.getServiceDump(serviceId, fd, args)
} catch (error) {
console.info(error.code)
console.info(error.message)
}
fileio.closeSync(fd);
})
```
## hidebug.startJsCpuProfiling<sup>9+</sup>
startJsCpuProfiling(filename : string) : void
Starts the profiling method. `startJsCpuProfiling()` and `stopJsCpuProfiling()` are called in pairs. `startJsCpuProfiling()` always occurs before `stopJsCpuProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
import hidebug from '@ohos.hidebug'
try {
hidebug.startJsCpuProfiling("cpu_profiling");
...
hidebug.stopJsCpuProfiling();
} catch (error) {
console.info(error.code)
console.info(error.message)
}
```
## hidebug.stopJsCpuProfiling<sup>9+</sup>
stopJsCpuProfiling() : void
Stops the profiling method. `startJsCpuProfiling()` and `stopJsCpuProfiling()` are called in pairs. `startJsCpuProfiling()` always occurs before `stopJsCpuProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
import hidebug from '@ohos.hidebug'
try {
hidebug.startJsCpuProfiling("cpu_profiling");
...
hidebug.stopJsCpuProfiling();
} catch (error) {
console.info(error.code)
console.info(error.message)
}
```
## hidebug.dumpJsHeapData<sup>9+</sup>
dumpJsHeapData(filename : string) : void
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
import hidebug from '@ohos.hidebug'
try {
hidebug.dumpJsHeapData("heapData");
} catch (error) {
console.info(error.code)
console.info(error.message)
}
``` ```
# System Event Logging # HiSysEvent
Provides system event logging APIs for system HAP applications. This module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file.
> **NOTE** > **NOTE**
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs. > - The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
...@@ -19,7 +19,7 @@ Enumerates event types. ...@@ -19,7 +19,7 @@ Enumerates event types.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name | Default Value | Description | | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| FAULT | 1 | Error event.| | FAULT | 1 | Error event.|
| STATISTIC | 2 | Statistic event.| | STATISTIC | 2 | Statistic event.|
...@@ -32,7 +32,7 @@ Defines a system event. ...@@ -32,7 +32,7 @@ Defines a system event.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.| | domain | string | Yes| Event domain.|
| name | string | Yes| Event name.| | name | string | Yes| Event name.|
...@@ -50,11 +50,26 @@ Writes event information to the event file. This API uses an asynchronous callba ...@@ -50,11 +50,26 @@ Writes event information to the event file. This API uses an asynchronous callba
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------- | ---- | ------------------------------------------------------------ | | --------- | ------------------------- | ---- | ------------------------------------------------------------ |
| info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | info | [SysEventInfo](#syseventinfo) | Yes| System event information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.<br>- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously. <br>- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.<br>- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.<br>- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously. <br>- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.<br>- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message|
| ------- | ----------------------------------------------------------------- |
| 11200001 | Invalid event domain. |
| 11200002 | Invalid event name. |
| 11200003 | Abnormal environment. |
| 11200004 | Length of the event is over limit. |
| 11200051 | Invalid event parameter. |
| 11200052 | Size of the event parameter of the string type is over limit. |
| 11200053 | Count of event parameters is over limit. |
| 11200054 | Count of event parameter of the array type is over limit. |
**Example** **Example**
```js ```js
...@@ -91,16 +106,31 @@ Writes event information to the event file. This API uses a promise to return th ...@@ -91,16 +106,31 @@ Writes event information to the event file. This API uses a promise to return th
**Parameters** **Parameters**
| Name | Type | Mandatory | Description| | Name | Type | Mandatory| Description|
| --------- | ----------------------- | ---- | --------------- | | --------- | ----------------------- | ---- | --------------- |
| info | [SysEventInfo](#syseventinfo) | Yes | System event information.| | info | [SysEventInfo](#syseventinfo) | Yes | System event information.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ------------------------------------------------------------ | | ------------------- | ------------------------------------------------------------ |
| Promise&lt;void&gt; | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| | Promise&lt;void&gt; | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message|
| -------- | ---------------------------------------------------------------- |
| 11200001 | Invalid event domain. |
| 11200002 | Invalid event name. |
| 11200003 | Abnormal environment. |
| 11200004 | Length of the event is over limit. |
| 11200051 | Invalid event parameter. |
| 11200052 | Size of the event parameter of the string type is over limit. |
| 11200053 | Count of event parameters is over limit. |
| 11200054 | Count of event parameter of the array type is over limit. |
**Example** **Example**
```js ```js
...@@ -138,7 +168,7 @@ Enumerates matching rule types. ...@@ -138,7 +168,7 @@ Enumerates matching rule types.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name | Default Value | Description | | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| WHOLE_WORD | 1 | Whole word matching.| | WHOLE_WORD | 1 | Whole word matching.|
| PREFIX | 2 | Prefix matching.| | PREFIX | 2 | Prefix matching.|
...@@ -146,11 +176,11 @@ Enumerates matching rule types. ...@@ -146,11 +176,11 @@ Enumerates matching rule types.
## WatchRule ## WatchRule
Defines rules for event subscription. Defines event subscription rules.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.| | domain | string | Yes| Event domain.|
| name | string | Yes| Event name.| | name | string | Yes| Event name.|
...@@ -163,15 +193,15 @@ Defines a watcher for event subscription. ...@@ -163,15 +193,15 @@ Defines a watcher for event subscription.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| | rules | [WatchRule](#watchrule)[] | Yes| Array of matching event subscription rules.|
| onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void|
| onServiceDied | function | Yes| Callback for disabling of event subscription: () => void| | onServiceDied | function | Yes| Callback for disabling of event subscription: () => void|
## hiSysEvent.addWatcher ## hiSysEvent.addWatcher
addWatcher(watcher: Watcher): number addWatcher(watcher: Watcher): void
Adds a watcher for event subscription. Adds a watcher for event subscription.
...@@ -181,10 +211,19 @@ Adds a watcher for event subscription. ...@@ -181,10 +211,19 @@ Adds a watcher for event subscription.
**Parameters** **Parameters**
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------ | ----------------------------- | ---- | ------------------------ | | ------ | ----------------------------- | ---- | ------------------------ |
| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message|
| -------- | ----------------------------------- |
| 11200101 | Count of watchers is over limit. |
| 11200102 | Count of watch rules is over limit. |
**Example** **Example**
```js ```js
...@@ -213,7 +252,7 @@ try { ...@@ -213,7 +252,7 @@ try {
## hiSysEvent.removeWatcher ## hiSysEvent.removeWatcher
removeWatcher(wathcer: Watcher): number removeWatcher(watcher: Watcher): void
Removes a watcher used for event subscription. Removes a watcher used for event subscription.
...@@ -223,10 +262,18 @@ Removes a watcher used for event subscription. ...@@ -223,10 +262,18 @@ Removes a watcher used for event subscription.
**Parameters** **Parameters**
| Name| Type | Mandatory | Description | | Name| Type | Mandatory| Description |
| ------ | ------------- | ---- | ------------------------ | | ------ | ------------- | ---- | ------------------------- |
| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message|
| -------- | --------------------------- |
| 11200201 | The watcher does not exist. |
**Example** **Example**
```js ```js
...@@ -256,26 +303,26 @@ try { ...@@ -256,26 +303,26 @@ try {
## QueryArg ## QueryArg
Defines arguments for event query. Defines arguments for an event query.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| beginTime | number | Yes| Start time (13-digit timestamp) for event query.| | beginTime | number | Yes| Start time (13-digit timestamp) for the event query.|
| endTime | number | Yes| End time (13-digit timestamp) for event query.| | endTime | number | Yes| End time (13-digit timestamp) for the event query.|
| maxEvents | number | Yes| Maximum number of events that can be queried.| | maxEvents | number | Yes| Maximum number of events that can be queried.|
## QueryRule ## QueryRule
Defines rules for event query. Defines event query rules.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domain | string | Yes| Event domain.| | domain | string | Yes| Event domain.|
| names | string[] | Yes| Array of event names.| | names | string[] | Yes| Array of event names. A **QueryRule** object contains multiple system event names.|
## Querier ## Querier
...@@ -283,14 +330,14 @@ Defines an event query instance. ...@@ -283,14 +330,14 @@ Defines an event query instance.
**System capability**: SystemCapability.HiviewDFX.HiSysEvent **System capability**: SystemCapability.HiviewDFX.HiSysEvent
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onQuery | function | Yes| Callback used to return the queried system events: (infos: [SysEventInfo](#syseventinfo)[]) => void.|
| onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| | onComplete | function | Yes| Callback used to return the query result statistics: (reason: number, total: number) => void|
## hiSysEvent.query ## hiSysEvent.query
query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): void
Queries system events. Queries system events.
...@@ -300,12 +347,23 @@ Queries system events. ...@@ -300,12 +347,23 @@ Queries system events.
**Parameters** **Parameters**
| Name| Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------ | ----------------------------- | ---- | ------------------------ | | ------ | ----------------------------- | ---- | ------------------------ |
| queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.|
| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.|
| querier | [Querier](#querier) | Yes | Event query instance.| | querier | [Querier](#querier) | Yes | Event query instance.|
**Error codes**
For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md).
| ID| Error Message|
| -------- | ------------------------------------------- |
| 11200301 | Count of query rules is over limit. |
| 11200302 | Invalid query rule. |
| 11200303 | Count of concurrent queriers is over limit. |
| 11200304 | Query frequency is over limit. |
**Example** **Example**
```js ```js
......
# Application Event Logging
This 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**
> 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.
## Modules to Import
```js
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
```
## hiAppEvent.write
write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback&lt;void&gt;): void
Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | -------------- |
| info | [AppEventInfo](#appeventinfo) | Yes | Application event object.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
| ID| Error Message |
| -------- | --------------------------------------------- |
| 11100001 | Function is disabled. |
| 11101001 | Invalid event domain. |
| 11101002 | Invalid event name. |
| 11101003 | Invalid number of event parameters. |
| 11101004 | Invalid string length of the event parameter. |
| 11101005 | Invalid event parameter name. |
| 11101006 | Invalid array length of the event parameter. |
**Example**
```js
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
}
}, (err) => {
if (err) {
console.error(`code: ${err.code}, message: ${err.message}`);
return;
}
console.log(`success to write event`);
});
```
## hiAppEvent.write
write(info: [AppEventInfo](#appeventinfo)): Promise&lt;void&gt;
Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses a promise to return the result.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | -------------- |
| info | [AppEventInfo](#appeventinfo) | Yes | Application event object.|
**Return value**
| Type | Description |
| ------------------- | ------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
| ID| Error Message |
| -------- | --------------------------------------------- |
| 11100001 | Function is disabled. |
| 11101001 | Invalid event domain. |
| 11101002 | Invalid event name. |
| 11101003 | Invalid number of event parameters. |
| 11101004 | Invalid string length of the event parameter. |
| 11101005 | Invalid event parameter name. |
| 11101006 | Invalid array length of the event parameter. |
**Example**
```js
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
}
}).then(() => {
console.log(`success to write event`);
}).catch((err) => {
console.error(`code: ${err.code}, message: ${err.message}`);
});
```
## AppEventInfo
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.|
## hiAppEvent.configure
configure(config: [ConfigOption](configoption)): void
Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------ |
| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.|
**Error codes**
For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
| ID| Error Message |
| -------- | -------------------------------- |
| 11103001 | Invalid max storage quota value. |
**Example**
```js
// Disable the event logging function.
hiAppEvent.configure({
disable: true
});
// Set the maximum size of the file storage directory to 100 MB.
hiAppEvent.configure({
maxStorage: '100M'
});
```
## ConfigOption
Configures options for application event logging.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| ---------- | ------- | ---- | ------------------------------------------------------------ |
| disable | boolean | No | Whether to enable the event logging function. The default value is **false**. The value **true** means to disable the event logging function, and the value **false** means the opposite.|
| maxStorage | string | No | Maximum size of the directory that stores event logging files. The default value is **10M**.<br>If the directory size exceeds the specified quota when application event logging is performed, event logging files in the directory will be cleared one by one based on the generation time to ensure that directory size does not exceed the quota.|
## hiAppEvent.addWatcher
addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpackageholder)
Adds a watcher to subscribe to application events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher) | Yes | Watcher for application events.|
**Return value**
| Type | Description |
| ------------------------------------------------ | ------------------------------------ |
| [AppEventPackageHolder](#appeventpackageholder) | Subscription data holder. If the subscription fails, **null** will be returned.|
**Error codes**
For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
| ID| Error Message |
| -------- | ------------------------------- |
| 11102001 | Invalid watcher name. |
| 11102002 | Invalid filtering event domain. |
| 11102003 | Invalid row value. |
| 11102004 | Invalid size value. |
| 11102005 | Invalid timeout value. |
**Example**
```js
// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered.
hiAppEvent.addWatcher({
name: "watcher1",
appEventFilters: [
{
domain: "test_domain",
eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
}
],
triggerCondition: {
row: 10,
size: 1000,
timeOut: 1
},
onTrigger: function (curRow, curSize, holder) {
if (holder == null) {
console.error("holder is null");
return;
}
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info(`eventPkg.packageId=${eventPkg.packageId}`);
console.info(`eventPkg.row=${eventPkg.row}`);
console.info(`eventPkg.size=${eventPkg.size}`);
for (const eventInfo of eventPkg.data) {
console.info(`eventPkg.data=${eventInfo}`);
}
}
}
});
// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder.
let holder = hiAppEvent.addWatcher({
name: "watcher2",
});
if (holder != null) {
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info(`eventPkg.packageId=${eventPkg.packageId}`);
console.info(`eventPkg.row=${eventPkg.row}`);
console.info(`eventPkg.size=${eventPkg.size}`);
for (const eventInfo of eventPkg.data) {
console.info(`eventPkg.data=${eventInfo}`);
}
}
}
```
## hiAppEvent.removeWatcher
removeWatcher(watcher: [Watcher](#watcher)): void
Removes a watcher to unsubscribe from application events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------------------- | ---- | ---------------- |
| watcher | [Watcher](#watcher) | Yes | Watcher for application events.|
**Error codes**
For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
| ID| Error Message |
| -------- | --------------------- |
| 11102001 | Invalid watcher name. |
**Example**
```js
// 1. Define a watcher for application events.
let watcher = {
name: "watcher1",
}
// 2. Add the watcher to subscribe to application events.
hiAppEvent.addWatcher(watcher);
// 3. Remove the watcher to unsubscribe from application events.
hiAppEvent.removeWatcher(watcher);
```
## Watcher
Defines parameters for a **Watcher** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| name | string | Yes | Unique name of the watcher. |
| triggerCondition | [TriggerCondition](#triggercondition) | No | Subscription callback triggering condition. This parameter takes effect only when it is passed together with the callback. |
| appEventFilters | [AppEventFilter](#appeventfilter)[] | No | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered. |
| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder)) => void | No | Subscription callback, which takes effect only when it is passed together with the callback triggering condition. The input arguments are described as follows:<br>**curRow**: total number of subscription events when the callback is triggered.<br>**curSize**: total size of subscribed events when the callback is triggered, in bytes.<br>**holder**: subscription data holder, which can be used to process subscribed events.|
## TriggerCondition
Defines callback triggering conditions. Subscription callback is triggered when any condition is met.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | -------------------------------------- |
| row | number | No | Number of events. |
| size | number | No | Event data size, in bytes.|
| timeOut | number | No | Timeout interval, in unit of 30s. |
## AppEventFilter
Defines parameters for an **AppEventFilter** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| ---------- | ------------------------- | ---- | ------------------------ |
| domain | string | Yes | Event domain. |
| eventTypes | [EventType](#eventtype)[] | No | Event types.|
## AppEventPackageHolder
Defines a subscription data holder for processing subscription events.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
### constructor
constructor(watcherName: string)
Constructor of the **Watcher** class. When a watcher is added, the system automatically calls this API to create a subscription data holder object for the watcher and returns the holder object to the application.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------- | ---- | ------------------------ |
| watcherName | string | Yes | Watcher name.|
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
```
### setSize
setSize(size: number): void
Sets the threshold for the data size of the application event package obtained each time.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------------------------- |
| size | number | Yes | Data size threshold, in bytes. The default value is **512*1024**.|
**Error codes**
For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md).
| ID| Error Message |
| -------- | ------------------- |
| 11104001 | Invalid size value. |
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
holder.setSize(1000);
```
### takeNext
takeNext(): [AppEventPackage](#appeventpackage)
Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
let eventPkg = holder.takeNext();
```
## AppEventPackage
Defines parameters for an **AppEventPackage** object.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type | Mandatory| Description |
| --------- | -------- | ---- | ------------------------------ |
| packageId | number | Yes | Event package ID, which is named from **0** in ascending order. |
| row | number | Yes | Number of events in the event package. |
| size | number | Yes | Event size of the event package, in bytes.|
| data | string[] | Yes | Event data in the event package. |
## hiAppEvent.clearData
clearData(): void
Clears local application event logging data.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
**Example**
```js
hiAppEvent.clearData();
```
## EventType
Enumerates event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Value | Description |
| --------- | ---- | -------------- |
| FAULT | 1 | Fault event.|
| STATISTIC | 2 | Statistical event.|
| SECURITY | 3 | Security event.|
| BEHAVIOR | 4 | Behavior 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.|
## 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.|
# USB
The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import usb from "@ohos.usb";
```
## usb.getDevices
getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt;
Obtains the USB device list.
**System capability**: SystemCapability.USB.USBManager
**Return value**
| Type | Description |
| ---------------------------------------------------- | ------- |
| Array&lt;Readonly&lt;[USBDevice](#usbdevice)&gt;&gt; | Device information list.|
**Example**
```js
let devicesList = usb.getDevices();
console.log(`devicesList = ${JSON.stringify(devicesList)}`);
// devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows:
[
{
name: "1-1",
serial: "",
manufacturerName: "",
productName: "",
version: "",
vendorId: 7531,
productId: 2,
clazz: 9,
subclass: 0,
protocol: 1,
devAddress: 1,
busNum: 1,
configs: [
{
id: 1,
attributes: 224,
isRemoteWakeup: true,
isSelfPowered: true,
maxPower: 0,
name: "1-1",
interfaces: [
{
id: 0,
protocol: 0,
clazz: 9,
subclass: 0,
alternateSetting: 0,
name: "1-1",
endpoints: [
{
address: 129,
attributes: 3,
interval: 12,
maxPacketSize: 4,
direction: 128,
number: 1,
type: 3,
interfaceId: 0,
},
],
},
],
},
],
},
]
```
## usb.connectDevice
connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
Connects to a USB device.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| device | [USBDevice](#usbdevice) | Yes| USB device information.|
**Return value**
| Type| Description|
| -------- | -------- |
| Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.|
**Example**
```js
let devicepipe= usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`);
```
## usb.hasRight
hasRight(deviceName: string): boolean
Checks whether the application has the permission to access the device.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | The value **true** indicates that the application has the permission to access the device, and the value **false** indicates the opposite.|
**Example**
```js
let devicesName="1-1";
let bool = usb.hasRight(devicesName);
console.log(bool);
```
## usb.requestRight
requestRight(deviceName: string): Promise&lt;boolean&gt;
Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted, and the value **false** indicates the opposite.|
**Example**
```js
let devicesName="1-1";
usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${JSON.stringify(ret)}`);
});
```
## usb.claimInterface
claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number
Claims a USB interface.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and USB interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to claim.|
| force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully claimed, and an error code indicates the opposite.|
**Example**
```js
let ret = usb.claimInterface(devicepipe, interfaces);
console.log(`claimInterface = ${ret}`);
```
## usb.releaseInterface
releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number
Releases a USB interface.
Before you do this, ensure that you have claimed the interface by calling [usb.claimInterface](#usbclaiminterface).
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully released, and an error code indicates the opposite.|
**Example**
```js
let ret = usb.releaseInterface(devicepipe, interfaces);
console.log(`releaseInterface = ${ret}`);
```
## usb.setConfiguration
setConfiguration(pipe: USBDevicePipe, config: USBConfig): number
Sets the device configuration.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device configuration, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| config | [USBConfig](#usbconfig) | Yes| USB configuration to set.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB configuration is successfully set, and an error code indicates the opposite.|
**Example**
```js
let ret = usb.setConfiguration(devicepipe, config);
console.log(`setConfiguration = ${ret}`);
```
## usb.setInterface
setInterface(pipe: USBDevicePipe, iface: USBInterface): number
Sets a USB interface.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------------------------------- | --- | ------------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes | Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes | USB interface to set. |
**Return value**
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully set, and an error code indicates the opposite.|
**Example**
```js
let ret = usb.setInterface(devicepipe, interfaces);
console.log(`setInterface = ${ret}`);
```
## usb.getRawDescriptor
getRawDescriptor(pipe: USBDevicePipe): Uint8Array
Obtains the raw USB descriptor.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | The return value is the raw USB descriptor if the operation is successful, or **undefined** if the operation has failed.|
**Example**
```js
let ret = usb.getRawDescriptor(devicepipe);
```
## usb.getFileDescriptor
getFileDescriptor(pipe: USBDevicePipe): number
Obtains the file descriptor.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | The return value is the file descriptor of the USB device if the operation is successful, or **-1** if the operation has failed.|
**Example**
```js
let ret = usb.getFileDescriptor(devicepipe);
```
## usb.controlTransfer
controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise&lt;number&gt;
Performs control transfer.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.|
**Example**
```js
usb.controlTransfer(devicepipe, USBControlParams).then((ret) => {
console.log(`controlTransfer = ${JSON.stringify(ret)}`);
})
```
## usb.bulkTransfer
bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt;
Performs bulk transfer.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB port for data transfer.|
| buffer | Uint8Array | Yes| Buffer for writing or reading data.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.|
**Example**
```js
// Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission.
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${JSON.stringify(ret)}`);
});
```
## usb.closePipe
closePipe(pipe: USBDevicePipe): number
Closes a USB device pipe.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB device pipe is closed successfully, and an error code indicates the opposite.|
**Example**
```js
let ret = usb.closePipe(devicepipe);
console.log(`closePipe = ${ret}`);
```
## usb.usbFunctionsFromString<sup>9+</sup>
usbFunctionsFromString(funcs: string): number
Converts the USB function list in the string format to a numeric mask in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------- |
| funcs | string | Yes | Function list in string format.|
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Function list in numeric mask format.|
**Example**
```js
let funcs = "acm";
let ret = usb.usbFunctionsFromString(funcs);
```
## usb.usbFunctionsToString<sup>9+</sup>
usbFunctionsToString(funcs: FunctionType): string
Converts the USB function list in the numeric mask format to a string in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ----------------- |
| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.|
**Return value**
| Type | Description |
| ------ | ------------------------------ |
| string | Function list in string format.|
**Example**
```js
let funcs = ACM | ECM;
let ret = usb.usbFunctionsToString(funcs);
```
## usb.setCurrentFunctions<sup>9+</sup>
setCurrentFunctions(funcs: FunctionType): Promise\<boolean\>
Sets the current USB function list in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ----------------- |
| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.|
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Promise\<boolean\> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.|
**Example**
```js
let funcs = HDC;
let ret = usb.setCurrentFunctions(funcs);
```
## usb.getCurrentFunctions<sup>9+</sup>
getCurrentFunctions(): FunctionType
Obtains the numeric mask combination for the USB function list in Device mode.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Return value**
| Type | Description |
| ------------------------------ | --------------------------------- |
| [FunctionType](#functiontype9) | Numeric mask combination for the USB function list.|
**Example**
```js
let ret = usb.getCurrentFunctions();
```
## usb.getPorts<sup>9+</sup>
getPorts(): Array\<USBPort\>
Obtains the list of all physical USB ports.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Return value**
| Type | Description |
| ----------------------------- | --------------------- |
| [Array\<USBPort\>](#usbport9) | List of physical USB ports.|
**Example**
```js
let ret = usb.getPorts();
```
## usb.getSupportedModes<sup>9+</sup>
getSupportedModes(portId: number): PortModeType
Obtains the mask combination for the supported mode list of a given USB port.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- |
| portId | number | Yes | Port number.|
**Return value**
| Type | Description |
| ------------------------------ | -------------------------- |
| [PortModeType](#portmodetype9) | Mask combination for the supported mode list.|
**Example**
```js
let ret = usb.getSupportedModes(0);
```
## usb.setPortRoles<sup>9+</sup>
setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\<boolean\>
Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer).
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | -------------------------------- | ---- | ---------------- |
| portId | number | Yes | Port number. |
| powerRole | [PowerRoleType](#powerroletype9) | Yes | Role for charging. |
| dataRole | [DataRoleType](#dataroletype9) | Yes | Role for data transfer.|
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Promise\<boolean\> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.|
**Example**
```js
let ret = usb.getSupportedModes(0);
```
## USBEndpoint
Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface).
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ------------- | ------------------------------------------- | ------------- |
| address | number | Endpoint address. |
| attributes | number | Endpoint attributes. |
| interval | number | Endpoint interval. |
| maxPacketSize | number | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction. |
| number | number | Endpoint number. |
| type | number | Endpoint type. |
| interfaceId | number | Unique ID of the interface to which the endpoint belongs.|
## USBInterface
Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **USBInterface** instances, each providing a specific function.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ---------------- | ---------------------------------------- | --------------------- |
| id | number | Unique ID of the USB interface. |
| protocol | number | Interface protocol. |
| clazz | number | Device type. |
| subClass | number | Device subclass. |
| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.|
| name | string | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Endpoints that belong to the USB interface. |
## USBConfig
Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| -------------- | ------------------------------------------------ | --------------- |
| id | number | Unique ID of the USB configuration. |
| attributes | number | Configuration attributes. |
| maxPower | number | Maximum power consumption, in mA. |
| name | string | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Support for remote wakeup.|
| isSelfPowered | boolean | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Supported interface attributes. |
## USBDevice
Represents the USB device information.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ---------------- | ------------------------------------ | ---------- |
| busNum | number | Bus address. |
| devAddress | number | Device address. |
| serial | string | Sequence number. |
| name | string | Device name. |
| manufacturerName | string | Device manufacturer. |
| productName | string | Product name. |
| version | string | Version number. |
| vendorId | number | Vendor ID. |
| productId | number | Product ID. |
| clazz | number | Device class. |
| subClass | number | Device subclass. |
| protocol | number | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Device configuration descriptor information.|
## USBDevicePipe
Represents a USB device pipe, which is used to determine a USB device.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ---------- | ------ | ----- |
| busNum | number | Bus address.|
| devAddress | number | Device address.|
## USBControlParams
Represents control transfer parameters.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ------- | ----------------------------------------------- | ---------------- |
| request | number | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Control request type. |
| value | number | Request parameter value. |
| index | number | Index of the request parameter value.|
| data | Uint8Array | Buffer for writing or reading data. |
## USBPort<sup>9+</sup>
Represents a USB port.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| -------------- | -------------------------------- | ----------------------------------- |
| id | number | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype9) | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus9) | USB port role. |
## USBPortStatus<sup>9+</sup>
Enumerates USB port roles.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Type| Description |
| ---------------- | -------- | ---------------------- |
| currentMode | number | Current USB mode. |
| currentPowerRole | number | Current power role. |
| currentDataRole | number | Current data role.|
## USBRequestTargetType
Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device.|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint.|
| USB_REQUEST_TARGET_OTHER | 3 | Other.|
## USBControlRequestType
Enumerates control request types.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------------------------- | ---- | ------ |
| USB_REQUEST_TYPE_STANDARD | 0 | Standard.|
| USB_REQUEST_TYPE_CLASS | 1 | Class. |
| USB_REQUEST_TYPE_VENDOR | 2 | Vendor.|
## USBRequestDirection
Enumerates request directions.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| --------------------------- | ---- | ------------------------ |
| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.|
| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.|
## FunctionType<sup>9+</sup>
Enumerates USB device function types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------------ | ---- | ---------- |
| NONE | 0 | No function.|
| ACM | 1 | ACM function. |
| ECM | 2 | ECM function. |
| HDC | 4 | HDC function. |
| MTP | 8 | Not supported currently.|
| PTP | 16 | Not supported currently.|
| RNDIS | 32 | Not supported currently.|
| MIDI | 64 | Not supported currently.|
| AUDIO_SOURCE | 128 | Not supported currently.|
| NCM | 256 | Not supported currently.|
## PortModeType<sup>9+</sup>
Enumerates USB port mode types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| --------- | ---- | ---------------------------------------------------- |
| NONE | 0 | None. |
| UFP | 1 | Upstream facing port, which functions as the sink of power supply. |
| DFP | 2 | Downstream facing port, which functions as the source of power supply. |
| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.|
| NUM_MODES | 4 | Not supported currently. |
## PowerRoleType<sup>9+</sup>
Enumerates power role types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------ | ---- | ---------- |
| NONE | 0 | None. |
| SOURCE | 1 | External power supply.|
| SINK | 2 | Internal power supply.|
## DataRoleType<sup>9+</sup>
Enumerates data role types.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ------ | ---- | ------------ |
| NONE | 0 | None. |
| HOST | 1 | USB host.|
| DEVICE | 2 | USB device.|
# USB # USB
The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```js ```js
import usb from "@ohos.usb"; import usb from "@ohos.usbV9";
``` ```
## usb.getDevices ## usb.getDevices
getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt; getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt;
Obtains the USB device list. Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
...@@ -24,7 +24,7 @@ Obtains the USB device list. ...@@ -24,7 +24,7 @@ Obtains the USB device list.
| Type | Description | | Type | Description |
| ---------------------------------------------------- | ------- | | ---------------------------------------------------- | ------- |
| Array&lt;Readonly&lt;[USBDevice](#usbdevice)&gt;&gt; | Device information list.| | Array&lt;Readonly&lt;[USBDevice](#usbdevice)&gt;&gt; | USB device list.|
**Example** **Example**
...@@ -89,7 +89,7 @@ connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt; ...@@ -89,7 +89,7 @@ connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt;
Connects to a USB device. Connects to a USB device.
Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, and then call [usb.requestRight](#usbrequestright) to request the device access permission. Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
...@@ -105,10 +105,26 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -105,10 +105,26 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| -------- | -------- | | -------- | -------- |
| Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.| | Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.|
**Error codes**
For details about the error codes, see [USB Error Codes](../errorcodes/errorcode-usb.md).
| ID| Error Message|
| -------- | -------- |
| 14400001 |Permission denied. Need call requestRight to get permission. |
**Example** **Example**
```js ```js
let devicepipe= usb.connectDevice(device); let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); console.log(`devicepipe = ${JSON.stringify(devicepipe)}`);
``` ```
...@@ -130,7 +146,7 @@ Checks whether the application has the permission to access the device. ...@@ -130,7 +146,7 @@ Checks whether the application has the permission to access the device.
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | The value **true** indicates that the application has the permission to access the device, and the value **false** indicates the opposite.| | boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise.|
**Example** **Example**
...@@ -144,7 +160,7 @@ console.log(bool); ...@@ -144,7 +160,7 @@ console.log(bool);
requestRight(deviceName: string): Promise&lt;boolean&gt; requestRight(deviceName: string): Promise&lt;boolean&gt;
Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result. Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
...@@ -158,7 +174,7 @@ Requests the temporary permission for the application to access the USB device. ...@@ -158,7 +174,7 @@ Requests the temporary permission for the application to access the USB device.
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted, and the value **false** indicates the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite.|
**Example** **Example**
...@@ -169,6 +185,70 @@ usb.requestRight(devicesName).then((ret) => { ...@@ -169,6 +185,70 @@ usb.requestRight(devicesName).then((ret) => {
}); });
``` ```
## usb.removeRight
removeRight(deviceName: string): boolean;
Removes the permission for the application to access a USB device.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite.|
**Example**
```js
let devicesName="1-1";
if (usb.removeRight(devicesName) {
console.log(`Succeed in removing right`);
}
```
## usb.addRight
addRight(bundleName: string, deviceName: string): boolean;
Adds the permission for the application to access a USB device.
[requestRight](#usbrequestright) triggers a dialog box to request for user authorization, whereas **addRight** adds the access permission directly without displaying a dialog box.
**System API**: This is a system API.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
| bundleName | string | Yes| Bundle name of the application.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.|
**Example**
```js
let devicesName = "1-1";
let bundleName = "com.example.hello";
if (usb.addRight(bundleName, devicesName) {
console.log(`Succeed in adding right`);
}
```
## usb.claimInterface ## usb.claimInterface
claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number
...@@ -191,7 +271,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -191,7 +271,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully claimed, and an error code indicates the opposite.| | number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise.|
**Example** **Example**
...@@ -221,7 +301,7 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c ...@@ -221,7 +301,7 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully released, and an error code indicates the opposite.| | number | Returns **0** if the USB interface is successfully released; returns an error code otherwise.|
**Example** **Example**
...@@ -251,7 +331,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -251,7 +331,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | The value **0** indicates that the USB configuration is successfully set, and an error code indicates the opposite.| | number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise.|
**Example** **Example**
...@@ -281,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -281,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully set, and an error code indicates the opposite.| | number | Returns **0** if the USB interface is successfully set; returns an error code otherwise.|
**Example** **Example**
...@@ -310,7 +390,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -310,7 +390,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Uint8Array | The return value is the raw USB descriptor if the operation is successful, or **undefined** if the operation has failed.| | Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.|
**Example** **Example**
...@@ -338,7 +418,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -338,7 +418,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Type | Description | | Type | Description |
| ------ | -------------------- | | ------ | -------------------- |
| number | The return value is the file descriptor of the USB device if the operation is successful, or **-1** if the operation has failed.| | number | Returns the file descriptor of the USB device if the operation is successful; returns **-1** otherwise.|
**Example** **Example**
...@@ -348,7 +428,7 @@ let ret = usb.getFileDescriptor(devicepipe); ...@@ -348,7 +428,7 @@ let ret = usb.getFileDescriptor(devicepipe);
## usb.controlTransfer ## usb.controlTransfer
controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise&lt;number&gt; controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise&lt;number&gt;
Performs control transfer. Performs control transfer.
...@@ -361,7 +441,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -361,7 +441,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| | controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| | timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value** **Return value**
...@@ -434,7 +514,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ...@@ -434,7 +514,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | The value **0** indicates that the USB device pipe is closed successfully, and an error code indicates the opposite.| | number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise.|
**Example** **Example**
...@@ -443,7 +523,7 @@ let ret = usb.closePipe(devicepipe); ...@@ -443,7 +523,7 @@ let ret = usb.closePipe(devicepipe);
console.log(`closePipe = ${ret}`); console.log(`closePipe = ${ret}`);
``` ```
## usb.usbFunctionsFromString<sup>9+</sup> ## usb.usbFunctionsFromString
usbFunctionsFromString(funcs: string): number usbFunctionsFromString(funcs: string): number
...@@ -472,7 +552,7 @@ let funcs = "acm"; ...@@ -472,7 +552,7 @@ let funcs = "acm";
let ret = usb.usbFunctionsFromString(funcs); let ret = usb.usbFunctionsFromString(funcs);
``` ```
## usb.usbFunctionsToString<sup>9+</sup> ## usb.usbFunctionsToString
usbFunctionsToString(funcs: FunctionType): string usbFunctionsToString(funcs: FunctionType): string
...@@ -486,7 +566,7 @@ Converts the USB function list in the numeric mask format to a string in Device ...@@ -486,7 +566,7 @@ Converts the USB function list in the numeric mask format to a string in Device
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ----------------- | | ------ | ------------------------------ | ---- | ----------------- |
| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.| | funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.|
**Return value** **Return value**
...@@ -501,7 +581,7 @@ let funcs = ACM | ECM; ...@@ -501,7 +581,7 @@ let funcs = ACM | ECM;
let ret = usb.usbFunctionsToString(funcs); let ret = usb.usbFunctionsToString(funcs);
``` ```
## usb.setCurrentFunctions<sup>9+</sup> ## usb.setCurrentFunctions
setCurrentFunctions(funcs: FunctionType): Promise\<boolean\> setCurrentFunctions(funcs: FunctionType): Promise\<boolean\>
...@@ -515,7 +595,7 @@ Sets the current USB function list in Device mode. ...@@ -515,7 +595,7 @@ Sets the current USB function list in Device mode.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ----------------- | | ------ | ------------------------------ | ---- | ----------------- |
| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.| | funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.|
**Return value** **Return value**
...@@ -530,7 +610,7 @@ let funcs = HDC; ...@@ -530,7 +610,7 @@ let funcs = HDC;
let ret = usb.setCurrentFunctions(funcs); let ret = usb.setCurrentFunctions(funcs);
``` ```
## usb.getCurrentFunctions<sup>9+</sup> ## usb.getCurrentFunctions
getCurrentFunctions(): FunctionType getCurrentFunctions(): FunctionType
...@@ -544,7 +624,7 @@ Obtains the numeric mask combination for the USB function list in Device mode. ...@@ -544,7 +624,7 @@ Obtains the numeric mask combination for the USB function list in Device mode.
| Type | Description | | Type | Description |
| ------------------------------ | --------------------------------- | | ------------------------------ | --------------------------------- |
| [FunctionType](#functiontype9) | Numeric mask combination for the USB function list.| | [FunctionType](#functiontype) | Numeric mask combination for the USB function list.|
**Example** **Example**
...@@ -552,7 +632,7 @@ Obtains the numeric mask combination for the USB function list in Device mode. ...@@ -552,7 +632,7 @@ Obtains the numeric mask combination for the USB function list in Device mode.
let ret = usb.getCurrentFunctions(); let ret = usb.getCurrentFunctions();
``` ```
## usb.getPorts<sup>9+</sup> ## usb.getPorts
getPorts(): Array\<USBPort\> getPorts(): Array\<USBPort\>
...@@ -566,7 +646,7 @@ Obtains the list of all physical USB ports. ...@@ -566,7 +646,7 @@ Obtains the list of all physical USB ports.
| Type | Description | | Type | Description |
| ----------------------------- | --------------------- | | ----------------------------- | --------------------- |
| [Array\<USBPort\>](#usbport9) | List of physical USB ports.| | [Array\<USBPort\>](#usbport) | List of physical USB ports.|
**Example** **Example**
...@@ -574,7 +654,7 @@ Obtains the list of all physical USB ports. ...@@ -574,7 +654,7 @@ Obtains the list of all physical USB ports.
let ret = usb.getPorts(); let ret = usb.getPorts();
``` ```
## usb.getSupportedModes<sup>9+</sup> ## usb.getSupportedModes
getSupportedModes(portId: number): PortModeType getSupportedModes(portId: number): PortModeType
...@@ -594,7 +674,7 @@ Obtains the mask combination for the supported mode list of a given USB port. ...@@ -594,7 +674,7 @@ Obtains the mask combination for the supported mode list of a given USB port.
| Type | Description | | Type | Description |
| ------------------------------ | -------------------------- | | ------------------------------ | -------------------------- |
| [PortModeType](#portmodetype9) | Mask combination for the supported mode list.| | [PortModeType](#portmodetype) | Mask combination for the supported mode list.|
**Example** **Example**
...@@ -602,7 +682,7 @@ Obtains the mask combination for the supported mode list of a given USB port. ...@@ -602,7 +682,7 @@ Obtains the mask combination for the supported mode list of a given USB port.
let ret = usb.getSupportedModes(0); let ret = usb.getSupportedModes(0);
``` ```
## usb.setPortRoles<sup>9+</sup> ## usb.setPortRoles
setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\<boolean\> setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\<boolean\>
...@@ -617,8 +697,8 @@ Sets the role types supported by a specified port, which can be **powerRole** (f ...@@ -617,8 +697,8 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | -------------------------------- | ---- | ---------------- | | --------- | -------------------------------- | ---- | ---------------- |
| portId | number | Yes | Port number. | | portId | number | Yes | Port number. |
| powerRole | [PowerRoleType](#powerroletype9) | Yes | Role for charging. | | powerRole | [PowerRoleType](#powerroletype) | Yes | Role for charging. |
| dataRole | [DataRoleType](#dataroletype9) | Yes | Role for data transfer.| | dataRole | [DataRoleType](#dataroletype) | Yes | Role for data transfer.|
**Return value** **Return value**
...@@ -638,16 +718,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain ...@@ -638,16 +718,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- | | ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Endpoint address. | | address | number | Yes|Endpoint address. |
| attributes | number | Endpoint attributes. | | attributes | number | Yes|Endpoint attributes. |
| interval | number | Endpoint interval. | | interval | number | Yes|Endpoint interval. |
| maxPacketSize | number | Maximum size of data packets on the endpoint. | | maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction. | | direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. |
| number | number | Endpoint number. | | number | number | Yes|Endpoint number. |
| type | number | Endpoint type. | | type | number | Yes|Endpoint type. |
| interfaceId | number | Unique ID of the interface to which the endpoint belongs.| | interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.|
## USBInterface ## USBInterface
...@@ -655,15 +735,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U ...@@ -655,15 +735,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | --------------------- | | ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Unique ID of the USB interface. | | id | number | Yes|Unique ID of the USB interface. |
| protocol | number | Interface protocol. | | protocol | number | Yes|Interface protocol. |
| clazz | number | Device type. | | clazz | number | Yes|Device type. |
| subClass | number | Device subclass. | | subClass | number | Yes|Device subclass. |
| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.| | alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.|
| name | string | Interface name. | | name | string | Yes|Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Endpoints that belong to the USB interface. | | endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. |
## USBConfig ## USBConfig
...@@ -671,15 +751,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip ...@@ -671,15 +751,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- | | -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Unique ID of the USB configuration. | | id | number | Yes|Unique ID of the USB configuration. |
| attributes | number | Configuration attributes. | | attributes | number | Yes|Configuration attributes. |
| maxPower | number | Maximum power consumption, in mA. | | maxPower | number | Yes|Maximum power consumption, in mA. |
| name | string | Configuration name, which can be left empty. | | name | string | Yes|Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Support for remote wakeup.| | isRemoteWakeup | boolean | Yes|Support for remote wakeup.|
| isSelfPowered | boolean | Support for independent power supplies.| | isSelfPowered | boolean | Yes| Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Supported interface attributes. | | interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. |
## USBDevice ## USBDevice
...@@ -687,21 +767,21 @@ Represents the USB device information. ...@@ -687,21 +767,21 @@ Represents the USB device information.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- | | ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Bus address. | | busNum | number | Yes|Bus address. |
| devAddress | number | Device address. | | devAddress | number | Yes|Device address. |
| serial | string | Sequence number. | | serial | string | Yes|Sequence number. |
| name | string | Device name. | | name | string | Yes|Device name. |
| manufacturerName | string | Device manufacturer. | | manufacturerName | string | Yes| Device manufacturer. |
| productName | string | Product name. | | productName | string | Yes|Product name. |
| version | string | Version number. | | version | string | Yes|Version number. |
| vendorId | number | Vendor ID. | | vendorId | number | Yes|Vendor ID. |
| productId | number | Product ID. | | productId | number | Yes|Product ID. |
| clazz | number | Device class. | | clazz | number | Yes|Device class. |
| subClass | number | Device subclass. | | subClass | number | Yes|Device subclass. |
| protocol | number | Device protocol code. | | protocol | number | Yes|Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Device configuration descriptor information.| | configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes|Device configuration descriptor information.|
## USBDevicePipe ## USBDevicePipe
...@@ -709,10 +789,10 @@ Represents a USB device pipe, which is used to determine a USB device. ...@@ -709,10 +789,10 @@ Represents a USB device pipe, which is used to determine a USB device.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| ---------- | ------ | ----- | | ---------- | ------ | ----- |----- |
| busNum | number | Bus address.| | busNum | number |Yes| Bus address.|
| devAddress | number | Device address.| | devAddress | number |Yes| Device address.|
## USBControlParams ## USBControlParams
...@@ -720,16 +800,16 @@ Represents control transfer parameters. ...@@ -720,16 +800,16 @@ Represents control transfer parameters.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- | | ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Request type. | | request | number | Yes |Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Request target type. | | target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Control request type. | | reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. |
| value | number | Request parameter value. | | value | number | Yes |Request parameter value. |
| index | number | Index of the request parameter value.| | index | number | Yes |Index of the request parameter value.|
| data | Uint8Array | Buffer for writing or reading data. | | data | Uint8Array | Yes |Buffer for writing or reading data. |
## USBPort<sup>9+</sup> ## USBPort
Represents a USB port. Represents a USB port.
...@@ -737,13 +817,13 @@ Represents a USB port. ...@@ -737,13 +817,13 @@ Represents a USB port.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory |Description |
| -------------- | -------------------------------- | ----------------------------------- | | -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Unique identifier of a USB port. | | id | number | Yes |Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype9) | Numeric mask combination for the supported mode list.| | supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus9) | USB port role. | | status | [USBPortStatus](#usbportstatus) | Yes |USB port role. |
## USBPortStatus<sup>9+</sup> ## USBPortStatus
Enumerates USB port roles. Enumerates USB port roles.
...@@ -751,11 +831,11 @@ Enumerates USB port roles. ...@@ -751,11 +831,11 @@ Enumerates USB port roles.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type| Description | | Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------------- | | ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Current USB mode. | | currentMode | number | Yes|Current USB mode. |
| currentPowerRole | number | Current power role. | | currentPowerRole | number | Yes |Current power role. |
| currentDataRole | number | Current data role.| | currentDataRole | number | Yes |Current data role.|
## USBRequestTargetType ## USBRequestTargetType
...@@ -765,10 +845,10 @@ Enumerates request target types. ...@@ -765,10 +845,10 @@ Enumerates request target types.
| Name | Value | Description | | Name | Value | Description |
| ---------------------------- | ---- | ------ | | ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device.| | USB_REQUEST_TARGET_DEVICE | 0 | Device|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.| | USB_REQUEST_TARGET_INTERFACE | 1 | Interface|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint.| | USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint|
| USB_REQUEST_TARGET_OTHER | 3 | Other.| | USB_REQUEST_TARGET_OTHER | 3 | Other|
## USBControlRequestType ## USBControlRequestType
...@@ -778,9 +858,9 @@ Enumerates control request types. ...@@ -778,9 +858,9 @@ Enumerates control request types.
| Name | Value | Description | | Name | Value | Description |
| ------------------------- | ---- | ------ | | ------------------------- | ---- | ------ |
| USB_REQUEST_TYPE_STANDARD | 0 | Standard.| | USB_REQUEST_TYPE_STANDARD | 0 | Standard|
| USB_REQUEST_TYPE_CLASS | 1 | Class. | | USB_REQUEST_TYPE_CLASS | 1 | Class |
| USB_REQUEST_TYPE_VENDOR | 2 | Vendor.| | USB_REQUEST_TYPE_VENDOR | 2 | Vendor|
## USBRequestDirection ## USBRequestDirection
...@@ -793,7 +873,7 @@ Enumerates request directions. ...@@ -793,7 +873,7 @@ Enumerates request directions.
| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.| | USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.|
| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.| | USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.|
## FunctionType<sup>9+</sup> ## FunctionType
Enumerates USB device function types. Enumerates USB device function types.
...@@ -814,7 +894,7 @@ Enumerates USB device function types. ...@@ -814,7 +894,7 @@ Enumerates USB device function types.
| AUDIO_SOURCE | 128 | Not supported currently.| | AUDIO_SOURCE | 128 | Not supported currently.|
| NCM | 256 | Not supported currently.| | NCM | 256 | Not supported currently.|
## PortModeType<sup>9+</sup> ## PortModeType
Enumerates USB port mode types. Enumerates USB port mode types.
...@@ -830,7 +910,7 @@ Enumerates USB port mode types. ...@@ -830,7 +910,7 @@ Enumerates USB port mode types.
| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.| | DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.|
| NUM_MODES | 4 | Not supported currently. | | NUM_MODES | 4 | Not supported currently. |
## PowerRoleType<sup>9+</sup> ## PowerRoleType
Enumerates power role types. Enumerates power role types.
...@@ -844,7 +924,7 @@ Enumerates power role types. ...@@ -844,7 +924,7 @@ Enumerates power role types.
| SOURCE | 1 | External power supply.| | SOURCE | 1 | External power supply.|
| SINK | 2 | Internal power supply.| | SINK | 2 | Internal power supply.|
## DataRoleType<sup>9+</sup> ## DataRoleType
Enumerates data role types. Enumerates data role types.
......
# Application Event Logging Error Codes
## 11100001 Application Event Logging Disabled
**Error Message**
Function is disabled.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related events because the logging function is disabled.
**Possible Causes**
The application event logging function is disabled.
**Solution**
Invoke the **configure** API to enable the application event logging function.
```js
hiAppEvent.configure({
disable: false
});
```
## 11101001 Invalid Event Domain Name
**Error Message**
Invalid event domain.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related events because the input event domain name is invalid.
**Possible Causes**
The specified event domain name does not comply with the following rules:
- The event domain name contains only digits, lowercase letters, and underscores (\_).
- The event domain name starts with a lowercase letter and does not end with an underscore (\_).
- 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
**Error Message**
Invalid event name.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related events because the input event name is invalid.
**Possible Causes**
The specified event name does not comply with the following rules:
- The event name contains only digits, lowercase letters, and underscores (\_).
- The event name starts with a lowercase letter and does not end with an underscore (\_).
- The event name is not empty and contains a maximum of 48 characters.
**Solution**
Specify a valid event name.
## 11101003 Invalid Number of Event Parameters
**Error Message**
Invalid number of event parameters.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system discards extra event parameters because the number of input event parameters exceeds the limit.
**Possible Causes**
The number of input event parameters exceeds 32.
**Solution**
Specify a valid number of event parameters.
## 11101004 Invalid Event Parameter String Length
**Error Message**
Invalid string length of the event parameter.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related event parameters because the value of the input event parameter is excessively long.
**Possible Causes**
The length of the input event parameter value exceeds 8 x 1024 characters.
**Solution**
Specify an event parameter value with a valid length.
## 11101005 Invalid Event Parameter Name
**Error Message**
Invalid event parameter name.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related event parameters because the input event parameter name is invalid.
**Possible Causes**
The specified event parameter name does not comply with the following rules:
- The event parameter name contains only digits, lowercase letters, and underscores (\_).
- The event parameter name starts with a lowercase letter and does not end with an underscore (\_).
- The event parameter name is not empty and contains a maximum of 16 characters.
**Solution**
Specify a valid event parameter name.
## 11101006 Invalid Array Length of Event Parameter Values
**Error Message**
Invalid array length of the event parameter.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system discards extra array elements because the array of the event parameter value is excessively long.
**Possible Causes**
The array length of the event parameter value exceeds 100.
**Solution**
Specify a valid array length for the event parameter value.
## 11102001 Invalid Watcher Name
**Error Message**
Invalid watcher name.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because the specified watcher name is invalid.
**Possible Causes**
The specified watcher name does not comply with the following rules:
- The watcher name can contain only digits, lowercase letters, and underscores (\_).
- The watcher name starts with a lowercase letter and does not end with an underscore (\_).
- The watcher name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid watcher name.
## 11102002 Invalid Filtering Event Domain Name
**Error Message**
Invalid filtering event domain.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because the specified filtering event domain name is invalid.
**Possible Causes**
The specified filtering event domain name does not comply with the following rules:
- The event domain name contains only digits, lowercase letters, and underscores (\_).
- The event domain name starts with a lowercase letter and does not end with an underscore (\_).
- The event domain name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid filtering event domain name.
## 11102003 Invalid Event Number
**Error Message**
Invalid row value.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because an invalid event number is passed in the callback trigger condition.
**Possible Causes**
The event number passed in the input callback triggering condition is a negative number.
**Solution**
Specify a valid event number.
## 11102004 Invalid Event Size
**Error Message**
Invalid size value.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because an invalid event size is passed in the callback trigger condition.
**Possible Causes**
The event size passed in the input callback triggering condition is a negative number.
**Solution**
Specify a valid event size.
## 11102005 Invalid Timeout Value
**Error Message**
Invalid timeout value.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because an invalid timeout value is passed in the callback trigger condition.
**Possible Causes**
The timeout value passed in the input callback triggering condition is a negative number.
**Solution**
Specify a valid timeout value.
## 11103001 Invalid Maximum Storage Quota
**Error Message**
Invalid max storage quota value.
**Description**
This error code is reported if the **configure** API is called to subscribe to application events but the system ignores the setting because the specified maximum storage quota is invalid.
**Possible Causes**
The maximum storage quota does not meet the following rules:
- The quota value consists of only digits and a unit (including b|k|kb|m|mb|g|gb|t|tb, which are case-insensitive).
- The quota value must start with a digit. You can determine whether to pass the unit. If the unit is left empty, **b** (that is, byte) is used by default.
**Solution**
Specify a valid maximum storage quota.
## 11104001 Invalid Event Package Size
**Error Message**
Invalid size value.
**Description**
This error code is reported if the **setSize** API is called to set the threshold of the event package size but the system ignores the setting because the specified event package size is invalid.
**Possible Causes**
The specified event package size is a negative number.
**Solution**
Specify a valid event package size.
# HiSysEvent Error Codes
## 1120001 Invalid Event Domain
**Error Message**
Invalid event domain.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the input event domain name is invalid.
**Possible Causes**
1. The event domain name contains more than 16 characters.
2. The event domain name contains special characters.
3. The event domain name is empty.
**Solution**
Specify a valid event domain name.
## 1120002 Invalid Event Name
**Error Message**
Invalid event name.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the input event name is invalid.
**Possible Causes**
1. The event name contains more than 32 characters.
2. The event name contains special characters.
3. The event name is empty.
**Solution**
Check whether the event name is valid.
## 11200003 Environment Error
**Error Message**
Abnormal environment.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the environment is abnormal.
**Possible Causes**
1. The hiview service fails to be started.
2. The socket of the hiview service is abnormal.
**Solution**
Call the **write** API again to perform event logging.
## 11200004 Invalid Event Length
**Error Message**
Length of the event is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the total event length is invalid.
**Possible Causes**
The total event length exceeds 384 KB.
**Solution**
Check whether the total event length is greater than 384 KB.
## 11200051 Invalid Event Parameter
**Error Message**
Invalid event parameter.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the input parameter name is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
1. The event parameter name contains more than 32 characters.
2. The event parameter name contains special characters.
3. The event parameter name is empty.
**Solution**
Check whether the event parameter name is valid.
## 11200052 Length of Event Parameter Values of the String Type Exceeding the Limit
**Error Message**
Size of the event parameter of the string type is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the length of event parameter values of the string type is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
The length of parameter values of the string type exceeds 10 KB.
**Solution**
Check whether the length of parameter values of the string type exceeds 10 KB.
## 11200053 Number of Event Parameters Exceeding the Limit
**Error Message**
Count of event parameters is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the number of event parameters is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
The number of event parameters exceeds 128.
**Solution**
Check whether the number of event parameters exceeds 128.
## 11200054 Length of Event Parameter Values of the Array Type Exceeding the Limit
**Error Message**
Count of event parameter of the array type is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the length of event parameter values of the array type is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
The length of a parameter values of the array type exceeds 100.
**Solution**
Check whether the length of the parameter value of the array type exceeds 100.
## 11200101 Number of Event Watchers Exceeding the Limit
**Error Message**
Count of watchers is over limit.
**Description**
This error code is reported if the **addWatcher** API is called to add an event watcher but the system rejects the operation because the number of watchers has exceeded the limit.
**Possible Causes**
A total of 30 event watchers have been added.
**Solution**
Check whether the number of event watchers exceeds 30.
## 11200102 Number of Event Watcher Rules Exceeding the Limit
**Error Message**
Count of watch rules is over limit.
**Description**
This error code is reported if the **addWatcher** API is called to add an event watcher but the system rejects the operation because the number of watcher rules has exceeded the limit.
**Possible Causes**
A total of 20 event watcher rules have been added.
**Solution**
Check whether the number of event watcher rules exceeds 20.
## 11200201 Event Watcher Not Exist
**Error Message**
The watcher does not exist.
**Description**
This error code is reported if the **removeWatcher** API is called to remove an event watcher but the system rejects the operation because the watcher does not exist.
**Possible Causes**
1. The event watcher to be removed is empty.
2. The event watcher to be removed has not been successfully added.
**Solution**
Check whether the event watcher to the removed is empty or whether the event watcher has been successfully added.
## 11200301 Number of Query Rules Exceeding the Limit
**Error Message**
Count of query rules is over limit.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the number of query rules has exceeded the limit.
**Possible Causes**
The number of query rules exceeds 10.
**Solution**
Check whether the number of query rules exceeds 10.
## 11200302 Invalid Query Rule
**Error Message**
Invalid query rule.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the input query rule is invalid.
**Possible Causes**
1. The event domain name in the query rule contains more than 16 characters or the event name contains more than 32 characters.
2. The event domain name or event name in the query rule contains special characters.
3. The event domain name or event name in the query rule is empty.
**Solution**
Check whether the event domain name and event name configured in the query rule are valid.
## 11200303 Number of Concurrent Queries Exceeding the Limit
**Error Message**
Count of concurrent queries is over limit.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the number of concurrent queries has exceeded the limit.
**Possible Causes**
The number of concurrent queries exceeds 4.
**Solution**
Check whether more than four queries are performed at the same time.
## 11200304 Query Frequency Exceeding the Limit
**Error Message**
Query frequency is over limit.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the query frequency has exceeded the limit.
**Possible Causes**
More than one query is performed in one second.
**Solution**
Check whether more than one query is performed in one second.
# HiDebug Error Codes
## 11400101 Failed to Obtain the System Service
**Error Message**
ServiceId is invalid, systemAbility is not exist.
**Description**
No system service is found based on the specified service ID.
**Possible Causes**
The specified service ID is incorrect.
**Solution**
Specify a correct system service ID.
# USB Error Codes
## 14400001 USB Device Connection Denied
**Error Message**
Permission denied. Need call requestRight to get permission.
**Description**
This error code is reported if a certain API of the USB module is called but the required permission is not granted.
**Possible Causes**
The permission to access the USB device is not granted.
**Solution**
Call **requestRight** to request for the permission to access the USB device.
# USB # USB
## Introduction
## Overview ### Function Overview
USB host development aims to provide host-related functions, including protocol encapsulation, device management, and driver installation and uninstall. The universal serial bus (USB) consists of a USB host and multiple USB devices. The USB host implement data transfer and port management in the USB bus, and the USB device can connect to various peripherals. Therefore, USB driver development is divided into USB host driver development and USB device driver development.
USB device development aims to provide device-related functions, including device management, configuration management, and I/O management. These functions implement creation, configuration, and data communication of USB devices. The USB module of OpenHarmony supports the development of USB services, provides USB-related functions, provides interfaces to read and write USB device data of third-party function drivers in user mode, creates and deletes USB devices, obtains notification events, enables or disables event listening, implements non-isochronous and isochronous data transfer over USB pipes, and sets custom USB attributes.
The following figures show the USB host and device driver models. The USB DriverDevelop Kit (DDK) is the USB driver development kit provided by the Framework of the OpenHarmony Driver Foundation (HDF). This kit consists of the USB Host DDK and USB Device DDK. It supports the development of USB device drivers based on the user mode and provides rich USB driver development capabilities that help you to efficiently develop USB drivers.
### Basic Concepts
- Pipe
A pipe is a model for data transfer between the USB host and a device endpoint. Once a USB device is powered on, a pipe, that is, the default control pipe, is established. The USB host obtains the description, configuration, and status of the USB device through the pipe, and configures the device as requested. Pipes and endpoints are associated and share the same attributes, such as the supported transfer type, maximum packet length, and data transfer direction.
- Endpoint
The minimum unit that transfers and receives data in a USB device. It supports unidirectional or bidirectional data transfer. One USB device may include several endpoints, and different endpoints are distinguished by endpoint numbers and directions. Different endpoints can support different data transfer types, access intervals, and maximum packet sizes. All endpoints except endpoint 0 support data transfer in only one direction. Endpoint 0 is a special endpoint that supports bidirectional control transfer.
- Interface
The application implements device control and data transfer through exchanging data with the device. Because a pipe supports only one data transfer type, multiple pipes are usually required to complete data exchange in this process. A collection of pipes that are used together to control a device is called an interface.
- Descriptor
A data structure used to describe device attributes. The first byte indicates the descriptor size (number of bytes), and the second byte indicates the descriptor type.
### Working Principles
#### USB Host DDK
The USB Host DDK provides the capability of developing USB drivers on the host. Based on functions, APIs of the USB Host DDK are classified into three types: DDK initialization, **interface** object operation, and **request** object operation.
**Figure 1** USB host driver model **Figure 1** USB host driver model
![](figures/USB_host_driver_model.png "USB host driver model") ![](figures/USB_host_driver_model.png "USB host driver model")
- The USB Interface Pool module manages USB interfaces. It applies for and reclaims USB interface objects, which are used to record device port information and resources. The module manages USB interfaces by USB port. In addition, it provides USB DDK APIs to read and write USB data.
- The USB Protocol Layer module provides USB protocol encapsulation, translates and parses device I/O and control commands based on the USB protocol, manages device descriptors, and matches descriptors based on the enum information reported by the USB device. This module creates the corresponding USB interface objects and adds them to the USB Interface Pool module for management.
- The Device I/O Manager module manages USB I/O requests and provides synchronous and asynchronous I/O management mechanisms. For the asynchronous I/O management mechanism, the module records the asynchronous I/O requests and processes the requests to be sent through the APIs provided by the Raw API Library module. After receiving the processing result from the USB controller, the I/O request receiving thread parses the processing result and reports it to the upper-layer caller.
- The Raw API Library module abstracts underlying OS capabilities, defines unified OS capability APIs, and provides the USB RAW APIs needed to implement more complex driver functions.
- The OS Adapter module encapsulates operations related to platforms (Linux and LiteOS). It compiles encapsulation APIs depending on the configuration of the specific platform. On the Linux platform, all USB FS access operations are encapsulated in this module. On the LiteOS platform, all device access operations based on the FreeBSD USB framework are encapsulated in this module.
- The PNP Notify module dynamically monitors USB status changes. This module updates the device information when a device is added or removed. Meanwhile, it reports all USB device information to the PNP Notify Manager module on the UHDF side through the KHDF to load or uninstall third-party function drivers.
#### USB Device DDK
The USB Device DDK provides the capability of developing USB drivers on the device side. For example, with the dynamic registration and deregistration capabilities, you can dynamically add and combine USB ports based on the actual requirement; with the dynamic instantiation capability, you can create device instances and transmission channels based on dynamically delivered device, configuration, interface, and endpoint descriptors. In addition, the following functions are supported: sending and receiving data in user mode, isolating multiple logical devices from each other on a physical device, and accessing different logical devices from different application processes at the same time.
**Figure 2** USB device driver model **Figure 2** USB device driver model
![](figures/USB_device_driver_model.png "USB device driver model") ![](figures/USB_device_driver_model.png "USB device driver model")
The USB driver model offers the following APIs: - The SDK IF module divides USB devices logically by device, interface, and pipe, and encapsulates functions including configuration management, device management, and I/O management. This module also provides APIs for device driver development, such as creating and obtaining devices, receiving events, and sending and receiving data.
- The Configuration Manager module parses the .hcs file for the USB descriptor information, which will be used for creating USB devices. In addition, the module provides operations such as reading, creating, deleting, and modifying custom USB attributes.
- The Device Manager module parses USB descriptor information and creates USB devices accordingly. It also provides functions such as adding or deleting USB devices, obtaining USB device status, and obtaining USB device interface information.
- The IO Manager module reads and writes data, including common events and data read and write events. It supports data read and write in synchronous and asynchronous modes.
- The Adapter IF module encapsulates device node operations of composite device configuration drivers and common function drivers to provide unified device management APIs for the upper layer.
- The Adapter module is provided by the composite device configuration driver and common function driver.
## How to Develop
- The USB host Driver Development Kit (DDK) provides driver capability APIs that can be directly called in user mode. The APIs can be classified into the DDK initialization class, interface operation class, and request operation class by function. These APIs can be used to perform DDK initialization, bind/release and open/close an interface, allocate/release a request, and implement synchronous or asynchronous transfer. The USB driver development in kernel mode is complex. Therefore, you need to have a deep understanding of the USB protocol. The USB DDK is introduced to help you to develop USB drivers in user mode more conveniently.
- The USB device DDK provides device management, I/O management, and configuration management APIs, which can be used to create or delete a device, obtain or open an interface, and perform synchronous or asynchronous transfer. ### When to Use
The USB Host DDK comes with two modes, namely, common mode and expert mode. In common mode, you can directly read and write USB data by using USB DDK APIs without knowing details about data transfer at the bottom layer. In expert mode, you can use USB RAW APIs to directly access the USB channel interfaces provided by the OS platform to implement more complex functions. The USB Device DDk provides functions such as USB device management, interface definition, and USB data request.
### Available APIs ### Available APIs
The tables below describe the APIs provided by the USB host driver model. The following table lists the APIs related to USB host driver development (common mode). For details about the API definitions, see the [source code](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/host/usb_ddk_interface.h).
**Table 1** usb_ddk_interface.h **Table 1** APIs for USB host driver development (common mode)
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| int32_t&nbsp;UsbInitHostSdk(struct&nbsp;UsbSession&nbsp;\*\*session); | Initializes the USB host driver DDK.| | int32_t&nbsp;UsbInitHostSdk(struct&nbsp;UsbSession&nbsp;\*\*session); | Initializes the USB host driver DDK.|
| int32_t&nbsp;UsbExitHostSdk(const&nbsp;struct&nbsp;UsbSession<br>\*session); | Exits the USB host driver DDK.|
| const&nbsp;struct&nbsp;UsbInterface&nbsp;\*UsbClaimInterface(const<br>struct&nbsp;UsbSession&nbsp;\*session,&nbsp;uint8_t&nbsp;busNum,&nbsp;uint8_t<br>usbAddr,&nbsp;uint8_t&nbsp;interfaceIndex); | Obtains a USB interface.| | const&nbsp;struct&nbsp;UsbInterface&nbsp;\*UsbClaimInterface(const<br>struct&nbsp;UsbSession&nbsp;\*session,&nbsp;uint8_t&nbsp;busNum,&nbsp;uint8_t<br>usbAddr,&nbsp;uint8_t&nbsp;interfaceIndex); | Obtains a USB interface.|
| int&nbsp;UsbReleaseInterface(const&nbsp;struct&nbsp;UsbInterface<br>\*interfaceObj); | Releases a USB interface.|
| int&nbsp;UsbAddOrRemoveInterface(const&nbsp;struct&nbsp;UsbSession<br>\*session,&nbsp;uint8_t&nbsp;busNum,&nbsp;uint8_t&nbsp;usbAddr,&nbsp;uint8_t<br>interfaceIndex,&nbsp;UsbInterfaceStatus&nbsp;status); | Adds or removes a USB interface.|
| UsbInterfaceHandle&nbsp;\*UsbOpenInterface(const&nbsp;struct<br>UsbInterface&nbsp;\*interfaceObj); | Opens a USB interface.| | UsbInterfaceHandle&nbsp;\*UsbOpenInterface(const&nbsp;struct<br>UsbInterface&nbsp;\*interfaceObj); | Opens a USB interface.|
| int32_t&nbsp;UsbCloseInterface(const&nbsp;UsbInterfaceHandle<br>\*interfaceHandle); | Closes a USB interface.|
| int32_t&nbsp;UsbSelectInterfaceSetting(const<br>UsbInterfaceHandle&nbsp;\*interfaceHandle,&nbsp;uint8_t<br>settingIndex,&nbsp;struct&nbsp;UsbInterface&nbsp;\*\*interfaceObj); | Sets a USB interface.|
| int32_t&nbsp;UsbGetPipeInfo(const&nbsp;UsbInterfaceHandle<br>\*interfaceHandle,&nbsp;uint8_t&nbsp;settingIndex,&nbsp;uint8_t&nbsp;pipeId,<br>struct&nbsp;UsbPipeInfo&nbsp;\*pipeInfo); | Obtains USB pipe information.| | int32_t&nbsp;UsbGetPipeInfo(const&nbsp;UsbInterfaceHandle<br>\*interfaceHandle,&nbsp;uint8_t&nbsp;settingIndex,&nbsp;uint8_t&nbsp;pipeId,<br>struct&nbsp;UsbPipeInfo&nbsp;\*pipeInfo); | Obtains USB pipe information.|
| int32_t&nbsp;UsbClearInterfaceHalt(const<br>UsbInterfaceHandle&nbsp;\*interfaceHandle,&nbsp;uint8_t<br>pipeAddress); | Clears the state of the pipe with the specified index.| | struct&nbsp;UsbRequest&nbsp;\*UsbAllocRequest(const<br>UsbInterfaceHandle&nbsp;\*interfaceHandle,&nbsp;int32_t&nbsp;isoPackets<br>,&nbsp;int32_t&nbsp;length); | Allocates a request object.|
| struct&nbsp;UsbRequest&nbsp;\*UsbAllocRequest(const<br>UsbInterfaceHandle&nbsp;\*interfaceHandle,&nbsp;int&nbsp;isoPackets<br>,&nbsp;int&nbsp;length); | Allocates a request object.|
| int&nbsp;UsbFreeRequest(const&nbsp;struct&nbsp;UsbRequest<br>\*request); | Releases a request object.|
| int&nbsp;UsbSubmitRequestAsync(const&nbsp;struct&nbsp;UsbRequest<br>\*request); | Sends an asynchronous request.|
| int32_t&nbsp;UsbFillRequest(const&nbsp;struct&nbsp;UsbRequest<br>\*request,&nbsp;const&nbsp;UsbInterfaceHandle&nbsp;\*interfaceHandle,<br>const&nbsp;struct&nbsp;UsbRequestParams&nbsp;\*params); | Fills in a request.| | int32_t&nbsp;UsbFillRequest(const&nbsp;struct&nbsp;UsbRequest<br>\*request,&nbsp;const&nbsp;UsbInterfaceHandle&nbsp;\*interfaceHandle,<br>const&nbsp;struct&nbsp;UsbRequestParams&nbsp;\*params); | Fills in a request.|
| sint&nbsp;UsbCancelRequest(const&nbsp;struct&nbsp;UsbRequest<br>\*request); | Cancels an asynchronous request.| | int32_t&nbsp;UsbSubmitRequestSync(const&nbsp;struct&nbsp;UsbRequest<br>\*request); | Sends a synchronous request.|
| int&nbsp;UsbSubmitRequestSync(const&nbsp;struct&nbsp;UsbRequest<br>\*request); | Sends a synchronous request.|
The following table lists the APIs related to USB host driver development (expert mode). For details about the API definitions, see the [source code](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/host/usb_raw_api.h).
**Table 2** usb_raw_api.h **Table 2** APIs for USB host driver development (expert mode)
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| int&nbsp;UsbRawInit(struct&nbsp;UsbSession&nbsp;\*\*session); | Initializes the USB raw APIs.| | int32_t&nbsp;UsbRawInit(struct&nbsp;UsbSession&nbsp;\*\*session); | Initializes the USB raw APIs.|
| int&nbsp;UsbRawExit(const&nbsp;struct&nbsp;UsbSession&nbsp;\*session); | Exits the USB raw APIs.|
| UsbRawHandle&nbsp;\*UsbRawOpenDevice(const&nbsp;struct<br>UsbSession&nbsp;\*session,&nbsp;uint8_t&nbsp;busNum,&nbsp;uint8_t<br>usbAddr); | Opens a USB device.| | UsbRawHandle&nbsp;\*UsbRawOpenDevice(const&nbsp;struct<br>UsbSession&nbsp;\*session,&nbsp;uint8_t&nbsp;busNum,&nbsp;uint8_t<br>usbAddr); | Opens a USB device.|
| int&nbsp;UsbRawCloseDevice(const&nbsp;UsbRawHandle<br>\*devHandle); | Closes a USB device.| | int32_t&nbsp;UsbRawSendControlRequest(const&nbsp;struct<br>UsbRawRequest&nbsp;\*request,&nbsp;const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;const&nbsp;struct&nbsp;UsbControlRequestData<br>\*requestData); | Performs a control transfer synchronously.|
| int&nbsp;UsbRawSendControlRequest(const&nbsp;struct<br>UsbRawRequest&nbsp;\*request,&nbsp;const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;const&nbsp;struct&nbsp;UsbControlRequestData<br>\*requestData); | Performs a control transfer synchronously.| | int32_t&nbsp;UsbRawSendBulkRequest(const&nbsp;struct<br>UsbRawRequest&nbsp;\*request,&nbsp;const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;const&nbsp;struct&nbsp;UsbRequestData<br>\*requestData); | Performs a bulk transfer synchronously.|
| int&nbsp;UsbRawSendBulkRequest(const&nbsp;struct<br>UsbRawRequest&nbsp;\*request,&nbsp;const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;const&nbsp;struct&nbsp;UsbRequestData<br>\*requestData); | Performs a bulk transfer synchronously.| | int32_t&nbsp;UsbRawSendInterruptRequest(const&nbsp;struct<br>UsbRawRequest&nbsp;\*request,&nbsp;const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;const&nbsp;struct&nbsp;UsbRequestData<br>\*requestData); | Performs an interrupt transfer synchronously.|
| int&nbsp;UsbRawSendInterruptRequest(const&nbsp;struct<br>UsbRawRequest&nbsp;\*request,&nbsp;const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;const&nbsp;struct&nbsp;UsbRequestData<br>\*requestData); | Performs an interrupt transfer synchronously.| | int32_t&nbsp;UsbRawGetConfigDescriptor(const&nbsp;UsbRawDevice<br>\*rawDev,&nbsp;uint8_t&nbsp;configIndex,&nbsp;struct<br>UsbRawConfigDescriptor&nbsp;\*\*config); | Obtains the configuration descriptor of a device.|
| int&nbsp;UsbRawGetConfigDescriptor(const&nbsp;UsbRawDevice<br>\*rawDev,&nbsp;uint8_t&nbsp;configIndex,&nbsp;struct<br>UsbRawConfigDescriptor&nbsp;\*\*config); | Obtains the configuration descriptor of a device.| | int32_t&nbsp;UsbRawFillInterruptRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawFillRequestData&nbsp;\*fillData); | Fills in an interrupt transfer request.|
| void&nbsp;UsbRawFreeConfigDescriptor(const&nbsp;struct<br>UsbRawConfigDescriptor&nbsp;\*config); | Releases the memory space of a configuration descriptor.| | int32_t&nbsp;UsbRawFillIsoRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawFillRequestData&nbsp;\*fillData); | Fills in an isochronous transfer request.|
| int&nbsp;UsbRawGetConfiguration(const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;int&nbsp;\*config); | Obtains the configuration in use.| | int32_t&nbsp;UsbRawSubmitRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request); | Submits a transfer request.|
| int&nbsp;UsbRawSetConfiguration(const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;int&nbsp;config); | Sets the configuration in use.| | int32_t&nbsp;UsbRawCancelRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request); | Cancels a transfer request.|
| int&nbsp;UsbRawGetDescriptor(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawDescriptorParam&nbsp;\*param,&nbsp;const&nbsp;unsigned&nbsp;char<br>\*data); | Obtains descriptor information.| | int32_t&nbsp;UsbRawHandleRequests(const&nbsp;UsbRawHandle<br>\*devHandle); | Handles a transfer request event.|
| UsbRawDevice&nbsp;\*UsbRawGetDevice(const&nbsp;UsbRawHandle<br>\*devHandle); | Obtains the device pointer based on the device handle.|
| int&nbsp;UsbRawGetDeviceDescriptor(const&nbsp;UsbRawDevice<br>\*rawDev,&nbsp;struct<br>UsbDeviceDescriptor&nbsp;\*desc); | Obtains the device descriptor of the specified USB device.| The following table lists the APIs for USB device management on the device side. For details about the API definitions, see the [source code](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/device/usbfn_device.h).
| int&nbsp;UsbRawClaimInterface(const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;int<br>interfaceNumber); | Declares the interface on the specified device handle.|
| int&nbsp;UsbRawReleaseInterface(const&nbsp;UsbRawHandle<br>\*devHandle,&nbsp;in<br>t&nbsp;interfaceNumber); | Releases the previously declared interface.| **Table 3** APIs for USB device management on the device side
| int&nbsp;UsbRawResetDevice(const&nbsp;UsbRawHandle<br>\*devHandle); | Resets a device.|
| struct&nbsp;UsbRawRequest&nbsp;\*UsbRawAllocRequest(const<br>UsbRawHandle<br>\*devHandle,&nbsp;int&nbsp;isoPackets,&nbsp;int&nbsp;length); | Allocates a transfer request with the specified number of sync packet descriptors.|
| int&nbsp;UsbRawFreeRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request); | Releases the previously allocated transfer request.|
| int&nbsp;UsbRawFillBulkRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawFillRequestData&nbsp;\*fillData); | Fills in a bulk transfer request.|
| int&nbsp;UsbRawFillControlSetup(const&nbsp;unsigned&nbsp;char&nbsp;\*setup,<br>const&nbsp;struct&nbsp;UsbControlRequestData&nbsp;\*requestData); | Fills in a control setup packet.|
| int&nbsp;UsbRawFillControlRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawFillRequestData&nbsp;\*fillData); | Fills in a control transfer request.|
| int&nbsp;UsbRawFillInterruptRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawFillRequestData&nbsp;\*fillData); | Fills in an interrupt transfer request.|
| int&nbsp;UsbRawFillIsoRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request,&nbsp;const&nbsp;UsbRawHandle&nbsp;\*devHandle,&nbsp;const&nbsp;struct<br>UsbRawFillRequestData&nbsp;\*fillData); | Fills in an isochronous transfer request.|
| int&nbsp;UsbRawSubmitRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request); | Submits a transfer request.|
| int&nbsp;UsbRawCancelRequest(const&nbsp;struct&nbsp;UsbRawRequest<br>\*request); | Cancels a transfer request.|
| int&nbsp;UsbRawHandleRequests(const&nbsp;UsbRawHandle<br>\*devHandle); | Handles a transfer request event.|
The tables below describe the APIs provided by the USB device driver model.
**Table 3** usbfn_device.h
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| const&nbsp;struct&nbsp;UsbFnDevice&nbsp;\*UsbFnCreateDevice(const<br>char&nbsp;\*udcName,&nbsp;const&nbsp;struct&nbsp;UsbFnDescriptorData<br>\*descriptor); | Creates a USB device.| | const&nbsp;struct&nbsp;UsbFnDevice&nbsp;\*UsbFnCreateDevice(const<br>char&nbsp;\*udcName,&nbsp;const&nbsp;struct&nbsp;UsbFnDescriptorData<br>\*descriptor); | Creates a USB device.|
| int&nbsp;UsbFnRemoveDevice(struct&nbsp;UsbFnDevice<br>\*fnDevice); | Deletes a USB device.| | int32_t&nbsp;UsbFnRemoveDevice(struct&nbsp;UsbFnDevice<br>\*fnDevice); | Deletes a USB device.|
| const&nbsp;struct&nbsp;UsbFnDevice&nbsp;\*UsbFnGetDevice(const&nbsp;char<br>\*udcName); | Obtains a USB device.| | const&nbsp;struct&nbsp;UsbFnDevice&nbsp;\*UsbFnGetDevice(const&nbsp;char<br>\*udcName); | Obtains a USB device.|
**Table 4** usbfn_interface.h The following table lists the APIs for USB interface definition on the device side. For details about the API definitions, see the [source code](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/device/usbfn_interface.h).
**Table 4** APIs for USB interface definition on the device side
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| int&nbsp;UsbFnStartRecvInterfaceEvent(struct<br>UsbFnInterface&nbsp;\*interface,&nbsp;uint32_t&nbsp;eventMask,<br>UsbFnEventCallback&nbsp;callback,&nbsp;void&nbsp;\*context); | Starts receiving events.| | int32_t&nbsp;UsbFnStartRecvInterfaceEvent(struct<br>UsbFnInterface&nbsp;\*interface,&nbsp;uint32_t&nbsp;eventMask,<br>UsbFnEventCallback&nbsp;callback,&nbsp;void&nbsp;\*context); | Starts receiving events.|
| int&nbsp;UsbFnStopRecvInterfaceEvent(struct<br>UsbFnInterface&nbsp;\*interface); | Stops receiving events.| | int32_t&nbsp;UsbFnStopRecvInterfaceEvent(struct<br>UsbFnInterface&nbsp;\*interface); | Stops receiving events.|
| UsbFnInterfaceHandle&nbsp;UsbFnOpenInterface(struct&nbsp;UsbFnInterface&nbsp;\*interface); | Opens an interface.| | UsbFnInterfaceHandle&nbsp;UsbFnOpenInterface(struct&nbsp;UsbFnInterface&nbsp;\*interface); | Opens an interface.|
| int&nbsp;UsbFnCloseInterface(UsbFnInterfaceHandle&nbsp;handle); | Closes an interface.| | int32_t&nbsp;UsbFnCloseInterface(UsbFnInterfaceHandle&nbsp;handle); | Closes an interface.|
| int&nbsp;UsbFnGetInterfacePipeInfo(struct&nbsp;UsbFnInterface<br>\*interface,&nbsp;uint8_t&nbsp;pipeId,&nbsp;struct&nbsp;UsbFnPipeInfo&nbsp;\*info); | Obtains pipe information.| | int32_t&nbsp;UsbFnGetInterfacePipeInfo(struct&nbsp;UsbFnInterface<br>\*interface,&nbsp;uint8_t&nbsp;pipeId,&nbsp;struct&nbsp;UsbFnPipeInfo&nbsp;\*info); | Obtains pipe information.|
| int&nbsp;UsbFnSetInterfaceProp(const&nbsp;struct&nbsp;UsbFnInterface<br>\*interface,&nbsp;const&nbsp;char&nbsp;\*name,&nbsp;const&nbsp;char&nbsp;\*value); | Sets custom properties.| | int32_t&nbsp;UsbFnSetInterfaceProp(const&nbsp;struct&nbsp;UsbFnInterface<br>\*interface,&nbsp;const&nbsp;char&nbsp;\*name,&nbsp;const&nbsp;char&nbsp;\*value); | Sets custom properties.|
The following table lists the APIs for USB data request on the device side. For details about the API definitions, see the [source code](https://gitee.com/openharmony/drivers_peripheral/blob/master/usb/interfaces/ddk/device/usbfn_request.h).
**Table 5** usbfn_request.h **Table 5** APIs for USB data request on the device side
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| struct&nbsp;UsbFnRequest<br>\*UsbFnAllocCtrlRequest(UsbFnInterfaceHandle&nbsp;handle,<br>uint32_t&nbsp;len); | Allocates a control transfer request.| | struct&nbsp;UsbFnRequest<br>\*UsbFnAllocCtrlRequest(UsbFnInterfaceHandle&nbsp;handle,<br>uint32_t&nbsp;len); | Allocates a control transfer request.|
| struct&nbsp;UsbFnRequest&nbsp;\*UsbFnAllocRequest(UsbFnInterfaceHandle&nbsp;handle,<br>uint8_t&nbsp;pipe,&nbsp;uint32_t&nbsp;len); | Allocates a data request.| | struct&nbsp;UsbFnRequest&nbsp;\*UsbFnAllocRequest(UsbFnInterfaceHandle&nbsp;handle,<br>uint8_t&nbsp;pipe,&nbsp;uint32_t&nbsp;len); | Allocates a data request.|
| int&nbsp;UsbFnFreeRequest(struct&nbsp;UsbFnRequest&nbsp;\*req); | Releases a request.| | int32_t&nbsp;UsbFnFreeRequest(struct&nbsp;UsbFnRequest&nbsp;\*req); | Releases a request.|
| int&nbsp;UsbFnSubmitRequestAsync(struct&nbsp;UsbFnRequest<br>\*req); | Sends an asynchronous request.| | int32_t&nbsp;UsbFnSubmitRequestAsync(struct&nbsp;UsbFnRequest<br>\*req); | Sends an asynchronous request.|
| int&nbsp;UsbFnSubmitRequestSync(struct&nbsp;UsbFnRequest<br>\*req,&nbsp;uint32_t&nbsp;timeout); | Sends a synchronous request.| | int32_t&nbsp;UsbFnSubmitRequestSync(struct&nbsp;UsbFnRequest<br>\*req,&nbsp;uint32_t&nbsp;timeout); | Sends a synchronous request.|
| int&nbsp;UsbFnCancelRequest(struct&nbsp;UsbFnRequest&nbsp;\*req); | Cancels a request.| | int32_t&nbsp;UsbFnCancelRequest(struct&nbsp;UsbFnRequest&nbsp;\*req); | Cancels a request.|
### How to Develop
USB drivers are developed based on the Hardware Driver Foundation (HDF), platform, and Operating System Abstraction Layer (OSAL) APIs. A unified driver model is provided for USB devices, irrespective of the operating system and chip architecture. This section uses the serial port as an example to describe how to develop USB host and USB device drivers.
#### Developing Driver Using Host DDK APIs
1. Configure USB host driver information in the .hcs file of private device data.
```cpp
root {
module = "usb_pnp_device";
usb_pnp_config {
match_attr = "usb_pnp_match";
usb_pnp_device_id = "UsbPnpDeviceId";
UsbPnpDeviceId {
idTableList = [
"host_acm_table"
];
host_acm_table {
// Driver module name, which must be the same as the value of moduleName in the driver entry structure.
moduleName = "usbhost_acm";
// Service name of the driver, which must be unique.
serviceName = "usbhost_acm_pnp_service";
// Keyword for matching private driver data.
deviceMatchAttr = "usbhost_acm_pnp_matchAttr";
// Data length starting from this field, in bytes.
length = 21;
// USB driver matching rule: vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber.
matchFlag = 0x0303;
// Vendor ID.
vendorId = 0x12D1;
// Product ID.
productId = 0x5000;
// The least significant 16 bits of the device sequence number.
bcdDeviceLow = 0x0000;
// The most significant 16 bits of the device sequence number.
bcdDeviceHigh = 0x0000;
// Device class code allocated by the USB.
deviceClass = 0;
// Child class code allocated by the USB.
deviceSubClass = 0;
// Device protocol code allocated by the USB.
deviceProtocol = 0;
// Interface type. You can enter multiple types as needed.
interfaceClass = [0];
// Interface subtype. You can enter multiple subtypes as needed.
interfaceSubClass = [2, 0];
// Protocol that the interface complies with. You can enter multiple protocols as needed.
interfaceProtocol = [1, 2];
// Interface number. You can enter multiple interface numbers as needed.
interfaceNumber = [2, 3];
}
}
}
}
```
2. Initialize the USB host driver DDK.
## How to Develop ```cpp
int32_t UsbInitHostSdk(struct UsbSession **session);
```
The USB driver is developed based on the Hardware Driver Foundation (HDF), platform, and Operating System Abstraction Layer (OSAL) APIs. A unified driver model is provided for USB devices, irrespective of the operating system and chip architecture. This document uses a serial port as an example to describe how to develop drivers for the USB host and USB device. 3. Obtain the **UsbInterface** object after initialization.
```cpp
const struct UsbInterface *UsbClaimInterface(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr, uint8_t interfaceIndex);
```
### Developing Driver Using Host DDK APIs 4. Open the **UsbInterface** object to obtain the **UsbInterfaceHandle** object.
1. Configure the driver mapping table. ```cpp
UsbInterfaceHandle *UsbOpenInterface(const struct UsbInterface *interfaceObj);
```
2. Initialize the USB host DDK. 5. Obtain pipe information of the specified **pipeIndex** based on the **UsbInterfaceHandle** object.
3. Obtain a **UsbInterface** object. ```cpp
int32_t UsbGetPipeInfo(const UsbInterfaceHandle *interfaceHandle, uint8_t settingIndex, uint8_t pipeId, struct UsbPipeInfo *pipeInfo);
```
4. Open the **UsbInterface** object to obtain the **UsbInterfaceHandle** object. 6. Pre-allocate an I/O request for the **UsbInterfaceHandle** object.
5. Obtain pipe information of the specified **pipeIndex** based on the **UsbInterfaceHandle** object. ```cpp
struct UsbRequest *UsbAllocRequest(const UsbInterfaceHandle *interfaceHandle, int32_t isoPackets, int32_t length);
6. Allocate an I/O request for the **UsbInterfaceHandle** object. ```
7. Fill in the I/O request based on the input parameters. 7. Fill in the I/O request based on the input parameters.
```cpp
int32_t UsbFillRequest(const struct UsbRequest *request, const UsbInterfaceHandle *interfaceHandle, const struct UsbRequestParams *params);
```
8. Submit the I/O request in synchronous or asynchronous mode. 8. Submit the I/O request in synchronous or asynchronous mode.
```cpp
int32_t UsbSubmitRequestSync(const struct UsbRequest *request); // Send a synchronous I/O request.
int32_t UsbSubmitRequestAsync(const struct UsbRequest *request); // Send an asynchronous I/O request.
```
### Developing Driver Using Host Raw APIs #### Developing Driver Using Host Raw APIs
1. Configure the driver mapping table. 1. Configure USB host driver information in the .hcs file of private device data. For details, see step 1 in the previous section.
2. Initialize the host raw data, open the USB device, obtain the descriptor, and then obtain interface and endpoint information based on the descriptor. 2. Initialize the host raw data, open the USB device, obtain the descriptor, and then obtain interface and endpoint information based on the descriptor.
3. Allocate a request and fill in the request based on the transfer type. ```cpp
int32_t UsbRawInit(struct UsbSession **session);
4. Submit the I/O request in synchronous or asynchronous mode. ```
3. Open the USB device.
### Developing Driver Using Device DDK APIs
```cpp
1. Construct a descriptor. UsbRawHandle *UsbRawOpenDevice(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr);
```
2. Instantiate a USB device using the descriptor constructed.
4. Obtain the device descriptor, and obtain the interface and endpoint information based on the descriptor.
3. Call **UsbFnDeviceGetInterface** to obtain an interface, call **UsbFnInterfaceGetPipeInfo** to obtain pipe information based on the interface, call **UsbFnInterfaceOpen** to open the interface to obtain the handle, and call **UsbFnRequestAlloc** to obtain the request based on the handle and pipe ID.
```cpp
4. Call **UsbFnInterfaceStartRecvEvent** to receive events such as Enable and Setup, and respond to the events in **UsbFnEventCallback**. int32_t UsbRawGetConfigDescriptor(const UsbRawDevice *rawDev, uint8_t configIndex, struct UsbRawConfigDescriptor **config);
```
5. Send and receive data in synchronous or asynchronous mode.
5. Allocate a request and fill in the request based on the transfer type.
```cpp
int32_t UsbRawFillBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // Populate the request for bulk transfer.
int32_t UsbRawFillControlSetup(const unsigned char *setup, const struct UsbControlRequestData *requestData);
int32_t UsbRawFillControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // Populate the request for control transfer.
int32_t UsbRawFillInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // Populate the request for interrupt transfer.
int32_t UsbRawFillIsoRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData); // Populate the request for isochronous transfer.
```
6. Submit the I/O request in synchronous or asynchronous mode.
```cpp
int32_t UsbRawSendControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbControlRequestData *requestData); // Send a synchronous request for control transfer.
int32_t UsbRawSendBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData); // Send a synchronous request for bulk transfer.
int32_t UsbRawSendInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData); // Send a synchronous request for interrupt transfer.
int32_t UsbRawSubmitRequest(const struct UsbRawRequest *request); // Send an asynchronous I/O request.
```
#### Developing Driver Using Device DDK APIs
1. Construct a descriptor in the device function code.
```cpp
static struct UsbFnFunction g_acmFunction = { // Function descriptor
.enable = true,
.funcName = "f_generic.a",
.strings = g_acmStrings,
.fsDescriptors = g_acmFsFunction,
.hsDescriptors = g_acmHsFunction,
.ssDescriptors = g_acmSsFunction,
.sspDescriptors = NULL,
};
struct UsbFnFunction *g_functions[] = {
#ifdef CDC_ECM
&g_ecmFunction,
#endif
#ifdef CDC_ACM
&g_acmFunction,
#endif
NULL
};
static struct UsbFnConfiguration g_masterConfig = { // Configuration descriptor
.configurationValue = 1,
.iConfiguration = USB_FUNC_CONFIG_IDX,
.attributes = USB_CFG_BUS_POWERED,
.maxPower = POWER,
.functions = g_functions,
};
static struct UsbFnConfiguration *g_configs[] = {
&g_masterConfig,
NULL,
};
static struct UsbDeviceDescriptor g_cdcMasterDeviceDesc = { // Device descriptor
.bLength = sizeof(g_cdcMasterDeviceDesc),
.bDescriptorType = USB_DDK_DT_DEVICE,
.bcdUSB = CpuToLe16(BCD_USB),
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = USB_MAX_PACKET_SIZE,
.idVendor = CpuToLe16(DEVICE_VENDOR_ID),
.idProduct = CpuToLe16(DEVICE_PRODUCT_ID),
.bcdDevice = CpuToLe16(DEVICE_VERSION),
.iManufacturer = USB_FUNC_MANUFACTURER_IDX,
.iProduct = USB_FUNC_PRODUCT_IDX,
.iSerialNumber = USB_FUNC_SERIAL_IDX,
.bNumConfigurations = 1,
};
static struct UsbFnDeviceDesc g_masterFuncDevice = { // Descriptor entry
.deviceDesc = &g_cdcMasterDeviceDesc,
.deviceStrings = g_devStrings,
.configs = g_configs,
};
```
2. Create a USB device. Call **UsbFnDeviceCreate** and pass in the UDC controller and **UsbFnDescriptorData** structure to create a USB device.
```cpp
if (useHcs == 0) { // Descriptor written in the code.
descData.type = USBFN_DESC_DATA_TYPE_DESC;
descData.descriptor = &g_acmFuncDevice;
} else { // Descriptor compiled by using the .hcs file.
descData.type = USBFN_DESC_DATA_TYPE_PROP;
descData.property = acm->device->property;
}
// Create a USB device.
fnDev = (struct UsbFnDevice *) UsbFnCreateDevice(acm->udcName, &descData);
```
3. Call **UsbFnGetInterface** to obtain a **UsbInterface** object, and call **UsbFnGetInterfacePipeInfo** to obtain the USB pipe information.
```cpp
// Obtain an interface.
fnIface = (struct UsbFnInterface *)UsbFnGetInterface(fnDev, i);
// Obtain the pipe information.
UsbFnGetInterfacePipeInfo(fnIface, i, &pipeInfo);
// Obtain a handle.
handle = UsbFnOpenInterface(fnIface);
// Obtain a control (EP0) request.
req = UsbFnAllocCtrlRequest(acm->ctrlIface.handle,
sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding));
// Obtain the request.
req = UsbFnAllocCtrlRequest(acm->ctrlIface.handle,
sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding));
```
4. Call **UsbFnStartRecvInterfaceEvent** to receive events, and call **UsbFnEventCallback** to respond to the events.
```cpp
// Start receiving events.
ret = UsbFnStartRecvInterfaceEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm);
// Process the event in the callback.
static void UsbAcmEventCallback(struct UsbFnEvent *event)
{
struct UsbAcmDevice *acm = NULL;
if (event == NULL || event->context == NULL) {
HDF_LOGE("%s: event is null", __func__);
return;
}
acm = (struct UsbAcmDevice *)event->context;
switch (event->type) {
case USBFN_STATE_BIND:
HDF_LOGI("%s: receive bind event", __func__);
break;
case USBFN_STATE_UNBIND:
HDF_LOGI("%s: receive unbind event", __func__);
break;
case USBFN_STATE_ENABLE:
HDF_LOGI("%s: receive enable event", __func__);
AcmEnable(acm);
break;
case USBFN_STATE_DISABLE:
HDF_LOGI("%s: receive disable event", __func__);
AcmDisable(acm);
acm->enableEvtCnt = 0;
break;
case USBFN_STATE_SETUP:
HDF_LOGI("%s: receive setup event", __func__);
if (event->setup != NULL) {
AcmSetup(acm, event->setup);
}
break;
case USBFN_STATE_SUSPEND:
HDF_LOGI("%s: receive suspend event", __func__);
AcmSuspend(acm);
break;
case USBFN_STATE_RESUME:
HDF_LOGI("%s: receive resume event", __func__);
AcmResume(acm);
break;
default:
break;
}
}
```
## Development Example 5. Send and receive data in synchronously or asynchronously.
The following examples help you better understand the development of the USB serial port driver. ```cpp
notify = (struct UsbCdcNotification *)req->buf;
...
if (memcpy_s((void *)(notify + 1), length, data, length) != EOK) {
return HDF_FAILURE;
}
ret = UsbFnSubmitRequestAsync(req); // Send data asynchronously.
```
### Development Example
### Developing Driver Using Host DDK APIs The following example helps you better understand the development of the USB serial port driver.
#### Developing Driver Using Host DDK APIs
```
root {
module = "usb_pnp_device";
usb_pnp_config {
match_attr = "usb_pnp_match";
usb_pnp_device_id = "UsbPnpDeviceId";
UsbPnpDeviceId {
idTableList = [
"host_acm_table"
];
host_acm_table {
// Driver module name, which must be the same as the value of moduleName in the driver entry structure.
moduleName = "usbhost_acm";
// Service name of the driver, which must be unique.
serviceName = "usbhost_acm_pnp_service";
// Keyword for matching private driver data.
deviceMatchAttr = "usbhost_acm_pnp_matchAttr";
// Data length starting from this field, in bytes.
length = 21;
// USB driver matching rule: vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber.
matchFlag = 0x0303;
// Vendor ID.
vendorId = 0x12D1;
// Product ID.
productId = 0x5000;
// The least significant 16 bits of the device sequence number.
bcdDeviceLow = 0x0000;
// The most significant 16 bits of the device sequence number.
bcdDeviceHigh = 0x0000;
// Device class code allocated by the USB.
deviceClass = 0;
// Child class code allocated by the USB.
deviceSubClass = 0;
// Device protocol code allocated by the USB.
deviceProtocol = 0;
// Interface type. You can enter multiple types as needed.
interfaceClass = [0];
// Interface subtype. You can enter multiple subtypes as needed.
interfaceSubClass = [2, 0];
// Protocol that the interface complies with. You can enter multiple protocols as needed.
interfaceProtocol = [1, 2];
// Interface number. You can enter multiple interface numbers as needed.
interfaceNumber = [2, 3];
}
}
}
}
```cpp
#include "usb_serial.h" #include "usb_serial.h"
#include "hdf_base.h" #include "hdf_base.h"
#include "hdf_log.h" #include "hdf_log.h"
...@@ -231,53 +459,52 @@ root { ...@@ -231,53 +459,52 @@ root {
#define HDF_LOG_TAG USB_HOST_ACM #define HDF_LOG_TAG USB_HOST_ACM
#define STR_LEN 512 #define STR_LEN 512
static struct UsbRequest *g_syncRequest = NULL; static struct UsbRequest *g_syncRequest = NULL; // Define a USB request.
static struct UsbRequest *g_ctrlCmdRequest = NULL; static struct UsbRequest *g_ctrlCmdRequest = NULL;
static bool g_acmReleaseFlag = false; static bool g_acmReleaseFlag = false;
static uint8_t *g_acmReadBuffer = NULL; static uint8_t *g_acmReadBuffer = NULL;
... ...
static int SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, static int32_t SerialCtrlMsg(struct AcmDevice *acm, uint8_t request,
uint16_t value, void *buf, uint16_t len) uint16_t value, void *buf, uint16_t len)
{ {
int ret; int32_t ret;
uint16_t index = acm->intPipe->interfaceId; uint16_t index = acm->intPipe->interfaceId;
struct UsbControlParams controlParams; struct UsbControlParams controlParams;
struct UsbRequestParams params; struct UsbRequestParams params; // Define a UsbRequestParams object.
if (acm == NULL || buf == NULL) { if (acm == NULL || buf == NULL) {
HDF_LOGE("%s:invalid param", __func__);
return HDF_ERR_IO; return HDF_ERR_IO;
} }
if (acm->ctrlReq == NULL) { if (acm->ctrlReq == NULL) {
// Pre-allocate the IO Request object to be sent to UsbInterfaceHandle.
acm->ctrlReq = UsbAllocRequest(acm->ctrDevHandle, 0, len); acm->ctrlReq = UsbAllocRequest(acm->ctrDevHandle, 0, len);
if (acm->ctrlReq == NULL) { if (acm->ctrlReq == NULL) {
HDF_LOGE("%s: UsbAllocRequest failed", __func__);
return HDF_ERR_IO; return HDF_ERR_IO;
} }
} }
controlParams.request = request; controlParams.request = request;
controlParams.target = USB_REQUEST_TARGET_INTERFACE; controlParams.target = USB_REQUEST_TARGET_INTERFACE; // Interface object
controlParams.reqType = USB_REQUEST_TYPE_CLASS; controlParams.reqType = USB_REQUEST_TYPE_CLASS; // Request type
controlParams.direction = USB_REQUEST_DIR_TO_DEVICE; controlParams.direction = USB_REQUEST_DIR_TO_DEVICE; // Data transfer from the host to the device
controlParams.value = value; controlParams.value = value;
controlParams.index = index; controlParams.index = index;
controlParams.data = buf; controlParams.data = buf;
controlParams.size = len; controlParams.size = len;
params.interfaceId = USB_CTRL_INTERFACE_ID; params.interfaceId = USB_CTRL_INTERFACE_ID; // Define the default ID of the USB control interface.
params.pipeAddress = acm->ctrPipe->pipeAddress; params.pipeAddress = acm->ctrPipe->pipeAddress;
params.pipeId = acm->ctrPipe->pipeId; params.pipeId = acm->ctrPipe->pipeId;
params.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; params.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; // Control type.
params.timeout = USB_CTRL_SET_TIMEOUT; params.timeout = USB_CTRL_SET_TIMEOUT; // Set the timeout interval.
params.ctrlReq = UsbControlSetUp(&controlParams); params.ctrlReq = UsbControlSetUp(&controlParams);
// Fill in the pre-allocated I/O request based on UsbRequestParams.
ret = UsbFillRequest(acm->ctrlReq, acm->ctrDevHandle, &params); ret = UsbFillRequest(acm->ctrlReq, acm->ctrDevHandle, &params);
if (HDF_SUCCESS != ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: failed, ret=%d ", __func__, ret);
return ret; return ret;
} }
ret = UsbSubmitRequestSync(acm->ctrlReq); // Send an I/O request synchronously. // Send an I/O request synchronously.
if (HDF_SUCCESS != ret) { ret = UsbSubmitRequestSync(acm->ctrlReq);
HDF_LOGE("UsbSubmitRequestSync failed, ret=%d ", ret); if (ret != HDF_SUCCESS) {
return ret; return ret;
} }
if (!acm->ctrlReq->compInfo.status) { if (!acm->ctrlReq->compInfo.status) {
...@@ -290,8 +517,8 @@ static struct UsbInterface *GetUsbInterfaceById(const struct AcmDevice *acm, ...@@ -290,8 +517,8 @@ static struct UsbInterface *GetUsbInterfaceById(const struct AcmDevice *acm,
uint8_t interfaceIndex) uint8_t interfaceIndex)
{ {
struct UsbInterface *tmpIf = NULL; struct UsbInterface *tmpIf = NULL;
tmpIf = (struct UsbInterface *)UsbClaimInterface(acm->session, acm->busNum, // Obtain a UsbInterface object.
acm->devAddr, interfaceIndex); // Obtain the UsbInterface object. tmpIf = (struct UsbInterface *)UsbClaimInterface(acm->session, acm->busNum, acm->devAddr, interfaceIndex);
return tmpIf; return tmpIf;
} }
... ...
...@@ -299,9 +526,9 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, ...@@ -299,9 +526,9 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm,
uint8_t interfaceIndex, UsbPipeType pipeType, UsbPipeDirection pipeDirection) uint8_t interfaceIndex, UsbPipeType pipeType, UsbPipeDirection pipeDirection)
{ {
uint8_t i; uint8_t i;
int ret; int32_t ret;
struct UsbInterfaceInfo *info = NULL; struct UsbInterfaceInfo *info = NULL; // Define a UsbInterfaceInfo object.
UsbInterfaceHandle *interfaceHandle = NULL; UsbInterfaceHandle *interfaceHandle = NULL; // Define a USB interface operation handle (that is, the void * type).
if (pipeType == USB_PIPE_TYPE_CONTROL) if (pipeType == USB_PIPE_TYPE_CONTROL)
{ {
info = &acm->ctrIface->info; info = &acm->ctrIface->info;
...@@ -310,19 +537,20 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, ...@@ -310,19 +537,20 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm,
else else
{ {
info = &acm->iface[interfaceIndex]->info; info = &acm->iface[interfaceIndex]->info;
// Obtain the device handle based on interfaceIndex.
interfaceHandle = InterfaceIdToHandle(acm, info->interfaceIndex); interfaceHandle = InterfaceIdToHandle(acm, info->interfaceIndex);
} }
for (i = 0; i <= info->pipeNum; i++) { for (i = 0; i <= info->pipeNum; i++) {
struct UsbPipeInfo p; struct UsbPipeInfo p;
ret = UsbGetPipeInfo(interfaceHandle, info->curAltSetting, i, &p);// Obtain information about the pipe with index i. // Obtain the pipeInfo object whose index is i.
ret = UsbGetPipeInfo(interfaceHandle, info->curAltSetting, i, &p);
if (ret < 0) { if (ret < 0) {
continue; continue;
} }
if ((p.pipeDirection == pipeDirection) && (p.pipeType == pipeType)) { if ((p.pipeDirection == pipeDirection) && (p.pipeType == pipeType)) {
struct UsbPipeInfo *pi = OsalMemCalloc(sizeof(*pi)); struct UsbPipeInfo *pi = OsalMemCalloc(sizeof(*pi)); // Allocate and initialize the memory.
if (pi == NULL) { if (pi == NULL) {
HDF_LOGE("%s: Alloc pipe failed", __func__);
return NULL; return NULL;
} }
p.interfaceId = info->interfaceIndex; p.interfaceId = info->interfaceIndex;
...@@ -338,7 +566,6 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm, ...@@ -338,7 +566,6 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm,
{ {
uint8_t i; uint8_t i;
if (acm == NULL) { if (acm == NULL) {
HDF_LOGE("%s: invalid params", __func__);
return NULL; return NULL;
} }
for (i = 0; i < acm->interfaceCnt; i++) { for (i = 0; i < acm->interfaceCnt; i++) {
...@@ -346,6 +573,7 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm, ...@@ -346,6 +573,7 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm,
if (!acm->iface[i]) { if (!acm->iface[i]) {
continue; continue;
} }
// Obtain pipe information of the control pipe.
p = EnumePipe(acm, i, pipeType, pipeDirection); p = EnumePipe(acm, i, pipeType, pipeDirection);
if (p == NULL) { if (p == NULL) {
continue; continue;
...@@ -362,40 +590,32 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) ...@@ -362,40 +590,32 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device)
errno_t err; errno_t err;
struct AcmDevice *acm = NULL; struct AcmDevice *acm = NULL;
if (device == NULL) { if (device == NULL) {
HDF_LOGE("%s: device is null", __func__);
return HDF_ERR_INVALID_OBJECT; return HDF_ERR_INVALID_OBJECT;
} }
acm = (struct AcmDevice *)OsalMemCalloc(sizeof(*acm)); acm = (struct AcmDevice *)OsalMemCalloc(sizeof(*acm));
if (acm == NULL) { if (acm == NULL) {
HDF_LOGE("%s: Alloc usb serial device failed", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
// Initialize the mutex. &acm->lock indicates the pointer pointing to the mutex.
if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) { if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) {
HDF_LOGE("%s:%d OsalMutexInit failed", __func__, __LINE__);
goto error; goto error;
} }
info = (struct UsbPnpNotifyServiceInfo *)device->priv; info = (struct UsbPnpNotifyServiceInfo *)device->priv;
if (info != NULL) { if (info != NULL) {
HDF_LOGD("%s:%d busNum=%d,devAddr=%d,interfaceLength=%d",
__func__, __LINE__, info->busNum, info->devNum, info->interfaceLength);
acm->busNum = info->busNum; acm->busNum = info->busNum;
acm->devAddr = info->devNum; acm->devAddr = info->devNum;
acm->interfaceCnt = info->interfaceLength; acm->interfaceCnt = info->interfaceLength;
err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES, err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES,
(const void*)info->interfaceNumber, info->interfaceLength); (const void*)info->interfaceNumber, info->interfaceLength);
if (err != EOK) { if (err != EOK) {
HDF_LOGE("%s:%d memcpy_s failed err=%d",
__func__, __LINE__, err);
goto lock_error; goto lock_error;
} }
} else { } else {
HDF_LOGE("%s:%d info is NULL!", __func__, __LINE__);
goto lock_error; goto lock_error;
} }
acm->device = device; acm->device = device;
device->service = &(acm->service); device->service = &(acm->service);
acm->device->service->Dispatch = UsbSerialDeviceDispatch; acm->device->service->Dispatch = UsbSerialDeviceDispatch;
HDF_LOGD("UsbSerialDriverBind=========================OK");
return HDF_SUCCESS; return HDF_SUCCESS;
lock_error: lock_error:
...@@ -408,14 +628,14 @@ error: ...@@ -408,14 +628,14 @@ error:
return HDF_FAILURE; return HDF_FAILURE;
} }
... ...
static int AcmAllocReadRequests(struct AcmDevice *acm) static int32_t AcmAllocReadRequests(struct AcmDevice *acm)
{ {
int ret; int32_t ret;
struct UsbRequestParams readParams; struct UsbRequestParams readParams;
for (int i = 0; i < ACM_NR; i++) { for (int32_t i = 0; i < ACM_NR; i++) {
acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // Allocate the readReq I/O request to be sent. // Allocate the readReq I/O request to be sent.
acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize);
if (!acm->readReq[i]) { if (!acm->readReq[i]) {
HDF_LOGE("readReq request failed");
goto error; goto error;
} }
readParams.userData = (void *)acm; readParams.userData = (void *)acm;
...@@ -423,14 +643,14 @@ static int AcmAllocReadRequests(struct AcmDevice *acm) ...@@ -423,14 +643,14 @@ static int AcmAllocReadRequests(struct AcmDevice *acm)
readParams.pipeId = acm->dataInPipe->pipeId; readParams.pipeId = acm->dataInPipe->pipeId;
readParams.interfaceId = acm->dataInPipe->interfaceId; readParams.interfaceId = acm->dataInPipe->interfaceId;
readParams.callback = AcmReadBulk; readParams.callback = AcmReadBulk;
readParams.requestType = USB_REQUEST_PARAMS_DATA_TYPE; readParams.requestType = USB_REQUEST_PARAMS_DATA_TYPE; /* Data type */
readParams.timeout = USB_CTRL_SET_TIMEOUT; readParams.timeout = USB_CTRL_SET_TIMEOUT;
readParams.dataReq.numIsoPackets = 0; readParams.dataReq.numIsoPackets = 0;
readParams.dataReq.direction = (acm->dataInPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; readParams.dataReq.direction = (acm->dataInPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1;
readParams.dataReq.length = acm->readSize; readParams.dataReq.length = acm->readSize;
ret = UsbFillRequest(acm->readReq[i], InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), &readParams); // Fills in the readReq object to be sent. // Fill in the readReq IO Request object to be sent based on readParams.
if (HDF_SUCCESS != ret) { ret = UsbFillRequest(acm->readReq[i], InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), &readParams);
HDF_LOGE("%s: UsbFillRequest failed, ret=%d n", __func__, ret); if (ret != HDF_SUCCESS) {
goto error; goto error;
} }
} }
...@@ -441,13 +661,13 @@ error: ...@@ -441,13 +661,13 @@ error:
return HDF_ERR_MALLOC_FAIL; return HDF_ERR_MALLOC_FAIL;
} }
static int AcmAllocNotifyRequest(struct AcmDevice *acm) static int32_t AcmAllocNotifyRequest(struct AcmDevice *acm)
{ {
int ret; int32_t ret;
struct UsbRequestParams intParams = {}; struct UsbRequestParams intParams = {};
acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); // Allocate the interrupt I/O request object to be sent. // Allocate the interrupt I/O request to be sent.
acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize);
if (!acm->notifyReq) { if (!acm->notifyReq) {
HDF_LOGE("notifyReq request failed");
return HDF_ERR_MALLOC_FAIL; return HDF_ERR_MALLOC_FAIL;
} }
intParams.userData = (void *)acm; intParams.userData = (void *)acm;
...@@ -460,9 +680,9 @@ static int AcmAllocNotifyRequest(struct AcmDevice *acm) ...@@ -460,9 +680,9 @@ static int AcmAllocNotifyRequest(struct AcmDevice *acm)
intParams.dataReq.numIsoPackets = 0; intParams.dataReq.numIsoPackets = 0;
intParams.dataReq.direction = (acm->intPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & DIRECTION_MASK; intParams.dataReq.direction = (acm->intPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & DIRECTION_MASK;
intParams.dataReq.length = acm->intSize; intParams.dataReq.length = acm->intSize;
ret = UsbFillRequest(acm->notifyReq, InterfaceIdToHandle(acm, acm->intPipe->interfaceId), &intParams); // Fill in the interrupt I/O request. // Fill in the interrupt I/O request.
if (HDF_SUCCESS != ret) { ret = UsbFillRequest(acm->notifyReq, InterfaceIdToHandle(acm, acm->intPipe->interfaceId), &intParams);
HDF_LOGE("%s: UsbFillRequest failed, ret=%d n", __func__, ret); if (ret != HDF_SUCCESS) {
goto error; goto error;
} }
return HDF_SUCCESS; return HDF_SUCCESS;
...@@ -474,8 +694,9 @@ error: ...@@ -474,8 +694,9 @@ error:
static void AcmReleaseInterfaces(struct AcmDevice *acm) static void AcmReleaseInterfaces(struct AcmDevice *acm)
{ {
for (int i = 0; i < acm->interfaceCnt; i++) { for (int32_t i = 0; i < acm->interfaceCnt; i++) {
if (acm->iface[i]) { if (acm->iface[i]) {
// Release a USB interface object.
UsbReleaseInterface(acm->iface[i]); UsbReleaseInterface(acm->iface[i]);
acm->iface[i] = NULL; acm->iface[i] = NULL;
} }
...@@ -488,31 +709,33 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm) ...@@ -488,31 +709,33 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm)
static int32_t AcmClaimInterfaces(struct AcmDevice *acm) static int32_t AcmClaimInterfaces(struct AcmDevice *acm)
{ {
for (int i = 0; i < acm->interfaceCnt; i++) { for (int32_t i = 0; i < acm->interfaceCnt; i++) {
acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); // Obtain the UsbInterface object. // Obtain a UsbInterface object.
acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]);
if (acm->iface[i] == NULL) { if (acm->iface[i] == NULL) {
HDF_LOGE("%s: interface%d is null", __func__, acm->interfaceIndex[i]);
goto error; goto error;
} }
} }
acm->ctrIface = GetUsbInterfaceById((const struct AcmDevice *)acm, USB_CTRL_INTERFACE_ID); // Obtain the UsbInterface object corresponding to the control interface. // Obtain the UsbInterface object corresponding to the control interface.
acm->ctrIface = GetUsbInterfaceById((const struct AcmDevice *)acm, USB_CTRL_INTERFACE_ID);
if (acm->ctrIface == NULL) { if (acm->ctrIface == NULL) {
HDF_LOGE("%s: GetUsbInterfaceById null", __func__);
goto error; goto error;
} }
return HDF_SUCCESS; return HDF_SUCCESS;
error: error:
// Release the UsbInterface object cyclically based on acm->interfaceCnt.
AcmReleaseInterfaces(acm); AcmReleaseInterfaces(acm);
return HDF_FAILURE; return HDF_FAILURE;
} }
static void AcmCloseInterfaces(struct AcmDevice *acm) static void AcmCloseInterfaces(struct AcmDevice *acm)
{ {
for (int i = 0; i < acm->interfaceCnt; i++) { for (int32_t i = 0; i < acm->interfaceCnt; i++) {
if (acm->devHandle[i]) { if (acm->devHandle[i]) {
// Close a USB device object.
UsbCloseInterface(acm->devHandle[i]); UsbCloseInterface(acm->devHandle[i]);
acm->devHandle[i] = NULL; acm->devHandle[i] = NULL;
} }
...@@ -525,51 +748,51 @@ static void AcmCloseInterfaces(struct AcmDevice *acm) ...@@ -525,51 +748,51 @@ static void AcmCloseInterfaces(struct AcmDevice *acm)
static int32_t AcmOpenInterfaces(struct AcmDevice *acm) static int32_t AcmOpenInterfaces(struct AcmDevice *acm)
{ {
for (int i = 0; i < acm->interfaceCnt; i++) { for (int32_t i = 0; i < acm->interfaceCnt; i++) {
if (acm->iface[i]) { if (acm->iface[i]) {
acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); // Open the UsbInterface object obtained. // Open the UsbInterface object obtained.
acm->devHandle[i] = UsbOpenInterface(acm->iface[i]);
if (acm->devHandle[i] == NULL) { if (acm->devHandle[i] == NULL) {
HDF_LOGE("%s: UsbOpenInterface null", __func__);
goto error; goto error;
} }
} }
} }
acm->ctrDevHandle = UsbOpenInterface(acm->ctrIface); acm->ctrDevHandle = UsbOpenInterface(acm->ctrIface);
if (acm->ctrDevHandle == NULL) { if (acm->ctrDevHandle == NULL) {
HDF_LOGE("%s: ctrDevHandle UsbOpenInterface null", __func__);
goto error; goto error;
} }
return HDF_SUCCESS; return HDF_SUCCESS;
error: error:
// Disable all UsbInterface objects.
AcmCloseInterfaces(acm); AcmCloseInterfaces(acm);
return HDF_FAILURE; return HDF_FAILURE;
} }
static int32_t AcmGetPipes(struct AcmDevice *acm) static int32_t AcmGetPipes(struct AcmDevice *acm)
{ {
acm->dataInPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_IN);// Obtain pipe information of dataInPipe. // Obtain pipe information of dataInPipe.
acm->dataInPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_IN);
if (acm->dataInPipe == NULL) { if (acm->dataInPipe == NULL) {
HDF_LOGE("dataInPipe is NULL");
goto error; goto error;
} }
acm->dataOutPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_OUT); // Obtain pipe information of dataOutPipe. // Obtain pipe information of dataOutPipe.
acm->dataOutPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_OUT);
if (acm->dataOutPipe == NULL) { if (acm->dataOutPipe == NULL) {
HDF_LOGE("dataOutPipe is NULL");
goto error; goto error;
} }
acm->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT); // Obtain pipe information of the control pipe. // Obtain pipe information of the control pipe.
acm->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT);
if (acm->ctrPipe == NULL) { if (acm->ctrPipe == NULL) {
HDF_LOGE("ctrPipe is NULL");
goto error; goto error;
} }
acm->intPipe = GetPipe(acm, USB_PIPE_TYPE_INTERRUPT, USB_PIPE_DIRECTION_IN); // Obtain pipe information of the interrupt pipe. //Obtain pipe information of the interrupt pipe.
acm->intPipe = GetPipe(acm, USB_PIPE_TYPE_INTERRUPT, USB_PIPE_DIRECTION_IN);
if (acm->intPipe == NULL) { if (acm->intPipe == NULL) {
HDF_LOGE("intPipe is NULL");
goto error; goto error;
} }
...@@ -577,10 +800,10 @@ static int32_t AcmGetPipes(struct AcmDevice *acm) ...@@ -577,10 +800,10 @@ static int32_t AcmGetPipes(struct AcmDevice *acm)
acm->writeSize = acm->dataOutPipe->maxPacketSize; acm->writeSize = acm->dataOutPipe->maxPacketSize;
acm->ctrlSize = acm->ctrPipe->maxPacketSize; acm->ctrlSize = acm->ctrPipe->maxPacketSize;
acm->intSize = acm->intPipe->maxPacketSize; acm->intSize = acm->intPipe->maxPacketSize;
return HDF_SUCCESS; return HDF_SUCCESS;
error: error:
// Release all pipe information on the device.
AcmFreePipes(acm); AcmFreePipes(acm);
return HDF_FAILURE; return HDF_FAILURE;
} }
...@@ -602,29 +825,26 @@ static int32_t AcmAllocRequests(struct AcmDevice *acm) ...@@ -602,29 +825,26 @@ static int32_t AcmAllocRequests(struct AcmDevice *acm)
int32_t ret; int32_t ret;
if (AcmWriteBufAlloc(acm) < 0) { if (AcmWriteBufAlloc(acm) < 0) {
HDF_LOGE("%s: AcmWriteBufAlloc failed", __func__);
return HDF_ERR_MALLOC_FAIL; return HDF_ERR_MALLOC_FAIL;
} }
for (int i = 0; i < ACM_NW; i++) { for (int32_t i = 0; i < ACM_NW; i++) {
struct AcmWb *snd = &(acm->wb[i]); struct AcmWb *snd = &(acm->wb[i]);
snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); // Allocate the I/O request object to be sent. // Allocate the I/O request to be sent.
snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize);
snd->instance = acm; snd->instance = acm;
if (snd->request == NULL) { if (snd->request == NULL) {
HDF_LOGE("%s:%d snd request failed", __func__, __LINE__);
goto error_alloc_write_req; goto error_alloc_write_req;
} }
} }
ret = AcmAllocNotifyRequest(acm); // Allocate and fill in the interrupt I/O request object. ret = AcmAllocNotifyRequest(acm); // Allocate and fill in the interrupt I/O request.
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s:%d AcmAllocNotifyRequest failed", __func__, __LINE__);
goto error_alloc_int_req; goto error_alloc_int_req;
} }
ret = AcmAllocReadRequests(acm); // Allocate and fill in the readReq I/O request object. ret = AcmAllocReadRequests(acm); // Allocate and fill in the readReq I/O request.
if (ret) { if (ret) {
HDF_LOGE("%s:%d AcmAllocReadRequests failed", __func__, __LINE__);
goto error_alloc_read_req; goto error_alloc_read_req;
} }
...@@ -645,57 +865,56 @@ static int32_t AcmInit(struct AcmDevice *acm) ...@@ -645,57 +865,56 @@ static int32_t AcmInit(struct AcmDevice *acm)
struct UsbSession *session = NULL; struct UsbSession *session = NULL;
if (acm->initFlag == true) { if (acm->initFlag == true) {
HDF_LOGE("%s:%d: initFlag is true", __func__, __LINE__);
return HDF_SUCCESS; return HDF_SUCCESS;
} }
ret = UsbInitHostSdk(NULL); // Initialize the Host DDK. // Initialize the USB Host DDK.
ret = UsbInitHostSdk(NULL);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: UsbInitHostSdk failed", __func__);
return HDF_ERR_IO; return HDF_ERR_IO;
} }
acm->session = session; acm->session = session;
// Obtain UsbInterface objects based on acm->interfaceIndex[i].
ret = AcmClaimInterfaces(acm); ret = AcmClaimInterfaces(acm);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: AcmClaimInterfaces failed", __func__);
goto error_claim_interfaces; goto error_claim_interfaces;
} }
// Open UsbInterface objects based on acm->iface[i].
ret = AcmOpenInterfaces(acm); ret = AcmOpenInterfaces(acm);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: AcmOpenInterfaces failed", __func__);
goto error_open_interfaces; goto error_open_interfaces;
} }
// Obtain the pointer to the pipe information.
ret = AcmGetPipes(acm); ret = AcmGetPipes(acm);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: AcmGetPipes failed", __func__);
goto error_get_pipes; goto error_get_pipes;
} }
ret = AcmAllocRequests(acm); ret = AcmAllocRequests(acm);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: AcmAllocRequests failed", __func__);
goto error_alloc_reqs; goto error_alloc_reqs;
} }
acm->lineCoding.dwDTERate = CpuToLe32(DATARATE); acm->lineCoding.dwDTERate = CpuToLe32(DATARATE); // Convert to little-endian data.
acm->lineCoding.bCharFormat = CHARFORMAT; acm->lineCoding.bCharFormat = CHARFORMAT; // 8
acm->lineCoding.bParityType = USB_CDC_NO_PARITY; acm->lineCoding.bParityType = USB_CDC_NO_PARITY;
acm->lineCoding.bDataBits = USB_CDC_1_STOP_BITS; acm->lineCoding.bDataBits = USB_CDC_1_STOP_BITS;
acm->initFlag = true; acm->initFlag = true;
HDF_LOGD("%s:%d========OK", __func__, __LINE__);
return HDF_SUCCESS; return HDF_SUCCESS;
error_alloc_reqs: error_alloc_reqs:
AcmFreePipes(acm); AcmFreePipes(acm);
error_get_pipes: error_get_pipes:
// Disable all UsbInterface objects.
AcmCloseInterfaces(acm); AcmCloseInterfaces(acm);
error_open_interfaces: error_open_interfaces:
// Release all UsbInterface objects.
AcmReleaseInterfaces(acm); AcmReleaseInterfaces(acm);
error_claim_interfaces: error_claim_interfaces:
// Exit the USB DDK on the host. acm->session indicates the pointer pointing to the session context.
UsbExitHostSdk(acm->session); UsbExitHostSdk(acm->session);
acm->session = NULL; acm->session = NULL;
return ret; return ret;
...@@ -704,7 +923,6 @@ error_claim_interfaces: ...@@ -704,7 +923,6 @@ error_claim_interfaces:
static void AcmRelease(struct AcmDevice *acm) static void AcmRelease(struct AcmDevice *acm)
{ {
if (acm->initFlag == false) { if (acm->initFlag == false) {
HDF_LOGE("%s:%d: initFlag is false", __func__, __LINE__);
return; return;
} }
...@@ -712,9 +930,9 @@ static void AcmRelease(struct AcmDevice *acm) ...@@ -712,9 +930,9 @@ static void AcmRelease(struct AcmDevice *acm)
AcmFreePipes(acm); AcmFreePipes(acm);
AcmCloseInterfaces(acm); AcmCloseInterfaces(acm);
AcmReleaseInterfaces(acm); AcmReleaseInterfaces(acm);
// Exit the USB DDK on the host.
UsbExitHostSdk(acm->session); UsbExitHostSdk(acm->session);
acm->session = NULL; acm->session = NULL;
acm->initFlag = false; acm->initFlag = false;
} }
...@@ -724,15 +942,15 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) ...@@ -724,15 +942,15 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device)
struct AcmDevice *acm = NULL; struct AcmDevice *acm = NULL;
if (device == NULL) { if (device == NULL) {
HDF_LOGE("%s: device is null", __func__);
return HDF_ERR_INVALID_OBJECT; return HDF_ERR_INVALID_OBJECT;
} }
acm = (struct AcmDevice *)device->service; acm = (struct AcmDevice *)device->service;
// Initialize the mutex. &acm->readLock indicates the pointer pointing to the mutex.
OsalMutexInit(&acm->readLock); OsalMutexInit(&acm->readLock);
OsalMutexInit(&acm->writeLock); OsalMutexInit(&acm->writeLock);
HDF_LOGD("%s:%d busNum=%d,devAddr=%d", HDF_LOGD("%s:%d busNum=%d,devAddr=%d", __func__, __LINE__, acm->busNum, acm->devAddr);
__func__, __LINE__, acm->busNum, acm->devAddr);
// Allocate space for the USB serial port device information and assign a value.
ret = UsbSerialDeviceAlloc(acm); ret = UsbSerialDeviceAlloc(acm);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: Serial Device alloc failed", __func__); HDF_LOGE("%s: Serial Device alloc failed", __func__);
...@@ -740,9 +958,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) ...@@ -740,9 +958,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device)
acm->initFlag = false; acm->initFlag = false;
g_acmReleaseFlag = false; g_acmReleaseFlag = false;
HDF_LOGD("%s:%d init ok!", __func__, __LINE__);
return ret; return ret;
} }
...@@ -751,30 +966,29 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) ...@@ -751,30 +966,29 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device)
struct AcmDevice *acm = NULL; struct AcmDevice *acm = NULL;
if (device == NULL) { if (device == NULL) {
HDF_LOGE("%s: device is NULL", __func__);
return; return;
} }
acm = (struct AcmDevice *)device->service; acm = (struct AcmDevice *)device->service;
if (acm == NULL) { if (acm == NULL) {
HDF_LOGE("%s: acm is null", __func__);
return; return;
} }
g_acmReleaseFlag = true; g_acmReleaseFlag = true;
if (acm->initFlag == true) { if (acm->initFlag == true) {
HDF_LOGE("%s:%d AcmRelease", __func__, __LINE__);
AcmRelease(acm); AcmRelease(acm);
} }
// Release the USB serial port device information.
UsbSeriaDevicelFree(acm); UsbSeriaDevicelFree(acm);
// Release the mutex.
OsalMutexDestroy(&acm->writeLock); OsalMutexDestroy(&acm->writeLock);
OsalMutexDestroy(&acm->readLock); OsalMutexDestroy(&acm->readLock);
OsalMutexDestroy(&acm->lock); OsalMutexDestroy(&acm->lock);
OsalMemFree(acm); OsalMemFree(acm);
acm = NULL; acm = NULL;
HDF_LOGD("%s:%d exit", __func__, __LINE__);
} }
// Perform Bind, Init, and Release operations on the driver.
struct HdfDriverEntry g_usbSerialDriverEntry = { struct HdfDriverEntry g_usbSerialDriverEntry = {
.moduleVersion = 1, .moduleVersion = 1,
.moduleName = "usbhost_acm", // Driver module name, which must be the same as that configured in the .hcs file. .moduleName = "usbhost_acm", // Driver module name, which must be the same as that configured in the .hcs file.
...@@ -782,14 +996,12 @@ struct HdfDriverEntry g_usbSerialDriverEntry = { ...@@ -782,14 +996,12 @@ struct HdfDriverEntry g_usbSerialDriverEntry = {
.Init = UsbSerialDriverInit, .Init = UsbSerialDriverInit,
.Release = UsbSerialDriverRelease, .Release = UsbSerialDriverRelease,
}; };
HDF_INIT(g_usbSerialDriverEntry); HDF_INIT(g_usbSerialDriverEntry); // Driver entry.
``` ```
#### Developing Driver Using Host Raw APIs
### Developing Driver Using Host Raw APIs
``` ```cpp
root { root {
module = "usb_pnp_device"; module = "usb_pnp_device";
usb_pnp_config { usb_pnp_config {
...@@ -836,7 +1048,9 @@ root { ...@@ -836,7 +1048,9 @@ root {
} }
} }
} }
```
```cpp
#include "usb_serial_rawapi.h" #include "usb_serial_rawapi.h"
#include <unistd.h> #include <unistd.h>
#include "osal_mem.h" #include "osal_mem.h"
...@@ -846,7 +1060,7 @@ root { ...@@ -846,7 +1060,7 @@ root {
#include "hdf_log.h" #include "hdf_log.h"
#include "hdf_usb_pnp_manage.h" #include "hdf_usb_pnp_manage.h"
#define HDF_LOG_TAG USB_HOST_ACM_RAW_API #define HDF_LOG_TAG USB_HOST_ACM_RAW_API // Labels that can be queried in logs.
#define USB_CTRL_REQ_SIZE 64 #define USB_CTRL_REQ_SIZE 64
#define USB_IO_THREAD_STACK_SIZE 8192 #define USB_IO_THREAD_STACK_SIZE 8192
#define USB_RAW_IO_SLEEP_MS_TIME 100 #define USB_RAW_IO_SLEEP_MS_TIME 100
...@@ -858,51 +1072,46 @@ struct OsalMutex g_stopIoLock; ...@@ -858,51 +1072,46 @@ struct OsalMutex g_stopIoLock;
static bool g_rawAcmReleaseFlag = false; static bool g_rawAcmReleaseFlag = false;
...... ......
static int UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDescriptor **config) static int32_t UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDescriptor **config)
{ {
UsbRawDevice *dev = NULL; UsbRawDevice *dev = NULL;
int activeConfig; int32_t activeConfig;
int ret; int32_t ret;
if (devHandle == NULL) { if (devHandle == NULL) {
HDF_LOGE("%s:%d devHandle is NULL",
__func__, __LINE__);
return HDF_ERR_INVALID_PARAM; return HDF_ERR_INVALID_PARAM;
} }
// Obtain the configuration of the active device.
ret = UsbRawGetConfiguration(devHandle, &activeConfig); ret = UsbRawGetConfiguration(devHandle, &activeConfig);
if (ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s:%d UsbRawGetConfiguration failed, ret=%d",
__func__, __LINE__, ret);
return HDF_FAILURE; return HDF_FAILURE;
} }
HDF_LOGE("%s:%d activeConfig=%d", __func__, __LINE__, activeConfig);
// Obtain the device pointer based on the specified device handle.
dev = UsbRawGetDevice(devHandle); dev = UsbRawGetDevice(devHandle);
if (dev == NULL) { if (dev == NULL) {
HDF_LOGE("%s:%d UsbRawGetDevice failed",
__func__, __LINE__);
return HDF_FAILURE; return HDF_FAILURE;
} }
// Obtain the device configuration descriptor based on the specified device ID.
ret = UsbRawGetConfigDescriptor(dev, activeConfig, config); ret = UsbRawGetConfigDescriptor(dev, activeConfig, config);
if (ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("UsbRawGetConfigDescriptor failed, ret=%dn", ret); HDF_LOGE("UsbRawGetConfigDescriptor failed, ret=%d\n", ret);
return HDF_FAILURE;
} }
return ret;
return HDF_SUCCESS;
} }
... ...
static int UsbAllocWriteRequests(struct AcmDevice *acm) static int32_t UsbAllocWriteRequests(struct AcmDevice *acm)
{ {
int i; int32_t i;
for (i = 0; i < ACM_NW; i++) { for (i = 0; i < ACM_NW; i++) {
struct AcmWb *snd = &acm->wb[i]; struct AcmWb *snd = &acm->wb[i];
// Allocate a transfer request with the specified number of sync packet descriptors.
snd->request = UsbRawAllocRequest(acm->devHandle, 0, acm->dataOutEp->maxPacketSize); snd->request = UsbRawAllocRequest(acm->devHandle, 0, acm->dataOutEp->maxPacketSize);
snd->instance = acm; snd->instance = acm;
if (snd->request == NULL) { if (snd->request == NULL) {
HDF_LOGE("%s: UsbRawAllocRequest failed", __func__);
return HDF_ERR_MALLOC_FAIL; return HDF_ERR_MALLOC_FAIL;
} }
} }
...@@ -918,17 +1127,14 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) ...@@ -918,17 +1127,14 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device)
errno_t err; errno_t err;
if (device == NULL) { if (device == NULL) {
HDF_LOGE("%s: device is null", __func__);
return HDF_ERR_INVALID_OBJECT; return HDF_ERR_INVALID_OBJECT;
} }
acm = (struct AcmDevice *)OsalMemCalloc(sizeof(*acm)); acm = (struct AcmDevice *)OsalMemCalloc(sizeof(*acm));
if (acm == NULL) { if (acm == NULL) {
HDF_LOGE("%s: Alloc usb serial device failed", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) { if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) {
HDF_LOGE("%s:%d OsalMutexInit failed", __func__, __LINE__);
goto error; goto error;
} }
...@@ -940,19 +1146,15 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) ...@@ -940,19 +1146,15 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device)
err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES, err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES,
(const void*)info->interfaceNumber, info->interfaceLength); (const void*)info->interfaceNumber, info->interfaceLength);
if (err != EOK) { if (err != EOK) {
HDF_LOGE("%s:%d memcpy_s failed err=%d",
__func__, __LINE__, err);
goto lock_error; goto lock_error;
} }
} else { } else {
HDF_LOGE("%s:%d info is NULL!", __func__, __LINE__);
goto lock_error; goto lock_error;
} }
device->service = &(acm->service); device->service = &(acm->service);
device->service->Dispatch = UsbSerialDeviceDispatch; device->service->Dispatch = UsbSerialDeviceDispatch;
acm->device = device; acm->device = device;
HDF_LOGD("UsbSerialDriverBind=========================OK");
return HDF_SUCCESS; return HDF_SUCCESS;
lock_error: lock_error:
...@@ -965,16 +1167,16 @@ error: ...@@ -965,16 +1167,16 @@ error:
return HDF_FAILURE; return HDF_FAILURE;
} }
... ...
static int UsbAllocReadRequests(struct AcmDevice *acm) static int32_t UsbAllocReadRequests(struct AcmDevice *acm)
{ {
struct UsbRawFillRequestData reqData; struct UsbRawFillRequestData reqData;
int size = acm->dataInEp->maxPacketSize; int32_t size = acm->dataInEp->maxPacketSize;
int ret; int32_t ret;
for (int i = 0; i < ACM_NR; i++) { for (int32_t i = 0; i < ACM_NR; i++) {
// Allocate a transfer request with the specified number of sync packet descriptors.
acm->readReq[i] = UsbRawAllocRequest(acm->devHandle, 0, size); acm->readReq[i] = UsbRawAllocRequest(acm->devHandle, 0, size);
if (!acm->readReq[i]) { if (!acm->readReq[i]) {
HDF_LOGE("readReq request failed");
return HDF_ERR_MALLOC_FAIL; return HDF_ERR_MALLOC_FAIL;
} }
...@@ -985,10 +1187,9 @@ static int UsbAllocReadRequests(struct AcmDevice *acm) ...@@ -985,10 +1187,9 @@ static int UsbAllocReadRequests(struct AcmDevice *acm)
reqData.timeout = USB_CTRL_SET_TIMEOUT; reqData.timeout = USB_CTRL_SET_TIMEOUT;
reqData.length = size; reqData.length = size;
// Fill the required information in the bulk transfer request.
ret = UsbRawFillBulkRequest(acm->readReq[i], acm->devHandle, &reqData); ret = UsbRawFillBulkRequest(acm->readReq[i], acm->devHandle, &reqData);
if (ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: FillBulkRequest failed, ret=%d n",
__func__, ret);
return HDF_FAILURE; return HDF_FAILURE;
} }
} }
...@@ -996,15 +1197,15 @@ static int UsbAllocReadRequests(struct AcmDevice *acm) ...@@ -996,15 +1197,15 @@ static int UsbAllocReadRequests(struct AcmDevice *acm)
return HDF_SUCCESS; return HDF_SUCCESS;
} }
... ...
static int UsbAllocNotifyRequest(struct AcmDevice *acm) static int32_t UsbAllocNotifyRequest(struct AcmDevice *acm)
{ {
struct UsbRawFillRequestData fillRequestData; struct UsbRawFillRequestData fillRequestData;
int size = acm->notifyEp->maxPacketSize; int32_t size = acm->notifyEp->maxPacketSize;
int ret; int32_t ret;
// Allocate a transfer request with the specified number of sync packet descriptors.
acm->notifyReq = UsbRawAllocRequest(acm->devHandle, 0, size); acm->notifyReq = UsbRawAllocRequest(acm->devHandle, 0, size);
if (!acm->notifyReq) { if (!acm->notifyReq) {
HDF_LOGE("notifyReq request failed");
return HDF_ERR_MALLOC_FAIL; return HDF_ERR_MALLOC_FAIL;
} }
...@@ -1015,9 +1216,9 @@ static int UsbAllocNotifyRequest(struct AcmDevice *acm) ...@@ -1015,9 +1216,9 @@ static int UsbAllocNotifyRequest(struct AcmDevice *acm)
fillRequestData.userData = (void *)acm; fillRequestData.userData = (void *)acm;
fillRequestData.timeout = USB_CTRL_SET_TIMEOUT; fillRequestData.timeout = USB_CTRL_SET_TIMEOUT;
// Fill the required information in the interrupt transfer request.
ret = UsbRawFillInterruptRequest(acm->notifyReq, acm->devHandle, &fillRequestData); ret = UsbRawFillInterruptRequest(acm->notifyReq, acm->devHandle, &fillRequestData);
if (ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: FillInterruptRequest failed, ret=%d", __func__, ret);
return HDF_FAILURE; return HDF_FAILURE;
} }
...@@ -1031,62 +1232,55 @@ static int32_t UsbSerialInit(struct AcmDevice *acm) ...@@ -1031,62 +1232,55 @@ static int32_t UsbSerialInit(struct AcmDevice *acm)
int32_t ret; int32_t ret;
if (acm->initFlag == true) { if (acm->initFlag == true) {
HDF_LOGE("%s:%d: initFlag is true", __func__, __LINE__);
return HDF_SUCCESS; return HDF_SUCCESS;
} }
// Initialize the USB DDK in expert mode.
ret = UsbRawInit(NULL); ret = UsbRawInit(NULL);
if (ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s:%d UsbRawInit failed", __func__, __LINE__);
return HDF_ERR_IO; return HDF_ERR_IO;
} }
acm->session = session; acm->session = session;
// Open a USB device object.
devHandle = UsbRawOpenDevice(session, acm->busNum, acm->devAddr); devHandle = UsbRawOpenDevice(session, acm->busNum, acm->devAddr);
if (devHandle == NULL) { if (devHandle == NULL) {
HDF_LOGE("%s:%d UsbRawOpenDevice failed", __func__, __LINE__);
ret = HDF_FAILURE; ret = HDF_FAILURE;
goto err_open_device; goto err_open_device;
} }
acm->devHandle = devHandle; acm->devHandle = devHandle;
// Obtain the configuration of the active device, device pointer, and configuration descriptor.
ret = UsbGetConfigDescriptor(devHandle, &acm->config); ret = UsbGetConfigDescriptor(devHandle, &acm->config);
if (ret) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s:%d UsbGetConfigDescriptor failed", __func__, __LINE__);
ret = HDF_FAILURE; ret = HDF_FAILURE;
goto err_get_desc; goto err_get_desc;
} }
ret = UsbParseConfigDescriptor(acm, acm->config); ret = UsbParseConfigDescriptor(acm, acm->config);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s:%d UsbParseConfigDescriptor failed", __func__, __LINE__);
ret = HDF_FAILURE; ret = HDF_FAILURE;
goto err_parse_desc; goto err_parse_desc;
} }
ret = AcmWriteBufAlloc(acm); ret = AcmWriteBufAlloc(acm);
if (ret < 0) { if (ret < 0) {
HDF_LOGE("%s:%d AcmWriteBufAlloc failed", __func__, __LINE__);
ret = HDF_FAILURE; ret = HDF_FAILURE;
goto err_alloc_write_buf; goto err_alloc_write_buf;
} }
ret = UsbAllocWriteRequests(acm); ret = UsbAllocWriteRequests(acm);
if (ret < 0) { if (ret < 0) {
HDF_LOGE("%s:%d UsbAllocWriteRequests failed", __func__, __LINE__);
ret = HDF_FAILURE; ret = HDF_FAILURE;
goto err_alloc_write_reqs; goto err_alloc_write_reqs;
} }
ret = UsbAllocNotifyRequest(acm); ret = UsbAllocNotifyRequest(acm);
if (ret) { if (ret) {
HDF_LOGE("%s:%d UsbAllocNotifyRequests failed", __func__, __LINE__);
goto err_alloc_notify_req; goto err_alloc_notify_req;
} }
ret = UsbAllocReadRequests(acm); ret = UsbAllocReadRequests(acm);
if (ret) { if (ret) {
HDF_LOGE("%s:%d UsbAllocReadRequests failed", __func__, __LINE__);
goto err_alloc_read_reqs; goto err_alloc_read_reqs;
} }
ret = UsbStartIo(acm); ret = UsbStartIo(acm);
if (ret) { if (ret) {
HDF_LOGE("%s:%d UsbAllocReadRequests failed", __func__, __LINE__);
goto err_start_io; goto err_start_io;
} }
...@@ -1097,18 +1291,14 @@ static int32_t UsbSerialInit(struct AcmDevice *acm) ...@@ -1097,18 +1291,14 @@ static int32_t UsbSerialInit(struct AcmDevice *acm)
ret = UsbRawSubmitRequest(acm->notifyReq); ret = UsbRawSubmitRequest(acm->notifyReq);
if (ret) { if (ret) {
HDF_LOGE("%s:%d UsbRawSubmitRequest failed", __func__, __LINE__);
goto err_submit_req; goto err_submit_req;
} }
acm->initFlag = true; acm->initFlag = true;
HDF_LOGD("%s:%d=========================OK", __func__, __LINE__);
return HDF_SUCCESS; return HDF_SUCCESS;
err_submit_req: err_submit_req:
UsbStopIo(acm); UsbStopIo(acm); // Stop the I/O thread and release all resources.
err_start_io: err_start_io:
UsbFreeReadRequests(acm); UsbFreeReadRequests(acm);
err_alloc_read_reqs: err_alloc_read_reqs:
...@@ -1123,9 +1313,9 @@ err_parse_desc: ...@@ -1123,9 +1313,9 @@ err_parse_desc:
UsbRawFreeConfigDescriptor(acm->config); UsbRawFreeConfigDescriptor(acm->config);
acm->config = NULL; acm->config = NULL;
err_get_desc: err_get_desc:
(void)UsbRawCloseDevice(devHandle); (void)UsbRawCloseDevice(devHandle); // Close the USB device object.
err_open_device: err_open_device:
UsbRawExit(acm->session); UsbRawExit(acm->session); // Exit the expert mode of the USB DDK.
return ret; return ret;
} }
...@@ -1133,7 +1323,6 @@ err_open_device: ...@@ -1133,7 +1323,6 @@ err_open_device:
static void UsbSerialRelease(struct AcmDevice *acm) static void UsbSerialRelease(struct AcmDevice *acm)
{ {
if (acm->initFlag == false) { if (acm->initFlag == false) {
HDF_LOGE("%s:%d: initFlag is false", __func__, __LINE__);
return; return;
} }
...@@ -1151,6 +1340,7 @@ static void UsbSerialRelease(struct AcmDevice *acm) ...@@ -1151,6 +1340,7 @@ static void UsbSerialRelease(struct AcmDevice *acm)
UsbReleaseInterfaces(acm); UsbReleaseInterfaces(acm);
UsbRawFreeConfigDescriptor(acm->config); UsbRawFreeConfigDescriptor(acm->config);
acm->config = NULL; acm->config = NULL;
// Exit the expert mode of the USB DDK.
UsbRawExit(acm->session); UsbRawExit(acm->session);
acm->initFlag = false; acm->initFlag = false;
...@@ -1162,7 +1352,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) ...@@ -1162,7 +1352,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device)
int32_t ret; int32_t ret;
if (device == NULL) { if (device == NULL) {
HDF_LOGE("%s:%d device is null", __func__, __LINE__);
return HDF_ERR_INVALID_OBJECT; return HDF_ERR_INVALID_OBJECT;
} }
acm = (struct AcmDevice *)device->service; acm = (struct AcmDevice *)device->service;
...@@ -1176,9 +1365,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) ...@@ -1176,9 +1365,6 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device)
acm->initFlag = false; acm->initFlag = false;
g_rawAcmReleaseFlag = false; g_rawAcmReleaseFlag = false;
HDF_LOGD("%s:%d init ok!", __func__, __LINE__);
return ret; return ret;
} }
...@@ -1186,20 +1372,17 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) ...@@ -1186,20 +1372,17 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device)
{ {
struct AcmDevice *acm = NULL; struct AcmDevice *acm = NULL;
if (device == NULL) { if (device == NULL) {
HDF_LOGE("%s: device is NULL", __func__);
return; return;
} }
acm = (struct AcmDevice *)device->service; acm = (struct AcmDevice *)device->service;
if (acm == NULL) { if (acm == NULL) {
HDF_LOGE("%s: acm is null", __func__);
return; return;
} }
g_rawAcmReleaseFlag = true; g_rawAcmReleaseFlag = true;
if (acm->initFlag == true) { if (acm->initFlag == true) {
HDF_LOGE("%s:%d UsbSerialRelease", __func__, __LINE__);
UsbSerialRelease(acm); UsbSerialRelease(acm);
} }
UsbSeriaDevicelFree(acm); UsbSeriaDevicelFree(acm);
...@@ -1208,12 +1391,11 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) ...@@ -1208,12 +1391,11 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device)
OsalMutexDestroy(&acm->lock); OsalMutexDestroy(&acm->lock);
OsalMemFree(acm); OsalMemFree(acm);
acm = NULL; acm = NULL;
HDF_LOGD("%s:%d exit", __func__, __LINE__);
} }
struct HdfDriverEntry g_usbSerialRawDriverEntry = { struct HdfDriverEntry g_usbSerialRawDriverEntry = {
.moduleVersion = 1, .moduleVersion = 1,
..moduleName = "usbhost_acm_rawapi", // Driver module name, which must be the same as that configured in the .hcs file. .moduleName = "usbhost_acm_rawapi", // Driver module name, which must be the same as that configured in the .hcs file.
.Bind = UsbSerialDriverBind, .Bind = UsbSerialDriverBind,
.Init = UsbSerialDriverInit, .Init = UsbSerialDriverInit,
.Release = UsbSerialDriverRelease, .Release = UsbSerialDriverRelease,
...@@ -1221,100 +1403,133 @@ struct HdfDriverEntry g_usbSerialRawDriverEntry = { ...@@ -1221,100 +1403,133 @@ struct HdfDriverEntry g_usbSerialRawDriverEntry = {
HDF_INIT(g_usbSerialRawDriverEntry); HDF_INIT(g_usbSerialRawDriverEntry);
``` ```
#### Developing Driver Using Device DDK APIs
### Developing Driver Using Device DDK APIs The core code of the USB ACM device is stored in **drivers\peripheral\usb\gadget\function\acm\cdcacm.c**. The following sample code implements driver development by using the Device DDK APIs. To develop a driver, you must create a device based on the descriptor, obtain the interface, open the interface to obtain the pipe information, receive events, and then perform USB communication (such as read and write). When the device is uninstalled, you need to close the interface, stop receiving events, and remove the device.
The core code of the USB Abstract Control Model (ACM) device is available in **drivers\peripheral\usb\gadget\function\acm\cdcacm.c**. The following is an example. 1. Create a USB device.
```cpp
``` static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, struct DeviceResourceIface *iface)
1. Create a device. {
static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, struct UsbFnDevice *fnDev = NULL;
struct DeviceResourceIface *iface) struct UsbFnDescriptorData descData;
{ uint8_t useHcs;
struct UsbFnDevice *fnDev = NULL; ...
struct UsbFnDescriptorData descData; if (useHcs == 0) { // The descriptor is sourced from the code.
uint8_t useHcs; descData.type = USBFN_DESC_DATA_TYPE_DESC;
... descData.descriptor = &g_masterFuncDevice;
if (useHcs == 0) { } else {// The descriptor is sourced from the .hcs file.
descData.type = USBFN_DESC_DATA_TYPE_DESC; descData.type = USBFN_DESC_DATA_TYPE_PROP;
descData.descriptor = &g_masterFuncDevice; descData.property = device->property;
} else { }
descData.type = USBFN_DESC_DATA_TYPE_PROP; /* Create a device. */
descData.property = device->property; fnDev = (struct UsbFnDevice *)UsbFnDeviceCreate(acm->udcName, &descData);
} if (fnDev == NULL) {
/* Create a device. */ return HDF_FAILURE;
fnDev = (struct UsbFnDevice *)UsbFnDeviceCreate(acm->udcName, &descData); }
if (fnDev == NULL) {
HDF_LOGE("%s: create usb function device failed", __func__);
return HDF_FAILURE;
}
...
}
2. Obtain an interface and open the interface for pipe information.
static int32_t AcmParseEachPipe(struct UsbAcmDevice *acm, struct UsbAcmInterface *iface)
{
...
for (i = 0; i < fnIface->info.numPipes; i++) {
struct UsbFnPipeInfo pipeInfo;
/* Obtain pipe information. */
ret = UsbFnInterfaceGetPipeInfo(fnIface, i, &pipeInfo);
... ...
} }
return HDF_SUCCESS; ```
}
/* Obtain the interface and open the interface to obtain the handle. */ 2. Obtain an interface and open the interface to obtain the pipe information.
static int32_t AcmParseEachIface(struct UsbAcmDevice *acm, struct UsbFnDevice *fnDev)
{ ```cpp
... static int32_t AcmParseEachPipe(struct UsbAcmDevice *acm, struct UsbAcmInterface *iface)
for (i = 0; i < fnDev->numInterfaces; i++) { {
/* Obtain an interface.*/
fnIface = (struct UsbFnInterface *)UsbFnDeviceGetInterface(fnDev, i);
... ...
/* Open the interface. */ for (i = 0; i < fnIface->info.numPipes; i++) {
handle = UsbFnInterfaceOpen(fnIface); struct UsbFnPipeInfo pipeInfo;
/* Obtain pipe information. */
ret = UsbFnInterfaceGetPipeInfo(fnIface, i, &pipeInfo);
...
}
return HDF_SUCCESS;
}
/* Obtain an interface and open the interface to obtain the handle. */
static int32_t AcmParseEachIface(struct UsbAcmDevice *acm, struct UsbFnDevice *fnDev)
{
... ...
for (i = 0; i < fnDev->numInterfaces; i++) {
/* Obtain an interface.*/
fnIface = (struct UsbFnInterface *)UsbFnGetInterface(fnDev, i);
...
/* Open the interface. */
handle = UsbFnInterfaceOpen(fnIface);
...
}
return HDF_SUCCESS;
} }
return HDF_SUCCESS; ```
}
3. Receive events. 3. Receive events (EP0 control transfer).
static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int num)
{ ```cpp
... static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int32_t num)
{
...
req = UsbFnCtrlRequestAlloc(acm->ctrlIface.handle, req = UsbFnCtrlRequestAlloc(acm->ctrlIface.handle,
sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding)); sizeof(struct UsbCdcLineCoding) + sizeof(struct UsbCdcLineCoding));
... ...
} }
static int32_t AcmDriverInit(struct HdfDeviceObject *device) static int32_t AcmDriverInit(struct HdfDeviceObject *device)
{ {
... ...
/* Start to receive events.*/ /* Start to receive events.*/
ret = UsbFnInterfaceStartRecvEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm); ret = UsbFnInterfaceStartRecvEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm);
... ...
} }
```
4. Perform USB communication (read and write). 4. Perform USB communication (read and write).
static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type,
uint16_t value, void *data, uint32_t length) ```cpp
{ static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type,
... uint16_t value, void *data, uint32_t length)
/* Send an asynchronous request.*/ {
ret = UsbFnRequestSubmitAsync(req); ...
... /* Send an asynchronous request.*/
} ret = UsbFnRequestSubmitAsync(req);
5. Close the interface, stop receiving events, and remove the device. ...
static int32_t AcmReleaseFuncDevice(struct UsbAcmDevice *acm)
{
int32_t ret;
/* Close the interface. */
(void)UsbFnInterfaceClose(acm->ctrlIface.handle);
(void)UsbFnInterfaceClose(acm->dataIface.handle);
/* Stop receiving events. */
(void)UsbFnInterfaceStopRecvEvent(acm->ctrlIface.fn);
/* Remove the device. */
ret = UsbFnDeviceRemove(acm->fnDev);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: remove usb function device failed", __func__);
} }
return ret; ```
}
``` 5. Close the interface, stop receiving events, and delete the device.
```cpp
static int32_t AcmReleaseFuncDevice(struct UsbAcmDevice *acm)
{
int32_t ret;
/* Close the interface. */
(void)UsbFnInterfaceClose(acm->ctrlIface.handle);
(void)UsbFnInterfaceClose(acm->dataIface.handle);
/* Stop receiving the Event EP0 control transfer. */
(void)UsbFnInterfaceStopRecvEvent(acm->ctrlIface.fn);
/* Delete the device. */
ret = UsbFnDeviceRemove(acm->fnDev);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: remove usb function device failed", __func__);
}
return ret;
}
```
## References
- Code repositories:
**[drivers\_hdf\_core](https://gitee.com/openharmony/drivers_hdf_core)**
[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral)
[drivers\_interface](https://gitee.com/openharmony/drivers_interface)
- Code paths:
USB driver model adaptation for LiteOS: //drivers/hdf_core/adapter/khdf/liteos/model/usb
USB DDK driver loading: //drivers/hdf_core/framework/model/usb
USB HDI server implementation: //drivers/peripheral/usb/hdi_service
USB HDI external APIs: //out/{product_name}/gen/drivers/interface/usb/v1_0
...@@ -24,6 +24,7 @@ The sandbox management module is available only for the standard system. ...@@ -24,6 +24,7 @@ The sandbox management module is available only for the standard system.
| src-path | Source path of the directory or file to mount.| | src-path | Source path of the directory or file to mount.|
| sandbox-path | Target path in the sandbox.| | sandbox-path | Target path in the sandbox.|
| sandbox-flags | Mount flag. The default value is **bind rec**.| | sandbox-flags | Mount flag. The default value is **bind rec**.|
| ignore | Whether to ignore a mounting failure. If the value is set to 1, the system ignores the mounting failure and proceeds with the subsequent step. |
| target-name | Directory to link.| | target-name | Directory to link.|
| link-name | Target link in the sandbox.| | link-name | Target link in the sandbox.|
...@@ -44,13 +45,13 @@ Logical storage structure of the sandbox: ...@@ -44,13 +45,13 @@ Logical storage structure of the sandbox:
bool InitSandboxWithName(const char *name); // Parsing to the JSON structure bool InitSandboxWithName(const char *name); // Parsing to the JSON structure
typedef struct { typedef struct {
mountlist_t *mounts; // Directory to mount ListNode pathMountsHead; // sandbox mount_path list head
mountlist_t *fileMounts; // File to mount ListNode fileMountsHead; // sandbox mount_file list head
linklist_t *links; // Directory to link ListNode linksHead; // sandbox symbolic link list head
char *rootPath; // Root path of the sandbox: /mnt/sandbox/system|vendor|xxx char *rootPath; // /mnt/sandbox/system|vendor|xxx
char name[MAX_BUFFER_LEN]; // Sandbox name, for example, system sandbox or chipset sandbox char name[MAX_BUFFER_LEN]; // name of sandbox. i.e system, chipset etc.
bool isCreated; // Sandbox creation flag bool isCreated; // sandbox already created or not
int ns; // namespace int ns; // namespace // namespace
} sandbox_t; } sandbox_t;
``` ```
### How to Develop ### How to Develop
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册