Commit Graph
96 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 92a0a8d5e8 fix(CommunicationRouter): republish status/playback on every MQTT (re)connect (F-066)
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>
2026-09-29 20:11:20 +03:00
bonaminandClaude Opus 5.5 fe5ab6223c docs(playback): formally document the "stopping" status/playback state (F-065)
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>
2026-09-29 20:10:03 +03:00
bonaminandClaude Opus 5.5 204b54fce1 feat(Player,MQTT): add pid/speed/duration/started_at/source/ts to status/playback (F-064)
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>
2026-09-29 20:09:16 +03:00
bonaminandClaude Opus 5.5 b80dbc9b89 docs(api-reference): audit against real handlers — playback.play/stop, message/data envelope, ~30 missing commands
The API reference had drifted far from the firmware. Rewritten against the
handlers' commands() lists, field parsing and CommandResult::err() strings:

- Playback: document playback.play / playback.stop (the bare v2
  cmd:"playback"+action form returns "Unknown command"; v1 form still works
  via LegacyAdapter, and is the only form UART's whitelist accepts). List the
  fields Player::setMelodyAttributes() actually parses (url, not download_url),
  how mode/duration interact, the legacy segment_duration/total_duration
  path, sticky fields, and reply type "playback".
- Response envelope: message (string) + data (object), status INFO only on
  WS broadcasts, no "payload" key; req_id is MQTT-only; v defaults per
  transport; type exceptions (pong/playback/unknown/parse_error/bad_request).
- Add missing commands: relay.set_config/test_bell/test_batch,
  clock.set_config/set_alerts_config/test_c1/test_c2, system.get_config/
  get_all/get_telemetry, ota.set_channel, log.get_config, logs.clear, all
  telemetry.* and bells.*. Remove nonexistent ota.status/ota.check.
- Fix wrong fields: clock.set_alerts is camelCase, clock.set_silence is
  nested, clock.set_time offsets need both fields, clock.set_timezone has no
  timezone_name, files.download needs download_url, ota.update defaults to
  "stable", RF play-slot fields are required (duration 0 rejected), fix legacy
  map to match LegacyAdapter.
- mqtt-events.md: fix the control/command example; note nothing calls
  CommandBus::broadcast(). Topic spec: req_id is MQTT-only today.

Doc-only — no catalog entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:02:58 +03:00
bonaminandClaude Sonnet 5 4ea581af5b fix(MQTTTransport): reply with error instead of silently dropping malformed input (F-063)
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>
2026-09-21 18:06:26 +03:00
bonaminandClaude Sonnet 5 391ecb63fc feat(MQTT): rebuild topic spec to v2 (F-062)
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>
2026-09-21 10:48:36 +03:00
bonaminandClaude Sonnet 5 20576f12ff docs(feature-catalog): fix fabricated version tags for F-024 through F-060
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>
2026-09-18 09:09:54 +03:00
bonaminandClaude Sonnet 5 1a7706d695 chore(version): bump to 2.1.1 for LegacyResponseAdapter fix
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>
2026-09-18 08:54:40 +03:00
bonaminandClaude Sonnet 5 2748cd5cce docs: add hardware bring-up sketches, known-issues note, and tablet reference
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>
2026-09-18 08:36:31 +03:00
bonaminandClaude Sonnet 5 230c1edfed fix(Communication): add LegacyResponseAdapter — v1 tablets saw device as unavailable while playing (F-061)
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>
2026-09-17 22:44:12 +03:00
bonaminandClaude Sonnet 5 2707594f65 chore(version): bump to 2.1.0
Corrects builds that were incorrectly shipped as 2.0.11 before the
firmware was properly rebuilt. First 2.x release to be tested on the
field.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 22:18:51 +03:00
bonaminandClaude Sonnet 5 64a8bc2b88 feat(SystemHandler,ConfigManager): add system.set_identity sysadmin command (F-060)
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>
2026-07-20 20:09:39 +03:00
bonamin 28b175b4fc fix(platformio): match partition table to already-deployed field devices
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.
2026-07-20 10:33:19 +03:00
bonamin 99ca468b54 docs(feature-catalog): add F-058 for NTP sync RTC corruption fix
Catalog entry for the TimeKeeper NTP fix committed in e89a1b6 —
missed in the same commit, adding immediately after per Rule 1.
2026-07-20 09:12:22 +03:00
bonamin e89a1b623f fix(TimeKeeper): guard NTP sync against reconnect storms and bad readings
Field units on unstable internet had RTC time drift wildly (10 min to
half a day), while units with stable internet stayed accurate. Root
cause: syncTimeWithNTP() wrote getLocalTime()'s result straight to the
RTC with no plausibility check, and fires on every WiFi reconnect
(not a fixed schedule) — so flaky links produced far more unguarded
sync attempts than healthy ones. The underlying configTime()/
getLocalTime() API has no request/response correlation, so a stale
reply from an abandoned attempt could be picked up by a later
attempt's window if reconnects outpaced a single attempt's ~5s resolve
time.

Three layers of defense, all in TimeKeeper:
- In-flight de-dup guard (ntpSyncInProgress) so only one sync attempt
  is ever listening at a time, closing the window a stale reply could
  land in.
- 10s cooldown between attempts to throttle reconnect storms.
- commitNtpResult(): corrections under 2 minutes commit immediately
  (normal drift); anything larger is held as a pending candidate and
  only written to the RTC once 3 consecutive syncs agree within 5s of
  each other, so a single bad reading can no longer move the clock by
  hours.

Documented in TimeKeeper/README.md under "NTP sync safety".
2026-07-20 09:08:05 +03:00
bonamin f41332a771 feat(Telemetry,FileManager,LoggingHandler): QA-to-shipping stats reset — telemetry.reset_boot_data + logs.clear
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.
2026-07-17 14:14:55 +03:00
bonamin 959cb77d81 feat(Telemetry,Networking,OTAManager,CommunicationRouter): diagnostics report — CPU temp, WiFi reconnects, OTA state, stack high-water mark
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.
2026-07-17 13:09:16 +03:00
bonaminandClaude Sonnet 5 9cd6b142ef fix(MQTTDriver,MQTTTransport): free-heap guard prevents heap-exhaustion abort() under command bursts
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>
2026-07-16 18:47:39 +03:00
bonaminandClaude Sonnet 5 8546604490 feat(MQTTDriver,SystemHandler): free_heap on heartbeat + ping RTT timestamp echo
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>
2026-07-16 12:32:51 +03:00
bonaminandClaude Sonnet 5 957c283788 feat(Telemetry): expose SD boot history via telemetry.get_boot_history, fix counter drift
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>
2026-07-16 11:41:17 +03:00
bonaminandClaude Sonnet 5 829ae23f09 feat(Telemetry,CommunicationRouter): lifetime boot counter + coredump crash detail over MQTT
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>
2026-07-16 11:17:41 +03:00
bonaminandClaude Sonnet 5 381465cfe4 fix(Logging): defer MQTT/SD publish off the caller's stack via dedicated task+queue
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>
2026-07-16 09:39:57 +03:00
bonaminandClaude Sonnet 5 838e206a82 fix(Telemetry,HealthMonitor): bump task stacks to fix reboot-every-10min crash
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>
2026-07-16 09:22:11 +03:00
bonamin 326ae2b767 feat(Logging): prefix SD log lines with wall-clock date/time + uptime
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.
2026-07-15 00:33:05 +03:00
bonamin e737769887 fix(FileManager): SD log pruning caused stack-canary panic on MQTT connect task
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.
2026-07-15 00:21:52 +03:00
bonamin 7675a67c90 feat(FirmwareValidator): expose rollback safety-net diagnostics via firmware.status
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).
2026-07-15 00:04:42 +03:00
bonamin 85cdc55b78 feat(Logging): per-subsystem token-bucket rate limit on MQTT publish
Protects the broker/airtime from a chatty or misconfigured subsystem (e.g. a
per-subsystem override left at VERBOSE via log.set_mqtt). Each tag gets a
burst of 10 messages, refilling 1/second; once exhausted, further messages
from that tag are dropped until it refills.

