CommWrapperBase.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #pragma once
  2. #include <windows.h>
  3. #include <string>
  4. #include <vector>
  5. #include <functional>
  6. #include <map>
  7. #include <mutex>
  8. // 事件类型
  9. enum class CommEventType
  10. {
  11. OP_NONE = 0,
  12. OP_OPEN = 1,
  13. OP_READ = 2,
  14. OP_WRITE = 3,
  15. OP_CLOSE = 4
  16. };
  17. // 事件数据结构
  18. struct CommEventData
  19. {
  20. CommEventType event_type;
  21. int port;
  22. std::vector<BYTE> data;
  23. DWORD data_size;
  24. };
  25. // 事件回调函数类型
  26. using CommEventCallback = std::function<void(const CommEventData &)>;
  27. // 通信包装器基类
  28. class CommWrapperBase
  29. {
  30. protected:
  31. bool initialized_;
  32. bool callback_initialized_;
  33. std::map<int, bool> monitored_ports_;
  34. std::mutex mutex_;
  35. CommEventCallback event_callback_;
  36. public:
  37. CommWrapperBase() : initialized_(false), callback_initialized_(false) {}
  38. virtual ~CommWrapperBase() = default;
  39. // 初始化
  40. virtual bool Initialize() = 0;
  41. // 释放资源
  42. virtual void Cleanup() = 0;
  43. // 初始化监控
  44. virtual bool InitMonitor(const std::string &key = "C09976511B62F0ADB759D87E6906D865") = 0;
  45. // 监控端口
  46. virtual bool MonitorPort(int port) = 0;
  47. // 停止监控端口
  48. virtual bool StopPort(int port) = 0;
  49. // 读数据
  50. virtual bool ReadData(int port, const std::string &hex_data) = 0;
  51. // 写数据
  52. virtual bool WriteData(int port, const std::string &hex_data) = 0;
  53. // 释放监控
  54. virtual bool FreeMonitor() = 0;
  55. // 获取最后错误
  56. virtual int GetLastError() = 0;
  57. // 设置事件回调
  58. virtual void SetEventCallback(CommEventCallback callback)
  59. {
  60. event_callback_ = callback;
  61. }
  62. // 获取错误信息
  63. virtual std::string GetErrorMessage(int error_code) = 0;
  64. // 检查端口是否正在监控
  65. virtual bool IsPortMonitored(int port)
  66. {
  67. std::lock_guard<std::mutex> lock(mutex_);
  68. auto it = monitored_ports_.find(port);
  69. return it != monitored_ports_.end() && it->second;
  70. }
  71. };