// 文件名: src/web/web_server.cc #include "web_server.h" #include "spdlog/spdlog.h" // 构造函数现在需要调用基类的构造函数 WebServer::WebServer(SystemMonitor::SystemMonitor& monitor, DeviceManager& deviceManager, LiveDataCache& liveDataCache,uint16_t port) // 注意基类已经改为 crow::Crow() : crow::Crow(), m_monitor(monitor), m_device_manager(deviceManager), m_live_data_cache(liveDataCache), m_port(port) { // ================= [ 新增 CORS 配置 ] ================= // 获取 CORS 中间件的引用 auto& cors = this->get_middleware(); cors .global() .origin("*") .headers("Content-Type", "Authorization") .methods("GET"_method, "POST"_method, "OPTIONS"_method); // ========================================================== // 设置日志级别 this->loglevel(crow::LogLevel::Warning); setup_routes(); } WebServer::~WebServer() { stop(); } void WebServer::start() { if (m_thread.joinable()) { spdlog::warn("Web server is already running."); return; } m_thread = std::thread([this]() { spdlog::info("Starting Web server on port {}", m_port); this->port(m_port).run(); spdlog::info("Web server has stopped."); }); } void WebServer::stop() { // 您的 Bug 修正非常正确,这里保持不变 crow::Crow::stop(); if (m_thread.joinable()) { m_thread.join(); } } void WebServer::setup_routes() { // ================= [ 系统状态获取 API ] ================= CROW_ROUTE((*this), "/api/system/status").methods("GET"_method) ([this] { auto cpu_util = m_monitor.getCpuUtilization(); auto mem_info = m_monitor.getMemoryInfo(); crow::json::wvalue response; response["cpu_usage_percentage"] = cpu_util.totalUsagePercentage; response["memory_total_kb"] = mem_info.total_kb; response["memory_free_kb"] = mem_info.available_kb; response["memory_usage_percentage"] = (mem_info.total_kb > 0) ? (1.0 - static_cast(mem_info.available_kb) / mem_info.total_kb) * 100.0 : 0.0; return response; }); CROW_ROUTE((*this), "/api/devices").methods("GET"_method) ([this] { // 这一行不变,从 DeviceManager 获取最新的设备信息 auto devices_info = m_device_manager.get_all_device_info(); std::vector devices_json; for (const auto& info : devices_info) { crow::json::wvalue device_obj; // 1. 直接映射的字段 device_obj["id"] = info.id; device_obj["type"] = info.type; device_obj["is_running"] = info.is_running; // 2. 将 std::map 转换为一个内嵌的 JSON 对象 crow::json::wvalue details_obj; for (const auto& pair : info.connection_details) { details_obj[pair.first] = pair.second; } device_obj["connection_details"] = std::move(details_obj); devices_json.push_back(std::move(device_obj)); } return crow::json::wvalue(devices_json); }); // ================= [ 新增实时数据 API ] ================= CROW_ROUTE((*this), "/api/data/latest").methods("GET"_method) ([this] { // 从缓存中获取所有设备的最新数据 auto latest_data_map = m_live_data_cache.get_all_data(); crow::json::wvalue response; for (const auto& pair : latest_data_map) { // pair.first 是 device_id (string) // pair.second 是 json_data (string) // 我们需要将 json_data 字符串再次解析为 crow 的 json 对象 response[pair.first] = crow::json::load(pair.second); } return response; }); }