diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index add85ce..17f60a2 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -79,6 +79,7 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne | F-064 | Richer `status/playback` — `pid`, `speed`, `duration`, `started_at`, `source`, `ts` (same fields on the WebSocket playback INFO event); command origin carried on `CommandEnvelope` | v2.3.0 | Stable | | 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 | --- @@ -1239,3 +1240,55 @@ switch, heap guard. Verified: `pio run -e vesper-std-v1` builds clean. Subsystem: `src/Communication/CommunicationRouter/CommunicationRouter.cpp` + +--- + +### F-067 — Specific playback ACK messages + +`Player::command()` returned a bare `bool`, so every rejection reached the caller as +`"Playback command failed"` and every success as `"Playback command executed"` — the phone app couldn't +tell "already playing" from "melody missing" from "bells switched off". + +**Now** `Player::command()` returns `PlayerCommandResult { ok, message }` and `PlaybackHandler` sends +`message` verbatim. All strings are constants at the top of `Player.cpp` (plus the per-field +`Invalid : …` validation messages) and are listed exhaustively, in check order, in +api-reference.md → `playback.play` and the console page. Reply `type` stays `"playback"`. + +Success: `Playback started`, `Melody download started — playback begins when it completes`, +`Playback stopped`, `Already stopped`. + +**Decision — stop when already idle is SUCCESS** (`"Already stopped"`), not an error: stop is idempotent, +the caller's goal state is reached, and an app's stop button shouldn't have to special-case an error. +The distinct message still lets a client tell the two apart. + +**Behaviour changes that come with it:** +- Up-front validation (`Player::validatePlayParams()`) runs **before** `setMelodyAttributes()`, so a + rejected play no longer half-applies its fields to the sticky state. New rejections that used to be + silently accepted: `speed` outside 0–65535 (used to wrap), `note_assignments` that isn't an array of + ≤16 ints in 0–16 (extras used to be ignored), negative/non-integer durations (used to wrap to huge + unsigned values), unknown `mode` (used to fall back to `single`), `timed`/`interval` with + `duration` 0 (`interval` with 0 re-paused on every timer tick). +- **Blocked gates** (`Player::playbackBlockedReason()`): `bells.disable` in effect (previously the + command succeeded and status said `playing` while `BellEngine::start()` silently refused — new + `BellEngine::areBellsEnabled()`), and any bell over its max load while the guard is on (the same + condition `Telemetry::checkBellLoads()` force-stops on, so a start would be cut off within a second). +- `loadMelodyInRAM()` returns the error string instead of `bool`, and now treats a **0-byte** SD file as + `Melody failed to load` (previously it "loaded" zero steps, `play()` bailed silently and the command + still returned success). +- Needs-a-download on a build with no FileManager (agnus) is now rejected up front instead of + queueing a download that could only fail. +- **`url` is no longer sticky.** A URL left over from an earlier play was reused for a later play of a + *different* `pid` that wasn't on SD, downloading the old melody's file and saving it under the new + pid's name. Omitted `url` now means "no download for this play". +- `name`/`pid`/`uid` are read with `| ""` — a non-string value used to assign `nullptr` to a + `std::string` (undefined behaviour / crash). + +Download failures still can't be ACK errors (the download runs after the reply, on `MelodyDL`) — see +F-068 for how they are reported. RF-triggered plays log the rejection reason (`RF slot N play +rejected: …`). + +Verified: `pio run -e vesper-std-v1` and `pio run -e agnus-v1` build clean; ArduinoJson 7 type-check +semantics used by the validator (`is` on negatives/floats/2^32, `is`, `| ""` on +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` diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md index e052bf6..8f84d58 100644 --- a/docs/reference/api-reference.md +++ b/docs/reference/api-reference.md @@ -165,22 +165,22 @@ 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 command executed" }` | +| 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). -**Fields are sticky.** Every field except `mode`/`continuous_loop` keeps the value from the *previous* `playback.play` (or its boot default) when omitted — including `pid`, `url`, `speed` and the tail of `note_assignments`. Send every field you care about on every play. +**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). | Field | Type | Required | Notes | |---|---|---|---| | `pid` | string | yes* | Melody ID. Looked up in the built-in library, then `/melodies/{pid}` on SD, then downloaded from `url`. *If omitted, the previous `pid` is reused; the command fails if that is empty. | | `uid` | string | no | Alias for `pid`, read only when `pid` is absent. | | `name` | string | no | Display name. Informational only. | -| `url` | string | no | Download URL, used only when the melody is not built-in and not on SD. **The field is `url` — `download_url` is not read by `playback.play`** (that name belongs to `files.download`). Sticky: a URL from an earlier play is reused if omitted. | -| `speed` | int | no | ms per beat. Boot default 500. `0` is coerced to 300. | -| `note_assignments` | int[] | no | Up to 16 entries. Index = melody note (0-based), value = **1-based bell channel** to ring for that note, `0` = silent. Boot default `[1,2,…,16]`. Entries past 16 are ignored; a shorter array leaves the remaining entries at their previous values. | -| `mode` | string | no | `"single"` \| `"timed"` \| `"interval"` \| `"infinite"`. Unrecognised values behave as `"single"`. Selects the timing model — see below. | -| `duration` | int | no | ms. **Read only when `mode` is present.** | +| `url` | string | no | Download URL, used only when the melody is not built-in and not on SD. **The field is `url` — `download_url` is not read by `playback.play`** (that name belongs to `files.download`). Not sticky: omitted = no download possible for this play. | +| `speed` | int | no | ms per beat, 0–65535. Boot default 500. `0` is coerced to 300. | +| `note_assignments` | int[] | no | Up to 16 integers, each 0–16. Index = melody note (0-based), value = **1-based bell channel** to ring for that note, `0` = silent. Boot default `[1,2,…,16]`. A shorter array leaves the remaining entries at their previous values. | +| `mode` | string | no | `"single"` \| `"timed"` \| `"interval"` \| `"infinite"` — anything else is rejected. Selects the timing model — see below. | +| `duration` | int | no | ms, ≥ 0. **Read only when `mode` is present**; must be > 0 for `timed`/`interval`. | | `pause_duration` | int | no | ms between segments. Read when `mode` is `"interval"`, or when `mode` is absent. | | `total_duration` | int | no | ms. Read when `mode` is `"interval"`, or (with `continuous_loop: true`) when `mode` is absent. | | `segment_duration` | int | no | ms. Legacy — read only when `mode` is absent. | @@ -191,8 +191,8 @@ The SUCCESS reply means the board **accepted** the command, not that bells are r | `mode` | Behaviour | Fields read | |---|---|---| | `"single"` | Play the melody once, then stop. | — (`duration` ignored) | -| `"timed"` | Loop the melody; when `duration` ms have elapsed, finish the current loop and stop (status goes `stopping` → `idle`). `duration: 0` behaves like `single`. | `duration` | -| `"interval"` | Play for `duration` ms, pause `pause_duration` ms, repeat; stop after `total_duration` ms overall (`0` = forever). | `duration`, `pause_duration`, `total_duration` | +| `"timed"` | Loop the melody; when `duration` ms have elapsed, finish the current loop and stop (status goes `stopping` → `idle`). | `duration` (> 0) | +| `"interval"` | Play for `duration` ms, pause `pause_duration` ms, repeat; stop after `total_duration` ms overall (`0` = forever). | `duration` (> 0), `pause_duration`, `total_duration` | | `"infinite"` | Loop until `playback.stop`. | — | **Legacy timing** (`mode` absent): @@ -202,11 +202,27 @@ The SUCCESS reply means the board **accepted** the command, not that bells are r | `false` / absent | Run for `segment_duration` ms (sticky, boot default 15000), finish the loop, stop. **`total_duration` is ignored** — it is overwritten with `segment_duration`. `segment_duration: 0` plays the melody once. | | `true` | Segments of `segment_duration` ms separated by `pause_duration` ms. Stops after `total_duration` ms if given in this command, else after `segment_duration` if that was given, else the previous `total_duration`. Total `0` = forever. | -| Error | Condition | -|---|---| -| `Playback command failed` | Any rejection: playback already active (playing / paused / stopping — send `playback.stop` first); `pid` empty or `"-"`; melody file on SD could not be loaded; melody not built-in/on SD and no `url` | +Errors are checked in this order; the first that applies is returned. Every one leaves the player (and its stored fields) untouched. -Known gaps in current firmware (addressed separately — see the feature catalog): when a download is needed the reply is SUCCESS and a failed download is only logged; with `bells.disable` in effect the command succeeds and status reports `playing` but no bell rings. +| Error `message` | Condition | +|---|---| +| `Playback already active — send playback.stop first` | Player is not idle (`playing` / `paused` / `stopping`) | +| `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 | +| `Invalid duration: must be a non-negative integer (ms)` | `duration` negative / non-integer / > 4294967295 | +| `Invalid segment_duration: must be a non-negative integer (ms)` | same, for `segment_duration` | +| `Invalid pause_duration: must be a non-negative integer (ms)` | same, for `pause_duration` | +| `Invalid total_duration: must be a non-negative integer (ms)` | same, for `total_duration` | +| `Invalid mode: must be single, timed, interval or infinite` | Unrecognised `mode` | +| `Invalid duration: mode timed and interval require duration > 0` | `mode` is `timed`/`interval` and `duration` is missing or 0 | +| `Playback blocked: bell mechanism is disabled (bells.enable)` | Bells master switch off (`bells.disable`) | +| `Playback blocked: bell overload protection active — wait for the bells to cool` | Load guard enabled and any bell is over its max load (the guard would force-stop immediately) | +| `Melody failed to load: file is empty or corrupt` | `/melodies/{pid}` exists on SD but is empty or has an odd byte count | +| `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. ```json { "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } } @@ -221,9 +237,11 @@ Known gaps in current firmware (addressed separately — see the feature catalog |---|---| | Transports | MQTT, WebSocket, HTTP (UART: v1 form only) | | Contents | *(none)* | -| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback command executed" }` | +| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback stopped" }` | -Stops immediately (bells are cut mid-loop, status goes straight to `idle`). Sending it while already idle also returns SUCCESS with the same message. +Stops immediately (bells are cut mid-loop, status goes straight to `idle`). + +**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 { "v": 2, "cmd": "playback.stop" } diff --git a/src/BellEngine/BellEngine.cpp b/src/BellEngine/BellEngine.cpp index 2f04d39..3703493 100644 --- a/src/BellEngine/BellEngine.cpp +++ b/src/BellEngine/BellEngine.cpp @@ -106,13 +106,17 @@ void BellEngine::setCommunicationManager(CommunicationRouter* commManager) { // ENGINE CONTROL IMPLEMENTATION (Thread-safe) // ═════════════════════════════════════════════════════════════════════════════════ +bool BellEngine::areBellsEnabled() const { + return _configManager.getBellsEnabled(); +} + /** * @brief Start the precision timing engine - * + * * Activates the high-precision timing loop. Requires melody data to be * loaded via setMelodyData() before calling. Uses atomic operations * for thread-safe state management. - * + * * @note Will log error and return if no melody data is available */ void BellEngine::start() { diff --git a/src/BellEngine/BellEngine.hpp b/src/BellEngine/BellEngine.hpp index 9d33ec2..cfab732 100644 --- a/src/BellEngine/BellEngine.hpp +++ b/src/BellEngine/BellEngine.hpp @@ -204,7 +204,14 @@ public: * Thread-safe atomic read operation. */ bool isEmergencyStopped() const { return _emergencyStop.load(); } - + + /** + * @brief Whether the bell mechanism master switch (bells.enable/disable) allows playback. + * start() refuses to run while this is false — Player checks it up front so a + * play command can be rejected with a reason instead of "playing" silently. + */ + bool areBellsEnabled() const; + // ═══════════════════════════════════════════════════════════════════════════════ // PERFORMANCE MONITORING // ═══════════════════════════════════════════════════════════════════════════════ diff --git a/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.cpp b/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.cpp index dd0ac51..4788b3d 100644 --- a/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.cpp +++ b/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.cpp @@ -32,15 +32,18 @@ CommandResult PlaybackHandler::handlePlay(const CommandEnvelope& envelope) { // whether it was set by the V1 adapter or arrived as a bare V2 play command. JsonDocument& contents = const_cast(envelope.contents); contents["action"] = "play"; - bool ok = _player.command(contents.as(), sourceFromOrigin(envelope.origin)); - if (ok) return CommandResult::ok("playback", "Playback command executed"); - return CommandResult::err("playback", "Playback command failed"); + return toResult(_player.command(contents.as(), sourceFromOrigin(envelope.origin))); } CommandResult PlaybackHandler::handleStop(const CommandEnvelope& envelope) { JsonDocument& contents = const_cast(envelope.contents); contents["action"] = "stop"; - bool ok = _player.command(contents.as(), sourceFromOrigin(envelope.origin)); - if (ok) return CommandResult::ok("playback", "Playback command executed"); - return CommandResult::err("playback", "Playback command failed"); + return toResult(_player.command(contents.as(), sourceFromOrigin(envelope.origin))); +} + +// Player supplies the exact reply text — success wording or the specific +// rejection reason — so the ACK tells the caller *why*, not just "failed". +CommandResult PlaybackHandler::toResult(const PlayerCommandResult& r) { + return r.ok ? CommandResult::ok("playback", r.message) + : CommandResult::err("playback", r.message); } diff --git a/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.hpp b/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.hpp index a9cecac..4161aa1 100644 --- a/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.hpp +++ b/src/Communication/Handlers/PlaybackHandler/PlaybackHandler.hpp @@ -4,6 +4,7 @@ #include "../ICommandHandler.hpp" class Player; +struct PlayerCommandResult; class PlaybackHandler : public ICommandHandler { public: @@ -17,4 +18,5 @@ private: CommandResult handlePlay(const CommandEnvelope& envelope); CommandResult handleStop(const CommandEnvelope& envelope); + static CommandResult toResult(const PlayerCommandResult& r); }; diff --git a/src/Player/Player.cpp b/src/Player/Player.cpp index 5a88958..0cb4212 100644 --- a/src/Player/Player.cpp +++ b/src/Player/Player.cpp @@ -12,6 +12,25 @@ // Note: Removed global melody_steps dependency for cleaner architecture +// ───────────────────────────────────────────────────────────────────────────── +// playback.play / playback.stop reply strings — sent verbatim as control/ack +// "message". Documented in docs/reference/api-reference.md and the console's +// ApiReferencePage.jsx; change all three together. +// ───────────────────────────────────────────────────────────────────────────── +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 ERR_BUSY = "Playback already active — send playback.stop first"; +static const char* const ERR_MISSING_PID = "Missing required field: pid"; +static const char* const ERR_NOT_FOUND = "Melody not found: not built-in, not on SD card, and no url given"; +static const char* const ERR_LOAD_FAILED = "Melody failed to load: file is empty or corrupt"; +static const char* const ERR_NO_DOWNLOAD = "Melody not found locally and this device has no SD card to download it to"; +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"; + // Constructor with dependencies Player::Player(CommunicationRouter* comm, FileManager* fm) : id(0) @@ -204,86 +223,166 @@ void Player::unpause() { LOG_DEBUG(TAG, "Plbck: RESUME"); } -bool Player::command(JsonVariant data, PlaybackSource source) { - String action = data["action"]; +PlayerCommandResult Player::command(JsonVariant data, PlaybackSource source) { + String action = data["action"] | ""; LOG_DEBUG(TAG, "Incoming Command: %s", action.c_str()); - // While playing or stopping, only a stop command is accepted - if (_status != PlayerStatus::STOPPED) { - if (action == "stop") { - forceStop(); - return true; + // ── stop ──────────────────────────────────────────────────────────────── + // Idempotent: stopping an idle player is SUCCESS ("Already stopped") — the + // caller's goal state is reached, so it isn't an error. + if (action == "stop") { + if (_status == PlayerStatus::STOPPED) { + return PlayerCommandResult::success(MSG_ALREADY_STOPPED); } - LOG_WARNING(TAG, "Command '%s' rejected — playback in progress", action.c_str()); - return false; + forceStop(); + return PlayerCommandResult::success(MSG_STOPPED); } - if (action == "stop") { - return true; // already stopped — no-op + if (action != "play") { + LOG_WARNING(TAG, "Unknown playback action: %s", action.c_str()); + return PlayerCommandResult::failure("Unknown playback action: " + action); + } + + // ── play ──────────────────────────────────────────────────────────────── + // Every check below runs before setMelodyAttributes(), so a rejected play + // never clobbers the (sticky) attributes of the previous one. + if (_status != PlayerStatus::STOPPED) { + LOG_WARNING(TAG, "Play rejected — playback in progress"); + return PlayerCommandResult::failure(ERR_BUSY); + } + + String invalid = validatePlayParams(data); + if (!invalid.isEmpty()) { + LOG_WARNING(TAG, "Play rejected — %s", invalid.c_str()); + return PlayerCommandResult::failure(invalid); + } + + const char* blocked = playbackBlockedReason(); + if (blocked) { + LOG_WARNING(TAG, "Play rejected — %s", blocked); + return PlayerCommandResult::failure(blocked); } setMelodyAttributes(data); _source = source; + String pidStr = String(pid.c_str()); - if (action == "play") { - String pidStr = String(pid.c_str()); - - // Fast path: melody is already in a built-in or on SD — load and play synchronously - if (!pidStr.isEmpty()) { - _melodySteps.clear(); - bool builtIn = BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps); - if (!builtIn) { - String filePath = "/melodies/" + pidStr; - File f = SD.open(filePath.c_str(), FILE_READ); - if (f) { - f.close(); - // File is present — loadMelodyInRAM() will open it properly - _melodySteps.clear(); - if (!loadMelodyInRAM()) { - LOG_WARNING(TAG, "Play command aborted — melody '%s' could not be loaded", pid.c_str()); - return false; - } - play(); - return true; - } - } else { - // Built-in was loaded by the probe above — hand off to play() - play(); - return true; - } - } - - // Slow path: melody needs downloading — offload to a task so we don't block async_tcp - if (pid.empty() || pid == "-") { - LOG_WARNING(TAG, "Play command aborted — PID is empty or invalid"); - return false; - } - if (url.empty() || url == "-") { - LOG_WARNING(TAG, "Play command aborted — melody '%s' not found and no download URL", pid.c_str()); - return false; - } - - LOG_INFO(TAG, "Melody '%s' needs download — signalling download task", pid.c_str()); - xTaskNotifyGive(_downloadTaskHandle); - return true; + // Fast path: melody is built-in or already on SD — load and play synchronously + _melodySteps.clear(); + if (BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps)) { + play(); + return PlayerCommandResult::success(MSG_PLAY_STARTED); } - LOG_WARNING(TAG, "Unknown playback action: %s", action.c_str()); - return false; + String filePath = "/melodies/" + pidStr; + File f = SD.open(filePath.c_str(), FILE_READ); + if (f) { + f.close(); + // File is present — loadMelodyInRAM() will open and parse it properly + const char* loadErr = loadMelodyInRAM(); + if (loadErr) { + LOG_WARNING(TAG, "Play rejected — melody '%s': %s", pid.c_str(), loadErr); + return PlayerCommandResult::failure(loadErr); + } + play(); + return PlayerCommandResult::success(MSG_PLAY_STARTED); + } + + // Slow path: melody needs downloading — offload to a task so we don't block async_tcp + if (url.empty() || url == "-") { + LOG_WARNING(TAG, "Play rejected — melody '%s' not found and no download URL", pid.c_str()); + return PlayerCommandResult::failure(ERR_NOT_FOUND); + } + if (!_fileManager) { + LOG_WARNING(TAG, "Play rejected — melody '%s' needs a download but there is no SD card", pid.c_str()); + return PlayerCommandResult::failure(ERR_NO_DOWNLOAD); + } + + LOG_INFO(TAG, "Melody '%s' needs download — signalling download task", pid.c_str()); + xTaskNotifyGive(_downloadTaskHandle); + return PlayerCommandResult::success(MSG_DOWNLOAD_STARTED); +} + +String Player::validatePlayParams(JsonVariant doc) const { + // pid — required unless a previous play left one behind (fields are sticky) + String effectivePid = String(pid.c_str()); + const char* pidKey = doc.containsKey("pid") ? "pid" : (doc.containsKey("uid") ? "uid" : nullptr); + if (pidKey) { + effectivePid = doc[pidKey].is() ? doc[pidKey].as() : String(); + } + if (effectivePid.isEmpty() || effectivePid == "-") { + return ERR_MISSING_PID; + } + + if (doc.containsKey("speed")) { + JsonVariant v = doc["speed"]; + if (!v.is() || v.as() < 0 || v.as() > 65535) { + return "Invalid speed: must be an integer from 0 to 65535 (ms per beat)"; + } + } + + if (doc.containsKey("note_assignments")) { + JsonVariant v = doc["note_assignments"]; + bool valid = v.is() && v.as().size() <= 16; + if (valid) { + for (JsonVariant n : v.as()) { + if (!n.is() || n.as() < 0 || n.as() > 16) { valid = false; break; } + } + } + if (!valid) { + return "Invalid note_assignments: must be an array of up to 16 integers, each 0-16"; + } + } + + static const char* const DURATION_FIELDS[] = { "duration", "segment_duration", "pause_duration", "total_duration" }; + for (const char* field : DURATION_FIELDS) { + if (doc.containsKey(field) && !doc[field].is()) { + return String("Invalid ") + field + ": must be a non-negative integer (ms)"; + } + } + + if (doc.containsKey("mode")) { + const char* mode = doc["mode"] | ""; + bool timedOrInterval = strcmp(mode, "timed") == 0 || strcmp(mode, "interval") == 0; + if (!timedOrInterval && strcmp(mode, "single") != 0 && strcmp(mode, "infinite") != 0) { + return "Invalid mode: must be single, timed, interval or infinite"; + } + if (timedOrInterval && (doc["duration"] | 0u) == 0) { + return "Invalid duration: mode timed and interval require duration > 0"; + } + } + + return String(); +} + +const char* Player::playbackBlockedReason() const { + if (_bellEngine && !_bellEngine->areBellsEnabled()) { + return ERR_BELLS_DISABLED; + } + // Same condition Telemetry::checkBellLoads() force-stops on — starting now + // would just be cut off at the next load check. + if (_telemetry && _telemetry->isGuardEnabled()) { + for (uint8_t i = 0; i < 16; i++) { + if (_telemetry->isOverloaded(i)) return ERR_OVERLOAD; + } + } + return nullptr; } void Player::setMelodyAttributes(JsonVariant doc) { + // `| ""` rather than as(): a non-string value would otherwise + // assign nullptr to std::string (UB/crash). pid/uid are already validated. if (doc.containsKey("name")) { - name = doc["name"].as(); + name = doc["name"] | ""; } if (doc.containsKey("pid")) { - pid = doc["pid"].as(); + pid = doc["pid"] | ""; } else if (doc.containsKey("uid")) { - pid = doc["uid"].as(); - } - if (doc.containsKey("url")) { - url = doc["url"].as(); + pid = doc["uid"] | ""; } + // url is NOT sticky: a URL left over from an earlier play would otherwise be + // used to download a different pid's file under this pid's name. + url = doc.containsKey("url") ? (doc["url"] | "-") : "-"; if (doc.containsKey("speed")) { uint16_t s = doc["speed"].as(); speed = (s == 0) ? 300 : s; // Default to 300ms if speed is 0 @@ -369,19 +468,19 @@ void Player::setMelodyAttributes(JsonVariant doc) { continuous_loop ? "true" : "false", infinite_play ? "true" : "false"); } -bool Player::loadMelodyInRAM() { +const char* Player::loadMelodyInRAM() { _melodySteps.clear(); // Always start clean — never play stale data from a previous command String pidStr = String(pid.c_str()); if (pidStr.isEmpty()) { LOG_ERROR(TAG, "Cannot load melody: PID is empty"); - return false; + return ERR_MISSING_PID; } // 🎵 PRIORITY 1: Check built-in library by PID (exact match, no prefix required) if (BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps)) { LOG_INFO(TAG, "Built-in melody loaded: %s (%d steps)", pidStr.c_str(), _melodySteps.size()); - return true; + return nullptr; } // 🎵 PRIORITY 2: Load from SD card @@ -392,36 +491,35 @@ bool Player::loadMelodyInRAM() { // 🎵 PRIORITY 3: Try to download using the provided URL if (url.empty() || url == "-") { LOG_ERROR(TAG, "Melody '%s' not found in built-ins or SD, and no download URL provided", pidStr.c_str()); - return false; + return ERR_NOT_FOUND; + } + if (!_fileManager) { + LOG_ERROR(TAG, "FileManager not available, cannot download '%s'", pidStr.c_str()); + return ERR_NO_DOWNLOAD; } LOG_INFO(TAG, "Melody '%s' not on SD, attempting download", pidStr.c_str()); - if (_fileManager) { - StaticJsonDocument<128> doc; - doc["download_url"] = url.c_str(); - doc["melodys_uid"] = pidStr; + JsonDocument doc; + doc["download_url"] = url.c_str(); + doc["melodys_uid"] = pidStr; - if (!_fileManager->addMelody(doc)) { - LOG_ERROR(TAG, "Download failed for '%s'", pidStr.c_str()); - return false; - } - bin_file = SD.open(filePath.c_str(), FILE_READ); - if (!bin_file) { - LOG_ERROR(TAG, "File still not found after download: %s", filePath.c_str()); - return false; - } - } else { - LOG_ERROR(TAG, "FileManager not available, cannot download '%s'", pidStr.c_str()); - return false; + if (!_fileManager->addMelody(doc)) { + LOG_ERROR(TAG, "Download failed for '%s'", pidStr.c_str()); + return ERR_DOWNLOAD_FAILED; + } + bin_file = SD.open(filePath.c_str(), FILE_READ); + if (!bin_file) { + LOG_ERROR(TAG, "File still not found after download: %s", filePath.c_str()); + return ERR_DOWNLOAD_FAILED; } } size_t fileSize = bin_file.size(); - if (fileSize % 2 != 0) { - LOG_ERROR(TAG, "Invalid file size: %u (not a multiple of 2)", fileSize); + if (fileSize == 0 || fileSize % 2 != 0) { + LOG_ERROR(TAG, "Invalid file size: %u (empty or not a multiple of 2)", fileSize); bin_file.close(); - return false; + return ERR_LOAD_FAILED; } _melodySteps.resize(fileSize / 2); @@ -433,7 +531,7 @@ bool Player::loadMelodyInRAM() { LOG_INFO(TAG, "Melody loaded from SD: %s (%d steps)", pidStr.c_str(), _melodySteps.size()); bin_file.close(); - return true; + return nullptr; } // Static timer callback — runs on Tmr Svc (tiny stack). @@ -496,11 +594,12 @@ void Player::melodyDownloadTaskFn(void* pvParameters) { LOG_INFO(TAG, "Download task: starting download for '%s'", player->pid.c_str()); - if (player->loadMelodyInRAM()) { + const char* err = player->loadMelodyInRAM(); + if (!err) { LOG_INFO(TAG, "Download task: success, starting playback of '%s'", player->pid.c_str()); player->play(); } else { - LOG_ERROR(TAG, "Download task: failed to load melody '%s'", player->pid.c_str()); + LOG_ERROR(TAG, "Download task: failed to load melody '%s': %s", player->pid.c_str(), err); } } } diff --git a/src/Player/Player.hpp b/src/Player/Player.hpp index 6d3e5f8..66fc4df 100644 --- a/src/Player/Player.hpp +++ b/src/Player/Player.hpp @@ -80,6 +80,21 @@ enum class PlayerStatus { STOPPING // 🔄 Soft stop triggered, waiting for melody to complete }; +/** + * @struct PlayerCommandResult + * @brief Outcome of Player::command() — `message` is sent verbatim as the + * control/ack "message" (success text or the specific rejection reason). + * Every string is listed in docs/reference/api-reference.md → playback.play / + * playback.stop; keep them in sync. + */ +struct PlayerCommandResult { + bool ok; + String message; + + static PlayerCommandResult success(const String& msg) { return { true, msg }; } + static PlayerCommandResult failure(const String& msg) { return { false, msg }; } +}; + /** * @class Player * @brief Melody playback and timing control system @@ -207,17 +222,21 @@ public: void unpause(); /** - * @brief Handle JSON commands from communication layer + * @brief Handle a play/stop command from the communication layer or RF remote * @param source What issued the command — recorded on an accepted play and * reported as status/playback "source" + * @return ok + success text, or !ok + the specific rejection reason */ - bool command(JsonVariant data, PlaybackSource source = PlaybackSource::UNKNOWN); - + PlayerCommandResult command(JsonVariant data, PlaybackSource source = PlaybackSource::UNKNOWN); + /** @brief Set melody attributes from JSON configuration */ void setMelodyAttributes(JsonVariant doc); - - /** @brief Load melody data into RAM for playback. Returns false if melody could not be loaded. */ - bool loadMelodyInRAM(); + + /** + * @brief Load melody data into RAM for playback (built-in → SD → download from url). + * @return nullptr on success, else the error message (one of the Player error strings) + */ + const char* loadMelodyInRAM(); /** @brief Static timer callback for FreeRTOS duration control */ static void durationTimerCallback(TimerHandle_t xTimer); @@ -301,6 +320,12 @@ private: /** @brief Unix epoch seconds (UTC) — NTP system clock, else RTC; 0 if neither is valid */ uint32_t currentEpoch(); + /** @brief Validate a play command's fields before any state is touched. "" if valid. */ + String validatePlayParams(JsonVariant doc) const; + + /** @brief Reason playback may not start right now (bells disabled / overload), or nullptr */ + const char* playbackBlockedReason() const; + // ═══════════════════════════════════════════════════════════════════════════════ // PRIVATE HELPER METHODS // ═══════════════════════════════════════════════════════════════════════════════ diff --git a/src/RFRemote/RFRemote.cpp b/src/RFRemote/RFRemote.cpp index 8045634..9625dd6 100644 --- a/src/RFRemote/RFRemote.cpp +++ b/src/RFRemote/RFRemote.cpp @@ -389,7 +389,10 @@ void RFRemote::triggerPlay(uint8_t slot) { na.add(s.note_assignments[i]); } - _player->command(doc.as(), PlaybackSource::RF); + PlayerCommandResult r = _player->command(doc.as(), PlaybackSource::RF); + if (!r.ok) { + LOG_WARNING(TAG, "RF slot %d play rejected: %s", slot, r.message.c_str()); + } } void RFRemote::triggerStop() {