触觉智能RK3576开发板OpenHarmony开源鸿蒙系统USB控制传输功能示例

科创之家 2025-10-01 8803人围观

本文介绍OpenHarmony开源鸿蒙系统USB控制传输功能实现及相关代码示例,基于触觉智能RK3576开发板Purple Pi OH2演示。

OpenHarmony的USB通信介绍

实现OpenHarmony开源鸿蒙设备与外部USB设备之间的连接管理、数据收发及设备信息交互,支持对USB 设备的枚举、配置及数据传输控制,适用于各类USB接口进行设备通信的场景。如AHD高清摄像头、密码键盘、检测模块等。

USB控制传输主要用于主机(Host)和设备(Device)进行设备状态的获取和设置,进行设备属性状态的的控制。根据设备支持的端点类型支持控制传输读和写。

示例环境

1、仅支持开源鸿蒙OpenHarmony L2标准系统上运行;

2、本示例已适配 API version 12 版本 SDK(兼容 API version 8 及以上版本);

3、本示例为Stage模型,需要使用DevEco Studio 5.0.2 Release及以上版本才可编译运行。;

核心功能模块实现逻辑

USB通信流程整体可分为3块组成:设备枚举→设备连接→数据传输/接收,流程图示:

wKgZPGjblNuARTImAANnBoKUGwo596.png

各流程示例代码,请继续浏览下文。

设备枚举模块

负责扫描并识别当前连接的 USB 设备,获取设备的基本信息(如设备ID、厂商 ID、产品 ID、接口类型等),基于 OpenHarmony 的 USB 服务接口实现设备列表的动态更新。代码示例:

// 获取USB设备列表 private getUsbDevices(): void { try { this.deviceList = usbManager.getDevices(); if (this.deviceList.length === 0) { this.log = '未检测到USB设备'; } else { this.log = `找到 ${this.deviceList.length} 个USB设备`; } this.selectedDeviceIndex = -1; this.interfaces = []; this.endpoints = []; this.selectedInterfaceIndex = -1; this.selectedEndpointIndex = -1; this.isDeviceSelected = false; this.isReceiving = false; } catch (error) { this.log = `获取设备列表失败: ${error}`; console.error("获取USB设备列表异常: ", error); } }

连接管理模块

处理 USB 设备的连接与断开逻辑,包括权限校验、设备挂载状态监测及连接状态回调通知,确保设备连接的稳定性。代码示例:

// 选择设备 private async selectDevice(index: number): Promise { this.selectedDeviceIndex = index; this.selectedInterfaceIndex = -1; this.selectedEndpointIndex = -1; this.interfaces = []; this.endpoints = []; this.isDeviceSelected = false; this.isReceiving = false; try { let deviceName: string = this.deviceList[index].name;

// 申请操作指定设备的权限 let hasRight: boolean = await usbManager.requestRight(deviceName); console.info("usb device request right result: " + hasRight); if (!hasRight) { this.log = 'USB设备权限获取失败'; return; }

数据传输模块

实现与 USB 设备的双向数据传输,支持批量传输。主机→USB 设备进行数据发送,适用于向 USB 设备发送配置命令、控制参数等场景,需选择 Out方向端点(端点地址 direction=0),流程包括:解析用户输入的16进制数据、建立设备通信管道、声明目标接口、调用 usbManager.bulkTransfer() 发送数据。代码示例

// 发送数据到设备 private async sendDataToDevice(): Promise { if (this.selectedDeviceIndex === -1 || this.selectedInterfaceIndex === -1 || this.selectedEndpointIndex === -1) { this.log = '请先选择设备、接口和端点'; this.showSendDataDialog = false; return; } if (!this.sendDataContent.trim()) { this.log = '发送数据不能为空'; return; }

数据接收模块

USB 设备→主机进行数据发送,适用于从 USB 设备获取状态数据、采集数据等场景,需选择 IN 方向端点(端点地址 direction=0x80),流程包括:建立设备通信管道、声明目标接口、循环调用 usbManager.bulkTransfer() 读取数据、解析数据为十六进制格式并展示。代码示例:

// 开始接收数据 private async startReceiveData(): Promise { if ( this.selectedDeviceIndex === -1 || this.selectedInterfaceIndex === -1 || this.selectedEndpointIndex === -1) { this.log = '请先选择设备、接口和端点'; return ; }

更多代码示例,请关注深圳触觉智能电子发烧友

  • 随机文章
  • 热门文章
  • 热评文章
不容错过
Powered By Z-BlogPHP