feat(ota): 会话 epoch/通道标识 + BLE 中止命令 + NVS 线程安全

- 新增 ota_channel_t(WiFi/BLE) + m_otaEpoch 会话代次,
  abortCurrentIfEpoch 防止同类型重启后旧 handler 误清新会话
- 同通道再次发起 OTA 时自动中止旧会话并重开
- 统一 prepareGd32Storage(validate+begin+erase+meta),
  消除 BLE/WiFi 两路径隐式差异
- OtaRelay 拆分子步骤(doRelayPackets/doFinishAndVerify),
  状态成员私有化消除数据竞争
- Gd32FlashStore NVS 读写加 mutex,metaUpdate 原子化
- BLE OTA 新增 0xFB 中止命令(保持连接)+ 0x20 ABORTED 处理
- HTTP handler 改 per-request buffer 支持并发
- 修复 CRITICAL 状态 RSSI 恢复无法降级的缺陷
- main.cpp 关键任务失败触发看门狗重启
- style.css 增强动画 + prefers-reduced-motion 兼容
This commit is contained in:
小龙虾
2026-06-28 04:32:18 +08:00
parent 6ef97307c3
commit a93dba60d2
41 changed files with 3142 additions and 6349 deletions
+35 -5
View File
@@ -1,4 +1,4 @@
/*
/*
* debug_log.cpp - 调试日志输出实现
*
* 日志会同时写入三处:
@@ -120,6 +120,8 @@ char* DebugLog::ringDrainJson(int *out_len)
int count = ringCount();
int capacity = count * (LOG_RING_SIZE * 2) + 16;
if (capacity < 16) capacity = 16;
// 当 count 较大(如 64)时 capacity 可能达 32KB+,单次 malloc 有风险。
// 当前为简化实现保留单次 malloc;若后续日志量增大,可改为按 8KB 分块 realloc。
char *buf = (char*)malloc(capacity);
if (!buf) return NULL;
@@ -130,10 +132,22 @@ char* DebugLog::ringDrainJson(int *out_len)
int entryLen = 0;
while (ringPopOldest(entry, sizeof(entry), &entryLen) && entryLen > 0) {
if (!first) buf[pos++] = ',';
// 逗号写入前做边界检查,预留 4 字节给 ']' + '\0' 及末尾余量
if (!first) {
if (pos + 1 >= capacity - 4) break;
buf[pos++] = ',';
}
first = false;
buf[pos++] = '"';
// 单条日志转义后超过 LOG_RING_SIZE * 2 时截断,标记 "..." 后缀
int content_start = pos;
bool truncated = false;
for (int i = 0; i < entryLen && pos < capacity - 4; i++) {
if (pos - content_start >= LOG_RING_SIZE * 2) {
truncated = true;
break;
}
char c = entry[i];
if (c == '"') { buf[pos++] = '\\'; buf[pos++] = '"'; }
else if (c == '\\') { buf[pos++] = '\\'; buf[pos++] = '\\'; }
@@ -142,6 +156,14 @@ char* DebugLog::ringDrainJson(int *out_len)
else if (c == '\t') { buf[pos++] = '\\'; buf[pos++] = 't'; }
else if ((unsigned char)c >= 0x20) { buf[pos++] = c; }
}
if (truncated) {
// 确保 "..." + '"' + ']' + '\0' (共 6 字节) 有空间才写入标记
if (pos + 6 <= capacity) {
buf[pos++] = '.';
buf[pos++] = '.';
buf[pos++] = '.';
}
}
buf[pos++] = '"';
}
buf[pos++] = ']';
@@ -216,6 +238,8 @@ esp_err_t DebugLog::uartInit()
}
m_uartInitialized = true;
// 标记 UART 真正可用,send() 依据此标志决定是否调用 uart_write_bytes
m_uartAvailable = true;
ESP_LOGD(TAG, "UART0 调试输出已初始化 (TX=GPIO%d, RX=GPIO%d, %d baud)",
UART_DEBUG_TX_GPIO, UART_DEBUG_RX_GPIO, UART_DEBUG_BAUD_RATE);
@@ -255,7 +279,13 @@ esp_err_t DebugLog::init()
return ESP_OK;
}
uartInit();
// 检查 uartInit 返回值;失败时仍让 ring buffer 模式工作,
// 但记录"UART 不可用"日志,并在 send() 中跳过 uart_write_bytes 调用。
esp_err_t uart_ret = uartInit();
if (uart_ret != ESP_OK) {
ESP_LOGW(TAG, "UART 不可用,仅 ring buffer 模式 (err=%s)", esp_err_to_name(uart_ret));
m_uartAvailable = false;
}
m_logRingMutex = xSemaphoreCreateMutex();
@@ -302,8 +332,8 @@ esp_err_t DebugLog::send(const uint8_t *data, size_t len)
esp_err_t udp_ret = ESP_FAIL;
esp_err_t uart_ret = ESP_FAIL;
// UART 通道
if (m_uartInitialized) {
// UART 通道(UART 不可用时跳过 uart_write_bytes 调用)
if (m_uartAvailable) {
uart_ret = uartSend(data, len);
}
+4 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* debug_log.h - 调试日志输出
*
* 当前日志会并行写入:
@@ -95,6 +95,9 @@ private:
struct sockaddr_in m_debugAddr;
bool m_initialized = false;
bool m_uartInitialized = false;
// 记录 UART 是否真正可用(uartInit 失败时为 false,跳过 uart_write_bytes)。
// m_uartInitialized 仅表示曾尝试初始化,m_uartAvailable 才是写日志的判据。
bool m_uartAvailable = false;
static constexpr int LOG_RING_SLOTS = 64;
static constexpr int LOG_RING_SIZE = 256;
+47 -24
View File
@@ -1,4 +1,4 @@
/*
/*
* health_monitor.cpp - 系统健康监控
* 包含:健康状态管理 + WiFi RSSI 监控 + 温度监控
*
@@ -46,6 +46,21 @@ void HealthMonitor::init()
}
}
/**
* @brief 反初始化:停止并删除温度监控定时器,回收 esp_timer 资源。
* 当前 HealthMonitor 任务为无限循环,无显式删除路径,
* 本方法预留给未来停用场景(如安全关机后停止监控)使用。
*/
void HealthMonitor::deinit()
{
if (m_tempTimer != nullptr) {
esp_timer_stop(m_tempTimer);
esp_timer_delete(m_tempTimer);
m_tempTimer = nullptr;
DEBUG_INFO("HEALTH", "温度监控定时器已停止并删除");
}
}
// ============================================================
// 线程安全的健康状态读写
// ============================================================
@@ -55,10 +70,8 @@ void HealthMonitor::init()
*/
health_state_t HealthMonitor::getState()
{
if (m_mutex) xSemaphoreTake(m_mutex, portMAX_DELAY);
health_state_t s = m_healthState;
if (m_mutex) xSemaphoreGive(m_mutex);
return s;
LockGuard lock(m_mutex);
return m_healthState;
}
/**
@@ -67,9 +80,8 @@ health_state_t HealthMonitor::getState()
*/
void HealthMonitor::setState(health_state_t newState)
{
if (m_mutex) xSemaphoreTake(m_mutex, portMAX_DELAY);
LockGuard lock(m_mutex);
m_healthState = newState;
if (m_mutex) xSemaphoreGive(m_mutex);
}
// ============================================================
@@ -90,10 +102,8 @@ health_state_t HealthMonitor::getCurrent()
*/
float HealthMonitor::getLastTemperature()
{
if (m_mutex) xSemaphoreTake(m_mutex, portMAX_DELAY);
float t = m_lastTemperature;
if (m_mutex) xSemaphoreGive(m_mutex);
return t;
LockGuard lock(m_mutex);
return m_lastTemperature;
}
/**
@@ -104,10 +114,13 @@ float HealthMonitor::getLastTemperature()
*/
bool HealthMonitor::getLastWifiRssi(int8_t *out_rssi, uint32_t *out_age_ms)
{
if (m_mutex) xSemaphoreTake(m_mutex, portMAX_DELAY);
int64_t lastMs = m_lastWifiRssiMs;
int8_t rssi = m_lastWifiRssi;
if (m_mutex) xSemaphoreGive(m_mutex);
int64_t lastMs;
int8_t rssi;
{
LockGuard lock(m_mutex);
lastMs = m_lastWifiRssiMs;
rssi = m_lastWifiRssi;
}
if (lastMs <= 0) {
return false;
@@ -138,9 +151,10 @@ void HealthMonitor::tempMonitorCallback(void *arg)
return;
}
if (self.m_mutex) xSemaphoreTake(self.m_mutex, portMAX_DELAY);
self.m_lastTemperature = temp;
if (self.m_mutex) xSemaphoreGive(self.m_mutex);
{
LockGuard lock(self.m_mutex);
self.m_lastTemperature = temp;
}
if (temp >= TEMP_CRITICAL) {
self.setState(SYS_SAFE_SHUTDOWN);
@@ -180,17 +194,17 @@ void HealthMonitor::taskEntry(void *pvParameters)
}
// 定时器,每1秒读取一次温度
esp_timer_handle_t temp_timer;
esp_timer_create_args_t timer_args = {};
timer_args.callback = &tempMonitorCallback;
timer_args.arg = nullptr;
timer_args.name = "temp_monitor";
timer_args.dispatch_method = ESP_TIMER_TASK;
if (esp_timer_create(&timer_args, &temp_timer) == ESP_OK) {
esp_timer_start_periodic(temp_timer, 1000000); // 1秒
if (esp_timer_create(&timer_args, &self.m_tempTimer) == ESP_OK) {
esp_timer_start_periodic(self.m_tempTimer, 1000000); // 1秒
DEBUG_INFO("MON", "温度监控定时器已启动 (1秒间隔)");
} else {
self.m_tempTimer = nullptr;
DEBUG_ERR("MON", "创建温度监控定时器失败");
}
@@ -246,7 +260,12 @@ health_status_t HealthMonitor::checkBeforeOta()
DEBUG_WARN("HEALTH", "OTA 前检查: SYS_WARNING,继续传输但需注意");
}
if (!m_wifiConnected) {
bool wifi_connected;
{
LockGuard lock(m_mutex);
wifi_connected = m_wifiConnected;
}
if (!wifi_connected) {
DEBUG_WARN("HEALTH", "OTA 前检查: WiFi 未连接");
return HEALTH_MON_CRITICAL;
}
@@ -320,6 +339,7 @@ health_status_t HealthMonitor::checkBeforeOtaRelay()
*/
void HealthMonitor::setWifiConnected(bool connected)
{
LockGuard lock(m_mutex);
m_wifiConnected = connected;
}
@@ -348,10 +368,13 @@ health_status_t HealthMonitor::updateFromWifiRssi(int8_t rssi)
return HEALTH_MON_WARNING;
}
// RSSI 已恢复正常(>= WIFI_RSSI_NORMAL):从 WARNING 或 CRITICAL 任一状态降级到 NORMAL。
// 历史缺陷:原仅当 cur == SYS_WARNING 时降级,导致 CRITICAL 状态下 RSSI 恢复正常无法降级。
// 注意:SAFE_SHUTDOWN 不应被 RSSI 恢复降级,仅处理 WARNING/CRITICAL。
health_state_t cur = getState();
if (cur == SYS_WARNING && rssi >= WIFI_RSSI_NORMAL) {
if ((cur == SYS_WARNING || cur == SYS_CRITICAL) && rssi >= WIFI_RSSI_NORMAL) {
setState(SYS_NORMAL);
DEBUG_INFO("HEALTH", "WiFi RSSI 恢复: %d dBm >= %d dBm", rssi, WIFI_RSSI_NORMAL);
DEBUG_INFO("HEALTH", "WiFi RSSI 恢复: %d dBm >= %d dBm (从 %d 降级)", rssi, WIFI_RSSI_NORMAL, (int)cur);
logEvent("WIFI恢复", rssi);
}
+29 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* health_monitor.h - 系统健康监控头文件
*
* HealthMonitor 类封装健康状态管理、温度监控和 WiFi RSSI 监控。
@@ -10,6 +10,7 @@
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "driver/temperature_sensor.h"
#include "esp_timer.h"
#include "app_config.h"
// T9.3: 健康状态等级
@@ -48,6 +49,13 @@ public:
/** @brief 初始化健康监控模块,创建内部互斥锁与基础状态。 */
void init();
/**
* @brief 反初始化:停止并删除温度监控定时器,回收 esp_timer 资源。
* 在任务删除路径中调用;当前 HealthMonitor 任务为无限循环,
* 无显式删除路径,本方法预留给未来停用场景使用。
*/
void deinit();
/** @brief 健康监控 FreeRTOS 任务入口。 */
static void taskEntry(void *pvParameters);
@@ -97,12 +105,32 @@ private:
SemaphoreHandle_t m_mutex = NULL;
temperature_sensor_handle_t m_tempHandle = NULL;
// 温度监控 esp_timer 句柄存为成员,便于 deinit() 时停止并删除定时器,
// 避免任务被删除后定时器仍在运行、回调继续访问 instance() 成员。
esp_timer_handle_t m_tempTimer = nullptr;
health_state_t m_healthState = SYS_NORMAL;
float m_lastTemperature = 0.0f;
int8_t m_lastWifiRssi = -127;
int64_t m_lastWifiRssiMs = 0;
TaskHandle_t m_taskHandle = NULL;
// m_wifiConnected 由 m_mutex 保护(setWifiConnected 写 / checkBeforeOta 读)。
// volatile 保留为历史兼容,实际同步由 LockGuard 提供。
volatile bool m_wifiConnected = false; ///< WiFi 连接状态(由 WiFi 事件推送)
static void tempMonitorCallback(void *arg);
// RAII 锁守卫(与 SpiMaster::LockGuard 风格一致)
class LockGuard {
public:
explicit LockGuard(SemaphoreHandle_t mutex) : m_lock(mutex) {
if (m_lock) { xSemaphoreTake(m_lock, portMAX_DELAY); }
}
~LockGuard() {
if (m_lock) { xSemaphoreGive(m_lock); }
}
LockGuard(const LockGuard&) = delete;
LockGuard& operator=(const LockGuard&) = delete;
private:
SemaphoreHandle_t m_lock;
};
};