# Communication Manager Component Specification **Component ID:** C-COM-001 **Component Name:** Communication Manager **Version:** 1.0 **Date:** 2025-02-01 ## 1. Component Overview ### 1.1 Purpose The Communication Manager is responsible for managing all external communication interfaces including MQTT-based Main Hub communication, ESP-NOW peer communication, and long-range fallback communication. It provides a unified interface for all communication protocols and handles connection management, message routing, and protocol-specific operations. ### 1.2 Scope - MQTT over TLS communication with Main Hub - ESP-NOW peer-to-peer communication - Message formatting and encoding (CBOR) - Connection management and health monitoring - Communication protocol abstraction ### 1.3 Responsibilities - Establish and maintain secure connections with Main Hub - Handle MQTT message publishing and subscription - Manage ESP-NOW peer communication - Implement heartbeat and keepalive mechanisms - Provide communication status monitoring - Handle automatic reconnection with exponential backoff - Route messages between internal components and external entities ## 2. Component Architecture ### 2.1 Static View ```mermaid graph TB subgraph "Communication Manager" CM[Communication Controller] MH[MQTT Handler] EN[ESP-NOW Handler] MF[Message Formatter] CS[Connection Supervisor] end subgraph "External Interfaces" MQTT[MQTT Broker] PEER[Peer Hubs] end subgraph "Internal Components" SM[Sensor Manager] DP[Data Pool] DIAG[Diagnostics Manager] end CM --> MH CM --> EN CM --> MF CM --> CS MH --> MQTT EN --> PEER SM --> CM DP --> CM DIAG --> CM ``` ### 2.2 Internal Components #### 2.2.1 Communication Controller - Central coordination of all communication activities - Message routing and protocol selection - Communication policy enforcement #### 2.2.2 MQTT Handler - MQTT client implementation - TLS session management - Topic subscription and message publishing - QoS handling and message acknowledgment #### 2.2.3 ESP-NOW Handler - ESP-NOW protocol implementation - Peer discovery and management - Message encryption and decryption - Acknowledgment and retry mechanisms #### 2.2.4 Message Formatter - CBOR encoding and decoding - Message versioning and schema validation - Payload compression and optimization #### 2.2.5 Connection Supervisor - Connection health monitoring - Automatic reconnection logic - Network status tracking - Communication diagnostics ## 3. Interfaces ### 3.1 Provided Interfaces #### 3.1.1 ICommunicationManager ```cpp class ICommunicationManager { public: virtual ~ICommunicationManager() = default; // Connection Management virtual Result initialize(const CommunicationConfig& config) = 0; virtual Result connect() = 0; virtual Result disconnect() = 0; virtual ConnectionStatus getConnectionStatus() const = 0; // Message Operations virtual Result publishSensorData(const SensorDataMessage& data) = 0; virtual Result publishDiagnostic(const DiagnosticMessage& diag) = 0; virtual Result publishHeartbeat(const HeartbeatMessage& heartbeat) = 0; virtual Result sendPeerMessage(const PeerMessage& message, NodeId peer) = 0; // Subscription Management virtual Result subscribeToCommands(ICommandHandler* handler) = 0; virtual Result subscribeToOTAUpdates(IOTAHandler* handler) = 0; virtual Result subscribeToPeerMessages(IPeerMessageHandler* handler) = 0; // Status and Control virtual CommunicationStats getStatistics() const = 0; virtual Result resetConnection() = 0; }; ``` #### 3.1.2 IMessageHandler ```cpp class IMessageHandler { public: virtual ~IMessageHandler() = default; virtual Result handleIncomingMessage(const Message& message) = 0; virtual Result handleConnectionEvent(ConnectionEvent event) = 0; }; ``` #### 3.1.3 IConnectionStatus ```cpp class IConnectionStatus { public: virtual ~IConnectionStatus() = default; virtual bool isConnected() const = 0; virtual int getSignalStrength() const = 0; virtual std::chrono::milliseconds getLatency() const = 0; virtual uint32_t getMessagesSent() const = 0; virtual uint32_t getMessagesReceived() const = 0; }; ``` ### 3.2 Required Interfaces #### 3.2.1 ITLSManager - TLS session establishment and management - Certificate validation and management - Secure communication channel setup #### 3.2.2 INetworkStack - Low-level network operations - Wi-Fi connection management - Network status monitoring #### 3.2.3 IDataPool - Access to sensor data for transmission - Retrieval of latest sensor values - Data validity checking #### 3.2.4 IEventSystem - Event publication for communication events - Event subscription for system events - Asynchronous notification handling #### 3.2.5 IDiagnosticsManager - Diagnostic event reporting - Communication error logging - Performance metrics reporting ## 4. Dynamic View ### 4.1 MQTT Communication Sequence ```mermaid sequenceDiagram participant SM as Sensor Manager participant CM as Communication Manager participant MH as MQTT Handler participant TLS as TLS Manager participant BROKER as MQTT Broker SM->>CM: publishSensorData(data) CM->>CM: formatMessage(data) CM->>MH: publish(topic, payload) MH->>TLS: sendSecure(message) TLS->>BROKER: encrypted_message BROKER-->>TLS: ack TLS-->>MH: send_result MH-->>CM: publish_result CM-->>SM: operation_result ``` ### 4.2 Connection Management Sequence ```mermaid sequenceDiagram participant CS as Connection Supervisor participant MH as MQTT Handler participant TLS as TLS Manager participant DIAG as Diagnostics Manager CS->>CS: monitorConnection() CS->>MH: checkConnectionHealth() MH-->>CS: connection_status alt Connection Lost CS->>DIAG: reportConnectionLoss() CS->>CS: startReconnectionTimer() CS->>MH: reconnect() MH->>TLS: establishConnection() TLS-->>MH: connection_result MH-->>CS: reconnection_result end ``` ## 5. Configuration ### 5.1 Communication Configuration ```cpp struct CommunicationConfig { // MQTT Configuration std::string mqtt_broker_url; uint16_t mqtt_port; std::string mqtt_client_id; std::string mqtt_username; std::string mqtt_password; uint16_t mqtt_keepalive_seconds; uint8_t mqtt_qos_level; // ESP-NOW Configuration bool espnow_enabled; uint8_t espnow_channel; std::vector espnow_peers; // TLS Configuration std::string ca_certificate; std::string client_certificate; std::string client_private_key; // Timing Configuration uint32_t heartbeat_interval_ms; uint32_t reconnection_timeout_ms; uint32_t message_timeout_ms; }; ``` ### 5.2 Topic Structure ```cpp namespace Topics { constexpr const char* SENSOR_DATA = "/farm/{site_id}/{house_id}/{node_id}/data/{sensor_id}"; constexpr const char* HEARTBEAT = "/farm/{site_id}/{house_id}/{node_id}/status/heartbeat"; constexpr const char* SYSTEM_STATUS = "/farm/{site_id}/{house_id}/{node_id}/status/system"; constexpr const char* COMMANDS = "/farm/{site_id}/{house_id}/{node_id}/cmd/{command_type}"; constexpr const char* DIAGNOSTICS = "/farm/{site_id}/{house_id}/{node_id}/diag/{severity}"; constexpr const char* OTA = "/farm/{site_id}/{house_id}/{node_id}/ota/{action}"; } ``` ## 6. State Management ### 6.1 Communication States ```cpp enum class CommunicationState { DISCONNECTED, CONNECTING, CONNECTED, RECONNECTING, ERROR, DISABLED }; ``` ### 6.2 State Transitions - DISCONNECTED → CONNECTING: Connection initiation - CONNECTING → CONNECTED: Successful connection establishment - CONNECTED → RECONNECTING: Connection loss detected - RECONNECTING → CONNECTED: Successful reconnection - Any State → ERROR: Critical communication error - Any State → DISABLED: System shutdown or disable command ## 7. Error Handling ### 7.1 Error Categories - **Connection Errors**: Network connectivity issues, broker unavailability - **Authentication Errors**: Certificate validation failures, credential issues - **Protocol Errors**: MQTT protocol violations, message format errors - **Timeout Errors**: Message delivery timeouts, keepalive failures - **Resource Errors**: Memory allocation failures, buffer overflows ### 7.2 Error Recovery Strategies - **Automatic Reconnection**: Exponential backoff with maximum retry limit - **Message Queuing**: Store messages during disconnection periods - **Graceful Degradation**: Continue operation with reduced functionality - **Diagnostic Reporting**: Log all communication errors for analysis ## 8. Performance Characteristics ### 8.1 Timing Requirements - **Message Latency**: < 100ms for on-demand data requests - **Heartbeat Interval**: 10 seconds (configurable) - **Reconnection Time**: < 30 seconds with exponential backoff - **Message Throughput**: > 100 messages/minute ### 8.2 Resource Usage - **Memory**: < 32KB for communication buffers - **CPU**: < 5% average utilization - **Network**: Adaptive based on message frequency and size ## 9. Security Considerations ### 9.1 Communication Security - All MQTT communication encrypted with TLS 1.2 - Device authentication using X.509 certificates - ESP-NOW messages encrypted with AES-128 - Message integrity verification ### 9.2 Access Control - Topic-based access control via broker configuration - Peer authentication for ESP-NOW communication - Command validation and authorization ## 10. Testing Strategy ### 10.1 Unit Tests - Message formatting and parsing - Connection state management - Error handling and recovery - Configuration validation ### 10.2 Integration Tests - End-to-end message delivery - TLS session establishment - ESP-NOW peer communication - Broker interaction testing ### 10.3 Performance Tests - Message throughput and latency - Connection stability under load - Memory usage profiling - Network efficiency analysis ## 11. Dependencies ### 11.1 Internal Dependencies - TLS Manager for secure communication - Event System for asynchronous notifications - Data Pool for sensor data access - Diagnostics Manager for error reporting ### 11.2 External Dependencies - ESP-IDF MQTT client library - ESP-IDF ESP-NOW library - mbedTLS for cryptographic operations - CBOR encoding/decoding library ## 12. Constraints and Assumptions ### 12.1 Constraints - Maximum message size: 8KB - Maximum concurrent connections: 1 MQTT + 20 ESP-NOW peers - Network latency: < 1000ms for reliable operation - Memory usage: Bounded and deterministic ### 12.2 Assumptions - Reliable network connectivity for MQTT communication - Proper broker configuration and availability - Valid certificates and credentials provisioned - Sufficient system resources for communication operations