diff --git a/docs/README.md b/docs/README.md index 00f4947..ece90bf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,7 @@ Bell automation firmware for ESP32 (Kincony KC868-A6). | File | Description | |---|---| | [architecture/communication-refactor-plan.md](architecture/communication-refactor-plan.md) | Full design doc for the v2 Communication subsystem (CommandBus, Handlers, Transports) | +| [architecture/legacy-response-adapter.md](architecture/legacy-response-adapter.md) | `LegacyResponseAdapter` — v2→v1 reply translation for the v1→v2 migration window (temporary, with removal steps) | ## Features diff --git a/docs/architecture/legacy-response-adapter.md b/docs/architecture/legacy-response-adapter.md new file mode 100644 index 0000000..eb98f88 --- /dev/null +++ b/docs/architecture/legacy-response-adapter.md @@ -0,0 +1,132 @@ +# LegacyResponseAdapter — v2 → v1 reply translation + +> Written: 2026-09-17 +> Status: **Active** — temporary migration scaffolding, scoped to a known removal condition +> Related: [communication-refactor-plan.md](communication-refactor-plan.md), [reference/api-reference.md](../reference/api-reference.md), [reference/api-reference-v1-legacy.md](../reference/api-reference-v1-legacy.md) + +--- + +## Why this exists + +The firmware's `LegacyAdapter` (`src/Communication/CommandBus/LegacyAdapter.cpp`) already translates +incoming v1 **requests** (no `"v"` field, or `"v":1` — sent by tablets still running the pre-refactor +Flutter app) into v2 internal commands, so old and new clients can share the same handler code. That +half of the migration bridge works correctly. + +The other half was missing: v2 handlers reply using v2 conventions (namespaced `type` strings, data +nested under `"data"` instead of `"payload"`, UPPERCASE status-enum strings, object-keyed +`strike_counters` instead of an array). A v1-only app doesn't recognise any of that. Concretely, for +`system.status` (the v1 app's `system_info/report_status` poll): + +| Aspect | v1 app expects | v2 firmware sent (before this fix) | +|---|---|---| +| Reply `type` | `"current_status"` | `"system.status"` | +| Structured field container | `payload` | `data` | +| `player_status` value | lowercase (`"playing"`, `"idle"`, ...) | UPPERCASE (`"PLAYING"`, `"STOPPED"`, ...) | +| Elapsed-time field | `time_elapsed` | `time_elapsed_ms` | +| `strike_counters` | JSON array | JSON object keyed `"0".."15"` | + +Because the reply never matched what the app's `sendAndWaitForResponse` matcher was waiting for, the +app's own 5-second request timeout fired, hit its `catch` block, and explicitly set +`playbackStatus: PlaybackStatus.unavailable` — **while the device was actually playing correctly and +had already replied.** This looked like an intermittent connectivity/availability bug but was a pure +reply-schema mismatch. `ResponseBuilder::deviceStatus()` (still present in +`src/Communication/ResponseBuilder/ResponseBuilder.cpp`) already builds the exact correct v1 shape — +it's dead code, unwired since the v2 refactor, which is the strongest evidence this was a regression +rather than an intentional break. + +The async `playback` INFO push (`Player::setStatus()`, `src/Player/Player.cpp:519-565`) was checked +too and does **not** have this problem — it already uses `type/payload`, `action` (not +`player_status`), and lowercase status words, matching what the v1 app expects. No changes were made +there. + +## What this migration is (and isn't) + +The plan going forward is to update **all** devices (firmware + tablets) to the v2 API. Until every +tablet in the field is confirmed on v2+, some boards running v2 firmware will still be talking to +tablets that only understand v1. `LegacyResponseAdapter` exists purely to keep that mixed-fleet window +functional — it is not a permanent second protocol. + +**Exit condition:** once fleet/console telemetry confirms zero v1-originated requests (no envelope +arriving with `"v"` missing or `"v":1`) for a safe observation period, delete this adapter and +`LegacyAdapter` together — see "How to remove" below. + +## What was built + +### `LegacyResponseAdapter` (`src/Communication/CommandBus/LegacyResponseAdapter.{hpp,cpp}`) + +A narrow, allowlisted translator — the reply-side mirror of `LegacyAdapter`. It does **not** attempt a +generic v1/v2 schema mapping; it only rewrites the specific `CommandResult` types known to diverge. +Today that's just `system.status`. If a future v2 handler introduces another reply shape a v1 client +depends on, add a case to `LegacyResponseAdapter.cpp` rather than generalising the mechanism — keeping +it a short, explicit list makes it easy to audit and easy to delete in full later. + +```cpp +// Returns true and fills `out` if a translation was applied. +// Returns false (out untouched) if the result isn't one this adapter +// knows how to translate — caller falls back to normal v2 serialisation. +bool translateLegacyResponse(const CommandResult& result, JsonDocument& out); +``` + +### Wiring: capture the *original* request version before dispatch mutates it + +`CommandBus::dispatch()` overwrites `envelope.version = 2` after `LegacyAdapter` translates a v1 +envelope (so the bus doesn't re-translate on a hypothetical second pass). That happens *before* the +reply lambda runs, so the reply lambda can't just read `envelope.version` at reply time — it has to +capture the original value by copy, at the point the lambda is constructed (which happens after +`envelope.version` is set from the incoming `"v"` field, but before `_bus.dispatch(envelope)` runs). + +Each transport's reply lambda now does this: + +```cpp +envelope.version = doc["v"] | 1; // (unchanged — existing per-transport default) + +// Capture the ORIGINAL version before CommandBus::dispatch() rewrites +// envelope.version to 2 post-translation (see LegacyAdapter.hpp). +bool isLegacyRequest = (envelope.version == 1); + +envelope.reply = [this, /* ... */, isLegacyRequest](const CommandResult& result) { + JsonDocument resp; + if (!isLegacyRequest || !translateLegacyResponse(result, resp)) { + // ... existing v2 serialisation, unchanged ... + } + // ... serialise `resp` and send, unchanged ... +}; +``` + +If `isLegacyRequest` is false, or the result's `type` isn't one `LegacyResponseAdapter` knows about, +behaviour is byte-for-byte identical to before this change — v2 clients and unaffected reply types are +untouched. + +### Scope — which transports were changed + +| Transport | Changed? | Reason | +|---|---|---| +| WebSocket (`WebSocketTransport.cpp`) | ✅ | Primary tablet transport — this is the live bug's path | +| MQTT (`MQTTTransport.cpp`) | ✅ | Same request/reply shape, same v1 default; console/backend or any MQTT-side v1 caller gets the same fix | +| HTTP (`HTTPTransport.cpp`, `handleCommandRequest`) | ✅ | Defaults unversioned requests to v2 already (`doc["v"] \| 2`, unlike the other transports' `\| 1`), so this only fires if a caller explicitly sends `"v":1` — added for symmetry/completeness, not a known live bug | +| HTTP (`HTTPTransport.cpp`, `handleStatusRequest`) | ❌ | Hardcodes `envelope.version = 2` — internal shortcut route, never receives a v1-tagged request | +| UART (`UARTTransport.cpp`) | ❌ | Used for board-to-board/internal links per `UARTTransport::WHITELIST`, not tablets. No evidence any UART peer speaks v1. Left alone to avoid unnecessary risk — revisit if that assumption changes | +| `CommandBus::broadcast()` | ❌ | Separate mechanism (internal subsystem → client push events, e.g. `_bus.broadcast(CommandResult::info(...))`), unrelated to per-request replies or to `Player`'s playback push. Not exercised by the bug. | + +## How to remove (when the migration is complete) + +This was designed to be deleted as a single, contained change: + +1. Delete `src/Communication/CommandBus/LegacyResponseAdapter.hpp` and `.cpp`. +2. In each of `WebSocketTransport.cpp`, `MQTTTransport.cpp`, `HTTPTransport.cpp`: + - Remove the `#include ".../LegacyResponseAdapter.hpp"` line. + - Remove the `bool isLegacyRequest = ...` line. + - Remove the `if (!isLegacyRequest || !translateLegacyResponse(result, resp))` wrapper, keeping the + v2 serialisation body unconditional (drop the `if`, keep the `{ ... }` contents). +3. Do the same removal for `LegacyAdapter` (see its own header comment in + `src/Communication/CommandBus/LegacyAdapter.hpp`) in the same PR — the two are a matched pair; there + is no reason to keep one without the other. +4. Delete `ResponseBuilder::deviceStatus()` (dead code, superseded by this adapter) if it's still + unused at that point — confirm with a repo-wide grep first. +5. Update `docs/README.md`'s reference table and this file's own status line to reflect removal, and + move `docs/reference/api-reference-v1-legacy.md` content into a clearly historical/archived note if + it isn't already treated that way. + +No data migration, no NVS changes, no wire-format changes for v2-only clients — this is a pure code +deletion once the exit condition is met. diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index 652e472..0311b44 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -70,6 +70,7 @@ Every feature — user-facing or significant internal mechanism — is listed he | F-058 | Fix: NTP sync RTC corruption on flaky internet — de-dup guard, retry cooldown, large-jump consensus check | v2.1.7 | Stable | | F-059 | Fix: partition table mismatch blocking safe OTA to pre-restructure field devices | v2.1.7 | Stable | | F-060 | `system.set_identity` — sysadmin override of factory-set device identity (serial/hw_family/hw_revision) | v2.1.7 | Stable | +| F-061 | Fix: `LegacyResponseAdapter` — v1 tablets saw device as "unavailable" while playing, due to `system.status` reply schema mismatch | v2.1.7 | Stable (temporary migration scaffolding) | --- @@ -995,3 +996,40 @@ This adds a narrow, deliberate exception: a new `system.set_identity` command le Not gated behind an additional `confirm` field in the command body — the console UI is expected to require its own confirmation step before ever publishing this command, so no device-side friction was added on top of that. Subsystem: `src/ConfigManager/ConfigManager.hpp`, `src/ConfigManager/ConfigManager.cpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.hpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.cpp` + +--- + +### F-061 — Fix: `LegacyResponseAdapter` — v1 tablets saw device as "unavailable" while playing + +`LegacyAdapter` already translates incoming v1 **requests** (tablets still on the old Flutter app, +which never sends a `"v"` field) into v2 internal commands. What was missing was the reverse: v2 +handlers reply using v2 conventions — `system.status`'s reply used `type:"system.status"` with fields +under `data`, UPPERCASE status strings (`"PLAYING"`/`"STOPPED"`/...), `time_elapsed_ms`, and +`strike_counters` as an object keyed `"0".."15"` — none of which the v1 app recognises. It polls for +`type:"current_status"` with fields under `payload`, lowercase status strings, `time_elapsed`, and +`strike_counters` as an array. + +Because the reply never matched, the v1 app's own 5-second request timeout fired every time, and its +`catch` block explicitly set `playbackStatus: PlaybackStatus.unavailable` — **while the device was +actually playing correctly and had already replied.** This was reported as "the board shows +unavailable sometimes while it's playing" and traced to this schema mismatch, not a real +connectivity/timeout issue. The async `playback` INFO push (`Player::setStatus()`) was checked too and +was already v1-compatible — no changes needed there. + +**Fix.** Added `LegacyResponseAdapter` (`src/Communication/CommandBus/LegacyResponseAdapter.{hpp,cpp}`) +— a narrow, allowlisted translator that rewrites a `CommandResult` back into v1 shape, but only for +replies to requests whose *original* envelope version was 1 (v2 clients and all other reply types are +untouched, byte-for-byte). Each transport's reply lambda now captures `isLegacyRequest` (from +`envelope.version` before `CommandBus::dispatch()` overwrites it to 2) and routes through the adapter +when true. Wired into WebSocket, MQTT, and HTTP's general command path; not touched: HTTP's +`system.status` shortcut route (hardcodes v2) and UART (board-to-board only, no known v1 peers). + +This is deliberately temporary migration scaffolding, not new permanent architecture — the plan is to +update all devices (firmware + tablets) to v2 and retire both `LegacyAdapter` and +`LegacyResponseAdapter` together once fleet telemetry shows zero v1 requests. Full rationale, the +before/after schema table, and the exact removal steps are in +[architecture/legacy-response-adapter.md](../architecture/legacy-response-adapter.md). + +Verified: `pio run -e vesper-std-v1` builds clean (all four environments share the touched files). + +Subsystem: `src/Communication/CommandBus/LegacyResponseAdapter.hpp` (new), `src/Communication/CommandBus/LegacyResponseAdapter.cpp` (new), `src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`, `src/Communication/Transport/HTTPTransport/HTTPTransport.cpp` diff --git a/src/Communication/CommandBus/LegacyResponseAdapter.cpp b/src/Communication/CommandBus/LegacyResponseAdapter.cpp new file mode 100644 index 0000000..9478905 --- /dev/null +++ b/src/Communication/CommandBus/LegacyResponseAdapter.cpp @@ -0,0 +1,54 @@ +#include "LegacyResponseAdapter.hpp" +#include "CommandResult.hpp" + +// --------------------------------------------------------------------------- +// Known v2 → v1 reply divergences. +// +// Each entry here corresponds to a v2 CommandResult "type" that a v1 client +// polls for and parses with hardcoded v1 field names/shapes. Add a new case +// only when a real v1 caller is confirmed to depend on the old shape — see +// the file header for why this stays a narrow allowlist rather than a +// generic mapper. +// --------------------------------------------------------------------------- + +// system.status → current_status +// v1 app: docs/reference/dart-command-handler.dart SystemInfo.getDeviceStatus() +// matches on type=="current_status", reads payload.player_status (lowercase), +// payload.time_elapsed, payload.strike_counters as an array. +static bool translateSystemStatus(const CommandResult& result, JsonDocument& out) { + JsonObjectConst data = result.data.as(); + + out["status"] = "SUCCESS"; + out["type"] = "current_status"; + JsonObject payload = out["payload"].to(); + + // v2 sends UPPERCASE enum names (PLAYING/PAUSED/STOPPING/STOPPED); + // v1 expects lowercase state words, with STOPPED spelled "idle". + const char* v2Status = data["player_status"] | "STOPPED"; + const char* v1Status = "idle"; + if (strcmp(v2Status, "PLAYING") == 0) v1Status = "playing"; + else if (strcmp(v2Status, "PAUSED") == 0) v1Status = "paused"; + else if (strcmp(v2Status, "STOPPING") == 0) v1Status = "stopping"; + + payload["player_status"] = v1Status; + payload["time_elapsed"] = data["time_elapsed_ms"] | 0; // same unit (ms), renamed key + payload["projected_run_time"] = data["projected_run_time"] | 0; + + // v2 sends strike_counters as an object keyed "0".."15"; v1 expects an array. + JsonArray strikes = payload["strike_counters"].to(); + JsonObjectConst v2Strikes = data["strike_counters"].as(); + for (uint8_t i = 0; i < 16; i++) { + strikes.add(v2Strikes[String(i)] | 0); + } + + return true; +} + +bool translateLegacyResponse(const CommandResult& result, JsonDocument& out) { + if (result.type == "system.status" && result.hasData) { + return translateSystemStatus(result, out); + } + + // Not a known divergence — caller falls back to standard v2 serialisation. + return false; +} diff --git a/src/Communication/CommandBus/LegacyResponseAdapter.hpp b/src/Communication/CommandBus/LegacyResponseAdapter.hpp new file mode 100644 index 0000000..1155408 --- /dev/null +++ b/src/Communication/CommandBus/LegacyResponseAdapter.hpp @@ -0,0 +1,48 @@ +#pragma once + +// --------------------------------------------------------------------------- +// LegacyResponseAdapter — v2 → v1 reply translation +// +// Companion to LegacyAdapter (which translates v1 *requests* into v2 before +// dispatch). This adapter runs the other direction: it takes the v2 +// CommandResult a handler produced and rewrites it into the wire shape a v1 +// client expects, but ONLY for replies going back to a client whose original +// request came in as v1 (no "v" field, or "v":1). +// +// Why this exists: +// V1 tablets (old Flutter app, pre-refactor) send commands without a "v" +// field. LegacyAdapter maps those onto v2 internal commands so the same +// handler code services both old and new clients. But v2 handlers reply +// using the v2 envelope/field conventions (e.g. "system.status" instead of +// "current_status", data nested under "data" instead of "payload", +// UPPERCASE status enum strings, "strike_counters" as an object keyed by +// index instead of an array). A v1-only app doesn't recognise any of that, +// so from its point of view the device never replies — its own +// request-timeout logic then marks the device "unavailable" even though it +// answered correctly and promptly. See docs/architecture/legacy-response-adapter.md +// for the full incident writeup. +// +// Translation is intentionally narrow: it only rewrites the handful of +// fields/types that are actually known to diverge (see the .cpp). It is NOT +// a generic v1/v2 schema mapper — anything not explicitly listed here is +// passed through unchanged. If a future v2 handler introduces another +// diverging reply shape that v1 clients rely on, add a case here rather than +// generalising the mechanism. +// +// This is temporary migration scaffolding, not permanent architecture. Once +// fleet telemetry (or "identify" logs) show zero v1 requests for a safe +// observation period, delete this adapter, LegacyAdapter, and the call sites +// in the transports together in one PR — see +// docs/architecture/legacy-response-adapter.md for the exact removal steps. +// --------------------------------------------------------------------------- + +#include + +struct CommandResult; + +// Rewrites `result` into a v1-shaped reply JsonDocument if (and only if) its +// `type` is one this adapter knows how to translate. Returns true and fills +// `out` if a translation was applied; returns false (leaving `out` +// untouched) if the result should be serialised normally — the caller must +// fall back to the standard v2 serialisation in that case. +bool translateLegacyResponse(const CommandResult& result, JsonDocument& out); diff --git a/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp b/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp index 6d6efcc..e597b9d 100644 --- a/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp +++ b/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp @@ -2,6 +2,7 @@ #include "../../CommandBus/CommandBus.hpp" #include "../../CommandBus/CommandEnvelope.hpp" #include "../../CommandBus/CommandResult.hpp" +#include "../../CommandBus/LegacyResponseAdapter.hpp" #include "../../../ConfigManager/ConfigManager.hpp" #define TAG "HTTPTransport" @@ -92,18 +93,26 @@ void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request, envelope.contents.set(doc["contents"]); } + // Capture the ORIGINAL version before CommandBus::dispatch() rewrites + // envelope.version to 2 post-translation (see LegacyAdapter.hpp). HTTP + // defaults unversioned requests to v2 (unlike WS/MQTT/UART, which default + // to v1) — this only fires for a caller that explicitly sends "v":1. + bool isLegacyRequest = (envelope.version == 1); + // Capture request pointer. The reply lambda must call request->send() exactly once. // AsyncWebServer keeps the request alive until we call send() or the connection closes. - envelope.reply = [this, request](const CommandResult& result) { + envelope.reply = [this, request, isLegacyRequest](const CommandResult& result) { JsonDocument resp; - resp["status"] = result.isOk() ? "SUCCESS" - : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); - resp["type"] = result.type; - if (!result.payload.isEmpty()) { - resp["message"] = result.payload; - } - if (result.hasData) { - resp["data"] = result.data; + if (!isLegacyRequest || !translateLegacyResponse(result, resp)) { + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } } String out; serializeJson(resp, out); diff --git a/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp b/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp index 85977f3..7903049 100644 --- a/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp +++ b/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp @@ -2,6 +2,7 @@ #include "../../CommandBus/CommandBus.hpp" #include "../../CommandBus/CommandEnvelope.hpp" #include "../../CommandBus/CommandResult.hpp" +#include "../../CommandBus/LegacyResponseAdapter.hpp" #define TAG "MQTTTransport" #include "../../../Logging/Logging.hpp" @@ -77,17 +78,23 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) { return; } + // Capture the ORIGINAL version before CommandBus::dispatch() rewrites + // envelope.version to 2 post-translation (see LegacyAdapter.hpp). + bool isLegacyRequest = (envelope.version == 1); + // Reply lambda — publishes the response back to the MQTT data topic - envelope.reply = [this](const CommandResult& result) { + envelope.reply = [this, isLegacyRequest](const CommandResult& result) { JsonDocument resp; - resp["status"] = result.isOk() ? "SUCCESS" - : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); - resp["type"] = result.type; - if (!result.payload.isEmpty()) { - resp["message"] = result.payload; - } - if (result.hasData) { - resp["data"] = result.data; + if (!isLegacyRequest || !translateLegacyResponse(result, resp)) { + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } } String out; serializeJson(resp, out); diff --git a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp index b62d48e..a5302f1 100644 --- a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp +++ b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp @@ -2,6 +2,7 @@ #include "../../CommandBus/CommandBus.hpp" #include "../../CommandBus/CommandEnvelope.hpp" #include "../../CommandBus/CommandResult.hpp" +#include "../../CommandBus/LegacyResponseAdapter.hpp" #define TAG "WebSocketTransport" #include "../../../Logging/Logging.hpp" @@ -75,17 +76,23 @@ void WebSocketTransport::onMessage(uint32_t clientId, const JsonDocument& doc) { envelope.contents.set(doc["contents"]); } + // Capture the ORIGINAL version before CommandBus::dispatch() rewrites + // envelope.version to 2 post-translation (see LegacyAdapter.hpp). + bool isLegacyRequest = (envelope.version == 1); + // Reply routes back to the originating WebSocket client only - envelope.reply = [this, clientId](const CommandResult& result) { + envelope.reply = [this, clientId, isLegacyRequest](const CommandResult& result) { JsonDocument resp; - resp["status"] = result.isOk() ? "SUCCESS" - : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); - resp["type"] = result.type; - if (!result.payload.isEmpty()) { - resp["message"] = result.payload; - } - if (result.hasData) { - resp["data"] = result.data; + if (!isLegacyRequest || !translateLegacyResponse(result, resp)) { + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } } String out; serializeJson(resp, out);