# Feature Specification: Firmware Update (OTA)
# Feature ID: F-OTA (F-OTA-001 to F-OTA-005)

**Document Type:** Feature Specification  
**Version:** 1.0  
**Date:** 2025-01-19  
**Feature Category:** Firmware Update (OTA)  

## 1. Feature Overview

### 1.1 Feature Purpose

The Firmware Update (OTA) feature provides secure, reliable over-the-air firmware update capabilities for the ASF Sensor Hub. This feature enables controlled firmware lifecycle management, ensuring system availability, data integrity, and fault containment during firmware update operations.

### 1.2 Feature Scope

**In Scope:**
- OTA negotiation and readiness validation with Main Hub
- Secure firmware reception over encrypted communication channels
- Firmware integrity validation using cryptographic verification
- Safe firmware activation with A/B partitioning and automatic rollback
- Controlled system teardown and data preservation during updates

**Out of Scope:**
- Firmware generation and cryptographic signing infrastructure
- Cloud-side firmware distribution and management
- Main Hub OTA coordination logic
- Hardware-level secure boot implementation (dependency)

## 2. Sub-Features

### 2.1 F-OTA-001: OTA Update Negotiation

**Description:** Comprehensive negotiation phase between Sensor Hub and Main Hub to establish OTA readiness and coordinate update initiation.

**Readiness Validation Criteria:**
```c
typedef struct {
    system_state_t current_state;      // Must be RUNNING
    bool power_stable;                 // Power supply stable
    bool storage_available;            // SD card accessible with sufficient space
    bool communication_stable;         // Network connection stable
    uint32_t free_sd_space_mb;        // Available SD card space
    uint32_t free_nvs_entries;        // Available NVS entries
    float supply_voltage;              // Current supply voltage
    uint32_t uptime_seconds;          // System uptime for stability
} ota_readiness_t;

typedef enum {
    OTA_READY_ACCEPT = 0,             // System ready for OTA
    OTA_READY_REJECT_STATE = 1,       // Invalid system state
    OTA_READY_REJECT_POWER = 2,       // Power instability
    OTA_READY_REJECT_STORAGE = 3,     // Storage unavailable
    OTA_READY_REJECT_COMM = 4,        // Communication unstable
    OTA_READY_REJECT_RESOURCES = 5    // Insufficient resources
} ota_readiness_result_t;
```

**Negotiation Sequence:**
```mermaid
sequenceDiagram
    participant MH as Main Hub
    participant API as Main Hub APIs
    participant OTA as OTA Manager
    participant STM as State Manager
    participant DIAG as Diagnostics
    
    MH->>API: OTA_AVAILABILITY_NOTIFICATION
    API->>OTA: otaAvailabilityReceived(metadata)
    OTA->>OTA: validateSystemReadiness()
    
    alt System Ready
        OTA->>STM: requestStateTransition(OTA_PREP)
        STM->>STM: validateTransition()
        STM-->>OTA: transitionAccepted()
        OTA->>API: otaResponse(ACCEPT, readiness_info)
        API->>MH: OTA_NEGOTIATION_RESPONSE(ACCEPT)
    else System Not Ready
        OTA->>DIAG: logDiagnosticEvent(OTA_REJECTED, reason)
        OTA->>API: otaResponse(REJECT, rejection_reason)
        API->>MH: OTA_NEGOTIATION_RESPONSE(REJECT)
    end
```

**Readiness Validation Logic:**
- **System State Check:** Must be in RUNNING state (not WARNING/FAULT/SERVICE/SD_DEGRADED)
- **Power Stability:** Supply voltage within 3.0V-3.6V range for >30 seconds
- **Storage Availability:** SD card accessible with >100MB free space
- **Communication Stability:** Network connection stable for >60 seconds
- **Resource Availability:** Sufficient NVS entries and heap memory

### 2.2 F-OTA-002: Firmware Reception and Storage

**Description:** Secure reception of firmware image from Main Hub with chunked download, progress monitoring, and temporary storage management.