Drops are counted, not silently discarded: the next time a rate-limited tag
publishes again, a WARNING summary line reports how many were suppressed.
Serial and SD channels are unaffected.

F-047 in the feature catalog.
2026-07-15 00:04:31 +03:00
bonamin 2b4fd7c5b0 fix(FileManager,Logging): day-rotated SD logs + boot reset-reason reporting
SD logging was a silent no-op on fresh cards: appendLine() opened /logs/vesper.log
in FILE_APPEND without ever creating the /logs directory first. FileManager now
exposes appendLogLine(), which creates the directory, rotates to YYYY-MM-DD.log
files, and prunes oldest files once a 512KB total budget is exceeded.

LoggingHandler gains logs.list / logs.download commands (chunked, paginated) so
SD logs can be pulled off a device remotely for offline-device troubleshooting.

Telemetry now captures esp_reset_reason() at boot and classifies it as a fault
(panic/watchdog/brownout) or an expected reset (power-on/software/deep sleep).
CommunicationRouter reports it once MQTT connects: faults go to status/alerts,
expected resets go to status/info (type: boot_reason). MQTTDriver gained a
setOnConnectCallback hook to support this.

F-045, F-046, F-048 in the feature catalog.
2026-07-15 00:04:21 +03:00
bonaminandClaude Sonnet 4.6 399b4d056c feat(heartbeat): add rssi to heartbeat payload
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>
2026-07-13 02:10:41 +03:00
bonaminandClaude Sonnet 4.6 3582218b54 feat(F-043,F-044): redesign network.info and network.status command split
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>
2026-07-13 00:53:37 +03:00
bonaminandClaude Sonnet 4.6 eb440a9888 fix(ClockHandler): backlight key mismatch, bell get_config conversion, timezone in get_config
- 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>
2026-07-12 19:37:31 +03:00
bonaminandClaude Sonnet 4.6 0ac63e82ed feat(F-040,F-041,F-042): relay.set_config, output numbering fix, clock batch commands
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>
2026-07-12 18:44:52 +03:00
bonaminandClaude Sonnet 4.6 a5395b0de7 fix(Telemetry): heap-corrupt crash in logBootEvent — StaticJsonDocument on small task stack
StaticJsonDocument<8192> in logBootEvent() was allocating 8KB on the stack of
ntpSyncTask, which only had 3072 bytes. Stack overflow silently corrupted the
heap, triggering assert in multi_heap_free immediately after the boot log write.

