2025-10-13 13:55:15 +08:00
|
|
|
#include "modbus_rtu_client.h"
|
|
|
|
|
#include "jwst20_sensor.h"
|
|
|
|
|
#include <iostream>
|
|
|
|
|
#include <memory>
|
|
|
|
|
#include <chrono>
|
|
|
|
|
#include <thread>
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
std::cout << "--- Modbus RTU Sensor Client (C++ Core) ---\n";
|
|
|
|
|
|
|
|
|
|
// 建议用一个 try-catch 块来捕获所有未处理的异常
|
|
|
|
|
try {
|
|
|
|
|
// 1. 创建 Modbus RTU 客户端,使用智能指针自动管理生命周期
|
|
|
|
|
ModbusClientPtr modbus_client = std::make_unique<ModbusRTUClient>("/dev/ttyS7", 9600);
|
|
|
|
|
std::cout << "Modbus client initialized on /dev/ttyS7 @ 9600 baud.\n";
|
|
|
|
|
|
|
|
|
|
// 2. 创建传感器实例,传入 Modbus 客户端指针和从站地址
|
|
|
|
|
JWST20Sensor sensor(modbus_client.get(), 0x01);
|
|
|
|
|
std::cout << "JWST-20 sensor initialized for slave 01.\n";
|
|
|
|
|
|
|
|
|
|
std::cout << "\nStarting continuous polling. Press Ctrl+C to exit.\n";
|
|
|
|
|
while (true) {
|
|
|
|
|
std::cout << "--- New Reading ---\n";
|
|
|
|
|
|
|
|
|
|
// 3. 使用高级API读取温度
|
|
|
|
|
try {
|
|
|
|
|
float temp = sensor.read_temperature();
|
|
|
|
|
std::cout << "Temperature: " << temp << " °C\n";
|
|
|
|
|
} catch (const std::exception& e) {
|
|
|
|
|
std::cerr << "[Temp Error] " << e.what() << std::endl;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 4. 使用高级API读取湿度
|
|
|
|
|
try {
|
|
|
|
|
float hum = sensor.read_humidity();
|
|
|
|
|
std::cout << "Humidity: " << hum << " %RH\n";
|
|
|
|
|
} catch (const std::exception& e) {
|
|
|
|
|
std::cerr << "[Humi Error] " << e.what() << std::endl;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
std::cout << "-------------------\n\n";
|
|
|
|
|
|
|
|
|
|
// 暂停2秒
|
|
|
|
|
std::this_thread::sleep_for(std::chrono::seconds(2));
|
|
|
|
|
}
|
|
|
|
|
} catch (const std::exception& e) {
|
|
|
|
|
// 捕获在 main 函数顶层发生的任何错误(例如,串口打开失败)
|
|
|
|
|
std::cerr << "[CRITICAL_ERROR] An unhandled exception occurred: " << e.what() << std::endl;
|
|
|
|
|
return 1; // 返回非零表示错误
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return 0; // 正常退出
|
|
|
|
|
}
|