1# USB Service Development 2 3<!--Kit: Basic Services Kit--> 4<!--Subsystem: USB--> 5<!--Owner: @hwymlgitcode--> 6<!--Designer: @w00373942--> 7<!--Tester: @dong-dongzhen--> 8<!--Adviser: @w_Machine_cc--> 9 10## When to Use 11 12In 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. 13 14 15## Available APIs 16 17The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. 18 19The following table lists the USB APIs currently available. For details, see the [API Reference](../../reference/apis-basic-services-kit/js-apis-usbManager.md). 20 21**Table 1** Open USB APIs 22 23| Name | Description | 24| ------------------------------------------------------------ | ------------------------------------------------------------ | 25| hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions.| 26| requestRight(deviceName: string): Promise<boolean> | Requests the device access permissions for the application. This API uses a promise to return the result. | 27| removeRight(deviceName: string): boolean | Revokes the device access permissions of the application.| 28| connectDevice(device: USBDevice): Readonly<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. If the USB service is abnormal, **undefined** may be returned. Check whether the return value of the API is empty. | 29| getDevices(): Array<Readonly<USBDevice>> | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. When the developer mode is disabled, **undefined** may be returned if no device is connected. Check whether the return value of the API is empty. | 30| setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. | 31| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | 32| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. | 33| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> | Performs bulk transfer. | 34| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | 35| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | 36| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | 37| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. If the USB service is abnormal, **undefined** may be returned. Check whether the return value of the API is empty. | 38| usbControlTransfer(pipe: USBDevicePipe, requestparam: USBDeviceRequestParams, timeout?: number): Promise<number> | Performs control transfer. | 39 40 41## How to Develop 42 43You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows: 44 45 461. Obtain the USB device list. 47 48 ```ts 49 // Import the USB API package. 50 import { usbManager } from '@kit.BasicServicesKit'; 51 // Obtain the USB device list. 52 let deviceList : Array<usbManager.USBDevice> = usbManager.getDevices(); 53 /* 54 Example deviceList structure: 55 [ 56 { 57 name: "1-1", 58 serial: "", 59 manufacturerName: "", 60 productName: "", 61 version: "", 62 vendorId: 7531, 63 productId: 2, 64 clazz: 9, 65 subClass: 0, 66 protocol: 1, 67 devAddress: 1, 68 busNum: 1, 69 configs: [ 70 { 71 id: 1, 72 attributes: 224, 73 isRemoteWakeup: true, 74 isSelfPowered: true, 75 maxPower: 0, 76 name: "1-1", 77 interfaces: [ 78 { 79 id: 0, 80 protocol: 0, 81 clazz: 9, 82 subClass: 0, 83 alternateSetting: 0, 84 name: "1-1", 85 endpoints: [ 86 { 87 address: 129, 88 attributes: 3, 89 interval: 12, 90 maxPacketSize: 4, 91 direction: 128, 92 number: 1, 93 type: 3, 94 interfaceId: 0, 95 } 96 ] 97 } 98 ] 99 } 100 ] 101 } 102 ] 103 */ 104 ``` 105 1062. Obtain the device operation permissions. 107 108 ```ts 109 import { usbManager } from '@kit.BasicServicesKit'; 110 import { BusinessError } from '@kit.BasicServicesKit'; 111 112 let deviceName : string = deviceList[0].name; 113 // Request the permissions to operate a specified device. 114 usbManager.requestRight(deviceName).then((hasRight : boolean) => { 115 console.info(`usb device request right result: ${hasRight}`); 116 }).catch((error : BusinessError)=> { 117 console.error(`usb device request right failed : ${error}`); 118 }); 119 ``` 120 1213. Open the device. 122 123 ```ts 124 // Open the device, and obtain the USB device pipe for data transfer. 125 let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]); 126 let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0]; 127 /* 128 Claim the corresponding interface from **deviceList**. 129 interface1 must be one present in the device configuration. 130 */ 131 usbManager.claimInterface(pipe, interface1, true); 132 ``` 133 1344. Perform data transfer. Currently, only bulk transfer and control transfer are supported. 135 136 - Bulk transfer 137 138 ```ts 139 import { usbManager } from '@kit.BasicServicesKit'; 140 import { BusinessError } from '@kit.BasicServicesKit'; 141 /* 142 Read data. Select the corresponding RX endpoint from deviceList for data transfer. 143 (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array. 144 */ 145 let inEndpoint : usbManager.USBEndpoint = interface1.endpoints[2]; 146 let outEndpoint : usbManager.USBEndpoint = interface1.endpoints[1]; 147 let dataUint8Array : Uint8Array = new Uint8Array(1024); 148 usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => { 149 if (dataLength >= 0) { 150 console.info(`usb readData result Length : ${dataLength}`); 151 } else { 152 console.error(`usb readData failed`); 153 } 154 }).catch((error : BusinessError) => { 155 console.error(`usb readData error : ${error}`); 156 }); 157 // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) 158 usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => { 159 if (dataLength >= 0) { 160 console.info(`usb writeData result write length : ${dataLength}`); 161 } else { 162 console.error("usb writeData failed"); 163 } 164 }).catch((error : BusinessError) => { 165 console.error(`usb writeData error : ${error}`); 166 }); 167 ``` 168 169 - Control transfer 170 171 ```ts 172 import { usbManager } from '@kit.BasicServicesKit'; 173 import { BusinessError } from '@kit.BasicServicesKit'; 174 175 /* 176 Construct control transfer parameters. 177 */ 178 let param: usbManager.USBDeviceRequestParams = { 179 bmRequestType: 0x80, // 0x80 indicates a standard request for data transfer from the device to the host. 180 bRequest: 0x06, // 0x06 indicates a request for the descriptor. 181 wValue:0x01 << 8 | 0, // The value is of two bytes. The high byte indicates the descriptor type. Here, 0x01 indicates the device descriptor. The low byte indicates the descriptor index. The value is set to 0 because it is not involved for the device descriptor. 182 wIndex: 0, // Descriptor index. The value can be 0. 183 wLength: 18, // Descriptor length. The value 18 indicates that a maximum of 1024 characters are supported. 184 data: new Uint8Array(18) 185 }; 186 187 usbManager.usbControlTransfer(pipe, param).then((ret: number) => { 188 console.info(`usbControlTransfer = ${ret}`); 189 }) 190 ``` 191 1925. Release the USB interface, and close the USB device. 193 194 ```ts 195 usbManager.releaseInterface(pipe, interface1); 196 usbManager.closePipe(pipe); 197 ```