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 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.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