Fix: switch logBootEvent to heap-allocated JsonDocument (ArduinoJson v7 default).
Also bumped ntpSyncTask stack from 3072 → 5120 bytes for NTP + SD write headroom.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-11 11:27:50 +03:00
bonaminandClaude Sonnet 4.6 07d5b2fb81 feat(F-038,F-039): bell and clock test fire commands
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>
2026-07-10 19:53:54 +03:00
bonaminandClaude Sonnet 4.6 e90771a539 feat(comms): bidirectional device control — bells master switch, guard toggle, runtime tracking, system aggregate commands
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>
2026-07-10 18:46:18 +03:00
bonaminandClaude Sonnet 4.6 825ffce5f5 docs(catalog): add F-028 logging calibration, expand F-014 NVS migration
F-014 updated from scaffold stub to full description: key rename table
(device_uid/hw_type/hw_version → serial/hw_family/hw_revision), hw_family
lookup table, idempotency behaviour.

F-028 new entry: default channel levels (Serial INFO, MQTT WARNING, SD
WARNING), per-subsystem MQTT caps table, and all secondary fixes from the
refactor(Logging) commit (early setLevel removal, heartbeat to VERBOSE,
HealthMonitor polling noise, FirmwareValidator boot lines, ConfigManager
VERBOSE cleanup).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-09 10:09:03 +03:00
bonaminandClaude Sonnet 4.6 3d90ed4292 refactor(Logging): calibrate default levels and reduce playback noise
Serial default VERBOSE→INFO, MQTT default NONE→WARNING, SD NONE→WARNING.
Per-subsystem MQTT caps added in CommunicationRouter: BellEngine/
OutputManager/HealthMonitor/ConfigManager at WARNING to silence per-note
and per-poll spam; Player/Telemetry/OTAManager at INFO to keep state
transitions visible.

