• Home
Name Date Size #Lines LOC

..--

figures/12-May-2024-

frameworks/dialog/dialog_ui/12-May-2024-608512

interfaces/12-May-2024-5,1073,348

sa_profile/12-May-2024-4528

services/12-May-2024-4,9994,162

test/12-May-2024-14,1209,879

utils/12-May-2024-559356

.clang-formatD12-May-2024892 2928

LICENSED12-May-20249.9 KiB176150

OAT.xmlD12-May-20247.6 KiB10855

README.mdD12-May-202415.2 KiB179137

README_zh.mdD12-May-20248 KiB154137

bundle.jsonD12-May-20241.9 KiB7777

hisysevent.yamlD12-May-20241.8 KiB4124

usbmgr.gniD12-May-2024741 1916

README.md

1# USB Manager `<a name="EN-US_TOPIC_0000001124094823"></a>`
2
3- [Introduction](#section11660541593)
4- [Directory Structure](#section19472752217)
5- [Available APIs](#section19472752218)
6- [Development Example](#section19472752219)
7- [Repositories Involved](#section63151229062)
8
9## Introduction`<a name="section11660541593"></a>`
10
11The following figure shows the USB service architecture.
12
13**Figure 1**  USB service architecture`<a name="fig15658513184019"></a>`
14![](figures/usb-manager-architecture.png "USB_service_architecture")
15
16The architecture logically consists of three layers:
17
181. USB API: provides USB APIs that implement various basic functions, for example, query of the USB device list, USB device plug notification, USB host and device mode switching, bulk transfer, control transfer, right management, and function switching in device mode.
192. USB Service: interacts with the HAL layer to receive, parse, and distribute data, manages foreground and background policies, and performs USB device management and right control.
203. USB HAL: provides driver capability APIs that can be directly called in user mode. The APIs are classified into the DDK initialization class, interface operation class, and request operation class by function. They can be used to perform DDK initialization, bind/release and open/close an interface, allocate/release a request, and implement isochronous or non-isochronous transfer. The USB HAL code is stored in [drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README.md).
21
22## Directory Structure`<a name="section19472752217"></a>`
23
24```
25base/usb/usb_manager
26├── interfaces                  # APIs
27│   ├── innerkits                  # Internal APIs
28│   └── kits                       # External APIs
29├── sa_profile                  # SA profile
30└── services                    # Services
31│   ├── native                     # Native APIs
32│   └── zidl                       # zidl APIs
33└── test                        # Test cases
34└── utils                       # Utilities
35```
36
37## Available APIs`<a name="section19472752218"></a>`
38
39### [External APIs](https://gitee.com/openharmony/usb_manager/blob/master/interfaces/kits/js/@ohos.usb.d.ts)
40
41### Internal APIs
42
43#### Host APIs
44
45| **API**                                                                                                        | **Description**                                                                                                                                                                                                                                                                                                                               |
46| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
47| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip);                                                     | Opens a USB device to set up a connection.                                                                                                                                                                                                                                                                                                          |
48| bool Close(const USBDevicePipe &pip);                                                                                | Closes a USB device to release all system resources related to the device.                                                                                                                                                                                                                                                                          |
49| int32_t GetDevices(std::vector &deviceList);                                                                         | Obtains the USB device list.                                                                                                                                                                                                                                                                                                                        |
50| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config);                                               | Sets the current configuration of the USB device.                                                                                                                                                                                                                                                                                                   |
51| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force);                               | Claims a USB interface exclusively. This must be done before data transfer.                                                                                                                                                                                                                                                                         |
52| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface);                                         | Releases a USB interface. This is usually done after data transfer.                                                                                                                                                                                                                                                                                 |
53| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface);                                            | Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings.                                                                                                                                                                                    |
54| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector<uint8_t> &vdata, int32_t timeout); | Writes data on a specified endpoint during bulk transfer.                                                                                                                                                                                                                                                                                           |
55| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &vdata);               | Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. If the result of**requestType & USB_ENDPOINT_DIR_MASK** is **USB_DIR_OUT**, the endpoint is in the data writing direction; if the result is **USB_DIR_IN**, the endpoint is in the data reading direction. |
56| int32_t RequestInitialize(UsbRequest &request);                                                                      | Initializes a request.                                                                                                                                                                                                                                                                                                                              |
57| int32_t RequestQueue(UsbRequest &request);                                                                           | Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction.                                                                                                                                                                                                   |
58| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req);                                       | Waits for the operation result of the isochronous transfer request in`<b>`RequestQueue`</b>`.                                                                                                                                                                                                                                                   |
59| int32_t RequestAbort(UsbRequest &request);                                                                           | Cancels the data transfer requests to be processed.                                                                                                                                                                                                                                                                                                 |
60| int32_t RequestFree(UsbRequest &request);                                                                            | Requests for releasing data.                                                                                                                                                                                                                                                                                                                        |
61| bool HasRight(std::string deviceName);                                                                               | Checks whether the application has permission to access the USB device.                                                                                                                                                                                                                                                                             |
62| int32_t RequestRight(std::string deviceName);                                                                        | Requests for permission to access the USB device.                                                                                                                                                                                                                                                                                                   |
63
64#### Device APIs
65
66| **API**                                      | **Description**                                                                      |
67| -------------------------------------------------- | ------------------------------------------------------------------------------------------ |
68| int32_t GetCurrentFunctions(int32_t &funcs);      | Obtains the list of functions (represented by bit field) supported by the current device.  |
69| int32_t SetCurrentFunctions(int32_t funcs);       | Sets the list of functions (represented by bit field) supported by the current device.     |
70| int32_t UsbFunctionsFromString(std::string funcs); | Converts the string descriptor of a given USB function list to a numeric mask combination. |
71| std::string UsbFunctionsToString(int32_t funcs);   | Converts the numeric mask combination of a given USB function list to a string descriptor. |
72
73#### Port APIs
74
75| **API**                                                             | **Description**                                                     |
76| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
77| int32_t GetPorts(std::vector &usbPorts);                                  | Obtains the port list.                                                    |
78| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | Sets the port role.                                                       |
79| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes);       | Obtains the mask combination for the supported mode list of a given port. |
80
81## Development Example`<a name="section19472752219"></a>`
82
83The following provides some examples on how to use major APIs. For detailed service code, see [js_unittest](test/native/js_unittest).
84
85#### Host Development
86
87In this example, the USB device serves as the host and connects to the device to implement data transfer.
88
891. Obtain the USB device list.
90
91```JS
92// Import the USB API package.
93import usb from '@ohos.usb';
94// Obtain the USB device list.
95var deviceList = usb.getDevices();
96```
97
982. Obtain the device operation permissions.
99
100```JS
101// device name
102var deviceName = deviceList[0].name;
103// Request for permission to operate a specified device.
104usb.requestRight(deviceName).then(hasRight => {
105	console.info("usb device request right result: " + hasRight);
106}).catch(error => {
107	console.info("usb device request right failed : " + error);
108});
109```
110
1113. Open the USB device.
112
113```JS
114// Open the USB device, and obtain the device pipe for data transfer.
115var pipe = usb.connectDevice(deviceList[0]);
116// Claim the USB interface.
117usb.claimInterface(pipe, interface, true); // Among the input arguments, interface refers to the one to be operated on the USB device.
118```
119
1204. Perform data transfer.
121
122```JS
123// Read data. Select the corresponding RX endpoint (endpoint.direction == 0x80) from deviceList for data transfer. The data data to be transferred is encapsulated in dataUint8Array.
124usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
125if (dataLength >= 0) {
126	console.info("usb readData result Length : " + dataLength);
127	var resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string.
128	console.info("usb readData buffer : " + resultStr);
129} else {
130	console.info("usb readData failed : " + dataLength);
131}
132}).catch(error => {
133console.info("usb readData error : " + JSON.stringify(error));
134});
135// Send data. Select the corresponding TX endpoint (endpoint.direction == 0) from deviceList for data transfer.
136usb.bulkTransfer(this.pip, this.outEndpoint, dataUint8Array, 15000).then(dataLength => {
137	if (dataLength >= 0) {
138		console.info("usb writeData result write length : " + dataLength);
139	} else {
140		console.info("writeData failed");
141	}
142}).catch(error => {
143	console.info("usb writeData error : " + JSON.stringify(error));
144});
145```
146
1475. Release the USB interface, and close the USB device.
148
149```JS
150usb.releaseInterface(pipe, interface);
151usb.closePipe(pipe);
152```
153
154#### Device Development
155
156In this example, the USB device is used as the device to set the ACM, ECM, and HDC functions.
157
1581. Set the USB functions.
159
160```JS
161usb.setCurrentFunctions(funType).then(data => {
162	console.info("usb setCurrentFunctions : " + data);
163}).catch(error => {
164	console.info("usb setCurrentFunctions error : " + error);
165});
166```
167
168## Repositories Involved`<a name="section63151229062"></a>`
169
170[Drive Subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/driver-subsystem.md)
171
172[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README.md)
173
174[drivers\_framework](https://gitee.com/openharmony/drivers_framework/blob/master/README.md)
175
176[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README.md)
177
178[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README.md)
179

README_zh.md

1# USB服务组件<a name="ZH-CN_TOPIC_0000001124094823"></a>
2
3-   [简介](#section11660541593)
4-   [目录](#section19472752217)
5-   [接口](#section19472752218)
6-   [开发示例](#section19472752219)
7-   [相关仓](#section63151229062)
8
9## 简介<a name="section11660541593"></a>
10USB服务框架如下图所示:
11
12**图 1**  USB服务框架架图<a name="fig15658513184019"></a>
13![](figures/usb-manager-architecture_zh.png "USB服务框架架图")
14
15架构及功能介绍:
161. USB API:提供USB的基础API,主要包含查询USB设备的列表、设备插拔通知、USB HOST/DEVICE 功能切换、批量数据传输、控制命令传输、USB设备打开的权限控制及USB device模式下的function功能切换等。
172. USB Service:主要实现HAL层数据接收、解析、分发,前后台的策略管控,对该设备USB的管理,USB权限管控等。
183. USB HAL层:提供给用户态可直接调用的驱动能力接口,按照功能分类三大类:DDK初始化类、对interface对象操作类、对request对象操作类,可以提供DDK初始化、interface绑定和释放,打开和关闭操作,request的申请和释放,同步和异步传输等。HAL层代码位于[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README_zh.md)
19
20## 目录<a name="section19472752217"></a>
21```
22base/usb/usb_manager
23├── interfaces                  # 接口层
24│   ├── innerkits                  # 内部接口
25│   └── kits                       # 外部接口
26├── sa_profile                  # SA配置文件
27└── services                    # 服务层
28│   ├── native                     # native层
29│   └── zidl                       # zidl接口层
30└── test                        # 测试用例
31└── utils                       # 工具和通用层
32```
33## 接口<a name="section19472752218"></a>
34### [外部接口](https://gitee.com/openharmony/usb_manager/blob/master/interfaces/kits/js/@ohos.usb.d.ts)
35
36### 内部接口
37#### Host 功能接口
38
39| **内部接口申明** | **接口描述** |
40| --- | --- |
41| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); | 打开设备,建立连接 |
42| bool Close(const USBDevicePipe &pip); | 关闭设备,释放与设备相关的所有系统资源 |
43| int32_t GetDevices(std::vector &deviceList); | 获取设备列表 |
44| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); | 设置设备当前使用的配置,通过配置值进行指定 |
45| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); | 打开接口,并申明独占接口,必须在数据传输前执行 |
46| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); | 关闭接口,释放接口的占用,在停止数据传输后执行 |
47| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); | 设置指定接口的备选设置,用于在具有相同ID但不同备用设置的两个接口之间进行选择 |
48| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector<uint8_t> &vdata, int32_t timeout); | 在给定端点上执行批量数据读写, 返回读取的数据和长度 |
49| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &vdata); | 对此设备执行端点零的控制事务,传输方向由请求类型决定。 如果requestType& USB_ENDPOINT_DIR_MASK是USB_DIR_OUT ,则传输是写入,如果是USB_DIR_IN ,则传输是读取。 |
50| int32_t RequestInitialize(UsbRequest &request); | 初始化请求 |
51| int32_t RequestQueue(UsbRequest &request); | 进行异步数据发送或者接收请求,数据传输方向由端点方向决定 |
52| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); | 等待RequestQueue异步请求的操作结果 |
53| int32_t RequestAbort(UsbRequest &request); | 取消待处理的数据请求 |
54| int32_t RequestFree(UsbRequest &request); | 释放数据请求 |
55| bool HasRight(std::string deviceName); | 判断设备是否有权限 |
56| int32_t RequestRight(std::string deviceName); | 给指定设备申请权限 |
57
58#### Device 功能接口
59| **内部接口申明** | **接口描述** |
60| --- | --- |
61| int32_t GetCurrentFunctions(int32_t &funcs); | 获取从设备支持的功能列表(按位域表示) |
62| int32_t SetCurrentFunctions(int32_t funcs); | 设置从设备支持的功能列表(按位域表示) |
63| int32_t UsbFunctionsFromString(std::string funcs); | 将给定的功能列表描述字符串转换为功能列表的数字组合掩码 |
64| std::string UsbFunctionsToString(int32_t funcs); | 将给定的功能列表的数字组合掩码转换为功能列表描述字符串 |
65
66#### Port 功能接口
67| **内部接口申明** | **接口描述** |
68| --- | --- |
69| int32_t GetPorts(std::vector &usbPorts); | 获取port列表 |
70| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | 设置端口工作模式 |
71| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); | 获取指定的端口支持的模式列表的组合掩码 |
72
73## 开发示例<a name="section19472752219"></a>
74主要接口调用示例如下,详细业务流程代码可以参考测试用例代码 [js_unittest](test/native/js_unittest)
75#### Host功能开发
76Usb设备作为host设备连接device设备进行数据传输。
771. 获取设备列表
78```JS
79// 导入usb接口api包
80import usb from '@ohos.usb';
81// 获取设备列表
82var deviceList = usb.getDevices();
83```
842. 获取设备操作权限
85```JS
86// device name
87var deviceName = deviceList[0].name;
88// 申请操作指定的device的操作权限
89usb.requestRight(deviceName).then(hasRight => {
90	console.info("usb device request right result: " + hasRight);
91}).catch(error => {
92	console.info("usb device request right failed : " + error);
93});
94```
953. 打开USB设备
96```JS
97// 打开设备,获取数据传输通道
98var pipe = usb.connectDevice(deviceList[0]);
99// 打开对应接口
100usb.claimInterface(pipe , interface, true); // interface为device中需要操作的interface,选取合适的interface进行对应操作
101```
1024. 数据传输
103```JS
104// 读取数据,在device信息中选取对应数据接收的endpoint来做数据传(endpoint.direction == 0x80);dataUint8Array要发送的数据
105usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
106if (dataLength >= 0) {
107	console.info("usb readData result Length : " + dataLength);
108	var resultStr = this.ab2str(dataUint8Array); // uint8数据转string
109	console.info("usb readData buffer : " + resultStr);
110} else {
111	console.info("usb readData failed : " + dataLength);
112}
113}).catch(error => {
114console.info("usb readData error : " + JSON.stringify(error));
115});
116// 发送数据,在device信息中选取对应数据发送的endpoint来做数据传(endpoint.direction == 0)
117usb.bulkTransfer(this.pip, this.outEndpoint, dataUint8Array, 15000).then(dataLength => {
118	if (dataLength >= 0) {
119		console.info("usb writeData result write length : " + dataLength);
120	} else {
121		console.info("writeData failed");
122	}
123}).catch(error => {
124	console.info("usb writeData error : " + JSON.stringify(error));
125});
126```
1275. 释放接口、关闭设备
128```JS
129usb.releaseInterface(pipe, interface);
130usb.closePipe(pipe);
131```
132#### Device功能开发
133Usb设备作为device设备,设置ACM、ECM、HDC等功能。
1341. 设置USB function功能
135```JS
136usb.setCurrentFunctions(funType).then(data => {
137	console.info("usb setCurrentFunctions : " + data);
138}).catch(error => {
139	console.info("usb setCurrentFunctions error : " + error);
140});
141```
142
143## 相关仓<a name="section63151229062"></a>
144
145[驱动子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E9%A9%B1%E5%8A%A8%E5%AD%90%E7%B3%BB%E7%BB%9F.md)
146
147[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README_zh.md)
148
149[drivers\_framework](https://gitee.com/openharmony/drivers_framework/blob/master/README_zh.md)
150
151[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README_zh.md)
152
153[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README_zh.md)
154