yituo_video/src/mqtt_client_wrapper.cpp

289 lines
9.3 KiB
C++
Raw Normal View History

2025-09-08 15:09:33 +08:00
// mqtt_client_wrapper.cpp
2025-09-08 10:59:08 +08:00
#include "mqtt_client_wrapper.hpp"
2025-09-10 10:34:36 +08:00
#include <thread>
#include <chrono>
#include <nlohmann/json.hpp>
2025-09-10 13:21:43 +08:00
#include <algorithm>
2025-09-08 10:59:08 +08:00
std::shared_ptr<MQTTClient> mqtt_client;
std::atomic<bool> mqtt_restart_required{false};
2025-09-08 15:45:22 +08:00
extern std::atomic<bool> g_running;
2025-09-10 10:34:36 +08:00
std::atomic<bool> g_streaming{false};
2025-09-09 16:10:56 +08:00
std::string g_dispatch_id;
std::mutex g_dispatch_id_mutex;
2025-09-09 16:04:58 +08:00
static void send_heartbeat()
{
if (!mqtt_client || !mqtt_client->isConnected())
return;
nlohmann::json hb_data;
2025-09-10 10:34:36 +08:00
hb_data["time"] = Logger::get_current_time_utc8();
2025-09-09 16:45:54 +08:00
hb_data["status"] = g_streaming ? 0 : 2;
2025-09-10 10:34:36 +08:00
{
std::lock_guard<std::mutex> lock(g_dispatch_id_mutex);
2025-09-10 10:37:13 +08:00
hb_data["dispatchId"] = g_streaming ? g_dispatch_id : "";
2025-09-10 10:34:36 +08:00
}
2025-09-09 16:04:58 +08:00
nlohmann::json msg;
msg["data"] = hb_data;
msg["isEnc"] = 0;
msg["type"] = 0;
mqtt_client->publish(g_app_config.mqtt.topics.heartbeat_up, msg.dump());
}
2025-09-10 13:21:43 +08:00
// MQTT 回调
2025-09-08 10:59:08 +08:00
static void on_mqtt_connected()
{
2025-09-08 16:40:04 +08:00
LOG_INFO("[MQTT] Connected to broker: " + g_app_config.mqtt.server_ip);
2025-09-08 15:09:33 +08:00
2025-11-20 16:29:36 +08:00
// --- ★关键MQTT 重连后立即执行全局复位 ---
g_streaming = false; // 清除推流状态
{
std::lock_guard<std::mutex> lock(g_dispatch_id_mutex);
g_dispatch_id.clear(); // 清除旧任务 ID
}
// 停掉所有流,清理 RTSP 状态
for (const auto &cam : g_app_config.cameras)
{
if (RTSPManager::is_streaming(cam.name))
{
RTSPManager::unmount_camera(cam);
LOG_WARN("[MQTT] Reconnected -> force unmount camera: " + cam.name);
}
}
// -------------------------------------------------------
send_heartbeat();
2025-09-08 15:09:33 +08:00
const auto &topics = g_app_config.mqtt.topics;
mqtt_client->subscribe(topics.video_down);
mqtt_client->subscribe(topics.substream_down);
mqtt_client->subscribe(topics.reset_down);
2025-09-08 10:59:08 +08:00
}
static void on_mqtt_disconnected()
{
2025-09-08 16:40:04 +08:00
LOG_WARN("[MQTT] Disconnected from broker: " + g_app_config.mqtt.server_ip);
2025-09-08 10:59:08 +08:00
}
static void on_mqtt_message_received(const std::string &topic, const std::string &message)
{
LOG_INFO("[MQTT] Received message on topic [" + topic + "], len = " + std::to_string(message.size()));
2025-09-09 17:19:59 +08:00
LOG_INFO("[MQTT] Message content: " + message); // 打印实际内容
2025-09-08 10:59:08 +08:00
try
{
2025-09-09 09:57:24 +08:00
if (topic == g_app_config.mqtt.topics.video_down)
{
2025-09-09 10:25:16 +08:00
// 处理 video_down
2025-09-09 10:20:04 +08:00
auto j = nlohmann::json::parse(message);
2025-09-09 14:04:59 +08:00
if (!j.contains("data") || !j["data"].contains("status") || !j["data"].contains("seqNo"))
2025-09-09 10:20:04 +08:00
{
2025-09-09 14:04:59 +08:00
LOG_WARN("[MQTT] video_down JSON missing required fields");
2025-09-09 10:20:04 +08:00
return;
}
2025-09-09 16:45:54 +08:00
// 写 dispatchId 并设置 streaming 状态
2025-09-09 16:04:58 +08:00
{
2025-09-09 16:10:56 +08:00
std::lock_guard<std::mutex> lock(g_dispatch_id_mutex);
2025-09-09 16:45:54 +08:00
if (j["data"].contains("dispatchId"))
g_dispatch_id = j["data"]["dispatchId"].get<std::string>();
2025-09-09 16:04:58 +08:00
}
2025-09-09 10:20:04 +08:00
int status = j["data"]["status"].get<int>();
2025-09-09 16:45:54 +08:00
2025-09-09 14:04:59 +08:00
std::string seqNo = j["data"]["seqNo"].get<std::string>();
2025-09-09 16:45:54 +08:00
2025-09-09 13:58:13 +08:00
bool success = true; // 标记是否操作成功
2025-09-09 09:57:24 +08:00
2025-09-09 10:25:16 +08:00
if (status == 0)
2025-09-09 09:57:24 +08:00
{
2025-09-09 16:45:54 +08:00
g_streaming = true;
2025-11-21 15:23:37 +08:00
2025-09-09 09:57:24 +08:00
for (const auto &cam : g_app_config.cameras)
{
if (!cam.enabled)
continue;
2025-11-21 15:23:37 +08:00
// 不再提前卸载
2025-11-20 16:29:36 +08:00
RTSPManager::mount_camera(cam);
LOG_INFO("[MQTT] Started streaming: " + cam.name);
2025-09-09 09:57:24 +08:00
}
}
2025-09-09 10:25:16 +08:00
else if (status == 1)
2025-09-09 09:57:24 +08:00
{
2025-09-09 16:45:54 +08:00
g_streaming = false;
std::lock_guard<std::mutex> lock(g_dispatch_id_mutex);
g_dispatch_id.clear(); // 停止拉流就清空 dispatchId
2025-09-09 09:57:24 +08:00
// 停止推流:卸载本地配置中 enabled 的摄像头
for (const auto &cam : g_app_config.cameras)
{
if (!cam.enabled)
continue;
if (RTSPManager::is_streaming(cam.name))
{
RTSPManager::unmount_camera(cam);
LOG_INFO("[MQTT] Stopped streaming: " + cam.name);
}
}
}
else
{
LOG_WARN("[MQTT] video_down: unknown status value " + std::to_string(status));
2025-09-09 13:58:13 +08:00
success = false;
2025-09-09 09:57:24 +08:00
}
2025-09-09 13:58:13 +08:00
2025-09-09 14:16:18 +08:00
// 获取当前时间 yyyyMMddHHmmssSSS (UTC+8)
std::string time_str = Logger::get_current_time_utc8();
2025-09-09 13:58:13 +08:00
2025-09-09 15:07:51 +08:00
nlohmann::json reply_data;
reply_data["time"] = time_str;
reply_data["result"] = success ? 0 : 1;
reply_data["seqNo"] = seqNo;
// 封装外层
2025-09-09 13:58:13 +08:00
nlohmann::json reply;
2025-09-09 15:07:51 +08:00
reply["data"] = reply_data;
reply["isEnc"] = 0;
reply["type"] = 0;
2025-09-09 13:58:13 +08:00
// 发送应答
2025-09-09 14:00:50 +08:00
if (mqtt_client)
{
2025-09-09 17:06:43 +08:00
mqtt_client->publish(g_app_config.mqtt.topics.video_down_ack, reply.dump());
2025-09-09 14:00:50 +08:00
LOG_INFO("[MQTT] Replied to video_down: " + reply.dump());
}
2025-09-09 09:57:24 +08:00
}
else if (topic == g_app_config.mqtt.topics.substream_down)
{
// 处理 substream_down
LOG_INFO("[MQTT] substream_down message received (not implemented yet).");
}
else if (topic == g_app_config.mqtt.topics.reset_down)
{
2025-09-09 15:07:51 +08:00
auto j = nlohmann::json::parse(message);
// reset/down 的 payload 在 data 里
auto data = j.contains("data") ? j["data"] : nlohmann::json::object();
std::string seqNo = data.value("seqNo", "");
std::string errCode = data.value("errorCode", "");
std::string des = data.value("des", "");
LOG_WARN("[MQTT] Reset command received, errorCode=" + errCode + ", des=" + des);
2025-11-20 16:29:36 +08:00
// --- ★★ 新增:重置全局 streaming 状态与 dispatchId ---
g_streaming = false;
{
std::lock_guard<std::mutex> lock(g_dispatch_id_mutex);
g_dispatch_id.clear();
}
// ------------------------------------------------------
2025-09-09 15:07:51 +08:00
// 停止所有流,相当于复位
for (const auto &cam : g_app_config.cameras)
{
if (RTSPManager::is_streaming(cam.name))
{
RTSPManager::unmount_camera(cam);
LOG_INFO("[RTSP] Camera " + cam.name + " reset/unmounted");
}
}
// 组装应答 data
nlohmann::json reply_data;
reply_data["time"] = Logger::get_current_time_utc8();
reply_data["result"] = 0; // 0=成功
reply_data["seqNo"] = seqNo;
// 外层封装
nlohmann::json reply;
reply["data"] = reply_data;
reply["isEnc"] = 0;
reply["type"] = 0;
if (mqtt_client)
{
mqtt_client->publish(g_app_config.mqtt.topics.reset_down_ack, reply.dump());
LOG_INFO("[MQTT] Replied to reset_down: " + reply.dump());
}
2025-09-09 09:57:24 +08:00
}
else
{
LOG_WARN("[MQTT] Unknown topic: " + topic);
}
2025-09-08 10:59:08 +08:00
}
catch (const std::exception &e)
{
LOG_ERROR(std::string("[MQTT] Failed to process incoming JSON: ") + e.what());
}
}
void mqtt_client_thread_func()
{
2025-09-08 15:45:22 +08:00
const auto &cfg = g_app_config.mqtt;
2025-09-09 16:32:28 +08:00
auto heartbeat_interval = std::chrono::milliseconds(static_cast<int>(cfg.keep_alive * 0.9));
2025-09-08 15:09:33 +08:00
2025-09-08 15:45:22 +08:00
while (g_running)
{
2025-09-08 10:59:08 +08:00
mqtt_client = std::make_unique<MQTTClient>(cfg);
mqtt_client->setConnectCallback(on_mqtt_connected);
mqtt_client->setDisconnectCallback(on_mqtt_disconnected);
mqtt_client->setMessageCallback(on_mqtt_message_received);
2025-09-10 13:33:29 +08:00
// 等待连接
2025-09-10 10:34:36 +08:00
while (g_running && !mqtt_client->isConnected())
{
2025-09-10 13:33:29 +08:00
mqtt_client->connect();
2025-09-10 11:06:42 +08:00
for (int i = 0; i < 10 && g_running && !mqtt_client->isConnected(); i++)
2025-09-10 13:21:43 +08:00
std::this_thread::sleep_for(std::chrono::milliseconds(50));
2025-09-10 13:33:29 +08:00
if (!g_running && !mqtt_client->isConnected())
2025-09-10 13:21:43 +08:00
mqtt_client->force_disconnect();
2025-09-10 10:34:36 +08:00
}
2025-09-08 10:59:08 +08:00
2025-09-10 13:33:29 +08:00
// 主循环:心跳
2025-09-10 10:34:36 +08:00
while (g_running && mqtt_client->isConnected())
2025-09-08 10:59:08 +08:00
{
2025-09-10 13:33:29 +08:00
send_heartbeat();
2025-09-10 13:21:43 +08:00
2025-09-10 11:06:42 +08:00
auto sleep_time = heartbeat_interval;
while (sleep_time.count() > 0 && g_running && mqtt_client->isConnected())
{
2025-09-10 13:21:43 +08:00
auto chunk = std::min(sleep_time, std::chrono::milliseconds(50));
2025-09-10 11:06:42 +08:00
std::this_thread::sleep_for(chunk);
sleep_time -= chunk;
}
2025-09-10 13:21:43 +08:00
if (!g_running && mqtt_client->isConnected())
mqtt_client->force_disconnect();
2025-09-08 10:59:08 +08:00
}
2025-09-10 13:33:29 +08:00
// 清理
2025-09-10 11:06:42 +08:00
if (mqtt_client)
{
2025-09-10 11:18:29 +08:00
if (g_running)
mqtt_client->disconnect();
else
mqtt_client->force_disconnect();
2025-09-10 11:06:42 +08:00
mqtt_client.reset();
}
2025-09-10 11:18:29 +08:00
2025-09-08 10:59:08 +08:00
mqtt_restart_required = false;
2025-09-10 11:18:29 +08:00
if (!g_running)
break;
2025-09-10 13:33:29 +08:00
// 短暂等待再重连
2025-09-10 11:18:29 +08:00
for (int i = 0; i < 5 && g_running; i++)
std::this_thread::sleep_for(std::chrono::milliseconds(200));
2025-09-08 10:59:08 +08:00
}
2025-09-08 15:45:22 +08:00
LOG_INFO("[MQTT] Client thread exiting.");
2025-09-08 10:59:08 +08:00
}