**Download Configuration:**
```c
typedef struct {
    uint32_t chunk_size;              // 4096 bytes (optimized for flash page)
    uint32_t total_size;              // Total firmware size
    uint32_t total_chunks;            // Number of chunks
    char firmware_version[32];        // Target firmware version
    uint8_t sha256_hash[32];         // Expected SHA-256 hash
    uint32_t timeout_seconds;         // Download timeout (600 seconds)
} ota_download_config_t;

typedef struct {
    uint32_t chunks_received;         // Number of chunks received
    uint32_t bytes_received;          // Total bytes received
    uint32_t chunks_failed;           // Failed chunk count
    uint32_t retries_performed;       // Retry attempts
    uint64_t start_time_ms;          // Download start timestamp
    uint64_t last_chunk_time_ms;     // Last chunk received timestamp
    ota_download_state_t state;       // Current download state
} ota_download_progress_t;

typedef enum {
    OTA_DOWNLOAD_IDLE = 0,
    OTA_DOWNLOAD_ACTIVE = 1,
    OTA_DOWNLOAD_PAUSED = 2,
    OTA_DOWNLOAD_COMPLETE = 3,
    OTA_DOWNLOAD_FAILED = 4,
    OTA_DOWNLOAD_TIMEOUT = 5
} ota_download_state_t;
```

**Storage Management:**
- **Temporary Storage:** SD card path `/ota/firmware_temp.bin`
- **Chunk Verification:** Per-chunk CRC32 validation
- **Progress Persistence:** Download state persisted to NVS for recovery
- **Timeout Handling:** 10-minute maximum download duration
- **Retry Logic:** Up to 3 retries per failed chunk

**Download Flow:**
```mermaid
sequenceDiagram
    participant MH as Main Hub
    participant NET as Network Stack
    participant OTA as OTA Manager
    participant SD as SD Card Storage
    participant NVS as NVS Storage
    
    Note over MH,NVS: Firmware Download Phase
    
    MH->>NET: firmwareChunk(chunk_id, data, crc32)
    NET->>OTA: chunkReceived(chunk_id, data, crc32)
    OTA->>OTA: validateChunkCRC(data, crc32)
    
    alt CRC Valid
        OTA->>SD: writeChunk(chunk_id, data)
        SD-->>OTA: writeComplete()
        OTA->>NVS: updateProgress(chunks_received++)
        OTA->>NET: chunkAck(chunk_id, SUCCESS)
        NET->>MH: CHUNK_ACK(chunk_id, SUCCESS)
    else CRC Invalid
        OTA->>NET: chunkAck(chunk_id, RETRY)
        NET->>MH: CHUNK_ACK(chunk_id, RETRY)
    end
    
    OTA->>OTA: checkDownloadComplete()
    
    alt All Chunks Received
        OTA->>OTA: transitionToValidation()
    end
```

### 2.3 F-OTA-003: Firmware Integrity Validation

**Description:** Comprehensive firmware integrity and authenticity validation using cryptographic verification before activation.

**Validation Methods:**
```c
typedef struct {
    bool size_valid;                  // Firmware size matches metadata
    bool sha256_valid;               // SHA-256 hash verification
    bool signature_valid;            // Digital signature verification (if available)
    bool partition_valid;            // Partition table validation
    bool version_valid;              // Version number validation
    bool compatibility_valid;        // Hardware compatibility check
} ota_validation_result_t;

typedef enum {
    OTA_VALIDATION_PENDING = 0,
    OTA_VALIDATION_IN_PROGRESS = 1,
    OTA_VALIDATION_SUCCESS = 2,
    OTA_VALIDATION_FAILED_SIZE = 3,
    OTA_VALIDATION_FAILED_HASH = 4,
    OTA_VALIDATION_FAILED_SIGNATURE = 5,
    OTA_VALIDATION_FAILED_PARTITION = 6,
    OTA_VALIDATION_FAILED_VERSION = 7,
    OTA_VALIDATION_FAILED_COMPATIBILITY = 8
} ota_validation_status_t;
```

**Validation Sequence:**
1. **Size Validation:** Verify received firmware size matches metadata
2. **SHA-256 Verification:** Calculate and compare full image hash
3. **Partition Table Validation:** Verify partition structure compatibility
4. **Version Validation:** Ensure version progression (anti-rollback)
5. **Hardware Compatibility:** Verify target platform compatibility

