| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- #pragma once
- #include <windows.h>
- #include <string>
- #include <vector>
- #include <functional>
- #include <map>
- #include <mutex>
- // 事件类型
- 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<BYTE> data;
- DWORD data_size;
- };
- // 事件回调函数类型
- using CommEventCallback = std::function<void(const CommEventData &)>;
- // 通信包装器基类
- class CommWrapperBase
- {
- protected:
- bool initialized_;
- bool callback_initialized_;
- std::map<int, bool> 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<std::mutex> lock(mutex_);
- auto it = monitored_ports_.find(port);
- return it != monitored_ports_.end() && it->second;
- }
- };
|