/** * WebSocket Client for Eufy Security WebSocket API * * Provides a robust WebSocket connection with automatic reconnection, state management, * and proper message handling. This client handles: * - Connection lifecycle management (connect, disconnect, reconnect) * - Message queuing and timeout handling * - Event-driven architecture for version negotiation and event streaming * - Centralized state management integration * - Error handling and connection recovery * * The client is designed to be used by higher-level API managers and provides * a clean abstraction over the raw WebSocket connection. * * @example Basic Usage * ```typescript * const client = new WebSocketClient("ws://localhost:3000"); * client.onConnected(() => console.log("Connected")); * client.onEventMessage((event) => console.log("Event:", event)); * await client.connect(); * ``` * * @public * @since 1.0.0 */ import { WebSocketCommand, WebSocketEventMessage, WebSocketVersionMessage } from "./websocket-types"; import { ClientStateManager } from "./client-state"; import { Logger, ILogObj } from "tslog"; /** * Represents a message that is pending a response. * Tracks the message ID, command, and other details for pending messages. */ export interface PendingMessage { /** Promise resolver for successful response */ resolve: Function; /** Promise rejector for failed response or timeout */ reject: Function; /** Timeout handle for message expiration */ timeout: NodeJS.Timeout; } /** * WebSocket Client with State Management and Automatic Reconnection * * Core WebSocket client that handles the low-level connection to the eufy-security-ws * container. Provides reliable message delivery, automatic reconnection with exponential * backoff, and proper state management integration. * * Features: * - Automatic reconnection with configurable retry limits * - Message correlation and timeout handling with efficient cleanup * - Event-driven architecture for different message types * - Integration with centralized state management * - Connection state tracking and error handling * - Memory-efficient message processing * * @public * @since 1.0.0 */ export declare class WebSocketClient { private ws; private wsUrl; private pendingMessages; private reconnectTimeout; private maxReconnectAttempts; private messageTimeout; private stateManager; private messageProcessor; private onConnectedHandler?; private onDisconnectedHandler?; private onVersionHandler?; private onEventHandler?; private onErrorHandler?; private logger; private messageCount; private lastMessageTime; /** * Creates a new WebSocket client instance * * @param wsUrl - WebSocket server URL (e.g., 'ws://localhost:3000') * @param stateManager - State manager instance for centralized state tracking * @param logger - Logger instance for logging messages * * @example * ```typescript * const stateManager = new ClientStateManager(logger); * const client = new WebSocketClient("ws://localhost:3000", stateManager, logger); * ``` */ constructor(wsUrl: string, stateManager: ClientStateManager, logger: Logger); /** * Get the current state manager instance * * @returns The ClientStateManager instance used by this client */ getStateManager(): ClientStateManager; /** * Register handler for successful WebSocket connection * Called when the WebSocket connection is established and ready * * @param handler - Callback function to execute on connection */ onConnected(handler: () => void): void; /** * Register handler for WebSocket disconnection * Called when the WebSocket connection is closed or lost * * @param handler - Callback function to execute on disconnection */ onDisconnected(handler: () => void): void; /** * Register handler for version/schema negotiation messages * Called when the server sends version information for API compatibility * * @param handler - Callback function to process version messages */ onVersionMessage(handler: (message: WebSocketVersionMessage) => void): void; /** * Register handler for event messages from the server * Called when the server pushes real-time events (device updates, etc.) * * @param handler - Callback function to process event messages */ onEventMessage(handler: (message: WebSocketEventMessage) => void): void; /** * Register handler for WebSocket errors * Called when connection errors or message parsing errors occur * * @param handler - Callback function to handle errors */ onError(handler: (error: Error) => void): void; /** * Establish WebSocket connection to the server * * Initiates connection to the configured WebSocket URL and sets up all event handlers. * Updates connection state throughout the process and handles connection errors. * * @returns Promise that resolves when connection is established, rejects on failure * @throws Error if connection fails or times out */ connect(): Promise; /** * Gracefully disconnect from WebSocket server * * Closes the WebSocket connection with normal closure code, cancels any pending * reconnection attempts, and cleans up all pending messages and state. */ disconnect(): void; /** * Check if WebSocket is currently connected and ready * * @returns true if WebSocket is connected and ready to send/receive messages */ isConnected(): boolean; /** * Send a command message to the WebSocket server and wait for response * * Sends a command message with correlation ID and waits for the corresponding * response. Handles message timeouts and connection state validation. * * @param message - Command message to send (must include messageId for correlation) * @returns Promise that resolves with the server response or rejects on error/timeout * @throws Error if not connected, message times out, or server returns an error */ sendMessage(message: WebSocketCommand): Promise; /** * Process incoming WebSocket messages based on type * * Routes different message types to appropriate handlers: * - VERSION: Schema negotiation messages * - EVENT: Real-time event notifications * - RESULT/RESPONSE: Command response correlation * * Optimized for performance with early type checking and minimal object creation. * * @param message - Parsed WebSocket message from server * @private */ private handleMessage; /** * Schedule automatic reconnection with exponential backoff * * Implements exponential backoff strategy for reconnection attempts to avoid * overwhelming the server. Respects maximum retry limits and existing reconnection * attempts to prevent multiple concurrent reconnection processes. * * Backoff formula: min(1000 * 2^attempts, 30000) milliseconds + jitter * * @private */ private scheduleReconnect; /** * Clean up all pending message promises on disconnection * * Rejects all pending message promises with connection error and clears * their timeout handlers to prevent memory leaks. Called during disconnection * or connection loss to ensure no promises remain hanging. * * @private */ private clearPendingMessages; /** * Get performance metrics for monitoring and debugging * * @returns Performance metrics object * @public */ getPerformanceMetrics(): { messageCount: number; lastMessageTime: number; pendingMessageCount: number; isConnected: boolean; reconnectAttempts: number; }; /** * Reset performance metrics * * @public */ resetPerformanceMetrics(): void; /** * Get message processing statistics * * @public */ getMessageProcessingStats(): { processedMessages: number; invalidMessages: number; rateLimitedMessages: number; rateLimiter: { messageCount: number; windowStart: number; maxMessages: number; windowMs: number; }; }; } //# sourceMappingURL=websocket-client.d.ts.map