Remove early Logging::setLevel() call in main.cpp — CommunicationRouter
applies all three channels once the MQTT callback is wired. Loop heartbeat
downgraded DEBUG→VERBOSE. HealthMonitor polling noise (skipping/performing
lines) removed; subsystem status and completion lines VERBOSE→DEBUG.
FirmwareValidator boot-path checks VERBOSE→INFO (one-shot, worth seeing).
ConfigManager isHealthy() false-branches and NVS read trace VERBOSE→DEBUG.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-09 10:01:19 +03:00
bonaminandClaude Sonnet 4.6 67da788738 fix(NvsMigration): check nvs_get_str return value before constructing String
nvsReadString previously ignored the error code from nvs_get_str and passed
an uninitialised or garbage buffer to String() on failure. Now returns an
empty string if the read fails.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-07 10:42:51 +03:00
bonaminandClaude Sonnet 4.6 9e415de7bc refactor(FileManager): drop HTTPS support — melody downloads over plain HTTP only
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>
2026-07-07 10:42:46 +03:00
bonaminandClaude Sonnet 4.6 9f33f90ea9 feat(Player): V2 playback command namespace + segment_duration fix + mode field
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>
2026-07-07 10:30:05 +03:00
bonaminandClaude Sonnet 4.6 7e8d91673f fix: builtin aliases, cmd version default, relay compat, NTP UTC, player guards
BuiltInMelodies (F-018):
- 24 builtin_* UID aliases added for backward compat with old device PIDs
- Two new PROGMEM arrays: builtin_catehetical, builtin_mournfull_toll_alternative
- isBuiltInMelody() helper for lightweight PID existence check
- FileManager download-skip now uses isBuiltInMelody() instead of findMelodyByPID()

Command envelope version default (F-020):
- MQTT, UART, WebSocket transports: missing "v" field defaults to 1 (was 2)
- Fixes legacy adapter rejecting commands from app and Node-RED

RelayHandler v1/v2 compat (F-021):
- set_durations and set_outputs accept both nested {"bells":{...}} (v2)
  and flat {...} (v1) payload shapes

NTP UTC fix (F-019):
- configTime(0,0,ntpServer) fetches raw UTC; stored gmtOffset+dstOffset
  applied manually to epoch before writing RTC
- Eliminates double-offset bug from SDK internal timezone handling

Player guards (F-022):
- speed==0 defaults to 300ms instead of producing silent/broken playback
- calculateProjectedRunTime() guards against singleLoopDuration==0

Telemetry (F-023):
- bellMaxLoad default raised 200→500 to eliminate false overload warnings

Version bump: 2.0.1 → 2.0.3

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 09:52:39 +03:00
bonaminandClaude Sonnet 4.6 df8426fce6 feat: two-tier factory reset, WiFi fallback chain, SettingsWebServer
Factory reset (F-015):
- InputManager gains MEDIUM_PRESSED state with mediumPressMs=5000
- 5s hold: wipe WiFi credentials only, restart on release
- 10s hold: full factory reset (WiFi wipe already done at 5s mark)
- New callbacks: setFactoryResetMediumPressCallback,
  setFactoryResetMediumPressReleaseCallback

