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 <time.h>
#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 "../../OTAManager/OTAManager.hpp"
#include "../../Networking/Networking.hpp"
@@ -124,6 +129,10 @@ void CommunicationRouter::begin() {
Logging::setSubsystemMqttLevel("Telemetry", Logging::INFO); // load data useful
Logging::setSubsystemMqttLevel("OTAManager", Logging::INFO); // update events important
_mqttClient.setOnConnectCallback([this](bool /*sessionPresent*/) {
reportBootReasonOnce();
});
LOG_INFO(TAG, "MQTT transport initialised");
// ── HTTP ─────────────────────────────────────────────────────────────────
@@ -191,9 +200,11 @@ void CommunicationRouter::setFileManagerReference(FileManager* fm) {
if (fm != nullptr) {
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));
}
// Logging — no optional dependencies
_bus.registerHandler(std::make_unique<LoggingHandler>(_configManager));
// Logging — FileManager optional; logs.list/logs.download degrade gracefully without it
_bus.registerHandler(std::make_unique<LoggingHandler>(_configManager, _fileManager));
// 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());
}
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) {
if (!_mqttClient.isConnected()) return;
@@ -138,6 +138,13 @@ public:
void onNetworkDisconnected();
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) ────────────────────────────────────
ConfigManager& _configManager;
OTAManager& _otaManager;
@@ -21,7 +21,7 @@
| Method | Description |
|--------|-------------|
| `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 setFirmwareValidatorReference(FirmwareValidator*)` | Required for FirmwareHandler. |
| `void setTelemetryReference(Telemetry*)` | Required for TelemetryHandler, SystemHandler. |
@@ -49,8 +49,8 @@
| `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 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 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 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. Used for e.g. `"boot_reason"` events on expected resets. |
### 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.
- **`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.
- **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.
- **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
startHeartbeat();
if (_onConnectCallback) {
_onConnectCallback(sessionPresent);
}
}
void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
@@ -17,6 +17,7 @@
#include <Arduino.h>
#include <AsyncMqttClient.h>
#include <functional>
class ConfigManager;
class Networking;
@@ -72,6 +73,13 @@ public:
*/
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
*/
@@ -96,7 +104,8 @@ private:
Networking& _networking;
AsyncMqttClient _mqttClient;
MessageCallback _messageCallback;
std::function<void(bool sessionPresent)> _onConnectCallback;
// Device topic strings (cached for performance)
String _controlTopic;
@@ -26,6 +26,7 @@ Topics:
| `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()`. |
| `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. |
| `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()`. |
@@ -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.
- **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.
- **`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 "../../../ConfigManager/ConfigManager.hpp"
#include "../../../Logging/Logging.hpp"
#include "../../../FileManager/FileManager.hpp"
#define TAG "LoggingHandler"
LoggingHandler::LoggingHandler(ConfigManager& configManager)
: _configManager(configManager) {}
// Directory where day-rotated SD logs live — must match CommunicationRouter's
// 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 {
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) {
@@ -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_mqtt") return handleSetLevel(envelope, "mqtt");
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");
}
@@ -60,3 +73,49 @@ CommandResult LoggingHandler::handleGetConfig(const CommandEnvelope& e) {
doc["mqtt_level"] = _configManager.getMqttLogLevel();
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"
class ConfigManager;
class FileManager;
class LoggingHandler : public ICommandHandler {
public:
explicit LoggingHandler(ConfigManager& configManager);
explicit LoggingHandler(ConfigManager& configManager, FileManager* fileManager = nullptr);
std::vector<String> commands() const override;
CommandResult execute(const CommandEnvelope& envelope) override;
private:
ConfigManager& _configManager;
FileManager* _fileManager; // nullptr on boards without SD — logs.* commands degrade gracefully
CommandResult handleSetLevel(const CommandEnvelope& e, const String& channel);
CommandResult handleGetConfig(const CommandEnvelope& e);
CommandResult handleLogsList(const CommandEnvelope& e);
CommandResult handleLogsDownload(const CommandEnvelope& e);
};