news 2026/5/1 3:45:27

【OpenHarmony】USB服务组件

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【OpenHarmony】USB服务组件

USB Manager 模块

目录

  1. 模块概述
    • 1.1 功能与目标
    • 1.2 系统位置
    • 1.3 设计思路与模式
    • 1.4 系统框图
  2. 模块结构
    • 2.1 源文件与头文件
    • 2.2 类、结构体、函数与方法
    • 2.3 类图
    • 2.4 模块内部依赖框图
  3. 模块间交互
    • 3.1 交互描述
    • 3.2 外部依赖框图
  4. 状态机转换图
    • 4.1 状态机模型
    • 4.2 状态机树图
    • 4.3 状态机切换规则
    • 4.4 状态机转换图
  5. 接口设计
    • 5.1 公共接口
    • 5.2 数据交换接口
    • 5.3 接口调用时序图

1. 模块概述

源码:https://gitee.com/openharmony/usb_usb_manager

1.1 功能与目标

主要功能

USB Manager 是 OpenHarmony 系统中的 USB 服务管理模块,提供完整的 USB 设备管理能力,主要功能包括:

功能类别功能描述
USB Host 功能查询USB设备列表、设备插拔通知、打开/关闭设备、批量数据传输、控制命令传输、设备权限管理
USB Device 功能USB function功能切换(ACM、ECM、HDC、MTP、PTP等)、配件模式管理
USB Port 功能USB HOST/DEVICE模式切换、端口角色设置、支持模式查询
Serial 功能串口设备管理、串口读写、串口属性配置
权限管理USB设备访问权限控制、权限申请与撤销、权限数据库管理
设计目标
  1. 统一管理: 提供统一的USB设备管理接口,屏蔽底层HAL差异
  2. 权限控制: 实现细粒度的USB设备访问权限控制
  3. 事件驱动: 支持USB设备热插拔事件的实时通知
  4. 多模式支持: 同时支持Host模式和Device模式
  5. 可扩展性: 模块化设计,便于功能扩展
使用场景
  • 移动设备连接USB外设(键盘、鼠标、U盘等)
  • 设备作为USB从设备连接PC进行数据传输
  • USB调试模式(HDC)
  • 串口通信应用
  • 配件模式连接

1.2 系统位置

USB Manager 在 OpenHarmony 系统中的位置如下:

┌─────────────────────────────────────────────────────────────┐ │ 应用层 (Application) │ │ JS/TS/ETS 应用程序 │ ├─────────────────────────────────────────────────────────────┤ │ 框架层 (Framework) │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ USB API (NAPI) │ │ │ │ @ohos.usbManager 接口 │ │ │ └─────────────────────────────────────────────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ 服务层 (Service) │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ ★ USB Manager Service ★ │ │ │ │ ┌──────────┬──────────┬──────────┬──────────────┐ │ │ │ │ │ Host │ Device │ Port │ Serial │ │ │ │ │ │ Manager │ Manager │ Manager │ Manager │ │ │ │ │ └──────────┴──────────┴──────────┴──────────────┘ │ │ │ │ ┌──────────────────┬──────────────────────────┐ │ │ │ │ │ Right Manager │ Accessory Manager │ │ │ │ │ └──────────────────┴──────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ HAL层 (Hardware Abstraction) │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ USB HAL │ │ │ │ IUsbInterface / ISerialInterface │ │ │ └─────────────────────────────────────────────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ 内核层 (Kernel) │ │ Linux USB Driver │ └─────────────────────────────────────────────────────────────┘
模块性质
  • 类型: 核心系统服务模块
  • SA ID: 4201 (USB_SYSTEM_ABILITY_ID)
  • 运行方式: 系统能力(SystemAbility)
  • 进程模型: 独立进程运行
与其他模块的关系
相关模块关系描述
驱动子系统依赖USB HAL层提供的驱动能力接口
系统服务管理作为SystemAbility注册到SAMgr
权限管理与AccessToken服务交互进行权限校验
包管理与BundleMgr交互获取应用信息
公共事件服务发布USB设备插拔等公共事件
数据共享使用DataShare存储权限数据

1.3 设计思路与模式

设计思路
  1. 分层架构设计

    • API层:提供NAPI接口供JS/TS应用调用
    • Service层:实现核心业务逻辑
    • HAL层:封装硬件抽象层接口
  2. 模块化设计

    • 按功能划分为Host、Device、Port、Serial等子管理器
    • 各子模块职责单一,便于维护和扩展
  3. 事件驱动机制

    • 通过订阅者模式接收HAL层的设备事件
    • 使用公共事件服务广播设备状态变化
  4. 权限控制机制

    • 基于数据库的权限持久化存储
    • 支持临时权限和永久权限
    • 集成系统权限框架
设计模式
设计模式应用场景说明
单例模式UsbService、UsbSrvClient确保全局唯一实例,使用DelayedSpSingleton实现延迟单例
观察者模式UsbServiceSubscriber订阅HAL层事件,实现设备插拔监听
代理模式UsbSrvClient客户端代理,封装IPC通信细节
工厂模式HDI接口获取通过IUsbInterface::Get()获取HAL实例
策略模式权限管理不同类型权限使用不同的处理策略
模板方法模式Parcelable序列化统一的序列化/反序列化框架

