first commit

This commit is contained in:
cxh 2025-09-10 13:21:43 +08:00
parent 4d5514d8a9
commit 61e267dece

View File

@ -3,6 +3,7 @@
#include <thread> #include <thread>
#include <chrono> #include <chrono>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <algorithm>
std::shared_ptr<MQTTClient> mqtt_client; std::shared_ptr<MQTTClient> mqtt_client;
std::atomic<bool> mqtt_restart_required{false}; std::atomic<bool> mqtt_restart_required{false};
@ -33,7 +34,7 @@ static void send_heartbeat()
mqtt_client->publish(g_app_config.mqtt.topics.heartbeat_up, msg.dump()); mqtt_client->publish(g_app_config.mqtt.topics.heartbeat_up, msg.dump());
} }
// MQTT 回调定义 // MQTT 回调
static void on_mqtt_connected() static void on_mqtt_connected()
{ {
LOG_INFO("[MQTT] Connected to broker: " + g_app_config.mqtt.server_ip); LOG_INFO("[MQTT] Connected to broker: " + g_app_config.mqtt.server_ip);
@ -220,10 +221,14 @@ void mqtt_client_thread_func()
{ {
} }
// 更频繁地检查退出标志 // 拆分等待,及时响应退出
for (int i = 0; i < 10 && g_running && !mqtt_client->isConnected(); i++) for (int i = 0; i < 10 && g_running && !mqtt_client->isConnected(); i++)
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if (!g_running && mqtt_client->isConnected() == false)
{ {
std::this_thread::sleep_for(std::chrono::milliseconds(200)); mqtt_client->force_disconnect();
break;
} }
} }
@ -233,33 +238,31 @@ void mqtt_client_thread_func()
{ {
send_heartbeat(); send_heartbeat();
} }
catch (const std::exception &e) catch (...)
{ {
LOG_ERROR("[MQTT] Heartbeat error: " + std::string(e.what()));
} }
// 将长睡眠拆分为多个短睡眠,以便更频繁检查退出标志
auto sleep_time = heartbeat_interval; auto sleep_time = heartbeat_interval;
while (sleep_time.count() > 0 && g_running && mqtt_client->isConnected()) while (sleep_time.count() > 0 && g_running && mqtt_client->isConnected())
{ {
auto chunk = std::min(sleep_time, std::chrono::milliseconds(200)); auto chunk = std::min(sleep_time, std::chrono::milliseconds(50));
std::this_thread::sleep_for(chunk); std::this_thread::sleep_for(chunk);
sleep_time -= chunk; sleep_time -= chunk;
} }
}
// 清理资源 if (!g_running && mqtt_client->isConnected())
if (mqtt_client)
{ {
// 只有在运行标志仍然为true时才尝试正常断开
if (g_running)
{
mqtt_client->disconnect();
}
else
{
// 如果正在退出,直接重置客户端,不等待断开完成
mqtt_client->force_disconnect(); mqtt_client->force_disconnect();
} }
}
// 清理客户端
if (mqtt_client)
{
if (g_running)
mqtt_client->disconnect();
else
mqtt_client->force_disconnect();
mqtt_client.reset(); mqtt_client.reset();
} }