feat(Player,PlaybackHandler): specific ACK messages for playback.play/stop (F-067)

Every rejection used to reach the caller as "Playback command failed".
Player::command() now returns PlayerCommandResult { ok, message } and
PlaybackHandler forwards the message verbatim:

- busy, missing pid, invalid speed / note_assignments / durations / mode,
  timed|interval without duration, bells disabled, bell overload lockout,
  melody failed to load (incl. 0-byte file), not found without url,
  needs download but no SD card
- success: "Playback started", "Melody download started — …",
  "Playback stopped", and "Already stopped" (stop while idle stays SUCCESS —
  idempotent, goal state reached)

Validation runs before setMelodyAttributes(), so a rejected play no longer
half-applies its fields. Also fixes: url was sticky (a later play of another
pid could download the old URL under the new name); bells.disable let a play
"succeed" and report playing with silent bells; a non-string name/pid
assigned nullptr to std::string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-29 20:17:47 +03:00
co-authored by Claude Opus 5.5
parent 92a0a8d5e8
commit 46a1a2567f
9 changed files with 331 additions and 117 deletions
+6 -2
View File
@@ -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() {
+8 -1
View File
@@ -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
// ═══════════════════════════════════════════════════════════════════════════════
@@ -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<JsonDocument&>(envelope.contents);
contents["action"] = "play";
bool ok = _player.command(contents.as<JsonVariant>(), 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<JsonVariant>(), sourceFromOrigin(envelope.origin)));
}
CommandResult PlaybackHandler::handleStop(const CommandEnvelope& envelope) {
JsonDocument& contents = const_cast<JsonDocument&>(envelope.contents);
contents["action"] = "stop";
bool ok = _player.command(contents.as<JsonVariant>(), 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<JsonVariant>(), 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);
}
@@ -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);
};
+185 -86
View File
@@ -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<const char*>() ? doc[pidKey].as<String>() : String();
}
if (effectivePid.isEmpty() || effectivePid == "-") {
return ERR_MISSING_PID;
}
if (doc.containsKey("speed")) {
JsonVariant v = doc["speed"];
if (!v.is<int>() || v.as<int>() < 0 || v.as<int>() > 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<JsonArray>() && v.as<JsonArray>().size() <= 16;
if (valid) {
for (JsonVariant n : v.as<JsonArray>()) {
if (!n.is<int>() || n.as<int>() < 0 || n.as<int>() > 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<uint32_t>()) {
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<const char*>(): 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<const char*>();
name = doc["name"] | "";
}
if (doc.containsKey("pid")) {
pid = doc["pid"].as<const char*>();
pid = doc["pid"] | "";
} else if (doc.containsKey("uid")) {
pid = doc["uid"].as<const char*>();
}
if (doc.containsKey("url")) {
url = doc["url"].as<const char*>();
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<uint16_t>();
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);
}
}
}
+31 -6
View File
@@ -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
// ═══════════════════════════════════════════════════════════════════════════════
+4 -1
View File
@@ -389,7 +389,10 @@ void RFRemote::triggerPlay(uint8_t slot) {
na.add(s.note_assignments[i]);
}
_player->command(doc.as<JsonVariant>(), PlaybackSource::RF);
PlayerCommandResult r = _player->command(doc.as<JsonVariant>(), PlaybackSource::RF);
if (!r.ok) {
LOG_WARNING(TAG, "RF slot %d play rejected: %s", slot, r.message.c_str());
}
}
void RFRemote::triggerStop() {