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
...
...
@@ -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. |
| 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()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| 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
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
...
...
@@ -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): 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).
| 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
## How to Develop
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
importhiAppEventfrom'@ohos.hiAppEvent';
importhiAppEventfrom'@ohos.hiviewdfx.hiAppEvent';
@Entry
@Component
...
...
@@ -91,10 +67,10 @@ The following uses a one-time event watcher as an example to illustrate the deve
int_data:100,
str_data:"strValue"
}
}).then((value)=>{
console.log(`HiAppEvent success to write event: ${value}`);
}).then(()=>{
console.log(`HiAppEvent success to write event`);
}).catch((err)=>{
console.error(`HiAppEvent failed to write event because ${err.code}`);
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The 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.
## Modules to Import
...
...
@@ -17,13 +17,9 @@ import hiAppEvent from '@ohos.hiAppEvent';
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**
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**
...
...
@@ -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:
-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.
- 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.
...
...
@@ -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 smaller than **0**, the event parameter verification fails, and the event will not be written to the event file.
**Subscription Callback**
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.
Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses an asynchronous callback to return the result.
| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.|
| callback | AsyncCallback<void> | 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}`);
| Promise<void> | 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.
@@ -263,225 +156,6 @@ Provides the configuration items for application event logging.
| 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.|
Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned.
> 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
...
...
@@ -17,7 +16,7 @@ import hidebug from '@ohos.hidebug';
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.
...
...
@@ -27,7 +26,7 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
| 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**
...
...
@@ -40,17 +39,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
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.
@@ -165,11 +162,13 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
letcpuUsage=hidebug.getCpuUsage();
```
## hidebug.startProfiling
## hidebug.startProfiling<sup>(deprecated)</sup>
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`.
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`.
| 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`.|
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`.
| 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
importhidebugfrom'@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`.
| 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`.|
| 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`.|
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**
> - 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.
| info | [SysEventInfo](#syseventinfo) | Yes| System event information.|
| callback | AsyncCallback<void> | 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).
| Promise<void> | 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).
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.
Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses an asynchronous callback to return the result.
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.
| 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.|
| 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.
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.
| 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
letholder=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.
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.
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.
| boolean | The value **true** indicates that the application has the permission to access the device, and the value **false** indicates the opposite.|
| Promise<boolean> | 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.|
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.
| 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
letret=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).
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.
| 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
letret=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.
| 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
letret=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.
| 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
letret=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.
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.
| 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<number> | 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.|
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.
| 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<number> | 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.
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.
| 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
letfuncs=HDC;
letret=usb.setCurrentFunctions(funcs);
```
## usb.getCurrentFunctions<sup>9+</sup>
getCurrentFunctions(): FunctionType
Obtains the numeric mask combination for the USB function list in Device mode.
| 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
letret=usb.getSupportedModes(0);
```
## USBEndpoint
Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface).
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**
>
> 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.
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.
@@ -130,7 +146,7 @@ Checks whether the application has the permission to access the device.
| 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.|
@@ -158,7 +174,7 @@ Requests the temporary permission for the application to access the USB device.
| Type| Description|
| -------- | -------- |
| Promise<boolean> | 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<boolean> | 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.|
| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite.|
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.
| 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
letdevicesName="1-1";
letbundleName="com.example.hello";
if(usb.addRight(bundleName,devicesName){
console.log(`Succeed in adding right`);
}
```
## usb.claimInterface
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
| 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**
...
...
@@ -221,7 +301,7 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c
| 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**
...
...
@@ -251,7 +331,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| 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**
...
...
@@ -281,7 +361,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| 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**
...
...
@@ -310,7 +390,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| 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**
...
...
@@ -338,7 +418,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| 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**
...
...
@@ -348,7 +428,7 @@ let ret = usb.getFileDescriptor(devicepipe);
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.
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.
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.
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.
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.
The USB driver model offers the following APIs:
- Interface
- 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 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.
-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.
-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.
### Available APIs
### Working Principles
The tables below describe the APIs provided by the USB host driver model.
#### USB Host DDK
**Table 1** usb_ddk_interface.h
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.
| API| Description|
| -------- | -------- |
| int32_t UsbInitHostSdk(struct UsbSession \*\*session); | Initializes the USB host driver DDK.|
| int32_t UsbExitHostSdk(const struct UsbSession<br>\*session); | Exits the USB host driver DDK.|
| const struct UsbInterface \*UsbClaimInterface(const<br>struct UsbSession \*session, uint8_t busNum, uint8_t<br>usbAddr, uint8_t interfaceIndex); | Obtains a USB interface.|
| int UsbReleaseInterface(const struct UsbInterface<br>\*interfaceObj); | Releases a USB interface.|
| int UsbAddOrRemoveInterface(const struct UsbSession<br>\*session, uint8_t busNum, uint8_t usbAddr, uint8_t<br>interfaceIndex, UsbInterfaceStatus status); | Adds or removes a USB interface.|
| UsbInterfaceHandle \*UsbOpenInterface(const struct<br>UsbInterface \*interfaceObj); | Opens a USB interface.|
| int32_t UsbCloseInterface(const UsbInterfaceHandle<br>\*interfaceHandle); | Closes a USB interface.|
| int32_t UsbSelectInterfaceSetting(const<br>UsbInterfaceHandle \*interfaceHandle, uint8_t<br>settingIndex, struct UsbInterface \*\*interfaceObj); | Sets a USB interface.|
| int32_t UsbGetPipeInfo(const UsbInterfaceHandle<br>\*interfaceHandle, uint8_t settingIndex, uint8_t pipeId,<br>struct UsbPipeInfo \*pipeInfo); | Obtains USB pipe information.|
| int32_t UsbClearInterfaceHalt(const<br>UsbInterfaceHandle \*interfaceHandle, uint8_t<br>pipeAddress); | Clears the state of the pipe with the specified index.|
| struct UsbRequest \*UsbAllocRequest(const<br>UsbInterfaceHandle \*interfaceHandle, int isoPackets<br>, int length); | Allocates a request object.|
| int UsbFreeRequest(const struct UsbRequest<br>\*request); | Releases a request object.|
| int UsbSubmitRequestAsync(const struct UsbRequest<br>\*request); | Sends an asynchronous request.|
| int32_t UsbFillRequest(const struct UsbRequest<br>\*request, const UsbInterfaceHandle \*interfaceHandle,<br>const struct UsbRequestParams \*params); | Fills in a request.|
| sint UsbCancelRequest(const struct UsbRequest<br>\*request); | Cancels an asynchronous request.|
| int UsbSubmitRequestSync(const struct UsbRequest<br>\*request); | Sends a synchronous request.|
| int UsbRawInit(struct UsbSession \*\*session); | Initializes the USB raw APIs.|
| int UsbRawExit(const struct UsbSession \*session); | Exits the USB raw APIs.|
| UsbRawHandle \*UsbRawOpenDevice(const struct<br>UsbSession \*session, uint8_t busNum, uint8_t<br>usbAddr); | Opens a USB device.|
| int UsbRawCloseDevice(const UsbRawHandle<br>\*devHandle); | Closes a USB device.|
| int UsbRawSendControlRequest(const struct<br>UsbRawRequest \*request, const UsbRawHandle<br>\*devHandle, const struct UsbControlRequestData<br>\*requestData); | Performs a control transfer synchronously.|
| int UsbRawSendBulkRequest(const struct<br>UsbRawRequest \*request, const UsbRawHandle<br>\*devHandle, const struct UsbRequestData<br>\*requestData); | Performs a bulk transfer synchronously.|
| int UsbRawSendInterruptRequest(const struct<br>UsbRawRequest \*request, const UsbRawHandle<br>\*devHandle, const struct UsbRequestData<br>\*requestData); | Performs an interrupt transfer synchronously.|
| int UsbRawGetConfigDescriptor(const UsbRawDevice<br>\*rawDev, uint8_t configIndex, struct<br>UsbRawConfigDescriptor \*\*config); | Obtains the configuration descriptor of a device.|
| void UsbRawFreeConfigDescriptor(const struct<br>UsbRawConfigDescriptor \*config); | Releases the memory space of a configuration descriptor.|
| int UsbRawGetConfiguration(const UsbRawHandle<br>\*devHandle, int \*config); | Obtains the configuration in use.|
| int UsbRawSetConfiguration(const UsbRawHandle<br>\*devHandle, int config); | Sets the configuration in use.|
| UsbRawDevice \*UsbRawGetDevice(const UsbRawHandle<br>\*devHandle); | Obtains the device pointer based on the device handle.|
| int UsbRawGetDeviceDescriptor(const UsbRawDevice<br>\*rawDev, struct<br>UsbDeviceDescriptor \*desc); | Obtains the device descriptor of the specified USB device.|
| int UsbRawClaimInterface(const UsbRawHandle<br>\*devHandle, int<br>interfaceNumber); | Declares the interface on the specified device handle.|
| int UsbRawReleaseInterface(const UsbRawHandle<br>\*devHandle, in<br>t interfaceNumber); | Releases the previously declared interface.|
| int UsbRawResetDevice(const UsbRawHandle<br>\*devHandle); | Resets a device.|
| struct UsbRawRequest \*UsbRawAllocRequest(const<br>UsbRawHandle<br>\*devHandle, int isoPackets, int length); | Allocates a transfer request with the specified number of sync packet descriptors.|
| int UsbRawFreeRequest(const struct UsbRawRequest<br>\*request); | Releases the previously allocated transfer request.|
| int UsbRawFillBulkRequest(const struct UsbRawRequest<br>\*request, const UsbRawHandle \*devHandle, const struct<br>UsbRawFillRequestData \*fillData); | Fills in a bulk transfer request.|
| int UsbRawFillControlSetup(const unsigned char \*setup,<br>const struct UsbControlRequestData \*requestData); | Fills in a control setup packet.|
| int UsbRawFillControlRequest(const struct UsbRawRequest<br>\*request, const UsbRawHandle \*devHandle, const struct<br>UsbRawFillRequestData \*fillData); | Fills in a control transfer request.|
| int UsbRawFillInterruptRequest(const struct UsbRawRequest<br>\*request, const UsbRawHandle \*devHandle, const struct<br>UsbRawFillRequestData \*fillData); | Fills in an interrupt transfer request.|
| int UsbRawFillIsoRequest(const struct UsbRawRequest<br>\*request, const UsbRawHandle \*devHandle, const struct<br>UsbRawFillRequestData \*fillData); | Fills in an isochronous transfer request.|
| int UsbRawSubmitRequest(const struct UsbRawRequest<br>\*request); | Submits a transfer request.|
| int UsbRawCancelRequest(const struct UsbRawRequest<br>\*request); | Cancels a transfer request.|
| int UsbRawHandleRequests(const 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
- 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.
| API| Description|
| -------- | -------- |
| const struct UsbFnDevice \*UsbFnCreateDevice(const<br>char \*udcName, const struct UsbFnDescriptorData<br>\*descriptor); | Creates a USB device.|
| int UsbFnRemoveDevice(struct UsbFnDevice<br>\*fnDevice); | Deletes a USB device.|
| const struct UsbFnDevice \*UsbFnGetDevice(const char<br>\*udcName); | Obtains a USB device.|
- 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.
**Table 4** usbfn_interface.h
- 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.
**Table 5** usbfn_request.h
- 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.
| API| Description|
| -------- | -------- |
| struct UsbFnRequest<br>\*UsbFnAllocCtrlRequest(UsbFnInterfaceHandle handle,<br>uint32_t len); | Allocates a control transfer request.|
| struct UsbFnRequest \*UsbFnAllocRequest(UsbFnInterfaceHandle handle,<br>uint8_t pipe, uint32_t len); | Allocates a data request.|
| int UsbFnFreeRequest(struct UsbFnRequest \*req); | Releases a request.|
| int UsbFnSubmitRequestAsync(struct UsbFnRequest<br>\*req); | Sends an asynchronous request.|
| int UsbFnSubmitRequestSync(struct UsbFnRequest<br>\*req, uint32_t timeout); | Sends a synchronous request.|
| int UsbFnCancelRequest(struct UsbFnRequest \*req); | Cancels a request.|
- 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
## How to Develop
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.
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.
- 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.
1. Configure the driver mapping table.
- 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.
2. Initialize the USB host DDK.
- 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.
3. Obtain a **UsbInterface** object.
- 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.
4. Open the **UsbInterface** object to obtain the **UsbInterfaceHandle** object.
- 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.
5. Obtain pipe information of the specified **pipeIndex** based on the **UsbInterfaceHandle** object.
- The Adapter module is provided by the composite device configuration driver and common function driver.
6. Allocate an I/O request for the **UsbInterfaceHandle** object.
## How to Develop
7. Fill in the I/O request based on the input parameters.
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.
8. Submit the I/O request in synchronous or asynchronous mode.
### 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.
### Developing Driver Using Host Raw APIs
### Available APIs
1. Configure the driver mapping table.
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).
2. Initialize the host raw data, open the USB device, obtain the descriptor, and then obtain interface and endpoint information based on the descriptor.
**Table 1** APIs for USB host driver development (common mode)
3. Allocate a request and fill in the request based on the transfer type.
| API| Description|
| -------- | -------- |
| int32_t UsbInitHostSdk(struct UsbSession \*\*session); | Initializes the USB host driver DDK.|
| const struct UsbInterface \*UsbClaimInterface(const<br>struct UsbSession \*session, uint8_t busNum, uint8_t<br>usbAddr, uint8_t interfaceIndex); | Obtains a USB interface.|
| UsbInterfaceHandle \*UsbOpenInterface(const struct<br>UsbInterface \*interfaceObj); | Opens a USB interface.|
| int32_t UsbGetPipeInfo(const UsbInterfaceHandle<br>\*interfaceHandle, uint8_t settingIndex, uint8_t pipeId,<br>struct UsbPipeInfo \*pipeInfo); | Obtains USB pipe information.|
| struct UsbRequest \*UsbAllocRequest(const<br>UsbInterfaceHandle \*interfaceHandle, int32_t isoPackets<br>, int32_t length); | Allocates a request object.|
| int32_t UsbFillRequest(const struct UsbRequest<br>\*request, const UsbInterfaceHandle \*interfaceHandle,<br>const struct UsbRequestParams \*params); | Fills in a request.|
| int32_t UsbSubmitRequestSync(const struct UsbRequest<br>\*request); | Sends a synchronous request.|
4. Submit the I/O request in synchronous or asynchronous mode.
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** APIs for USB host driver development (expert mode)
### Developing Driver Using Device DDK APIs
| API| Description|
| -------- | -------- |
| int32_t UsbRawInit(struct UsbSession \*\*session); | Initializes the USB raw APIs.|
| UsbRawHandle \*UsbRawOpenDevice(const struct<br>UsbSession \*session, uint8_t busNum, uint8_t<br>usbAddr); | Opens a USB device.|
| int32_t UsbRawSendControlRequest(const struct<br>UsbRawRequest \*request, const UsbRawHandle<br>\*devHandle, const struct UsbControlRequestData<br>\*requestData); | Performs a control transfer synchronously.|
| int32_t UsbRawSendBulkRequest(const struct<br>UsbRawRequest \*request, const UsbRawHandle<br>\*devHandle, const struct UsbRequestData<br>\*requestData); | Performs a bulk transfer synchronously.|
| int32_t UsbRawSendInterruptRequest(const struct<br>UsbRawRequest \*request, const UsbRawHandle<br>\*devHandle, const struct UsbRequestData<br>\*requestData); | Performs an interrupt transfer synchronously.|
| int32_t UsbRawGetConfigDescriptor(const UsbRawDevice<br>\*rawDev, uint8_t configIndex, struct<br>UsbRawConfigDescriptor \*\*config); | Obtains the configuration descriptor of a device.|
| int32_t UsbRawFillInterruptRequest(const struct UsbRawRequest<br>\*request, const UsbRawHandle \*devHandle, const struct<br>UsbRawFillRequestData \*fillData); | Fills in an interrupt transfer request.|
| int32_t UsbRawFillIsoRequest(const struct UsbRawRequest<br>\*request, const UsbRawHandle \*devHandle, const struct<br>UsbRawFillRequestData \*fillData); | Fills in an isochronous transfer request.|
| int32_t UsbRawSubmitRequest(const struct UsbRawRequest<br>\*request); | Submits a transfer request.|
| int32_t UsbRawCancelRequest(const struct UsbRawRequest<br>\*request); | Cancels a transfer request.|
| int32_t UsbRawHandleRequests(const UsbRawHandle<br>\*devHandle); | Handles a transfer request event.|
1. Construct a descriptor.
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).
2. Instantiate a USB device using the descriptor constructed.
**Table 3** APIs for USB device management on the device side
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.
| API| Description|
| -------- | -------- |
| const struct UsbFnDevice \*UsbFnCreateDevice(const<br>char \*udcName, const struct UsbFnDescriptorData<br>\*descriptor); | Creates a USB device.|
| int32_t UsbFnRemoveDevice(struct UsbFnDevice<br>\*fnDevice); | Deletes a USB device.|
| const struct UsbFnDevice \*UsbFnGetDevice(const char<br>\*udcName); | Obtains a USB device.|
4. Call **UsbFnInterfaceStartRecvEvent** to receive events such as Enable and Setup, and respond to the events in **UsbFnEventCallback**.
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).
5. Send and receive data in synchronous or asynchronous mode.
**Table 4** APIs for USB interface definition on the device side
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).
The following examples help you better understand the development of the USB serial port driver.
**Table 5** APIs for USB data request on the device side
| API| Description|
| -------- | -------- |
| struct UsbFnRequest<br>\*UsbFnAllocCtrlRequest(UsbFnInterfaceHandle handle,<br>uint32_t len); | Allocates a control transfer request.|
| struct UsbFnRequest \*UsbFnAllocRequest(UsbFnInterfaceHandle handle,<br>uint8_t pipe, uint32_t len); | Allocates a data request.|
| int32_t UsbFnFreeRequest(struct UsbFnRequest \*req); | Releases a request.|
| int32_t UsbFnSubmitRequestAsync(struct UsbFnRequest<br>\*req); | Sends an asynchronous request.|
| int32_t UsbFnSubmitRequestSync(struct UsbFnRequest<br>\*req, uint32_t timeout); | Sends a synchronous request.|
| int32_t UsbFnCancelRequest(struct UsbFnRequest \*req); | Cancels a request.|
### Developing Driver Using Host DDK APIs
### How to Develop
```
root {
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.
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.
acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // Allocate the readReq I/O request to be sent.
HDF_LOGE("%s: interface%d is null", __func__, acm->interfaceIndex[i]);
gotoerror;
}
}
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->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT); // Obtain pipe information of the control pipe.
snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); // Allocate the I/O request object to be sent.
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.
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.
@@ -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.|
| sandbox-path | Target path in the sandbox.|
| 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.|
| link-name | Target link in the sandbox.|
...
...
@@ -44,13 +45,13 @@ Logical storage structure of the sandbox:
boolInitSandboxWithName(constchar*name);// Parsing to the JSON structure
typedefstruct{
mountlist_t*mounts;// Directory to mount
mountlist_t*fileMounts;// File to mount
linklist_t*links;// Directory to link
char*rootPath;// Root path of the sandbox: /mnt/sandbox/system|vendor|xxx
charname[MAX_BUFFER_LEN];// Sandbox name, for example, system sandbox or chipset sandbox
boolisCreated;// Sandbox creation flag
intns;// namespace
ListNodepathMountsHead;// sandbox mount_path list head
ListNodefileMountsHead;// sandbox mount_file list head
ListNodelinksHead;// sandbox symbolic link list head
char*rootPath;// /mnt/sandbox/system|vendor|xxx
charname[MAX_BUFFER_LEN];// name of sandbox. i.e system, chipset etc.