bonus-edge-proxy/src/mqtt/handler/data_handler.cpp

26 lines
1.0 KiB
C++
Raw Normal View History

2025-10-13 13:55:15 +08:00
#include "data_handler.h"
#include "spdlog/spdlog.h"
#include "vendor/nlohmann/json.hpp"
using json = nlohmann::json;
DataHandler::DataHandler(MqttClient& client) : m_client(client) {}
void DataHandler::handle(mqtt::const_message_ptr msg) {
spdlog::info("DataHandler is processing message from topic: {}", msg->get_topic());
try {
// (这里是原来 MqttRouter 中处理数据上报的逻辑)
auto received_json = json::parse(msg->get_payload_str());
if (received_json.contains("temperature")) {
double temp = received_json["temperature"];
json forward_json;
forward_json["source_topic"] = msg->get_topic();
forward_json["processed_temp"] = temp;
forward_json["timestamp"] = time(0);
const std::string output_topic = "proxy/processed/temperature";
m_client.publish(output_topic, forward_json.dump());
}
} catch (const json::parse_error& e) {
spdlog::error("JSON parse error in DataHandler: {}", e.what());
}
}