WiFi fallback chain (F-016):
- Connection now cycles: saved creds → hardcoded failsafe → portal
- MAX_WIFI_FAILURES reduced 3→2 per stage
- Portal now reboots after saving credentials (fixes port 80 conflict
  between WiFiManager and AsyncWebServer)
- AP SSID sourced from netConfig.apSsid instead of hardcoded pattern
- clearWiFiCredentials() added to Networking for 5s reset gesture

SettingsWebServer (F-017):
- Instantiated in main.cpp alongside CommunicationRouter
- begin() called when network becomes ready (both WiFi paths)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 09:52:17 +03:00
bonaminandClaude Sonnet 4.6 ee73d4d2c4 docs: add feature catalog and working rules to README
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>
2026-06-30 09:52:01 +03:00
bonaminandClaude Sonnet 4.6 ed1123283b feat: boot-phase OTA, RS485 variant, async melody download, HAL guards
- bootOtaCheck() runs at top of setup() before any task/timer; streams
  firmware to flash on update, reboots, otherwise returns immediately
- New bespoke-rs485-v1 build env + Rs485OutputManager for Waveshare 16CH
  Modbus RTU relay; vesper.hpp renamed vesper-std.hpp, env renamed accordingly
- Player: permanent melodyDownloadTaskFn task; fast path (built-in/SD) before
  async download; uid accepted as alias for pid
- CommunicationRouter: HAS_UART guards throughout so UART transport compiles
  out when Serial2 is claimed by Modbus
- OTAManager: stack 8KB→16KB, pinned to Core 1, HTTPClient recreated per
  retry, download timeout 30s→60s
- FileManager: heap guard before SSL alloc; watchdog log cleanup
- ConfigManager: OTA fallback URLs http (no TLS for firmware servers)
- agnus.hpp: HAS_UART 1 added
- provisioning/nvs_agnus_lab_device.csv added
- Version bumped to v2.0.1

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-18 20:48:26 +03:00
bonaminandClaude Sonnet 4.6 a4d071d5d5 feat: multi-board HAL guards, RFRemote subsystem, Player/OTA improvements
Multi-board variant support:
- variants/vesper.hpp: enable HAS_RF=1, define RF_RX_PIN=22
- variants/agnus.hpp: enable HAS_RF=1, RF_RX_PIN=22, correct HAS_RTC=0
- main.cpp, Player, HealthMonitor, OTAManager, ConfigManager: wrap all
  RTC/SD/RF-dependent code in #if HAS_RTC / HAS_SD_CARD / HAS_RF guards
  so Agnus builds cleanly without those peripherals

RFRemote subsystem (new):
- src/RFRemote/: RF receiver driver (GPIO RF_RX_PIN) + command handler
- Registered with HealthMonitor and CommunicationRouter when HAS_RF=1

Player improvements:
- uid -> pid rename throughout (Player, BuiltInMelodies, api-reference)
- loadMelodyInRAM() now returns bool
- playerControlTaskFn task added — defers stop/pause/resume out of
  timer callback (Tmr Svc) to avoid stack overflows
- setDependencies() accepts nullptr FileManager for SD-less boards

OTAManager:
- Consume download_url from server metadata response instead of
  constructing firmware path locally
- HTTP redirect following enabled (setFollowRedirects)
- HAS_RTC guards on TimeKeeper references

platformio.ini:
- Add rc-switch library for RF remote support
- Remove BOARD_TYPE/BOARD_NAME/BOARD_VERSION flags (moved to variant headers)
- MQTT_SECRET placeholders only — no secrets in source

Docs:
- docs/architecture/codebase-refactor-plan.md: new migration strategy doc
- docs/reference/api-reference.md: updated for pid, note_assignments, download_url
- Remove stale docs: ota-telemetry-api.md, platformio-commands.md, firmware-variants.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 17:02:01 +02:00
bonaminandClaude Sonnet 4.6 37b65cc15a feat: HAL variant system, OTA improvements, NVS migration scaffold
- Add variants/vesper.hpp and variants/agnus.hpp with HAS_SD_CARD, HAS_RTC,
  HAS_PCF8574, OUTPUT_COUNT_MAX, HW_FAMILY capability flags
