# Interface Definitions
# ASF Sensor Hub (Sub-Hub) Software Interfaces

**Document ID:** ICD-ASF-SensorHub-SW-001  
**Version:** 1.0  
**Date:** 2025-02-01  
**Standard:** ISO/IEC/IEEE 29148:2018  
**Scope:** Software Interface Definitions for ASF Sensor Hub

## 1. Introduction

### 1.1 Purpose

This document defines all software interfaces for the ASF Sensor Hub embedded system. It provides detailed specifications for external interfaces (hardware, communication) and internal interfaces (component-to-component) to ensure consistent implementation and integration.

### 1.2 Scope

This document covers:
- **External Interfaces:** Hardware sensors, communication protocols, storage devices, user interfaces
- **Internal Interfaces:** Component APIs, event system, data structures
- **Data Formats:** Message structures, persistent data formats, configuration schemas
- **Protocol Specifications:** Communication protocols, state machine interfaces

### 1.3 Interface Categories

| Category | Description | Examples |
|----------|-------------|----------|
| **Hardware Interfaces** | Physical device interfaces | I2C sensors, GPIO buttons, SD card |
| **Communication Interfaces** | Network and peer communication | MQTT/TLS, ESP-NOW, diagnostic protocols |
| **Component Interfaces** | Internal software APIs | Event System, Data Pool, State Manager |
| **Data Interfaces** | Data structures and formats | Sensor records, diagnostic events, configuration |
| **Storage Interfaces** | Persistent storage access | SD card files, NVM data, configuration storage |

## 2. External Interfaces

### 2.1 Hardware Interfaces

#### 2.1.1 Sensor Interfaces

**I2C Sensor Interface**
```c
// I2C Sensor Interface Definition
typedef struct {
    uint8_t device_address;     // I2C device address (7-bit)
    uint32_t clock_speed;       // Clock speed in Hz (100kHz, 400kHz)
    uint8_t register_width;     // Register address width (8 or 16 bits)
    bool use_repeated_start;    // Use repeated start condition
} i2c_sensor_config_t;

// Standard I2C operations
esp_err_t i2c_sensor_init(uint8_t sensor_id, const i2c_sensor_config_t* config);
esp_err_t i2c_sensor_read_register(uint8_t sensor_id, uint16_t reg_addr, uint8_t* data, size_t len);
esp_err_t i2c_sensor_write_register(uint8_t sensor_id, uint16_t reg_addr, const uint8_t* data, size_t len);
esp_err_t i2c_sensor_detect_presence(uint8_t sensor_id, bool* present);
```

**SPI Sensor Interface**
```c
// SPI Sensor Interface Definition
typedef struct {
    uint32_t clock_speed;       // SPI clock speed in Hz
    uint8_t mode;              // SPI mode (0-3)
    uint8_t bit_order;         // MSB_FIRST or LSB_FIRST
    uint8_t cs_pin;            // Chip select GPIO pin
    bool cs_active_low;        // CS polarity
} spi_sensor_config_t;

// Standard SPI operations
esp_err_t spi_sensor_init(uint8_t sensor_id, const spi_sensor_config_t* config);
esp_err_t spi_sensor_transfer(uint8_t sensor_id, const uint8_t* tx_data, uint8_t* rx_data, size_t len);
esp_err_t spi_sensor_detect_presence(uint8_t sensor_id, bool* present);
```

**UART Sensor Interface**
```c
// UART Sensor Interface Definition
typedef struct {
    uint32_t baud_rate;        // Baud rate (9600, 19200, 38400, 115200)
    uint8_t data_bits;         // Data bits (7, 8)
    uint8_t parity;            // Parity (NONE, EVEN, ODD)
    uint8_t stop_bits;         // Stop bits (1, 2)
    uint8_t flow_control;      // Flow control (NONE, RTS_CTS)
    uint16_t rx_timeout_ms;    // Receive timeout in milliseconds
} uart_sensor_config_t;

// Standard UART operations
esp_err_t uart_sensor_init(uint8_t sensor_id, const uart_sensor_config_t* config);
esp_err_t uart_sensor_send_command(uint8_t sensor_id, const uint8_t* cmd, size_t cmd_len);
esp_err_t uart_sensor_read_response(uint8_t sensor_id, uint8_t* response, size_t max_len, size_t* actual_len);
esp_err_t uart_sensor_detect_presence(uint8_t sensor_id, bool* present);
```

