Console requested four more Health-tab metrics beyond F-054's free_heap/ping
work. None needed 30s heartbeat freshness, so this adds a separate low-frequency
report instead of growing the heartbeat further: published every 5 min to
status/info (diagnostics_report) and queryable on-demand via a new
telemetry.get_diagnostics command.
Only CPU temperature needs local sampling (15s, via a min/max/avg RunningStats
accumulator on Telemetry) — a thermal spike could occur and subside entirely
within a 5-minute gap. The other three fields are monotonic/self-tracking
(WiFi reconnect counter, FreeRTOS's own stack high-water mark, rarely-changing
OTA state) so a single read at report time loses no information.
Verified: pio run on all four board variants.
Requested by the console-side agent building a device Health tab
(RSSI, ping latency, free heap, restart timeline graphs). Both changes
are additive and backward-compatible.
publishHeartbeat() now includes free_heap (ESP.getFreeHeap()) on the
existing 30s heartbeat, alongside rssi — previously free heap was only
visible once per boot via boot_report, a single point rather than a
trend.
handlePing() previously built a JsonDocument and never used it —
ping was a pure ack. It now echoes back an optional caller-supplied
"ts" (epoch-millis) unchanged, plus device_uptime_ms, so the caller
can compute round-trip latency as (time of receipt) - ts without
needing synchronized clocks. ts is optional on both request and
response, so existing callers doing a plain liveness check are
unaffected. Left the existing #if HAS_RTC scoping on SystemHandler.cpp
untouched, per the request — ping remains RTC-variant-only.
Verified: pio run on vesper-std-v1 and agnus-v1 (confirms the HAS_RTC
scoping around SystemHandler.cpp wasn't disturbed).
Documented in feature-catalog.md F-054, MQTTDriver/README.md, and
Communication/Handlers/README.md.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The SD-based boot history (logBootEvent() -> /telemetry_boot_log.json)
was write-only: nothing in the firmware ever read it back, and its
"boot" field was a locally-tallied counter (only advanced on the
NTP-gated write path) that could silently drift from the new
lifetime_boot_count added in the previous commit.
- logBootEvent() now stamps each entry with getLifetimeBootCount()
directly instead of its own total_boots tally, so the SD history's
"boot" numbers always agree with what MQTT boot_report and
telemetry.get_metrics/system.get_telemetry report. The old
total_boots JSON key is no longer written (old files may still have
it; current firmware ignores it).
- Each entry now also carries crash detail (task/pc/exc_cause/
exc_vaddr) when a coredump was captured for that boot, same shape
as the MQTT boot_report's crash object.
- New Telemetry::getBootHistory() + telemetry.get_boot_history command
actually exposes the file: optional {"limit": N} (clamped 1-200),
returns {"count", "boots": [...]}. Returns an error response (not a
crash or empty success) when there's no SD/FileManager or the file
doesn't exist yet — expected on agnus (no-SD) variants or before a
device's first NTP sync.
Full request/response contract documented in Telemetry's README and
feature-catalog.md F-053, written for direct consumption by whoever
builds the console-side retrieval UI.
Verified: pio run on vesper-std-v1 and agnus-v1 (no-SD variant).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Investigating the F-051 TelemetryTask crash surfaced two gaps: the
console only ever saw a coarse "Device reset due to fault: PANIC"
alert, none of the serial monitor's task-name/register detail; and
there was no automatic per-boot report a console could use to count
reboots without polling.
Adds Telemetry::getLifetimeBootCount() — a new NVS-backed counter
(namespace "vesper_boot") that increments once per boot, works on
every board variant (SD or not), and is reliable regardless of NTP
sync status. Deliberately kept separate from FirmwareValidator's
existing NVS boot_count (scoped to boots-since-this-OTA-slot-was-
flashed, feeds rollback-safety retry logic — left untouched) and
Telemetry's existing SD-based total_boots (repositioned as history-
only; unreliable as a counter since it's SD/NTP-dependent).
Adds Telemetry::captureCrashReport(), which reads the ESP-IDF
coredump summary (esp_core_dump_get_summary) once at begin(). The
coredump partition and CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH were
already present/enabled in this project's stock min_spiffs.csv and
precompiled Arduino-ESP32 core — no partition table or SDK config
change needed. This is the official "user mode" retrieval API, safe
to call from ordinary application code after boot; no custom panic
hook, nothing runs inside the panic handler itself. Extracts the
faulting task name, PC, and exception cause/vaddr, then erases the
dump so it's reported exactly once.
CommunicationRouter::reportBootReasonOnce() (renamed reportBootOnce())
now always publishes a consolidated "boot_report" event to
status/info on first MQTT connect — boot count, reset reason, free
heap, and crash detail when available — alongside the existing
fault-triggered status/alerts WARNING (unchanged).
lifetime_boot_count also added to telemetry.get_metrics,
system.get_telemetry, and system.get_all for on-demand polling.
Verified: pio run on both vesper-std-v1 and agnus-v1 (no-SD variant).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Startup retry count, runtime failure count, and backup partition info were
tracked internally (NVS-persisted) but only visible via LOG_* output — not
queryable remotely. Added getStartupRetryCount()/getRuntimeFailureCount()
getters and extended firmware.status with startup_retry_count,
max_startup_retries, runtime_failure_count, max_runtime_failures,
backup_version, backup_is_valid.
F-049 in the feature catalog. Also finalizes the feature-catalog.md and
api-reference.md updates for F-045/F-046/F-047/F-048 from the two prior
commits (doc content is consolidated into this final commit rather than
split across the changeset).
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.
network.info now returns all addressing/identity fields needed by the console
network panel: ip, subnet, gateway, dns, mac, hostname, ssid, connection_type.
Previously only returned ip, gateway, dns.
network.status slimmed to pure runtime/health data: connected, ap_mode, rssi,
uptime_ms, state. Removed ip, mac, hostname, ssid, type — static facts now
belong in network.info.
Feature catalog updated with F-043 and F-044 detail sections.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- updateClockBacklight: fix key names to match wire format
(backlight/backlight_output/backlight_on/backlight_off instead of enabled/output/onTime/offTime)
- handleGetConfig: convert stored 0-based bell indices back to 1-based for hour_bell/half_bell/quarter_bell
(255 disabled sentinel passed through unchanged)
- handleGetConfig: include gmt_offset_sec, dst_offset_sec, ntp_server from TimeConfig
so clock.get_config supersedes clock.get_timezone
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Enforce 1-based output numbering throughout the entire stack. Stored values,
MQTT wire format, and console UI are all 1-based; the single 0-based conversion
happens only in OutputManager::getPhysicalOutput(). Fixed createDefaultBellConfig
(was setting identity 0-based map instead of 0=disabled), updateBellDurations and
updateBellOutputs (support both v2 0/1 and v1 b1/b2 keys), all call
sites that bypassed getPhysicalOutput, and fireClockOutput conversion.
New commands:
- relay.set_config: combined durations + outputs in one round trip (F-040)
- clock.set_config: enabled/c1/c2/pulse_duration/pause_duration in one call (F-042)
- clock.set_alerts_config: alert type, bells, and silence windows in one call (F-042)
Feature catalog updated with F-040, F-041, F-042 detail sections.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
relay.test_bell — fire bell N using configured output + duration, non-blocking
relay.test_batch — fire a list of bells simultaneously (single melody step)
clock.test_c1 — fire C1 (ODD) clock output using pulse_duration
clock.test_c2 — fire C2 (EVEN) clock output using pulse_duration
All four bypass bellsEnabled guard intentionally — test commands always fire.
ClockHandler now accepts an optional OutputManager* for the test commands.
CommunicationRouter passes _outputManager to ClockHandler.
Feature catalog updated: F-038 and F-039 added.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds full bidirectional remote control across all major subsystems,
establishing the device as the single source of truth for all settings.
New firmware features (F-029 to F-037):
- bells.enable / bells.disable: master ON/OFF for all playback and clock
alerts (relay.test_output intentionally unaffected)
- telemetry.set_guard_enabled: enable/disable thermal protection at runtime
without touching thresholds
- telemetry.set_max_loads: set bellMaxLoad per-bell or globally via command
- Device runtime tracking: lifetime seconds flushed to SD every 10 min,
boot log (up to 200 entries, rotating) written after first NTP sync
- Total playback counter persisted to SD, increments on every play()
- telemetry.get_metrics / telemetry.reset_metrics: new aggregate read + reset
- system.get_config (replaces system.get_settings, old name still accepted),
system.get_all (everything in one call), system.get_telemetry
- log.get_config, mqtt.get_config, bells.get_config: new getters for
previously write-only subsystems
- network.status now includes ssid, mac, hostname
- BellsHandler: new handler registered on CommandBus
- LegacyAdapter updated with all new command mappings
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
F-024 — V1 single-segment fix: when continuous_loop=false, total_duration is
now always overwritten with segment_duration regardless of what the client
sent. Sending total_duration:0 explicitly no longer bypasses the stop timer.
The play-once fallback in onMelodyLoopCompleted is tightened to only fire when
both segment_duration and total_duration are zero.
F-025 — V2 command namespace: PlaybackHandler now registers playback.play and
playback.stop instead of the old root-level playback command. LegacyAdapter
maps V1 { cmd:playback, action:play/stop } to the new V2 names so all deployed
clients keep working without changes.
F-026 — V2 mode field: setMelodyAttributes accepts a mode string (single /
timed / interval / infinite) with a duration field, replacing the ambiguous
continuous_loop + segment_duration + total_duration triplet. V1 timing fields
are still parsed when mode is absent.
Docs: feature-catalog.md entries F-024, F-025, F-026 added.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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>
- Version.hpp: extract FW_VERSION from main.cpp into shared header
- OTAManager: replace uint16_t version with SemVer struct; update API URLs
to new FastAPI backend (/api/firmware/{hw_type}/{channel}/latest);
add postDownloadTelemetry() and postFlashTelemetry() for fleet visibility
- ConfigManager: remove fwVersion from DeviceConfig (always read from
FW_VERSION constant); saveDeviceConfig/loadDeviceConfig are now no-ops;
fallbackServerUrl replaced with fallbackServerUrls[2] array
- HealthMonitor: add AlertCallback + setAlertCallback() firing on state
transitions (including CLEARED on recovery)
- CommunicationRouter: wire HealthMonitor alert callback on begin();
add publishAlert() and publishInfo() for MQTT status topics
- MQTTDriver: add _alertsTopic + _infoTopic; add publishDirect() for
absolute topic publishing; migrate heartbeat to JsonDocument
- ResponseBuilder, ClientManager, BellEngine: StaticJsonDocument /
DynamicJsonDocument → JsonDocument; remove dead notifyBellsFired()
- docs: reorganise into architecture/, dev/, features/, reference/
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Delete dead code: CommandHandler (700-line God Class) and
HTTPRequestHandler — both replaced by new architecture in Stage 4
- Create Drivers/ group for the three low-level protocol drivers,
mirroring the Transport/ pattern:
MQTTAsyncClient → Drivers/MQTTDriver (class: MQTTDriver)
WebSocketServer → Drivers/WebSocketDriver (class: WebSocketDriver)
UARTCommandHandler → Drivers/UARTDriver (class: UARTDriver)
- Update all includes and type references across CommunicationRouter,
all three Transport wrappers, and MQTTHandler
- Add -std=gnu++14 + build_unflags to platformio.ini so std::make_unique
compiles on ESP32 (required by CommunicationRouter::registerHandlers)
Build: passing
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds the complete set of v2 command handlers. Old CommandHandler is
untouched — handlers are standalone and not yet wired to anything.
Handlers added:
PlaybackHandler — playback (1 dependency)
LoggingHandler — log.set_serial/sd/mqtt
FileHandler — files.list/list_builtin/download/delete
TelemetryHandler — telemetry.get_strikes/reset_strikes/get_loads
RelayHandler — relay.set_durations/set_outputs/get_config/test_output
FirmwareHandler — firmware.status/commit/rollback + ota.update/custom
NetworkHandler — network.info/status/set_config
MQTTHandler — mqtt.enable/disable
SystemHandler — ping/identify + system.* commands (8 total)
ClockHandler — 16 clock.* commands
Notable fixes vs. original CommandHandler:
- clock.set_timings now sets pulseDuration/pauseDuration correctly
(original called updateClockOutputs — was a bug)
- system.restart uses a deferred FreeRTOS task (no blocking delay)
- relay.test_output safety-gated: player must be fully stopped
- Timekeeper class name (lowercase k) corrected throughout
Two compile-time fixes applied during build:
- JsonVariantConst → const_cast<JsonDocument&>().as<JsonVariant>()
(ConfigManager methods take non-const JsonVariant)
- class TimeKeeper → class Timekeeper (actual class name in header)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds the core data structures and interfaces for the comms refactor.
No behaviour change — old CommandHandler is completely untouched.
New files:
CommandEnvelope.hpp — universal message wrapper (transport + command + reply lambda)
CommandResult.hpp — standardised return type with ok/err/info factories
ICommandHandler.hpp — interface every domain handler will implement
ITransport.hpp — interface every transport layer will implement
CommandBus.hpp/.cpp — registry + dispatcher (std::map, O(log n) lookup)
Two minor corrections vs. plan:
std::unordered_map → std::map (Arduino String has no std::hash)
LOG_WARN → LOG_WARNING (codebase macro name)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>