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
@@ -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;
+89 -11
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();
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<JsonObject>());
_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<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
};
/**
@@ -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;