**Analog Sensor Interface**
```c
// ADC Sensor Interface Definition
typedef struct {
    uint8_t adc_channel;       // ADC channel number
    uint32_t sample_rate;      // Sampling rate in Hz
    uint8_t resolution;        // ADC resolution (12-bit for ESP32-S3)
    uint32_t reference_voltage; // Reference voltage in mV
    bool enable_filter;        // Enable hardware filter
} adc_sensor_config_t;

// Standard ADC operations
esp_err_t adc_sensor_init(uint8_t sensor_id, const adc_sensor_config_t* config);
esp_err_t adc_sensor_read_raw(uint8_t sensor_id, uint32_t* raw_value);
esp_err_t adc_sensor_read_voltage(uint8_t sensor_id, uint32_t* voltage_mv);
esp_err_t adc_sensor_detect_presence(uint8_t sensor_id, bool* present);
```

#### 2.1.2 User Interface Hardware

**OLED Display Interface**
```c
// OLED Display Configuration
typedef struct {
    uint8_t i2c_address;       // I2C address (typically 0x3C or 0x3D)
    uint16_t width;            // Display width in pixels (128)
    uint16_t height;           // Display height in pixels (64)
    bool flip_horizontal;      // Flip display horizontally
    bool flip_vertical;        // Flip display vertically
} oled_config_t;

// OLED Display Operations
esp_err_t oled_init(const oled_config_t* config);
esp_err_t oled_clear_screen(void);
esp_err_t oled_set_cursor(uint8_t x, uint8_t y);
esp_err_t oled_write_text(const char* text, uint8_t font_size);
esp_err_t oled_draw_bitmap(uint8_t x, uint8_t y, const uint8_t* bitmap, uint8_t width, uint8_t height);
esp_err_t oled_update_display(void);
```

**Button Interface**
```c
// Button Configuration
typedef enum {
    BUTTON_UP = 0,
    BUTTON_DOWN = 1,
    BUTTON_SELECT = 2,
    BUTTON_COUNT = 3
} button_id_t;

typedef struct {
    uint8_t gpio_pin;          // GPIO pin number
    bool active_low;           // Button active low or high
    uint32_t debounce_ms;      // Debounce time in milliseconds
    uint32_t repeat_delay_ms;  // Initial repeat delay
    uint32_t repeat_rate_ms;   // Repeat rate
} button_config_t;

// Button Operations
esp_err_t button_init(button_id_t button, const button_config_t* config);
esp_err_t button_register_callback(button_id_t button, void (*callback)(button_id_t, bool pressed));
bool button_is_pressed(button_id_t button);
```

#### 2.1.3 Storage Interfaces

**SD Card Interface**
```c
// SD Card Configuration
typedef struct {
    uint8_t spi_host;          // SPI host (SPI2_HOST, SPI3_HOST)
    uint8_t cs_pin;            // Chip select pin
    uint32_t max_frequency;    // Maximum SPI frequency
    bool format_if_mount_failed; // Format if mount fails
} sdcard_config_t;

// SD Card Operations
esp_err_t sdcard_init(const sdcard_config_t* config);
esp_err_t sdcard_mount(const char* mount_point);
esp_err_t sdcard_unmount(void);
esp_err_t sdcard_get_info(uint64_t* total_bytes, uint64_t* free_bytes);
bool sdcard_is_mounted(void);
```

**NVM Interface**
```c
// NVM (Non-Volatile Memory) Operations
esp_err_t nvm_init(void);
esp_err_t nvm_write_blob(const char* namespace, const char* key, const void* data, size_t length);
esp_err_t nvm_read_blob(const char* namespace, const char* key, void* data, size_t* length);
esp_err_t nvm_erase_key(const char* namespace, const char* key);
esp_err_t nvm_erase_namespace(const char* namespace);
```

### 2.2 Communication Interfaces

#### 2.2.1 Main Hub Communication Interface

