fix(FileManager,Logging): day-rotated SD logs + boot reset-reason reporting

SD logging was a silent no-op on fresh cards: appendLine() opened /logs/vesper.log
in FILE_APPEND without ever creating the /logs directory first. FileManager now
exposes appendLogLine(), which creates the directory, rotates to YYYY-MM-DD.log
files, and prunes oldest files once a 512KB total budget is exceeded.

LoggingHandler gains logs.list / logs.download commands (chunked, paginated) so
SD logs can be pulled off a device remotely for offline-device troubleshooting.

Telemetry now captures esp_reset_reason() at boot and classifies it as a fault
(panic/watchdog/brownout) or an expected reset (power-on/software/deep sleep).
CommunicationRouter reports it once MQTT connects: faults go to status/alerts,
expected resets go to status/info (type: boot_reason). MQTTDriver gained a
setOnConnectCallback hook to support this.

F-045, F-046, F-048 in the feature catalog.
This commit is contained in:
2026-07-15 00:04:21 +03:00
parent 399b4d056c
commit 2b4fd7c5b0
16 changed files with 419 additions and 22 deletions
@@ -6,9 +6,14 @@
*/ */
#include "CommunicationRouter.hpp" #include "CommunicationRouter.hpp"
#include <time.h>
#define TAG "CommRouter" #define TAG "CommRouter"
// Total size budget for /logs on SD, across all rotated daily files.
// Oldest day is pruned first once this is exceeded.
static constexpr size_t SD_LOG_MAX_TOTAL_BYTES = 512 * 1024; // 512KB
#include "../../ConfigManager/ConfigManager.hpp" #include "../../ConfigManager/ConfigManager.hpp"
#include "../../OTAManager/OTAManager.hpp" #include "../../OTAManager/OTAManager.hpp"
#include "../../Networking/Networking.hpp" #include "../../Networking/Networking.hpp"
@@ -124,6 +129,10 @@ void CommunicationRouter::begin() {
Logging::setSubsystemMqttLevel("Telemetry", Logging::INFO); // load data useful Logging::setSubsystemMqttLevel("Telemetry", Logging::INFO); // load data useful
Logging::setSubsystemMqttLevel("OTAManager", Logging::INFO); // update events important Logging::setSubsystemMqttLevel("OTAManager", Logging::INFO); // update events important
_mqttClient.setOnConnectCallback([this](bool /*sessionPresent*/) {
reportBootReasonOnce();
});
LOG_INFO(TAG, "MQTT transport initialised"); LOG_INFO(TAG, "MQTT transport initialised");
// ── HTTP ───────────────────────────────────────────────────────────────── // ── HTTP ─────────────────────────────────────────────────────────────────
@@ -191,9 +200,11 @@ void CommunicationRouter::setFileManagerReference(FileManager* fm) {
if (fm != nullptr) { if (fm != nullptr) {
Logging::setSdWriteCallback([fm](const String& line) { Logging::setSdWriteCallback([fm](const String& line) {
fm->appendLine("/logs/vesper.log", line); // Day-rotated: /logs/YYYY-MM-DD.log, capped at SD_LOG_MAX_TOTAL_BYTES
// total across the directory (oldest day pruned first).
fm->appendLogLine("/logs", line, time(nullptr), SD_LOG_MAX_TOTAL_BYTES);
}); });
LOG_INFO(TAG, "SD log channel registered -> /logs/vesper.log"); LOG_INFO(TAG, "SD log channel registered -> /logs/YYYY-MM-DD.log (cap: %u bytes)", (unsigned)SD_LOG_MAX_TOTAL_BYTES);
} }
} }
@@ -281,8 +292,8 @@ void CommunicationRouter::registerHandlers() {
_bus.registerHandler(std::make_unique<FileHandler>(*_fileManager)); _bus.registerHandler(std::make_unique<FileHandler>(*_fileManager));
} }
// Logging — no optional dependencies // Logging — FileManager optional; logs.list/logs.download degrade gracefully without it
_bus.registerHandler(std::make_unique<LoggingHandler>(_configManager)); _bus.registerHandler(std::make_unique<LoggingHandler>(_configManager, _fileManager));
// Telemetry // Telemetry
if (_telemetry) { if (_telemetry) {
@@ -489,6 +500,23 @@ void CommunicationRouter::publishAlert(const String& subsystem, const String& ne
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str()); LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
} }
void CommunicationRouter::reportBootReasonOnce() {
if (_bootReasonReported || !_telemetry) return;
_bootReasonReported = true;
String reason = _telemetry->getResetReasonString();
if (_telemetry->isFaultReset()) {
publishAlert("System", "WARNING", "Device reset due to fault: " + reason);
LOG_WARNING(TAG, "Fault reset reported: %s", reason.c_str());
} else {
JsonDocument payload;
payload["reason"] = reason;
publishInfo("boot_reason", payload);
LOG_INFO(TAG, "Boot reason reported: %s", reason.c_str());
}
}
void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) { void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) {
if (!_mqttClient.isConnected()) return; if (!_mqttClient.isConnected()) return;
@@ -138,6 +138,13 @@ public:
void onNetworkDisconnected(); void onNetworkDisconnected();
private: private:
// Reports the boot reset reason once, the first time MQTT connects after
// startup. Fault reasons (panic/watchdog/brownout) go to status/alerts;
// expected reasons (power-on, software reset, deep sleep wake) go to
// status/info. Registered as MQTTDriver's onConnect callback in begin().
void reportBootReasonOnce();
bool _bootReasonReported = false;
// ── External dependencies (injected) ──────────────────────────────────── // ── External dependencies (injected) ────────────────────────────────────
ConfigManager& _configManager; ConfigManager& _configManager;
OTAManager& _otaManager; OTAManager& _otaManager;
@@ -21,7 +21,7 @@
| Method | Description | | Method | Description |
|--------|-------------| |--------|-------------|
| `void setPlayerReference(Player*)` | Required for PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler. | | `void setPlayerReference(Player*)` | Required for PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler. |
| `void setFileManagerReference(FileManager*)` | Required for FileHandler; also wires the SD log channel into `Logging`. | | `void setFileManagerReference(FileManager*)` | Required for FileHandler and for `logs.list`/`logs.download` on LoggingHandler; also wires the day-rotated SD log channel into `Logging` (`/logs/YYYY-MM-DD.log`, capped at `SD_LOG_MAX_TOTAL_BYTES` — 512KB — across the directory). |
| `void setTimeKeeperReference(Timekeeper*)` | Required for ClockHandler, SystemHandler. | | `void setTimeKeeperReference(Timekeeper*)` | Required for ClockHandler, SystemHandler. |
| `void setFirmwareValidatorReference(FirmwareValidator*)` | Required for FirmwareHandler. | | `void setFirmwareValidatorReference(FirmwareValidator*)` | Required for FirmwareHandler. |
| `void setTelemetryReference(Telemetry*)` | Required for TelemetryHandler, SystemHandler. | | `void setTelemetryReference(Telemetry*)` | Required for TelemetryHandler, SystemHandler. |
@@ -49,8 +49,8 @@
| `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. | | `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. |
| `void publishToMqtt(const String& data)` | Publishes to the device data topic. No-op if MQTT is not connected. | | `void publishToMqtt(const String& data)` | Publishes to the device data topic. No-op if MQTT is not connected. |
| `void sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity)` | Builds and broadcasts a structured `bell_overload` INFO event. | | `void sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity)` | Builds and broadcasts a structured `bell_overload` INFO event. |
| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`. No-op if MQTT is not connected. | | `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootReasonOnce()` for fault reset reasons. No-op if MQTT is not connected. |
| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. | | `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. Used for e.g. `"boot_reason"` events on expected resets. |
### Network callbacks (called by Networking) ### Network callbacks (called by Networking)
@@ -118,5 +118,6 @@ If any required reference is null when `registerHandlers()` runs (inside `begin(
- **`server.begin()` is deferred**: The `AsyncWebServer` is not started inside `begin()` — it is started in the `onNetworkConnected` callback in `main.cpp`. This prevents a port 80 conflict when WiFiManager's captive portal is active. - **`server.begin()` is deferred**: The `AsyncWebServer` is not started inside `begin()` — it is started in the `onNetworkConnected` callback in `main.cpp`. This prevents a port 80 conflict when WiFiManager's captive portal is active.
- **`loop()` must be called**: `UARTTransport` is the only transport that requires polling. `CommunicationRouter::loop()` delegates to it. All other transports are fully event-driven. - **`loop()` must be called**: `UARTTransport` is the only transport that requires polling. `CommunicationRouter::loop()` delegates to it. All other transports are fully event-driven.
- **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink. - **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink.
- **Boot reason reporting**: `begin()` registers a one-shot `onConnect` callback on `MQTTDriver` (`reportBootReasonOnce()`) that fires the first time MQTT connects after startup (including the very first connection). It reads `Telemetry::getResetReasonString()`/`isFaultReset()` and routes to `publishAlert` (fault reasons: panic, watchdog, brownout) or `publishInfo` (expected reasons: power-on, software reset, deep sleep wake). Guarded by `_bootReasonReported` so it only fires once per boot, not on every reconnect.
- **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out. They are separate paths; subsystems outside the communication layer use the router's helpers. - **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out. They are separate paths; subsystems outside the communication layer use the router's helpers.
- **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`. - **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`.
@@ -238,6 +238,10 @@ void MQTTDriver::onMqttConnect(bool sessionPresent) {
// 🔥 Start heartbeat timer // 🔥 Start heartbeat timer
startHeartbeat(); startHeartbeat();
if (_onConnectCallback) {
_onConnectCallback(sessionPresent);
}
} }
void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
@@ -17,6 +17,7 @@
#include <Arduino.h> #include <Arduino.h>
#include <AsyncMqttClient.h> #include <AsyncMqttClient.h>
#include <functional>
class ConfigManager; class ConfigManager;
class Networking; class Networking;
@@ -72,6 +73,13 @@ public:
*/ */
void setCallback(MessageCallback callback); void setCallback(MessageCallback callback);
/**
* @brief Set a callback fired once each time MQTT successfully connects
* (including reconnects). Used for one-shot "publish now that we're
* online" work like reporting the boot/reset reason.
*/
void setOnConnectCallback(std::function<void(bool sessionPresent)> callback) { _onConnectCallback = callback; }
/** /**
* @brief Check if connected to MQTT broker * @brief Check if connected to MQTT broker
*/ */
@@ -96,6 +104,7 @@ private:
Networking& _networking; Networking& _networking;
AsyncMqttClient _mqttClient; AsyncMqttClient _mqttClient;
MessageCallback _messageCallback; MessageCallback _messageCallback;
std::function<void(bool sessionPresent)> _onConnectCallback;
// Device topic strings (cached for performance) // Device topic strings (cached for performance)
@@ -26,6 +26,7 @@ Topics:
| `const String& getAlertsTopic() const` | Returns the cached `vesper/{uid}/status/alerts` topic string. Available after `begin()`. | | `const String& getAlertsTopic() const` | Returns the cached `vesper/{uid}/status/alerts` topic string. Available after `begin()`. |
| `const String& getInfoTopic() const` | Returns the cached `vesper/{uid}/status/info` topic string. Available after `begin()`. | | `const String& getInfoTopic() const` | Returns the cached `vesper/{uid}/status/info` topic string. Available after `begin()`. |
| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. | | `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. |
| `void setOnConnectCallback(std::function<void(bool sessionPresent)> callback)` | Registers a callback fired once each time MQTT successfully connects (including reconnects). Used by `CommunicationRouter` for one-shot "publish now that we're online" work such as reporting the boot/reset reason. |
| `bool isConnected() const` | Returns the AsyncMqttClient connection state. | | `bool isConnected() const` | Returns the AsyncMqttClient connection state. |
| `void onNetworkConnected()` | Starts the 2-second network-stabilisation timer; connects after it fires. Resets `_reconnectAttempts`. | | `void onNetworkConnected()` | Starts the 2-second network-stabilisation timer; connects after it fires. Resets `_reconnectAttempts`. |
| `void onNetworkDisconnected()` | Force-disconnects the client if connected. Reconnect logic waits for the next `onNetworkConnected()`. | | `void onNetworkDisconnected()` | Force-disconnects the client if connected. Reconnect logic waits for the next `onNetworkConnected()`. |
@@ -83,3 +84,4 @@ Once connected, a heartbeat is published immediately and then every 30 seconds t
- **Error logging is suppressed on publish failure.** `publish()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because `publish()` is also called from the MQTT log channel and logging an error there would recurse infinitely. - **Error logging is suppressed on publish failure.** `publish()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because `publish()` is also called from the MQTT log channel and logging an error there would recurse infinitely.
- **Credentials from NVS.** The broker username and password are read from `ConfigManager`, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID and `MQTT_SECRET` (compiled in via `-DMQTT_SECRET`). - **Credentials from NVS.** The broker username and password are read from `ConfigManager`, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID and `MQTT_SECRET` (compiled in via `-DMQTT_SECRET`).
- **`begin()` must be called before `connect()`.** `begin()` registers AsyncMqttClient event handlers and configures the server. Calling `connect()` before `begin()` will silently do nothing useful. - **`begin()` must be called before `connect()`.** `begin()` registers AsyncMqttClient event handlers and configures the server. Calling `connect()` before `begin()` will silently do nothing useful.
- **`onConnect` callback fires on every connect, not just the first.** `setOnConnectCallback` fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like `CommunicationRouter::reportBootReasonOnce()`) must track that themselves.
@@ -1,14 +1,25 @@
#include "LoggingHandler.hpp" #include "LoggingHandler.hpp"
#include "../../../ConfigManager/ConfigManager.hpp" #include "../../../ConfigManager/ConfigManager.hpp"
#include "../../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
#include "../../../FileManager/FileManager.hpp"
#define TAG "LoggingHandler" #define TAG "LoggingHandler"
LoggingHandler::LoggingHandler(ConfigManager& configManager) // Directory where day-rotated SD logs live — must match CommunicationRouter's
: _configManager(configManager) {} // setFileManagerReference wiring (Logging.hpp SD channel).
static const char* SD_LOG_DIR = "/logs";
// Cap a single logs.download response chunk — keeps every response small
// regardless of file size, matching the JSON-payload sizes used elsewhere
// (MQTT/WS/HTTP transports).
static constexpr size_t LOGS_DOWNLOAD_MAX_CHUNK_BYTES = 4096;
LoggingHandler::LoggingHandler(ConfigManager& configManager, FileManager* fileManager)
: _configManager(configManager), _fileManager(fileManager) {}
std::vector<String> LoggingHandler::commands() const { std::vector<String> LoggingHandler::commands() const {
return { "log.set_serial", "log.set_sd", "log.set_mqtt", "log.get_config" }; return { "log.set_serial", "log.set_sd", "log.set_mqtt", "log.get_config",
"logs.list", "logs.download" };
} }
CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) { CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) {
@@ -16,6 +27,8 @@ CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) {
if (envelope.command == "log.set_sd") return handleSetLevel(envelope, "sd"); if (envelope.command == "log.set_sd") return handleSetLevel(envelope, "sd");
if (envelope.command == "log.set_mqtt") return handleSetLevel(envelope, "mqtt"); if (envelope.command == "log.set_mqtt") return handleSetLevel(envelope, "mqtt");
if (envelope.command == "log.get_config") return handleGetConfig(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);
return CommandResult::err(envelope.command, "Unknown log command"); return CommandResult::err(envelope.command, "Unknown log command");
} }
@@ -60,3 +73,49 @@ CommandResult LoggingHandler::handleGetConfig(const CommandEnvelope& e) {
doc["mqtt_level"] = _configManager.getMqttLogLevel(); doc["mqtt_level"] = _configManager.getMqttLogLevel();
return CommandResult::ok("log.get_config", doc); return CommandResult::ok("log.get_config", doc);
} }
CommandResult LoggingHandler::handleLogsList(const CommandEnvelope& e) {
if (!_fileManager) {
return CommandResult::err("logs.list", "SD card not available on this device");
}
String listJson = _fileManager->listLogFilesAsJson(SD_LOG_DIR);
JsonDocument doc;
DeserializationError err = deserializeJson(doc, listJson);
if (err) {
LOG_ERROR(TAG, "Failed to parse log file list JSON: %s", err.c_str());
return CommandResult::err("logs.list", "Failed to read log directory");
}
JsonDocument result;
result["files"] = doc["files"];
return CommandResult::ok("logs.list", result);
}
CommandResult LoggingHandler::handleLogsDownload(const CommandEnvelope& e) {
if (!_fileManager) {
return CommandResult::err("logs.download", "SD card not available on this device");
}
if (!e.contents["file"].is<const char*>()) {
return CommandResult::err("logs.download", "Missing required field: file");
}
String fileName = e.contents["file"].as<String>();
size_t offset = e.contents["offset"].is<size_t>() ? e.contents["offset"].as<size_t>() : 0;
String chunkJson = _fileManager->readLogChunkAsJson(SD_LOG_DIR, fileName, offset,
LOGS_DOWNLOAD_MAX_CHUNK_BYTES);
JsonDocument doc;
DeserializationError err = deserializeJson(doc, chunkJson);
if (err || doc.isNull()) {
return CommandResult::err("logs.download", "Log file not found: " + fileName);
}
JsonDocument result;
result["file"] = fileName;
result["data"] = doc["data"];
result["next_offset"] = doc["next_offset"];
result["eof"] = doc["eof"];
return CommandResult::ok("logs.download", result);
}
@@ -4,17 +4,21 @@
#include "../ICommandHandler.hpp" #include "../ICommandHandler.hpp"
class ConfigManager; class ConfigManager;
class FileManager;
class LoggingHandler : public ICommandHandler { class LoggingHandler : public ICommandHandler {
public: public:
explicit LoggingHandler(ConfigManager& configManager); explicit LoggingHandler(ConfigManager& configManager, FileManager* fileManager = nullptr);
std::vector<String> commands() const override; std::vector<String> commands() const override;
CommandResult execute(const CommandEnvelope& envelope) override; CommandResult execute(const CommandEnvelope& envelope) override;
private: private:
ConfigManager& _configManager; ConfigManager& _configManager;
FileManager* _fileManager; // nullptr on boards without SD — logs.* commands degrade gracefully
CommandResult handleSetLevel(const CommandEnvelope& e, const String& channel); CommandResult handleSetLevel(const CommandEnvelope& e, const String& channel);
CommandResult handleGetConfig(const CommandEnvelope& e); CommandResult handleGetConfig(const CommandEnvelope& e);
CommandResult handleLogsList(const CommandEnvelope& e);
CommandResult handleLogsDownload(const CommandEnvelope& e);
}; };
+1 -1
View File
@@ -218,7 +218,7 @@ public:
*/ */
struct GeneralConfig { struct GeneralConfig {
uint8_t serialLogLevel = 3; // INFO uint8_t serialLogLevel = 3; // INFO
uint8_t sdLogLevel = 2; // WARNING (inactive until SD callback is wired) uint8_t sdLogLevel = 2; // WARNING
uint8_t mqttLogLevel = 2; // WARNING uint8_t mqttLogLevel = 2; // WARNING
bool mqttEnabled = true; // MQTT enabled by default bool mqttEnabled = true; // MQTT enabled by default
bool bellsEnabled = true; // Master bell mechanism ON/OFF (blocks playback + clock alerts) bool bellsEnabled = true; // Master bell mechanism ON/OFF (blocks playback + clock alerts)
+183
View File
@@ -320,3 +320,186 @@ bool FileManager::appendLine(const String& filePath, const String& line) {
file.close(); file.close();
return true; return true;
} }
// ════════════════════════════════════════════════════════════════════════════
// DAY-ROTATED SD LOG FILE
// ════════════════════════════════════════════════════════════════════════════
String FileManager::logFileNameForTimestamp(time_t timestamp) const {
// No wall clock yet (RTC absent and NTP hasn't synced) — bucket these
// early lines together rather than losing them.
if (timestamp <= 0) {
return "unset-date.log";
}
struct tm timeInfo;
gmtime_r(&timestamp, &timeInfo);
char name[16]; // "YYYY-MM-DD.log" + null
snprintf(name, sizeof(name), "%04d-%02d-%02d.log",
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday);
return String(name);
}
bool FileManager::appendLogLine(const String& logDir, const String& line, time_t timestamp,
size_t maxTotalBytes) {
if (!ensureDirectoryExists(logDir)) {
return false;
}
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
String fullPath = dirPath + logFileNameForTimestamp(timestamp);
if (!appendLine(fullPath, line)) {
return false;
}
if (maxTotalBytes > 0) {
pruneLogDirectory(logDir, maxTotalBytes);
}
return true;
}
// Deletes the oldest dated .log files in logDir until the directory's total
// size is at or under maxTotalBytes. Relies on filenames sorting
// lexicographically oldest-first (YYYY-MM-DD.log).
void FileManager::pruneLogDirectory(const String& logDir, size_t maxTotalBytes) {
if (!initializeSD()) {
return;
}
File dir = SD.open(logDir.c_str());
if (!dir || !dir.isDirectory()) {
return;
}
std::vector<std::pair<String, size_t>> files;
size_t totalBytes = 0;
File file = dir.openNextFile();
while (file) {
if (!file.isDirectory()) {
String name = file.name();
size_t size = file.size();
files.push_back({name, size});
totalBytes += size;
}
file = dir.openNextFile();
}
dir.close();
if (totalBytes <= maxTotalBytes) {
return;
}
std::sort(files.begin(), files.end(),
[](const std::pair<String, size_t>& a, const std::pair<String, size_t>& b) {
return a.first < b.first;
});
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
for (const auto& entry : files) {
if (totalBytes <= maxTotalBytes) break;
// entry.first may already be a full path (SD.open on some cores
// returns the absolute name) — normalize to dirPath + basename.
String name = entry.first;
int lastSlash = name.lastIndexOf('/');
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
String fullPath = dirPath + name;
if (SD.remove(fullPath.c_str())) {
LOG_INFO(TAG, "Log rotation: removed oldest log file %s (%u bytes)", fullPath.c_str(), (unsigned)entry.second);
totalBytes -= entry.second;
}
}
}
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
// as returned by listLogFilesAsJson.
if (fileName.indexOf('/') >= 0 || fileName.indexOf("..") >= 0 || fileName.isEmpty()) {
LOG_ERROR(TAG, "readLogChunkAsJson: invalid file name: %s", fileName.c_str());
return "{}";
}
if (!initializeSD()) {
return "{}";
}
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
String fullPath = dirPath + fileName;
File file = SD.open(fullPath.c_str(), FILE_READ);
if (!file) {
LOG_ERROR(TAG, "readLogChunkAsJson: file not found: %s", fullPath.c_str());
return "{}";
}
size_t fileSize = file.size();
if (offset > fileSize) offset = fileSize;
file.seek(offset);
size_t remaining = fileSize - offset;
size_t toRead = remaining < maxBytes ? remaining : maxBytes;
String chunk;
chunk.reserve(toRead + 1);
while (chunk.length() < toRead && file.available()) {
chunk += (char)file.read();
}
file.close();
size_t nextOffset = offset + chunk.length();
bool eof = nextOffset >= fileSize;
DynamicJsonDocument doc(chunk.length() + 256);
doc["data"] = chunk;
doc["next_offset"] = nextOffset;
doc["eof"] = eof;
String json;
serializeJson(doc, json);
return json;
}
String FileManager::listLogFilesAsJson(const String& logDir) {
if (!initializeSD()) {
LOG_ERROR(TAG, "SD initialization failed");
return "{}";
}
File dir = SD.open(logDir.c_str());
if (!dir || !dir.isDirectory()) {
LOG_ERROR(TAG, "Log directory not found: %s", logDir.c_str());
return "{}";
}
DynamicJsonDocument doc(2048);
JsonArray fileList = doc.createNestedArray("files");
File file = dir.openNextFile();
while (file) {
if (!file.isDirectory()) {
String name = file.name();
int lastSlash = name.lastIndexOf('/');
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
JsonObject entry = fileList.createNestedObject();
entry["name"] = name;
entry["size"] = file.size();
}
file = dir.openNextFile();
}
dir.close();
String json;
serializeJson(doc, json);
return json;
}
+23
View File
@@ -23,6 +23,9 @@
#include <HTTPClient.h> #include <HTTPClient.h>
#include <WiFiClient.h> #include <WiFiClient.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <vector>
#include <algorithm>
#include <time.h>
#include "../Logging/Logging.hpp" #include "../Logging/Logging.hpp"
#include "../ConfigManager/ConfigManager.hpp" #include "../ConfigManager/ConfigManager.hpp"
@@ -52,6 +55,24 @@ public:
// Append a single text line to a file (used by SD log channel) // Append a single text line to a file (used by SD log channel)
bool appendLine(const String& filePath, const String& line); bool appendLine(const String& filePath, const String& line);
// Append a line to a day-rotated log file under logDir (e.g. "/logs").
// Creates the directory if missing, names the file YYYY-MM-DD.log using
// `timestamp` (falls back to a fixed bucket if timestamp <= 0, i.e. no
// wall clock yet), and prunes oldest dated files once the directory
// exceeds maxTotalBytes.
bool appendLogLine(const String& logDir, const String& line, time_t timestamp,
size_t maxTotalBytes);
// List dated log files under logDir as JSON: {"files":[{"name":"2026-07-14.log","size":1234}, ...]}
String listLogFilesAsJson(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}
// Empty JSON object on error (file not found, etc).
String readLogChunkAsJson(const String& logDir, const String& fileName,
size_t offset, size_t maxBytes);
// ═══════════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════════
// HEALTH CHECK METHOD // HEALTH CHECK METHOD
// ═══════════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════════
@@ -63,6 +84,8 @@ private:
// Helper functions // Helper functions
bool initializeSD(); bool initializeSD();
bool ensureDirectoryExists(const String& dirPath); bool ensureDirectoryExists(const String& dirPath);
String logFileNameForTimestamp(time_t timestamp) const;
void pruneLogDirectory(const String& logDir, size_t maxTotalBytes);
}; };
#endif #endif
+21 -2
View File
@@ -20,7 +20,10 @@ FileManager is the single access point for all SD card I/O in Vesper. It abstrac
| `getFileSize` | `size_t getFileSize(const String& filePath)` | Returns the size in bytes of a file, or `0` if it cannot be opened. | | `getFileSize` | `size_t getFileSize(const String& filePath)` | Returns the size in bytes of a file, or `0` if it cannot be opened. |
| `writeJsonFile` | `bool writeJsonFile(const String& filePath, JsonDocument& doc)` | Serializes an ArduinoJson `JsonDocument` to a file, overwriting any existing content. | | `writeJsonFile` | `bool writeJsonFile(const String& filePath, JsonDocument& doc)` | Serializes an ArduinoJson `JsonDocument` to a file, overwriting any existing content. |
| `readJsonFile` | `bool readJsonFile(const String& filePath, JsonDocument& doc)` | Deserializes a file into an ArduinoJson `JsonDocument`. Returns `false` on open or parse failure. | | `readJsonFile` | `bool readJsonFile(const String& filePath, JsonDocument& doc)` | Deserializes a file into an ArduinoJson `JsonDocument`. Returns `false` on open or parse failure. |
| `appendLine` | `bool appendLine(const String& filePath, const String& line)` | Opens a file in `FILE_APPEND` mode and writes `line` followed by `\n`. Used by the Logging subsystem's SD write callback to write to `/logs/vesper.log`. | | `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. |
| `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. | | `isHealthy` | `bool isHealthy() const` | Returns `true` if the ConfigManager pointer is set and `SD.cardType() != CARD_NONE`. Used by HealthMonitor. |
--- ---
@@ -79,4 +82,20 @@ The `setFileManagerReference` call on `CommunicationRouter` is particularly impo
**`listFilesAsJson` has a fixed 1024-byte JSON budget.** Directories with more than roughly 20–25 average-length filenames will overflow this `DynamicJsonDocument` allocation silently. Increase the capacity if `/melodies` is expected to hold a large number of files. **`listFilesAsJson` has a fixed 1024-byte JSON budget.** Directories with more than roughly 20–25 average-length filenames will overflow this `DynamicJsonDocument` allocation silently. Increase the capacity if `/melodies` is expected to hold a large number of files.
**Log file path is hardcoded in the caller.** The path `/logs/vesper.log` is set inside `CommunicationRouter::setFileManagerReference`, not inside FileManager. FileManager itself is path-agnostic. **Log directory is hardcoded in the caller.** The `/logs` base path is set inside `CommunicationRouter::setFileManagerReference`, not inside FileManager. FileManager itself is path-agnostic — it only knows `logDir` as a parameter.
---
## Log file rotation
Prior to this feature, `appendLine` was called directly with a single hardcoded path (`/logs/vesper.log`) and never created the `/logs` directory first — on most SD/FAT implementations, `SD.open(path, FILE_APPEND)` fails silently (returns an invalid `File`) when the parent directory doesn't exist. On a freshly formatted SD card this meant SD logging was a silent no-op.
`appendLogLine` fixes this and adds day-based rotation:
1. Calls `ensureDirectoryExists(logDir)` before every write.
2. Names the file `YYYY-MM-DD.log` (UTC, derived from the `timestamp` argument via `gmtime_r`). If `timestamp <= 0` — no RTC and NTP hasn't synced yet — lines are bucketed into `unset-date.log` rather than being lost.
3. After each write, if `maxTotalBytes > 0`, sums the size of every file in `logDir` and, if over budget, deletes whole files oldest-filename-first (lexicographic sort on `YYYY-MM-DD.log` sorts chronologically) until back under budget.
The caller (`CommunicationRouter::setFileManagerReference`) supplies `time(nullptr)` as the timestamp — this works regardless of `HAS_RTC`, since `configTime()`/NTP sync (in `Timekeeper::syncTimeWithNTP()`) sets the ESP32's system clock independently of any RTC peripheral. Before NTP has synced, `time(nullptr)` returns a small epoch value, which is treated as "no wall clock" and routed to `unset-date.log`.
**Pruning is whole-file, not line-level.** If a single day's file alone exceeds `maxTotalBytes`, it will not be truncated mid-file — pruning only removes complete files from the oldest end.
+10 -2
View File
@@ -54,6 +54,12 @@ Pass `Logging::NONE` to fully suppress a tag on a channel. The override map is k
Both channels start disabled (callbacks are `nullptr`). Output on a channel is silenced until the relevant callback is registered. Both channels start disabled (callbacks are `nullptr`). Output on a channel is silenced until the relevant callback is registered.
### MQTT rate limiting
Each subsystem tag has its own token bucket on the MQTT channel: a burst of 10 messages, refilling at 1/second. Once a tag's bucket is empty, further messages from that tag are dropped (not queued) until it refills. This protects the broker/airtime from a chatty or misconfigured subsystem — e.g. a per-subsystem override left at `VERBOSE` in the field.
Drops are not silent: the next time that tag is allowed to publish again, a `WARNING`-level summary line is emitted first (`"suppressed N log message(s) (MQTT rate limit)"`), so a burst is visible even though not every line survived it. Serial and SD channels are unaffected by this limiter — only MQTT.
### Utilities ### Utilities
| Method | Description | | Method | Description |
@@ -86,7 +92,7 @@ Both channels start disabled (callbacks are `nullptr`). Output on a channel is s
``` ```
`timestamp` is `millis()` (ms since boot), not wall-clock time. `timestamp` is `millis()` (ms since boot), not wall-clock time.
**SD line (plain text):** `[LEVL][Tag] message (12345ms)` **SD line (plain text):** `[LEVL][Tag] message (12345ms)`, written to a day-rotated file — see [FileManager](../FileManager/README.md#log-file-rotation).
--- ---
@@ -112,7 +118,9 @@ This happens immediately after `configManager.begin()`, before any other subsyst
```cpp ```cpp
Logging::setMqttPublishCallback(..., "vesper/<uid>/logs"); Logging::setMqttPublishCallback(..., "vesper/<uid>/logs");
Logging::setSdWriteCallback([fm](const String& line) { fm->appendLine("/logs/vesper.log", line); }); Logging::setSdWriteCallback([fm](const String& line) {
fm->appendLogLine("/logs", line, time(nullptr), SD_LOG_MAX_TOTAL_BYTES);
});
Logging::setSerialLevel(...); Logging::setSerialLevel(...);
Logging::setMqttLevel(...); Logging::setMqttLevel(...);
Logging::setSdLevel(...); Logging::setSdLevel(...);
+5
View File
@@ -26,6 +26,9 @@ Telemetry tracks per-bell strike counts and thermal load to protect actuators fr
| `bool isHealthy() const` | Returns `true` if the task is running, the player reference is set, and no bell is currently overloaded. Polled by HealthMonitor. | | `bool isHealthy() const` | Returns `true` if the task is running, the player reference is set, and no bell is currently overloaded. Polled by HealthMonitor. |
| `void logTemperature(float temperature)` | Stub — logs value to serial only. No persistent storage or analysis yet. | | `void logTemperature(float temperature)` | Stub — logs value to serial only. No persistent storage or analysis yet. |
| `void logVibration(float vibration)` | Stub — logs value to serial only. No persistent storage or analysis yet. | | `void logVibration(float vibration)` | Stub — logs value to serial only. No persistent storage or analysis yet. |
| `esp_reset_reason_t getResetReason() const` | Returns the ESP32 reset reason captured once at `begin()`, via `esp_reset_reason()`. |
| `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"`. |
--- ---
@@ -83,6 +86,8 @@ communication.setTelemetryReference(&telemetry);
**Heat model.** The thermal model is a simple increment/decrement counter, not a physical model. One strike adds 1 unit of load; 1 unit decays per second. A bell with `maxLoad = 200` (the default) tolerates sustained rates up to ~200 strikes per second before triggering overload, which is far beyond any realistic bell schedule. The threshold is more useful as a runaway-loop guard than a true thermal limit. Adjust per-bell thresholds via `setBellMaxLoad()` if tighter protection is needed for a specific installation. **Heat model.** The thermal model is a simple increment/decrement counter, not a physical model. One strike adds 1 unit of load; 1 unit decays per second. A bell with `maxLoad = 200` (the default) tolerates sustained rates up to ~200 strikes per second before triggering overload, which is far beyond any realistic bell schedule. The threshold is more useful as a runaway-loop guard than a true thermal limit. Adjust per-bell thresholds via `setBellMaxLoad()` if tighter protection is needed for a specific installation.
**Reset reason capture.** `resetReason` is read once at the very top of `begin()`, before anything else can crash again this boot. It's included in the boot log entry written by `logBootEvent()` (field `"reason"`) so it's available on SD even for offline devices. For online devices, `CommunicationRouter` reports it once, the first time MQTT connects after boot: fault reasons go to `vesper/{uid}/status/alerts` (via `publishAlert`), expected reasons go to `vesper/{uid}/status/info` (via `publishInfo`, event type `"boot_reason"`). See [CommunicationRouter](../Communication/CommunicationRouter/README.md).
**Remote commands (via TelemetryHandler).** The following v2 commands are handled by `TelemetryHandler` and routed through `CommunicationRouter`: **Remote commands (via TelemetryHandler).** The following v2 commands are handled by `TelemetryHandler` and routed through `CommunicationRouter`:
| Command | Description | | Command | Description |
+36 -2
View File
@@ -4,6 +4,9 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
void Telemetry::begin() { void Telemetry::begin() {
resetReason = esp_reset_reason();
LOG_INFO(TAG, "Reset reason: %s%s", getResetReasonString().c_str(), isFaultReset() ? " (FAULT)" : "");
for (uint8_t i = 0; i < 16; i++) { for (uint8_t i = 0; i < 16; i++) {
strikeCounters[i] = 0; strikeCounters[i] = 0;
bellLoad[i] = 0; bellLoad[i] = 0;
@@ -21,6 +24,36 @@ void Telemetry::begin() {
LOG_INFO(TAG, "Telemetry initialized"); LOG_INFO(TAG, "Telemetry initialized");
} }
bool Telemetry::isFaultReset() const {
switch (resetReason) {
case ESP_RST_PANIC:
case ESP_RST_INT_WDT:
case ESP_RST_TASK_WDT:
case ESP_RST_WDT:
case ESP_RST_BROWNOUT:
return true;
default:
return false;
}
}
String Telemetry::getResetReasonString() const {
switch (resetReason) {
case ESP_RST_UNKNOWN: return "UNKNOWN";
case ESP_RST_POWERON: return "POWERON";
case ESP_RST_EXT: return "EXTERNAL_PIN";
case ESP_RST_SW: return "SOFTWARE";
case ESP_RST_PANIC: return "PANIC";
case ESP_RST_INT_WDT: return "INTERRUPT_WATCHDOG";
case ESP_RST_TASK_WDT: return "TASK_WATCHDOG";
case ESP_RST_WDT: return "OTHER_WATCHDOG";
case ESP_RST_DEEPSLEEP: return "DEEPSLEEP_WAKE";
case ESP_RST_BROWNOUT: return "BROWNOUT";
case ESP_RST_SDIO: return "SDIO";
default: return "UNKNOWN";
}
}
void Telemetry::setPlayerReference(bool* isPlayingPtr) { void Telemetry::setPlayerReference(bool* isPlayingPtr) {
playerIsPlayingPtr = isPlayingPtr; playerIsPlayingPtr = isPlayingPtr;
LOG_DEBUG(TAG, "Player reference set"); LOG_DEBUG(TAG, "Player reference set");
@@ -270,8 +303,9 @@ void Telemetry::logBootEvent(uint32_t bootTimestamp) {
uint32_t bootNum = (uint32_t)(doc["total_boots"] | 0) + 1; uint32_t bootNum = (uint32_t)(doc["total_boots"] | 0) + 1;
JsonObject entry = entries.add<JsonObject>(); JsonObject entry = entries.add<JsonObject>();
entry["ts"] = bootTimestamp; entry["ts"] = bootTimestamp;
entry["boot"] = bootNum; entry["boot"] = bootNum;
entry["reason"] = getResetReasonString();
doc["total_boots"] = bootNum; doc["total_boots"] = bootNum;
if (!fileManager->writeJsonFile("/telemetry_boot_log.json", doc)) { if (!fileManager->writeJsonFile("/telemetry_boot_log.json", doc)) {
+11
View File
@@ -54,6 +54,7 @@
#define TELEMETRY_HPP #define TELEMETRY_HPP
#include <Arduino.h> #include <Arduino.h>
#include <esp_system.h>
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "../Logging/Logging.hpp" #include "../Logging/Logging.hpp"
@@ -92,6 +93,9 @@ private:
// Pause flag for OTA freeze mode // Pause flag for OTA freeze mode
volatile bool isPaused = false; volatile bool isPaused = false;
// Reset reason, captured once at begin()
esp_reset_reason_t resetReason = ESP_RST_UNKNOWN;
public: public:
// Initialization // Initialization
void begin(); void begin();
@@ -135,6 +139,13 @@ public:
// Boot log // Boot log
void logBootEvent(uint32_t bootTimestamp); void logBootEvent(uint32_t bootTimestamp);
// Reset reason (captured once at begin(), before anything else can crash again)
esp_reset_reason_t getResetReason() const { return resetReason; }
// True if the reset reason indicates a fault (panic, watchdog, brownout) rather
// than an expected reset (power-on, software reset/OTA, deep sleep wake).
bool isFaultReset() const;
String getResetReasonString() const;
// Data collection (future expansion) // Data collection (future expansion)
void logTemperature(float temperature); void logTemperature(float temperature);
void logVibration(float vibration); void logVibration(float vibration);