# Feature Specification: Power & Fault Handling
# Feature ID: F-PWR (F-PWR-001 to F-PWR-002)

**Document Type:** Feature Specification  
**Version:** 1.0  
**Date:** 2025-01-19  
**Feature Category:** Power & Fault Handling  

## 1. Feature Overview

### 1.1 Feature Purpose

The Power & Fault Handling feature provides comprehensive power management and fault recovery capabilities for the ASF Sensor Hub. This feature ensures reliable operation under power fluctuations, graceful recovery from power interruptions, and protection of critical data during power loss events.

### 1.2 Feature Scope

**In Scope:**
- Hardware-based brownout detection and response
- Power-loss data protection with supercapacitor backup
- Graceful shutdown and recovery procedures
- Power quality monitoring and reporting
- Critical data preservation during power events

**Out of Scope:**
- Battery-powered operation modes (system assumes continuous power)
- Advanced power management for low-power modes
- External power supply design and regulation
- Hardware power supply fault diagnosis

## 2. Sub-Features

### 2.1 F-PWR-001: Brownout Detection and Handling

**Description:** Hardware-based brownout detection with immediate response to protect system integrity and preserve critical data during power supply fluctuations.

**Brownout Detection Configuration:**
```c
typedef struct {
    float brownout_threshold_v;       // 3.0V threshold (configurable)
    uint32_t detection_delay_ms;     // 10ms detection delay
    bool hardware_detection_enabled; // ESP32-S3 BOD enabled
    brownout_response_t response;    // Immediate response action
    uint32_t supercap_runtime_ms;    // Available supercapacitor runtime
} brownout_config_t;

typedef enum {
    BROWNOUT_RESPONSE_IMMEDIATE_FLUSH = 0, // Flush critical data immediately
    BROWNOUT_RESPONSE_GRACEFUL_SHUTDOWN = 1, // Attempt graceful shutdown
    BROWNOUT_RESPONSE_EMERGENCY_SAVE = 2   // Emergency data save only
} brownout_response_t;

typedef struct {
    bool brownout_detected;          // Current brownout status
    uint64_t brownout_start_time;    // Brownout detection timestamp
    uint32_t brownout_duration_ms;   // Duration of current brownout
    uint32_t brownout_count;         // Total brownout events
    float min_voltage_recorded;      // Minimum voltage during event
    power_loss_severity_t severity;  // Brownout severity classification
} brownout_status_t;

typedef enum {
    POWER_LOSS_MINOR = 0,           // Brief voltage dip, no action needed
    POWER_LOSS_MODERATE = 1,        // Voltage drop, flush critical data
    POWER_LOSS_SEVERE = 2,          // Extended brownout, emergency shutdown
    POWER_LOSS_CRITICAL = 3         // Imminent power loss, immediate save
} power_loss_severity_t;
```

**Hardware Configuration:**
- **Brownout Detector:** ESP32-S3 hardware BOD with 3.0V threshold
- **Supercapacitor:** 0.5-1.0F capacitor providing 1-2 seconds runtime at 3.3V
- **Detection ISR:** High-priority interrupt service routine for immediate response
- **Voltage Monitoring:** Continuous ADC monitoring of supply voltage