**MQTT over TLS Configuration**
```c
// MQTT Configuration
typedef struct {
    char broker_uri[256];      // MQTT broker URI (mqtts://...)
    char client_id[64];        // Unique client identifier
    char username[64];         // MQTT username (optional)
    char password[64];         // MQTT password (optional)
    uint16_t keepalive;        // Keepalive interval in seconds
    uint8_t qos_level;         // QoS level (0, 1, 2)
    bool clean_session;        // Clean session flag
    uint32_t reconnect_timeout_ms; // Reconnection timeout
} mqtt_config_t;

// TLS Configuration
typedef struct {
    const char* ca_cert_pem;   // CA certificate in PEM format
    const char* client_cert_pem; // Client certificate in PEM format
    const char* client_key_pem;  // Client private key in PEM format
    bool verify_peer;          // Verify peer certificate
    bool verify_hostname;      // Verify hostname
} tls_config_t;

// MQTT Operations
esp_err_t mqtt_init(const mqtt_config_t* mqtt_config, const tls_config_t* tls_config);
esp_err_t mqtt_connect(void);
esp_err_t mqtt_disconnect(void);
esp_err_t mqtt_publish(const char* topic, const void* payload, size_t payload_len, uint8_t qos, bool retain);
esp_err_t mqtt_subscribe(const char* topic, uint8_t qos);
esp_err_t mqtt_unsubscribe(const char* topic);
bool mqtt_is_connected(void);
```

**MQTT Topic Structure**
```
/farm/{site_id}/{house_id}/{node_id}/data/{sensor_type}     - Sensor data
/farm/{site_id}/{house_id}/{node_id}/status/heartbeat       - Heartbeat messages
/farm/{site_id}/{house_id}/{node_id}/status/system          - System status
/farm/{site_id}/{house_id}/{node_id}/diag/{severity}        - Diagnostic events
/farm/{site_id}/{house_id}/{node_id}/cmd/{command_type}     - Commands from Main Hub
/farm/{site_id}/{house_id}/{node_id}/ota/{action}           - OTA update messages
```

**CBOR Message Format**
```c
// CBOR Message Header
typedef struct {
    uint16_t message_type;     // Message type identifier
    uint16_t version;          // Message format version
    uint32_t timestamp;        // Unix timestamp
    uint32_t sequence_number;  // Message sequence number
    uint16_t payload_length;   // Payload length in bytes
    uint16_t checksum;         // Message checksum
} __attribute__((packed)) cbor_header_t;

// Sensor Data Message (CBOR encoded)
typedef struct {
    cbor_header_t header;
    uint8_t sensor_id;
    uint8_t sensor_type;
    float value;
    char unit[8];
    uint32_t timestamp;
    uint8_t validity;
    uint16_t error_count;
} __attribute__((packed)) sensor_data_msg_t;

// Diagnostic Event Message (CBOR encoded)
typedef struct {
    cbor_header_t header;
    uint16_t diagnostic_code;
    uint8_t severity;
    uint8_t component_id;
    uint32_t timestamp;
    char description[64];
    uint32_t occurrence_count;
} __attribute__((packed)) diagnostic_msg_t;
```

#### 2.2.2 Peer Communication Interface

**ESP-NOW Configuration**
```c
// ESP-NOW Peer Configuration
typedef struct {
    uint8_t mac_address[6];    // Peer MAC address
    uint8_t channel;           // Wi-Fi channel (1-14)
    bool encrypt;              // Enable encryption
    uint8_t lmk[16];          // Local Master Key (if encryption enabled)
} espnow_peer_config_t;

// ESP-NOW Operations
esp_err_t espnow_init(void);
esp_err_t espnow_add_peer(const espnow_peer_config_t* peer_config);
esp_err_t espnow_remove_peer(const uint8_t* mac_address);
esp_err_t espnow_send_data(const uint8_t* mac_address, const void* data, size_t len);
esp_err_t espnow_register_recv_callback(void (*callback)(const uint8_t* mac_addr, const uint8_t* data, int len));
```

