# 1. Communication Architecture

## Overview
The communication architecture for the ASF project is designed to be industrial-grade, ensuring reliability, low latency, and high throughput for critical operations like Over-the-Air (OTA) updates and real-time monitoring.

## Primary & Secondary Communication Stack
The system utilizes a multi-layered communication approach to ensure connectivity even in challenging environments.

| Role | Technology | Why (Industrial Rationale) |
| :--- | :--- | :--- |
| **Primary Uplink** | **Wi-Fi 802.11n (2.4 GHz)** | Leverages existing infrastructure and provides high throughput necessary for OTA updates. |
| **Peer-to-Peer** | **ESP-NOW** | Provides deterministic, low-latency communication without dependency on an Access Point (AP). |
| **Long-range Fallback** | **LoRa (External Module)** | Ensures resilience at farm-scale distances where Wi-Fi may not reach. |

> **Note:** Zigbee on ESP32-S3 is currently not considered industrial-mature in ESP-IDF. ESP-NOW is the preferred choice for reliable peer-to-peer communication.

## Application Protocol
To avoid the pitfalls of raw TCP sockets or unversioned custom protocols, the system adopts **MQTT over TLS 1.2**.

| Item | Decision |
| :--- | :--- |
| **Broker** | Main Hub / Edge Gateway |
| **QoS** | QoS 1 (At least once delivery) |
| **Retain** | Used for configuration topics only |
| **Payload** | CBOR (Binary, versioned for efficiency and compatibility) |
| **Topic Model** | `/farm/{site}/{house}/{node}/...` |

### Why MQTT?
* **Store-and-Forward:** Handles intermittent connectivity gracefully.
* **Built-in Keepalive:** Monitors connection health automatically.
* **Industrial Tooling:** Compatible with standard monitoring and management tools.
* **Native Support:** Stable implementation within the ESP-IDF framework.

## Heartbeat & Liveness
A formalized heartbeat mechanism is implemented to feed into predictive maintenance systems.

* **Interval:** 10 seconds
* **Timeout:** 3 missed heartbeats (30 seconds) triggers an "offline" status.
* **Payload includes:** Uptime, firmware version, free heap memory, RSSI (signal strength), and an error bitmap.
