/** * ConnectionManager - Manages multiple device connections. * * Supports multiple simultaneous connections with one "active" device. * Routes messages to the active transport and handles lifecycle events. */ import { isInvalidDeviceAddressError } from "@/lib/coreApi"; import type { RpcCall } from "@/lib/crypto/pairing"; import { logger } from "../logger"; import { BluetoothTransport } from "./ble/BluetoothTransport"; import { HybridTransport } from "./hybrid/HybridTransport"; import type { Transport, TransportConfig, DeviceConnection, DeviceEndpointsResult, LearnedBluetoothIdentity, TransportEventHandlers, TransportLink, } from "./types"; import { WebSocketTransport } from "./WebSocketTransport"; export interface ConnectionManagerEventHandlers { /** Called when any connection state changes */ onConnectionChange?: (deviceId: string, connection: DeviceConnection) => void; /** Called when a message is received from any device */ onMessage?: (deviceId: string, event: MessageEvent) => void; /** Called when the active device changes */ onActiveDeviceChange?: (deviceId: string | null) => void; /** Called when a connection error occurs */ onError?: (deviceId: string, error: Error) => void; /** Called when the encrypted handshake is verified for a device. */ onEncryptedHandshakeOk?: (deviceId: string) => void; /** Called when the transport commits to plaintext for a device. */ onPlaintextMode?: (deviceId: string) => void; /** Called when the server requires pairing (-32002, no creds). */ onEncryptionRequired?: (deviceId: string) => void; /** Called when the server returned -32001 (unsupported version). */ onUnsupportedVersion?: (deviceId: string) => void; /** Called when the server doesn't recognise our credentials. */ onCredentialsRevoked?: (deviceId: string) => void; /** Called when the server keeps silently closing the encrypted handshake. */ onEncryptedHandshakeRejected?: (deviceId: string) => void; /** Called with each heartbeat round trip on the device's current link. */ onHeartbeat?: (deviceId: string, rttMs: number) => void; /** Called when a device's link changes between Wi-Fi and Bluetooth. */ onLinkChange?: (deviceId: string, link: TransportLink | null) => void; /** Called when Bluetooth learns how to find a device again. */ onBluetoothIdentity?: ( deviceId: string, identity: LearnedBluetoothIdentity, ) => void; /** Called when a device reports the addresses it can be reached at. */ onEndpoints?: (deviceId: string, endpoints: DeviceEndpointsResult) => void; } export class ConnectionManager { private transports = new Map(); private connections = new Map(); private activeDeviceId: string | null = null; private handlers: ConnectionManagerEventHandlers = {}; private isPaused = false; /** * Set event handlers for connection manager events. */ setEventHandlers(handlers: ConnectionManagerEventHandlers): void { this.handlers = handlers; } /** * Add a new device connection. */ addDevice(config: TransportConfig): Transport { // Remove existing connection with same deviceId if any if (this.transports.has(config.deviceId)) { this.removeDevice(config.deviceId); } logger.log(`[ConnectionManager] Adding device: ${config.deviceId}`); // Create transport based on type const transport = this.createTransport(config); // Initialize connection record const connection: DeviceConnection = { deviceId: config.deviceId, address: config.address, type: config.type, link: null, state: "disconnected", hasData: false, lastDataTimestamp: null, hasConnectedBefore: false, }; // Setup event handlers const transportHandlers: TransportEventHandlers = { onOpen: (address) => { // Keep the route that actually opened so pairing and diagnostics do not // fall back to a stale primary candidate. connection.address = address; this.connections.set(config.deviceId, { ...connection }); logger.debug( `[ConnectionManager] Transport ${config.deviceId} opened at ${address}`, ); }, onClose: () => { // State will be updated by onStateChange }, onError: (error) => { if (isInvalidDeviceAddressError(error)) { logger.warn( `[ConnectionManager] Device ${config.deviceId} invalid address`, error, { category: "connection", action: "device-connect", severity: "warning", deviceId: config.deviceId, }, ); } else { logger.error( `[ConnectionManager] Device ${config.deviceId} error:`, error, { category: "connection", action: "device-connect", severity: "error", deviceId: config.deviceId, }, ); } this.handlers.onError?.(config.deviceId, error); }, onMessage: (event) => { // Mark that we've received data (internal tracking only - don't trigger React re-renders) connection.hasData = true; connection.lastDataTimestamp = Date.now(); this.connections.set(config.deviceId, { ...connection }); this.handlers.onMessage?.(config.deviceId, event); }, onStateChange: (state) => { connection.state = state; // Sync hasConnectedBefore from transport connection.hasConnectedBefore = transport.hasEverConnected; this.connections.set(config.deviceId, { ...connection }); this.handlers.onConnectionChange?.(config.deviceId, { ...connection }); }, onEncryptedHandshakeOk: () => this.handlers.onEncryptedHandshakeOk?.(config.deviceId), onPlaintextMode: () => this.handlers.onPlaintextMode?.(config.deviceId), onEncryptionRequired: () => this.handlers.onEncryptionRequired?.(config.deviceId), onUnsupportedVersion: () => this.handlers.onUnsupportedVersion?.(config.deviceId), onCredentialsRevoked: () => this.handlers.onCredentialsRevoked?.(config.deviceId), onEncryptedHandshakeRejected: () => this.handlers.onEncryptedHandshakeRejected?.(config.deviceId), onHeartbeat: (rttMs) => this.handlers.onHeartbeat?.(config.deviceId, rttMs), onLinkChange: (link) => { connection.link = link; this.handlers.onLinkChange?.(config.deviceId, link); this.handlers.onConnectionChange?.(config.deviceId, { ...connection }); }, onBluetoothIdentity: (identity) => this.handlers.onBluetoothIdentity?.(config.deviceId, identity), onEndpoints: (endpoints) => this.handlers.onEndpoints?.(config.deviceId, endpoints), }; transport.setEventHandlers(transportHandlers); // Store transport and connection this.transports.set(config.deviceId, transport); this.connections.set(config.deviceId, connection); // Connect if not paused if (!this.isPaused) { transport.connect(); } return transport; } /** * Remove a device connection. */ removeDevice(deviceId: string): void { logger.log(`[ConnectionManager] Removing device: ${deviceId}`); const transport = this.transports.get(deviceId); if (transport) { transport.destroy(); this.transports.delete(deviceId); } this.connections.delete(deviceId); // Clear active device if it was removed if (this.activeDeviceId === deviceId) { this.activeDeviceId = null; this.handlers.onActiveDeviceChange?.(null); } } /** * Set the active device for message routing. */ setActiveDevice(deviceId: string | null): void { if (this.activeDeviceId === deviceId) return; if (deviceId && !this.transports.has(deviceId)) { logger.warn( `[ConnectionManager] Cannot set active: device ${deviceId} not found`, ); return; } logger.log(`[ConnectionManager] Active device: ${deviceId}`); this.activeDeviceId = deviceId; this.handlers.onActiveDeviceChange?.(deviceId); } /** * Get the active device ID. */ getActiveDeviceId(): string | null { return this.activeDeviceId; } /** * Get a transport by device ID. */ getTransport(deviceId: string): Transport | undefined { return this.transports.get(deviceId); } /** * Get the active transport. */ getActiveTransport(): Transport | null { return this.activeDeviceId ? (this.transports.get(this.activeDeviceId) ?? null) : null; } /** * Get connection info for a device. */ getConnection(deviceId: string): DeviceConnection | undefined { return this.connections.get(deviceId); } /** * Get the active connection info. */ getActiveConnection(): DeviceConnection | null { return this.activeDeviceId ? (this.connections.get(this.activeDeviceId) ?? null) : null; } /** * Get all connections. */ getAllConnections(): Map { return new Map(this.connections); } /** * Send a message to the active device. */ sendToActive(data: string): void { const transport = this.getActiveTransport(); if (!transport) { logger.warn("[ConnectionManager] Cannot send: no active device"); return; } transport.send(data); } /** * Send a message to a specific device. */ sendToDevice(deviceId: string, data: string): void { const transport = this.transports.get(deviceId); if (!transport) { logger.warn( `[ConnectionManager] Cannot send: device ${deviceId} not found`, ); return; } transport.send(data); } /** * Check if the active device is connected. */ isActiveConnected(): boolean { const transport = this.getActiveTransport(); return transport?.isConnected ?? false; } /** * Pause all connections (used when app goes to background). */ pauseAll(): void { logger.log("[ConnectionManager] Pausing all connections"); this.isPaused = true; this.transports.forEach((transport) => { transport.pauseHeartbeat(); }); } /** * Resume all connections (used when app comes to foreground). */ resumeAll(): void { logger.log("[ConnectionManager] Resuming all connections"); this.isPaused = false; this.transports.forEach((transport) => { if (transport.isConnected) { // Resume heartbeat for connected transports to detect stale connections // (e.g., device went away while app was in background) transport.resumeHeartbeat(); } else { // Try to reconnect disconnected transports transport.immediateReconnect(); } }); } /** * Trigger immediate reconnect on the active device. Ignored while paused * (app backgrounded) - e.g. a network change event must not reopen the * socket in the background; resumeAll() will reconnect on foreground. */ immediateReconnectActive(): void { if (this.isPaused) { logger.debug( "[ConnectionManager] immediateReconnectActive ignored while paused", ); return; } const transport = this.getActiveTransport(); if (transport) { transport.immediateReconnect(); } } /** * Replace the active device's socket, even when it is currently connected. * Used after pairing so an optional plaintext connection immediately reloads * the newly stored credentials. While paused, disconnect now and let * resumeAll() open the replacement socket in the foreground. */ restartActiveConnection(): void { const transport = this.getActiveTransport(); if (!transport) return; transport.disconnect(); if (!this.isPaused) { transport.immediateReconnect(); } } /** * Clear the encryption-blocked state on the active device. Call this after * resolving the encryption issue (e.g. successful pairing) before restarting * the connection so the reconnect actually proceeds. */ clearEncryptionBlockActive(): void { this.getActiveTransport()?.clearEncryptionBlock(); } /** * How to run pairing's JSON-RPC exchange on the active device's own link, * or null when pairing should use Core's HTTP endpoints. */ getActivePairingCall(): RpcCall | null { return this.getActiveTransport()?.pairingCall?.() ?? null; } /** Whether pairing the active device would run over Bluetooth. */ activePairsOverBluetooth(): boolean { return this.getActiveTransport()?.pairsOverBluetooth ?? false; } /** * Destroy all connections and clean up. */ destroy(): void { logger.log("[ConnectionManager] Destroying all connections"); this.transports.forEach((transport) => { transport.destroy(); }); this.transports.clear(); this.connections.clear(); this.activeDeviceId = null; } /** * Create a transport based on config type. */ private createTransport(config: TransportConfig): Transport { switch (config.type) { case "websocket": return new WebSocketTransport({ deviceId: config.deviceId, url: config.address, fallbackUrls: config.fallbackAddresses, pingInterval: 15000, pongTimeout: 10000, reconnectInterval: 2000, maxReconnectInterval: 30000, maxReconnectAttempts: Infinity, pingMessage: "ping", connectionTimeout: 5000, encryption: config.encryption, }); case "bluetooth": return new BluetoothTransport({ deviceId: config.deviceId, identity: config.bluetooth ?? {}, encryption: config.encryption, }); case "hybrid": return new HybridTransport({ deviceId: config.deviceId, wsUrls: [config.address, ...(config.fallbackAddresses ?? [])].filter( (url) => url !== "", ), encryption: config.encryption, bluetooth: config.bluetooth, }); default: throw new Error(`Unknown transport type: ${config.type}`); } } } // Singleton instance export const connectionManager = new ConnectionManager();