**ESP-NOW Message Format**
```c
// ESP-NOW Message Types
typedef enum {
    ESPNOW_MSG_PING = 0x01,
    ESPNOW_MSG_PONG = 0x02,
    ESPNOW_MSG_TIME_SYNC_REQ = 0x03,
    ESPNOW_MSG_TIME_SYNC_RESP = 0x04,
    ESPNOW_MSG_STATUS = 0x05
} espnow_msg_type_t;

// ESP-NOW Message Header
typedef struct {
    uint8_t message_type;      // Message type
    uint8_t sequence;          // Sequence number
    uint16_t payload_length;   // Payload length
    uint32_t timestamp;        // Timestamp
    uint16_t checksum;         // Message checksum
} __attribute__((packed)) espnow_header_t;

// Ping/Pong Message
typedef struct {
    espnow_header_t header;
    uint8_t sender_id[6];      // Sender MAC address
    uint32_t uptime;           // Sender uptime in seconds
    int8_t rssi;               // Signal strength
} __attribute__((packed)) espnow_ping_msg_t;
```

### 2.3 Diagnostic Interface

**Diagnostic Session Protocol**
```c
// Diagnostic Command Types
typedef enum {
    DIAG_CMD_GET_STATUS = 0x01,
    DIAG_CMD_GET_SENSORS = 0x02,
    DIAG_CMD_GET_DIAGNOSTICS = 0x03,
    DIAG_CMD_CLEAR_DIAGNOSTICS = 0x04,
    DIAG_CMD_GET_CONFIG = 0x05,
    DIAG_CMD_SET_CONFIG = 0x06,
    DIAG_CMD_REBOOT = 0x07
} diag_cmd_type_t;

// Diagnostic Command Structure
typedef struct {
    uint8_t command;           // Command type
    uint8_t sequence;          // Sequence number
    uint16_t payload_length;   // Payload length
    uint8_t payload[];         // Variable length payload
} __attribute__((packed)) diag_command_t;

// Diagnostic Response Structure
typedef struct {
    uint8_t command;           // Original command
    uint8_t sequence;          // Sequence number
    uint8_t status;            // Response status (0=success)
    uint16_t payload_length;   // Payload length
    uint8_t payload[];         // Variable length payload
} __attribute__((packed)) diag_response_t;
```

## 3. Internal Interfaces

### 3.1 Component Interfaces

#### 3.1.1 Event System Interface

**Event System API**
```c
// Event Types
typedef enum {
    EVENT_SENSOR_DATA_UPDATE = 0x0001,
    EVENT_DIAGNOSTIC_EVENT = 0x0002,
    EVENT_STATE_CHANGED = 0x0003,
    EVENT_OTA_REQUEST = 0x0004,
    EVENT_MC_UPDATE = 0x0005,
    EVENT_COMMUNICATION_STATUS = 0x0006,
    EVENT_STORAGE_STATUS = 0x0007,
    EVENT_BUTTON_PRESSED = 0x0008,
    EVENT_TIMER_EXPIRED = 0x0009,
    EVENT_SYSTEM_ERROR = 0x000A
} event_type_t;

// Event Data Structure
typedef struct {
    event_type_t type;         // Event type
    uint32_t timestamp;        // Event timestamp
    uint8_t source_component;  // Source component ID
    uint16_t data_length;      // Event data length
    void* data;                // Event data pointer
} event_t;

// Event Handler Function Type
typedef void (*event_handler_t)(const event_t* event);

// Event System Operations
esp_err_t event_system_init(void);
esp_err_t event_publish(event_type_t type, const void* data, size_t data_len);
esp_err_t event_subscribe(event_type_t type, event_handler_t handler);
esp_err_t event_unsubscribe(event_type_t type, event_handler_t handler);
esp_err_t event_system_process(void); // Process pending events
```

#### 3.1.2 Data Pool Interface

**Data Pool API**
```c
// Data Pool Entry Types
typedef enum {
    DATA_TYPE_SENSOR_READING = 0x01,
    DATA_TYPE_SYSTEM_STATUS = 0x02,
    DATA_TYPE_COMMUNICATION_STATUS = 0x03,
    DATA_TYPE_DIAGNOSTIC_SUMMARY = 0x04,
    DATA_TYPE_CONFIGURATION = 0x05
} data_type_t;

// Data Pool Entry
typedef struct {
    data_type_t type;          // Data type
    uint8_t key[16];           // Data key (sensor ID, etc.)
    uint32_t timestamp;        // Last update timestamp
    uint16_t data_length;      // Data length
    void* data;                // Data pointer
    bool valid;                // Data validity flag
} data_pool_entry_t;

// Data Pool Operations
esp_err_t data_pool_init(void);
esp_err_t data_pool_write(data_type_t type, const uint8_t* key, const void* data, size_t data_len);
esp_err_t data_pool_read(data_type_t type, const uint8_t* key, void* data, size_t* data_len);
esp_err_t data_pool_get_timestamp(data_type_t type, const uint8_t* key, uint32_t* timestamp);
esp_err_t data_pool_is_valid(data_type_t type, const uint8_t* key, bool* valid);
esp_err_t data_pool_invalidate(data_type_t type, const uint8_t* key);
```