1.4 系统框图

┌────────────────────────────────────────────────────────────────────────┐ │ USB API │ │ ┌────────────────────────┬─────────────────────┬──────────────────┐ │ │ │ USB FUNCTION │ USB INTERFACE │ USB ENUM │ │ │ │ • getDevices │ • USBEndpoint │ • PowerRoleType │ │ │ │ • connectDevice │ • USBInterface │ • DataRoleType │ │ │ │ • hasRight │ • USBConfig │ • PortModeType │ │ │ │ • requestRight │ • USBDevice │ • USBPortStatus │ │ │ │ • claimInterface │ • USBDevicePipe │ • FunctionType │ │ │ │ • bulkTransfer │ • USBPort │ │ │ │ │ • controlTransfer │ • USBControlParams │ │ │ │ └────────────────────────┴─────────────────────┴──────────────────┘ │ └────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ USB SERVICE │ │ ┌──────────────────┬──────────────────┬──────────────────────────┐ │ │ │ HOST │ DEVICE │ PORT │ │ │ │ ┌────────────┐ │ ┌────────────┐ │ ┌──────────────────┐ │ │ │ │ │ Right │ │ │ Function │ │ │ Status │ │ │ │ │ │ Manager │ │ │ Manager │ │ │ Manager │ │ │ │ │ └────────────┘ │ └────────────┘ │ └──────────────────┘ │ │ │ │ ┌────────────┐ │ ┌────────────┐ │ ┌──────────────────┐ │ │ │ │ │ Device │ │ │ Device │ │ │ Role │ │ │ │ │ │ Manager │ │ │ Manager │ │ │ Manager │ │ │ │ │ └────────────┘ │ └────────────┘ │ └──────────────────┘ │ │ │ └──────────────────┴──────────────────┴──────────────────────────┘ │ └────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ USB HAL │ │ ┌────────────────────────────────────────────────────────────────┐ │ │ │ HAL (INTERFACE IUsbInterface) │ │ │ └────────────────────────────────────────────────────────────────┘ │ │ ┌──────────────────────────┬─────────────────────────────────────┐ │ │ │ HOST DDK │ DEVICE DDK │ │ │ └──────────────────────────┴─────────────────────────────────────┘ │ └────────────────────────────────────────────────────────────────────────┘

2. 模块结构

2.1 源文件与头文件

2.1.1 服务层核心文件 (services/native/)
文件名功能描述
usb_service.h/cppUSB服务主类,继承SystemAbility,协调各子管理器
usb_host_manager.h/cppUSB Host模式管理器,处理外设连接和数据传输
usb_device_manager.h/cppUSB Device模式管理器,处理function切换
usb_port_manager.h/cppUSB端口管理器,处理Host/Device模式切换
usb_right_manager.h/cppUSB权限管理器,处理设备访问权限
usb_accessory_manager.h/cppUSB配件模式管理器
serial_manager.h/cpp串口管理器,处理USB串口设备
usb_right_database.h/cpp权限数据库操作封装
usb_right_db_helper.h/cpp权限数据库辅助类
usb_descriptor_parser.h/cppUSB描述符解析器
usb_service_subscriber.h/cppHAL层事件订阅者
usb_connection_notifier.h/cpp连接状态通知器
usb_function_switch_window.h/cppFunction切换窗口管理
usb_report_sys_event.h/cpp系统事件上报
usb_bulkcallback_impl.h/cpp批量传输回调实现
usb_transfer_callback_impl.h/cpp传输回调实现
2.1.2 接口层文件 (interfaces/innerkits/native/)
文件名功能描述
usb_srv_client.h/cppUSB服务客户端,提供C++ API
usb_device.hUSB设备数据结构定义
usb_config.hUSB配置数据结构
usb_interface.hUSB接口数据结构
usb_endpoint.hUSB端点数据结构
usb_device_pipe.hUSB设备管道数据结构
usb_port.hUSB端口数据结构
usb_request.hUSB请求数据结构
usb_accessory.hUSB配件数据结构
iusb_srv.hUSB服务接口定义
usb_interface_type.h接口类型定义
2.1.3 IDL接口文件 (interfaces/innerkits/)
文件名功能描述
IUsbServer.idlUSB服务IPC接口定义
UsbServerTypes.idl服务类型定义
2.1.4 工具类文件 (utils/native/)
文件名功能描述
usb_common.h通用常量和宏定义
usb_errors.h错误码定义
hilog_wrapper.h日志封装

2.2 类、结构体、函数与方法

