# Software Feature Specification

## SF-COM: Communication

**Software Feature ID:** SF-COM  
**Mapped System Feature:** F-COM (Communication Features)  
**Version:** 1.0  
**Date:** 2025-02-01  

## 1. Feature Overview

The Communication software feature implements secure, reliable data exchange between the Sensor Hub and external entities including the Main Hub and peer Sensor Hubs. This feature provides the software implementation of MQTT-based Main Hub communication, on-demand data broadcasting, and ESP-NOW peer communication.

### 1.1 Mapped System Features

- **F-COM-01**: Main Hub Communication
- **F-COM-02**: On-Demand Data Broadcasting
- **F-COM-03**: Peer Sensor Hub Communication
- **F-COM-04**: Long-Range Fallback Communication (Optional)

## 2. Static View - Component Architecture

```mermaid
graph TB
    subgraph "Application Layer"
        MHA[Main Hub APIs]
        CM[Communication Manager]
    end
    
    subgraph "Protocol Layer"
        MQTT[MQTT Client]
        ESPNOW[ESP-NOW Handler]
        TLS[TLS/mTLS Handler]
    end
    
    subgraph "Network Layer"
        WIFI[WiFi Stack]
        NET[Network Stack]
    end
    
    subgraph "Hardware Abstraction"
        RADIO[Radio Hardware]
    end
    
    MHA --> CM
    CM --> MQTT
    CM --> ESPNOW
    MQTT --> TLS
    TLS --> NET
    ESPNOW --> WIFI
    NET --> WIFI
    WIFI --> RADIO
```

### 2.1 Component Interfaces

#### 2.1.1 Communication Manager Interfaces

**Provided Interfaces:**
- `ICommunicationManager`: Main communication interface
- `IMessageHandler`: Message processing interface
- `IConnectionStatus`: Connection monitoring interface

**Required Interfaces:**
- `IMQTTClient`: MQTT communication interface
- `IESPNOWHandler`: ESP-NOW communication interface
- `IDataPool`: Data access interface
- `IEventSystem`: Event notification interface

#### 2.1.2 Protocol Layer Interfaces

**Provided Interfaces:**
- `IMQTTClient`: MQTT client interface
- `IESPNOWHandler`: ESP-NOW handler interface
- `ITLSHandler`: TLS/mTLS security interface

**Required Interfaces:**
- `INetworkStack`: Network layer interface
- `IWiFiStack`: WiFi layer interface

## 3. Dynamic View - Communication Sequences

### 3.1 Main Hub Communication Sequence

```mermaid
sequenceDiagram
    participant SM as Sensor Manager
    participant CM as Communication Manager
    participant MQTT as MQTT Client
    participant TLS as TLS Handler
    participant MH as Main Hub
    
    SM->>CM: publishSensorData(data)
    CM->>CM: formatMessage(data)
    CM->>MQTT: publish(topic, payload)
    MQTT->>TLS: sendSecure(message)
    TLS->>MH: encrypted_message
    
    MH->>TLS: command_request
    TLS->>MQTT: receive(message)
    MQTT->>CM: onMessageReceived(topic, payload)
    CM->>CM: processCommand(payload)
    CM->>SM: executeCommand(command)
```

### 3.2 On-Demand Data Request Sequence

```mermaid
sequenceDiagram
    participant MH as Main Hub
    participant CM as Communication Manager
    participant DP as Data Pool
    participant MQTT as MQTT Client
    
    MH->>MQTT: request_data(node_id)
    MQTT->>CM: onDataRequest(node_id)
    CM->>DP: getLatestSensorData()
    DP-->>CM: sensor_data
    CM->>CM: formatResponse(sensor_data)
    CM->>MQTT: publish(response_topic, data)
    MQTT->>MH: sensor_data_response
    
    Note over CM,MH: Response time < 100ms
```

### 3.3 ESP-NOW Peer Communication Sequence

