Files
xInfo/main/DashboardFetcher.cpp
T
2026-08-31 15:05:13 +08:00

74 lines
2.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file DashboardFetcher.cpp
* @brief 本地环境数据聚合器实现(无需后端服务)。
*/
#include "DashboardFetcher.h"
#include <cmath>
#include <cstdio>
#include <ctime>
#include "esp_log.h"
static const char *TAG = "DashboardFetcher";
DashboardFetcher::DashboardFetcher(SensorDriver &sensorDriver,
Dht11Driver &dht11Driver)
: sensorDriver_(sensorDriver), dht11Driver_(dht11Driver) {}
DashboardFetcher::~DashboardFetcher() {}
std::optional<DashboardData> DashboardFetcher::fetch() {
ESP_LOGI(TAG, "开始执行本地传感器采集与数据聚合...");
DashboardData data;
char buf[32];
// 1. 读取 DHT11 温湿度
float temp = NAN;
float humi = NAN;
bool dhtOk = dht11Driver_.read(temp, humi);
if (dhtOk && !std::isnan(temp)) {
snprintf(buf, sizeof(buf), "%.1f", temp);
data.temperature = buf;
}
if (dhtOk && !std::isnan(humi)) {
snprintf(buf, sizeof(buf), "%.1f", humi);
data.humidity = buf;
}
// 2. 读取 UART 空气质量传感器(CO2, TVOC, CH2O)
SensorReading air = sensorDriver_.read();
if (!std::isnan(air.co2) && air.co2 > 0) {
snprintf(buf, sizeof(buf), "%.0f", air.co2);
data.co2 = buf;
}
if (!std::isnan(air.tvoc) && air.tvoc >= 0) {
snprintf(buf, sizeof(buf), "%.2f", air.tvoc);
data.tvoc = buf;
}
if (!std::isnan(air.ch2o) && air.ch2o >= 0) {
snprintf(buf, sizeof(buf), "%.3f", air.ch2o);
data.ch2o = buf;
}
// 3. 读取本地系统时间(通过 NTP 同步)
time_t now = time(nullptr);
struct tm timeinfo;
localtime_r(&now, &timeinfo);
if (timeinfo.tm_year >= (2020 - 1900)) {
snprintf(buf, sizeof(buf), "%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min);
data.lastReport = buf;
} else {
data.lastReport = "--:--";
}
ESP_LOGI(TAG, "本地数据聚合完成: 温度=%s, 湿度=%s, CO2=%s, TVOC=%s, CH2O=%s, 时间=%s",
data.temperature.c_str(), data.humidity.c_str(),
data.co2.c_str(), data.tvoc.c_str(), data.ch2o.c_str(),
data.lastReport.c_str());
return data;
}