- Add agnus-v1 and agnus-mini-v1 PlatformIO environments with -include injection
- Add src/NvsMigration/ scaffold for future NVS schema versioning
- FirmwareHandler: OTA flow improvements and header updates
- OTAManager: FastAPI integration, semver handling improvements
- ConfigManager: refactoring groundwork for NVS-only variant support
- CommunicationRouter: minor fix
- provisioning/nvs_lab_device.csv: fix hw_type to VS, update device id fields
- docs/dev/ota-telemetry-api.md: update API spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 11:39:11 +02:00
bonaminandClaude Sonnet 4.6 d4d8b1c380 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>
2026-03-14 22:16:03 +02:00
bonaminandClaude Sonnet 4.6 d4bd990e53 feat: semver versioning, FastAPI OTA integration, health alerts via MQTT
- 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>
2026-03-14 22:15:27 +02:00
bonaminandClaude Sonnet 4.6 c3dc0a79bc refactor(comms): clean up Communication folder structure
- 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>
2026-02-28 23:22:50 +02:00
bonaminandClaude Sonnet 4.6 682c604abe feat(comms): Stages 3–6 — transport layer, router simplification, legacy adapter, WebServerTransport
## Stage 3 — Transport Layer
- MQTTTransport: wraps MQTTAsyncClient, implements ITransport
- WebSocketTransport: wraps WebSocketServer + ClientManager; broadcastToMasters/Secondary
- HTTPTransport: first-class HTTP identity (no more 0xFFFFFFFF fake WS client); registers
  POST /api/command, GET /api/ping, GET /api/status; reply lambda captures AsyncWebServerRequest*
- UARTTransport: wraps UARTCommandHandler; UART whitelist enforced before dispatch

## Stage 4 — CommunicationRouter simplification
- Router now owns CommandBus + 4 transports; registerHandlers() wires all 10 domain handlers
- Old CommandHandler marked DEPRECATED on disk, no longer called
- HTTPRequestHandler no longer instantiated (replaced by HTTPTransport)
- ResponseBuilder::fromResult() factory method added
- main.cpp: all setXxxReference() calls moved before begin(); HealthMonitor + OutputManager wired

## Stage 5 — Legacy Adapter
- LegacyAdapter.hpp/cpp: 35 v1→v2 command mappings (simple 1:1, action-based, boolean splits)
- CommandBus::dispatch() applies translation when envelope.version == 1

## Stage 6 — WebServerTransport (4th transport, absorbs SettingsWebServer)
- WebServerTransport implements ITransport; registered in CommunicationRouter::begin()
- GET /settings: HTML settings page (PROGMEM template unchanged)
- POST /api/set-mode: routes network.set_config {permanent_ap_mode} through CommandBus
- POST /api/reboot: routes system.restart through CommandBus
- NetworkHandler::handleSetConfig: handles permanent_ap_mode field independently
- SettingsWebServer member removed from CommunicationRouter; src/SettingsWebServer/ is dead
  code, deletable in a follow-up PR once SettingsPage.h is moved

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-28 22:54:43 +02:00
bonaminandClaude Sonnet 4.6 f6107e2cfe feat(comms): Stage 2 — all 10 domain handlers implemented
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>
2026-02-28 22:16:34 +02:00
bonaminandClaude Sonnet 4.6 6294044569 feat(comms): Stage 1 — CommandBus scaffolding (headers + skeleton)
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>
2026-02-28 22:04:51 +02:00
bonamin 30d660268f refactor: Fixed the file hierarchy and switched to platform.io 2026-02-28 21:57:42 +02:00
bonaminandClaude Sonnet 4.6 ab1e4f2e6d Merge feature/subsystem-logging into main
- Per-subsystem log tags across all firmware modules
- PlatformIO migration (ESP32-S3, env:vesper-v1)
- Manufacturing automation plan docs added
- .gitignore updated for PlatformIO build artifacts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-26 17:32:31 +02:00
bonaminandClaude Sonnet 4.6 3877d27dae feat: Migrate firmware to PlatformIO (ESP32-S3, vesper-v1 env)
Replaces Arduino IDE with PlatformIO as the build system. Entry point
moved from vesper.ino to src/main.cpp. All library dependencies are now
declared in platformio.ini and downloaded automatically via lib_deps.

