湖州网站建设网站建设策划

四川晟源达科技有限公司 2026/09/09 20:00:50

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
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

网站外链建设郴州网站建设

快速体验打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容:创建一个Spring Boot项目示例,演示当出现'o

2026/06/30 10:47:22

网站建设网站阳网站建设

深度解析Rimraf:企业级文件清理架构的最佳实践【免费下载链接】rimrafA `rm -rf` util for nodejs项目地址: https://gitcod

2026/06/30 13:05:35

模板网站建设阳网站建设

还在为Python测试代码的复杂配置而烦恼吗?想要快速掌握业界最流行的测试框架吗?今天,我将带你用3小时彻底征服pytest——这个让Python测试变得轻松

2026/06/30 10:15:19

盐城网站建设哈尔滨网站建设

摘要:本文将探讨如何利用编程技术(Python及相关库)自动分析电影素材,并基于特定规则或机器学习模型智能剪辑生成具有吸引力的电影预告片。我们将

2026/06/30 13:16:35

网站建设方案书成都建设网站

快速体验打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容:开发一个针对电商网站的字体检测分析工具,重点功能:

2026/06/30 13:11:04

深圳网站建设论坛滨州网站建设

如何快速掌握Opus音频格式:新手的完整测试指南【免费下载链接】Opus格式音频测试文件下载探索Opus格式音频的魅力!本项目提供四份高质量的Opus音频测试文件ÿ

2026/06/30 11:55:28

西安网站建设公司扬中网站建设

当千亿参数模型成为行业标配,你是否还在为漫长的训练周期而焦虑?当GPU资源消耗居高不下,你是否在寻找更高效的解决方案?今天,我们将

2026/06/30 13:23:35

网站建设策划书邯郸网站建设

YOLO在无人机视觉中的应用:轻量模型+低功耗GPU方案在消费级与工业级无人机快速普及的今天,一个核心挑战日益凸显:如何让飞行器“看得清、反应快、能耗

2026/06/30 12:34:02

网站建设步骤银川网站建设

深度学习环境搭建新范式:从 PyTorch 到 GPU 加速的无缝实践在深度学习项目启动的第一天,你是否也经历过这样的场景?满怀热情地打开电脑,

2026/06/30 12:43:32

怎么建设网站烟台网站建设

导语【免费下载链接】WanVideo_comfy项目地址: https://ai.gitcode.com/hf_mirrors/Kijai/WanVideo_comfy阿里WanVideo_comfy

2026/06/30 13:18:05