# ClientManager ## Summary `ClientManager` tracks all active WebSocket clients and their assigned device roles. It exists because the Vesper WebSocket API distinguishes between **master** clients (primary control apps) and **secondary** clients (auxiliary devices), and different subsystems need to send targeted responses rather than indiscriminate broadcasts. The class owns the client registry and exposes send primitives that `WebSocketDriver` delegates to; it does not interact with the network stack directly. --- ## Public API ### Client Lifecycle | Method | Description | |---|---| | `addClient(client, deviceType)` | Registers a new WebSocket client, defaulting to `UNKNOWN` type until identified. | | `removeClient(clientId)` | Erases a client from the registry by its WebSocket ID. | | `updateClientType(clientId, deviceType)` | Promotes a client from `UNKNOWN` to `MASTER` or `SECONDARY` after the `system.identify` handshake. | | `updateClientLastSeen(clientId)` | Stamps the client's `lastSeen` field with the current `millis()`. Called on every received message and every outbound send. | | `cleanupDisconnectedClients()` | Iterates the registry and removes entries whose underlying `AsyncWebSocketClient` is no longer in `WS_CONNECTED` state. | ### Client Queries | Method | Description | |---|---| | `hasClients()` | Returns `true` if the registry is non-empty. | | `getClientCount()` | Returns the number of entries currently in the registry. | | `isClientConnected(clientId)` | Returns `true` if the client is registered and its socket reports `WS_CONNECTED`. | | `getClientType(clientId)` | Returns the `DeviceType` of the client, or `UNKNOWN` if not found. | | `getClientInfo(clientId)` | Returns a raw pointer to the `ClientInfo` struct, or `nullptr` if not found. | | `getClientListJson()` | Serializes the current client registry to a JSON string (`{"clients":[...]}`). | ### Messaging | Method | Description | |---|---| | `sendToClient(clientId, message)` | Sends a text message to a single client; returns `false` if the client is absent or disconnected. | | `sendToMasterClients(message)` | Sends to all clients whose type is `MASTER`. | | `sendToSecondaryClients(message)` | Sends to all clients whose type is `SECONDARY`. | | `broadcastToAll(message)` | Sends to every client that passes the `isValidClient` check, regardless of type. | --- ## Initialization `ClientManager` has no `begin()` method and no hardware dependencies. It is constructed at global scope inside `CommunicationRouter` (which owns a `ClientManager` member). `CommunicationRouter` passes the instance by reference into `WebSocketDriver` and `SystemHandler` at construction time. The relevant initialization chain in `main.cpp`: ``` CommunicationRouter communication(...); // constructs ClientManager internally communication.begin(); // constructs WebSocketDriver and SystemHandler, // both receive ClientManager& at this point ``` No explicit ordering constraint beyond `CommunicationRouter::begin()` being called after the `AsyncWebServer` and `AsyncWebSocket` objects exist. --- ## Dependencies | Dependency | Role | |---|---| | `ESPAsyncWebServer` (`AsyncWebSocket`, `AsyncWebSocketClient`) | Provides the socket handle and connection status via `client->status()`. | | `ArduinoJson` | Used only in `getClientListJson()` to serialize the registry. | | `Logging` | All lifecycle events and send results are logged at `INFO` or `DEBUG` level. | `ClientManager` has no dependency on `ConfigManager`, `MQTT`, `SD`, or any hardware peripheral. --- ## Gotchas / Notes **No FreeRTOS task.** `ClientManager` is purely synchronous. All methods execute in the caller's context. `WebSocketDriver` event callbacks fire in the `AsyncTCP` task (Core 0); the `SystemHandler` `system.identify` handler runs in whatever task dispatches `CommandBus`. If both paths mutate `_clients` concurrently there is a potential race on the `std::map`. In practice, the async event task and the command dispatch path currently share Core 0, reducing (but not eliminating) the risk. There is no mutex guarding `_clients`. **`isValidClient` is the source of truth for liveness.** The `isConnected` flag inside `ClientInfo` is set to `false` only during `cleanupDisconnectedClients()` and is otherwise not authoritative — actual connectivity is determined by `client->status() == WS_CONNECTED`. Do not rely on `ClientInfo::isConnected` alone. **`cleanupDisconnectedClients()` must be called externally.** The class does not self-clean. `WebSocketDriver::onDisconnect()` calls it after every disconnect event. The `main.cpp` loop also calls `ws.cleanupClients()` every 2 seconds at the `AsyncWebSocket` level, which is a separate mechanism. **Client type identification requires a handshake.** Clients connect as `UNKNOWN`. The app must send a `system.identify` command to be promoted: ```json { "v": 2, "cmd": "system.identify", "contents": { "device_type": "master" } } ``` `SystemHandler` calls `updateClientType()` upon receiving this command. Until then, `sendToMasterClients` and `sendToSecondaryClients` will not reach the client. **Maximum client capacity is not enforced.** The header comment mentions "up to 5 total devices" but there is no enforcement in the code. The `std::map` will grow without bound if clients connect without disconnecting. **`getClientListJson()` uses a fixed `StaticJsonDocument<512>`.** With the current 5-client design intent this is sufficient, but it will silently truncate if a large number of clients are present.