```mermaid
sequenceDiagram
    participant P1 as Peer Hub 1
    participant EN1 as ESP-NOW Handler 1
    participant EN2 as ESP-NOW Handler 2
    participant P2 as Peer Hub 2
    
    P1->>EN1: sendPeerMessage(PING, peer_id)
    EN1->>EN1: encrypt(message)
    EN1->>EN2: ESP-NOW transmission
    EN2->>EN2: decrypt(message)
    EN2->>P2: onPeerMessage(PING, sender_id)
    P2->>EN2: sendPeerMessage(PONG, sender_id)
    EN2->>EN1: ESP-NOW transmission
    EN1->>P1: onPeerMessage(PONG, peer_id)
```

## 4. Software Constraints

### 4.1 Performance Constraints
- **SWC-COM-001**: On-demand data response must be transmitted within 100ms
- **SWC-COM-002**: MQTT message processing must not block sensor acquisition
- **SWC-COM-003**: ESP-NOW peer communication latency must be < 10ms

### 4.2 Resource Constraints
- **SWC-COM-004**: Maximum MQTT message size limited to 8KB
- **SWC-COM-005**: Maximum 20 ESP-NOW peer connections supported
- **SWC-COM-006**: Communication buffers limited to 16KB total

### 4.3 Security Constraints
- **SWC-COM-007**: All MQTT communication must use TLS 1.2 or higher
- **SWC-COM-008**: ESP-NOW messages must use application-layer AES-128 encryption
- **SWC-COM-009**: Certificate validation must be enforced for mTLS connections

### 4.4 Reliability Constraints
- **SWC-COM-010**: Communication failures must not affect sensor data acquisition
- **SWC-COM-011**: Automatic reconnection with exponential backoff required
- **SWC-COM-012**: Message delivery must use QoS 1 (at least once) for critical data

## 5. Traceability Matrix - Software Requirements

| Software Requirement ID | Feature Mapping | Component | Verification Method |
|-------------------------|-----------------|-----------|-------------------|
| SWR-COM-001 | F-COM-01 | Communication Manager | Integration Test |
| SWR-COM-002 | F-COM-01 | MQTT Client | Unit Test |
| SWR-COM-003 | F-COM-01 | Communication Manager | Integration Test |
| SWR-COM-004 | F-COM-01 | Communication Manager | Unit Test |
| SWR-COM-005 | F-COM-02 | Communication Manager | Performance Test |
| SWR-COM-006 | F-COM-02 | Communication Manager | Integration Test |
| SWR-COM-007 | F-COM-02 | Data Pool | Unit Test |
| SWR-COM-008 | F-COM-03 | ESP-NOW Handler | Unit Test |
| SWR-COM-009 | F-COM-03 | ESP-NOW Handler | Integration Test |
| SWR-COM-010 | F-COM-03 | Communication Manager | Unit Test |
| SWR-COM-011 | F-COM-01 | Communication Manager | Unit Test |
| SWR-COM-012 | F-COM-01 | MQTT Client | Unit Test |
| SWR-COM-013 | F-COM-01 | Communication Manager | Integration Test |
| SWR-COM-014 | F-COM-03 | ESP-NOW Handler | Security Test |
| SWR-COM-015 | F-COM-03 | ESP-NOW Handler | Unit Test |
| SWR-COM-016 | F-COM-04 | Communication Manager | Integration Test |
| SWR-COM-017 | F-COM-04 | Communication Manager | Unit Test |

## 6. Implementation Notes

### 6.1 MQTT Configuration
- Broker compatibility: Mosquitto 2.x, HiveMQ
- Topic structure: `/farm/{site_id}/{house_id}/{node_id}/{message_type}`
- Payload encoding: CBOR for efficiency and versioning
- Keepalive: 60 seconds with 30-second timeout detection

### 6.2 Security Implementation
- mTLS with device-unique X.509 certificates
- Private keys stored in encrypted flash or eFuse
- ESP-NOW application-layer encryption using AES-128
- Certificate size optimization for ESP32-S3 constraints

### 6.3 Error Handling
- Connection failures trigger diagnostic events
- Automatic reconnection with exponential backoff (1s, 2s, 4s, max 60s)
- Message queuing during disconnection periods
- Peer communication isolation from main hub operations

### 6.4 Data Flow
- Sensor data flows from Data Pool to Communication Manager
- Commands flow from Main Hub through Communication Manager to target components
- Peer messages are processed independently of main hub communication
- Heartbeat mechanism maintains connection health monitoring