**Brownout Response Flow:**
```mermaid
sequenceDiagram
    participant PWR as Power Supply
    participant BOD as Brownout Detector
    participant ISR as Brownout ISR
    participant PWR_MGR as Power Manager
    participant PERSIST as Persistence
    participant DIAG as Diagnostics
    
    Note over PWR,DIAG: Brownout Detection and Response
    
    PWR->>PWR: voltageDropBelow3.0V()
    PWR->>BOD: triggerBrownoutDetection()
    BOD->>ISR: brownoutInterrupt()
    
    ISR->>ISR: setPowerLossFlag()
    ISR->>PWR_MGR: notifyBrownoutDetected()
    
    PWR_MGR->>PWR_MGR: assessSeverity(voltage, duration)
    
    alt Severity >= MODERATE
        PWR_MGR->>PERSIST: flushCriticalDataImmediate()
        PERSIST->>PERSIST: flushMachineConstants()
        PERSIST->>PERSIST: flushCalibrationData()
        PERSIST->>PERSIST: flushDiagnosticEvents()
        PERSIST-->>PWR_MGR: criticalDataFlushed()
    end
    
    alt Severity >= SEVERE
        PWR_MGR->>PWR_MGR: initiateGracefulShutdown()
        PWR_MGR->>DIAG: logPowerEvent(BROWNOUT_SHUTDOWN)
    end
    
    PWR->>PWR: voltageRestored()
    BOD->>ISR: brownoutCleared()
    ISR->>PWR_MGR: notifyBrownoutCleared()
    PWR_MGR->>PWR_MGR: initiatePowerRecovery()
```

**Critical Data Flush Priority:**
1. **Machine Constants:** System configuration and calibration parameters
2. **Diagnostic Events:** Recent fault and warning events
3. **Sensor Calibration:** Current sensor calibration data
4. **System State:** Current system state and operational parameters
5. **Recent Sensor Data:** Latest sensor readings (if time permits)

**Supercapacitor Runtime Management:**
```c
typedef struct {
    float capacitance_f;             // Supercapacitor capacitance (0.5-1.0F)
    float initial_voltage_v;         // Initial charge voltage (3.3V)
    float cutoff_voltage_v;          // Minimum operating voltage (2.7V)
    uint32_t estimated_runtime_ms;   // Calculated runtime at current load
    uint32_t flush_time_budget_ms;   // Time allocated for data flush
    bool supercap_present;           // Supercapacitor detection status
} supercapacitor_config_t;

// Runtime calculation: t = C * (V_initial - V_cutoff) / I_load
uint32_t calculateSupercapRuntime(float capacitance, float v_init, 
                                 float v_cutoff, float current_ma);
```

### 2.2 F-PWR-002: Power-Loss Recovery

**Description:** Comprehensive power-loss recovery system that detects power restoration, performs system integrity checks, and restores normal operation with full data consistency validation.

**Recovery Configuration:**
```c
typedef struct {
    uint32_t power_stabilization_delay_ms; // 100ms stabilization wait
    uint32_t recovery_timeout_ms;          // 30s maximum recovery time
    bool integrity_check_required;         // Data integrity validation
    bool state_restoration_enabled;        // System state restoration
    recovery_mode_t recovery_mode;         // Recovery behavior mode
} power_recovery_config_t;

typedef enum {
    RECOVERY_MODE_FAST = 0,         // Quick recovery, minimal checks
    RECOVERY_MODE_SAFE = 1,         // Full integrity checks
    RECOVERY_MODE_DIAGNOSTIC = 2    // Extended diagnostics during recovery
} recovery_mode_t;

typedef struct {
    bool power_restored;            // Power restoration status
    uint64_t power_loss_start;      // Power loss start timestamp
    uint64_t power_loss_duration;   // Total power loss duration
    uint32_t recovery_attempts;     // Number of recovery attempts
    recovery_status_t status;       // Current recovery status
    data_integrity_result_t integrity; // Data integrity check results
} power_recovery_status_t;

typedef enum {
    RECOVERY_STATUS_PENDING = 0,    // Recovery not started
    RECOVERY_STATUS_IN_PROGRESS = 1, // Recovery in progress
    RECOVERY_STATUS_SUCCESS = 2,    // Recovery completed successfully
    RECOVERY_STATUS_FAILED = 3,     // Recovery failed
    RECOVERY_STATUS_PARTIAL = 4     // Partial recovery (degraded mode)
} recovery_status_t;
```

