diff --git a/include/LedMqttSubscriber.h b/include/LedMqttSubscriber.h index ef85fa4..a826456 100644 --- a/include/LedMqttSubscriber.h +++ b/include/LedMqttSubscriber.h @@ -7,7 +7,10 @@ class MqttClient { public: MqttClient(const std::string &configPath); - bool start(); + ~MqttClient(); + + bool start(); // 连接并订阅 + void disconnect(); // 断开连接 private: std::string broker; diff --git a/src/LedMqttSubscriber.cpp b/src/LedMqttSubscriber.cpp index 1262d35..30bca30 100644 --- a/src/LedMqttSubscriber.cpp +++ b/src/LedMqttSubscriber.cpp @@ -49,6 +49,11 @@ MqttClient::MqttClient(const std::string &configPath) } } +MqttClient::~MqttClient() +{ + delete client; +} + bool MqttClient::start() { try @@ -65,6 +70,19 @@ bool MqttClient::start() } } +void MqttClient::disconnect() +{ + try + { + std::cout << "断开 MQTT 连接..." << std::endl; + client->disconnect()->wait(); + } + catch (const mqtt::exception &e) + { + std::cerr << "MQTT 断开失败: " << e.what() << std::endl; + } +} + void MqttClient::Callback::message_arrived(mqtt::const_message_ptr msg) { std::cout << "接收到消息: " << msg->to_string() << std::endl; diff --git a/src/main.cpp b/src/main.cpp index f552185..2b70e37 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -88,16 +88,21 @@ int main() std::cout << "串口号: " << port << "\n波特率: " << baudrate << std::endl; // ===== MQTT 测试连接 ===== - MqttClient mqtt("config.toml"); // 构造时自动读取配置并初始化 - if (mqtt.connect()) + MqttClient mqtt("config.toml"); + if (mqtt.start()) { - std::cout << "MQTT 连接成功" << std::endl; - std::this_thread::sleep_for(std::chrono::seconds(2)); + std::cout << "MQTT 启动成功,等待消息..." << std::endl; + std::this_thread::sleep_for(std::chrono::seconds(5)); mqtt.disconnect(); } else { - std::cerr << "MQTT 连接失败" << std::endl; + std::cerr << "MQTT 启动失败" << std::endl; + } + + while (1) + { + /* code */ } SerialPort serial;