feat(Player,MQTT): add pid/speed/duration/started_at/source/ts to status/playback (F-064)
The remote phone app treats status/playback as the source of truth for what the board is doing, but the payload couldn't say what was playing, and a client receiving a stale retained message couldn't work out real elapsed time. Adds (old fields kept): - pid, speed, duration (effective stop timer after mode/legacy resolution) - started_at / ts — Unix epoch s (UTC); system clock once NTP-synced, else new Timekeeper::getUtcEpoch() (RTC local time minus configured offsets), else 0 - source — app | rf | button | schedule | unknown. Carried, not guessed: new CommandEnvelope::origin set by each transport (MQTT/WS/HTTP → APP, UART slave board → BUTTON), mapped by PlaybackHandler; RFRemote passes RF New PlaybackState.hpp has one PlaybackSnapshot::writeTo() used for both the WebSocket INFO broadcast (under "payload") and MQTT status/playback (flat), so local and remote clients match. publishPlayback() now honours the hasHeapForPublish() guard before building the document. Bumps FW_VERSION to 2.3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -76,6 +76,7 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
|
||||
| F-061 | Fix: `LegacyResponseAdapter` — v1 tablets saw device as "unavailable" while playing, due to `system.status` reply schema mismatch | v2.1.1 | Stable (temporary migration scaffolding) |
|
||||
| F-062 | MQTT topic spec v2 — restructured topics (`control/command`/`control/ack`/`control/reports`/`status/playback`/`system/*`), LWT, `req_id` correlation, per-topic ON/OFF switches (`mqtt.set_topics`) | v2.2.0 | Stable |
|
||||
| F-063 | Fix: malformed `control/command` input (bad JSON, missing `cmd`) now gets an `ERROR` reply on `control/ack` instead of being silently dropped | v2.2.1 | Stable |
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -1147,3 +1148,48 @@ guard itself must stay silent by design.
|
||||
Verified: `pio run -e vesper-std-v1` builds clean.
|
||||
|
||||
Subsystem: `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-064 — Richer `status/playback` payload
|
||||
|
||||
Built for the remote (MQTT) phone app, which treats `status/playback` as the source of truth for what
|
||||
the board is doing (a `control/ack` SUCCESS only means "accepted"). The old payload
|
||||
(`action`, `time_elapsed`, `projected_run_time`) couldn't say *what* was playing, and — because the topic
|
||||
is retained — a client receiving an old message had no way to work out real elapsed time.
|
||||
|
||||
**New fields** (old ones kept unchanged for backward compatibility):
|
||||
- `pid` — melody being played (`""` when idle)
|
||||
- `speed` — ms per beat (0 when idle)
|
||||
- `duration` — requested run-time cap in ms. This is `Player::total_duration` *after* `mode`/legacy
|
||||
resolution (`timed` → `duration`, `interval` → `total_duration`, legacy → `segment_duration` or
|
||||
`total_duration`), i.e. the value the stop timer actually uses. `0` = no cap.
|
||||
- `started_at` — Unix epoch s (UTC) when playback started, derived at publish time as `ts − elapsed`
|
||||
so it is right even for a snapshot built mid-playback. `0` when idle or no valid clock.
|
||||
- `source` — `app` | `rf` | `button` | `schedule` | `unknown` (`""` when idle).
|
||||
- `ts` — Unix epoch s (UTC) when the message was built, `0` if no valid clock.
|
||||
|
||||
**Clock.** `Player::currentEpoch()`: the system clock if it is past 2024-01-01 (it is UTC once NTP has
|
||||
synced via `configTime(0, 0, …)`), else `Timekeeper::getUtcEpoch()` (new) on RTC builds, else `0`.
|
||||
The RTC holds *local* time (NTP results and `clock.set_time` are written with GMT+DST applied), so
|
||||
`getUtcEpoch()` subtracts the configured offsets back out; it returns 0 when the RTC isn't running and
|
||||
never logs. RTC-less builds (agnus) report `0` until NTP syncs.
|
||||
|
||||
**Source is carried, not guessed.** `CommandEnvelope` gained an `origin` field
|
||||
(`UNKNOWN`/`APP`/`BUTTON`/`SCHEDULE`) set by each transport when it builds the envelope: MQTT, WebSocket,
|
||||
HTTP and the settings web server → `APP`; UART → `BUTTON` (its peer is the LCD/button slave board).
|
||||
`PlaybackHandler` maps it to `PlaybackSource` and passes it to `Player::command()`; `RFRemote::triggerPlay()`
|
||||
passes `PlaybackSource::RF` directly. `SCHEDULE` is reserved — `Timekeeper::triggerEvent()` is still a TODO
|
||||
and never starts playback.
|
||||
|
||||
**One writer for both transports.** New `src/Player/PlaybackState.hpp` defines `PlaybackSnapshot` with a
|
||||
single `writeTo(JsonObject)`. `Player::setStatus()` builds one snapshot (`Player::getPlaybackSnapshot()`,
|
||||
public so the MQTT connect path can reuse it) and writes it both into the WebSocket INFO broadcast
|
||||
(under `payload`, legacy shape) and to `CommunicationRouter::publishPlayback(snapshot)` (flat), so
|
||||
local and remote clients see identical fields. `publishPlayback()` now checks
|
||||
`MQTTDriver::hasHeapForPublish()` before building the document, same as the heartbeat. Payload is ~170
|
||||
bytes.
|
||||
|
||||
Verified: `pio run -e vesper-std-v1` and `pio run -e agnus-v1` both build clean.
|
||||
|
||||
Subsystem: `src/Player/PlaybackState.hpp` (new), `src/Player/Player.hpp`, `src/Player/Player.cpp`, `src/TimeKeeper/TimeKeeper.hpp`, `src/TimeKeeper/TimeKeeper.cpp`, `src/Communication/CommandBus/CommandEnvelope.hpp`, `src/Communication/Handlers/PlaybackHandler/PlaybackHandler.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, all five transports (origin), `src/RFRemote/RFRemote.cpp`, `src/Version.hpp` (→ 2.3.0)
|
||||
|
||||
@@ -87,19 +87,47 @@ to `status/heartbeat` (QoS 1, retained), overwriting the last "online" heartbeat
|
||||
|
||||
**QoS:** 1 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
|
||||
|
||||
Published by `Player::setStatus()` on every transition (not polled).
|
||||
Published by `Player::setStatus()` on every transition (not polled). This topic — not the `control/ack` reply — is the source of truth for what the board is actually doing. Skipped (not queued) while free heap is below the publish guard.
|
||||
|
||||
### Payload
|
||||
|
||||
Flat — no envelope wrapper.
|
||||
|
||||
```json
|
||||
{ "action": "playing", "time_elapsed": 12, "projected_run_time": 45000 }
|
||||
{
|
||||
"action": "playing",
|
||||
"time_elapsed": 12,
|
||||
"projected_run_time": 45000,
|
||||
"pid": "westminster",
|
||||
"speed": 400,
|
||||
"duration": 120000,
|
||||
"started_at": 1790000000,
|
||||
"source": "app",
|
||||
"ts": 1790000012
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{ "action": "idle", "time_elapsed": 0, "projected_run_time": 0, "pid": "", "speed": 0, "duration": 0, "started_at": 0, "source": "", "ts": 1790000130 }
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `action` | string | `playing` \| `paused` \| `idle` |
|
||||
| `time_elapsed` | integer | Seconds since playback started (0 for `idle`) |
|
||||
| `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) |
|
||||
| `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. |
|
||||
| `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. |
|
||||
|
||||
**Clock source for `started_at` / `ts`:** the NTP-synced system clock if valid, else the RTC (converted from its stored local time to UTC using the configured offsets), else `0`. RTC-less builds (agnus) therefore report `0` until NTP has synced. Always check for `0` before using either.
|
||||
|
||||
**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... } }`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ and [MQTTTransport](../../src/Communication/Transport/MQTTTransport/README.md) (
|
||||
| `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}/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`/`idle`, plus `time_elapsed`, `projected_run_time`. Published on transition, not polled. |
|
||||
| `vesper/{device_id}/status/playback` | Playback state transitions only | 1 | **Yes** | `playback` | `action`: `playing`/`paused`/`idle`, 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. 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()`. |
|
||||
|
||||
@@ -30,6 +30,18 @@ struct CommandEnvelope {
|
||||
|
||||
Transport transport = Transport::WEBSOCKET;
|
||||
|
||||
// Who issued the command, as far as the transport knows. Set by each
|
||||
// transport when it builds the envelope (MQTT/WebSocket/HTTP → APP, UART
|
||||
// slave board → BUTTON). Handlers that record provenance (PlaybackHandler →
|
||||
// status/playback "source") read this instead of guessing from `transport`.
|
||||
enum class Origin {
|
||||
UNKNOWN,
|
||||
APP,
|
||||
BUTTON,
|
||||
SCHEDULE
|
||||
};
|
||||
Origin origin = Origin::UNKNOWN;
|
||||
|
||||
// WebSocket client ID — 0 for transports that don't have per-client identity
|
||||
uint32_t clientId = 0;
|
||||
|
||||
|
||||
@@ -649,19 +649,18 @@ void CommunicationRouter::publishInfo(const String& type, const JsonDocument& pa
|
||||
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs) {
|
||||
void CommunicationRouter::publishPlayback(const PlaybackSnapshot& snapshot) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().playback) return;
|
||||
if (!_mqttClient.hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
||||
|
||||
JsonDocument doc;
|
||||
doc["action"] = action;
|
||||
doc["time_elapsed"] = timeElapsedSec;
|
||||
doc["projected_run_time"] = projectedRunTimeMs;
|
||||
snapshot.writeTo(doc.to<JsonObject>());
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 1, true);
|
||||
LOG_DEBUG(TAG, "Playback published: %s", action.c_str());
|
||||
LOG_DEBUG(TAG, "Playback published: %s", snapshot.action);
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishReport(const String& type, const JsonDocument& payload) {
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
#include "../Transport/WebServerTransport/WebServerTransport.hpp"
|
||||
|
||||
#include "../../OTAManager/OTAManager.hpp" // needed for OTAManager::ErrorCode in otaErrorCodeToString()
|
||||
#include "../../Player/PlaybackState.hpp" // PlaybackSnapshot for publishPlayback()
|
||||
|
||||
// Forward declarations — resolved in .cpp
|
||||
class ConfigManager;
|
||||
@@ -121,16 +122,15 @@ public:
|
||||
const String& severity);
|
||||
|
||||
/**
|
||||
* @brief Publish a playback state transition to vesper/{id}/status/playback (retained).
|
||||
* @brief Publish the playback state to vesper/{id}/status/playback (retained, QoS 1).
|
||||
* Called by Player::setStatus() on every transition. WS clients
|
||||
* still receive the same event via broadcastStatus() separately —
|
||||
* this is the MQTT-specific path.
|
||||
* still receive the same fields via broadcastStatus() separately —
|
||||
* this is the MQTT-specific path. Skipped (not queued) when MQTT is
|
||||
* down, the "playback" switch is off, or heap is below the publish guard.
|
||||
*
|
||||
* @param action "playing" | "paused" | "idle"
|
||||
* @param timeElapsedSec Seconds since playback started (0 for idle)
|
||||
* @param projectedRunTimeMs Projected total run time in ms (0 if not applicable)
|
||||
* @param snapshot Player::getPlaybackSnapshot() — see PlaybackState.hpp for fields
|
||||
*/
|
||||
void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs);
|
||||
void publishPlayback(const PlaybackSnapshot& snapshot);
|
||||
|
||||
/**
|
||||
* @brief Publish a critical, time-sensitive board-initiated event to
|
||||
|
||||
@@ -16,12 +16,23 @@ CommandResult PlaybackHandler::execute(const CommandEnvelope& envelope) {
|
||||
return CommandResult::err("playback", "Unknown playback command");
|
||||
}
|
||||
|
||||
// Carry the command's origin through to the Player so status/playback can
|
||||
// report what triggered playback (see PlaybackState.hpp).
|
||||
static PlaybackSource sourceFromOrigin(CommandEnvelope::Origin origin) {
|
||||
switch (origin) {
|
||||
case CommandEnvelope::Origin::APP: return PlaybackSource::APP;
|
||||
case CommandEnvelope::Origin::BUTTON: return PlaybackSource::BUTTON;
|
||||
case CommandEnvelope::Origin::SCHEDULE: return PlaybackSource::SCHEDULE;
|
||||
default: return PlaybackSource::UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
CommandResult PlaybackHandler::handlePlay(const CommandEnvelope& envelope) {
|
||||
// Inject action so Player::command() takes the play branch regardless of
|
||||
// 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>());
|
||||
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");
|
||||
}
|
||||
@@ -29,7 +40,7 @@ CommandResult PlaybackHandler::handlePlay(const CommandEnvelope& envelope) {
|
||||
CommandResult PlaybackHandler::handleStop(const CommandEnvelope& envelope) {
|
||||
JsonDocument& contents = const_cast<JsonDocument&>(envelope.contents);
|
||||
contents["action"] = "stop";
|
||||
bool ok = _player.command(contents.as<JsonVariant>());
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -85,6 +85,7 @@ void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request,
|
||||
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||
envelope.origin = CommandEnvelope::Origin::APP;
|
||||
envelope.clientId = 0;
|
||||
envelope.command = cmd;
|
||||
envelope.version = doc["v"] | 2;
|
||||
@@ -138,6 +139,7 @@ void HTTPTransport::handleStatusRequest(AsyncWebServerRequest* request) {
|
||||
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||
envelope.origin = CommandEnvelope::Origin::APP;
|
||||
envelope.clientId = 0;
|
||||
envelope.command = "system.status";
|
||||
envelope.version = 2;
|
||||
|
||||
@@ -82,6 +82,7 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||
// Build the envelope
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::MQTT;
|
||||
envelope.origin = CommandEnvelope::Origin::APP;
|
||||
envelope.clientId = 0;
|
||||
envelope.command = doc["cmd"].as<String>();
|
||||
envelope.version = doc["v"] | 1;
|
||||
|
||||
@@ -76,6 +76,7 @@ void UARTTransport::onMessage(JsonDocument& doc) {
|
||||
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::UART;
|
||||
envelope.origin = CommandEnvelope::Origin::BUTTON; // UART peer is the LCD/button slave board
|
||||
envelope.clientId = 0;
|
||||
envelope.command = cmd;
|
||||
envelope.version = doc["v"] | 1;
|
||||
|
||||
@@ -87,6 +87,7 @@ void WebServerTransport::handleSetMode(AsyncWebServerRequest* request) {
|
||||
// Route through CommandBus: network.set_config with permanent_ap_mode field.
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||
envelope.origin = CommandEnvelope::Origin::APP;
|
||||
envelope.clientId = 0;
|
||||
envelope.command = "network.set_config";
|
||||
envelope.version = 2;
|
||||
@@ -116,6 +117,7 @@ void WebServerTransport::handleReboot(AsyncWebServerRequest* request) {
|
||||
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||
envelope.origin = CommandEnvelope::Origin::APP;
|
||||
envelope.clientId = 0;
|
||||
envelope.command = "system.restart";
|
||||
envelope.version = 2;
|
||||
|
||||
@@ -68,6 +68,7 @@ void WebSocketTransport::onMessage(uint32_t clientId, const JsonDocument& doc) {
|
||||
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::WEBSOCKET;
|
||||
envelope.origin = CommandEnvelope::Origin::APP;
|
||||
envelope.clientId = clientId;
|
||||
envelope.command = cmd;
|
||||
envelope.version = doc["v"] | 1;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PlaybackState
|
||||
//
|
||||
// The wire-level description of what the Player is doing, shared by the two
|
||||
// places that publish it: Player::setStatus() (WebSocket INFO broadcast, under
|
||||
// "payload") and CommunicationRouter::publishPlayback() (MQTT status/playback,
|
||||
// flat). One writer (PlaybackSnapshot::writeTo) keeps local and remote clients
|
||||
// byte-for-byte identical. See docs/reference/mqtt-events.md → status/playback.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// What triggered the current playback. Carried from the command's origin
|
||||
// (CommandEnvelope::origin, or the RF remote calling Player directly) — never
|
||||
// inferred after the fact.
|
||||
enum class PlaybackSource : uint8_t {
|
||||
UNKNOWN,
|
||||
APP, // MQTT / WebSocket / HTTP command
|
||||
RF, // RF remote slot
|
||||
SCHEDULE, // scheduled event (reserved — Timekeeper doesn't start playback yet)
|
||||
BUTTON // UART slave board (LCD / physical buttons)
|
||||
};
|
||||
|
||||
inline const char* playbackSourceToString(PlaybackSource s) {
|
||||
switch (s) {
|
||||
case PlaybackSource::APP: return "app";
|
||||
case PlaybackSource::RF: return "rf";
|
||||
case PlaybackSource::SCHEDULE: return "schedule";
|
||||
case PlaybackSource::BUTTON: return "button";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
struct PlaybackSnapshot {
|
||||
const char* action = "idle"; // playing | paused | stopping | idle
|
||||
uint32_t timeElapsedSec = 0; // since playback started (0 when idle)
|
||||
uint64_t projectedRunTimeMs = 0; // 0 if not applicable
|
||||
String pid; // "" when idle
|
||||
uint16_t speed = 0; // ms per beat (0 when idle)
|
||||
uint32_t durationMs = 0; // requested run-time cap, 0 = no cap
|
||||
uint32_t startedAt = 0; // Unix epoch s, 0 if idle or no valid clock
|
||||
const char* source = ""; // app | rf | schedule | button | unknown ("" when idle)
|
||||
uint32_t ts = 0; // Unix epoch s at publish, 0 if no valid clock
|
||||
|
||||
void writeTo(JsonObject obj) const {
|
||||
obj["action"] = action;
|
||||
obj["time_elapsed"] = timeElapsedSec;
|
||||
obj["projected_run_time"] = projectedRunTimeMs;
|
||||
obj["pid"] = pid;
|
||||
obj["speed"] = speed;
|
||||
obj["duration"] = durationMs;
|
||||
obj["started_at"] = startedAt;
|
||||
obj["source"] = source;
|
||||
obj["ts"] = ts;
|
||||
}
|
||||
};
|
||||
+53
-38
@@ -1,4 +1,5 @@
|
||||
#include "Player.hpp"
|
||||
#include <time.h>
|
||||
|
||||
#define TAG "Player"
|
||||
#include "../Communication/CommunicationRouter/CommunicationRouter.hpp"
|
||||
@@ -203,7 +204,7 @@ void Player::unpause() {
|
||||
LOG_DEBUG(TAG, "Plbck: RESUME");
|
||||
}
|
||||
|
||||
bool Player::command(JsonVariant data) {
|
||||
bool Player::command(JsonVariant data, PlaybackSource source) {
|
||||
String action = data["action"];
|
||||
LOG_DEBUG(TAG, "Incoming Command: %s", action.c_str());
|
||||
|
||||
@@ -222,6 +223,7 @@ bool Player::command(JsonVariant data) {
|
||||
}
|
||||
|
||||
setMelodyAttributes(data);
|
||||
_source = source;
|
||||
|
||||
if (action == "play") {
|
||||
String pidStr = String(pid.c_str());
|
||||
@@ -526,52 +528,65 @@ void Player::setStatus(PlayerStatus newStatus) {
|
||||
|
||||
// Send appropriate message to ALL clients (WebSocket + MQTT) based on status change
|
||||
if (_commManager) {
|
||||
StaticJsonDocument<256> doc;
|
||||
PlaybackSnapshot snapshot = getPlaybackSnapshot();
|
||||
|
||||
// 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";
|
||||
|
||||
// Create payload object for complex data
|
||||
JsonObject payload = doc.createNestedObject("payload");
|
||||
|
||||
switch (newStatus) {
|
||||
case PlayerStatus::PLAYING:
|
||||
payload["action"] = "playing";
|
||||
payload["time_elapsed"] = (millis() - startTime) / 1000; // Convert to seconds
|
||||
break;
|
||||
case PlayerStatus::PAUSED:
|
||||
payload["action"] = "paused";
|
||||
payload["time_elapsed"] = (millis() - startTime) / 1000;
|
||||
break;
|
||||
case PlayerStatus::STOPPED:
|
||||
payload["action"] = "idle";
|
||||
payload["time_elapsed"] = 0;
|
||||
break;
|
||||
case PlayerStatus::STOPPING:
|
||||
payload["action"] = "stopping";
|
||||
payload["time_elapsed"] = (millis() - startTime) / 1000;
|
||||
break;
|
||||
}
|
||||
|
||||
// Add projected run time for all states (0 if not applicable)
|
||||
uint64_t projectedRunTime = calculateProjectedRunTime();
|
||||
payload["projected_run_time"] = projectedRunTime;
|
||||
|
||||
// WebSocket clients keep the existing envelope shape via broadcastStatus().
|
||||
snapshot.writeTo(doc["payload"].to<JsonObject>());
|
||||
_commManager->broadcastStatus(doc);
|
||||
|
||||
// MQTT clients get the dedicated status/playback topic — see
|
||||
// docs/reference/vesper_mqtt_topic_spec_v2.md. Same action/time_elapsed/
|
||||
// projected_run_time values, just published to a topic that carries
|
||||
// ONLY playback transitions instead of every broadcastStatus() event.
|
||||
_commManager->publishPlayback(payload["action"].as<String>(),
|
||||
payload["time_elapsed"].as<uint32_t>(),
|
||||
projectedRunTime);
|
||||
// MQTT clients get the dedicated status/playback topic (flat, retained) —
|
||||
// see docs/reference/mqtt-events.md.
|
||||
_commManager->publishPlayback(snapshot);
|
||||
|
||||
LOG_DEBUG(TAG, "Status changed: %d → %d, broadcast sent with runTime: %llu",
|
||||
(int)oldStatus, (int)newStatus, projectedRunTime);
|
||||
(int)oldStatus, (int)newStatus, snapshot.projectedRunTimeMs);
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t Player::currentEpoch() {
|
||||
static constexpr time_t MIN_VALID_EPOCH = 1704067200; // 2024-01-01T00:00:00Z
|
||||
|
||||
// System clock is UTC once NTP has synced (Timekeeper::syncTimeWithNTP →
|
||||
// configTime(0, 0, ...)); before that it counts up from 1970.
|
||||
time_t now = time(nullptr);
|
||||
if (now >= MIN_VALID_EPOCH) return (uint32_t)now;
|
||||
|
||||
#if HAS_RTC
|
||||
// No NTP (common on internet-less site networks) — fall back to the RTC.
|
||||
if (_timekeeper) return _timekeeper->getUtcEpoch();
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
PlaybackSnapshot Player::getPlaybackSnapshot() {
|
||||
PlaybackSnapshot s;
|
||||
s.ts = currentEpoch();
|
||||
s.projectedRunTimeMs = calculateProjectedRunTime();
|
||||
|
||||
switch (_status) {
|
||||
case PlayerStatus::PLAYING: s.action = "playing"; break;
|
||||
case PlayerStatus::PAUSED: s.action = "paused"; break;
|
||||
case PlayerStatus::STOPPING: s.action = "stopping"; break;
|
||||
case PlayerStatus::STOPPED:
|
||||
default:
|
||||
s.action = "idle";
|
||||
return s; // pid "", speed/duration/started_at 0, source ""
|
||||
}
|
||||
|
||||
uint32_t elapsedSec = (uint32_t)((millis() - startTime) / 1000);
|
||||
s.timeElapsedSec = elapsedSec;
|
||||
s.pid = pid.c_str();
|
||||
s.speed = speed;
|
||||
s.durationMs = total_duration; // the effective stop timer after mode/legacy fixups; 0 = no cap
|
||||
s.source = playbackSourceToString(_source);
|
||||
s.startedAt = (s.ts != 0) ? s.ts - elapsedSec : 0;
|
||||
return s;
|
||||
}
|
||||
|
||||
void Player::onMelodyLoopCompleted() {
|
||||
segmentCmpltTime = millis();
|
||||
|
||||
|
||||
+20
-2
@@ -57,6 +57,7 @@
|
||||
#include "freertos/task.h" // FreeRTOS task management
|
||||
#include "../Logging/Logging.hpp" // Centralized logging system
|
||||
#include "../FileManager/FileManager.hpp" // File operations abstraction
|
||||
#include "PlaybackState.hpp" // PlaybackSource + PlaybackSnapshot (status/playback wire shape)
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// FORWARD DECLARATIONS - Dependencies injected at runtime
|
||||
@@ -205,8 +206,12 @@ public:
|
||||
/** @brief Resume paused playback */
|
||||
void unpause();
|
||||
|
||||
/** @brief Handle JSON commands from communication layer */
|
||||
bool command(JsonVariant data);
|
||||
/**
|
||||
* @brief Handle JSON commands from communication layer
|
||||
* @param source What issued the command — recorded on an accepted play and
|
||||
* reported as status/playback "source"
|
||||
*/
|
||||
bool command(JsonVariant data, PlaybackSource source = PlaybackSource::UNKNOWN);
|
||||
|
||||
/** @brief Set melody attributes from JSON configuration */
|
||||
void setMelodyAttributes(JsonVariant doc);
|
||||
@@ -248,6 +253,13 @@ public:
|
||||
/** @brief Calculate the projected total run time of current playback */
|
||||
uint64_t calculateProjectedRunTime() const;
|
||||
|
||||
/**
|
||||
* @brief Current playback state in its wire shape (status/playback + WS INFO).
|
||||
* Safe to call at any time — used by setStatus() and to republish the
|
||||
* real state on every MQTT (re)connect.
|
||||
*/
|
||||
PlaybackSnapshot getPlaybackSnapshot();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -283,6 +295,12 @@ private:
|
||||
// Async download — permanent task signalled via task notification
|
||||
TaskHandle_t _downloadTaskHandle = nullptr;
|
||||
|
||||
// Origin of the command that started the current playback (status/playback "source")
|
||||
PlaybackSource _source = PlaybackSource::UNKNOWN;
|
||||
|
||||
/** @brief Unix epoch seconds (UTC) — NTP system clock, else RTC; 0 if neither is valid */
|
||||
uint32_t currentEpoch();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE HELPER METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -389,7 +389,7 @@ void RFRemote::triggerPlay(uint8_t slot) {
|
||||
na.add(s.note_assignments[i]);
|
||||
}
|
||||
|
||||
_player->command(doc.as<JsonVariant>());
|
||||
_player->command(doc.as<JsonVariant>(), PlaybackSource::RF);
|
||||
}
|
||||
|
||||
void RFRemote::triggerStop() {
|
||||
|
||||
@@ -139,6 +139,15 @@ void Timekeeper::setTimeWithLocalTimestamp(unsigned long localTimestamp) {
|
||||
loadTodaysEvents();
|
||||
}
|
||||
|
||||
uint32_t Timekeeper::getUtcEpoch() {
|
||||
static constexpr int64_t MIN_VALID_EPOCH = 1704067200; // 2024-01-01T00:00:00Z
|
||||
if (!_configManager || !rtc.isrunning()) return 0;
|
||||
|
||||
const auto& tc = _configManager->getTimeConfig();
|
||||
int64_t utc = (int64_t)rtc.now().unixtime() - (tc.gmtOffsetSec + tc.daylightOffsetSec);
|
||||
return (utc >= MIN_VALID_EPOCH) ? (uint32_t)utc : 0;
|
||||
}
|
||||
|
||||
unsigned long Timekeeper::getTime() {
|
||||
if (!rtc.isrunning()) {
|
||||
LOG_ERROR(TAG, "RTC not running - cannot get time");
|
||||
|
||||
@@ -119,6 +119,17 @@ public:
|
||||
*/
|
||||
void setTimeWithLocalTimestamp(unsigned long localTimestamp); // Set RTC time from Unix timestamp
|
||||
unsigned long getTime(); // Get current time as Unix timestamp
|
||||
|
||||
/**
|
||||
* @brief True UTC Unix epoch seconds from the RTC, or 0 if unavailable.
|
||||
*
|
||||
* The RTC stores LOCAL time (NTP results and clock.set_time are written with
|
||||
* the configured GMT+DST offsets applied), so getTime() is not a Unix epoch.
|
||||
* This subtracts the stored offsets back out. Returns 0 if the RTC isn't
|
||||
* running or the result predates 2024 (unset/garbage clock). Never logs —
|
||||
* safe to call on every playback transition.
|
||||
*/
|
||||
uint32_t getUtcEpoch();
|
||||
void syncTimeWithNTP(); // Sync RTC time with NTP server
|
||||
|
||||
// Event management
|
||||
|
||||
+4
-1
@@ -21,8 +21,11 @@
|
||||
// system/alerts+info+logs+metrics, LWT, req_id correlation, per-topic switches
|
||||
// v2.2.1 - Fixes malformed control/command input (bad JSON, missing cmd) being
|
||||
// silently dropped instead of replying with an ERROR on control/ack
|
||||
// v2.3.0 - Remote-app playback support: richer status/playback (pid/speed/duration/
|
||||
// started_at/source/ts), republish on MQTT connect, specific playback
|
||||
// errors, "loading" state + playback_failed report for downloads
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
#define FW_VERSION "2.2.1"
|
||||
#define FW_VERSION "2.3.0"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// SemVer — lightweight 3-part version struct
|
||||
|
||||
Reference in New Issue
Block a user