**Data Integrity Validation:**
```c
typedef struct {
    bool machine_constants_valid;    // MC data integrity
    bool calibration_data_valid;     // Calibration integrity
    bool diagnostic_logs_valid;      // Diagnostic data integrity
    bool system_state_valid;         // State data integrity
    bool sensor_data_valid;          // Sensor data integrity
    uint32_t corrupted_files;        // Number of corrupted files
    uint32_t recovered_files;        // Number of recovered files
} data_integrity_result_t;

typedef enum {
    INTEGRITY_CHECK_PASS = 0,       // All data intact
    INTEGRITY_CHECK_MINOR_LOSS = 1, // Minor data loss, recoverable
    INTEGRITY_CHECK_MAJOR_LOSS = 2, // Major data loss, degraded operation
    INTEGRITY_CHECK_CRITICAL_LOSS = 3 // Critical data loss, requires intervention
} integrity_check_result_t;
```

**Power Recovery Flow:**
```mermaid
sequenceDiagram
    participant PWR as Power Supply
    participant PWR_MGR as Power Manager
    participant PERSIST as Persistence
    participant DIAG as Diagnostics
    participant STM as State Manager
    participant SENSOR as Sensor Manager
    
    Note over PWR,SENSOR: Power Recovery Sequence
    
    PWR->>PWR: powerRestored()
    PWR->>PWR_MGR: notifyPowerRestoration()
    
    PWR_MGR->>PWR_MGR: waitForStabilization(100ms)
    PWR_MGR->>PWR_MGR: detectPowerLossDuration()
    
    PWR_MGR->>PERSIST: performIntegrityCheck()
    PERSIST->>PERSIST: validateMachineConstants()
    PERSIST->>PERSIST: validateCalibrationData()
    PERSIST->>PERSIST: validateDiagnosticLogs()
    PERSIST-->>PWR_MGR: integrityResults()
    
    alt Integrity Check PASS
        PWR_MGR->>STM: restoreSystemState()
        STM->>STM: transitionToRunningState()
        PWR_MGR->>SENSOR: restoreSensorConfiguration()
        PWR_MGR->>DIAG: logPowerEvent(RECOVERY_SUCCESS)
    else Integrity Check MINOR_LOSS
        PWR_MGR->>PERSIST: attemptDataRecovery()
        PWR_MGR->>STM: transitionToWarningState()
        PWR_MGR->>DIAG: logPowerEvent(RECOVERY_PARTIAL)
    else Integrity Check MAJOR_LOSS
        PWR_MGR->>STM: transitionToFaultState()
        PWR_MGR->>DIAG: logPowerEvent(RECOVERY_FAILED)
    end
    
    PWR_MGR->>PWR_MGR: reportRecoveryStatus()
```

**Recovery Validation Steps:**
1. **Power Stabilization:** Wait 100ms for power supply stabilization
2. **System Clock Recovery:** Restore system time from RTC (if available)
3. **Data Integrity Check:** Validate all persistent data structures
4. **Configuration Restoration:** Reload machine constants and calibration
5. **State Restoration:** Restore system state and component configuration
6. **Sensor Reinitialization:** Reinitialize sensors and resume acquisition
7. **Communication Recovery:** Re-establish network connections
8. **Recovery Reporting:** Log recovery status and any data loss

**RTC Battery Support (Optional):**
```c
typedef struct {
    bool rtc_battery_present;        // External RTC battery detected
    float rtc_battery_voltage;       // Current RTC battery voltage
    uint64_t time_before_loss;       // Time before power loss
    uint64_t time_after_recovery;    // Time after power recovery
    bool time_accuracy_maintained;   // Time accuracy status
} rtc_battery_status_t;

// RTC battery specifications: CR2032, 3V, 220mAh
// Maintains time accuracy during power loss up to several months
```

## 3. Requirements Coverage

### 3.1 System Requirements (SR-XXX)

| Feature | System Requirements | Description |
|---------|-------------------|-------------|
| **F-PWR-001** | SR-PWR-001, SR-PWR-002, SR-PWR-003, SR-PWR-004 | Brownout detection, data flush, graceful shutdown, clean reboot |
| **F-PWR-002** | SR-PWR-005, SR-PWR-006, SR-PWR-007, SR-PWR-008 | Power recovery, integrity validation, state restoration, event reporting |