**Validation Flow:**
```mermaid
sequenceDiagram
    participant OTA as OTA Manager
    participant SD as SD Card Storage
    participant SEC as Security Manager
    participant DIAG as Diagnostics
    participant API as Main Hub APIs
    
    Note over OTA,API: Firmware Validation Phase
    
    OTA->>SD: readFirmwareImage()
    SD-->>OTA: firmware_data
    
    OTA->>OTA: validateSize(firmware_data)
    
    alt Size Valid
        OTA->>SEC: calculateSHA256(firmware_data)
        SEC-->>OTA: calculated_hash
        OTA->>OTA: compareSHA256(calculated_hash, expected_hash)
        
        alt Hash Valid
            OTA->>SEC: validateSignature(firmware_data)
            SEC-->>OTA: signature_result
            
            alt Signature Valid
                OTA->>OTA: validatePartitionTable(firmware_data)
                OTA->>OTA: validateVersion(firmware_data)
                OTA->>OTA: validateCompatibility(firmware_data)
                OTA->>API: validationComplete(SUCCESS)
            else Signature Invalid
                OTA->>DIAG: logDiagnosticEvent(OTA_VALIDATION_FAILED)
                OTA->>API: validationComplete(FAILED_SIGNATURE)
            end
        else Hash Invalid
            OTA->>DIAG: logDiagnosticEvent(OTA_HASH_MISMATCH)
            OTA->>API: validationComplete(FAILED_HASH)
        end
    else Size Invalid
        OTA->>DIAG: logDiagnosticEvent(OTA_SIZE_MISMATCH)
        OTA->>API: validationComplete(FAILED_SIZE)
    end
```

### 2.4 F-OTA-004: Safe Firmware Activation

**Description:** Controlled firmware activation with system teardown, data preservation, and safe transition to new firmware.

**Activation Sequence:**
```c
typedef enum {
    OTA_ACTIVATION_IDLE = 0,
    OTA_ACTIVATION_TEARDOWN = 1,
    OTA_ACTIVATION_DATA_FLUSH = 2,
    OTA_ACTIVATION_FLASHING = 3,
    OTA_ACTIVATION_PARTITION_UPDATE = 4,
    OTA_ACTIVATION_REBOOT = 5,
    OTA_ACTIVATION_COMPLETE = 6,
    OTA_ACTIVATION_FAILED = 7
} ota_activation_state_t;

typedef struct {
    bool sensor_data_flushed;         // Latest sensor data preserved
    bool diagnostics_flushed;         // Diagnostic events preserved
    bool machine_constants_flushed;   // Machine constants preserved
    bool calibration_data_flushed;    // Calibration data preserved
    bool system_state_flushed;        // System state preserved
} ota_data_flush_status_t;
```

**Activation Flow:**
```mermaid
sequenceDiagram
    participant OTA as OTA Manager
    participant STM as State Manager
    participant PERSIST as Persistence
    participant FLASH as Flash Manager
    participant BOOT as Boot Manager
    
    Note over OTA,BOOT: Firmware Activation Phase
    
    OTA->>STM: requestStateTransition(TEARDOWN)
    STM->>STM: initiateTeardown()
    STM->>PERSIST: flushCriticalData()
    
    PERSIST->>PERSIST: flushSensorData()
    PERSIST->>PERSIST: flushDiagnostics()
    PERSIST->>PERSIST: flushMachineConstants()
    PERSIST->>PERSIST: flushCalibrationData()
    PERSIST-->>STM: flushComplete()
    
    STM->>OTA: teardownComplete()
    OTA->>STM: requestStateTransition(OTA_UPDATE)
    
    OTA->>FLASH: flashFirmwareToInactivePartition()
    FLASH-->>OTA: flashingComplete()
    
    OTA->>BOOT: updatePartitionTable()
    BOOT-->>OTA: partitionTableUpdated()
    
    OTA->>STM: systemReboot()
```

**Data Preservation Priority:**
1. **Critical System Data:** Machine constants, calibration data
2. **Diagnostic Data:** Recent diagnostic events and system health
3. **Sensor Data:** Latest sensor readings and statistics
4. **System State:** Current system state and configuration

### 2.5 F-OTA-005: A/B Partitioning with Rollback

**Description:** A/B partitioning implementation with automatic rollback capability for safe firmware updates.

