# Annex B: External Interface Specifications

**Document:** SRS Annex B  
**Version:** 1.0  
**Date:** 2025-01-19

## Purpose

This annex defines the external interfaces between the Sensor Hub and external entities (Main Hub, sensors, storage, HMI).

## 1. Main Hub Communication Interface

### 1.1 Protocol Stack

```
Application Layer (Sensor Hub APIs)
    ↓
Transport Security Layer (TLS/DTLS)
    ↓
Network Layer (Wi-Fi / Zigbee / LoRa)
    ↓
Physical Layer
```

### 1.2 Message Format

**Request Message Structure:**
```c
typedef struct {
    uint8_t message_type;      // REQ_DATA, REQ_STATUS, REQ_DIAG, CMD_CONFIG, CMD_OTA
    uint16_t message_id;       // Unique request ID
    uint32_t timestamp;        // Request timestamp
    uint16_t payload_length;   // Payload length in bytes
    uint8_t payload[];         // Message-specific payload
    uint32_t checksum;         // Message integrity checksum
} main_hub_request_t;
```

**Response Message Structure:**
```c
typedef struct {
    uint8_t message_type;      // RESP_DATA, RESP_STATUS, RESP_DIAG, ACK, NACK
    uint16_t message_id;       // Matching request ID
    uint8_t status_code;        // SUCCESS, ERROR, TIMEOUT
    uint32_t timestamp;        // Response timestamp
    uint16_t payload_length;   // Payload length in bytes
    uint8_t payload[];         // Message-specific payload
    uint32_t checksum;         // Message integrity checksum
} main_hub_response_t;
```

### 1.3 Message Types

| Message Type | Direction | Purpose | Payload |
|--------------|-----------|---------|---------|
| `REQ_DATA` | Main Hub → Sensor Hub | Request latest sensor data | None |
| `RESP_DATA` | Sensor Hub → Main Hub | Sensor data response | Sensor data records |
| `REQ_STATUS` | Main Hub → Sensor Hub | Request system status | None |
| `RESP_STATUS` | Sensor Hub → Main Hub | System status response | Status information |
| `REQ_DIAG` | Main Hub → Sensor Hub | Request diagnostic data | Diagnostic filter |
| `RESP_DIAG` | Sensor Hub → Main Hub | Diagnostic data response | Diagnostic events |
| `CMD_CONFIG` | Main Hub → Sensor Hub | Configuration update | Configuration data |
| `CMD_OTA` | Main Hub → Sensor Hub | OTA update request | OTA metadata |
| `ACK` | Sensor Hub → Main Hub | Acknowledgment | None or status |
| `NACK` | Sensor Hub → Main Hub | Negative acknowledgment | Error code |

### 1.4 Communication Requirements

- **Encryption:** All messages SHALL be encrypted using TLS/DTLS
- **Authentication:** All messages SHALL be authenticated
- **Integrity:** All messages SHALL include integrity checksums
- **Timeout:** Request timeout: 5 seconds
- **Retry:** Maximum 3 retries with exponential backoff

## 2. Sensor Interfaces

### 2.1 Supported Protocols

| Protocol | Sensor Types | Interface |
|----------|--------------|-----------|
| I2C | Temperature, Humidity, CO2, NH3, VOC, Light | I2C bus (configurable pins) |
| SPI | Particulate matter sensors | SPI bus (configurable pins) |
| UART | Some sensor modules | UART (configurable pins) |
| Analog | Analog sensors | ADC channels |

### 2.2 Sensor Detection Signal

Each sensor slot SHALL provide a dedicated GPIO pin for presence detection:
- **High (3.3V):** Sensor present
- **Low (0V):** Sensor absent

### 2.3 Sensor Data Format

```c
typedef struct {
    uint8_t sensor_id;          // Unique sensor identifier
    uint8_t sensor_type;        // TEMP, HUM, CO2, NH3, VOC, PM, LIGHT
    float value;                // Filtered sensor value
    uint8_t unit;               // Unit code (C, RH, PPM, LUX, etc.)
    uint64_t timestamp_us;     // Timestamp in microseconds
    uint8_t validity_status;    // VALID, INVALID, DEGRADED, FAILED
    uint8_t sample_count;       // Number of samples used for filtering
} sensor_data_record_t;
```

## 3. Storage Interfaces

### 3.1 SD Card Interface

**File System:** FAT32  
**Mount Point:** `/sdcard`

