docs: add per-subsystem README files

Add inline documentation for all src/ subsystems covering purpose,
responsibilities, public API, and usage notes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-14 22:16:03 +02:00
co-authored by Claude Sonnet 4.6
parent d4bd990e53
commit d4d8b1c380
29 changed files with 2961 additions and 0 deletions
+170
View File
@@ -0,0 +1,170 @@
# Logging
Centralized, subsystem-aware logging layer for Vesper firmware. It routes log messages to up to three independent output channels — Serial (USB), MQTT, and SD card — each with its own configurable log level. Per-subsystem tag overrides let individual subsystems be silenced or restricted on a specific channel without affecting others (e.g. silencing `MQTTClient` on the MQTT channel to prevent recursion). The class is fully static; there is no instance to manage.
---
## Public API
### Log emission
Each `.cpp` file defines `#define TAG "SubsystemName"` at the top and calls the macros below. The macros are thin wrappers around the static methods.
| Macro / Method | Description |
|---|---|
| `LOG_ERROR(tag, fmt, ...)` / `Logging::error(tag, fmt, ...)` | Emit at ERROR level |
| `LOG_WARNING(tag, fmt, ...)` / `Logging::warning(tag, fmt, ...)` | Emit at WARNING level |
| `LOG_INFO(tag, fmt, ...)` / `Logging::info(tag, fmt, ...)` | Emit at INFO level |
| `LOG_DEBUG(tag, fmt, ...)` / `Logging::debug(tag, fmt, ...)` | Emit at DEBUG level |
| `LOG_VERBOSE(tag, fmt, ...)` / `Logging::verbose(tag, fmt, ...)` | Emit at VERBOSE level |
`fmt` is a `printf`-style format string. The formatted message is capped at 512 bytes internally.
### Global channel levels
| Method | Description |
|---|---|
| `Logging::setSerialLevel(level)` | Set baseline level for Serial output |
| `Logging::setMqttLevel(level)` | Set baseline level for MQTT output |
| `Logging::setSdLevel(level)` | Set baseline level for SD output |
| `Logging::getSerialLevel()` | Return current Serial level |
| `Logging::getMqttLevel()` | Return current MQTT level |
| `Logging::getSdLevel()` | Return current SD level |
| `Logging::setLevel(level)` | Legacy alias for `setSerialLevel` |
| `Logging::getLevel()` | Legacy alias for `getSerialLevel` |
| `Logging::setMqttLogLevel(level)` | Legacy alias for `setMqttLevel` |
| `Logging::getMqttLogLevel()` | Legacy alias for `getMqttLevel` |
### Per-subsystem overrides
| Method | Description |
|---|---|
| `Logging::setSubsystemSerialLevel(tag, level)` | Cap or silence `tag` on Serial only |
| `Logging::setSubsystemMqttLevel(tag, level)` | Cap or silence `tag` on MQTT only |
| `Logging::setSubsystemSdLevel(tag, level)` | Cap or silence `tag` on SD only |
Pass `Logging::NONE` to fully suppress a tag on a channel. The override map is keyed by the exact `tag` string.
### Output channel registration
| Method | Description |
|---|---|
| `Logging::setMqttPublishCallback(callback, logTopic)` | Register the function used to publish log messages over MQTT, and the topic to publish to |
| `Logging::setSdWriteCallback(callback)` | Register the function used to append log lines to the SD log file |
Both channels start disabled (callbacks are `nullptr`). Output on a channel is silenced until the relevant callback is registered.
### Utilities
| Method | Description |
|---|---|
| `Logging::isLevelEnabled(level)` | Returns `true` if Serial level is at or above `level` (checks Serial only) |
| `Logging::levelToString(level)` | Returns a human-readable string for a `LogLevel` value |
---
## Log levels
| Value | Name | Integer |
|---|---|---|
| `NONE` | No output | 0 |
| `ERROR` | Errors only | 1 |
| `WARNING` | Warnings and errors | 2 |
| `INFO` | Info, warnings, errors | 3 |
| `DEBUG` | Debug detail | 4 |
| `VERBOSE` | Everything | 5 |
---
## Output formats
**Serial:** `[LEVL][Tag] message\n`
**MQTT payload (JSON):**
```json
{"level":"WARNING","subsystem":"BellEngine","message":"...","timestamp":12345}
```
`timestamp` is `millis()` (ms since boot), not wall-clock time.
**SD line (plain text):** `[LEVL][Tag] message (12345ms)`
---
## Initialization
Logging has no `begin()` call. Static defaults at startup are:
- Serial: `VERBOSE`
- MQTT: `NONE`
- SD: `NONE`
### Step 1 — Apply Serial level from config (`main.cpp`, early in `setup`)
```cpp
Logging::setLevel((Logging::LogLevel)configManager.getGeneralConfig().serialLogLevel);
```
This happens immediately after `configManager.begin()`, before any other subsystem is initialized, so all subsequent boot messages respect the configured level.
### Step 2 — Register MQTT and SD callbacks (`CommunicationRouter::begin`)
`CommunicationRouter::begin()` registers both callbacks and applies all three channel levels from `ConfigManager`:
```cpp
Logging::setMqttPublishCallback(..., "vesper/<uid>/logs");
Logging::setSdWriteCallback([fm](const String& line) { fm->appendLine("/logs/vesper.log", line); });
Logging::setSerialLevel(...);
Logging::setMqttLevel(...);
Logging::setSdLevel(...);
```
It also sets the default per-subsystem MQTT suppressions to prevent feedback loops:
```cpp
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
```
MQTT and SD output are therefore inactive until `CommunicationRouter::begin()` runs.
### Runtime level changes
`LoggingHandler` handles the `log.set_serial`, `log.set_mqtt`, and `log.set_sd` commands routed through the `CommandBus`. These persist the new level to `ConfigManager` (saved to SD) and apply it immediately.
Command example:
```json
{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 3 } }
```
---
## Dependencies
| Dependency | Why |
|---|---|
| `Arduino.h` / `Serial` | Serial output channel |
| `ConfigManager` | Reads initial log levels at boot; saves runtime changes |
| `CommunicationRouter` | Registers the MQTT publish callback and SD write callback |
| `FileManager` | Provides `appendLine()` used by the SD callback |
| `std::map<String, LogLevel>` | Per-subsystem override storage |
`Logging.hpp` includes `<map>` and `<functional>` directly. No FreeRTOS headers are included; the class does not create any tasks or timers.
---
## Gotchas / Notes
**Thread safety.** The class has no mutex protection. The per-channel re-entrancy guards (`isPublishing`, `isWriting`) are `static bool` flags, not atomics. These prevent log-of-a-log recursion within a single call path but are not safe across concurrent FreeRTOS tasks. In practice, Serial output is the only channel exercised from multiple tasks simultaneously (e.g. BellEngine on Core 1, MQTT task on Core 0). Serial's hardware FIFO makes this tolerable in practice, but strictly speaking concurrent calls are a data race.
**MQTT feedback loop.** Any subsystem whose logs are emitted on the MQTT channel must not call `Logging` from within the MQTT publish path. `MQTTClient` and `CommRouter` are silenced on MQTT by default for this reason. The `isPublishing` guard is a secondary safeguard.
**SD writes are synchronous.** `setSdWriteCallback` delegates to `FileManager::appendLine`, which acquires the SD card mutex. Calling `LOG_*` at high frequency with SD enabled can stall the calling task for the duration of the SD write.
**`isLevelEnabled` checks Serial only.** If you need to guard an expensive log-string build (e.g. formatting a large buffer before calling `LOG_DEBUG`), use `Logging::isLevelEnabled(Logging::DEBUG)`. Be aware this ignores MQTT and SD levels.
**Message truncation.** The internal format buffer is 512 bytes. Messages longer than 511 characters are silently truncated by `vsnprintf`.
**No timestamps beyond `millis()`.** MQTT and SD payloads use `millis()` (ms since boot). Wall-clock timestamps are not included; correlate with NTP-synced log entries from the backend if absolute time is needed.
**MQTT and SD channels are disabled by default.** Both callbacks start as `nullptr`. Messages targeting those channels are dropped silently until `CommunicationRouter::begin()` registers the callbacks. Any logs emitted before that point (early boot) are Serial-only regardless of configured levels.