**Partition Management:**
```c
typedef enum {
    OTA_PARTITION_A = 0,              // Primary partition (ota_0)
    OTA_PARTITION_B = 1,              // Secondary partition (ota_1)
    OTA_PARTITION_FACTORY = 2         // Factory partition (rescue)
} ota_partition_t;

typedef struct {
    ota_partition_t active_partition;  // Currently running partition
    ota_partition_t inactive_partition; // Target for next update
    char active_version[32];          // Version of active firmware
    char inactive_version[32];        // Version of inactive firmware
    uint32_t boot_count;             // Boot attempts since activation
    uint64_t activation_time;        // Activation timestamp
    bool rollback_pending;           // Rollback flag
} ota_partition_status_t;
```

**Rollback Triggers:**
- **Boot Failure:** System fails to boot within 60 seconds
- **Health Check Failure:** No health report within 120 seconds after boot
- **Application Crash:** Critical application failure during confirmation period
- **Manual Rollback:** Explicit rollback command from Main Hub

**Rollback Flow:**
```mermaid
sequenceDiagram
    participant BOOT as Boot Manager
    participant APP as Application
    participant HEALTH as Health Monitor
    participant OTA as OTA Manager
    participant DIAG as Diagnostics
    
    Note over BOOT,DIAG: Firmware Rollback Scenario
    
    BOOT->>APP: startApplication()
    
    alt Boot Successful
        APP->>HEALTH: startHealthMonitoring()
        HEALTH->>HEALTH: waitForConfirmationWindow(120s)
        
        alt Health Report Received
            HEALTH->>OTA: confirmFirmwareStability()
            OTA->>OTA: markFirmwareAsValid()
        else No Health Report
            HEALTH->>OTA: firmwareValidationTimeout()
            OTA->>OTA: triggerRollback(HEALTH_TIMEOUT)
        end
    else Boot Failed
        BOOT->>OTA: bootFailureDetected()
        OTA->>OTA: triggerRollback(BOOT_FAILURE)
    end
    
    alt Rollback Triggered
        OTA->>BOOT: switchToInactivePartition()
        OTA->>DIAG: logDiagnosticEvent(FIRMWARE_ROLLBACK)
        OTA->>BOOT: systemReboot()
    end
```

**Rollback Process:**
1. **Failure Detection:** Detect rollback trigger condition
2. **Partition Switch:** Update partition table to boot from previous partition
3. **Diagnostic Logging:** Record rollback event and reason
4. **System Reboot:** Restart system with previous firmware
5. **Rollback Notification:** Report rollback to Main Hub after recovery

## 3. Requirements Coverage

### 3.1 System Requirements (SR-XXX)

| Feature | System Requirements | Description |
|---------|-------------------|-------------|
| **F-OTA-001** | SR-OTA-001, SR-OTA-002, SR-OTA-003 | OTA negotiation and readiness validation |
| **F-OTA-002** | SR-OTA-004, SR-OTA-005, SR-OTA-006 | Firmware reception and temporary storage |
| **F-OTA-003** | SR-OTA-007, SR-OTA-008, SR-OTA-009 | Firmware integrity and authenticity validation |
| **F-OTA-004** | SR-OTA-010, SR-OTA-011, SR-OTA-012, SR-OTA-013 | Safe firmware activation and data preservation |
| **F-OTA-005** | SR-OTA-014, SR-OTA-015, SR-OTA-016 | A/B partitioning and automatic rollback |

### 3.2 Software Requirements (SWR-XXX)

| Feature | Software Requirements | Implementation Details |
|---------|---------------------|----------------------|
| **F-OTA-001** | SWR-OTA-001, SWR-OTA-002, SWR-OTA-003 | Readiness validation, negotiation protocol, state coordination |
| **F-OTA-002** | SWR-OTA-004, SWR-OTA-005, SWR-OTA-006 | Chunked download, progress tracking, storage management |
| **F-OTA-003** | SWR-OTA-007, SWR-OTA-008, SWR-OTA-009 | SHA-256 validation, signature verification, compatibility checks |
| **F-OTA-004** | SWR-OTA-010, SWR-OTA-011, SWR-OTA-012 | Teardown coordination, data flush, firmware flashing |
| **F-OTA-005** | SWR-OTA-013, SWR-OTA-014, SWR-OTA-015 | Partition management, rollback detection, recovery procedures |

## 4. Component Implementation Mapping

