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:
2026-07-17 14:14:55 +03:00
parent 959cb77d81
commit f41332a771
11 changed files with 172 additions and 2 deletions
@@ -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);
};
+47
View File
@@ -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
+6
View File
@@ -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}
+1
View File
@@ -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. |
+1
View File
@@ -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()`. |
+37
View File
@@ -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
// ════════════════════════════════════════════════════════════════════════════
+9
View File
@@ -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.