# WebSocketDriver ## Summary `WebSocketDriver` is the low-level WebSocket protocol driver. It wraps `AsyncWebSocket` and delegates client lifecycle management (add, remove, type classification, targeted sends, broadcast) to `ClientManager`. When a complete text frame is received, it parses the JSON payload and invokes the registered callback with the client ID and parsed document. `WebSocketTransport` sits on top of this driver and connects it to the `CommandBus`. The driver also sends an unsolicited welcome message to each new client on connect. --- ## Public API | Method | Description | |--------|-------------| | `WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager)` | Constructor. Sets the global `_instance` pointer. | | `void begin()` | Registers the static `onEvent` callback with `AsyncWebSocket`. Does not add the handler to `AsyncWebServer` — that is done by `CommunicationRouter::begin()` via `_server.addHandler(&_webSocket)`. | | `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `WebSocketTransport::begin()`. Signature: `void(uint32_t clientId, const JsonDocument& message)`. | | `void sendToClient(uint32_t clientId, const String& message)` | Sends a message to a specific connected client. Delegates to `ClientManager::sendToClient()`. | | `void broadcastToAll(const String& message)` | Sends to all connected clients via `ClientManager::broadcastToAll()`. | | `void broadcastToMaster(const String& message)` | Sends to clients classified as `MASTER` only. | | `void broadcastToSecondary(const String& message)` | Sends to clients classified as `SECONDARY` only. | | `bool hasClients() const` | True if at least one client is connected. | | `size_t getClientCount() const` | Number of currently connected clients. | --- ## Initialization `CommunicationRouter::begin()`: 1. Calls `_server.addHandler(&_webSocket)` — attaches the WebSocket handler to the HTTP server. 2. Calls `_wsTransport.begin()` — which calls `WebSocketDriver::begin()` to register the event callback. The `AsyncWebServer` is started later by `main.cpp` in the network-connected callback. --- ## Dependencies - `AsyncWebSocket` (ESPAsyncWebServer) — WebSocket protocol layer - `ClientManager` — client registry, type tracking, targeted/broadcast sends - `ResponseBuilder` — used for the welcome message on connect and parse error responses - `ArduinoJson`, `Logging` --- ## Gotchas / Notes - **Singleton pattern via `_instance`.** `AsyncWebSocket::onEvent` is a static C-style callback. The driver routes it through `WebSocketDriver::_instance`. Only one instance should ever be created. - **Only complete single-frame text messages are processed.** The `onData` handler checks `info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT`. Fragmented messages and binary frames are dropped with a warning. - **Per-message heap allocation.** Each incoming message allocates a `char*` buffer via `malloc(len + 1)`. If allocation fails, the client receives a `"memory_error"` response. This is the only dynamic allocation path in the driver. - **JSON parse limit: 2 KB (`StaticJsonDocument<2048>`).** Messages larger than this will fail to parse. The client receives a `"parse_error"` response. - **Client cleanup is external.** The driver calls `_clientManager.cleanupDisconnectedClients()` on each disconnect event, but dead ghost connections (network drop without close frame) are only evicted when `ws.cleanupClients()` is called from `main.cpp` every 2 seconds. - **Welcome message uses `ResponseBuilder`.** The welcome message on connect (`"type": "connection"`) is built with the legacy `ResponseBuilder::success()` path. New code should use `CommandResult` factory methods.