### 4.1 Primary Components

| Component | Responsibility | Location |
|-----------|---------------|----------|
| **OTA Manager** | OTA coordination, validation, activation | `application_layer/business_stack/fw_upgrader/` |
| **State Manager** | System state coordination, teardown management | `application_layer/business_stack/STM/` |
| **Persistence** | Data flush, firmware storage | `application_layer/DP_stack/persistence/` |
| **Security Manager** | Cryptographic validation, signature verification | `application_layer/security/` |

### 4.2 Supporting Components

| Component | Support Role | Interface |
|-----------|-------------|-----------|
| **Main Hub APIs** | OTA communication protocol, message handling | `application_layer/business_stack/main_hub_apis/` |
| **Network Stack** | Secure firmware download transport | `drivers/network_stack/` |
| **SD Card Driver** | Temporary firmware storage | `drivers/SDcard/` |
| **NVM Driver** | Progress persistence, partition management | `drivers/nvm/` |
| **Diagnostics** | OTA event logging, failure reporting | `application_layer/diag_task/` |

### 4.3 Component Interaction Diagram

```mermaid
graph TB
    subgraph "OTA Firmware Update Feature"
        OTA[OTA Manager]
        STM[State Manager]
        PERSIST[Persistence]
        SEC[Security Manager]
    end
    
    subgraph "Communication Components"
        API[Main Hub APIs]
        NET[Network Stack]
    end
    
    subgraph "Storage Components"
        SD[SD Card Driver]
        NVM[NVM Driver]
    end
    
    subgraph "System Components"
        DIAG[Diagnostics]
        BOOT[Boot Manager]
        HEALTH[Health Monitor]
    end
    
    subgraph "External Interfaces"
        MH[Main Hub]
        FLASH[Flash Memory]
        PART[Partition Table]
    end
    
    MH <-->|OTA Protocol| API
    API <--> OTA
    OTA <--> STM
    OTA <--> PERSIST
    OTA <--> SEC
    
    OTA --> NET
    NET -->|Firmware Download| MH
    
    PERSIST --> SD
    PERSIST --> NVM
    
    OTA --> DIAG
    OTA --> BOOT
    OTA --> HEALTH
    
    BOOT --> FLASH
    BOOT --> PART
    
    STM -.->|State Events| DIAG
    SEC -.->|Validation Events| DIAG
```

### 4.4 OTA Update Sequence

```mermaid
sequenceDiagram
    participant MH as Main Hub
    participant API as Main Hub APIs
    participant OTA as OTA Manager
    participant STM as State Manager
    participant PERSIST as Persistence
    participant SEC as Security Manager
    participant BOOT as Boot Manager
    
    Note over MH,BOOT: Complete OTA Update Flow
    
    MH->>API: OTA_AVAILABILITY_NOTIFICATION
    API->>OTA: otaAvailabilityReceived()
    OTA->>OTA: validateReadiness()
    OTA->>STM: requestStateTransition(OTA_PREP)
    OTA->>API: otaResponse(ACCEPT)
    
    loop Firmware Download
        MH->>API: firmwareChunk(data)
        API->>OTA: chunkReceived(data)
        OTA->>PERSIST: storeChunk(data)
    end
    
    OTA->>SEC: validateFirmware()
    SEC-->>OTA: validationResult(SUCCESS)
    
    OTA->>STM: requestStateTransition(TEARDOWN)
    STM->>PERSIST: flushCriticalData()
    PERSIST-->>STM: flushComplete()
    
    OTA->>BOOT: flashFirmwareToInactivePartition()
    OTA->>BOOT: updatePartitionTable()
    OTA->>STM: systemReboot()
    
    Note over MH,BOOT: System Reboots with New Firmware
    
    BOOT->>BOOT: bootFromNewPartition()
    BOOT->>OTA: firmwareActivated()
    OTA->>API: otaStatus(ACTIVATION_SUCCESS)
    API->>MH: OTA_STATUS_REPORT(SUCCESS)
```

## 5. Feature Behavior

### 5.1 Normal Operation Flow

1. **OTA Availability Phase:**
   - Receive OTA availability notification from Main Hub
   - Validate system readiness (state, power, storage, communication)
   - Negotiate OTA acceptance or rejection with detailed reasons
   - Transition to OTA_PREP state if accepted