#### 3.1.3 State Manager Interface

**State Manager API**
```c
// System States
typedef enum {
    STATE_INIT = 0,
    STATE_BOOT_FAILURE = 1,
    STATE_RUNNING = 2,
    STATE_WARNING = 3,
    STATE_FAULT = 4,
    STATE_OTA_PREP = 5,
    STATE_OTA_UPDATE = 6,
    STATE_MC_UPDATE = 7,
    STATE_TEARDOWN = 8,
    STATE_SERVICE = 9,
    STATE_SD_DEGRADED = 10
} system_state_t;

// State Transition Reasons
typedef enum {
    TRANSITION_REASON_STARTUP = 0,
    TRANSITION_REASON_NORMAL_OPERATION = 1,
    TRANSITION_REASON_ERROR_DETECTED = 2,
    TRANSITION_REASON_OTA_REQUEST = 3,
    TRANSITION_REASON_MC_UPDATE_REQUEST = 4,
    TRANSITION_REASON_USER_REQUEST = 5,
    TRANSITION_REASON_SYSTEM_SHUTDOWN = 6
} transition_reason_t;

// State Change Callback
typedef void (*state_change_callback_t)(system_state_t old_state, system_state_t new_state, transition_reason_t reason);

// State Manager Operations
esp_err_t state_manager_init(void);
system_state_t state_manager_get_current_state(void);
esp_err_t state_manager_request_transition(system_state_t target_state, transition_reason_t reason);
bool state_manager_is_transition_valid(system_state_t from_state, system_state_t to_state);
esp_err_t state_manager_register_callback(state_change_callback_t callback);
bool state_manager_is_operation_allowed(system_state_t state, const char* operation);
```

#### 3.1.4 Data Persistence Interface

**Data Persistence API**
```c
// Persistence Data Types
typedef enum {
    PERSIST_TYPE_SENSOR_DATA = 0x01,
    PERSIST_TYPE_DIAGNOSTIC_LOG = 0x02,
    PERSIST_TYPE_MACHINE_CONSTANTS = 0x03,
    PERSIST_TYPE_SYSTEM_CONFIG = 0x04,
    PERSIST_TYPE_CALIBRATION_DATA = 0x05,
    PERSIST_TYPE_FIRMWARE_IMAGE = 0x06
} persist_type_t;

// Persistence Operations
esp_err_t persistence_init(void);
esp_err_t persistence_write(persist_type_t type, const char* key, const void* data, size_t data_len);
esp_err_t persistence_read(persist_type_t type, const char* key, void* data, size_t* data_len);
esp_err_t persistence_delete(persist_type_t type, const char* key);
esp_err_t persistence_list_keys(persist_type_t type, char keys[][32], size_t* key_count);
esp_err_t persistence_flush_all(void);
esp_err_t persistence_get_storage_info(uint64_t* total_bytes, uint64_t* free_bytes, uint64_t* used_bytes);
bool persistence_is_available(void);
```

#### 3.1.5 Sensor Manager Interface

