122 lines
3.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ifndef MODBUSRTUMASTER_H
#define MODBUSRTUMASTER_H
#include <QObject>
#include <QTimer>
#include <atomic>
#include <thread>
#include <mutex>
#include <functional>
// 包含Modbus库头文件
extern "C" {
#include "modbus.h"
#include "modbus-rtu.h"
}
/**
* @brief Modbus-RTU主端类
* 实现通过串口读取温度数据
*/
class ModbusRTUMaster : public QObject
{
Q_OBJECT
public:
/**
* @brief 构造函数
* @param parent 父对象
*/
explicit ModbusRTUMaster(QObject *parent = nullptr);
/**
* @brief 析构函数
*/
~ModbusRTUMaster();
/**
* @brief 初始化Modbus-RTU主端
* @param device 串口设备路径,例如"/dev/ttyS4"
* @param baud 波特率
* @param parity 校验位('N':无校验, 'E':偶校验, 'O':奇校验)
* @param dataBit 数据位(通常为8)
* @param stopBit 停止位(通常为1)
* @return 0-成功,其他-错误码
*/
int Initialize(const QString& device, int baud = 115200, char parity = 'N', int dataBit = 8, int stopBit = 1);
/**
* @brief 反初始化,停止服务
*/
void Deinitialize();
/**
* @brief 设置温度数据回调函数
* @param callback 回调函数
*/
void SetTemperatureCallback(const std::function<void(float)>& callback);
/**
* @brief 开始读取温度数据
* @return 0-成功,其他-错误码
*/
int StartReading();
/**
* @brief 停止读取温度数据
*/
void StopReading();
/**
* @brief 获取当前运行状态
* @return true-运行中false-已停止
*/
bool IsRunning() const;
private slots:
/**
* @brief 定时读取温度数据
*/
void OnReadTimer();
private:
/**
* @brief 读取温度寄存器数据
* @param temperature[out] 温度值(摄氏度)
* @return 0-成功,其他-错误码
*/
int ReadTemperature(float& temperature);
private:
// Modbus相关
modbus_t* m_pModbusCtx; // Modbus上下文
QString m_device; // 串口设备路径
int m_baud; // 波特率
char m_parity; // 校验位
int m_dataBit; // 数据位
int m_stopBit; // 停止位
uint8_t m_slaveAddr; // 从机地址
std::chrono::milliseconds m_responseTimeout; // 响应超时时间
// 运行状态
std::atomic<bool> m_bInitialized; // 是否已初始化
std::atomic<bool> m_bRunning; // 是否正在运行
// 定时器
QTimer* m_pReadTimer; // 读取定时器
std::chrono::milliseconds m_readInterval; // 读取间隔
// 温度数据回调函数
std::function<void(float)> m_temperatureCallback; // 温度数据回调
// 互斥锁
mutable std::mutex m_mutex; // 线程安全互斥锁
// Modbus地址映射
static const uint16_t TEMPERATURE_ADDR = 0x00; // 温度寄存器地址
static const uint16_t TEMPERATURE_QUANTITY = 1; // 温度寄存器数量单个寄存器值除以10为实际温度
};
#endif // MODBUSRTUMASTER_H