Board: Kincony KC868-A6 (ESP32-S3, 4MB flash) → env:vesper-v1
Future variants Vesper+ and Vesper Pro are pre-configured but commented out.

Compatibility fixes applied for this framework version:
- Removed ETH.h dependency (Ethernet was disabled in v138)
- Watchdog init updated to IDF v4 API (esp_task_wdt_init signature)
- ETH.linkUp() check removed from OTAManager

Also adds .pio/ to .gitignore and commits the manufacturing plan docs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-26 17:31:53 +02:00
bonaminandClaude Sonnet 4.6 fe6b1d871a feat: Add per-subsystem log tags to all firmware modules
Refactored logging system to require a TAG as first argument on all
LOG_* macros, enabling per-subsystem log filtering and cleaner output.
Each subsystem now defines its own TAG (e.g. "BellEngine", "Player").
Also overhauled Logging.hpp/cpp with improved level control and output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-26 17:31:28 +02:00
bonamin c656835d8e Fix LCD Communicaiton infinite looping upon failed commands 2026-02-10 18:45:41 +02:00
bonamin 980de08584 Fix Infinite Loop Bug, Melody Download crashes and dwnld skip if melody is builin. 2026-02-04 17:00:27 +02:00
bonamin 9c314d88cf Fixed Infinite Play bug
When Infinite Play was set once, it was never reset.
2026-02-03 15:46:47 +02:00
bonamin 53c55d2726 Added Sync Time to LCD, Fixed UTC Timestamp issues 2026-01-28 10:28:05 +02:00
bonamin 094b1a9620 Added UART as a communication interface option. 2026-01-19 21:24:35 +02:00
bonamin 11b98166d1 Fixed OTA problems, Clock Alerts and MQTT Logs. V151 2026-01-19 19:02:25 +02:00
bonamin 7e279c6e45 Added delay to NTP to let WiFi catch up before time request 2026-01-07 21:46:26 +02:00
bonamin eb6e0f0e5c Added Global Mutex for SD IOPS, and changed OTA to write directly to Flash 2026-01-07 21:04:33 +02:00
bonamin 7adc1fec34 Changed OTA to write Directly to flash 2026-01-07 15:46:20 +02:00
bonamin 51b7722e1d Removed Ethernet, added default WiFi (mikrotik AP) and fixed various Clock bugs. 2026-01-07 01:06:45 +02:00
bonamin 9f07e9ea39 Fixed a getter method in CommandHandler.cpp (player is playing) 2026-01-06 21:09:20 +02:00
bonamin 3d184773c1 Added Extra Heartbeat Metrics and Separated HTML Page 2025-12-29 20:38:52 +02:00
bonamin 953b5bd07d Added Reboot and Manual FW Update commands 2025-12-29 20:12:54 +02:00
bonamin db57b355b9 Added HTTP-API support, Standalone AP Support and Built-in Melodies 2025-12-28 21:49:49 +02:00
bonamin 0f0b67cab9 Added MQTT Logs, and improved OTA and NTP to Async 2025-12-28 18:39:13 +02:00
bonamin 8d397c6dd5 Reverted Websocket Code to previous commit 2025-12-26 10:02:41 +02:00
bonamin 7d9bc42078 Websocket Fix, Added Clock NTP Sync, Updated MQTT IP 2025-12-26 09:33:24 +02:00
bonamin b04590d270 Added MQTT Heartbeat and changed Firware Versioning System 2025-12-03 18:22:17 +02:00
bonamin a7f1bd1667 Added Telemetry data report to the App 2025-10-31 21:10:38 +02:00
bonamin f286abb023 Updates to BellEngine, ClientManager, ConfigManager, and Telemetry Logging 2025-10-30 22:42:01 +02:00
bonamin c9f1e8e4ae Fixed Single-loop mode playing multiple times on fast speeds. 2025-10-29 08:55:36 +02:00
bonamin 06891e8d82 Fixed issue with Bell Assignments 2025-10-26 11:08:19 +02:00
bonamin d1835beff5 Added Set Log Level Commands 2025-10-23 09:34:44 +03:00
bonamin 470d7bfacc Fixed Indexing on Bell Output Assignments 2025-10-18 18:43:51 +03:00
bonamin cc0bec97b5 Added Network Info Command 2025-10-15 12:44:10 +03:00
bonamin d6f105319d fixed WiFi not setting Hostname 2025-10-14 19:14:59 +03:00
bonamin fce760ebe0 Removed Firmware Load from SD during boot 2025-10-13 17:50:25 +03:00
bonamin 956786321a Fixed MQTT and WS Routing - w/o SSL 2025-10-13 17:34:54 +03:00
bonamin f696984cd1 Complete Rebuild, with Subsystems for each component. RTOS Tasks. (help by Claude) 2025-10-01 12:42:00 +03:00
bonamin 104c1d04d4 Stop tracking build folder and ignore it 2025-10-01 12:33:30 +03:00
bonamin 101f9e7135 MAJOR update. More like a Backup before things get Crazy
Added Websocket Support
Added Universal Message Handling for both MQTT and WS
Added Timekeeper Class, that handles Physical Clock and Scheduling
Added Bell Assignment Settings, Note to Bell mapping
2025-09-05 19:27:13 +03:00
bonamin c1fa1d5e57 Added basic WebSocket Functionality 2025-07-12 18:14:40 +03:00
bonamin 516eeab751 Added basic Logger with 4 modes. 2025-01-26 18:02:39 +02:00
bonamin 7dd6f81264 Added basic Scheduling Functionality
A JSON message can now be received on:
'vesper/DEV_ID/control/addSchedule"
Each message, must hold a "file" and "data".
The file is the month's name in 3 letter mode (eg jan, feb, mar)
The data is an entry for each day of the month.
Each day can be an array containing multiple items.
2025-01-26 14:02:15 +02:00
bonamin 84534025f4 Added Separate Timings for each Relay
The setting is saved on a file in:
/settings/relayTimings.json

