#pragma once #include #include #include #include #include #include // 事件类型 enum class CommEventType { OP_NONE = 0, OP_OPEN = 1, OP_READ = 2, OP_WRITE = 3, OP_CLOSE = 4 }; // 事件数据结构 struct CommEventData { CommEventType event_type; int port; std::vector data; DWORD data_size; }; // 事件回调函数类型 using CommEventCallback = std::function; // 通信包装器基类 class CommWrapperBase { protected: bool initialized_; bool callback_initialized_; std::map monitored_ports_; std::mutex mutex_; CommEventCallback event_callback_; public: CommWrapperBase() : initialized_(false), callback_initialized_(false) {} virtual ~CommWrapperBase() = default; // 初始化 virtual bool Initialize() = 0; // 释放资源 virtual void Cleanup() = 0; // 初始化监控 virtual bool InitMonitor(const std::string &key = "C09976511B62F0ADB759D87E6906D865") = 0; // 监控端口 virtual bool MonitorPort(int port) = 0; // 停止监控端口 virtual bool StopPort(int port) = 0; // 读数据 virtual bool ReadData(int port, const std::string &hex_data) = 0; // 写数据 virtual bool WriteData(int port, const std::string &hex_data) = 0; // 释放监控 virtual bool FreeMonitor() = 0; // 获取最后错误 virtual int GetLastError() = 0; // 设置事件回调 virtual void SetEventCallback(CommEventCallback callback) { event_callback_ = callback; } // 获取错误信息 virtual std::string GetErrorMessage(int error_code) = 0; // 检查端口是否正在监控 virtual bool IsPortMonitored(int port) { std::lock_guard lock(mutex_); auto it = monitored_ports_.find(port); return it != monitored_ports_.end() && it->second; } };