kunlang_video/src/mqtt_client_wrapper.cpp

63 lines
1.7 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"
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-08 10:59:08 +08:00
// MQTT 回调定义
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
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()));
try
{
}
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-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);
mqtt_client->connect();
2025-09-08 15:45:22 +08:00
while (!mqtt_restart_required && g_running)
2025-09-08 10:59:08 +08:00
{
2025-09-08 15:59:15 +08:00
std::this_thread::sleep_for(std::chrono::milliseconds(100));
2025-09-08 10:59:08 +08:00
}
2025-09-08 15:45:22 +08:00
// 需要重启或退出
mqtt_client->disconnect();
2025-09-08 10:59:08 +08:00
mqtt_client.reset();
mqtt_restart_required = false;
}
2025-09-08 15:45:22 +08:00
LOG_INFO("[MQTT] Client thread exiting.");
2025-09-08 10:59:08 +08:00
}