usb-guidelines.md 6.3 KB
Newer Older
1
# USB Service Development
Z
zengyawen 已提交
2

3
## When to Use
Z
zengyawen 已提交
4

5
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.
Z
zengyawen 已提交
6

7
## APIs
Z
zengyawen 已提交
8

S
shawn_he 已提交
9 10
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.

S
shawn_he 已提交
11
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md).
Z
zengyawen 已提交
12 13 14

**Table  1**  Open USB APIs

15 16
| API                                                          | Description                                                  |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
17 18 19 20
| hasRight(deviceName: string): boolean                        | Checks whether the user has the device access permissions. |
| requestRight(deviceName: string): Promise\<boolean>          | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe>   | Connects to the USB device based on the device list returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>>                    | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. |
21 22
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration.                           |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface.                                        |
S
shawn_he 已提交
23 24
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface.                                       |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\<number> | Performs bulk transfer.                                      |
25 26 27 28
| closePipe(pipe: USBDevicePipe): number                       | Closes a USB device pipe.                                    |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface.                                    |
| getFileDescriptor(pipe: USBDevicePipe): number               | Obtains the file descriptor.                                 |
| getRawDescriptor(pipe: USBDevicePipe): Uint8Array            | Obtains the raw USB descriptor.                              |
29
| controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise\<number> | Performs control transfer.                                   |
30 31

## How to Develop
Z
zengyawen 已提交
32

S
shawn_he 已提交
33
You can set a USB device as the USB host to connect to other USB devices for data transfer. The development procedure is as follows:
Z
zengyawen 已提交
34 35 36

1.  Obtain the USB device list.

W
wu-chengwen 已提交
37
    ```js
Z
zengyawen 已提交
38
    // Import the USB API package.
39
    import usb from '@ohos.usbV9';
Z
zengyawen 已提交
40
    // Obtain the USB device list.
S
shawn_he 已提交
41
    let deviceList = usb.getDevices();
Z
zengyawen 已提交
42 43 44 45 46 47 48 49 50 51 52 53
    /*
    Example deviceList structure
    [
      {
        name: "1-1",
        serial: "",
        manufacturerName: "",
        productName: "",
        version: "",
        vendorId: 7531,
        productId: 2,
        clazz: 9,
S
shawn_he 已提交
54
        subClass: 0,
Z
zengyawen 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        protocol: 1,
        devAddress: 1,
        busNum: 1,
        configs: [
          {
            id: 1,
            attributes: 224,
            isRemoteWakeup: true,
            isSelfPowered: true,
            maxPower: 0,
            name: "1-1",
            interfaces: [
              {
                id: 0,
                protocol: 0,
                clazz: 9,
S
shawn_he 已提交
71
                subClass: 0,
Z
zengyawen 已提交
72 73 74 75 76 77 78 79 80 81 82 83
                alternateSetting: 0,
                name: "1-1",
                endpoints: [
                  {
                    address: 129,
                    attributes: 3,
                    interval: 12,
                    maxPacketSize: 4,
                    direction: 128,
                    number: 1,
                    type: 3,
                    interfaceId: 0,
G
ge-yafang 已提交
84 85 86 87 88 89 90 91
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
Z
zengyawen 已提交
92 93 94 95 96
    */
    ```

2.  Obtain the device operation permissions.

W
wu-chengwen 已提交
97
    ```js
S
shawn_he 已提交
98
    let deviceName = deviceList[0].name;
Z
zengyawen 已提交
99 100 101 102 103 104 105 106 107 108
    // Request the permissions to operate a specified device.
    usb.requestRight(deviceName).then(hasRight => {
      console.info("usb device request right result: " + hasRight);
    }).catch(error => {
      console.info("usb device request right failed : " + error);
    });
    ```

3.  Open the device.

W
wu-chengwen 已提交
109
    ```js
Z
zengyawen 已提交
110
    // Open the device, and obtain the USB device pipe for data transfer.
S
shawn_he 已提交
111
    let interface1 = deviceList[0].configs[0].interfaces[0];
Z
zengyawen 已提交
112 113
    /*
    Claim the corresponding interface from deviceList.
S
shawn_he 已提交
114
    interface1 must be one present in the device configuration.
Z
zengyawen 已提交
115
    */
S
shawn_he 已提交
116
    usb.claimInterface(pipe, interface1, true);
Z
zengyawen 已提交
117 118 119 120
    ```

4.  Perform data transfer.

121 122 123 124 125
   ```js
   /*
   Read data. Select the corresponding RX endpoint from deviceList for data transfer.
   (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array.
   */
S
shawn_he 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
   let inEndpoint = interface1.endpoints[2];
   let outEndpoint = interface1.endpoints[1];
   let dataUint8Array = new Uint8Array(1024);
   usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
   if (dataLength >= 0) {
     console.info("usb readData result Length : " + dataLength);
     let resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string.
     console.info("usb readData buffer : " + resultStr);
   } else {
     console.info("usb readData failed : " + dataLength);
   }
   }).catch(error => {
   console.info("usb readData error : " + JSON.stringify(error));
   });
   // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0)
   usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => {
     if (dataLength >= 0) {
       console.info("usb writeData result write length : " + dataLength);
     } else {
       console.info("writeData failed");
     }
   }).catch(error => {
     console.info("usb writeData error : " + JSON.stringify(error));
   });
150
   ```
Z
zengyawen 已提交
151 152 153

5.  Release the USB interface, and close the USB device.

W
wu-chengwen 已提交
154
    ```js
Z
zengyawen 已提交
155 156
    usb.releaseInterface(pipe, interface);
    usb.closePipe(pipe);
157
    ```