2. **Firmware Download Phase:**
   - Receive firmware in 4KB chunks over secure channel
   - Validate each chunk with CRC32 verification
   - Store chunks to SD card temporary location
   - Track download progress and handle retries
   - Enforce 10-minute download timeout

3. **Validation Phase:**
   - Perform comprehensive firmware integrity validation
   - Verify SHA-256 hash, digital signature, and compatibility
   - Report validation results to Main Hub
   - Proceed to activation only if all validations pass

4. **Activation Phase:**
   - Coordinate system teardown with State Manager
   - Flush all critical data to persistent storage
   - Flash validated firmware to inactive partition
   - Update partition table for next boot
   - Perform controlled system reboot

5. **Confirmation Phase:**
   - Boot with new firmware and start health monitoring
   - Confirm firmware stability within 120-second window
   - Mark firmware as valid or trigger automatic rollback
   - Report final OTA status to Main Hub

### 5.2 Error Handling

| Error Condition | Detection Method | Response Action |
|----------------|------------------|-----------------|
| **System Not Ready** | Readiness validation failure | Reject OTA request, report specific reason |
| **Download Timeout** | 10-minute timeout exceeded | Abort download, clean up temporary files |
| **Chunk Corruption** | CRC32 validation failure | Request chunk retransmission (up to 3 retries) |
| **Validation Failure** | Integrity check failure | Abort OTA, report validation error |
| **Flash Failure** | Firmware flashing error | Abort OTA, maintain current firmware |
| **Boot Failure** | New firmware boot failure | Automatic rollback to previous firmware |
| **Health Check Failure** | No health report within window | Automatic rollback to previous firmware |

### 5.3 State-Dependent Behavior

| System State | Feature Behavior |
|-------------|------------------|
| **INIT** | OTA Manager initialization, partition status check |
| **RUNNING** | Accept OTA requests, perform readiness validation |
| **WARNING** | Reject OTA requests (system not stable) |
| **FAULT** | Reject OTA requests (system in fault state) |
| **OTA_PREP** | Prepare for OTA, coordinate with other components |
| **OTA_UPDATE** | Execute OTA download, validation, and activation |
| **TEARDOWN** | Coordinate data flush before firmware activation |
| **SERVICE** | Reject OTA requests (maintenance mode) |
| **SD_DEGRADED** | Reject OTA requests (storage unavailable) |

## 6. Feature Constraints

### 6.1 Timing Constraints

- **Negotiation Response:** Maximum 5 seconds for readiness validation
- **Download Timeout:** Maximum 10 minutes for complete firmware download
- **Validation Time:** Maximum 2 minutes for integrity validation
- **Activation Time:** Maximum 5 minutes for firmware activation
- **Confirmation Window:** 120 seconds for firmware stability confirmation

### 6.2 Resource Constraints

- **Storage Requirements:** Minimum 100MB free space on SD card
- **Memory Usage:** Maximum 64KB for OTA buffers and state
- **Network Bandwidth:** Optimized for 4KB chunk size
- **Flash Wear:** Minimize flash write cycles during activation

### 6.3 Security Constraints

- **Encrypted Transport:** All firmware data must be transmitted over TLS
- **Integrity Validation:** SHA-256 verification mandatory
- **Anti-Rollback:** Version progression enforcement via eFuse
- **Secure Storage:** Temporary firmware files encrypted on SD card

## 7. Interface Specifications

### 7.1 OTA Manager Public API

```c
// OTA lifecycle management
bool otaMgr_initialize(void);
bool otaMgr_isReady(void);
ota_status_t otaMgr_getStatus(void);

// OTA operations
bool otaMgr_handleAvailabilityNotification(const ota_metadata_t* metadata);
bool otaMgr_receiveFirmwareChunk(uint32_t chunk_id, const uint8_t* data, 
                                size_t size, uint32_t crc32);
bool otaMgr_validateFirmware(void);
bool otaMgr_activateFirmware(void);

// Rollback operations
bool otaMgr_triggerRollback(rollback_reason_t reason);
bool otaMgr_confirmFirmwareStability(void);
bool otaMgr_isRollbackPending(void);

// Status and diagnostics
bool otaMgr_getDownloadProgress(ota_download_progress_t* progress);
bool otaMgr_getValidationResult(ota_validation_result_t* result);
bool otaMgr_getPartitionStatus(ota_partition_status_t* status);
```