### 3.2 Software Requirements (SWR-XXX)

| Feature | Software Requirements | Implementation Details |
|---------|---------------------|----------------------|
| **F-PWR-001** | SWR-PWR-001, SWR-PWR-002, SWR-PWR-003 | BOD configuration, ISR handling, supercapacitor management |
| **F-PWR-002** | SWR-PWR-004, SWR-PWR-005, SWR-PWR-006 | Recovery procedures, integrity checks, state restoration |

## 4. Component Implementation Mapping

### 4.1 Primary Components

| Component | Responsibility | Location |
|-----------|---------------|----------|
| **Power Manager** | Power event coordination, recovery management | `application_layer/power_manager/` |
| **Error Handler** | Power fault classification, escalation | `application_layer/error_handler/` |
| **Persistence** | Critical data flush, integrity validation | `application_layer/DP_stack/persistence/` |
| **State Manager** | System state coordination during power events | `application_layer/business_stack/STM/` |

### 4.2 Supporting Components

| Component | Support Role | Interface |
|-----------|-------------|-----------|
| **Diagnostics** | Power event logging, recovery reporting | `application_layer/diag_task/` |
| **Sensor Manager** | Sensor state preservation and restoration | `application_layer/business_stack/sensor_manager/` |
| **Machine Constant Manager** | Configuration preservation and restoration | `application_layer/business_stack/machine_constant_manager/` |
| **ADC Driver** | Voltage monitoring, supercapacitor status | `ESP_IDF_FW_wrappers/adc/` |

### 4.3 Component Interaction Diagram

```mermaid
graph TB
    subgraph "Power & Fault Handling Feature"
        PWR_MGR[Power Manager]
        ERR[Error Handler]
        PERSIST[Persistence]
        STM[State Manager]
    end
    
    subgraph "System Components"
        DIAG[Diagnostics]
        SENSOR[Sensor Manager]
        MC_MGR[MC Manager]
    end
    
    subgraph "Hardware Interfaces"
        BOD[Brownout Detector]
        ADC[ADC Driver]
        SUPERCAP[Supercapacitor]
        RTC[RTC Battery]
    end
    
    subgraph "Storage"
        NVS[NVS Flash]
        SD[SD Card]
    end
    
    BOD -->|Brownout ISR| PWR_MGR
    ADC -->|Voltage Monitoring| PWR_MGR
    SUPERCAP -->|Runtime Power| PWR_MGR
    RTC -->|Time Backup| PWR_MGR
    
    PWR_MGR <--> STM
    PWR_MGR <--> ERR
    PWR_MGR <--> PERSIST
    
    PWR_MGR --> DIAG
    PWR_MGR --> SENSOR
    PWR_MGR --> MC_MGR
    
    PERSIST --> NVS
    PERSIST --> SD
    
    ERR -.->|Power Faults| DIAG
    STM -.->|State Events| DIAG
```

### 4.4 Power Event Sequence

```mermaid
sequenceDiagram
    participant HW as Hardware
    participant BOD as Brownout Detector
    participant PWR as Power Manager
    participant PERSIST as Persistence
    participant STM as State Manager
    participant DIAG as Diagnostics
    
    Note over HW,DIAG: Complete Power Event Cycle
    
    HW->>BOD: voltageDropDetected(2.9V)
    BOD->>PWR: brownoutISR()
    PWR->>PWR: assessPowerLossSeverity()
    
    alt Critical Power Loss
        PWR->>PERSIST: emergencyDataFlush()
        PERSIST->>NVS: flushCriticalData()
        PWR->>STM: notifyPowerLoss(CRITICAL)
        PWR->>DIAG: logPowerEvent(BROWNOUT_CRITICAL)
    end
    
    Note over HW,DIAG: Power Loss Period
    
    HW->>HW: powerLost()
    
    Note over HW,DIAG: Power Restoration
    
    HW->>PWR: powerRestored()
    PWR->>PWR: waitForStabilization()
    PWR->>PERSIST: performIntegrityCheck()
    
    alt Data Integrity OK
        PWR->>STM: restoreSystemState()
        STM->>STM: transitionToRunning()
        PWR->>DIAG: logPowerEvent(RECOVERY_SUCCESS)
    else Data Corruption Detected
        PWR->>STM: transitionToFault()
        PWR->>DIAG: logPowerEvent(RECOVERY_FAILED)
    end
```

