diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index 6b521ca..2b04b74 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -6,9 +6,14 @@ */ #include "CommunicationRouter.hpp" +#include #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(*_fileManager)); } - // Logging — no optional dependencies - _bus.registerHandler(std::make_unique(_configManager)); + // Logging — FileManager optional; logs.list/logs.download degrade gracefully without it + _bus.registerHandler(std::make_unique(_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; diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index 75af7d0..6d0b63b 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -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; diff --git a/src/Communication/CommunicationRouter/README.md b/src/Communication/CommunicationRouter/README.md index 21a2f79..db3e492 100644 --- a/src/Communication/CommunicationRouter/README.md +++ b/src/Communication/CommunicationRouter/README.md @@ -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& bells, const std::vector& 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()`. diff --git a/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp b/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp index 21d7f3e..7776227 100644 --- a/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp +++ b/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp @@ -238,6 +238,10 @@ void MQTTDriver::onMqttConnect(bool sessionPresent) { // 🔥 Start heartbeat timer startHeartbeat(); + + if (_onConnectCallback) { + _onConnectCallback(sessionPresent); + } } void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { diff --git a/src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp b/src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp index ec7a6f1..3c324e0 100644 --- a/src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp +++ b/src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp @@ -17,6 +17,7 @@ #include #include +#include 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 callback) { _onConnectCallback = callback; } + /** * @brief Check if connected to MQTT broker */ @@ -96,7 +104,8 @@ private: Networking& _networking; AsyncMqttClient _mqttClient; MessageCallback _messageCallback; - + std::function _onConnectCallback; + // Device topic strings (cached for performance) String _controlTopic; diff --git a/src/Communication/Drivers/MQTTDriver/README.md b/src/Communication/Drivers/MQTTDriver/README.md index 4a0402f..8ff7f10 100644 --- a/src/Communication/Drivers/MQTTDriver/README.md +++ b/src/Communication/Drivers/MQTTDriver/README.md @@ -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 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. diff --git a/src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp b/src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp index 6cb6334..7b248e4 100644 --- a/src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp +++ b/src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp @@ -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 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()) { + return CommandResult::err("logs.download", "Missing required field: file"); + } + + String fileName = e.contents["file"].as(); + size_t offset = e.contents["offset"].is() ? e.contents["offset"].as() : 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); +} diff --git a/src/Communication/Handlers/LoggingHandler/LoggingHandler.hpp b/src/Communication/Handlers/LoggingHandler/LoggingHandler.hpp index 6a6b585..04a2f7f 100644 --- a/src/Communication/Handlers/LoggingHandler/LoggingHandler.hpp +++ b/src/Communication/Handlers/LoggingHandler/LoggingHandler.hpp @@ -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 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); }; diff --git a/src/ConfigManager/ConfigManager.hpp b/src/ConfigManager/ConfigManager.hpp index cac7d8c..31da7b6 100644 --- a/src/ConfigManager/ConfigManager.hpp +++ b/src/ConfigManager/ConfigManager.hpp @@ -218,7 +218,7 @@ public: */ struct GeneralConfig { 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 bool mqttEnabled = true; // MQTT enabled by default bool bellsEnabled = true; // Master bell mechanism ON/OFF (blocks playback + clock alerts) diff --git a/src/FileManager/FileManager.cpp b/src/FileManager/FileManager.cpp index 77d23d2..2319b6c 100644 --- a/src/FileManager/FileManager.cpp +++ b/src/FileManager/FileManager.cpp @@ -320,3 +320,186 @@ bool FileManager::appendLine(const String& filePath, const String& line) { file.close(); 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(×tamp, &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> 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& a, const std::pair& 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; +} diff --git a/src/FileManager/FileManager.hpp b/src/FileManager/FileManager.hpp index 9f6a0e1..fc54c77 100644 --- a/src/FileManager/FileManager.hpp +++ b/src/FileManager/FileManager.hpp @@ -23,6 +23,9 @@ #include #include #include +#include +#include +#include #include "../Logging/Logging.hpp" #include "../ConfigManager/ConfigManager.hpp" @@ -51,18 +54,38 @@ public: // Append a single text line to a file (used by SD log channel) 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":"","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 // ═══════════════════════════════════════════════════════════════════════════════ - + /** @brief Check if FileManager is in healthy state */ bool isHealthy() const; - + private: // Helper functions bool initializeSD(); bool ensureDirectoryExists(const String& dirPath); + String logFileNameForTimestamp(time_t timestamp) const; + void pruneLogDirectory(const String& logDir, size_t maxTotalBytes); }; #endif diff --git a/src/FileManager/README.md b/src/FileManager/README.md index d06351b..8a6ed1c 100644 --- a/src/FileManager/README.md +++ b/src/FileManager/README.md @@ -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. | | `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. | -| `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. | --- @@ -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. -**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. diff --git a/src/Logging/README.md b/src/Logging/README.md index 6a84f9d..90c1c0b 100644 --- a/src/Logging/README.md +++ b/src/Logging/README.md @@ -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. +### 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 | 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. -**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 Logging::setMqttPublishCallback(..., "vesper//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::setMqttLevel(...); Logging::setSdLevel(...); diff --git a/src/Telemetry/README.md b/src/Telemetry/README.md index 1989b81..137deef 100644 --- a/src/Telemetry/README.md +++ b/src/Telemetry/README.md @@ -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. | | `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. | +| `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. +**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`: | Command | Description | diff --git a/src/Telemetry/Telemetry.cpp b/src/Telemetry/Telemetry.cpp index 0d4906e..4cd52e4 100644 --- a/src/Telemetry/Telemetry.cpp +++ b/src/Telemetry/Telemetry.cpp @@ -4,6 +4,9 @@ #include 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++) { strikeCounters[i] = 0; bellLoad[i] = 0; @@ -21,6 +24,36 @@ void Telemetry::begin() { 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) { playerIsPlayingPtr = isPlayingPtr; 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; JsonObject entry = entries.add(); - entry["ts"] = bootTimestamp; - entry["boot"] = bootNum; + entry["ts"] = bootTimestamp; + entry["boot"] = bootNum; + entry["reason"] = getResetReasonString(); doc["total_boots"] = bootNum; if (!fileManager->writeJsonFile("/telemetry_boot_log.json", doc)) { diff --git a/src/Telemetry/Telemetry.hpp b/src/Telemetry/Telemetry.hpp index a9b2e14..55a52e5 100644 --- a/src/Telemetry/Telemetry.hpp +++ b/src/Telemetry/Telemetry.hpp @@ -54,6 +54,7 @@ #define TELEMETRY_HPP #include +#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "../Logging/Logging.hpp" @@ -92,6 +93,9 @@ private: // Pause flag for OTA freeze mode volatile bool isPaused = false; + // Reset reason, captured once at begin() + esp_reset_reason_t resetReason = ESP_RST_UNKNOWN; + public: // Initialization void begin(); @@ -135,6 +139,13 @@ public: // Boot log 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) void logTemperature(float temperature); void logVibration(float vibration);