76 lines
2.4 KiB
C++
76 lines
2.4 KiB
C++
// 文件名: src/modbus/modbus_rtu_poller_service.h
|
||
#ifndef MODBUS_RTU_POLLER_SERVICE_H
|
||
#define MODBUS_RTU_POLLER_SERVICE_H
|
||
|
||
#include "protocol/iprotocol_adapter.h"
|
||
#include "modbus_rtu_client.h"
|
||
#include "modbus_common.h" // 包含 ModbusRtuDeviceConfig 和 DataPointConfig 定义
|
||
#include <thread>
|
||
#include <atomic>
|
||
#include <string>
|
||
|
||
/**
|
||
* @brief Modbus RTU 轮询服务类
|
||
* * 负责在一个独立的后台线程中,根据配置周期性地轮询一个Modbus RTU设备。
|
||
* 这种设计将同步阻塞的串口IO操作与主程序的异步事件循环隔离开来,
|
||
* 避免了主线程被阻塞。
|
||
*/
|
||
class ModbusRtuPollerService {
|
||
public:
|
||
/**
|
||
* @brief 构造函数
|
||
* @param config 描述了要连接的设备、串口参数以及需要采集的数据点列表
|
||
* @param report_cb 用于将解析后的数据上报给核心业务层的回调函数
|
||
*/
|
||
ModbusRtuPollerService(ModbusRtuDeviceConfig config, ReportDataCallback report_cb);
|
||
|
||
/**
|
||
* @brief 析构函数
|
||
* * 确保在对象销毁时,后台线程能够被安全地停止和清理。
|
||
*/
|
||
~ModbusRtuPollerService();
|
||
|
||
// 禁止拷贝和赋值,因为该类管理着一个线程资源
|
||
ModbusRtuPollerService(const ModbusRtuPollerService&) = delete;
|
||
ModbusRtuPollerService& operator=(const ModbusRtuPollerService&) = delete;
|
||
|
||
/**
|
||
* @brief 启动轮询服务
|
||
* * 创建并启动一个新的后台线程来执行 run() 方法中的轮询逻辑。
|
||
*/
|
||
void start();
|
||
|
||
/**
|
||
* @brief 停止轮询服务
|
||
* * 设置停止标志位,并等待后台线程安全地执行完毕并退出。
|
||
*/
|
||
void stop();
|
||
|
||
// --- <<< 新增方法 >>> ---
|
||
/**
|
||
* @brief 获取设备的配置信息 (const-ref to avoid copy)
|
||
*/
|
||
const ModbusRtuDeviceConfig& get_config() const;
|
||
|
||
/**
|
||
* @brief 检查轮询服务是否正在运行
|
||
*/
|
||
bool is_running() const;
|
||
// --- <<< END >>> ---
|
||
private:
|
||
/**
|
||
* @brief 线程的主循环函数
|
||
* * 该函数是后台线程的入口点。它包含了连接串口、周期性轮询、
|
||
* 解析数据和上报数据的完整逻辑。
|
||
*/
|
||
void run();
|
||
|
||
ModbusRtuDeviceConfig m_config;
|
||
ReportDataCallback m_report_callback;
|
||
ModbusRTUClient m_client;
|
||
|
||
std::thread m_thread;
|
||
std::atomic<bool> m_stop_flag{false};
|
||
};
|
||
|
||
#endif // MODBUS_RTU_POLLER_SERVICE_H
|