## 5. Feature Behavior

### 5.1 Normal Operation Flow

1. **Continuous Monitoring:**
   - Monitor supply voltage using ADC and hardware brownout detector
   - Track supercapacitor charge level and estimated runtime
   - Maintain power quality statistics and trend analysis
   - Report power events to diagnostics system

2. **Brownout Response:**
   - Detect voltage drop below 3.0V threshold within 10ms
   - Assess brownout severity based on voltage level and duration
   - Execute immediate data flush for critical system data
   - Coordinate graceful shutdown if extended brownout detected

3. **Power Recovery:**
   - Detect power restoration and wait for stabilization
   - Perform comprehensive data integrity validation
   - Restore system state and component configuration
   - Resume normal operation or enter degraded mode if data loss detected

4. **Event Reporting:**
   - Log all power events with timestamps and severity
   - Report power quality metrics to Main Hub
   - Maintain power event history for trend analysis
   - Generate diagnostic alerts for recurring power issues

### 5.2 Error Handling

| Error Condition | Detection Method | Response Action |
|----------------|------------------|-----------------|
| **Supercapacitor Failure** | Voltage monitoring, runtime calculation | Log warning, reduce flush scope |
| **Data Flush Timeout** | Flush operation timeout | Abort flush, log partial completion |
| **Recovery Failure** | Integrity check failure | Enter fault state, request intervention |
| **RTC Battery Low** | Battery voltage monitoring | Log warning, continue without RTC |
| **Repeated Brownouts** | Event frequency analysis | Escalate to system fault, notify Main Hub |
| **Critical Data Loss** | Integrity validation failure | Enter fault state, preserve remaining data |

### 5.3 State-Dependent Behavior

| System State | Feature Behavior |
|-------------|------------------|
| **INIT** | Initialize power monitoring, configure brownout detection |
| **RUNNING** | Full power monitoring, immediate brownout response |
| **WARNING** | Enhanced power monitoring, preemptive data flush |
| **FAULT** | Critical power functions only, preserve fault data |
| **OTA_UPDATE** | Reject OTA if power unstable, maintain power monitoring |
| **TEARDOWN** | Coordinate with teardown, ensure data preservation |
| **SERVICE** | Limited power monitoring for diagnostics |
| **SD_DEGRADED** | NVS-only data flush, reduced recovery capabilities |

## 6. Feature Constraints

### 6.1 Timing Constraints

- **Brownout Detection:** Maximum 10ms detection delay
- **Data Flush:** Must complete within supercapacitor runtime (1-2 seconds)
- **Power Stabilization:** 100ms wait after power restoration
- **Recovery Timeout:** Maximum 30 seconds for complete recovery

### 6.2 Resource Constraints

- **Supercapacitor Runtime:** 1-2 seconds at 3.3V with 0.5-1.0F capacitance
- **Critical Data Size:** Maximum data that can be flushed within runtime
- **Memory Usage:** Maximum 16KB for power management buffers
- **Flash Wear:** Minimize NVS writes during frequent brownouts

### 6.3 Hardware Constraints

- **Brownout Threshold:** 3.0V ±0.1V (ESP32-S3 BOD limitation)
- **Voltage Monitoring:** ADC accuracy ±50mV
- **Supercapacitor Leakage:** Account for self-discharge over time
- **RTC Battery Life:** CR2032 provides several months of timekeeping

## 7. Interface Specifications

### 7.1 Power Manager Public API

