USB Manager 模块
目录
- 模块概述
- 1.1 功能与目标
- 1.2 系统位置
- 1.3 设计思路与模式
- 1.4 系统框图
- 模块结构
- 2.1 源文件与头文件
- 2.2 类、结构体、函数与方法
- 2.3 类图
- 2.4 模块内部依赖框图
- 模块间交互
- 状态机转换图
- 4.1 状态机模型
- 4.2 状态机树图
- 4.3 状态机切换规则
- 4.4 状态机转换图
- 接口设计
- 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设备访问权限控制、权限申请与撤销、权限数据库管理 |
设计目标
- 统一管理: 提供统一的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 类
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 类图
2.4 模块内部依赖框图
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 异步处理机制
3.1.4 多线程处理
USB Manager 使用以下多线程机制:
- 主线程: 处理IPC请求
- 事件处理线程: 处理HAL层事件回调
- 定时器线程: 处理超时和延迟任务
- 回调线程: 处理异步传输回调
// 线程安全保护示例classUsbService{private:std::mutex mutex_;// 主互斥锁std::mutex serialPidVidMapMutex_;// 串口映射锁// 子管理器各自维护独立的锁// UsbHostManager::mutex_// UsbPortManager::mutex_// SerialManager::serialPortMapMutex_};
3.2 外部依赖框图
4. 状态机转换图
4.1 状态机模型
USB Manager 包含多个状态机,分别管理不同的功能模块:
- USB Service 状态机: 管理服务生命周期
- USB Device 状态机: 管理Device模式连接状态
- USB Accessory 状态机: 管理配件模式状态
- USB Port 状态机: 管理端口角色状态
4.2 状态机树图
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 状态转换图
UsbDevice 状态转换图
UsbAccessory 状态转换图
UsbPort 状态转换图
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)
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 设备打开与数据传输时序
5.3.2 设备插拔事件处理时序
5.3.3 Function切换时序
附录
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 | 数据设备 |