diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index 17f60a2..c974e6e 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -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` on negatives/floats/2^32, `is(); - // 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"; diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index 15eded0..8599dc6 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -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 // ───────────────────────────────────────────────────────────────────────────── diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index d90dcee..89eb3b0 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -121,6 +121,15 @@ public: const std::vector& 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 diff --git a/src/Communication/Handlers/SystemHandler/SystemHandler.cpp b/src/Communication/Handlers/SystemHandler/SystemHandler.cpp index 2215bc0..56455a9 100644 --- a/src/Communication/Handlers/SystemHandler/SystemHandler.cpp +++ b/src/Communication/Handlers/SystemHandler/SystemHandler.cpp @@ -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; diff --git a/src/Player/Player.cpp b/src/Player/Player.cpp index 0cb4212..6082c51 100644 --- a/src/Player/Player.cpp +++ b/src/Player/Player.cpp @@ -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(); - 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': %s", player->pid.c_str(), err); + + 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'", downloadPid.c_str()); + player->play(); + } else { + 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. - JsonDocument doc; - doc["status"] = "INFO"; - doc["type"] = "playback"; - snapshot.writeTo(doc["payload"].to()); - _commManager->broadcastStatus(doc); + // 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()); + _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"; diff --git a/src/Player/Player.hpp b/src/Player/Player.hpp index 66fc4df..e9183b4 100644 --- a/src/Player/Player.hpp +++ b/src/Player/Player.hpp @@ -55,6 +55,7 @@ #include // 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 }; /** @@ -265,6 +267,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;