Then during bootup, it's read and restored. 
Settings can be set via MQTT command on Topic: 
vesoer/*dev-id*/control/settings/relayTimers
using a json format. 
{ "b1":50, b2...}
where b1 is Bell 1, b2 Bell 2, etc..
2025-01-21 11:42:23 +02:00
bonamin a33f626dde Added initial Melody Playback Ability
Now, controlled via MQTT a Playback of a melody can Start, Stop, Pause 
etc. 

Settings like speed, total duration, pauses etc can be set.
2025-01-19 21:15:07 +02:00
bonamin 2cbbc8d591 Added Basic Melody-Handling Task and temp-task for testing 2025-01-12 19:54:19 +02:00
bonamin 540d8a14fe Added Melody Struct & Ajusted MQTT Subs and Deserialization
A new Melody Struct was added containing the melody's main attributes.
The MQTT Topic Subscriptions were updated to a more proper format.
Also added DEV_ID that corresponds to the device's ID or Serial Number.
Chnaged the Deserialization function to actually adjust the MelodyStruct's attributes.
Added basic play/stop functionality.
2025-01-12 19:46:24 +02:00
bonamin 30e708f048 Added Basic MQTT Support and JSON Deserialization 2024-12-29 13:04:23 +02:00
bonamin c523b59e90 Initiaze of Project Vesper 2024-12-26 19:29:09 +02:00