文档管理中心

USB批量传输

场景介绍

批量传输主要应用在传输和接收大量数据同时又没有带宽和间隔时间要求的情况下,例如传输文件、图像等场景,打印机和扫描仪等设备属于这种类型的设备。

环境准备

环境要求

  • 开发工具及配置:

    DevEco Studio作为驱动开发工具,是进行驱动开发必备条件之一,开发者可以使用该工具进行开发、调试、打包等操作。请下载安装该工具,并参考DevEco Studio使用指南中的创建工程及运行进行基本的操作验证,保证DevEco Studio可正常运行。

  • SDK版本配置:

    扩展外设管理提供的ArkTS接口,所需SDK版本为API 16及以上才可使用。

  • HDC配置:

    HDC(HarmonyOS Device Connector)是为开发人员提供的用于调试的命令行工具,通过该工具可以在Windows/Linux/Mac系统上与真实设备或者模拟器进行交互,详细参考HDC配置

搭建环境

  • 在PC上安装DevEco Studio,要求版本在4.1及以上。
  • 将public-SDK更新到API 16或以上。
  • PC安装HDC工具,通过该工具可以在Windows/Linux/Mac系统上与真实设备或者模拟器进行交互。
  • 用USB线缆将搭载HarmonyOS的设备连接到PC。

开发指导

接口说明

展开
接口名 描述
bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> 批量传输。

更多关于设备管理和传输模式的详细接口介绍,请查阅@ohos.usbManager

开发步骤

主机(Host)连接设备(Device),通过bulkTransfer接口进行数据传输。以下步骤描述了如何使用批量传输方式来传输数据:

说明