**Sensor Manager API**
```c
// Sensor Types
typedef enum {
    SENSOR_TYPE_TEMPERATURE = 0x01,
    SENSOR_TYPE_HUMIDITY = 0x02,
    SENSOR_TYPE_CO2 = 0x03,
    SENSOR_TYPE_NH3 = 0x04,
    SENSOR_TYPE_VOC = 0x05,
    SENSOR_TYPE_PM = 0x06,
    SENSOR_TYPE_LIGHT = 0x07
} sensor_type_t;

// Sensor Status
typedef enum {
    SENSOR_STATUS_NOT_PRESENT = 0,
    SENSOR_STATUS_INITIALIZING = 1,
    SENSOR_STATUS_WARMING_UP = 2,
    SENSOR_STATUS_READY = 3,
    SENSOR_STATUS_ERROR = 4,
    SENSOR_STATUS_FAILED = 5
} sensor_status_t;

// Sensor Data Record
typedef struct {
    uint8_t sensor_id;         // Sensor identifier
    sensor_type_t sensor_type; // Sensor type
    float value;               // Sensor reading
    char unit[8];              // Unit of measurement
    uint32_t timestamp;        // Reading timestamp
    sensor_status_t status;    // Sensor status
    uint16_t error_count;      // Error count
    float min_value;           // Minimum valid value
    float max_value;           // Maximum valid value
} sensor_data_record_t;

// Sensor Manager Operations
esp_err_t sensor_manager_init(void);
esp_err_t sensor_manager_start_acquisition(void);
esp_err_t sensor_manager_stop_acquisition(void);
esp_err_t sensor_manager_get_sensor_data(uint8_t sensor_id, sensor_data_record_t* data);
esp_err_t sensor_manager_get_all_sensor_data(sensor_data_record_t* data_array, size_t* count);
sensor_status_t sensor_manager_get_sensor_status(uint8_t sensor_id);
bool sensor_manager_is_sensor_present(uint8_t sensor_id);
esp_err_t sensor_manager_calibrate_sensor(uint8_t sensor_id, float reference_value);
```

### 3.2 Data Structures

#### 3.2.1 Machine Constants Structure

**Machine Constants Data Format**
```c
// Machine Constants Structure
typedef struct {
    // Header
    uint32_t magic_number;     // Magic number for validation (0xDEADBEEF)
    uint16_t version;          // Structure version
    uint16_t checksum;         // Data checksum
    uint32_t timestamp;        // Last update timestamp
    
    // System Identity
    char site_id[16];          // Farm site identifier
    char house_id[16];         // House identifier
    char node_id[16];          // Node identifier
    uint8_t mac_address[6];    // Device MAC address
    
    // Communication Configuration
    char mqtt_broker_uri[256]; // MQTT broker URI
    char mqtt_username[64];    // MQTT username
    char mqtt_password[64];    // MQTT password
    uint16_t mqtt_port;        // MQTT port
    uint16_t heartbeat_interval; // Heartbeat interval in seconds
    
    // Sensor Configuration
    struct {
        bool enabled;          // Sensor enabled flag
        sensor_type_t type;    // Sensor type
        uint8_t interface_type; // Interface type (I2C, SPI, UART, ADC)
        uint8_t address;       // I2C address or SPI CS pin
        uint32_t sample_rate;  // Sampling rate in Hz
        uint16_t warmup_time;  // Warmup time in seconds
        float calibration_offset; // Calibration offset
        float calibration_scale;  // Calibration scale factor
        float min_valid_value; // Minimum valid reading
        float max_valid_value; // Maximum valid reading
    } sensors[8];              // Support up to 8 sensors
    
    // System Configuration
    uint32_t acquisition_interval; // Acquisition interval in ms
    uint16_t diagnostic_retention; // Diagnostic retention in days
    uint8_t log_level;         // Logging level
    bool debug_enabled;        // Debug mode enabled
    
    // Reserved for future use
    uint8_t reserved[128];
} __attribute__((packed)) machine_constants_t;
```

#### 3.2.2 Diagnostic Event Structure

**Diagnostic Event Data Format**
```c
// Diagnostic Severity Levels
typedef enum {
    DIAG_SEVERITY_INFO = 0,
    DIAG_SEVERITY_WARNING = 1,
    DIAG_SEVERITY_ERROR = 2,
    DIAG_SEVERITY_FATAL = 3
} diagnostic_severity_t;

// Diagnostic Event Structure
typedef struct {
    uint16_t diagnostic_code;  // Diagnostic code (0xSCCC format)
    diagnostic_severity_t severity; // Severity level
    uint8_t component_id;      // Source component identifier
    uint32_t timestamp;        // Event timestamp
    uint32_t occurrence_count; // Number of occurrences
    uint32_t first_occurrence; // First occurrence timestamp
    uint32_t last_occurrence;  // Last occurrence timestamp
    char description[64];      // Human-readable description
    uint8_t context_data[32];  // Context-specific data
} __attribute__((packed)) diagnostic_event_t;

// Diagnostic Code Definitions
#define DIAG_CODE_SENSOR_DISCONNECTED    0x1001
#define DIAG_CODE_SENSOR_OUT_OF_RANGE    0x1002
#define DIAG_CODE_SENSOR_CALIBRATION_FAIL 0x1003
#define DIAG_CODE_COMMUNICATION_TIMEOUT   0x2001
#define DIAG_CODE_COMMUNICATION_AUTH_FAIL 0x2002
#define DIAG_CODE_STORAGE_WRITE_FAIL      0x3001
#define DIAG_CODE_STORAGE_READ_FAIL       0x3002
#define DIAG_CODE_STORAGE_FULL            0x3003
#define DIAG_CODE_OTA_DOWNLOAD_FAIL       0x4001
#define DIAG_CODE_OTA_VALIDATION_FAIL     0x4002
#define DIAG_CODE_SYSTEM_MEMORY_LOW       0x5001
#define DIAG_CODE_SYSTEM_WATCHDOG_RESET   0x5002
```

