// mqtt_client_wrapper.cpp #include "mqtt_client_wrapper.hpp" #include #include #include #include #include #include #include std::shared_ptr mqtt_client; std::atomic mqtt_restart_required{false}; extern std::atomic g_running; std::atomic g_streaming{false}; std::string g_dispatch_id; std::mutex g_dispatch_id_mutex; static void send_heartbeat() { if (!mqtt_client || !mqtt_client->isConnected()) return; // 获取当前时间戳(13位毫秒) auto now = std::chrono::system_clock::now(); auto ms = std::chrono::duration_cast(now.time_since_epoch()).count(); g_streaming.store(RTMPManager::is_any_streaming()); nlohmann::json hb; hb["timestamp"] = ms; hb["status"] = g_streaming ? 1 : 0; // 0:等待中,1:推流中 mqtt_client->publish(g_app_config.mqtt.topics.heartbeat_up, hb.dump()); } // MQTT 回调 static void on_mqtt_connected() { LOG_INFO("[MQTT] Connected to broker: " + g_app_config.mqtt.server_ip); const auto &topics = g_app_config.mqtt.topics; mqtt_client->subscribe(topics.video_down); } static void on_mqtt_disconnected() { LOG_WARN("[MQTT] Disconnected from broker: " + g_app_config.mqtt.server_ip); } static void on_mqtt_message_received(const std::string &topic, const std::string &message) { try { auto j = nlohmann::json::parse(message); if (topic != g_app_config.mqtt.topics.video_down || j["type"] != "request") return; LOG_INFO("[MQTT] Received message on topic [" + topic + "], len = " + std::to_string(message.size())); LOG_INFO("[MQTT] Message content: " + j.dump(-1)); VideoPushRequest req; req.seqNo = j.value("seqNo", ""); auto data = j["data"]; if (data.is_object()) { VideoPushRequest::DataItem item; item.switchVal = data.value("switch", 0); item.streamType = data.value("streamType", 1); // ✅ 默认子码流 if (item.streamType == 0) item.streamType = 1; // ✅ 防止平台误发 main item.channels = data.value("channels", std::vector{}); req.data.push_back(item); } else if (data.is_array()) { for (auto &d : data) { VideoPushRequest::DataItem item; item.switchVal = d.value("switch", 0); item.streamType = data.value("streamType", 1); // ✅ 默认子码流 if (item.streamType == 0) item.streamType = 1; // ✅ 防止平台误发 main item.channels = d.value("channels", std::vector{}); req.data.push_back(item); } } // 异步执行推流任务 std::thread( [req]() { try { auto results = RTMPManager::process_push_request(req); // 组装 MQTT 回复 nlohmann::json reply; reply["type"] = "response"; reply["seqNo"] = req.seqNo; reply["data"] = nlohmann::json::array(); for (const auto &r : results) { nlohmann::json item; item["loc"] = r.loc; item["url"] = r.url; item["result"] = r.result; item["reason"] = r.reason; reply["data"].push_back(item); } mqtt_client->publish(g_app_config.mqtt.topics.video_down, reply.dump(), 1); LOG_INFO("[MQTT] Sent RTMP response: " + reply.dump()); } catch (const std::exception &e) { LOG_ERROR(std::string("[MQTT] Exception in RTMP thread: ") + e.what()); } catch (...) { LOG_ERROR("[MQTT] Unknown exception in RTMP thread"); } }) .detach(); } catch (const std::exception &e) { LOG_ERROR(std::string("[MQTT] Failed to process incoming JSON: ") + e.what()); } } void mqtt_client_thread_func() { const auto &cfg = g_app_config.mqtt; auto heartbeat_interval = std::chrono::milliseconds(static_cast(cfg.keep_alive * 0.9)); while (g_running) { mqtt_client = std::make_unique(cfg); mqtt_client->setConnectCallback(on_mqtt_connected); mqtt_client->setDisconnectCallback(on_mqtt_disconnected); mqtt_client->setMessageCallback(on_mqtt_message_received); // 等待连接 while (g_running && !mqtt_client->isConnected()) { mqtt_client->connect(); 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()) mqtt_client->force_disconnect(); } // 主循环:心跳 while (g_running && mqtt_client->isConnected()) { send_heartbeat(); auto sleep_time = heartbeat_interval; while (sleep_time.count() > 0 && g_running && mqtt_client->isConnected()) { auto chunk = std::min(sleep_time, std::chrono::milliseconds(50)); std::this_thread::sleep_for(chunk); sleep_time -= chunk; } if (!g_running && mqtt_client->isConnected()) mqtt_client->force_disconnect(); } // 清理 if (mqtt_client) { if (g_running) mqtt_client->disconnect(); else mqtt_client->force_disconnect(); mqtt_client.reset(); } mqtt_restart_required = false; if (!g_running) break; // 短暂等待再重连 for (int i = 0; i < 5 && g_running; i++) std::this_thread::sleep_for(std::chrono::milliseconds(200)); } LOG_INFO("[MQTT] Client thread exiting."); }