feat(Telemetry,FileManager,LoggingHandler): QA-to-shipping stats reset — telemetry.reset_boot_data + logs.clear
Console wants a "reset device stats before shipping" button for staff to clear QA-bench data (test reboots, debug log spam) without wiping actual device configuration. telemetry.reset_strikes and telemetry.reset_metrics already covered bell strikes and runtime/playback counters — this adds the two gaps: lifetime boot count + SD boot history, and SD debug logs. Deliberately does not touch FirmwareValidator's NVS namespace (rollback safety state, not history) or device identity NVS (serial/hw_family). Verified: pio run on all four board variants.
This commit is contained in:
@@ -66,6 +66,7 @@ Every feature — user-facing or significant internal mechanism — is listed he
|
||||
| F-054 | Console Health tab support — `free_heap` on heartbeat + `ping` round-trip timestamp echo | v2.1.4 | Stable |
|
||||
| F-055 | Fix: heap-exhaustion abort() under rapid MQTT command bursts — free-heap guard on publish + command intake | v2.1.4 | Stable |
|
||||
| F-056 | Diagnostics report — CPU temperature, WiFi reconnects, OTA state, stack high-water mark, published automatically every 5 min + on-demand via `telemetry.get_diagnostics` | v2.1.5 | Stable |
|
||||
| F-057 | QA-to-shipping stats reset — `telemetry.reset_boot_data` (lifetime boot count + SD boot log) and `logs.clear` (SD debug logs) | v2.1.6 | Stable |
|
||||
|
||||
---
|
||||
|
||||
@@ -900,3 +901,35 @@ Only temperature needed the local-sampling treatment; over-engineering a samplin
|
||||
**Scope note (RTC/SD independence):** unlike F-054's `ping` addition, none of these four metrics depend on `#if HAS_RTC` or SD-card presence — `temperatureRead()`, `uxTaskGetStackHighWaterMark()`, WiFi events, and `OTAManager` are all available on every board variant. Verified via `pio run` on all four environments (`vesper-std-v1`, `agnus-v1`, `agnus-mini-v1`, `bespoke-rs485-v1`).
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Networking/Networking.hpp`, `src/Networking/Networking.cpp`, `src/OTAManager/OTAManager.hpp`, `src/OTAManager/OTAManager.cpp`, `src/HealthMonitor/HealthMonitor.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-057 — QA-to-shipping stats reset: `telemetry.reset_boot_data` + `logs.clear`
|
||||
|
||||
Console-requested: a "reset device stats before shipping to customer" button, to clear data accumulated on the bench during QA (bell fires, melody playback, deliberate reboots) without wiping the device's actual configuration. Two commands cover the pieces that had no existing reset path — `telemetry.reset_strikes` (bell strikes) and `telemetry.reset_metrics` (runtime seconds + playback count) already existed and needed no changes.
|
||||
|
||||
**1. `telemetry.reset_boot_data`.** [Telemetry.hpp](../../src/Telemetry/Telemetry.hpp)/[.cpp](../../src/Telemetry/Telemetry.cpp) add `resetBootData()`, called by the new command in [TelemetryHandler.cpp](../../src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp). Does two things:
|
||||
- Zeroes the lifetime boot counter — both in RAM (`lifetimeBootCount`) and persisted (`nvs_set_u32(_bootNvsHandle, "lifetime_boots", 0)` + `nvs_commit()`, namespace `vesper_boot`).
|
||||
- Deletes `/telemetry_boot_log.json` (the SD-side rotating boot history) via `FileManager::deleteFile()`. Best-effort — a missing SD card or FileManager doesn't fail the command, since the NVS counter is the authoritative piece.
|
||||
|
||||
**Explicitly does NOT touch `FirmwareValidator`'s NVS namespace (`fw_validator`)** — `boot_count` there is validation-cycle/rollback-safety bookkeeping (boots since the current OTA slot was flashed), not a customer-facing "how many times has this device rebooted" stat. Wiping it would be pointless (not history) and could force an unwanted re-validation cycle. See the boot-tracking table in F-052 for why these two counters are kept structurally separate — this reset only ever touches the one meant to represent device history.
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "telemetry.reset_boot_data", "contents": {} }
|
||||
```
|
||||
Response: `{ "status": "SUCCESS", "type": "telemetry.reset_boot_data", "message": "Lifetime boot count and SD boot log reset" }` — or an error if the NVS write itself failed (SD-only failure is silent/best-effort, not surfaced as an error).
|
||||
|
||||
**2. `logs.clear`.** [FileManager.hpp](../../src/FileManager/FileManager.hpp)/[.cpp](../../src/FileManager/FileManager.cpp) add `deleteAllLogFiles(logDir)` — lists every file under `/logs` (the day-rotated SD debug log directory) via the same `SD.open()`/`openNextFile()` iteration `pruneLogDirectory()` already uses, then `SD.remove()`s each one. [LoggingHandler.cpp](../../src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp) wires this to a new `logs.clear` command.
|
||||
|
||||
**Not the same thing as automatic day-rotation pruning** (`FileManager::pruneLogDirectory()`, called from inside `appendLogLine()`) — that only trims the *oldest* files once the directory exceeds `SD_LOG_MAX_TOTAL_BYTES` (512KB), during normal operation, and is deliberately silent (no `LOG_*` calls, to avoid re-entering the SD log write path it's called from). `logs.clear` is a full wipe, invoked only via explicit command, and logs normally (`LOG_WARNING`) since it isn't called from that same nested write path.
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "logs.clear", "contents": {} }
|
||||
```
|
||||
Response: `{ "status": "SUCCESS", "type": "logs.clear", "data": { "deleted": 4 } }` — `deleted` is the file count actually removed. Returns an error only when no SD card/FileManager is present on this board variant (same degrade-gracefully pattern as `logs.list`/`logs.download`).
|
||||
|
||||
**What this feature does NOT reset** (by design — see the console-side plan for the full picture): `strikeCounters`/runtime seconds/playback count (already covered by the two pre-existing commands), NVS `device_id` (factory identity, never touched by any reset), NVS `fw_validator` (rollback safety state, not history), NVS `rf` (RF remote pairings — customer configuration, not QA noise), and anything `system.factory_reset` already covers (network/bell/clock config, melodies — a different, much broader operation).
|
||||
|
||||
Verified: `pio run` on all four environments.
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/FileManager/FileManager.hpp`, `src/FileManager/FileManager.cpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp`, `src/Communication/Handlers/LoggingHandler/LoggingHandler.hpp`, `src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp`
|
||||
|
||||
@@ -19,7 +19,7 @@ LoggingHandler::LoggingHandler(ConfigManager& configManager, FileManager* fileMa
|
||||
|
||||
std::vector<String> LoggingHandler::commands() const {
|
||||
return { "log.set_serial", "log.set_sd", "log.set_mqtt", "log.get_config",
|
||||
"logs.list", "logs.download" };
|
||||
"logs.list", "logs.download", "logs.clear" };
|
||||
}
|
||||
|
||||
CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) {
|
||||
@@ -29,6 +29,7 @@ CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "log.get_config") return handleGetConfig(envelope);
|
||||
if (envelope.command == "logs.list") return handleLogsList(envelope);
|
||||
if (envelope.command == "logs.download") return handleLogsDownload(envelope);
|
||||
if (envelope.command == "logs.clear") return handleLogsClear(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown log command");
|
||||
}
|
||||
|
||||
@@ -119,3 +120,20 @@ CommandResult LoggingHandler::handleLogsDownload(const CommandEnvelope& e) {
|
||||
result["eof"] = doc["eof"];
|
||||
return CommandResult::ok("logs.download", result);
|
||||
}
|
||||
|
||||
CommandResult LoggingHandler::handleLogsClear(const CommandEnvelope& e) {
|
||||
// Deletes every day-rotated SD debug log file — a QA-to-shipping reset,
|
||||
// not part of normal log rotation. Not to be confused with the day-
|
||||
// rotation pruning that already runs automatically in appendLogLine()
|
||||
// (that only trims oldest files once over budget, never clears everything).
|
||||
if (!_fileManager) {
|
||||
return CommandResult::err("logs.clear", "SD card not available on this device");
|
||||
}
|
||||
|
||||
size_t deleted = _fileManager->deleteAllLogFiles(SD_LOG_DIR);
|
||||
LOG_WARNING(TAG, "SD debug logs cleared via logs.clear command (%u file(s))", (unsigned)deleted);
|
||||
|
||||
JsonDocument result;
|
||||
result["deleted"] = deleted;
|
||||
return CommandResult::ok("logs.clear", result);
|
||||
}
|
||||
|
||||
@@ -21,4 +21,5 @@ private:
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
CommandResult handleLogsList(const CommandEnvelope& e);
|
||||
CommandResult handleLogsDownload(const CommandEnvelope& e);
|
||||
CommandResult handleLogsClear(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -14,7 +14,8 @@ std::vector<String> TelemetryHandler::commands() const {
|
||||
"telemetry.get_strikes", "telemetry.reset_strikes", "telemetry.get_loads",
|
||||
"telemetry.set_max_loads", "telemetry.set_guard_enabled",
|
||||
"telemetry.get_metrics", "telemetry.reset_metrics",
|
||||
"telemetry.get_boot_history", "telemetry.get_diagnostics"
|
||||
"telemetry.get_boot_history", "telemetry.get_diagnostics",
|
||||
"telemetry.reset_boot_data"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -28,6 +29,7 @@ CommandResult TelemetryHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "telemetry.reset_metrics") return handleResetMetrics(envelope);
|
||||
if (envelope.command == "telemetry.get_boot_history") return handleGetBootHistory(envelope);
|
||||
if (envelope.command == "telemetry.get_diagnostics") return handleGetDiagnostics(envelope);
|
||||
if (envelope.command == "telemetry.reset_boot_data") return handleResetBootData(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown telemetry command");
|
||||
}
|
||||
|
||||
@@ -162,3 +164,17 @@ CommandResult TelemetryHandler::handleGetDiagnostics(const CommandEnvelope& e) {
|
||||
|
||||
return CommandResult::ok("telemetry.get_diagnostics", doc);
|
||||
}
|
||||
|
||||
CommandResult TelemetryHandler::handleResetBootData(const CommandEnvelope& e) {
|
||||
// Zeroes the lifetime boot counter (NVS) and deletes the SD boot history
|
||||
// log — used before shipping a device to a customer, to clear reboot
|
||||
// counts accumulated during QA/bench testing. Console-side history in
|
||||
// device_boot_events (Postgres) is a separate reset, not touched here.
|
||||
bool ok = _telemetry.resetBootData();
|
||||
if (!ok) {
|
||||
return CommandResult::err("telemetry.reset_boot_data",
|
||||
"Failed to reset lifetime boot count in NVS");
|
||||
}
|
||||
LOG_WARNING(TAG, "Boot data reset via telemetry.reset_boot_data command");
|
||||
return CommandResult::ok("telemetry.reset_boot_data", "Lifetime boot count and SD boot log reset");
|
||||
}
|
||||
|
||||
@@ -30,4 +30,5 @@ private:
|
||||
CommandResult handleResetMetrics(const CommandEnvelope& e);
|
||||
CommandResult handleGetBootHistory(const CommandEnvelope& e);
|
||||
CommandResult handleGetDiagnostics(const CommandEnvelope& e);
|
||||
CommandResult handleResetBootData(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -430,6 +430,53 @@ void FileManager::pruneLogDirectory(const String& logDir, size_t maxTotalBytes)
|
||||
}
|
||||
}
|
||||
|
||||
size_t FileManager::deleteAllLogFiles(const String& logDir) {
|
||||
// Unlike pruneLogDirectory(), this is called from a command handler
|
||||
// (LoggingHandler::handleLogsClear), not from inside the SD log write
|
||||
// path — LOG_* here is safe and doesn't risk re-entering Logging::writeToSd().
|
||||
if (!initializeSD()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
File dir = SD.open(logDir.c_str());
|
||||
if (!dir || !dir.isDirectory()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::vector<String> names;
|
||||
File file = dir.openNextFile();
|
||||
while (file) {
|
||||
if (!file.isDirectory()) {
|
||||
names.push_back(file.name());
|
||||
}
|
||||
file = dir.openNextFile();
|
||||
}
|
||||
dir.close();
|
||||
|
||||
String dirPath = logDir;
|
||||
if (!dirPath.endsWith("/")) dirPath += "/";
|
||||
|
||||
size_t deleted = 0;
|
||||
for (const auto& rawName : names) {
|
||||
// Same normalization as pruneLogDirectory() — some cores return an
|
||||
// absolute path from file.name() rather than a bare basename.
|
||||
String name = rawName;
|
||||
int lastSlash = name.lastIndexOf('/');
|
||||
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
|
||||
|
||||
String fullPath = dirPath + name;
|
||||
if (SD.remove(fullPath.c_str())) {
|
||||
deleted++;
|
||||
} else {
|
||||
LOG_WARNING(TAG, "deleteAllLogFiles: failed to remove %s", fullPath.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
LOG_WARNING(TAG, "deleteAllLogFiles: removed %u of %u file(s) from %s",
|
||||
(unsigned)deleted, (unsigned)names.size(), logDir.c_str());
|
||||
return deleted;
|
||||
}
|
||||
|
||||
String FileManager::readLogChunkAsJson(const String& logDir, const String& fileName,
|
||||
size_t offset, size_t maxBytes) {
|
||||
// Reject path traversal / nested paths — fileName must be a bare filename
|
||||
|
||||
@@ -66,6 +66,12 @@ public:
|
||||
// List dated log files under logDir as JSON: {"files":[{"name":"2026-07-14.log","size":1234}, ...]}
|
||||
String listLogFilesAsJson(const String& logDir);
|
||||
|
||||
// Deletes every dated log file under logDir (e.g. all of "/logs"). Used
|
||||
// by logs.clear — a QA-to-shipping reset, not part of normal log rotation
|
||||
// (that's pruneLogDirectory(), which only trims oldest files over budget).
|
||||
// Returns the number of files actually deleted.
|
||||
size_t deleteAllLogFiles(const String& logDir);
|
||||
|
||||
// Read a bounded chunk of a log file for remote retrieval (paginated —
|
||||
// callers loop, feeding next_offset back in, until eof is true).
|
||||
// Returns JSON: {"data":"<raw text chunk>","next_offset":N,"eof":bool}
|
||||
|
||||
@@ -23,6 +23,7 @@ FileManager is the single access point for all SD card I/O in Vesper. It abstrac
|
||||
| `appendLine` | `bool appendLine(const String& filePath, const String& line)` | Opens a file in `FILE_APPEND` mode and writes `line` followed by `\n`. Does **not** create parent directories — callers must ensure the directory exists first (see `appendLogLine` below for the log-specific entry point that handles this). |
|
||||
| `appendLogLine` | `bool appendLogLine(const String& logDir, const String& line, time_t timestamp, size_t maxTotalBytes)` | Log-specific entry point used by the Logging subsystem's SD write callback. Ensures `logDir` exists, names the file `YYYY-MM-DD.log` from `timestamp` (or `unset-date.log` if `timestamp <= 0`, i.e. no wall clock yet), and prunes the oldest dated file(s) once the directory exceeds `maxTotalBytes`. See [Log file rotation](#log-file-rotation). |
|
||||
| `listLogFilesAsJson` | `String listLogFilesAsJson(const String& logDir)` | Returns `{"files":[{"name":"2026-07-14.log","size":1234}, ...]}` for dated log files under `logDir`. Backs the `logs.list` command. |
|
||||
| `deleteAllLogFiles` | `size_t deleteAllLogFiles(const String& logDir)` | Deletes every dated log file under `logDir`. Backs the `logs.clear` command — a QA-to-shipping reset, distinct from the automatic pruning in `appendLogLine` (see [Log file rotation](#log-file-rotation)), which only trims oldest files once over budget. Unlike pruning, this logs normally (`LOG_WARNING`) since it's invoked from a command handler, not from inside the SD write path. Returns the number of files actually removed. |
|
||||
| `readLogChunkAsJson` | `String readLogChunkAsJson(const String& logDir, const String& fileName, size_t offset, size_t maxBytes)` | Returns a bounded chunk of a log file: `{"data":"...","next_offset":N,"eof":bool}`. Rejects `fileName` values containing `/` or `..` (path traversal guard — `fileName` must be a bare name as returned by `listLogFilesAsJson`). Backs the `logs.download` command; callers loop, feeding `next_offset` back in as `offset`, until `eof` is `true`. |
|
||||
| `isHealthy` | `bool isHealthy() const` | Returns `true` if the ConfigManager pointer is set and `SD.cardType() != CARD_NONE`. Used by HealthMonitor. |
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ Telemetry tracks per-bell strike counts and thermal load to protect actuators fr
|
||||
| `bool isFaultReset() const` | Returns `true` if the captured reset reason indicates a fault: `ESP_RST_PANIC`, `ESP_RST_INT_WDT`, `ESP_RST_TASK_WDT`, `ESP_RST_WDT`, or `ESP_RST_BROWNOUT`. `false` for expected resets (power-on, software reset/OTA, deep sleep wake, etc). |
|
||||
| `String getResetReasonString() const` | Human-readable reset reason, e.g. `"PANIC"`, `"POWERON"`, `"TASK_WATCHDOG"`. |
|
||||
| `uint32_t getLifetimeBootCount() const` | NVS-backed count of every boot this device has ever done. The authoritative counter — see [Boot tracking](#boot-tracking) below for why this exists alongside two other, narrower counters. |
|
||||
| `bool resetBootData()` | Zeroes the lifetime boot counter (NVS `vesper_boot`) and deletes the SD boot history log (`/telemetry_boot_log.json`). Used by `telemetry.reset_boot_data` — a QA-to-shipping reset, see F-057 in the [feature catalog](../../docs/features/feature-catalog.md). Does NOT touch `FirmwareValidator`'s separate NVS namespace. Returns `false` only if the NVS write itself failed; the SD deletion is always best-effort. |
|
||||
| `const CrashReport& getCrashReport() const` | Coredump summary from the most recent crash, if one was found at `begin()`. `.available` is `false` when the last reset wasn't a crash, or no coredump was present for one that was. |
|
||||
| `void sampleDiagnosticsIfDue()` | Called from `TelemetryTask`'s existing 1s loop. Reads `temperatureRead()` every `DIAGNOSTICS_SAMPLE_INTERVAL_MS` (15s) and folds it into `temperatureStats`. See [Diagnostics reporting](#diagnostics-reporting) below. |
|
||||
| `const RunningStats& getTemperatureStats() const` | Current accumulated min/max/avg temperature since the last `resetDiagnosticsStats()`. |
|
||||
|
||||
@@ -380,6 +380,43 @@ void Telemetry::resetMetrics() {
|
||||
LOG_WARNING(TAG, "Telemetry metrics reset by user");
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// BOOT DATA RESET — clears the lifetime boot counter (NVS) and the SD-side
|
||||
// boot history log. Deliberately separate from FirmwareValidator's own NVS
|
||||
// namespace ("fw_validator") — that one is live rollback-safety state, not
|
||||
// "history," and must never be touched by this. See docs/features/
|
||||
// feature-catalog.md's boot-tracking table for why the two are kept distinct.
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool Telemetry::resetBootData() {
|
||||
bool nvsOk = true;
|
||||
if (_bootNvsHandle != 0) {
|
||||
esp_err_t err = nvs_set_u32(_bootNvsHandle, "lifetime_boots", 0);
|
||||
if (err == ESP_OK) err = nvs_commit(_bootNvsHandle);
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "Failed to reset lifetime boot count in NVS: %s", esp_err_to_name(err));
|
||||
nvsOk = false;
|
||||
}
|
||||
} else {
|
||||
nvsOk = false;
|
||||
}
|
||||
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
lifetimeBootCount = 0;
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
|
||||
// SD boot log — best-effort. Absent SD/FileManager isn't a failure of the
|
||||
// NVS reset (which is the authoritative counter); deleteFile() returning
|
||||
// false because the file never existed yet is also not an error worth
|
||||
// surfacing.
|
||||
if (fileManager) {
|
||||
fileManager->deleteFile("/telemetry_boot_log.json");
|
||||
}
|
||||
|
||||
LOG_WARNING(TAG, "Boot data reset by user (lifetime count + SD boot log)");
|
||||
return nvsOk;
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// RUNTIME PERSISTENCE
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -222,6 +222,15 @@ public:
|
||||
// "how many times has this device rebooted, ever."
|
||||
uint32_t getLifetimeBootCount() const { return lifetimeBootCount; }
|
||||
|
||||
// Resets the lifetime boot counter (NVS) to 0 and deletes the SD boot
|
||||
// history log — used before shipping a device to a customer, to clear
|
||||
// reboot counts accumulated during QA/bench testing. Does NOT touch
|
||||
// FirmwareValidator's separate "fw_validator" NVS namespace (rollback
|
||||
// safety state, not history). Returns false if the NVS write failed;
|
||||
// the SD-side deletion is always best-effort and doesn't affect the
|
||||
// return value.
|
||||
bool resetBootData();
|
||||
|
||||
// Most recent crash's coredump summary (task name, PC, exception cause/vaddr),
|
||||
// if one was captured. available == false when the last reset wasn't a crash,
|
||||
// or no coredump was found for one that was.
|
||||
|
||||
Reference in New Issue
Block a user