jsp网站缓存在哪,动漫制作专业有本科吗,效果好的免费网站建设,济南网站建设力推搜点网络okUSB Manager 模块
目录
模块概述 1.1 功能与目标1.2 系统位置1.3 设计思路与模式1.4 系统框图 模块结构 2.1 源文件与头文件2.2 类、结构体、函数与方法2.3 类图2.4 模块内部依赖框图 模块间交互 3.1 交互描述3.2 外部依赖框图 状态机转换图 4.1 状态机模型4.2 状态机树图4.3…USB Manager 模块目录模块概述1.1 功能与目标1.2 系统位置1.3 设计思路与模式1.4 系统框图模块结构2.1 源文件与头文件2.2 类、结构体、函数与方法2.3 类图2.4 模块内部依赖框图模块间交互3.1 交互描述3.2 外部依赖框图状态机转换图4.1 状态机模型4.2 状态机树图4.3 状态机切换规则4.4 状态机转换图接口设计5.1 公共接口5.2 数据交换接口5.3 接口调用时序图1. 模块概述源码https://gitee.com/openharmony/usb_usb_manager1.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/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 APIusb_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::vectorUsbDevicedeviceList);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_tfuncs);int32_tSetCurrentFunctions(int32_tfuncs);// Port功能接口int32_tGetPorts(std::vectorUsbPortports);int32_tSetPortRole(int32_tportId,int32_tpowerRole,int32_tdataRole);// 权限管理接口boolHasRight(conststd::stringdeviceName);int32_tRequestRight(conststd::stringdeviceName);int32_tRemoveRight(conststd::stringdeviceName);// Serial功能接口int32_tSerialOpen(int32_tportId,constsptrIRemoteObjectserialRemote);int32_tSerialClose(int32_tportId);int32_tSerialRead(...);int32_tSerialWrite(...);private:std::shared_ptrUsbHostManagerusbHostManager_;std::shared_ptrUsbDeviceManagerusbDeviceManager_;std::shared_ptrUsbPortManagerusbPortManager_;std::shared_ptrUsbRightManagerusbRightManager_;std::shared_ptrUsbAccessoryManagerusbAccessoryManager_;std::shared_ptrSERIAL::SerialManagerusbSerialManager_;sptrHDI::Usb::V1_2::IUsbInterfaceusbd_;};UsbHostManager 类classUsbHostManager{public:explicitUsbHostManager(SystemAbility*systemAbility);~UsbHostManager();// 设备管理voidGetDevices(MAP_STR_DEVICEdevices);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_;sptrHDI::Usb::V1_2::IUsbInterfaceusbd_;};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_tfuncs);int32_tSetCurrentFunctions(int32_tfuncs);// 事件处理voidHandleEvent(int32_tstatus);voidSetPhyConnectState(boolphyConnect);boolIsGadgetConnected(void);// 调试接口voidDump(int32_tfd,conststd::vectorstd::stringargs);private:int32_tcurrentFunctions_;boolconnected_;boolgadgetConnected_;sptrHDI::Usb::V1_0::IUsbInterfaceusbd_;std::mutex functionMutex_;};UsbPortManager 类classUsbPortManager{public:UsbPortManager();~UsbPortManager();voidInit();// 端口查询int32_tGetPorts(std::vectorUsbPortports);int32_tGetSupportedModes(int32_tportId,int32_tsupportedModes);int32_tQueryPort();// 端口设置int32_tSetPortRole(int32_tportId,int32_tpowerRole,int32_tdataRole);voidUpdatePort(int32_tportId,int32_tpowerRole,int32_tdataRole,int32_tmode);voidAddPort(UsbPortport);voidRemovePort(int32_tportId);private:std::mutex mutex_;std::mapint32_t,UsbPortportMap_;std::mapint32_t,int32_tsupportedModeMap_;sptrHDI::Usb::V1_0::IUsbInterfaceusbd_;};UsbRightManager 类classUsbRightManager{public:int32_tInit();// 权限查询boolHasRight(conststd::stringdeviceName,conststd::stringbundleName,conststd::stringtokenId,constint32_tuserId);// 权限申请int32_tRequestRight(conststd::stringbusDev,conststd::stringdeviceName,conststd::stringbundleName,conststd::stringtokenId,constint32_tuserId);// 权限管理boolAddDeviceRight(conststd::stringdeviceName,conststd::stringbundleName,conststd::stringtokenId,constint32_tuserId);boolRemoveDeviceRight(conststd::stringdeviceName,conststd::stringbundleName,conststd::stringtokenId,constint32_tuserId);int32_tCancelDeviceRight(...);boolRemoveDeviceAllRight(conststd::stringdeviceName);// 权限清理int32_tCleanUpRightExpired(std::vectorstd::stringdevices);staticint32_tCleanUpRightUserDeleted(int32_ttotalUsers,int32_tdeleteUsers);staticint32_tCleanUpRightAppUninstalled(int32_tuid,conststd::stringbundleName);// 权限校验boolIsSystemAppOrSa();boolVerifyPermission();int32_tHasSetFuncRight(int32_tfunctions);private:std::mutex dialogRunning_;sptrUsbAbilityConnusbAbilityConn_;};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::vectorUSBConfigconfigs);// 序列化接口boolMarshalling(Parcelparcel)constoverride;staticUsbDevice*Unmarshalling(Parceldata);// 属性访问器conststd::stringGetName()const;conststd::stringGetManufacturerName()const;conststd::stringGetProductName()const;int32_tGetVendorId()const;int32_tGetProductId()const;int32_tGetClass()const;uint8_tGetBusNum()const;uint8_tGetDevAddr()const;std::vectorUSBConfigGetConfigs();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::vectorUSBConfigconfigs_;};UsbPort 结构structUsbPortStatus{int32_tcurrentMode;// 当前模式int32_tcurrentPowerRole;// 当前电源角色int32_tcurrentDataRole;// 当前数据角色};structUsbPort:publicParcelable{int32_tid;// 端口IDint32_tsupportedModes;// 支持的模式UsbPortStatus usbPortStatus;// 端口状态boolMarshalling(Parcelparcel)constoverride;staticUsbPort*Unmarshalling(Parceldata);};错误码枚举enumUsbErrCode{UEC_OK0,// 接口层错误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_ptrUsbHostManager usbHostManager_-shared_ptrUsbDeviceManager usbDeviceManager_-shared_ptrUsbPortManager usbPortManager_-shared_ptrUsbRightManager usbRightManager_-shared_ptrUsbAccessoryManager usbAccessoryManager_-shared_ptrSerialManager usbSerialManager_-sptrIUsbInterface usbd_OnStart() : voidOnStop() : voidOpenDevice() : int32_tClose() : int32_tGetDevices() : int32_tBulkTransferRead() : int32_tControlTransfer() : int32_tUsbHostManager-MAP_STR_DEVICE devices_-sptrIUsbInterface usbd_-mutex mutex_OpenDevice() : int32_tClose() : int32_tBulkTransfer() : int32_tAddDevice() : boolDelDevice() : boolUsbDeviceManager-int32_t currentFuncs_-bool connected_-sptrIUsbInterface usbd_GetFunctions() : int32_tSetFunctions() : int32_tHandleEvent() : voidUsbPortManager-map portMap_-sptrIUsbInterface usbd_GetPorts() : int32_tSetPortRole() : int32_tUpdatePort() : voidUsbRightManager-mutex dialogRunning_-sptrUsbAbilityConn usbAbilityConn_HasRight() : boolRequestRight() : int32_tAddDeviceRight() : boolUsbAccessoryManager-USBAccessory accessory_-int32_t accStatus_HandleEvent() : voidOpenAccessory() : int32_tCloseAccessory() : int32_tSerialManager-map portTokenMap_-sptrISerialInterface serial_SerialOpen() : int32_tSerialClose() : int32_tSerialRead() : int32_tUsbSrvClient-sptrIUsbServer proxy_-sptrDeathRecipient deathRecipient_-mutex mutex_GetInstance() : UsbSrvClientOpenDevice() : int32_tGetDevices() : int32_tHasRight() : boolRequestRight() : int32_tBulkTransfer() : int32_tUsbDevice-string name_-int32_t vendorId_-int32_t productId_-vectorUSBConfig configs_Marshalling() : boolUnmarshalling()UsbPortint32_t idint32_t supportedModesUsbPortStatus usbPortStatusMarshalling() : boolUnmarshalling()USBConfig-int32_t id_-uint32_t attributes_-vector interfaces_Marshalling() : boolUnmarshalling()2.4 模块内部依赖框图HAL InterfaceUsbService (核心协调器)Manager 层Helper/Utility 层Subscriber/Callback 层IUsbInterfaceISerialInterfaceIUsbdSubscriberUsbServiceSubscriberUsbBulkCallbackImplUsbTransferCallbackImplUsbRightDbHelperUsbRightDatabaseUsbDescriptorParserUsbTimerWraperUsbReportSysEventUsbHostManagerUsbDeviceManagerUsbPortManagerUsbRightManagerUsbAccessoryManagerSerialManager3. 模块间交互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 异步处理机制异步事件处理流程事件通知处理请求广播事件UsbSubscriberUSB HALUsbServiceHostManagerDeviceManagerPortManagerCommonEvent Service应用层接收事件3.1.4 多线程处理USB Manager 使用以下多线程机制主线程: 处理IPC请求事件处理线程: 处理HAL层事件回调定时器线程: 处理超时和延迟任务回调线程: 处理异步传输回调// 线程安全保护示例classUsbService{private:std::mutex mutex_;// 主互斥锁std::mutex serialPidVidMapMutex_;// 串口映射锁// 子管理器各自维护独立的锁// UsbHostManager::mutex_// UsbPortManager::mutex_// SerialManager::serialPortMapMutex_};3.2 外部依赖框图Linux Kernel外部依赖USB Core DriverUSB Host ControllerUSB Gadget DriverUSB HALIUsbInterfaceISerialIntfIUsbdSubscriberAccessToken ServiceVerifyAccessGetTokenInfoIsSystemAppBundleMgr ServiceGetBundleInfoGetAppNameCommonEvent ServicePublishCommonEventDataShare ServiceQuery/Insert/DeleteUSB Manager Service4. 状态机转换图4.1 状态机模型USB Manager 包含多个状态机分别管理不同的功能模块USB Service 状态机: 管理服务生命周期USB Device 状态机: 管理Device模式连接状态USB Accessory 状态机: 管理配件模式状态USB Port 状态机: 管理端口角色状态4.2 状态机树图USB Manager 状态机层次结构USB ManagerUsbService 状态机UNINITIALIZED未初始化INITIALIZING初始化中READY就绪STOPPING停止中UsbDevice 状态机DISCONNECTED未连接CONNECTED已连接CONFIGURING配置中FUNCTION_NONEFUNCTION_HDCFUNCTION_MTPFUNCTION_PTPFUNCTION_RNDISUsbAccessory 状态机ACC_NONE无配件ACC_CONFIGURING配置中ACC_START已启动ACC_SEND发送中ACC_STOP已停止UsbPort 状态机MODE_NONE无模式MODE_HOST主机模式MODE_DEVICE设备模式MODE_DRP双角色POWER_SOURCEDATA_HOSTPOWER_SINKDATA_DEVICE4.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()清理完成UNINITIALIZEDINITIALIZINGREADYSTOPPINGUsbDevice 状态转换图USB_DEVICE_ATTACHEDUSB_DEVICE_DETACHEDSetCurrentFunctions()配置成功配置失败(恢复原功能)DISCONNECTEDCONNECTED切换HDC切换MTP切换PTP切换RNDIS切换NONE切换NONE切换NONE切换NONEFUNC_NONEFUNC_HDCFUNC_MTPFUNC_PTPFUNC_RNDISCONFIGURINGUsbAccessory 状态转换图检测到配件配置完成OpenAccessory()CloseAccessory()配件断开配件断开(异常)配件断开(异常)配件断开(异常)ACC_NONEACC_CONFIGURINGACC_STARTACC_SENDACC_STOPUsbPort 状态转换图支持双角色SetPortRole(HOST)SetPortRole(DEVICE)SetPortRole(DEVICE)SetPortRole(HOST)协商为HOST协商为DEVICEMODE_NONEMODE_HOSTPOWER_SOURCEDATA_HOSTMODE_DEVICEPOWER_SINKDATA_DEVICEMODE_DRP5. 接口设计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(Parcelparcel)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(Parcelparcel)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 HAL5.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非系统应用调用系统APIUEC_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数据设备