```c
// Power management initialization
bool powerMgr_initialize(void);
bool powerMgr_configureBrownoutDetection(const brownout_config_t* config);
bool powerMgr_configureRecovery(const power_recovery_config_t* config);

// Power monitoring
bool powerMgr_getCurrentVoltage(float* voltage);
bool powerMgr_getSupercapStatus(supercapacitor_status_t* status);
bool powerMgr_getPowerQuality(power_quality_metrics_t* metrics);

// Power event handling
bool powerMgr_isBrownoutActive(void);
bool powerMgr_isRecoveryInProgress(void);
bool powerMgr_getPowerEventHistory(power_event_t* events, size_t* count);

// Emergency operations
bool powerMgr_triggerEmergencyFlush(void);
bool powerMgr_estimateFlushTime(uint32_t* estimated_ms);
```

### 7.2 Brownout ISR Interface

```c
// Brownout interrupt service routine
void IRAM_ATTR brownout_isr_handler(void* arg);

// ISR-safe operations
void IRAM_ATTR powerMgr_setBrownoutFlag(void);
void IRAM_ATTR powerMgr_recordBrownoutTime(void);
void IRAM_ATTR powerMgr_triggerEmergencyResponse(void);
```

### 7.3 Recovery Validation Interface

```c
// Data integrity validation
bool powerMgr_validateDataIntegrity(data_integrity_result_t* result);
bool powerMgr_attemptDataRecovery(const char* data_type);
bool powerMgr_restoreSystemConfiguration(void);

// Recovery status
recovery_status_t powerMgr_getRecoveryStatus(void);
bool powerMgr_isRecoveryComplete(void);
bool powerMgr_getRecoveryReport(recovery_report_t* report);
```

## 8. Testing and Validation

### 8.1 Unit Testing

- **Brownout Detection:** Simulated voltage drops and ISR response
- **Data Flush:** Critical data preservation under time constraints
- **Recovery Logic:** Data integrity validation and state restoration
- **Supercapacitor Management:** Runtime calculation and monitoring

### 8.2 Integration Testing

- **End-to-End Power Cycle:** Complete brownout and recovery sequence
- **State Coordination:** Integration with State Manager during power events
- **Data Persistence:** Integration with Persistence component for data flush
- **Diagnostic Integration:** Power event logging and reporting

### 8.3 System Testing

- **Hardware Power Testing:** Real power supply interruptions and brownouts
- **Stress Testing:** Repeated power cycles and brownout events
- **Data Integrity Testing:** Validation of data preservation under various scenarios
- **Performance Testing:** Timing constraints under different system loads

### 8.4 Acceptance Criteria

- Brownout detection responds within 10ms of voltage drop
- Critical data successfully preserved during power loss events
- System recovers gracefully from power interruptions
- Data integrity maintained across power cycles
- No data corruption during normal power events
- Power quality monitoring provides accurate metrics
- Complete audit trail of all power events

## 9. Dependencies

### 9.1 Internal Dependencies

- **State Manager:** System state coordination during power events
- **Persistence:** Critical data flush and integrity validation
- **Error Handler:** Power fault classification and escalation
- **Diagnostics:** Power event logging and reporting

### 9.2 External Dependencies

- **ESP-IDF Framework:** Brownout detector, ADC, NVS, RTC
- **Hardware Components:** Supercapacitor, RTC battery, voltage regulators
- **FreeRTOS:** ISR handling, task coordination
- **Power Supply:** Stable 3.3V supply with brownout protection

## 10. Future Enhancements

### 10.1 Planned Improvements

- **Predictive Power Management:** Machine learning for power failure prediction
- **Advanced Supercapacitor Management:** Dynamic runtime optimization
- **Power Quality Analytics:** Advanced power supply analysis and reporting
- **Battery Backup Support:** Optional battery backup for extended operation

### 10.2 Scalability Considerations

- **Fleet Power Monitoring:** Centralized power quality monitoring across hubs
- **Predictive Maintenance:** Power supply health monitoring and replacement alerts
- **Advanced Recovery:** Multi-level recovery strategies based on data loss severity
- **Energy Harvesting:** Integration with renewable energy sources

---

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