playbackLoop() slept 500 ms after every loop whenever the run had no end
time (infinite, interval with total_duration 0, v1 continuous_loop with no
total), so those modes paused between loops while timed / interval with a
total did not. The delay was meant to give Player time to pause/stop, but
play-once already stops synchronously in onMelodyLoopCompleted(), stop is
checked before every pass and pause after every loop. Every looping mode
now plays loop-to-loop with no gap; single is unaffected.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"infinite" now optionally plays duration ms, pauses pause_duration ms and
repeats until playback.stop, the same as "interval" with total_duration 0,
which is what people expect "infinite" to mean. Sending neither keeps the
old back-to-back looping; sending only one is rejected, since a duration
without a pause flickers paused/playing and a pause without a duration
never triggers. total_duration is never read for infinite.
api-reference.md now documents the exact timing of every mode: 500 ms
tick, loops never cut short, paused/stopping status transitions, pause
measured from the loop end, total_duration including pauses, and the
~0.5 s engine gap between loops when the run has no end time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
timeToResume() measured the pause from segmentCmpltTime, which still held
the previous loop's end while the engine finished the loop that was playing
when the pause was flagged. A pause_duration shorter than one melody loop
therefore resumed before the bells ever went quiet. Only start counting
once that loop has ended (segmentCmpltTime >= pauseTime).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
recordPlayback() and saveStrikeCounters() wrote JSON to SD inline in the
async_tcp task, before playback.play/stop could send their reply. They now
set a pending flag and notify TelemetryTask, which writes within ms. The
task's periodic work keeps its 1 s cadence (checkBellLoads decays per call);
pending writes are held during the OTA pause. Verified on hardware: the reply
now goes out before the SD write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Today's MQTT reliability/latency work and the infinite-mode fix were
committed without a version bump. 2.4.0 (minor: adds mqtt.status, changes
QoS and reconnect timing). docs/README.md gains rule 6: every change bumps
FW_VERSION (patch = fixes, minor = features/behaviour, major = discuss with
owner first) in the same commit, with the history comment and catalog
"Since" column updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"infinite" maps to continuous_loop=true with segment_duration=0, and
timeToPause() only checked continuous_loop, so every duration-timer tick
paused and the next resumed: ~2 status broadcasts per second on WebSocket
and retained MQTT status/playback for the whole melody. Zero segment length
now means "no segments". Found and verified on hardware.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- MQTTDriver::publishConfirmed(): QoS 1 + PUBACK tracking (8 s; heartbeat
20 s). A missed PUBACK forces a reconnect. status/playback relies on the
existing republish-current-state-on-connect; control/reports are resent
after the next CONNACK (newest 4). Publish + registration under one
recursive mutex since the PUBACK can arrive before publish() returns.
- AsyncMqttClient vendored into lib/ (upstream 3d93fc7) with one patch:
_onPubAck()/_onPubComp() call _handleQueue(), so a QoS 1 message delays
the next packet by one RTT instead of RTT + up to ~500 ms.
- platformio.ini: platform and every library pinned to the exact versions
already being built (git deps by commit). Clean-libdeps rebuild verified
to resolve the same AsyncTCP and the vendored AsyncMqttClient.
- Removed board_build.cmake_extra_args (timer stack): no effect on Arduino
builds, the SDK is precompiled with 2048. Replaced by a warning comment.
- mqtt.status gains resent_messages and the new forced-reset reasons.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Device went cloud-silent after days of uptime while WebSocket kept working;
last thing on status/heartbeat was garbage. Causes and fixes:
- LWT payload was a dangling pointer: setWill() stores the raw char*, begin()
passed a temporary String. The broker published freed heap as the Will on
the unclean drop. Now held in _willPayload.
- Reconnect/stabilisation/heartbeat timers each xTaskCreate()d a short-lived
task with the result ignored; one failed allocation ended the one-shot
reconnect chain for good. Replaced by one persistent supervisor task that
polls WiFi.status() itself, reconnects with backoff (cap now 60 s), sends
the heartbeat, and force-resets the client when a connect attempt is stuck
for 30 s or the heartbeat PUBACK is missing for 20 s.
- New mqtt.status command (all transports) exposes connect/disconnect
counters, last reasons and forced resets for post-mortems over WebSocket.
Latency (F-072): AsyncMqttClient holds its queue behind every QoS 1 PUBACK
and only resumes on the ~500 ms poll, so each QoS 1 message cost RTT + up to
500 ms. All publishes are now QoS 0 except the heartbeat (liveness probe);
cleanSession=true on both ends meant QoS 1 never gave redelivery. WiFi modem
sleep disabled on connect to remove DTIM-induced RX delays.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Crash reports only carried the coredump's PC/cause/vaddr, which for every
abort() is panic_abort()'s own write to 0x0 - so all aborts looked the same.
- Read the coredump backtrace (up to 16 PCs) and crashing ELF SHA prefix
- Wrap esp_system_abort (-Wl,--wrap) to keep the abort/assert/stack-overflow
message in RTC_NOINIT memory across the reboot
- TelemetryTask snapshots uptime/free heap/largest block/min free heap into
the same RTC block every second
- Reported in MQTT boot_report and SD boot log as crash.backtrace,
crash.elf_sha256 and a new pre_crash object (additive)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No fielded Vesper Standard unit has an RF receiver, but vesper-std.hpp set
HAS_RF 1, so every build ran the RF task on GPIO 22 and exposed rf.*
commands that could never do anything. Set HAS_RF 0 (RF_RX_PIN kept for a
future RF revision). rf.* now return "Unknown command" on this build; agnus
keeps RF. Docs updated to say rf.* is agnus-only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A play that needed a download was ACKed SUCCESS and then nothing was
visible until playback started — and a failed download was only logged.
- New PlayerStatus::LOADING: status/playback publishes action "loading"
(pid/speed/duration/source set) before the ACK, then "playing" on success
or "idle" on failure.
- On failure after the ACK, control/reports gets
{ "type": "playback_failed", "payload": { "pid", "reason" } } (and a WS
INFO of the same). The download task re-checks bells-disabled/overload
before playing.
- playback.stop / forceStop during LOADING cancels the pending start
("Download cancelled — playback will not start"); the transfer finishes
and is discarded. New plays are refused until it does, since the task
still owns pid/_melodySteps. A mutex serialises the task's cancel-check +
play() against the cancel path.
- "loading" is MQTT-only: v1 tablets map unknown WS playback actions to
"unavailable" (F-061 symptom). system.status reports LOADING; the v1
adapter maps it to "idle".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every rejection used to reach the caller as "Playback command failed".
Player::command() now returns PlayerCommandResult { ok, message } and
PlaybackHandler forwards the message verbatim:
- busy, missing pid, invalid speed / note_assignments / durations / mode,
timed|interval without duration, bells disabled, bell overload lockout,
melody failed to load (incl. 0-byte file), not found without url,
needs download but no SD card
- success: "Playback started", "Melody download started — …",
"Playback stopped", and "Already stopped" (stop while idle stays SUCCESS —
idempotent, goal state reached)
Validation runs before setMelodyAttributes(), so a rejected play no longer
half-applies its fields. Also fixes: url was sticky (a later play of another
pid could download the old URL under the new name); bells.disable let a play
"succeed" and report playing with silent bells; a non-string name/pid
assigned nullptr to std::string.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
status/playback is retained but was only published on a Player transition.
After a power loss mid-melody the Player boots straight into STOPPED with no
transition, so the broker kept serving the old "playing" forever. The
MQTT on-connect callback now publishes Player::getPlaybackSnapshot() on
every CONNECT (not just the first after boot) — "idle" after a reboot, the
live state after a plain reconnect.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Player::setStatus() publishes action "stopping" when the run-time cap is
reached and BellEngine is finishing the current melody loop, but the spec
only listed playing/paused/idle. Kept it (not suppressed): it is a real
state that can last a whole loop while bells still ring, suppressing it on
MQTT alone would break WS/MQTT parity, and v1 tablets already know it.
Adds a state table (entry/exit, stop/play behaviour) to mqtt-events.md and
updates the topic spec and API reference. No firmware change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The remote phone app treats status/playback as the source of truth for what
the board is doing, but the payload couldn't say what was playing, and a
client receiving a stale retained message couldn't work out real elapsed
time. Adds (old fields kept):
- pid, speed, duration (effective stop timer after mode/legacy resolution)
- started_at / ts — Unix epoch s (UTC); system clock once NTP-synced, else
new Timekeeper::getUtcEpoch() (RTC local time minus configured offsets),
else 0
- source — app | rf | button | schedule | unknown. Carried, not guessed:
new CommandEnvelope::origin set by each transport (MQTT/WS/HTTP → APP,
UART slave board → BUTTON), mapped by PlaybackHandler; RFRemote passes RF
New PlaybackState.hpp has one PlaybackSnapshot::writeTo() used for both the
WebSocket INFO broadcast (under "payload") and MQTT status/playback (flat),
so local and remote clients match. publishPlayback() now honours the
hasHeapForPublish() guard before building the document.
Bumps FW_VERSION to 2.3.0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Invalid JSON or a missing 'cmd' field on control/command previously logged
a WARNING on serial and returned with no reply at all — a client waiting
on control/ack had no way to tell "malformed request" apart from "message
never arrived" or "device offline," all three looking identical until its
own timeout fired.
Both onMessage() drop paths now publish an ERROR to control/ack before
returning: { "status": "ERROR", "type": "parse_error", "message": "..." }.
Unparseable JSON necessarily has no req_id (nothing to read it from); a
valid-but-cmd-less message echoes req_id if one was present. The heap-guard
drop above these two (hasHeapForPublish() check) is untouched — that one's
silence is deliberate, protecting against allocation under critical heap
pressure (see F-055), not something this fix should touch.
Bumped to v2.2.1. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Full MQTT topic rebuild per docs/reference/vesper_mqtt_topic_spec_v2.md.
Only the MQTT transport path changed — WebSocket, HTTP, and UART are untouched.
- control/command (in) + control/ack (out, strictly replies) replace the old
control/data pair; new control/reports for critical unsolicited events
(bell overload) that don't belong on the strictly-reply ack channel
- status/playback split out for playback transitions only
- status/alerts + status/info renamed to system/alerts + system/info, both
now correctly retained; new system/logs and system/metrics (diagnostics
report moved here from system/info, gained bell strike/heat data)
- LWT registered for the first time — status/heartbeat gets
{"state":"offline","ok":false} on an unclean disconnect; graceful
disconnect (mqtt.disable) announces offline explicitly since LWT doesn't
fire on a clean disconnect
- heartbeat payload flattened, gains independently-derived state/ok fields
(via a new MQTTDriver::setStateProvider() wired from Player+HealthMonitor)
- optional req_id correlation added bus-wide (CommandEnvelope/CommandResult),
not MQTT-only, since any transport with multiple senders sharing one
channel has the same problem. Always optional — v1 clients unaffected.
- per-topic ON/OFF switches (ConfigManager::MqttTopicConfig, 8 flags) as
sub-switches under the existing mqtt.enable/disable master switch, so a
device can breathe by disabling topics it doesn't need. New
mqtt.get_topics/mqtt.set_topics commands; command switch applies live.
Bumped to v2.2.0. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The catalog's "Since" column was being hand-incremented per entry
(2.1.0 -> 2.1.7) independently of src/Version.hpp, which stayed at
2.0.3 the entire time these features were built (2026-07-07 through
2026-07-20). The version was only actually bumped straight from 2.0.3
to 2.1.0 on 2026-09-17 (commit 2707594), well after all of F-024-F-060
had landed, so that's the version they really shipped in. F-061 is the
only entry that landed after the 2.1.0 bump, correctly shipping in
2.1.1.
Also fixes F-051, which had been left at a stale v2.0.3 despite
landing the same day as its v2.1.3-tagged neighbors — the clearest
sign these tags were manual guesses, not derived from the real build.
Added a note above the index to tag future entries from the actual
FW_VERSION in src/Version.hpp instead of guessing an increment.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
F-061 (LegacyResponseAdapter) shipped in 230c1ed without a version bump.
Also corrects the F-060/F-061 catalog version tags from the mistaken
v2.1.7 to the actual v2.1.1 they ship in.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Standalone Arduino test sketches for IS31FL3193 LED driver and PCF8575/PCF8574
relay bring-up (not part of the PlatformIO build), a known-issues note, and
two Dart files from the tablet app kept as reference for the comms protocol.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
LegacyAdapter already translates incoming v1 requests to v2 internal
commands, but v2 handler replies used v2-only conventions (namespaced
type strings, data nested under "data", UPPERCASE status enum,
object-keyed strike_counters). A v1-only Flutter app polling
system.status never recognised the reply, hit its own 5s request
timeout, and its catch block explicitly set the UI to "unavailable" —
even though the device was playing correctly and had already replied
in time. Not a connectivity bug; a pure reply-schema mismatch.
Adds LegacyResponseAdapter, the reply-side mirror of LegacyAdapter: a
narrow, allowlisted translator that rewrites a CommandResult back into
v1 shape, but only for replies to requests whose original envelope
version was 1. Wired into WebSocket, MQTT, and HTTP's general command
path by capturing envelope.version before CommandBus::dispatch()
overwrites it to 2. v2 clients and all other reply types are
untouched, byte-for-byte.
This is deliberately temporary migration scaffolding for the v1→v2
tablet rollout window, not new permanent architecture — designed to be
deleted alongside LegacyAdapter in one PR once fleet telemetry shows
zero v1 requests. Full rationale and removal steps in
docs/architecture/legacy-response-adapter.md.
Verified: pio run across all four environments (vesper-std-v1,
agnus-v1, agnus-mini-v1, bespoke-rs485-v1).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Device identity (serial/hw_family/hw_revision) has been read-only from
production firmware since NVS provisioning — serial derives the MQTT
password and hw_family/hw_revision select the OTA channel, so an
uncontrolled write path could desync MQTT auth or brick OTA to the
wrong hardware. This adds one narrow, deliberate exception: an
MQTT-only system.set_identity command for correcting a
mis-provisioned unit or reassigning a serial after a board swap,
without a USB/serial reflash.
Rejected over WebSocket/HTTP/UART by design (same pattern as
identify's WebSocket-only check); requires all three fields together
to avoid partial-identity states; forces a reboot after a successful
write since MQTT credentials/hostname/AP SSID are derived from serial
only once at boot. Firmware does not update the backend device record
itself — that's the caller's (console's) responsibility in the same
operation.
Also includes docs/README.md's rule 6 (console API reference sync
requirement) from an earlier uncommitted session, which this change
follows.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Pre-OTA sanity check ahead of pushing this firmware to 6-7 units still
running the pre-restructure firmware. All four PlatformIO environments
were building against min_spiffs.csv, but field devices were originally
flashed via Arduino IDE with PartitionScheme=no_fs — the two tables
disagree on app1's offset (0x200000 vs 0x1F0000) and both app slot
sizes, because min_spiffs.csv carves out an unused 128KB spiffs
partition this firmware never touches (SD-card only, zero SPIFFS/
LittleFS references anywhere in the codebase).
OTA cannot migrate a device from one partition table to another — the
bootloader and running app both resolve offsets from a boot-time
snapshot of the table at flash 0x8000, which OTA never reads or
writes. A device still on the old no_fs table has no partition entry
at 0x1F0000, so a min_spiffs-built OTA image can never land where it
needs to be; forcibly rewriting that sector via OTA is an unsupported,
unrecoverable-on-power-loss operation Espressif explicitly warns
against.
Added no_fs.csv (copied verbatim from the Arduino ESP32 core) and
switched every environment to it. Verified the built partitions.bin
decodes to a byte-for-byte match of what's already burned into field
devices. No functionality lost — each app slot actually gained ~64KB
by dropping the unused spiffs partition. OTA to existing field devices
is now safe without any USB/serial reflash.
Catalog entry: docs/features/feature-catalog.md F-059.
Console wants a "reset device stats before shipping" button for staff to
clear QA-bench data (test reboots, debug log spam) without wiping actual
device configuration. telemetry.reset_strikes and telemetry.reset_metrics
already covered bell strikes and runtime/playback counters — this adds the
two gaps: lifetime boot count + SD boot history, and SD debug logs.
Deliberately does not touch FirmwareValidator's NVS namespace (rollback
safety state, not history) or device identity NVS (serial/hw_family).
Verified: pio run on all four board variants.
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.
Decoded a new crash via addr2line against the exact flashed ELF:
console reported faulting task "async_tcp", cause 29, vaddr 0. Full
backtrace traced through AsyncTCP's _async_service_task ->
AsyncMqttClient::_onData -> MQTTTransport::onMessage ->
CommandBus::dispatch -> the reply path -> MQTTDriver::publish ->
AsyncMqttClient::publish -> PublishOutPacket's vector::reserve ->
operator new failing -> unhandled C++ exception -> abort().
Root cause is heap fragmentation, not a single bad allocation: rapid
relay.test_bell commands with Verbose/Debug logging meant every
command triggered ~4-5 JsonDocument/String allocations (RX log,
dispatch log, handler log, MQTT log-channel copies, reply publish),
all on AsyncTCP's own task, faster than the allocator could coalesce
freed blocks between cycles. Two "JSON parse error: NoMemory"
warnings preceded the abort by seconds - an early symptom of the same
fragmentation.
Checked why this can't be a catchable exception: this SDK build has
CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so when the heap is
too fragmented to even allocate the object needed to throw
std::bad_alloc, it aborts instead of throwing. That's baked into the
precompiled Arduino-ESP32 core; fixing it means rebuilding the whole
ESP-IDF core from source, judged out of scope. Chose prevention over
a catchable-exception fix.
Adds MQTTDriver::hasHeapForPublish() (20KB threshold, chosen with
margin above the ~62KB-free-but-already-fragmented state seen at
crash time) and applies it before every allocation-heavy publish path
(publish, publishDirect, publishHeartbeat) and before MQTTTransport::
onMessage() does its own incoming-command deserialization. Skip
warnings use Serial.printf directly, not LOG_*, to avoid recursing
into the same low-heap condition via MQTT-channel logging.
Also corrects how coredump crash detail should be read for abort()-
reached crashes (vs. true hardware exceptions like the F-051 stack
canary trip): pc/exc_cause/exc_vaddr describe abort() internals in
this case, not the original fault site - only the task name is
reliably the "real" crash location. Documented for console/dashboard
consumers in feature-catalog.md F-055.
A full fix (queueing incoming commands off AsyncTCP's task, mirroring
the F-051 logging-queue redesign) is scoped out as a documented
future improvement, not rushed into this change.
Verified: pio run on vesper-std-v1 and agnus-v1.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
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>
Logging::log() previously ran AsyncMqttClient::publish() and SD file
writes synchronously on whatever task called LOG_*. Both are
variable-depth, stack-hungry operations, and this is what let
TelemetryTask's 4096B stack silently absorb enough nested cost to
overflow its canary (see feature-catalog.md F-051).
Serial output stays synchronous (cheap, and must reflect true event
order for crash debugging). MQTT/SD-bound messages are now copied
into a fixed-size LogQueueItem (256-byte message cap, audited against
real LOG_* call sites — worst case ~150-180 chars, comfortable
margin) and handed via non-blocking xQueueSend to a lazily-created
LoggingTask, which performs the actual publish/write on its own
4096B stack. A full queue drops the line rather than blocking the
caller. Queue+task creation is spinlock-guarded against concurrent
first-callers.
This removes the stack-nesting risk for every current and future
task that logs, not just Telemetry/HealthMonitor — closing the
broader risk flagged in F-051 for OutputManager, TimeKeeper,
MQTTDriver's own tasks, and Networking's netRecon.
Verified via pio run: RAM impact negligible (62980 vs 62956 bytes).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
TelemetryTask (4096B) overflowed its stack canary because
flushRuntimeToSD() nests ArduinoJson serialization + SD write + a
LOG_DEBUG call that fans out to Logging::log()'s 512B format buffer
and publishToMqtt()'s String + AsyncMqttClient::publish() — all on
the same small stack. Bumped to 8192B.
HealthMonitor's monitoring task shares the same nested-logging
pattern (11 LOG_* calls per health check pass) and was judged next
most likely to trip, so bumped 4096B -> 6144B pre-emptively.
RAM headroom confirmed fine post-bump (19.2%, 63KB/320KB used).
Root cause, other at-risk tasks, and the planned logging-queue
redesign are documented in feature-catalog.md F-051.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
SD lines previously carried only millis(), which is meaningless when reading
a log file after the fact without knowing when boot happened. New format:
2026-07-15 | 12:28:04 | 13460843 -> 🔵 [DEBG][OutputManager] message
Date/time from time(nullptr), set by NTP (Timekeeper::syncTimeWithNTP) —
works regardless of HAS_RTC. Falls back to "unset-date | unset-time" if NTP
hasn't synced yet, rather than printing a bogus 1970 epoch date. Also added
the level icon to SD lines (previously Serial-only) for faster visual
scanning when reading a raw log file.
F-050 in the feature catalog.
Confirmed on hardware: enabling SD logging at INFO level caused a boot loop
within seconds — "Guru Meditation Error... Stack canary watchpoint triggered
(mqttConnect)". appendLogLine() was running pruneLogDirectory() (a full
SD.open() directory scan + std::vector<pair<String,size_t>> build) on every
single log write, and the first write happened to land on MQTTDriver's
3KB-stack connect task.
Fixes:
- Prune check now throttled to once per 50 writes instead of every write —
removes the expensive directory scan from the hot logging path entirely.
- Bumped mqttConnect/mqttRecon/mqttHB task stacks from 3072 to 4096 bytes
as defense-in-depth, since these tasks can still trigger SD log writes.
- Removed a LOG_INFO call inside pruneLogDirectory that could have re-entered
Logging::writeToSd() from within the SD write path itself.
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).
WiFi signal strength (dBm) now included in every heartbeat message.
Docs updated: MQTTDriver README, api-reference, heartbeat feature doc.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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>
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>
The ESP32 mbedTLS TLS handshake requires ~40KB of contiguous heap, which is
not reliably available after runtime heap fragmentation. Melody .bsm files
carry no credentials so plain HTTP is acceptable.
Removed: WiFiClientSecure, esp_task_wdt WDT disable/re-enable around the GET,
SSL heap guard, and all secureClient cleanup paths. HTTPS URLs are now rejected
immediately with a clear error log (F-027).
Also fixed: ensureDirectoryExists now strips trailing slashes instead of
appending one — SD.exists() returns false for directories when a trailing
slash is present.
Docs: feature-catalog.md F-027 added, FileManager README updated.
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>
Establishes the production workflow:
- docs/features/feature-catalog.md: index + detail entries for all 23
known features (F-001 through F-023), seeded from git history and
current uncommitted changes
- docs/README.md: replaced loose notes with enforced Working Rules
section (feature catalog mandate, commit discipline, session startup)
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>