first commit

This commit is contained in:
cxh 2025-09-08 15:59:15 +08:00
parent 84be23c2dc
commit 0e8ced1624
3 changed files with 12 additions and 5 deletions

View File

@ -8,6 +8,7 @@
#include <mutex> #include <mutex>
#include <mqtt/async_client.h> #include <mqtt/async_client.h>
#include "app_config.hpp" #include "app_config.hpp"
#include "logger.hpp"
class MQTTClient : public virtual mqtt::callback class MQTTClient : public virtual mqtt::callback
{ {

View File

@ -43,10 +43,12 @@ void MQTTClient::connect()
if (on_connect_) if (on_connect_)
on_connect_(); on_connect_();
LOG_INFO("[MQTTClient] Connected to broker: " + config_.server_ip);
} }
catch (const mqtt::exception &e) catch (const mqtt::exception &e)
{ {
std::cerr << "[MQTTClient] Connect failed: " << e.what() << std::endl; LOG_ERROR("[MQTTClient] Connect failed: " + std::string(e.what()));
startReconnect(); startReconnect();
} }
} }
@ -63,10 +65,12 @@ void MQTTClient::disconnect()
connected_ = false; connected_ = false;
if (on_disconnect_) if (on_disconnect_)
on_disconnect_(); on_disconnect_();
LOG_INFO("[MQTTClient] Disconnected from broker: " + config_.server_ip);
} }
catch (const mqtt::exception &e) catch (const mqtt::exception &e)
{ {
std::cerr << "[MQTTClient] Disconnect failed: " << e.what() << std::endl; LOG_ERROR("[MQTTClient] Disconnect failed: " + std::string(e.what()));
} }
} }
@ -78,10 +82,11 @@ void MQTTClient::publish(const std::string &topic, const std::string &payload, i
try try
{ {
client_->publish(topic, payload.data(), payload.size(), qos, false)->wait_for(std::chrono::milliseconds(500)); client_->publish(topic, payload.data(), payload.size(), qos, false)->wait_for(std::chrono::milliseconds(500));
LOG_INFO("[MQTTClient] Published message to topic: " + topic);
} }
catch (const mqtt::exception &e) catch (const mqtt::exception &e)
{ {
std::cerr << "[MQTTClient] Publish failed: " << e.what() << std::endl; LOG_ERROR("[MQTTClient] Publish failed: " + std::string(e.what()));
if (!connected_) if (!connected_)
startReconnect(); startReconnect();
} }
@ -95,10 +100,11 @@ void MQTTClient::subscribe(const std::string &topic, int qos)
try try
{ {
client_->subscribe(topic, qos)->wait(); client_->subscribe(topic, qos)->wait();
LOG_INFO("[MQTTClient] Subscribed to topic: " + topic);
} }
catch (const mqtt::exception &e) catch (const mqtt::exception &e)
{ {
std::cerr << "[MQTTClient] Subscribe failed: " << e.what() << std::endl; LOG_ERROR("[MQTTClient] Subscribe failed: " + std::string(e.what()));
if (!connected_) if (!connected_)
startReconnect(); startReconnect();
} }

View File

@ -50,7 +50,7 @@ void mqtt_client_thread_func()
while (!mqtt_restart_required && g_running) while (!mqtt_restart_required && g_running)
{ {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
} }
// 需要重启或退出 // 需要重启或退出