65 lines
2.0 KiB
C++
65 lines
2.0 KiB
C++
// 文件名: src/modbus/modbus_rtu_bus_service.h (注意文件名已更改)
|
|
#ifndef MODBUS_RTU_BUS_SERVICE_H
|
|
#define MODBUS_RTU_BUS_SERVICE_H
|
|
|
|
#include "protocol/iprotocol_adapter.h"
|
|
#include "modbus_rtu_client.h"
|
|
#include "modbus_common.h"
|
|
#include <thread>
|
|
#include <atomic>
|
|
#include <string>
|
|
#include <vector> // <--- 新增
|
|
#include <mutex>
|
|
|
|
/**
|
|
* @brief Modbus RTU 总线服务类
|
|
* * 负责在一个独立的后台线程中,管理一个物理串口,并依次轮询该串口上的所有设备。
|
|
*/
|
|
class ModbusRtuBusService {
|
|
public:
|
|
/**
|
|
* @brief 构造函数
|
|
* @param port_path 该总线所使用的串口路径, e.g., "/dev/ttyS0"
|
|
* @param devices 该总线上所有设备的配置列表
|
|
* @param report_cb 用于上报数据的回调函数
|
|
*/
|
|
ModbusRtuBusService(std::string port_path,
|
|
std::vector<ModbusRtuDeviceConfig> devices,
|
|
ReportDataCallback report_cb);
|
|
~ModbusRtuBusService();
|
|
|
|
ModbusRtuBusService(const ModbusRtuBusService&) = delete;
|
|
ModbusRtuBusService& operator=(const ModbusRtuBusService&) = delete;
|
|
|
|
void start();
|
|
void stop();
|
|
bool is_running() const;
|
|
|
|
/**
|
|
* @brief 检查该总线服务是否管理着指定的设备ID
|
|
*/
|
|
bool manages_device(const std::string& device_id) const;
|
|
const std::vector<ModbusRtuDeviceConfig>& get_all_device_configs() const;
|
|
|
|
/**
|
|
* @brief (线程安全) 向总线上的某个设备写入单个寄存器
|
|
* @param device_id 目标设备的ID
|
|
* @param address 寄存器地址
|
|
* @param value 要写入的值
|
|
*/
|
|
void write_single_register(const std::string& device_id, uint16_t address, uint16_t value);
|
|
|
|
private:
|
|
void run();
|
|
|
|
std::string m_port_path;
|
|
std::vector<ModbusRtuDeviceConfig> m_devices;
|
|
ReportDataCallback m_report_callback;
|
|
ModbusRTUClient m_client;
|
|
|
|
std::thread m_thread;
|
|
std::atomic<bool> m_stop_flag{false};
|
|
std::mutex m_client_mutex; // 保护 m_client 的互斥锁
|
|
};
|
|
|
|
#endif // MODBUS_RTU_BUS_SERVICE_H
|