**Directory Structure:**
```
/sdcard/
  ├── sensor_data/
  │   └── YYYYMMDD_HHMMSS.dat
  ├── diagnostics/
  │   └── diag_log.dat
  ├── machine_constants/
  │   └── mc.dat
  └── ota/
      └── firmware.bin
```

**File Naming Convention:**
- Sensor data: `YYYYMMDD_HHMMSS.dat` (timestamp-based)
- Diagnostics: `diag_log.dat` (circular log)
- Machine constants: `mc.dat` (single file)
- OTA firmware: `firmware.bin` (temporary)

### 3.2 NVM (Non-Volatile Memory) Interface

**Storage Areas:**
- **Machine Constants:** 4KB
- **System Configuration:** 2KB
- **Diagnostic Log (circular):** 8KB
- **OTA Metadata:** 1KB

**Access Method:** ESP-IDF NVS (Non-Volatile Storage) API

## 4. HMI Interfaces

### 4.1 OLED Display Interface

**Protocol:** I2C  
**Address:** Configurable (default: 0x3C)  
**Display:** 128x64 pixels, monochrome

**Display Content:**
- **Main Screen:** Connectivity, System State, Sensor Count, Time/Date
- **Menu Screens:** Diagnostics, Sensors, Health

### 4.2 Button Interface

**Buttons:** 3 GPIO inputs (Up, Down, Select)

**Button Behavior:**
- **Up:** Navigate menu up / Scroll up
- **Down:** Navigate menu down / Scroll down
- **Select:** Enter menu / Select item / Return to main screen

**Debouncing:** Hardware debouncing (10ms) + software debouncing (50ms)

## 5. Debug Interface

### 5.1 Physical Interface

**Protocol:** UART  
**Baud Rate:** 115200  
**Data Bits:** 8  
**Parity:** None  
**Stop Bits:** 1  
**Flow Control:** None

### 5.2 Debug Protocol

**Session Establishment:**
1. Client sends authentication challenge
2. Sensor Hub responds with challenge response
3. Client sends session key (encrypted)
4. Sensor Hub validates and establishes session

**Debug Commands:**
- `READ_DIAG <filter>` - Read diagnostic events
- `READ_STATUS` - Read system status
- `READ_MC` - Read machine constants
- `CLEAR_DIAG` - Clear diagnostic log
- `REBOOT` - Reboot system
- `TEARDOWN` - Initiate controlled teardown

**Security:** All debug sessions SHALL be authenticated. Unauthorized access SHALL be rejected and logged as a security violation.

## 6. Peer Sensor Hub Communication

### 6.1 Protocol

**Protocol:** Same as Main Hub communication (Wi-Fi / Zigbee / LoRa)  
**Message Types:** Limited to connectivity checks and time synchronization

### 6.2 Message Types

| Message Type | Purpose |
|--------------|---------|
| `PEER_PING` | Connectivity check |
| `PEER_PONG` | Connectivity response |
| `PEER_TIME_SYNC` | Time synchronization request |
| `PEER_TIME_RESP` | Time synchronization response |

### 6.3 Requirements

- Peer communication SHALL NOT interfere with Main Hub communication
- Peer communication SHALL be encrypted and authenticated
- Peer communication SHALL be limited to coordination functions only

## 7. Interface Requirements Summary

| Interface | Protocol | Encryption | Authentication | Integrity |
|-----------|----------|------------|----------------|-----------|
| Main Hub | TLS/DTLS over Wi-Fi/Zigbee/LoRa | Yes | Yes | Yes |
| Sensors | I2C/SPI/UART/Analog | No | No | No (hardware-level) |
| SD Card | SPI (SD protocol) | Optional (SWR-SEC-006) | No | Yes (file system) |
| NVM | ESP-IDF NVS | Optional (SWR-SEC-005) | No | Yes (NVS) |
| OLED Display | I2C | No | No | No |
| Buttons | GPIO | No | No | No |
| Debug | UART | Yes | Yes | Yes |
| Peer Sensor Hub | Same as Main Hub | Yes | Yes | Yes |

## 8. Traceability

- **SWR-IF-001:** Main Hub communication interface
- **SWR-IF-002:** Sensor interfaces
- **SWR-IF-003:** OLED display interface
- **SWR-IF-004:** Button input interfaces
- **SWR-IF-005:** Storage interfaces
- **SWR-IF-006:** Debug interface
