diff --git a/src/mqtt_client_wrapper.cpp b/src/mqtt_client_wrapper.cpp index b7db638..f0f14a9 100644 --- a/src/mqtt_client_wrapper.cpp +++ b/src/mqtt_client_wrapper.cpp @@ -3,6 +3,7 @@ #include #include #include +#include std::shared_ptr mqtt_client; std::atomic 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 回调定义 +// MQTT 回调 static void on_mqtt_connected() { 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++) + 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(); } - catch (const std::exception &e) + catch (...) { - LOG_ERROR("[MQTT] Heartbeat error: " + std::string(e.what())); } - // 将长睡眠拆分为多个短睡眠,以便更频繁检查退出标志 + auto sleep_time = heartbeat_interval; 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); sleep_time -= chunk; } - } - // 清理资源 - if (mqtt_client) - { - // 只有在运行标志仍然为true时才尝试正常断开 - if (g_running) + if (!g_running && mqtt_client->isConnected()) { - mqtt_client->disconnect(); - } - else - { - // 如果正在退出,直接重置客户端,不等待断开完成 mqtt_client->force_disconnect(); } + } + + // 清理客户端 + if (mqtt_client) + { + if (g_running) + mqtt_client->disconnect(); + else + mqtt_client->force_disconnect(); mqtt_client.reset(); }