2.2.1 核心类
UsbService 类
classUsbService:publicSystemAbility,publicUsbServerStub{DECLARE_SYSTEM_ABILITY(UsbService)DECLARE_DELAYED_SP_SINGLETON(UsbService);public:// 生命周期管理voidOnStart()override;voidOnStop()override;// Host功能接口int32_tOpenDevice(uint8_tbusNum,uint8_tdevAddr);int32_tClose(uint8_tbusNum,uint8_tdevAddr);int32_tGetDevices(std::vector<UsbDevice>&deviceList);int32_tClaimInterface(uint8_tbusNum,uint8_tdevAddr,uint8_tinterfaceid,uint8_tforce);int32_tReleaseInterface(uint8_tbusNum,uint8_tdevAddr,uint8_tinterfaceid);int32_tBulkTransferRead(...);int32_tBulkTransferWrite(...);int32_tControlTransfer(...);// Device功能接口int32_tGetCurrentFunctions(int32_t&funcs);int32_tSetCurrentFunctions(int32_tfuncs);// Port功能接口int32_tGetPorts(std::vector<UsbPort>&ports);int32_tSetPortRole(int32_tportId,int32_tpowerRole,int32_tdataRole);// 权限管理接口boolHasRight(conststd::string&deviceName);int32_tRequestRight(conststd::string&deviceName);int32_tRemoveRight(conststd::string&deviceName);// Serial功能接口int32_tSerialOpen(int32_tportId,constsptr<IRemoteObject>&serialRemote);int32_tSerialClose(int32_tportId);int32_tSerialRead(...);int32_tSerialWrite(...);private:std::shared_ptr<UsbHostManager>usbHostManager_;std::shared_ptr<UsbDeviceManager>usbDeviceManager_;std::shared_ptr<UsbPortManager>usbPortManager_;std::shared_ptr<UsbRightManager>usbRightManager_;std::shared_ptr<UsbAccessoryManager>usbAccessoryManager_;std::shared_ptr<SERIAL::SerialManager>usbSerialManager_;sptr<HDI::Usb::V1_2::IUsbInterface>usbd_;};
UsbHostManager 类
classUsbHostManager{public:explicitUsbHostManager(SystemAbility*systemAbility);~UsbHostManager();// 设备管理voidGetDevices(MAP_STR_DEVICE&devices);boolAddDevice(UsbDevice*dev);boolDelDevice(uint8_tbusNum,uint8_tdevNum);// 设备操作int32_tOpenDevice(uint8_tbusNum,uint8_tdevAddr);int32_tClose(uint8_tbusNum,uint8_tdevAddr);int32_tResetDevice(uint8_tbusNum,uint8_tdevAddr);// 接口操作int32_tClaimInterface(uint8_tbusNum,uint8_tdevAddr,uint8_tinterfaceid,uint8_tforce);int32_tReleaseInterface(uint8_tbusNum,uint8_tdevAddr,uint8_tinterface);int32_tSetInterface(uint8_tbusNum,uint8_tdevAddr,uint8_tinterfaceid,uint8_taltIndex);// 数据传输int32_tBulkTransferRead(...);int32_tBulkTransferWrite(...);int32_tControlTransfer(...);int32_tRequestQueue(...);int32_tRequestWait(...);// 策略执行voidExecuteStrategy(UsbDevice*devInfo);int32_tManageGlobalInterface(booldisable);int32_tManageDevice(int32_tvendorId,int32_tproductId,booldisable);private:MAP_STR_DEVICE devices_;SystemAbility*systemAbility_;std::mutex mutex_;sptr<HDI::Usb::V1_2::IUsbInterface>usbd_;};
UsbDeviceManager 类
classUsbDeviceManager{public:UsbDeviceManager();int32_tInit();// Function管理staticuint32_tConvertFromString(std::string_view funcs);staticstd::stringConvertToString(uint32_tfunc);staticboolIsSettableFunctions(int32_tfuncs);voidUpdateFunctions(int32_tfunc);int32_tGetCurrentFunctions();int32_tGetCurrentFunctions(int32_t&funcs);int32_tSetCurrentFunctions(int32_tfuncs);// 事件处理voidHandleEvent(int32_tstatus);voidSetPhyConnectState(boolphyConnect);boolIsGadgetConnected(void);// 调试接口voidDump(int32_tfd,conststd::vector<std::string>&args);private:int32_tcurrentFunctions_;boolconnected_;boolgadgetConnected_;sptr<HDI::Usb::V1_0::IUsbInterface>usbd_;std::mutex functionMutex_;};
UsbPortManager 类
classUsbPortManager{public:UsbPortManager();~UsbPortManager();voidInit();// 端口查询int32_tGetPorts(std::vector<UsbPort>&ports);int32_tGetSupportedModes(int32_tportId,int32_t&supportedModes);int32_tQueryPort();// 端口设置int32_tSetPortRole(int32_tportId,int32_tpowerRole,int32_tdataRole);voidUpdatePort(int32_tportId,int32_tpowerRole,int32_tdataRole,int32_tmode);voidAddPort(UsbPort&port);voidRemovePort(int32_tportId);private:std::mutex mutex_;std::map<int32_t,UsbPort>portMap_;std::map<int32_t,int32_t>supportedModeMap_;sptr<HDI::Usb::V1_0::IUsbInterface>usbd_;};
UsbRightManager 类
classUsbRightManager{public:int32_tInit();// 权限查询boolHasRight(conststd::string&deviceName,conststd::string&bundleName,conststd::string&tokenId,constint32_t&userId);// 权限申请int32_tRequestRight(conststd::string&busDev,conststd::string&deviceName,conststd::string&bundleName,conststd::string&tokenId,constint32_t&userId);// 权限管理boolAddDeviceRight(conststd::string&deviceName,conststd::string&bundleName,conststd::string&tokenId,constint32_t&userId);boolRemoveDeviceRight(conststd::string&deviceName,conststd::string&bundleName,conststd::string&tokenId,constint32_t&userId);int32_tCancelDeviceRight(...);boolRemoveDeviceAllRight(conststd::string&deviceName);// 权限清理int32_tCleanUpRightExpired(std::vector<std::string>&devices);staticint32_tCleanUpRightUserDeleted(int32_t&totalUsers,int32_t&deleteUsers);staticint32_tCleanUpRightAppUninstalled(int32_tuid,conststd::string&bundleName);// 权限校验boolIsSystemAppOrSa();boolVerifyPermission();int32_tHasSetFuncRight(int32_tfunctions);private:std::mutex dialogRunning_;sptr<UsbAbilityConn>usbAbilityConn_;};
2.2.2 核心数据结构
UsbDevice 结构
classUsbDevice:publicParcelable{public:// 构造函数UsbDevice(std::string name,std::string manufacturerName,std::string productName,std::string version,uint8_tdevAddr,uint8_tbusNum,int32_tvendorId,int32_tproductId,int32_tbaseClass,int32_tsubClass,int32_tprotocol,std::vector<USBConfig>configs);// 序列化接口boolMarshalling(Parcel&parcel)constoverride;staticUsbDevice*Unmarshalling(Parcel&data);// 属性访问器conststd::string&GetName()const;conststd::string&GetManufacturerName()const;conststd::string&GetProductName()const;int32_tGetVendorId()const;int32_tGetProductId()const;int32_tGetClass()const;uint8_tGetBusNum()const;uint8_tGetDevAddr()const;std::vector<USBConfig>&GetConfigs();private:std::string name_;std::string manufacturerName_;std::string productName_;std::string version_;std::string serial_;uint8_tdevAddr_;uint8_tbusNum_;int32_tvendorId_;int32_tproductId_;int32_tbaseClass_;int32_tsubClass_;int32_tprotocol_;std::vector<USBConfig>configs_;};
UsbPort 结构
structUsbPortStatus{int32_tcurrentMode;// 当前模式int32_tcurrentPowerRole;// 当前电源角色int32_tcurrentDataRole;// 当前数据角色};structUsbPort:publicParcelable{int32_tid;// 端口IDint32_tsupportedModes;// 支持的模式UsbPortStatus usbPortStatus;// 端口状态boolMarshalling(Parcel&parcel)constoverride;staticUsbPort*Unmarshalling(Parcel&data);};
错误码枚举
enumUsbErrCode{UEC_OK=0,// 接口层错误UEC_INTERFACE_NO_MEMORY,UEC_INTERFACE_INVALID_OPERATION,UEC_INTERFACE_INVALID_VALUE,UEC_INTERFACE_PERMISSION_DENIED,// 服务层错误UEC_SERVICE_NO_MEMORY,UEC_SERVICE_INVALID_OPERATION,UEC_SERVICE_INVALID_VALUE,UEC_SERVICE_PERMISSION_DENIED,UEC_SERVICE_PERMISSION_DENIED_SYSAPI,// 串口错误UEC_SERIAL_PORT_REPEAT_OPEN,UEC_SERIAL_PORT_REPEAT_CLOSE,UEC_SERIAL_PORT_NOT_OPEN,UEC_SERIAL_IO_EXCEPTION,};

2.3 类图

聚合
聚合
聚合
聚合
聚合
聚合
关联
使用
使用
使用
UsbService
-shared_ptr<UsbHostManager> usbHostManager_
-shared_ptr<UsbDeviceManager> usbDeviceManager_
-shared_ptr<UsbPortManager> usbPortManager_
-shared_ptr<UsbRightManager> usbRightManager_
-shared_ptr<UsbAccessoryManager> usbAccessoryManager_
-shared_ptr<SerialManager> usbSerialManager_
-sptr<IUsbInterface> usbd_
+OnStart() : void
+OnStop() : void
+OpenDevice() : int32_t
+Close() : int32_t
+GetDevices() : int32_t
+BulkTransferRead() : int32_t
+ControlTransfer() : int32_t
UsbHostManager
-MAP_STR_DEVICE devices_
-sptr<IUsbInterface> usbd_
-mutex mutex_
+OpenDevice() : int32_t
+Close() : int32_t
+BulkTransfer() : int32_t
+AddDevice() : bool
+DelDevice() : bool
UsbDeviceManager
-int32_t currentFuncs_
-bool connected_
-sptr<IUsbInterface> usbd_
+GetFunctions() : int32_t
+SetFunctions() : int32_t
+HandleEvent() : void
UsbPortManager
-map portMap_
-sptr<IUsbInterface> usbd_
+GetPorts() : int32_t
+SetPortRole() : int32_t
+UpdatePort() : void
UsbRightManager
-mutex dialogRunning_
-sptr<UsbAbilityConn> usbAbilityConn_
+HasRight() : bool
+RequestRight() : int32_t
+AddDeviceRight() : bool
UsbAccessoryManager
-USBAccessory accessory_
-int32_t accStatus_
+HandleEvent() : void
+OpenAccessory() : int32_t
+CloseAccessory() : int32_t
SerialManager
-map portTokenMap_
-sptr<ISerialInterface> serial_
+SerialOpen() : int32_t
+SerialClose() : int32_t
+SerialRead() : int32_t
UsbSrvClient
-sptr<IUsbServer> proxy_
-sptr<DeathRecipient> deathRecipient_
-mutex mutex_
+GetInstance() : UsbSrvClient
+OpenDevice() : int32_t
+GetDevices() : int32_t
+HasRight() : bool
+RequestRight() : int32_t
+BulkTransfer() : int32_t
UsbDevice
-string name_
-int32_t vendorId_
-int32_t productId_
-vector<USBConfig> configs_
+Marshalling() : bool
+Unmarshalling()
UsbPort
+int32_t id
+int32_t supportedModes
+UsbPortStatus usbPortStatus
+Marshalling() : bool
+Unmarshalling()
USBConfig
-int32_t id_
-uint32_t attributes_
-vector interfaces_
+Marshalling() : bool
+Unmarshalling()

2.4 模块内部依赖框图

HAL Interface
UsbService (核心协调器)
Manager 层
Helper/Utility 层
Subscriber/Callback 层
IUsbInterface
ISerialInterface
IUsbdSubscriber
UsbServiceSubscriber
UsbBulkCallbackImpl
UsbTransferCallbackImpl
UsbRightDbHelper
UsbRightDatabase
UsbDescriptorParser
UsbTimerWraper
UsbReportSysEvent
UsbHostManager
UsbDeviceManager
UsbPortManager
UsbRightManager
UsbAccessoryManager
SerialManager

3. 模块间交互

3.1 交互描述

3.1.1 与HAL层的交互

USB Manager 通过 HDI (Hardware Device Interface) 与 USB HAL 层进行交互:

接口版本功能
IUsbInterfaceV1_2USB主要功能接口,包括设备操作、数据传输等
ISerialInterfaceV1_0串口功能接口
IUsbdSubscriberV1_0USB事件订阅接口
IUsbdBulkCallbackV1_0批量传输回调接口
3.1.2 与系统服务的交互
系统服务交互方式功能描述
SAMgrSystemAbility注册注册USB服务为系统能力
AccessTokenAPI调用权限校验、Token信息获取
BundleMgrIPC调用获取应用包信息、安装/卸载监听
CommonEvent事件发布发布USB设备插拔事件
DataShare数据访问权限数据持久化存储
AbilityMgr能力连接启动权限申请对话框
3.1.3 异步处理机制
异步事件处理流程
事件通知
处理请求
广播事件
UsbSubscriber
USB HAL
UsbService
HostManager
DeviceManager
PortManager
CommonEvent Service
应用层接收事件
3.1.4 多线程处理

USB Manager 使用以下多线程机制:

  1. 主线程: 处理IPC请求
  2. 事件处理线程: 处理HAL层事件回调
  3. 定时器线程: 处理超时和延迟任务
  4. 回调线程: 处理异步传输回调
// 线程安全保护示例classUsbService{private:std::mutex mutex_;// 主互斥锁std::mutex serialPidVidMapMutex_;// 串口映射锁// 子管理器各自维护独立的锁// UsbHostManager::mutex_// UsbPortManager::mutex_// SerialManager::serialPortMapMutex_};

3.2 外部依赖框图

Linux Kernel
外部依赖
USB Core Driver
USB Host Controller
USB Gadget Driver
USB HAL
IUsbInterface
ISerialIntf
IUsbdSubscriber
AccessToken Service
VerifyAccess
GetTokenInfo
IsSystemApp
BundleMgr Service
GetBundleInfo
GetAppName
CommonEvent Service
PublishCommonEvent
DataShare Service
Query/Insert/Delete
USB Manager Service

4. 状态机转换图

4.1 状态机模型

USB Manager 包含多个状态机,分别管理不同的功能模块:

  1. USB Service 状态机: 管理服务生命周期
  2. USB Device 状态机: 管理Device模式连接状态
  3. USB Accessory 状态机: 管理配件模式状态
  4. USB Port 状态机: 管理端口角色状态

4.2 状态机树图

USB Manager 状态机层次结构
USB Manager
UsbService 状态机
UNINITIALIZED
未初始化
INITIALIZING
初始化中
READY
就绪
STOPPING
停止中
UsbDevice 状态机
DISCONNECTED
未连接
CONNECTED
已连接
CONFIGURING
配置中
FUNCTION_NONE
FUNCTION_HDC
FUNCTION_MTP
FUNCTION_PTP
FUNCTION_RNDIS
UsbAccessory 状态机
ACC_NONE
无配件
ACC_CONFIGURING
配置中
ACC_START
已启动
ACC_SEND
发送中
ACC_STOP
已停止
UsbPort 状态机
MODE_NONE
无模式
MODE_HOST
主机模式
MODE_DEVICE
设备模式
MODE_DRP
双角色
POWER_SOURCE
DATA_HOST
POWER_SINK
DATA_DEVICE

4.3 状态机切换规则

4.3.1 UsbService 状态切换
当前状态触发事件目标状态条件
UNINITIALIZEDOnStart()INITIALIZING系统启动
INITIALIZINGInit完成READYHAL初始化成功
INITIALIZINGInit失败UNINITIALIZEDHAL初始化失败
READYOnStop()STOPPING系统关闭
READYUnloadSelf()STOPPING空闲超时
STOPPING清理完成UNINITIALIZED-
4.3.2 UsbDevice 状态切换
当前状态触发事件目标状态条件
DISCONNECTEDUSB_DEVICE_ATTACHEDCONNECTED物理连接建立
CONNECTEDUSB_DEVICE_DETACHEDDISCONNECTED物理连接断开
CONNECTEDSetCurrentFunctions()CONFIGURING切换功能
CONFIGURING配置成功CONNECTED-
CONFIGURING配置失败CONNECTED恢复原功能
4.3.3 UsbAccessory 状态切换
当前状态触发事件目标状态条件
ACC_NONEAccessory连接ACC_CONFIGURING检测到配件
ACC_CONFIGURING配置完成ACC_START配置成功
ACC_START开始传输ACC_SEND打开配件
ACC_SEND关闭配件ACC_STOP传输结束
ACC_STOP配件断开ACC_NONE物理断开
任意状态配件断开ACC_NONE异常断开

4.4 状态机转换图

UsbService 状态转换图
OnStart()
Init成功
Init失败
OnStop() / UnloadSelf()
清理完成
UNINITIALIZED
INITIALIZING
READY
STOPPING
UsbDevice 状态转换图
USB_DEVICE_ATTACHED
USB_DEVICE_DETACHED
SetCurrentFunctions()
配置成功
配置失败(恢复原功能)
DISCONNECTED
CONNECTED
切换HDC
切换MTP
切换PTP
切换RNDIS
切换NONE
切换NONE
切换NONE
切换NONE
FUNC_NONE
FUNC_HDC
FUNC_MTP
FUNC_PTP
FUNC_RNDIS
CONFIGURING
UsbAccessory 状态转换图
检测到配件
配置完成
OpenAccessory()
CloseAccessory()
配件断开
配件断开(异常)
配件断开(异常)
配件断开(异常)
ACC_NONE
ACC_CONFIGURING
ACC_START
ACC_SEND
ACC_STOP
UsbPort 状态转换图
支持双角色
SetPortRole(HOST)
SetPortRole(DEVICE)
SetPortRole(DEVICE)
SetPortRole(HOST)
协商为HOST
协商为DEVICE
MODE_NONE
MODE_HOST
POWER_SOURCE
DATA_HOST
MODE_DEVICE
POWER_SINK
DATA_DEVICE
MODE_DRP

5. 接口设计

5.1 公共接口

5.1.1 Host 功能接口
接口名称功能描述参数返回值异常处理
OpenDevice打开USB设备busNum: 总线号
devAddr: 设备地址
int32_t: 错误码UEC_SERVICE_INVALID_VALUE: 参数无效
UEC_SERVICE_PERMISSION_DENIED: 无权限
Close关闭USB设备busNum: 总线号
devAddr: 设备地址
int32_t: 错误码UEC_SERVICE_INVALID_VALUE: 设备未打开
GetDevices获取设备列表deviceList: 输出设备列表int32_t: 错误码-
ClaimInterface声明接口busNum, devAddr, interfaceid, forceint32_t: 错误码UEC_SERVICE_INVALID_VALUE: 接口不存在
ReleaseInterface释放接口busNum, devAddr, interfaceidint32_t: 错误码-
BulkTransferRead批量读取busNum, devAddr, ep, bufferData, timeoutint32_t: 错误码UEC_SERVICE_TIMED_OUT: 超时
BulkTransferWrite批量写入busNum, devAddr, ep, bufferData, timeoutint32_t: 错误码UEC_SERVICE_TIMED_OUT: 超时
ControlTransfer控制传输busNum, devAddr, ctrlParams, bufferDataint32_t: 错误码-
5.1.2 Device 功能接口
接口名称功能描述参数返回值异常处理
GetCurrentFunctions获取当前功能funcs: 输出功能位域int32_t: 错误码-
SetCurrentFunctions设置当前功能funcs: 功能位域int32_t: 错误码UEC_SERVICE_PERMISSION_DENIED: 无权限
UEC_SERVICE_PERMISSION_CHECK_HDC: HDC权限检查失败
UsbFunctionsFromString字符串转功能funcs: 功能字符串int32_t: 功能位域-
UsbFunctionsToString功能转字符串funcs: 功能位域string: 功能字符串-
5.1.3 Port 功能接口
接口名称功能描述参数返回值异常处理
GetPorts获取端口列表ports: 输出端口列表int32_t: 错误码-
GetSupportedModes获取支持模式portId, supportedModesint32_t: 错误码UEC_SERVICE_INVALID_VALUE: 端口不存在
SetPortRole设置端口角色portId, powerRole, dataRoleint32_t: 错误码UEC_SERVICE_NOT_SUPPORT_SWITCH_PORT: 不支持切换
5.1.4 权限管理接口
接口名称功能描述参数返回值异常处理
HasRight检查权限deviceNamebool: 是否有权限-
RequestRight申请权限deviceNameint32_t: 错误码用户拒绝返回失败
RemoveRight移除权限deviceNameint32_t: 错误码-
AddRight添加权限bundleName, deviceNameint32_t: 错误码UEC_SERVICE_PERMISSION_DENIED_SYSAPI: 非系统应用
5.1.5 Serial 功能接口
接口名称功能描述参数返回值异常处理
SerialOpen打开串口portId, serialRemoteint32_t: 错误码UEC_SERIAL_PORT_REPEAT_OPEN: 重复打开
UEC_SERIAL_PORT_NOT_EXIST: 端口不存在
SerialClose关闭串口portIdint32_t: 错误码UEC_SERIAL_PORT_NOT_OPEN: 未打开
SerialRead串口读取portId, data, size, actualSize, timeoutint32_t: 错误码UEC_SERIAL_IO_EXCEPTION: IO异常
SerialWrite串口写入portId, data, size, actualSize, timeoutint32_t: 错误码UEC_SERIAL_IO_EXCEPTION: IO异常
SerialGetAttribute获取属性portId, attributeint32_t: 错误码-
SerialSetAttribute设置属性portId, attributeint32_t: 错误码-
SerialGetPortList获取端口列表serialPortListint32_t: 错误码-

5.2 数据交换接口

5.2.1 IPC 接口定义 (IUsbServer.idl)
interface OHOS.USB.IUsbServer { // Host功能 [macrodef USB_MANAGER_FEATURE_HOST] void GetDevices([out]UsbDevice[] deviceList); [macrodef USB_MANAGER_FEATURE_HOST] void OpenDevice([in]unsigned char busNum, [in]unsigned char devAddr); [macrodef USB_MANAGER_FEATURE_HOST] void Close([in]unsigned char busNum, [in]unsigned char devAddr); [macrodef USB_MANAGER_FEATURE_HOST] void BulkTransferRead([in]unsigned char busNum, [in]unsigned char devAddr, [in]USBEndpoint ep, [out]UsbBulkTransData buffData, [in]int timeOut); [macrodef USB_MANAGER_FEATURE_HOST] void ControlTransfer([in]unsigned char busNum, [in]unsigned char devAddr, [in]UsbCtlSetUp ctrlParams, [inout]unsigned char[] bufferData); // Device功能 [macrodef USB_MANAGER_FEATURE_DEVICE] void GetCurrentFunctions([out] int funcs); [macrodef USB_MANAGER_FEATURE_DEVICE] void SetCurrentFunctions([in] int funcs); // Port功能 [macrodef USB_MANAGER_FEATURE_PORT] void GetPorts([out]UsbPort[] ports); [macrodef USB_MANAGER_FEATURE_PORT] void SetPortRole([in] int portId, [in] int powerRole, [in] int dataRole); // Serial功能 void SerialOpen([in] int portId, [in] IRemoteObject serialRemote); void SerialClose([in] int portId); void SerialRead([in] int portId, [out]unsigned char[] buffData, [in]unsigned int size, [out]unsigned int actualSize, [in]unsigned int timeout); void SerialWrite([in] int portId, [in]unsigned char[] buffData, [in]unsigned int size, [out]unsigned int actualSize, [in]unsigned int timeout); }
5.2.2 数据结构序列化

所有跨进程传输的数据结构都实现了Parcelable接口:

// UsbDevice 序列化boolUsbDevice::Marshalling(Parcel&parcel)const{WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Uint8,parcel,this->busNum_);WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Uint8,parcel,this->devAddr_);WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Int32,parcel,this->vendorId_);WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Int32,parcel,this->productId_);// ... 其他字段returntrue;}// UsbPort 序列化boolUsbPort::Marshalling(Parcel&parcel)const{WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Int32,parcel,this->id);WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Int32,parcel,this->supportedModes);WRITE_PARCEL_AND_RETURN_FALSE_WHEN_FAIL(Int32,parcel,this->usbPortStatus.currentMode);// ... 其他字段returntrue;}

5.3 接口调用时序图

5.3.1 设备打开与数据传输时序
应用程序UsbSrvClientUsbServiceUSB HALGetDevices()GetDevices()GetDevices()deviceListdeviceListdeviceListRequestRight(deviceName)RequestRight()ShowDialog()用户确认OKtrueOpenDevice(device)OpenDevice()OpenDevice()OKOKpipeClaimInterface(pipe, interface)ClaimInterface()ClaimInterface()OKOKOKBulkTransfer(pipe, endpoint, data)BulkTransfer()BulkTransfer()datadatadataClose(pipe)Close()Close()OKOKOK应用程序UsbSrvClientUsbServiceUSB HAL
5.3.2 设备插拔事件处理时序
USB HALUsbSrvSubscriberUsbServiceUsbHostManager应用程序DeviceEvent(ATTACH)DeviceEvent()AddDevice()解析描述符OKPublishEvent(USB_ATTACHED)CommonEvent: USB_ATTACHEDDeviceEvent(DETACH)DeviceEvent()DelDevice()OKPublishEvent(USB_DETACHED)CommonEvent: USB_DETACHEDUSB HALUsbSrvSubscriberUsbServiceUsbHostManager应用程序
5.3.3 Function切换时序
应用程序UsbSrvClientUsbServiceUsbDeviceManagerUSB HALSetCurrentFunctions(MTP)SetCurrentFunctions()CheckPermission()权限检查OKSetCurrentFunctions()ValidateFunc()功能验证OKSetCurrentFunctions()OKUpdateFunctions()BroadcastEvent()OKOKOK应用程序UsbSrvClientUsbServiceUsbDeviceManagerUSB HAL

附录

A. 错误码说明

错误码说明
UEC_OK0操作成功
UEC_SERVICE_INVALID_VALUE0x2710066无效参数
UEC_SERVICE_PERMISSION_DENIED0x2710068权限拒绝
UEC_SERVICE_PERMISSION_DENIED_SYSAPI0x271007B非系统应用调用系统API
UEC_SERVICE_NOT_SUPPORT_SWITCH_PORT0x271007D不支持端口切换
UEC_SERIAL_PORT_NOT_EXIST0x2710092串口不存在

B. 功能位域定义

功能位值说明
FUNCTION_NONE0无功能
FUNCTION_ACM1ACM串口
FUNCTION_ECM2ECM网络
FUNCTION_HDC4HDC调试
FUNCTION_MTP8MTP文件传输
FUNCTION_PTP16PTP图片传输
FUNCTION_RNDIS32RNDIS网络
FUNCTION_NCM64NCM网络
FUNCTION_STORAGE512大容量存储

C. 端口角色定义

角色类型说明
POWER_ROLE_NONE0无电源角色
POWER_ROLE_SOURCE1供电方
POWER_ROLE_SINK2受电方
DATA_ROLE_NONE0无数据角色
DATA_ROLE_HOST1数据主机
DATA_ROLE_DEVICE2数据设备
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 2:07:36

TensorRT-LLM快速入门与核心特性解析

TensorRT-LLM&#xff1a;打通大模型高效推理的“任督二脉” 在当前的大模型浪潮中&#xff0c;一个700亿参数的LLaMA-2模型跑一次推理要花多少钱&#xff1f;如果你还在用原生PyTorch部署&#xff0c;答案可能是——每千次请求几十美分。而换上TensorRT-LLM后&#xff0c;这个…

作者头像 李华
网站建设 2026/4/23 13:37:14

电脑卡到想砸了?别急!3分钟让老机器“健步如飞”的魔法操作

前言有没有那么一瞬间&#xff0c;你想和你的电脑“同归于尽”&#xff1f;打开文件&#xff0c;转圈&#xff1b;点开网页&#xff0c;转圈&#xff1b;甚至移动鼠标&#xff0c;都像在粘稠的糖浆里划动……开会前紧急修改PPT&#xff0c;它给你卡成幻灯片。这里玄子给大家一套…

作者头像 李华
网站建设 2026/4/25 19:17:11

PaddlePaddle深度学习平台实战:从git下载到模型训练全流程解析

PaddlePaddle深度学习平台实战&#xff1a;从环境搭建到模型训练全流程解析 在AI项目落地的过程中&#xff0c;一个常见的痛点是&#xff1a;研究阶段的模型代码到了生产环境却“跑不起来”——依赖冲突、CUDA版本不匹配、Python包缺失……这些问题让不少开发者苦不堪言。特别是…

作者头像 李华
网站建设 2026/4/17 19:05:05

FLUX.1-dev微调实战:从环境到生成

FLUX.1-dev微调实战&#xff1a;从环境部署到图像生成 在AIGC领域&#xff0c;文生图模型的迭代速度令人目不暇接。而当FLUX.1-dev横空出世时&#xff0c;许多开发者眼前一亮——它不仅拥有高达120亿参数的Flow Transformer架构&#xff0c;在细节还原、构图逻辑和提示词理解上…

作者头像 李华
网站建设 2026/4/25 2:27:49

【WinForm】 旧项目维护问题总结

问题一&#xff1a;DataGridViewComboBoxColumn多次点击触发下拉问题修正 如果在没有其他事件重复触发的情况下&#xff0c;需要把DataGridView的EditMode修改为EditOnEnter就可以了。

作者头像 李华
网站建设 2026/4/29 2:44:05

Java九个正面和背面

任务描述 本关任务&#xff1a;编写一个程序&#xff0c;输入一个整数&#xff0c;输出对应的九枚硬币状态。相关知识 游戏规则 一个 3 x 3 的矩阵中放置了 9 个硬币&#xff0c;这些硬币有些面向上&#xff0c;有些面向 下。可以使用 3 x 3 的矩阵中的 0 (正面&#xff09;或 …

作者头像 李华