first commit
This commit is contained in:
parent
84be23c2dc
commit
0e8ced1624
@ -8,6 +8,7 @@
|
||||
#include <mutex>
|
||||
#include <mqtt/async_client.h>
|
||||
#include "app_config.hpp"
|
||||
#include "logger.hpp"
|
||||
|
||||
class MQTTClient : public virtual mqtt::callback
|
||||
{
|
||||
|
||||
@ -43,10 +43,12 @@ void MQTTClient::connect()
|
||||
|
||||
if (on_connect_)
|
||||
on_connect_();
|
||||
|
||||
LOG_INFO("[MQTTClient] Connected to broker: " + config_.server_ip);
|
||||
}
|
||||
catch (const mqtt::exception &e)
|
||||
{
|
||||
std::cerr << "[MQTTClient] Connect failed: " << e.what() << std::endl;
|
||||
LOG_ERROR("[MQTTClient] Connect failed: " + std::string(e.what()));
|
||||
startReconnect();
|
||||
}
|
||||
}
|
||||
@ -63,10 +65,12 @@ void MQTTClient::disconnect()
|
||||
connected_ = false;
|
||||
if (on_disconnect_)
|
||||
on_disconnect_();
|
||||
|
||||
LOG_INFO("[MQTTClient] Disconnected from broker: " + config_.server_ip);
|
||||
}
|
||||
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
|
||||
{
|
||||
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)
|
||||
{
|
||||
std::cerr << "[MQTTClient] Publish failed: " << e.what() << std::endl;
|
||||
LOG_ERROR("[MQTTClient] Publish failed: " + std::string(e.what()));
|
||||
if (!connected_)
|
||||
startReconnect();
|
||||
}
|
||||
@ -95,10 +100,11 @@ void MQTTClient::subscribe(const std::string &topic, int qos)
|
||||
try
|
||||
{
|
||||
client_->subscribe(topic, qos)->wait();
|
||||
LOG_INFO("[MQTTClient] Subscribed to topic: " + topic);
|
||||
}
|
||||
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_)
|
||||
startReconnect();
|
||||
}
|
||||
|
||||
@ -50,7 +50,7 @@ void mqtt_client_thread_func()
|
||||
|
||||
while (!mqtt_restart_required && g_running)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
|
||||
// 需要重启或退出
|
||||
|
||||
Loading…
Reference in New Issue
Block a user