以下示例代码只是使用批量传输方式来传输数据的必要流程,需要放入具体的方法中执行。在实际调用时,设备开发者需要遵循设备相关协议进行调用,确保数据的正确传输和设备的兼容性。

  1. 导入模块。

    收起
    自动换行
    深色代码主题
    复制
    1. // 导入usbManager模块
    2. import { usbManager } from '@kit.BasicServicesKit';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. import { JSON } from '@kit.ArkTS';
  2. 获取设备列表。

    说明

    批量传输只能在传输类型为2的端点上进行,若不匹配会返回IO错误。

    收起
    自动换行
    深色代码主题
    复制
    1. // 获取设备列表。
    2. let deviceList: usbManager.USBDevice[] = [];
    3. try {
    4. deviceList = usbManager.getDevices();
    5. } catch (error) {
    6. console.error(`USB getDevices failed: ${error}`);
    7. this.logInfo_ += '\n[ERROR] USB getDevices failed: ' + JSON.stringify(error);
    8. }
    9. console.info(`deviceList: ${deviceList}`);
    10. this.logInfo_ += '\n[INFO] deviceList: ' + JSON.stringify(deviceList);
    11. if (deviceList === undefined || deviceList.length === 0) {
    12. console.error('deviceList is empty');
    13. this.logInfo_ += '\n[ERROR] deviceList is empty';
    14. return;
    15. }
    16. /*
    17. deviceList结构示例
    18. [
    19. {
    20. name: '1-1',
    21. serial: '',
    22. manufacturerName: '',
    23. productName: '',
    24. version: '',
    25. vendorId: 7531,
    26. productId: 2,
    27. clazz: 9,
    28. subClass: 0,
    29. protocol: 1,
    30. devAddress: 1,
    31. busNum: 1,
    32. configs: [
    33. {
    34. id: 1,
    35. attributes: 224,
    36. isRemoteWakeup: true,
    37. isSelfPowered: true,
    38. maxPower: 0,
    39. name: '1-1',
    40. interfaces: [
    41. {
    42. id: 0,
    43. protocol: 0,
    44. clazz: 9,
    45. subClass: 0,
    46. alternateSetting: 0,
    47. name: '1-1',
    48. endpoints: [
    49. {
    50. address: 129,
    51. attributes: 3,
    52. interval: 12,
    53. maxPacketSize: 4,
    54. direction: 128,
    55. number: 1,
    56. type: 3,
    57. interfaceId: 0,
    58. }
    59. ]
    60. }
    61. ]
    62. }
    63. ]
    64. }
    65. ]
    66. */
    67. this.deviceList_ = deviceList;
  3. 获取设备操作权限。

    收起
    自动换行
    深色代码主题
    复制
    1. if (this.deviceList_ === undefined || this.deviceList_.length === 0) {
    2. console.error('deviceList is empty');
    3. this.logInfo_ += '\n[ERROR] deviceList is empty';
    4. return;
    5. }
    6. let deviceList: usbManager.USBDevice[] = this.deviceList_;
    7. let deviceName: string = deviceList[0].name;
    8. // 申请操作指定的device的操作权限。
    9. usbManager.requestRight(deviceName).then((hasRight: boolean) => {
    10. console.info('usb device request right result: ' + hasRight);
    11. this.logInfo_ += '\n[INFO] usb device request right result: ' + JSON.stringify(hasRight);
    12. }).catch((error: BusinessError) => {
    13. console.error(`usb device request right failed : ${error}`);
    14. this.logInfo_ += '\n[ERROR] usb device request right failed: ' + JSON.stringify(error);
    15. });
  4. 打开设备。

    收起
    自动换行
    深色代码主题
    复制
    1. if (this.deviceList_ === undefined || this.deviceList_.length === 0) {
    2. console.error('deviceList_ is empty');
    3. this.logInfo_ += '\n[ERROR] deviceList is empty';
    4. return;
    5. }
    6. let deviceList: usbManager.USBDevice[] = this.deviceList_;
    7. try {
    8. if (!usbManager.hasRight(deviceList[0]?.name)) {
    9. console.error('permission denied');
    10. this.logInfo_ += '\n[ERROR] permission denied';
    11. return;
    12. }
    13. // 打开设备,获取数据传输通道。
    14. let pipe: usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]);
    15. if (!deviceList?.[0]?.configs?.[0]?.interfaces?.[0]) {
    16. console.error('invalid interface');
    17. this.logInfo_ += '\n[ERROR] invalid interface';
    18. return;
    19. }
    20. let interface1: usbManager.USBInterface = deviceList?.[0]?.configs?.[0]?.interfaces?.[0];
    21. /*
    22. 打开对应接口,在设备信息(deviceList)中选取对应的interface。
    23. interface1为设备配置中的一个接口。
    24. */
    25. usbManager.claimInterface(pipe, interface1, true);
    26. this.pipe_ = pipe;
    27. this.interface_ = interface1;
    28. console.info('open device success');
    29. this.logInfo_ += '\n[INFO] open device success';
    30. } catch (error) {
    31. console.error(`USB hasRight failed: ${error}`);
    32. this.logInfo_ += '\n[ERROR] USB hasRight failed: ' + JSON.stringify(error);
    33. }
  5. 数据传输。

    说明

    在数据传输前建议先获取interface所属endpoint的type,通过type判断interface是否支持所需的传输类型。

    若调用传输接口失败,请先确认设备interface是否支持模式切换。若alternateSetting支持切换设置,可在传输前调用usbManager.setInterface重新设置interface,使端点和传输类型匹配,保证端点正常通信。

    收起
    自动换行
    深色代码主题
    复制
    1. if (this.pipe_ === undefined || this.interface_ === undefined) {
    2. console.error('pipe_ or interface_ is null');
    3. this.logInfo_ += '\n[ERROR] pipe_ or interface_ is null';
    4. return;
    5. }
    6. let pipe: usbManager.USBDevicePipe = this.pipe_;
    7. let interface1: usbManager.USBInterface = this.interface_;
    8. /*
    9. 读取数据,在device信息中选取对应数据接收的endpoint来做数据传输
    10. (endpoint.direction == 0x80);dataUint8Array是要读取的数据,类型为Uint8Array。
    11. */
    12. let inEndpoint: usbManager.USBEndpoint = interface1.endpoints?.[1];
    13. let outEndpoint: usbManager.USBEndpoint = interface1.endpoints?.[0];
    14. let dataUint8Array: Uint8Array = new Uint8Array(1024);
    15. if (inEndpoint !== undefined && inEndpoint.direction === 0x80) {
    16. usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength: number) => {
    17. if (dataLength >= 0) {
    18. console.info(`usb readData result Length : ${dataLength}`);
    19. this.logInfo_ += '\n[INFO] usb readData result Length: ' + JSON.stringify(dataLength);
    20. } else {
    21. console.error('usb readData failed');
    22. this.logInfo_ += '\n[ERROR] usb readData failed';
    23. }
    24. }).catch((error: BusinessError) => {
    25. console.error(`usb readData error : ${error}`);
    26. this.logInfo_ += '\n[ERROR] usb readData error: ' + JSON.stringify(error);
    27. });
    28. }
    29. // 发送数据,在device信息中选取对应数据发送的endpoint来做数据传输。(endpoint.direction == 0)
    30. if (outEndpoint !== undefined && outEndpoint.direction === 0) {
    31. usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength: number) => {
    32. if (dataLength >= 0) {
    33. console.info(`usb writeData result write length : ${dataLength}`);
    34. this.logInfo_ += '\n[INFO] usb writeData result write length: ' + JSON.stringify(dataLength);
    35. } else {
    36. console.error('usb writeData failed');
    37. this.logInfo_ += '\n[ERROR] usb writeData failed';
    38. }
    39. }).catch((error: BusinessError) => {
    40. console.error(`usb writeData error : ${error}`);
    41. this.logInfo_ += '\n[ERROR] usb writeData error: ' + JSON.stringify(error);
    42. });
    43. }
  6. 释放接口,关闭设备。

    收起
    自动换行
    深色代码主题
    复制
    1. if (this.pipe_ === undefined || this.interface_ === undefined) {
    2. console.error('pipe_ or interface_ is null');
    3. this.logInfo_ += '\n[ERROR] pipe_ or interface_ is null';
    4. return;
    5. }
    6. let pipe: usbManager.USBDevicePipe = this.pipe_;
    7. let interface1: usbManager.USBInterface = this.interface_;
    8. try {
    9. usbManager.releaseInterface(pipe, interface1);
    10. usbManager.closePipe(pipe);
    11. } catch (error) {
    12. console.error(`failed: ${error}`);
    13. this.logInfo_ += '\n[ERROR] failed: ' + JSON.stringify(error);
    14. }
    15. this.pipe_ = undefined;
    16. this.interface_ = undefined;
    17. console.info('close device success');
    18. this.logInfo_ += '\n[INFO] close device success';