# ResponseBuilder ## Summary `ResponseBuilder` is a legacy utility class that serialises responses to JSON strings for direct transmission. It predates the `CommandResult` / `CommandBus` architecture and was the primary response-building mechanism before the Stage 4 comms refactor. Its role has shrunk significantly: new handler code uses `CommandResult` factory methods, and transports serialise `CommandResult` inline. `ResponseBuilder` is still used by `WebSocketDriver` (welcome message on connect, parse error responses) and by some older code paths. It is not on the critical command-dispatch path for any handler. New code should use `CommandResult` instead. --- ## Public API ### Bridge method (preferred for integrating with CommandBus) | Method | Description | |--------|-------------| | `static String fromResult(const CommandResult& result)` | Serialises a `CommandResult` to the standard wire JSON format. Used to convert `CommandResult` objects when a pre-serialised string is needed outside the transport dispatch path. | ### Generic builders | Method | Description | |--------|-------------| | `static String success(const String& type, const String& payload = "")` | `{ "status": "SUCCESS", "type": ..., "payload": ... }` | | `static String success(const String& type, const JsonObject& payload)` | Success with a JSON object payload. | | `static String error(const String& type, const String& message)` | `{ "status": "ERROR", "type": ..., "payload": ... }` | | `static String status(const String& type, const JsonObject& data)` | Alias for `success` with JSON data. | | `static String status(const String& type, const String& data)` | Alias for `success` with string data. | | `static String buildResponse(Status, const String& type, const String& payload)` | Low-level builder. Reuses a static `StaticJsonDocument<512>`. | | `static String buildResponse(Status, const String& type, const JsonObject& payload)` | Low-level builder with JSON payload. | ### Specialised builders | Method | Description | |--------|-------------| | `static String acknowledgment(const String& commandType)` | `success(type, "Command acknowledged")` | | `static String pong()` | `success("pong", "")` | | `static String deviceStatus(PlayerStatus, uint32_t elapsed, uint64_t projected, const uint32_t counters[16])` | Serialises full player status. Uses a `DynamicJsonDocument<1024>`. | | `static String melodyList(const String& fileListJson)` | Wraps a pre-serialised file list. | | `static String downloadResult(bool success, const String& filename)` | Download success/failure response. | | `static String configUpdate(const String& configType)` | Generic config-saved acknowledgment. | ### Error builders | Method | Description | |--------|-------------| | `static String invalidCommand(const String& command)` | `error("invalid_command", "Unknown command: ...")` | | `static String missingParameter(const String& parameter)` | `error("missing_parameter", "Required parameter missing: ...")` | | `static String operationFailed(const String& operation, const String& reason)` | `error(operation, "... failed: ...")` | | `static String deviceBusy()` | `error("device_busy", "Device is currently busy, try again later")` | | `static String unauthorized()` | `error("unauthorized", "Operation not authorized for this client")` | --- ## Response Format `buildResponse()` produces: ```json { "status": "SUCCESS|ERROR|INFO", "type": "command_type", "payload": "..." } ``` `fromResult()` produces: ```json { "status": "SUCCESS|ERROR|INFO", "type": "command_type", "message": "...", "data": { ... } } ``` Note: `buildResponse` uses the key `"payload"` while `fromResult` and all transport reply lambdas use `"message"` and `"data"`. These two formats are not identical. Prefer `fromResult` / `CommandResult` for consistency with the transport layer. --- ## Initialization No initialization required. All methods are static. The static member `_responseDoc` is zero-initialised. --- ## Dependencies - `CommandResult` — used by `fromResult()` - `Player` — `PlayerStatus` enum used by `deviceStatus()` - `ArduinoJson`, `Logging` --- ## Gotchas / Notes - **`_responseDoc` is a shared static.** `buildResponse()` calls `_responseDoc.clear()` before use, but if two calls interleave (e.g. from an ISR or concurrent task), the shared document will be corrupted. All current callers are on the main loop / AsyncWebServer callback thread, so this is not currently a problem. Do not call `ResponseBuilder` methods from FreeRTOS tasks. - **`buildResponse` vs `fromResult` key mismatch.** `buildResponse` uses `"payload"` as the JSON key; `fromResult` (and all transport reply lambdas) use `"message"`. Mixing these in a single client will require handling both keys. Prefer `CommandResult` + transport serialisation for all new code. - **`deviceStatus()` uses `DynamicJsonDocument<1024>`.** This is a heap allocation per call. All other methods use the static `_responseDoc`. For high-frequency status polling, this is a notable allocation hotspot. - **Prefer `CommandResult` for new handlers.** `ResponseBuilder` is retained for backward compatibility with `WebSocketDriver` and any code that needs a pre-serialised string before the bus is involved. For all command handler responses, use `CommandResult::ok()`, `CommandResult::err()`, or `CommandResult::info()`.