### 7.2 State Manager Integration

**State Transitions:**
- `RUNNING → OTA_PREP`: OTA request accepted
- `OTA_PREP → TEARDOWN`: Firmware validated, ready for activation
- `TEARDOWN → OTA_UPDATE`: Data flushed, ready for flashing
- `OTA_UPDATE → REBOOT`: Firmware activated, system restart

**State Coordination:**
```c
// State transition requests
bool otaMgr_requestStateTransition(system_state_t target_state, 
                                  transition_reason_t reason);
bool otaMgr_onStateChanged(system_state_t new_state, system_state_t old_state);

// Teardown coordination
bool otaMgr_initiateTeardown(teardown_reason_t reason);
bool otaMgr_onTeardownComplete(void);
```

### 7.3 Security Manager Integration

**Validation Interface:**
```c
// Firmware integrity validation
bool secMgr_calculateSHA256(const uint8_t* data, size_t size, uint8_t* hash);
bool secMgr_validateSignature(const uint8_t* firmware, size_t size, 
                             const uint8_t* signature);
bool secMgr_validateAntiRollback(const char* version);

// Secure storage
bool secMgr_encryptFirmwareChunk(const uint8_t* plaintext, size_t size, 
                                uint8_t* ciphertext);
bool secMgr_decryptFirmwareChunk(const uint8_t* ciphertext, size_t size, 
                                uint8_t* plaintext);
```

## 8. Testing and Validation

### 8.1 Unit Testing

- **Readiness Validation:** All readiness criteria and rejection scenarios
- **Chunk Processing:** Chunk reception, validation, and storage
- **Integrity Validation:** SHA-256, signature, and compatibility checks
- **Rollback Logic:** All rollback triggers and recovery procedures

### 8.2 Integration Testing

- **End-to-End OTA:** Complete OTA flow from negotiation to confirmation
- **State Coordination:** Integration with State Manager and other components
- **Security Integration:** Cryptographic validation and secure storage
- **Network Integration:** Firmware download over encrypted channels

### 8.3 System Testing

- **Fault Injection:** Network failures, power loss, corruption scenarios
- **Performance Testing:** Large firmware downloads and timing constraints
- **Security Testing:** Malicious firmware rejection and rollback scenarios
- **Long-Duration Testing:** Multiple OTA cycles and partition wear

### 8.4 Acceptance Criteria

- OTA negotiation completes within timing constraints
- Firmware download handles all error conditions gracefully
- Integrity validation rejects all invalid firmware images
- Activation preserves all critical data during transition
- Rollback mechanism recovers from all failure scenarios
- No security vulnerabilities in OTA process
- Complete audit trail of all OTA activities

## 9. Dependencies

### 9.1 Internal Dependencies

- **State Manager:** System state coordination and teardown management
- **Persistence:** Data flush and firmware storage operations
- **Security Manager:** Cryptographic validation and secure storage
- **Main Hub APIs:** OTA communication protocol implementation
- **Diagnostics:** OTA event logging and failure reporting

### 9.2 External Dependencies

- **ESP-IDF Framework:** Partition management and flash operations
- **Secure Boot:** Hardware-enforced firmware authentication
- **Network Stack:** Secure communication transport (TLS/DTLS)
- **Hardware Components:** SD card, NVS flash, network interface

## 10. Future Enhancements

### 10.1 Planned Improvements

- **Delta Updates:** Incremental firmware updates to reduce download size
- **Compression:** Firmware compression to optimize storage and bandwidth
- **Multi-Stage Rollback:** Graduated rollback with multiple recovery points
- **Predictive Validation:** Pre-validation of firmware compatibility

### 10.2 Scalability Considerations

- **Fleet Management:** Coordinated OTA updates across multiple sensor hubs
- **Cloud Integration:** Direct cloud-based firmware distribution
- **Advanced Analytics:** OTA success rate monitoring and optimization
- **Automated Testing:** Continuous integration with automated OTA testing

---

**Document Status:** Final for Implementation Phase  
**Component Dependencies:** Verified against architecture  
**Requirements Traceability:** Complete (SR-OTA, SWR-OTA)  
**Next Review:** After component implementation