From 61b86ae589f93e4d4c034e675251ecec280ae9c8 Mon Sep 17 00:00:00 2001 From: cxh Date: Tue, 9 Sep 2025 16:10:56 +0800 Subject: [PATCH] first commit --- src/mqtt_client_wrapper.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/mqtt_client_wrapper.cpp b/src/mqtt_client_wrapper.cpp index 266f23a..d685a86 100644 --- a/src/mqtt_client_wrapper.cpp +++ b/src/mqtt_client_wrapper.cpp @@ -6,7 +6,9 @@ std::atomic mqtt_restart_required{false}; extern std::atomic g_running; -std::atomic g_dispatch_id{""}; +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)); @@ -28,8 +30,13 @@ static void send_heartbeat() nlohmann::json hb_data; hb_data["time"] = Logger::get_current_time_utc8(); - if (!g_dispatch_id.load().empty()) - hb_data["dispatchId"] = g_dispatch_id.load(); + + { + std::lock_guard lock(g_dispatch_id_mutex); + if (!g_dispatch_id.empty()) + hb_data["dispatchId"] = g_dispatch_id; + } + hb_data["status"] = status; nlohmann::json msg; @@ -74,8 +81,10 @@ static void on_mqtt_message_received(const std::string &topic, const std::string return; } + // 写入 dispatchId 时加锁 if (j["data"].contains("dispatchId")) { + std::lock_guard lock(g_dispatch_id_mutex); g_dispatch_id = j["data"]["dispatchId"].get(); }