#### 3.2.3 System Status Structure

**System Status Data Format**
```c
// System Status Structure
typedef struct {
    // System Information
    system_state_t current_state; // Current system state
    uint32_t uptime_seconds;   // System uptime in seconds
    uint32_t boot_count;       // Number of boots since manufacturing
    uint32_t last_reset_reason; // Last reset reason
    
    // Resource Usage
    uint32_t free_heap_bytes;  // Free heap memory in bytes
    uint32_t min_free_heap;    // Minimum free heap since boot
    uint8_t cpu_usage_percent; // CPU usage percentage
    uint32_t task_count;       // Number of active tasks
    
    // Communication Status
    bool mqtt_connected;       // MQTT connection status
    int8_t wifi_rssi;          // Wi-Fi signal strength in dBm
    uint32_t messages_sent;    // Total messages sent
    uint32_t messages_received; // Total messages received
    uint32_t communication_errors; // Communication error count
    
    // Storage Status
    bool sd_card_mounted;      // SD card mount status
    uint64_t sd_total_bytes;   // SD card total capacity
    uint64_t sd_free_bytes;    // SD card free space
    uint32_t storage_errors;   // Storage error count
    
    // Sensor Status Summary
    uint8_t sensors_present;   // Number of sensors present
    uint8_t sensors_active;    // Number of active sensors
    uint8_t sensors_failed;    // Number of failed sensors
    uint32_t last_acquisition_time; // Last successful acquisition timestamp
    
    // Diagnostic Summary
    uint16_t info_events;      // Number of INFO events
    uint16_t warning_events;   // Number of WARNING events
    uint16_t error_events;     // Number of ERROR events
    uint16_t fatal_events;     // Number of FATAL events
    
    // Temperature and Performance
    float cpu_temperature;     // CPU temperature in Celsius
    uint32_t flash_wear_level; // Flash wear level (0-100%)
    
    // Firmware Information
    char firmware_version[32]; // Firmware version string
    uint32_t firmware_build_time; // Firmware build timestamp
    uint8_t firmware_checksum[32]; // Firmware SHA-256 checksum
} __attribute__((packed)) system_status_t;
```

## 4. Protocol Specifications

### 4.1 State Machine Protocol

**State Transition Protocol**
```c
// State Transition Request
typedef struct {
    system_state_t target_state; // Requested target state
    transition_reason_t reason;   // Reason for transition
    uint32_t timeout_ms;         // Transition timeout
    bool force_transition;       // Force transition flag
    uint8_t context_data[16];    // Context-specific data
} state_transition_request_t;

// State Transition Response
typedef struct {
    bool accepted;               // Transition accepted
    system_state_t current_state; // Current state after transition
    uint32_t transition_time_ms; // Time taken for transition
    char error_message[64];      // Error message if rejected
} state_transition_response_t;
```

### 4.2 OTA Update Protocol

