HarmonyOS设备管理开发:USB服务开发指导

基本概念

USB服务是应用访问底层的一种设备抽象概念。开发者根据提供的USB API,可以获取设备列表、控制设备访问权限、以及与连接的设备进行数据传输、控制命令传输等。

运作机制

USB服务系统包含USB API、USB Service、USB HAL。

图1 USB服务运作机制

● USB API:提供USB的基础API,主要包含查询USB设备列表、批量数据传输、控制命令传输、权限控制等。

● USB Service:主要实现HAL层数据的接收、解析、分发以及对设备的管理等。

● USB HAL层:提供给用户态可直接调用的驱动能力接口。

场景介绍

Host模式下,可以获取到已经连接的USB设备列表,并根据需要打开和关闭设备、控制设备权限、进行数据传输等。

接口说明

USB服务主要提供的功能有:查询USB设备列表、批量数据传输、控制命令传输、权限控制等。

USB类开放能力如下,具体请查阅API参考文档

表1 USB类的开放能力接口

接口名 描述
hasRight(deviceName: string): boolean 判断是否有权访问该设备
requestRight(deviceName: string): Promise 请求软件包的临时权限以访问设备。使用Promise异步回调。
removeRight(deviceName: string): boolean 移除软件包对设备的访问权限。
connectDevice(device: USBDevice): Readonly 根据getDevices()返回的设备信息打开USB设备。
getDevices(): Array<Readonly> 获取接入主设备的USB设备列表。如果没有设备接入,那么将会返回一个空的列表。
setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number 设置设备的配置。
setInterface(pipe: USBDevicePipe, iface: USBInterface): number 设置设备的接口。
claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number 注册通信接口。
bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise 批量传输。
closePipe(pipe: USBDevicePipe): number 关闭设备消息控制通道。
releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number 释放注册过的通信接口。
getFileDescriptor(pipe: USBDevicePipe): number 获取文件描述符。
getRawDescriptor(pipe: USBDevicePipe): Uint8Array 获取原始的USB描述符。
controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise 控制传输。

开发步骤

USB设备可作为Host设备连接Device设备进行数据传输。开发示例如下:

  1. 获取设备列表。
yaml 复制代码
```ts
// 导入USB接口api包。
import usb from '@ohos.usbManager';
// 获取设备列表。
let deviceList : Array<usb.USBDevice> = usb.getDevices();
/
deviceList结构示例
[
  {
    name: "1-1",
    serial: "",
    manufacturerName: "",
    productName: "",
    version: "",
    vendorId: 7531,
    productId: 2,
    clazz: 9,
    subClass: 0,
    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,
            subClass: 0,
            alternateSetting: 0,
            name: "1-1",
            endpoints: [
              {
                address: 129,
                attributes: 3,
                interval: 12,
                maxPacketSize: 4,
                direction: 128,
                number: 1,
                type: 3,
                interfaceId: 0,
              }
            ]
          }
        ]
      }
    ]
  }
]
/
  1. 获取设备操作权限。
vbnet 复制代码
```ts 
import usb from '@ohos.usbManager'; 
import { BusinessError } from '@ohos.base'; 
let deviceName : string = deviceList[0].name;
// 申请操作指定的device的操作权限。
usb.requestRight(deviceName).then((hasRight : boolean) => {
  console.info("usb device request right result: " + hasRight);
}).catch((error : BusinessError)=> {
  console.info("usb device request right failed : " + error);
});
```
  1. 打开Device设备。
ini 复制代码
```ts
// 打开设备,获取数据传输通道。
let interface1 = deviceList[0].configs[0].interfaces[0];
let interface1 : number = deviceList[0].configs[0].interfaces[0];
/
 打开对应接口,在设备信息(deviceList)中选取对应的interface。
interface1为设备配置中的一个接口。
/
usb.claimInterface(pipe, interface1, true);

let pipe : USBDevicePipe = usb.connectDevice(deviceList[0]);

  1. 数据传输。
typescript 复制代码
import usb from '@ohos.usbManager'; 
import { BusinessError } from '@ohos.base';
/*
 读取数据,在device信息中选取对应数据接收的endpoint来做数据传输
(endpoint.direction == 0x80);dataUint8Array是要读取的数据,类型为Uint8Array。
*/
let inEndpoint : USBEndpoint = interface1.endpoints[2];
let outEndpoint : USBEndpoint = interface1.endpoints[1];
let dataUint8Array : Array<number> = new Uint8Array(1024);
usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => {
if (dataLength >= 0) {
  console.info("usb readData result Length : " + dataLength);
} else {
  console.info("usb readData failed : " + dataLength);
}
}).catch((error : BusinessError) => {
console.info("usb readData error : " + JSON.stringify(error));
});
// 发送数据,在device信息中选取对应数据发送的endpoint来做数据传输。(endpoint.direction == 0)
usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => {
  if (dataLength >= 0) {
    console.info("usb writeData result write length : " + dataLength);
  } else {
    console.info("writeData failed");
  }
}).catch((error : BusinessError) => {
  console.info("usb writeData error : " + JSON.stringify(error));
});

let inEndpoint : USBEndpoint = interface1.endpoints[2];

  1. 释放接口,关闭设备。
go 复制代码
```ts
usb.releaseInterface(pipe, interface1);
usb.closePipe(pipe);
```
相关推荐
音视频牛哥1 天前
SmartMediaKit 鸿蒙NEXT GB28181设备接入SDK
华为·harmonyos·鸿蒙gb28181·鸿蒙next gb28181·鸿蒙gb28181接入·鸿蒙接入gb28181平台·鸿蒙执法记录仪gb28181
key_3_feng1 天前
鸿蒙车规级MCU开发方案
单片机·华为·harmonyos
大雷神1 天前
HarmonyOS APP<<古今职鉴定>>开源教程第14篇:碰一碰分享:NFC 近场通信
华为·华为云·harmonyos
想你依然心痛1 天前
HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“智流工坊“——低代码可视化智能体编排平台
低代码·华为·harmonyos
richard_yuu1 天前
鸿蒙ArkUI组件化实战|公共组件封装、复用解耦与上架级UI规范落地
ui·华为·harmonyos
KKei16381 天前
Flutter for OpenHarmony 学习专注模式APP技术文章
学习·flutter·华为·harmonyos
想你依然心痛1 天前
HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“数字孪生工坊“——工业制造AI智能体协同平台
人工智能·制造·harmonyos
UnicornDev1 天前
【Flutter x HarmonyOS 6】挑战功能的业务逻辑实现
flutter·华为·harmonyos·鸿蒙·鸿蒙系统
不爱吃糖的程序媛1 天前
Harmonybrew:让Homebrew落地OpenHarmony,补齐鸿蒙命令行包管理能力
华为·harmonyos
nashane2 天前
HarmonyOS 6学习:AI攻略长截图“防抖”与像素级拼接术
学习·华为·harmonyos