USB Manager 模块
目录
- 模块概述
- [1.1 功能与目标](#1.1 功能与目标)
- [1.2 系统位置](#1.2 系统位置)
- [1.3 设计思路与模式](#1.3 设计思路与模式)
- [1.4 系统框图](#1.4 系统框图)
- 模块结构
- [2.1 源文件与头文件](#2.1 源文件与头文件)
- [2.2 类、结构体、函数与方法](#2.2 类、结构体、函数与方法)
- [2.3 类图](#2.3 类图)
- [2.4 模块内部依赖框图](#2.4 模块内部依赖框图)
- 模块间交互
- [3.1 交互描述](#3.1 交互描述)
- [3.2 外部依赖框图](#3.2 外部依赖框图)
- 状态机转换图
- [4.1 状态机模型](#4.1 状态机模型)
- [4.2 状态机树图](#4.2 状态机树图)
- [4.3 状态机切换规则](#4.3 状态机切换规则)
- [4.4 状态机转换图](#4.4 状态机转换图)
- 接口设计
- [5.1 公共接口](#5.1 公共接口)
- [5.2 数据交换接口](#5.2 数据交换接口)
- [5.3 接口调用时序图](#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设备访问权限控制、权限申请与撤销、权限数据库管理 |
设计目标
- 统一管理: 提供统一的USB设备管理接口,屏蔽底层HAL差异
- 权限控制: 实现细粒度的USB设备访问权限控制
- 事件驱动: 支持USB设备热插拔事件的实时通知
- 多模式支持: 同时支持Host模式和Device模式
- 可扩展性: 模块化设计,便于功能扩展
使用场景
- 移动设备连接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 设计思路与模式
设计思路
-
分层架构设计
- API层:提供NAPI接口供JS/TS应用调用
- Service层:实现核心业务逻辑
- HAL层:封装硬件抽象层接口
-
模块化设计
- 按功能划分为Host、Device、Port、Serial等子管理器
- 各子模块职责单一,便于维护和扩展
-
事件驱动机制
- 通过订阅者模式接收HAL层的设备事件
- 使用公共事件服务广播设备状态变化
-
权限控制机制
- 基于数据库的权限持久化存储
- 支持临时权限和永久权限
- 集成系统权限框架
设计模式
| 设计模式 | 应用场景 | 说明 |
|---|---|---|
| 单例模式 | 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/cpp | USB服务主类,继承SystemAbility,协调各子管理器 |
| usb_host_manager.h/cpp | USB Host模式管理器,处理外设连接和数据传输 |
| usb_device_manager.h/cpp | USB Device模式管理器,处理function切换 |
| usb_port_manager.h/cpp | USB端口管理器,处理Host/Device模式切换 |
| usb_right_manager.h/cpp | USB权限管理器,处理设备访问权限 |
| usb_accessory_manager.h/cpp | USB配件模式管理器 |
| serial_manager.h/cpp | 串口管理器,处理USB串口设备 |
| usb_right_database.h/cpp | 权限数据库操作封装 |
| usb_right_db_helper.h/cpp | 权限数据库辅助类 |
| usb_descriptor_parser.h/cpp | USB描述符解析器 |
| usb_service_subscriber.h/cpp | HAL层事件订阅者 |
| usb_connection_notifier.h/cpp | 连接状态通知器 |
| usb_function_switch_window.h/cpp | Function切换窗口管理 |
| 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/cpp | USB服务客户端,提供C++ API |
| usb_device.h | USB设备数据结构定义 |
| usb_config.h | USB配置数据结构 |
| usb_interface.h | USB接口数据结构 |
| usb_endpoint.h | USB端点数据结构 |
| usb_device_pipe.h | USB设备管道数据结构 |
| usb_port.h | USB端口数据结构 |
| usb_request.h | USB请求数据结构 |
| usb_accessory.h | USB配件数据结构 |
| iusb_srv.h | USB服务接口定义 |
| usb_interface_type.h | 接口类型定义 |
2.1.3 IDL接口文件 (interfaces/innerkits/)
| 文件名 | 功能描述 |
|---|---|
| IUsbServer.idl | USB服务IPC接口定义 |
| UsbServerTypes.idl | 服务类型定义 |
2.1.4 工具类文件 (utils/native/)
| 文件名 | 功能描述 |
|---|---|
| usb_common.h | 通用常量和宏定义 |
| usb_errors.h | 错误码定义 |
| hilog_wrapper.h | 日志封装 |
2.2 类、结构体、函数与方法
2.2.1 核心类
UsbService 类
cpp
class UsbService : public SystemAbility, public UsbServerStub {
DECLARE_SYSTEM_ABILITY(UsbService)
DECLARE_DELAYED_SP_SINGLETON(UsbService);
public:
// 生命周期管理
void OnStart() override;
void OnStop() override;
// Host功能接口
int32_t OpenDevice(uint8_t busNum, uint8_t devAddr);
int32_t Close(uint8_t busNum, uint8_t devAddr);
int32_t GetDevices(std::vector<UsbDevice> &deviceList);
int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t force);
int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid);
int32_t BulkTransferRead(...);
int32_t BulkTransferWrite(...);
int32_t ControlTransfer(...);
// Device功能接口
int32_t GetCurrentFunctions(int32_t &funcs);
int32_t SetCurrentFunctions(int32_t funcs);
// Port功能接口
int32_t GetPorts(std::vector<UsbPort> &ports);
int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole);
// 权限管理接口
bool HasRight(const std::string &deviceName);
int32_t RequestRight(const std::string &deviceName);
int32_t RemoveRight(const std::string &deviceName);
// Serial功能接口
int32_t SerialOpen(int32_t portId, const sptr<IRemoteObject> &serialRemote);
int32_t SerialClose(int32_t portId);
int32_t SerialRead(...);
int32_t SerialWrite(...);
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 类
cpp
class UsbHostManager {
public:
explicit UsbHostManager(SystemAbility *systemAbility);
~UsbHostManager();
// 设备管理
void GetDevices(MAP_STR_DEVICE &devices);
bool AddDevice(UsbDevice *dev);
bool DelDevice(uint8_t busNum, uint8_t devNum);
// 设备操作
int32_t OpenDevice(uint8_t busNum, uint8_t devAddr);
int32_t Close(uint8_t busNum, uint8_t devAddr);
int32_t ResetDevice(uint8_t busNum, uint8_t devAddr);
// 接口操作
int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t force);
int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface);
int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex);
// 数据传输
int32_t BulkTransferRead(...);
int32_t BulkTransferWrite(...);
int32_t ControlTransfer(...);
int32_t RequestQueue(...);
int32_t RequestWait(...);
// 策略执行
void ExecuteStrategy(UsbDevice *devInfo);
int32_t ManageGlobalInterface(bool disable);
int32_t ManageDevice(int32_t vendorId, int32_t productId, bool disable);
private:
MAP_STR_DEVICE devices_;
SystemAbility *systemAbility_;
std::mutex mutex_;
sptr<HDI::Usb::V1_2::IUsbInterface> usbd_;
};
UsbDeviceManager 类
cpp
class UsbDeviceManager {
public:
UsbDeviceManager();
int32_t Init();
// Function管理
static uint32_t ConvertFromString(std::string_view funcs);
static std::string ConvertToString(uint32_t func);
static bool IsSettableFunctions(int32_t funcs);
void UpdateFunctions(int32_t func);
int32_t GetCurrentFunctions();
int32_t GetCurrentFunctions(int32_t& funcs);
int32_t SetCurrentFunctions(int32_t funcs);
// 事件处理
void HandleEvent(int32_t status);
void SetPhyConnectState(bool phyConnect);
bool IsGadgetConnected(void);
// 调试接口
void Dump(int32_t fd, const std::vector<std::string> &args);
private:
int32_t currentFunctions_;
bool connected_;
bool gadgetConnected_;
sptr<HDI::Usb::V1_0::IUsbInterface> usbd_;
std::mutex functionMutex_;
};
UsbPortManager 类
cpp
class UsbPortManager {
public:
UsbPortManager();
~UsbPortManager();
void Init();
// 端口查询
int32_t GetPorts(std::vector<UsbPort> &ports);
int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes);
int32_t QueryPort();
// 端口设置
int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole);
void UpdatePort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode);
void AddPort(UsbPort &port);
void RemovePort(int32_t portId);
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 类
cpp
class UsbRightManager {
public:
int32_t Init();
// 权限查询
bool HasRight(const std::string &deviceName, const std::string &bundleName,
const std::string &tokenId, const int32_t &userId);
// 权限申请
int32_t RequestRight(const std::string &busDev, const std::string &deviceName,
const std::string &bundleName, const std::string &tokenId, const int32_t &userId);
// 权限管理
bool AddDeviceRight(const std::string &deviceName, const std::string &bundleName,
const std::string &tokenId, const int32_t &userId);
bool RemoveDeviceRight(const std::string &deviceName, const std::string &bundleName,
const std::string &tokenId, const int32_t &userId);
int32_t CancelDeviceRight(...);
bool RemoveDeviceAllRight(const std::string &deviceName);
// 权限清理
int32_t CleanUpRightExpired(std::vector<std::string> &devices);
static int32_t CleanUpRightUserDeleted(int32_t &totalUsers, int32_t &deleteUsers);
static int32_t CleanUpRightAppUninstalled(int32_t uid, const std::string &bundleName);
// 权限校验
bool IsSystemAppOrSa();
bool VerifyPermission();
int32_t HasSetFuncRight(int32_t functions);
private:
std::mutex dialogRunning_;
sptr<UsbAbilityConn> usbAbilityConn_;
};
2.2.2 核心数据结构
UsbDevice 结构
cpp
class UsbDevice : public Parcelable {
public:
// 构造函数
UsbDevice(std::string name, std::string manufacturerName, std::string productName,
std::string version, uint8_t devAddr, uint8_t busNum, int32_t vendorId,
int32_t productId, int32_t baseClass, int32_t subClass, int32_t protocol,
std::vector<USBConfig> configs);
// 序列化接口
bool Marshalling(Parcel &parcel) const override;
static UsbDevice *Unmarshalling(Parcel &data);
// 属性访问器
const std::string &GetName() const;
const std::string &GetManufacturerName() const;
const std::string &GetProductName() const;
int32_t GetVendorId() const;
int32_t GetProductId() const;
int32_t GetClass() const;
uint8_t GetBusNum() const;
uint8_t GetDevAddr() const;
std::vector<USBConfig> &GetConfigs();
private:
std::string name_;
std::string manufacturerName_;
std::string productName_;
std::string version_;
std::string serial_;
uint8_t devAddr_;
uint8_t busNum_;
int32_t vendorId_;
int32_t productId_;
int32_t baseClass_;
int32_t subClass_;
int32_t protocol_;
std::vector<USBConfig> configs_;
};
UsbPort 结构
cpp
struct UsbPortStatus {
int32_t currentMode; // 当前模式
int32_t currentPowerRole; // 当前电源角色
int32_t currentDataRole; // 当前数据角色
};
struct UsbPort : public Parcelable {
int32_t id; // 端口ID
int32_t supportedModes; // 支持的模式
UsbPortStatus usbPortStatus; // 端口状态
bool Marshalling(Parcel &parcel) const override;
static UsbPort *Unmarshalling(Parcel &data);
};
错误码枚举
cpp
enum UsbErrCode {
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 层进行交互:
| 接口 | 版本 | 功能 |
|---|---|---|
| IUsbInterface | V1_2 | USB主要功能接口,包括设备操作、数据传输等 |
| ISerialInterface | V1_0 | 串口功能接口 |
| IUsbdSubscriber | V1_0 | USB事件订阅接口 |
| IUsbdBulkCallback | V1_0 | 批量传输回调接口 |
3.1.2 与系统服务的交互
| 系统服务 | 交互方式 | 功能描述 |
|---|---|---|
| SAMgr | SystemAbility注册 | 注册USB服务为系统能力 |
| AccessToken | API调用 | 权限校验、Token信息获取 |
| BundleMgr | IPC调用 | 获取应用包信息、安装/卸载监听 |
| CommonEvent | 事件发布 | 发布USB设备插拔事件 |
| DataShare | 数据访问 | 权限数据持久化存储 |
| AbilityMgr | 能力连接 | 启动权限申请对话框 |
3.1.3 异步处理机制
异步事件处理流程 事件通知 处理请求 广播事件 UsbSubscriber USB HAL UsbService HostManager DeviceManager PortManager CommonEvent Service 应用层接收事件
3.1.4 多线程处理
USB Manager 使用以下多线程机制:
- 主线程: 处理IPC请求
- 事件处理线程: 处理HAL层事件回调
- 定时器线程: 处理超时和延迟任务
- 回调线程: 处理异步传输回调
cpp
// 线程安全保护示例
class UsbService {
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 包含多个状态机,分别管理不同的功能模块:
- USB Service 状态机: 管理服务生命周期
- USB Device 状态机: 管理Device模式连接状态
- USB Accessory 状态机: 管理配件模式状态
- 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 状态切换
| 当前状态 | 触发事件 | 目标状态 | 条件 |
|---|---|---|---|
| UNINITIALIZED | OnStart() | INITIALIZING | 系统启动 |
| INITIALIZING | Init完成 | READY | HAL初始化成功 |
| INITIALIZING | Init失败 | UNINITIALIZED | HAL初始化失败 |
| READY | OnStop() | STOPPING | 系统关闭 |
| READY | UnloadSelf() | STOPPING | 空闲超时 |
| STOPPING | 清理完成 | UNINITIALIZED | - |
4.3.2 UsbDevice 状态切换
| 当前状态 | 触发事件 | 目标状态 | 条件 |
|---|---|---|---|
| DISCONNECTED | USB_DEVICE_ATTACHED | CONNECTED | 物理连接建立 |
| CONNECTED | USB_DEVICE_DETACHED | DISCONNECTED | 物理连接断开 |
| CONNECTED | SetCurrentFunctions() | CONFIGURING | 切换功能 |
| CONFIGURING | 配置成功 | CONNECTED | - |
| CONFIGURING | 配置失败 | CONNECTED | 恢复原功能 |
4.3.3 UsbAccessory 状态切换
| 当前状态 | 触发事件 | 目标状态 | 条件 |
|---|---|---|---|
| ACC_NONE | Accessory连接 | 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, force | int32_t: 错误码 | UEC_SERVICE_INVALID_VALUE: 接口不存在 |
ReleaseInterface |
释放接口 | busNum, devAddr, interfaceid | int32_t: 错误码 | - |
BulkTransferRead |
批量读取 | busNum, devAddr, ep, bufferData, timeout | int32_t: 错误码 | UEC_SERVICE_TIMED_OUT: 超时 |
BulkTransferWrite |
批量写入 | busNum, devAddr, ep, bufferData, timeout | int32_t: 错误码 | UEC_SERVICE_TIMED_OUT: 超时 |
ControlTransfer |
控制传输 | busNum, devAddr, ctrlParams, bufferData | int32_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, supportedModes | int32_t: 错误码 | UEC_SERVICE_INVALID_VALUE: 端口不存在 |
SetPortRole |
设置端口角色 | portId, powerRole, dataRole | int32_t: 错误码 | UEC_SERVICE_NOT_SUPPORT_SWITCH_PORT: 不支持切换 |
5.1.4 权限管理接口
| 接口名称 | 功能描述 | 参数 | 返回值 | 异常处理 |
|---|---|---|---|---|
HasRight |
检查权限 | deviceName | bool: 是否有权限 | - |
RequestRight |
申请权限 | deviceName | int32_t: 错误码 | 用户拒绝返回失败 |
RemoveRight |
移除权限 | deviceName | int32_t: 错误码 | - |
AddRight |
添加权限 | bundleName, deviceName | int32_t: 错误码 | UEC_SERVICE_PERMISSION_DENIED_SYSAPI: 非系统应用 |
5.1.5 Serial 功能接口
| 接口名称 | 功能描述 | 参数 | 返回值 | 异常处理 |
|---|---|---|---|---|
SerialOpen |
打开串口 | portId, serialRemote | int32_t: 错误码 | UEC_SERIAL_PORT_REPEAT_OPEN: 重复打开 UEC_SERIAL_PORT_NOT_EXIST: 端口不存在 |
SerialClose |
关闭串口 | portId | int32_t: 错误码 | UEC_SERIAL_PORT_NOT_OPEN: 未打开 |
SerialRead |
串口读取 | portId, data, size, actualSize, timeout | int32_t: 错误码 | UEC_SERIAL_IO_EXCEPTION: IO异常 |
SerialWrite |
串口写入 | portId, data, size, actualSize, timeout | int32_t: 错误码 | UEC_SERIAL_IO_EXCEPTION: IO异常 |
SerialGetAttribute |
获取属性 | portId, attribute | int32_t: 错误码 | - |
SerialSetAttribute |
设置属性 | portId, attribute | int32_t: 错误码 | - |
SerialGetPortList |
获取端口列表 | serialPortList | int32_t: 错误码 | - |
5.2 数据交换接口
5.2.1 IPC 接口定义 (IUsbServer.idl)
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 接口:
cpp
// UsbDevice 序列化
bool UsbDevice::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_);
// ... 其他字段
return true;
}
// UsbPort 序列化
bool UsbPort::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);
// ... 其他字段
return true;
}
5.3 接口调用时序图
5.3.1 设备打开与数据传输时序
应用程序 UsbSrvClient UsbService USB HAL GetDevices() GetDevices() GetDevices() deviceList deviceList deviceList RequestRight(deviceName) RequestRight() ShowDialog() 用户确认 OK true OpenDevice(device) OpenDevice() OpenDevice() OK OK pipe ClaimInterface(pipe, interface) ClaimInterface() ClaimInterface() OK OK OK BulkTransfer(pipe, endpoint, data) BulkTransfer() BulkTransfer() data data data Close(pipe) Close() Close() OK OK OK 应用程序 UsbSrvClient UsbService USB HAL
5.3.2 设备插拔事件处理时序
USB HAL UsbSrvSubscriber UsbService UsbHostManager 应用程序 DeviceEvent(ATTACH) DeviceEvent() AddDevice() 解析描述符 OK PublishEvent(USB_ATTACHED) CommonEvent: USB_ATTACHED DeviceEvent(DETACH) DeviceEvent() DelDevice() OK PublishEvent(USB_DETACHED) CommonEvent: USB_DETACHED USB HAL UsbSrvSubscriber UsbService UsbHostManager 应用程序
5.3.3 Function切换时序
应用程序 UsbSrvClient UsbService UsbDeviceManager USB HAL SetCurrentFunctions(MTP) SetCurrentFunctions() CheckPermission() 权限检查OK SetCurrentFunctions() ValidateFunc() 功能验证OK SetCurrentFunctions() OK UpdateFunctions() BroadcastEvent() OK OK OK 应用程序 UsbSrvClient UsbService UsbDeviceManager USB HAL
附录
A. 错误码说明
| 错误码 | 值 | 说明 |
|---|---|---|
| UEC_OK | 0 | 操作成功 |
| UEC_SERVICE_INVALID_VALUE | 0x2710066 | 无效参数 |
| UEC_SERVICE_PERMISSION_DENIED | 0x2710068 | 权限拒绝 |
| UEC_SERVICE_PERMISSION_DENIED_SYSAPI | 0x271007B | 非系统应用调用系统API |
| UEC_SERVICE_NOT_SUPPORT_SWITCH_PORT | 0x271007D | 不支持端口切换 |
| UEC_SERIAL_PORT_NOT_EXIST | 0x2710092 | 串口不存在 |
B. 功能位域定义
| 功能 | 位值 | 说明 |
|---|---|---|
| FUNCTION_NONE | 0 | 无功能 |
| FUNCTION_ACM | 1 | ACM串口 |
| FUNCTION_ECM | 2 | ECM网络 |
| FUNCTION_HDC | 4 | HDC调试 |
| FUNCTION_MTP | 8 | MTP文件传输 |
| FUNCTION_PTP | 16 | PTP图片传输 |
| FUNCTION_RNDIS | 32 | RNDIS网络 |
| FUNCTION_NCM | 64 | NCM网络 |
| FUNCTION_STORAGE | 512 | 大容量存储 |
C. 端口角色定义
| 角色类型 | 值 | 说明 |
|---|---|---|
| POWER_ROLE_NONE | 0 | 无电源角色 |
| POWER_ROLE_SOURCE | 1 | 供电方 |
| POWER_ROLE_SINK | 2 | 受电方 |
| DATA_ROLE_NONE | 0 | 无数据角色 |
| DATA_ROLE_HOST | 1 | 数据主机 |
| DATA_ROLE_DEVICE | 2 | 数据设备 |