**OTA Update Message Flow**
```c
// OTA Request Message
typedef struct {
    uint32_t firmware_size;      // Firmware size in bytes
    uint8_t firmware_checksum[32]; // SHA-256 checksum
    char firmware_version[32];   // Firmware version string
    uint32_t chunk_size;         // Chunk size for transfer
    uint16_t total_chunks;       // Total number of chunks
    bool force_update;           // Force update flag
} ota_request_msg_t;

// OTA Response Message
typedef struct {
    bool accepted;               // Update accepted
    char reason[64];             // Reason if rejected
    uint32_t estimated_time_ms;  // Estimated update time
} ota_response_msg_t;

// OTA Chunk Message
typedef struct {
    uint16_t chunk_number;       // Chunk sequence number
    uint16_t chunk_size;         // Actual chunk size
    uint8_t chunk_checksum[4];   // CRC32 checksum of chunk
    uint8_t data[];              // Chunk data
} ota_chunk_msg_t;

// OTA Status Message
typedef struct {
    uint16_t chunks_received;    // Number of chunks received
    uint16_t chunks_total;       // Total chunks expected
    uint8_t progress_percent;    // Progress percentage
    bool validation_complete;    // Validation completed
    bool ready_to_activate;      // Ready for activation
} ota_status_msg_t;
```

## 5. Error Codes and Return Values

### 5.1 Standard Error Codes

```c
// Standard ESP-IDF Error Codes (esp_err_t)
#define ESP_OK                    0     // Success
#define ESP_FAIL                 -1     // Generic failure
#define ESP_ERR_NO_MEM           0x101  // Out of memory
#define ESP_ERR_INVALID_ARG      0x102  // Invalid argument
#define ESP_ERR_INVALID_STATE    0x103  // Invalid state
#define ESP_ERR_INVALID_SIZE     0x104  // Invalid size
#define ESP_ERR_NOT_FOUND        0x105  // Requested resource not found
#define ESP_ERR_NOT_SUPPORTED    0x106  // Operation not supported
#define ESP_ERR_TIMEOUT          0x107  // Operation timed out
#define ESP_ERR_INVALID_RESPONSE 0x108  // Received response was invalid
#define ESP_ERR_INVALID_CRC      0x109  // CRC or checksum was invalid
#define ESP_ERR_INVALID_VERSION  0x10A  // Version was invalid

// Application-Specific Error Codes
#define APP_ERR_SENSOR_NOT_PRESENT    0x1001  // Sensor not detected
#define APP_ERR_SENSOR_INIT_FAILED    0x1002  // Sensor initialization failed
#define APP_ERR_SENSOR_READ_FAILED    0x1003  // Sensor read operation failed
#define APP_ERR_COMMUNICATION_FAILED  0x2001  // Communication failure
#define APP_ERR_AUTHENTICATION_FAILED 0x2002  // Authentication failure
#define APP_ERR_STORAGE_NOT_AVAILABLE 0x3001  // Storage not available
#define APP_ERR_STORAGE_WRITE_FAILED  0x3002  // Storage write failed
#define APP_ERR_STORAGE_READ_FAILED   0x3003  // Storage read failed
#define APP_ERR_STATE_TRANSITION_INVALID 0x4001 // Invalid state transition
#define APP_ERR_OTA_VALIDATION_FAILED 0x5001  // OTA validation failed
#define APP_ERR_SECURITY_VIOLATION    0x6001  // Security violation detected
```

## 6. Interface Validation

### 6.1 Interface Testing Requirements

Each interface SHALL be validated using the following methods:

| Interface Type | Validation Method | Test Coverage |
|----------------|------------------|---------------|
| **Hardware Interfaces** | Unit tests with hardware simulation | 100% of API functions |
| **Communication Interfaces** | Integration tests with protocol validation | Message format and error handling |
| **Component Interfaces** | Unit and integration tests | API contracts and data flow |
| **Data Structures** | Serialization/deserialization tests | All data formats and edge cases |
| **Protocol Specifications** | Protocol compliance tests | State machines and message flows |

### 6.2 Interface Compliance

All interfaces SHALL comply with:
- **Data Alignment:** Structures use appropriate packing and alignment
- **Endianness:** Network byte order for communication protocols
- **Error Handling:** Consistent error code usage and propagation
- **Thread Safety:** Interfaces used by multiple tasks are thread-safe
- **Resource Management:** Proper resource allocation and cleanup

---

**Document Status:** Final for Implementation Phase  
**Interface Count:** 50+ interfaces defined  
**Compliance:** ISO/IEC/IEEE 29148:2018  
**Next Phase:** Component Implementation

**This document serves as the definitive interface specification for the ASF Sensor Hub software implementation.**