feat(Player): "loading" status while a melody downloads + playback_failed report (F-068)

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>
This commit is contained in:
2026-09-29 20:25:27 +03:00
co-authored by Claude Opus 5.5
parent 46a1a2567f
commit b01e755c92
10 changed files with 238 additions and 34 deletions
+48
View File
@@ -80,6 +80,7 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
| F-065 | `stopping` playback state formally documented (duration reached, bells finishing the current loop) — kept on `status/playback`, not suppressed | v2.3.0 | Stable |
| F-066 | Fix: stale retained `status/playback` — republished with the Player's real state on every MQTT (re)connect | v2.3.0 | Stable |
| F-067 | Specific `playback.play` / `playback.stop` ACK messages (busy, invalid params, not found, load failed, bells disabled, overload…) instead of a generic "Playback command failed"; `url` no longer sticky | v2.3.0 | Stable |
| F-068 | `loading` playback state while a melody downloads (MQTT `status/playback`), cancellable by `playback.stop`; `playback_failed` event on `control/reports` when an ACKed play never starts | v2.3.0 | Stable |
---
@@ -1292,3 +1293,50 @@ semantics used by the validator (`is<uint32_t>` on negatives/floats/2^32, `is<in
non-strings/null) confirmed with a host-side test.
Subsystem: `src/Player/Player.hpp`, `src/Player/Player.cpp`, `src/BellEngine/BellEngine.hpp`, `src/BellEngine/BellEngine.cpp`, `src/Communication/Handlers/PlaybackHandler/PlaybackHandler.hpp`, `src/Communication/Handlers/PlaybackHandler/PlaybackHandler.cpp`, `src/RFRemote/RFRemote.cpp`
---
### F-068 — `loading` state + `playback_failed` report for downloaded melodies
When a `playback.play` needed a download, the board replied SUCCESS and then nothing was visible until
playback started — and if the download failed, nothing at all (only a log line). The app had no way to
show progress or learn that the play it was told "succeeded" never happened.
**New `PlayerStatus::LOADING`.** The download branch of `Player::command()` now sets `LOADING` (published
on `status/playback` as `action: "loading"` with `pid`/`speed`/`duration`/`source` set, `started_at` 0)
*before* returning the SUCCESS ACK (`Melody download started — playback begins when it completes`),
then signals `MelodyDL`. The download task then:
- success → re-checks `playbackBlockedReason()` (bells may have been disabled / a bell overloaded
during the download) → `play()` → `playing`;
- any failure → `setStatus(STOPPED)` → `idle`, then `CommunicationRouter::sendPlaybackFailedNotification(pid, reason)`:
`control/reports` `{ "type": "playback_failed", "payload": { "pid", "reason" } }` plus a WebSocket INFO
of the same shape. Reasons are the F-067 strings (`Melody download failed`, `Melody failed to load: …`,
the two `Playback blocked: …`).
**Stop while loading = cancel.** `playback.stop` (and `forceStop()` from RF / the overload guard) during
`LOADING` sets `_cancelDownload` and goes `idle` immediately (ACK `Download cancelled — playback will
not start`). The HTTP transfer can't be aborted, so `MelodyDL` finishes it and discards the result
without playing or reporting. Until it does, `_downloadInFlight` stays true and new plays are rejected
with `Playback blocked: a cancelled melody download is still finishing — try again shortly` — the task
still owns `pid`/`_melodySteps`, so letting a fast-path play in would race it (previously a second play
during a download could rewrite `pid`/`url` under the running download).
**Race handling.** `_loadingMutex` (FreeRTOS mutex) serialises the download task's
"check cancel → play()/STOPPED" against `cancelLoading()`'s "re-check LOADING → cancel → STOPPED", so a
stop can't land between the cancel check and `play()`; if the task wins, the stop falls through to a
normal `forceStop()` of the playback that just started. The download itself runs outside the lock.
**`loading` is MQTT-only.** `setStatus()` skips the WebSocket broadcast for `LOADING`: the v1 tablet app
(`dart-message-handler.dart`) maps any unknown playback action to `PlaybackStatus.unavailable` — the
F-061 symptom — so WebSocket clients keep seeing `idle` → `playing` exactly as before. `playback_failed`
*is* sent over WebSocket, because v1 ignores unknown INFO types. `system.status` / `system.get_all`
report `"LOADING"`; `LegacyResponseAdapter` maps it to `"idle"` for v1 callers; the heartbeat's
`state` reports `idle` (unchanged payload).
**Phone app subscription.** `playback_failed` lives on `control/reports`, so the phone app now needs
that topic too (spec updated). It carries no `req_id` (as for every report) — correlate by `pid`; only
one download can be pending.
Verified: `pio run -e vesper-std-v1`, `-e agnus-v1` and `-e bespoke-rs485-v1` build clean.
Subsystem: `src/Player/Player.hpp`, `src/Player/Player.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.cpp`, `src/Communication/CommandBus/LegacyResponseAdapter.cpp`
+17 -8
View File
@@ -78,7 +78,7 @@ MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_to
|---|---|---|---|
| MQTT | `vesper/{device_id}/control/command` | Inbound commands | Read-only from the board's perspective. Replies go to `control/ack`. |
| MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited |
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | e.g. bell overload — not retained |
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | `bell_overload`, `playback_failed` — not retained |
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT |
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions |
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events |
@@ -167,7 +167,7 @@ Both commands reply with **`type: "playback"`** (not the command name).
| Transports | MQTT, WebSocket, HTTP (UART: v1 form only) |
| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback started" }` — or `"message": "Melody download started — playback begins when it completes"` when the melody must be downloaded first |
The SUCCESS reply means the board **accepted** the command, not that bells are ringing. `status/playback` (MQTT) is the source of truth for what the board is actually doing — `playing` / `paused` / `stopping` / `idle`; see [mqtt-events.md → States](mqtt-events.md#states).
The SUCCESS reply means the board **accepted** the command, not that bells are ringing. `status/playback` (MQTT) is the source of truth for what the board is actually doing — `loading` / `playing` / `paused` / `stopping` / `idle`; see [mqtt-events.md → States](mqtt-events.md#states).
**Fields are sticky.** Every field except `url`, `mode` and `continuous_loop` keeps the value from the *previous* `playback.play` (or its boot default) when omitted — including `pid`, `speed` and the tail of `note_assignments`. Send every field you care about on every play. A rejected play never changes the stored values (all checks run first).
@@ -206,7 +206,8 @@ Errors are checked in this order; the first that applies is returned. Every one
| Error `message` | Condition |
|---|---|
| `Playback already active — send playback.stop first` | Player is not idle (`playing` / `paused` / `stopping`) |
| `Playback already active — send playback.stop first` | Player is not idle (`loading` / `playing` / `paused` / `stopping`) |
| `Playback blocked: a cancelled melody download is still finishing — try again shortly` | A download was cancelled by `playback.stop` and its transfer hasn't ended yet |
| `Missing required field: pid` | No `pid`/`uid` in this command and none stored from a previous play; or it is empty, `"-"`, or not a string |
| `Invalid speed: must be an integer from 0 to 65535 (ms per beat)` | `speed` present but not an integer in range |
| `Invalid note_assignments: must be an array of up to 16 integers, each 0-16` | Not an array, more than 16 entries, or an entry outside 0–16 |
@@ -222,7 +223,13 @@ Errors are checked in this order; the first that applies is returned. Every one
| `Melody not found: not built-in, not on SD card, and no url given` | Needs a download but no `url` was sent |
| `Melody not found locally and this device has no SD card to download it to` | Needs a download but the build has no SD card / FileManager (agnus) |
A download itself happens **after** the SUCCESS reply (it would otherwise block the network task for seconds), so a failed download can't be an ACK error — the board logs `Melody download failed` (or `Melody failed to load: …` for a bad downloaded file) and playback simply doesn't start.
**Download path.** When the melody must be downloaded, the ACK is SUCCESS `Melody download started — playback begins when it completes`, and `status/playback` shows **`loading`** (with `pid` set) — published just before the ACK. The download runs after the reply (it would otherwise block the network task for seconds), so its failure can't be an ACK error. Instead:
- success → `status/playback` goes `loading` → `playing`;
- failure → `status/playback` goes `loading` → `idle` **and** a [`playback_failed`](mqtt-events.md#playback-failed-event) event `{ "pid", "reason" }` is published on `control/reports` (reason: `Melody download failed`, `Melody failed to load: file is empty or corrupt`, or one of the two `Playback blocked: …` messages if conditions changed during the download);
- `playback.stop` while `loading` → cancelled, `idle`, no `playback_failed`.
The ACK itself is always sent synchronously from the command's own dispatch, so `req_id` is echoed on it in both the local and the download case. `playback_failed` (like every `control/reports` event) carries no `req_id` — match it by `pid`.
```json
{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } }
@@ -241,6 +248,8 @@ A download itself happens **after** the SUCCESS reply (it would otherwise block
Stops immediately (bells are cut mid-loop, status goes straight to `idle`).
**While `loading` → SUCCESS**, `"message": "Download cancelled — playback will not start"` (status goes `loading` → `idle`; the transfer finishes in the background and is discarded).
**Already idle → SUCCESS**, `"message": "Already stopped"` (no status/playback publish, since nothing changed). Stop is idempotent: the caller's goal state is reached, so it is not an error — the distinct message lets a client tell the two cases apart if it cares. `playback.stop` has no error replies.
```json
@@ -503,9 +512,9 @@ Fire C1/C2 for the configured pulse. Returns `data: { "output": "C1", "duration_
### `system.status`
Returns `data: { "player_status": "PLAYING"|"PAUSED"|"STOPPING"|"STOPPED", "time_elapsed_ms", "projected_run_time", "strike_counters": { "0": 1234, ... } }`.
Returns `data: { "player_status": "PLAYING"|"PAUSED"|"STOPPING"|"LOADING"|"STOPPED", "time_elapsed_ms", "projected_run_time", "strike_counters": { "0": 1234, ... } }`.
A **v1** request (no `v`, or `v:1`) gets the reply translated by `LegacyResponseAdapter`: `type: "current_status"`, fields under `payload` (not `data`), lowercase `player_status` (`playing`/`paused`/`stopping`/`idle`), `time_elapsed` (ms), `strike_counters` as an array.
A **v1** request (no `v`, or `v:1`) gets the reply translated by `LegacyResponseAdapter`: `type: "current_status"`, fields under `payload` (not `data`), lowercase `player_status` (`playing`/`paused`/`stopping`/`idle` — `LOADING` is reported as `idle`), `time_elapsed` (ms), `strike_counters` as an array.
### `system.get_time`
@@ -517,7 +526,7 @@ Full ConfigManager dump plus `general: { bells_enabled, mqtt_enabled, ota_channe
### `system.get_all`
Returns `data: { "device": { serial, hw_family, hw_revision, fw_version, uptime_ms, free_heap }, "config": {...}, "telemetry": {...}, "player": { "status": "PLAYING"|"PAUSED"|"STOPPING"|"STOPPED" } }`.
Returns `data: { "device": { serial, hw_family, hw_revision, fw_version, uptime_ms, free_heap }, "config": {...}, "telemetry": {...}, "player": { "status": "PLAYING"|"PAUSED"|"STOPPING"|"LOADING"|"STOPPED" } }`.
### `system.get_telemetry`
@@ -865,7 +874,7 @@ Published without a request, on the v2 topic set. Full field-level reference: [m
|---|---|---|---|---|
| `vesper/{id}/status/heartbeat` | Every 30s (+ LWT on unclean disconnect) | 1 | yes | `heartbeat` |
| `vesper/{id}/status/playback` | On playback transition | 1 | yes | `playback` |
| `vesper/{id}/control/reports` | Critical unsolicited events (e.g. bell overload) | 1 | no | `reports` |
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 1 | no | `reports` |
| `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` |
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 1 | yes | `info` |
| `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` |
+31 -9
View File
@@ -15,7 +15,7 @@ Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but no
|-------|-----------|-----|----------|--------|---------|
| `vesper/{id}/control/command` | Inbound | 1 | no | `command` | Commands from server/app — board only ever receives here |
| `vesper/{id}/control/ack` | Outbound | 1 | no | `command` | Replies to commands **only** — strictly request/response |
| `vesper/{id}/control/reports` | Outbound | 1 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (e.g. bell overload) |
| `vesper/{id}/control/reports` | Outbound | 1 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | `heartbeat` | Periodic liveness + state signal. Also carries LWT. |
| `vesper/{id}/status/playback` | Outbound | 1 | yes | `playback` | Playback transitions only |
| `vesper/{id}/system/alerts` | Outbound | 1 | yes, until cleared | `alerts` | Subsystem state-change events |
@@ -23,7 +23,7 @@ Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but no
| `vesper/{id}/system/logs` | Outbound | 0 | no | `logs` | Full log stream, mirrors serial log output |
| `vesper/{id}/system/metrics` | Outbound | 0 | no | `metrics` | Structured telemetry — fleet-health graphing |
Subscribe to `vesper/+/#` to receive everything from all devices (fleet webserver pattern). The phone app subscribes only to `control/ack`, `status/heartbeat`, `status/playback`.
Subscribe to `vesper/+/#` to receive everything from all devices (fleet webserver pattern). The phone app subscribes to `control/ack`, `status/heartbeat`, `status/playback`, and `control/reports` (for `playback_failed`).
Every topic above except `control/command`/`control/ack` (which share one switch, `command`) has its own independent ON/OFF publish switch — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#per-topic-onoff-switches) for the full mechanism (`mqtt.get_topics`/`mqtt.set_topics`).
@@ -113,13 +113,13 @@ Flat — no envelope wrapper.
| Field | Type | Description |
|-------|------|-------------|
| `action` | string | `playing` \| `paused` \| `stopping` \| `idle` — see [States](#states) |
| `action` | string | `loading` \| `playing` \| `paused` \| `stopping` \| `idle` — see [States](#states) |
| `time_elapsed` | integer | Seconds since playback started, as of `ts` (0 for `idle`) |
| `projected_run_time` | integer | Projected total run time in ms (0 if not applicable) |
| `pid` | string | Melody being played (`""` when idle) |
| `pid` | string | Melody being played or loaded (`""` when idle) |
| `speed` | integer | ms per beat (0 when idle) |
| `duration` | integer | Requested run-time cap in ms — the effective stop timer after `mode`/legacy field resolution (`timed` → `duration`, `interval` → `total_duration`, legacy → `segment_duration`/`total_duration`). `0` = no cap: a `single` play ends naturally, `infinite` runs until stopped. 0 when idle. |
| `started_at` | integer | Unix epoch seconds (UTC) when playback started. `0` when idle or when the board has no valid clock. |
| `started_at` | integer | Unix epoch seconds (UTC) when playback started. `0` when idle, while `loading` (not started yet), or when the board has no valid clock. |
| `source` | string | What started the playback: `app` (MQTT/WebSocket/HTTP command), `rf` (RF remote slot), `button` (UART LCD/button slave board), `schedule` (reserved — scheduled events don't start playback yet), `unknown`. `""` when idle. |
| `ts` | integer | Unix epoch seconds (UTC) when this message was built. `0` when the board has no valid clock. |
@@ -127,18 +127,25 @@ Flat — no envelope wrapper.
**Stale retained messages.** Because the topic is retained, a client may receive a message published long ago. Real elapsed time is `now − started_at` (when `started_at != 0`); `ts` tells you how old the snapshot is. `time_elapsed` is only correct as of `ts`.
The WebSocket transport receives the same fields on every transition, wrapped in the legacy broadcast envelope: `{ "status": "INFO", "type": "playback", "payload": { ...fields above... } }`.
```json
{ "action": "loading", "time_elapsed": 0, "projected_run_time": 0, "pid": "ABC123", "speed": 400, "duration": 120000, "started_at": 0, "source": "app", "ts": 1790000100 }
```
The WebSocket transport receives the same fields on every transition, wrapped in the legacy broadcast envelope: `{ "status": "INFO", "type": "playback", "payload": { ...fields above... } }` — **except `loading`, which is MQTT-only**: v1 tablets (WebSocket) map any unknown playback action to "unavailable", so WebSocket clients keep seeing `idle` → `playing` for a download.
### States
| `action` | Meaning | Entered from | Leaves to |
|---|---|---|---|
| `playing` | Bells are ringing. | `idle` (play accepted), `paused` (segment pause over) | `paused`, `stopping`, `idle` |
| `loading` | A `playback.play` was accepted (ACK: `Melody download started — …`) and the melody is downloading to SD first. No bells yet; `pid` identifies what is coming. | `idle` | `playing` (download OK), `idle` (download failed → also a [`playback_failed`](#playback-failed-event) report; or `playback.stop` → cancelled) |
| `playing` | Bells are ringing. | `idle` (play accepted), `loading` (download done), `paused` (segment pause over) | `paused`, `stopping`, `idle` |
| `paused` | Between segments of an `interval` (or legacy `continuous_loop`) play — bells silent, playback still active. | `playing` | `playing`, `idle` |
| `stopping` | The run-time cap (`duration`) has elapsed; the bells are **finishing the current melody loop** before stopping (can last up to one full loop, i.e. steps × `speed`). Still ringing. | `playing` (timer reached `duration`) | `idle` (loop finished) |
| `idle` | Nothing playing. | any (`playback.stop`, natural end, overload force-stop) | `playing` |
`playback.stop` during `playing`/`paused`/`stopping` cuts the bells immediately and goes straight to `idle` — it never passes through `stopping`. A new `playback.play` is rejected in every state except `idle`. The heartbeat's independently-derived `state` reports `idle` during `stopping`.
`playback.stop` during `playing`/`paused`/`stopping` cuts the bells immediately and goes straight to `idle` — it never passes through `stopping`. During `loading` it cancels the pending start (ACK `Download cancelled — playback will not start`); the transfer itself finishes in the background and is discarded. A new `playback.play` is rejected in every state except `idle` (and briefly after a cancelled download, until that transfer ends).
On a SUCCESS play ACK the board publishes `status/playback` **before** the ACK: `playing` (melody was local) or `loading` (download needed). The heartbeat's independently-derived `state` reports `idle` during `stopping`.
---
@@ -175,6 +182,21 @@ Published by `CommunicationRouter::sendBellOverloadNotification()` → `publishR
| `payload.loads` | array of int | Strike count load per bell channel |
| `payload.severity` | string | `WARNING` (≥60% load) or `CRITICAL` (≥90% load) |
### Playback failed event
Published by `CommunicationRouter::sendPlaybackFailedNotification()` from the melody download task when a `playback.play` was already ACKed SUCCESS (`Melody download started — …`) but playback never began. `status/playback` goes `loading` → `idle` at the same moment. Not sent when the download was cancelled by `playback.stop`.
```json
{ "type": "playback_failed", "payload": { "pid": "ABC123", "reason": "Melody download failed" } }
```
| Field | Type | Description |
|-------|------|-------------|
| `payload.pid` | string | The melody that failed to start |
| `payload.reason` | string | One of: `Melody download failed` (HTTP/SD failure), `Melody failed to load: file is empty or corrupt` (downloaded file unusable), `Playback blocked: bell mechanism is disabled (bells.enable)` / `Playback blocked: bell overload protection active — wait for the bells to cool` (conditions changed during the download) |
Like every `control/reports` event it carries no `req_id` — correlate with the command by `pid` (only one download can be pending at a time). WebSocket clients get the same as `{ "status": "INFO", "type": "playback_failed", "payload": { "pid", "reason" } }`.
---
## `vesper/{id}/system/alerts`
@@ -353,7 +375,7 @@ Invalid JSON or a missing `cmd` field gets an `ERROR` reply on `control/ack` (`t
```
vesper/+/status/heartbeat → update last_seen + state/ok, no logging (unless state:"offline" from LWT)
vesper/+/status/playback → update device detail panel's playback state
vesper/+/control/reports → surface immediately — critical, time-sensitive (e.g. bell_overload)
vesper/+/control/reports → surface immediately — critical, time-sensitive (bell_overload, playback_failed)
vesper/+/system/alerts → upsert/remove active alert set per device
vesper/+/system/info → update device state panel (boot_report, etc.)
vesper/+/system/logs → remote log viewer / archival
+3 -3
View File
@@ -10,9 +10,9 @@ and [MQTTTransport](../../src/Communication/Transport/MQTTTransport/README.md) (
|---|---|---|---|---|---|
| `vesper/{device_id}/control/command` | Inbound commands (play, stop, ping, etc.) | 1 | No | `command` | **Read-only from the board's perspective — the board only receives here, never publishes.** Includes optional `req_id` for correlation. `v`, `cmd`, `contents` as before. |
| `vesper/{device_id}/control/ack` | Replies to commands, including `pong` | 1 | No | `command` | **Strictly replies only — every message here answers a specific request, and every reply goes here. Nothing unsolicited is ever published to this topic.** Echoes `req_id` from the originating command when one was sent. `status: SUCCESS/ERROR/INFO`, `type`, optional `message`/`data`. Malformed input (invalid JSON, missing `cmd`) also gets an `ERROR` reply here (`type: "parse_error"`) rather than being silently dropped — see [Malformed input](#malformed-input) below. |
| `vesper/{device_id}/control/reports` | Critical, time-sensitive board-initiated events (e.g. bell overload) | 1 | No | `reports` | The opposite of `control/command` — unsolicited data the board sends because it needs to be read *now*. Not a reply to anything, no `req_id`. Not retained — an event stream, not a status snapshot. |
| `vesper/{device_id}/control/reports` | Critical, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) | 1 | No | `reports` | The opposite of `control/command` — unsolicited data the board sends because it needs to be read *now*. Not a reply to anything, no `req_id`. Not retained — an event stream, not a status snapshot. |
| `vesper/{device_id}/status/heartbeat` | Periodic health/state summary, every 30s | 1 | **Yes** | `heartbeat` | Also carries LWT (see below). Fields: `device_id`, `state` (`idle`/`playing`/`paused`/`error`/`booting`), `ok` (bool), `fw_version`, `uptime_ms`, `uptime_human`, `ip_address`, `gateway`, `rssi`, `free_heap` — `state`/`ok` independently derived, never mirrored from `status/playback` or `system/alerts`. |
| `vesper/{device_id}/status/playback` | Playback state transitions only | 1 | **Yes** | `playback` | `action`: `playing`/`paused`/`stopping`/`idle` (`stopping` = run-time cap reached, bells finishing the current loop), plus `time_elapsed`, `projected_run_time`, `pid`, `speed`, `duration`, `started_at`, `source`, `ts` — see [mqtt-events.md](mqtt-events.md#vesperidstatusplayback). Published on transition, not polled — plus once on every (re)connect with the current real state, so a stale retained `playing` never outlives a reboot. Source of truth for what the board is doing (a `control/ack` SUCCESS only means "accepted"). |
| `vesper/{device_id}/status/playback` | Playback state transitions only | 1 | **Yes** | `playback` | `action`: `loading`/`playing`/`paused`/`stopping`/`idle` (`loading` = play accepted, melody downloading; `stopping` = run-time cap reached, bells finishing the current loop), plus `time_elapsed`, `projected_run_time`, `pid`, `speed`, `duration`, `started_at`, `source`, `ts` — see [mqtt-events.md](mqtt-events.md#vesperidstatusplayback). Published on transition, not polled — plus once on every (re)connect with the current real state, so a stale retained `playing` never outlives a reboot. Source of truth for what the board is doing (a `control/ack` SUCCESS only means "accepted"). |
| `vesper/{device_id}/system/alerts` | Subsystem state changes (warnings/errors) | 1 | **Yes**, until cleared | `alerts` | Published on transition only (WARNING/CRITICAL/FAILED/CLEARED). Not consumed by phone app — webserver/fleet only. |
| `vesper/{device_id}/system/info` | Discrete system events (e.g. `boot_report`) | 1 | **Yes** | `info` | Not consumed by phone app. Excludes errors (those go to `alerts`) and metrics (those go to `metrics`). |
| `vesper/{device_id}/system/logs` | Full log stream, serial-log equivalent | 0 | No | `logs` | Not consumed by phone app. Respects device's configured log level (`log.set_mqtt`) **and** this on/off switch independently — the switch can silence the whole channel without touching the configured level. Should not compete with heap/buffer needed for command traffic — guard same as `hasHeapForPublish()`. |
@@ -66,7 +66,7 @@ A reply to unparseable JSON necessarily has no `req_id` — it couldn't be read
- **LWT (Last Will and Testament)**: on connect, register Last Will → publishes to `status/heartbeat` with `{"device_id": "...", "state": "offline", "ok": false}` (retained), fired by the broker only on an *unclean* disconnect. Re-registered automatically on every reconnect (AsyncMqttClient resends the Will on every CONNECT).
- **Graceful disconnect**: if the firmware ever disconnects intentionally (e.g. `mqtt.disable`, before OTA), it explicitly publishes the same offline payload before disconnecting, since LWT won't fire for clean disconnects. See `MQTTDriver::disconnect(bool graceful)`.
- **Subscribers**:
- Phone app subscribes only to `control/ack`, `status/heartbeat`, `status/playback` (+ publishes to `control/command`).
- Phone app subscribes to `control/ack`, `status/heartbeat`, `status/playback`, plus `control/reports` for `playback_failed` (a play that was ACKed but whose melody download then failed) — publishes to `control/command`.
- Fleet webserver subscribes to everything via `vesper/+/#`, including `control/reports`, `system/alerts`, `system/info`, `system/logs`, `system/metrics`.
## Migration from v1
@@ -22,8 +22,10 @@ static bool translateSystemStatus(const CommandResult& result, JsonDocument& out
out["type"] = "current_status";
JsonObject payload = out["payload"].to<JsonObject>();
// v2 sends UPPERCASE enum names (PLAYING/PAUSED/STOPPING/STOPPED);
// v1 expects lowercase state words, with STOPPED spelled "idle".
// v2 sends UPPERCASE enum names (PLAYING/PAUSED/STOPPING/STOPPED/LOADING);
// v1 expects lowercase state words, with STOPPED spelled "idle". LOADING
// deliberately falls through to "idle" — v1 apps have no loading state and
// treat unknown words as "unavailable".
const char* v2Status = data["player_status"] | "STOPPED";
const char* v1Status = "idle";
if (strcmp(v2Status, "PLAYING") == 0) v1Status = "playing";
@@ -514,6 +514,25 @@ void CommunicationRouter::sendBellOverloadNotification(
bellNumbers.size(), severity.c_str());
}
// ─────────────────────────────────────────────────────────────────────────────
// Playback failed notification
// ─────────────────────────────────────────────────────────────────────────────
void CommunicationRouter::sendPlaybackFailedNotification(const String& pid, const String& reason) {
JsonDocument payload;
payload["pid"] = pid;
payload["reason"] = reason;
JsonDocument wsDoc;
wsDoc["status"] = "INFO";
wsDoc["type"] = "playback_failed";
wsDoc["payload"] = payload;
broadcastStatus(wsDoc);
publishReport("playback_failed", payload);
LOG_WARNING(TAG, "Playback failed notification sent: %s — %s", pid.c_str(), reason.c_str());
}
// ─────────────────────────────────────────────────────────────────────────────
// Alert / Info publishing
// ─────────────────────────────────────────────────────────────────────────────
@@ -121,6 +121,15 @@ public:
const std::vector<uint16_t>& bellLoads,
const String& severity);
/**
* @brief A play command was ACKed SUCCESS ("download started") but playback
* never began — download failed, file bad, or blocked by the time it
* finished. MQTT: control/reports {"type":"playback_failed","payload":
* {"pid","reason"}}. WS: INFO broadcast of the same (v1 tablets ignore
* unknown INFO types). Called from the MelodyDL task.
*/
void sendPlaybackFailedNotification(const String& pid, const String& reason);
/**
* @brief Publish the playback state to vesper/{id}/status/playback (retained, QoS 1).
* Called by Player::setStatus() on every transition. WS clients
@@ -113,6 +113,7 @@ CommandResult SystemHandler::handleStatus(const CommandEnvelope& e) {
case PlayerStatus::PLAYING: statusStr = "PLAYING"; break;
case PlayerStatus::PAUSED: statusStr = "PAUSED"; break;
case PlayerStatus::STOPPING: statusStr = "STOPPING"; break;
case PlayerStatus::LOADING: statusStr = "LOADING"; break;
default: break;
}
doc["player_status"] = statusStr;
@@ -247,6 +248,7 @@ CommandResult SystemHandler::handleGetAll(const CommandEnvelope& e) {
case PlayerStatus::PLAYING: psStr = "PLAYING"; break;
case PlayerStatus::PAUSED: psStr = "PAUSED"; break;
case PlayerStatus::STOPPING: psStr = "STOPPING"; break;
case PlayerStatus::LOADING: psStr = "LOADING"; break;
default: break;
}
player["status"] = psStr;
+81 -3
View File
@@ -21,6 +21,7 @@ static const char* const MSG_PLAY_STARTED = "Playback started";
static const char* const MSG_STOPPED = "Playback stopped";
static const char* const MSG_ALREADY_STOPPED = "Already stopped";
static const char* const MSG_DOWNLOAD_STARTED = "Melody download started — playback begins when it completes";
static const char* const MSG_DOWNLOAD_CANCELLED = "Download cancelled — playback will not start";
static const char* const ERR_BUSY = "Playback already active — send playback.stop first";
static const char* const ERR_MISSING_PID = "Missing required field: pid";
@@ -30,6 +31,7 @@ static const char* const ERR_NO_DOWNLOAD = "Melody not found locally and th
static const char* const ERR_DOWNLOAD_FAILED = "Melody download failed";
static const char* const ERR_BELLS_DISABLED = "Playback blocked: bell mechanism is disabled (bells.enable)";
static const char* const ERR_OVERLOAD = "Playback blocked: bell overload protection active — wait for the bells to cool";
static const char* const ERR_DOWNLOAD_BUSY = "Playback blocked: a cancelled melody download is still finishing — try again shortly";
// Constructor with dependencies
Player::Player(CommunicationRouter* comm, FileManager* fm)
@@ -135,6 +137,8 @@ void Player::begin() {
// Timer callbacks run on Tmr Svc (tiny stack) so we must not do MQTT/WS work there.
xTaskCreate(playerControlTaskFn, "PlayerCtrl", 4096, this, 2, NULL);
_loadingMutex = xSemaphoreCreateMutex();
// Permanent download task — created once at boot so its stack is allocated while heap
// is fresh and contiguous. Sleeps until signalled by xTaskNotifyGive().
xTaskCreate(melodyDownloadTaskFn, "MelodyDL", 8192, this, 3, &_downloadTaskHandle);
@@ -168,6 +172,12 @@ void Player::play() {
}
void Player::forceStop() {
// Nothing is ringing yet while LOADING — just cancel the pending start.
if (cancelLoading()) {
LOG_DEBUG(TAG, "Plbck: FORCE STOP while loading — download cancelled");
return;
}
if (_bellEngine) {
_bellEngine->emergencyStop();
}
@@ -234,6 +244,9 @@ PlayerCommandResult Player::command(JsonVariant data, PlaybackSource source) {
if (_status == PlayerStatus::STOPPED) {
return PlayerCommandResult::success(MSG_ALREADY_STOPPED);
}
if (cancelLoading()) {
return PlayerCommandResult::success(MSG_DOWNLOAD_CANCELLED);
}
forceStop();
return PlayerCommandResult::success(MSG_STOPPED);
}
@@ -250,6 +263,12 @@ PlayerCommandResult Player::command(JsonVariant data, PlaybackSource source) {
LOG_WARNING(TAG, "Play rejected — playback in progress");
return PlayerCommandResult::failure(ERR_BUSY);
}
// A cancelled download keeps running to completion on MelodyDL (it can't be
// aborted mid-transfer) and still owns _melodySteps / pid until it finishes.
if (_downloadInFlight) {
LOG_WARNING(TAG, "Play rejected — cancelled download still finishing");
return PlayerCommandResult::failure(ERR_DOWNLOAD_BUSY);
}
String invalid = validatePlayParams(data);
if (!invalid.isEmpty()) {
@@ -298,11 +317,34 @@ PlayerCommandResult Player::command(JsonVariant data, PlaybackSource source) {
return PlayerCommandResult::failure(ERR_NO_DOWNLOAD);
}
// Visible intermediate state: status/playback "loading" (pid set) until the
// download task moves us to PLAYING, or back to STOPPED + playback_failed.
LOG_INFO(TAG, "Melody '%s' needs download — signalling download task", pid.c_str());
_cancelDownload = false;
_downloadInFlight = true;
setStatus(PlayerStatus::LOADING);
xTaskNotifyGive(_downloadTaskHandle);
return PlayerCommandResult::success(MSG_DOWNLOAD_STARTED);
}
bool Player::cancelLoading() {
if (_status != PlayerStatus::LOADING || !_loadingMutex) return false;
bool cancelled = false;
xSemaphoreTake(_loadingMutex, portMAX_DELAY);
// Re-check under the lock: MelodyDL may have just moved us to PLAYING
// (then the caller falls through to a normal stop) or failed to STOPPED.
if (_status == PlayerStatus::LOADING) {
_cancelDownload = true;
setStatus(PlayerStatus::STOPPED);
cancelled = true;
}
xSemaphoreGive(_loadingMutex);
if (cancelled) LOG_INFO(TAG, "Pending download-then-play of '%s' cancelled", pid.c_str());
return cancelled;
}
String Player::validatePlayParams(JsonVariant doc) const {
// pid — required unless a previous play left one behind (fields are sticky)
String effectivePid = String(pid.c_str());
@@ -592,14 +634,37 @@ void Player::melodyDownloadTaskFn(void* pvParameters) {
for (;;) {
ulTaskNotifyTake(pdTRUE, portMAX_DELAY); // sleep until notified
LOG_INFO(TAG, "Download task: starting download for '%s'", player->pid.c_str());
String downloadPid = player->pid.c_str();
LOG_INFO(TAG, "Download task: starting download for '%s'", downloadPid.c_str());
// The (possibly multi-second) download runs without the lock; only the
// outcome → state transition is serialised against a concurrent stop.
const char* err = player->loadMelodyInRAM();
xSemaphoreTake(player->_loadingMutex, portMAX_DELAY);
bool cancelled = player->_cancelDownload;
if (!cancelled) {
// Conditions may have changed during the download (bells.disable, overload).
if (!err) err = player->playbackBlockedReason();
if (!err) {
LOG_INFO(TAG, "Download task: success, starting playback of '%s'", player->pid.c_str());
LOG_INFO(TAG, "Download task: success, starting playback of '%s'", downloadPid.c_str());
player->play();
} else {
LOG_ERROR(TAG, "Download task: failed to load melody '%s': %s", player->pid.c_str(), err);
player->setStatus(PlayerStatus::STOPPED);
}
}
xSemaphoreGive(player->_loadingMutex);
player->_downloadInFlight = false;
if (cancelled) {
LOG_INFO(TAG, "Download task: '%s' finished after cancel — not playing", downloadPid.c_str());
} else if (err) {
// The ACK already went out as SUCCESS ("download started") — this is the
// only way the caller learns the play never happened, and why.
LOG_ERROR(TAG, "Download task: failed to start '%s': %s", downloadPid.c_str(), err);
if (player->_commManager) {
player->_commManager->sendPlaybackFailedNotification(downloadPid, err);
}
}
}
}
@@ -631,11 +696,16 @@ void Player::setStatus(PlayerStatus newStatus) {
// WebSocket clients keep the existing envelope shape via broadcastStatus()
// (fields nested under "payload"); same field set as MQTT status/playback.
// Exception: "loading" is MQTT-only. v1 tablets (WebSocket) map any unknown
// playback action to "unavailable" — the F-061 symptom — so they keep
// seeing idle → playing (or idle → playback_failed) as before.
if (newStatus != PlayerStatus::LOADING) {
JsonDocument doc;
doc["status"] = "INFO";
doc["type"] = "playback";
snapshot.writeTo(doc["payload"].to<JsonObject>());
_commManager->broadcastStatus(doc);
}
// MQTT clients get the dedicated status/playback topic (flat, retained) —
// see docs/reference/mqtt-events.md.
@@ -670,6 +740,14 @@ PlaybackSnapshot Player::getPlaybackSnapshot() {
case PlayerStatus::PLAYING: s.action = "playing"; break;
case PlayerStatus::PAUSED: s.action = "paused"; break;
case PlayerStatus::STOPPING: s.action = "stopping"; break;
case PlayerStatus::LOADING:
// Accepted but not started: identify what's coming, no timing yet.
s.action = "loading";
s.pid = pid.c_str();
s.speed = speed;
s.durationMs = total_duration;
s.source = playbackSourceToString(_source);
return s;
case PlayerStatus::STOPPED:
default:
s.action = "idle";
+16 -1
View File
@@ -55,6 +55,7 @@
#include <SD.h> // SD card operations for melody files
#include "freertos/FreeRTOS.h" // FreeRTOS kernel
#include "freertos/task.h" // FreeRTOS task management
#include "freertos/semphr.h" // Mutex for LOADING → PLAYING/STOPPED handoff
#include "../Logging/Logging.hpp" // Centralized logging system
#include "../FileManager/FileManager.hpp" // File operations abstraction
#include "PlaybackState.hpp" // PlaybackSource + PlaybackSnapshot (status/playback wire shape)
@@ -77,7 +78,8 @@ enum class PlayerStatus {
STOPPED, // ⏹️ Not playing, engine stopped
PLAYING, // ▶️ Actively playing melody
PAUSED, // ⏸️ Temporarily paused between segments
STOPPING // 🔄 Soft stop triggered, waiting for melody to complete
STOPPING, // 🔄 Soft stop triggered, waiting for melody to complete
LOADING // ⬇️ Play accepted, melody downloading before playback starts
};
/**
@@ -266,6 +268,9 @@ public:
/** @brief Check if player is completely stopped */
bool isCurrentlyStopped() const { return _status == PlayerStatus::STOPPED; }
/** @brief Check if a play was accepted and its melody is still downloading */
bool isCurrentlyLoading() const { return _status == PlayerStatus::LOADING; }
/** @brief BellEngine callback when melody loop actually completes */
void onMelodyLoopCompleted();
@@ -314,6 +319,16 @@ private:
// Async download — permanent task signalled via task notification
TaskHandle_t _downloadTaskHandle = nullptr;
// LOADING bookkeeping. _loadingMutex serialises "download finished → play()"
// (MelodyDL task) against "stop while LOADING → cancel" (command/RF/telemetry),
// so a stop can never land between the cancel check and play().
SemaphoreHandle_t _loadingMutex = nullptr;
volatile bool _cancelDownload = false; // set by a stop during LOADING
volatile bool _downloadInFlight = false; // MelodyDL is working (may outlive a cancel)
/** @brief If LOADING, cancel the pending download-then-play and go idle. Returns true if it did. */
bool cancelLoading();
// Origin of the command that started the current playback (status/playback "source")
PlaybackSource _source = PlaybackSource::UNKNOWN;