diff --git a/src/mqtt_client_wrapper.cpp b/src/mqtt_client_wrapper.cpp index d685a86..319490d 100644 --- a/src/mqtt_client_wrapper.cpp +++ b/src/mqtt_client_wrapper.cpp @@ -9,9 +9,6 @@ extern std::atomic g_running; std::string g_dispatch_id; std::mutex g_dispatch_id_mutex; -auto last_heartbeat = std::chrono::steady_clock::now(); -auto heartbeat_interval = std::chrono::milliseconds(static_cast(g_app_config.mqtt.keep_alive * 0.9)); - static void send_heartbeat() { if (!mqtt_client || !mqtt_client->isConnected()) @@ -29,14 +26,9 @@ static void send_heartbeat() } nlohmann::json hb_data; - hb_data["time"] = Logger::get_current_time_utc8(); - - { - std::lock_guard lock(g_dispatch_id_mutex); - if (!g_dispatch_id.empty()) - hb_data["dispatchId"] = g_dispatch_id; - } - + hb_data["time"] = Logger::get_current_time_utc8(); // UTC+8 + if (!g_dispatch_id.empty()) + hb_data["dispatchId"] = g_dispatch_id; hb_data["status"] = status; nlohmann::json msg; @@ -209,6 +201,7 @@ static void on_mqtt_message_received(const std::string &topic, const std::string void mqtt_client_thread_func() { const auto &cfg = g_app_config.mqtt; + auto heartbeat_interval = std::chrono::milliseconds(static_cast(cfg.mqtt.keep_alive * 0.9)); while (g_running) { @@ -222,20 +215,18 @@ void mqtt_client_thread_func() while (!mqtt_restart_required && g_running) { auto now = std::chrono::steady_clock::now(); - if (now - last_heartbeat >= heartbeat_interval) - { - try - { - send_heartbeat(); - } - catch (const std::exception &e) - { - LOG_ERROR(std::string("[MQTT] Heartbeat error: ") + e.what()); - } - last_heartbeat = now; - } - std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 轻量轮询 + try + { + send_heartbeat(); + } + catch (const std::exception &e) + { + LOG_ERROR(std::string("[MQTT] Heartbeat error: ") + e.what()); + } + last_heartbeat = now; + + std::this_thread::sleep_for(heartbeat_interval); // 固定周期 } // 需要重启或退出