# Feature Specification: System Management
# Feature ID: F-SYS (F-SYS-001 to F-SYS-005)

**Document Type:** Feature Specification  
**Version:** 1.0  
**Date:** 2025-01-19  
**Feature Category:** System Management  

## 1. Feature Overview

### 1.1 Feature Purpose

The System Management feature provides comprehensive control over the ASF Sensor Hub's operational lifecycle, state management, local human-machine interface, and engineering access capabilities. This feature acts as the supervisory layer governing all other functional domains.

### 1.2 Feature Scope

**In Scope:**
- System finite state machine implementation and control
- Controlled teardown sequences for safe transitions
- Local OLED-based human-machine interface
- Engineering and diagnostic access sessions
- GPIO discipline and hardware resource management

**Out of Scope:**
- Main Hub system management
- Cloud-based management interfaces
- User authentication and role management
- Remote control of other Sub-Hubs

## 2. Sub-Features

### 2.1 F-SYS-001: System State Management

**Description:** Comprehensive finite state machine controlling all system operations and transitions.

**System States (11 Total):**

| State | Description | Entry Conditions | Exit Conditions |
|-------|-------------|------------------|-----------------|
| **INIT** | Hardware and software initialization | Power-on, reset | Initialization complete or failure |
| **BOOT_FAILURE** | Secure boot verification failed | Boot verification failure | Manual recovery or reset |
| **RUNNING** | Normal sensor acquisition and communication | Successful initialization | Fault detected, update requested |
| **WARNING** | Non-fatal fault detected, degraded operation | Recoverable fault | Fault cleared or escalated |
| **FAULT** | Fatal error, core functionality disabled | Critical fault | Manual recovery or reset |
| **OTA_PREP** | OTA preparation phase | OTA request accepted | Teardown complete or OTA cancelled |
| **OTA_UPDATE** | Firmware update in progress | OTA preparation complete | Update complete or failed |
| **MC_UPDATE** | Machine constants update in progress | MC update request | Update complete or failed |
| **TEARDOWN** | Controlled shutdown sequence | Update request, fault escalation | Teardown complete |
| **SERVICE** | Engineering or diagnostic interaction | Service request | Service session ended |
| **SD_DEGRADED** | SD card failure detected, fallback mode | SD card failure | SD card restored or replaced |

**State Transition Matrix:**
```mermaid
stateDiagram-v2
    [*] --> INIT
    INIT --> RUNNING : Initialization Success
    INIT --> BOOT_FAILURE : Boot Verification Failed
    BOOT_FAILURE --> INIT : Manual Recovery
    
    RUNNING --> WARNING : Non-Fatal Fault
    RUNNING --> FAULT : Fatal Fault
    RUNNING --> OTA_PREP : OTA Request
    RUNNING --> MC_UPDATE : MC Update Request
    RUNNING --> SERVICE : Service Request
    RUNNING --> SD_DEGRADED : SD Card Failure
    
    WARNING --> RUNNING : Fault Cleared
    WARNING --> FAULT : Fault Escalated
    WARNING --> SERVICE : Service Request
    
    FAULT --> INIT : Manual Recovery
    FAULT --> SERVICE : Service Request
    
    OTA_PREP --> TEARDOWN : Ready for OTA
    OTA_PREP --> RUNNING : OTA Cancelled
    
    TEARDOWN --> OTA_UPDATE : OTA Teardown
    TEARDOWN --> MC_UPDATE : MC Teardown
    TEARDOWN --> INIT : Reset Teardown
    
    OTA_UPDATE --> INIT : Update Complete
    OTA_UPDATE --> FAULT : Update Failed
    
    MC_UPDATE --> RUNNING : Update Success
    MC_UPDATE --> FAULT : Update Failed
    
    SERVICE --> RUNNING : Service Complete
    SERVICE --> FAULT : Service Error
    
    SD_DEGRADED --> RUNNING : SD Restored
    SD_DEGRADED --> FAULT : Critical SD Error
```

### 2.2 F-SYS-002: Controlled Teardown Mechanism

**Description:** Safe system shutdown ensuring data consistency and resource cleanup.

**Teardown Triggers:**
- Firmware update (OTA) request
- Machine constants update request
- Fatal system fault escalation
- Manual engineering command
- System reset request

**Teardown Sequence (Mandatory Order):**
1. **Stop Active Operations**
   - Halt sensor acquisition tasks
   - Pause communication activities
   - Suspend diagnostic operations

2. **Data Preservation**
   - Flush pending sensor data via DP component
   - Persist current system state
   - Save diagnostic events and logs
   - Update machine constants if modified

3. **Resource Cleanup**
   - Close active communication sessions
   - Release hardware resources (I2C, SPI, UART)
   - Stop non-essential tasks
   - Clear temporary buffers

4. **State Transition**
   - Verify data persistence completion
   - Update system state to target state
   - Signal teardown completion
   - Enter target operational mode

**Teardown Verification:**
```mermaid
sequenceDiagram
    participant STM as State Manager
    participant SM as Sensor Manager
    participant DP as Data Persistence
    participant COM as Communication
    participant ES as Event System
    
    Note over STM,ES: Teardown Initiation
    STM->>ES: publish(TEARDOWN_INITIATED)
    
    STM->>SM: stopAcquisition()
    SM-->>STM: acquisitionStopped()
    
    STM->>COM: closeSessions()
    COM-->>STM: sessionsClosed()
    
    STM->>DP: flushCriticalData()
    DP->>DP: persistSensorData()
    DP->>DP: persistSystemState()
    DP->>DP: persistDiagnostics()
    DP-->>STM: flushComplete()
    
    STM->>STM: releaseResources()
    STM->>ES: publish(TEARDOWN_COMPLETE)
    
    Note over STM,ES: Ready for Target State
```

### 2.3 F-SYS-003: Local Human-Machine Interface (HMI)

**Description:** OLED-based local interface with three-button navigation for system status and diagnostics.

**Hardware Components:**
- **OLED Display:** 128x64 pixels, I2C interface (SSD1306 compatible)
- **Navigation Buttons:** 3 physical buttons (Up, Down, Select)
- **Status Indicators:** Software-based status display

**Main Screen Display:**
```
┌─────────────────────────┐
│ ASF Sensor Hub v1.0     │
│ Status: RUNNING         │
│ ─────────────────────── │
│ WiFi: Connected (75%)   │
│ Sensors: 6/7 Active     │
│ Storage: 2.1GB Free     │
│ Time: 14:32:15          │
│                         │
│ [SELECT] for Menu       │
└─────────────────────────┘
```

**Menu Structure:**
```mermaid
graph TD
    MAIN[Main Screen] --> MENU{Main Menu}
    MENU --> DIAG[Diagnostics]
    MENU --> SENSORS[Sensors]
    MENU --> HEALTH[System Health]
    MENU --> NETWORK[Network Status]
    MENU --> SERVICE[Service Mode]
    
    DIAG --> DIAG_ACTIVE[Active Diagnostics]
    DIAG --> DIAG_HISTORY[Diagnostic History]
    DIAG --> DIAG_CLEAR[Clear Diagnostics]
    
    SENSORS --> SENSOR_LIST[Sensor List]
    SENSORS --> SENSOR_STATUS[Sensor Status]
    SENSORS --> SENSOR_DATA[Latest Data]
    
    HEALTH --> HEALTH_CPU[CPU Usage]
    HEALTH --> HEALTH_MEM[Memory Usage]
    HEALTH --> HEALTH_STORAGE[Storage Status]
    HEALTH --> HEALTH_UPTIME[System Uptime]
    
    NETWORK --> NET_WIFI[WiFi Status]
    NETWORK --> NET_MAIN[Main Hub Conn]
    NETWORK --> NET_PEER[Peer Status]
    
    SERVICE --> SERVICE_AUTH[Authentication]
    SERVICE --> SERVICE_LOGS[View Logs]
    SERVICE --> SERVICE_REBOOT[System Reboot]
```

**Button Navigation Logic:**
- **UP Button:** Navigate up in menus, scroll up in lists
- **DOWN Button:** Navigate down in menus, scroll down in lists  
- **SELECT Button:** Enter submenu, confirm action, return to main

### 2.4 F-SYS-004: Engineering Access Sessions

**Description:** Secure engineering and diagnostic access for system maintenance and troubleshooting.

**Session Types:**

| Session Type | Access Level | Capabilities | Authentication |
|-------------|-------------|--------------|----------------|
| **Diagnostic Session** | Read-only | Log retrieval, status inspection | Basic PIN |
| **Engineering Session** | Read-write | Configuration, controlled commands | Certificate-based |
| **Service Session** | Full access | System control, firmware access | Multi-factor |

**Supported Access Methods:**
- **Local UART:** Direct serial connection for field service
- **Network Session:** Encrypted connection via Main Hub
- **Local HMI:** Limited diagnostic access via OLED interface

**Engineering Commands:**
```c
// System information
CMD_GET_SYSTEM_INFO
CMD_GET_SENSOR_STATUS
CMD_GET_DIAGNOSTIC_LOGS
CMD_GET_PERFORMANCE_STATS

// Configuration management
CMD_GET_MACHINE_CONSTANTS
CMD_UPDATE_MACHINE_CONSTANTS
CMD_VALIDATE_CONFIGURATION
CMD_BACKUP_CONFIGURATION

// System control
CMD_REBOOT_SYSTEM
CMD_INITIATE_TEARDOWN
CMD_CLEAR_DIAGNOSTICS
CMD_RESET_STATISTICS

// Debug operations
CMD_ENABLE_DEBUG_LOGGING
CMD_DUMP_MEMORY_USAGE
CMD_TRIGGER_DIAGNOSTIC_TEST
CMD_MONITOR_REAL_TIME
```

### 2.5 F-SYS-005: GPIO Discipline and Hardware Management

**Description:** Centralized GPIO resource management and hardware access control.

**GPIO Ownership Model:**
```c
typedef enum {
    GPIO_OWNER_NONE = 0,
    GPIO_OWNER_SENSOR_I2C,
    GPIO_OWNER_SENSOR_SPI,
    GPIO_OWNER_SENSOR_UART,
    GPIO_OWNER_SENSOR_ADC,
    GPIO_OWNER_COMMUNICATION,
    GPIO_OWNER_STORAGE,
    GPIO_OWNER_HMI,
    GPIO_OWNER_SYSTEM,
    GPIO_OWNER_DEBUG
} gpio_owner_t;

typedef struct {
    uint8_t pin_number;
    gpio_owner_t owner;
    gpio_mode_t mode;
    bool is_allocated;
    char description[32];
} gpio_resource_t;
```

**Resource Allocation Rules:**
- Each GPIO pin has single owner at any time
- Ownership must be requested and granted before use
- Automatic release on component shutdown
- Conflict detection and resolution

## 3. Requirements Coverage

### 3.1 System Requirements (SR-XXX)

| Feature | System Requirements | Description |
|---------|-------------------|-------------|
| **F-SYS-001** | SR-SYS-001 | Finite state machine with 11 defined states |
| **F-SYS-002** | SR-SYS-002, SR-SYS-003 | State-aware operation and controlled teardown |
| **F-SYS-003** | SR-SYS-004 | Local HMI with OLED display and button navigation |
| **F-SYS-004** | SR-SYS-005 | Engineering access sessions with authentication |
| **F-SYS-005** | SR-HW-003 | GPIO discipline and hardware resource management |

### 3.2 Software Requirements (SWR-XXX)

| Feature | Software Requirements | Implementation Details |
|---------|---------------------|----------------------|
| **F-SYS-001** | SWR-SYS-001, SWR-SYS-002, SWR-SYS-003 | FSM implementation, state validation, transition logic |
| **F-SYS-002** | SWR-SYS-007, SWR-SYS-008, SWR-SYS-009 | Teardown sequence, resource cleanup, completion verification |
| **F-SYS-003** | SWR-SYS-010, SWR-SYS-011, SWR-SYS-012 | OLED driver, button handling, menu navigation |
| **F-SYS-004** | SWR-SYS-013, SWR-SYS-014, SWR-SYS-015 | Session authentication, command interface, access control |
| **F-SYS-005** | SWR-HW-007, SWR-HW-008, SWR-HW-009 | GPIO ownership, access control, conflict prevention |

## 4. Component Implementation Mapping

### 4.1 Primary Components

| Component | Responsibility | Location |
|-----------|---------------|----------|
| **State Manager (STM)** | FSM implementation, state transitions, teardown coordination | `application_layer/business_stack/STM/` |
| **HMI Controller** | OLED display management, button handling, menu navigation | `application_layer/hmi/` |
| **Engineering Session Manager** | Session authentication, command processing, access control | `application_layer/engineering/` |
| **GPIO Manager** | Hardware resource allocation, ownership management | `drivers/gpio_manager/` |

### 4.2 Supporting Components

| Component | Support Role | Interface |
|-----------|-------------|-----------|
| **Event System** | State change notifications, component coordination | `application_layer/business_stack/event_system/` |
| **Data Persistence** | State persistence, configuration storage | `application_layer/DP_stack/persistence/` |
| **Diagnostics Task** | System health monitoring, diagnostic reporting | `application_layer/diag_task/` |
| **Security Manager** | Session authentication, access validation | `application_layer/security/` |

### 4.3 Component Interaction Diagram

```mermaid
graph TB
    subgraph "System Management Feature"
        STM[State Manager]
        HMI[HMI Controller]
        ESM[Engineering Session Manager]
        GPIO[GPIO Manager]
    end
    
    subgraph "Core Components"
        ES[Event System]
        DP[Data Persistence]
        DIAG[Diagnostics Task]
        SEC[Security Manager]
    end
    
    subgraph "Hardware Interfaces"
        OLED[OLED Display]
        BUTTONS[Navigation Buttons]
        UART[UART Interface]
        PINS[GPIO Pins]
    end
    
    STM <--> ES
    STM --> DP
    STM --> DIAG
    
    HMI --> OLED
    HMI --> BUTTONS
    HMI <--> ES
    HMI --> DIAG
    
    ESM --> UART
    ESM <--> SEC
    ESM <--> STM
    ESM --> DP
    
    GPIO --> PINS
    GPIO <--> ES
    
    ES -.->|State Events| HMI
    ES -.->|System Events| ESM
    DIAG -.->|Health Data| HMI
```

### 4.4 State Management Flow

```mermaid
sequenceDiagram
    participant EXT as External Trigger
    participant STM as State Manager
    participant ES as Event System
    participant COMP as System Components
    participant DP as Data Persistence
    
    Note over EXT,DP: State Transition Request
    
    EXT->>STM: requestStateTransition(target_state, reason)
    STM->>STM: validateTransition(current, target)
    
    alt Valid Transition
        STM->>ES: publish(STATE_TRANSITION_STARTING)
        STM->>COMP: prepareForStateChange(target_state)
        COMP-->>STM: preparationComplete()
        
        alt Requires Teardown
            STM->>STM: initiateTeardown()
            STM->>COMP: stopOperations()
            STM->>DP: flushCriticalData()
            DP-->>STM: flushComplete()
        end
        
        STM->>STM: transitionToState(target_state)
        STM->>ES: publish(STATE_CHANGED, new_state)
        STM->>DP: persistSystemState(new_state)
        
    else Invalid Transition
        STM->>ES: publish(STATE_TRANSITION_REJECTED)
        STM-->>EXT: transitionRejected(reason)
    end
```

## 5. Feature Behavior

### 5.1 Normal Operation Flow

1. **System Initialization:**
   - Power-on self-test and hardware verification
   - Load system configuration and machine constants
   - Initialize all components and establish communication
   - Transition to RUNNING state upon successful initialization

2. **State Management:**
   - Monitor system health and component status
   - Process state transition requests from components
   - Validate transitions against state machine rules
   - Coordinate teardown sequences when required

3. **HMI Operation:**
   - Continuously update main screen with system status
   - Process button inputs for menu navigation
   - Display diagnostic information and system health
   - Provide local access to system functions

4. **Engineering Access:**
   - Authenticate engineering session requests
   - Process authorized commands and queries
   - Provide secure access to system configuration
   - Log all engineering activities for audit

### 5.2 Error Handling

| Error Condition | Detection Method | Response Action |
|----------------|------------------|-----------------|
| **Invalid State Transition** | State validation logic | Reject transition, log diagnostic event |
| **Teardown Timeout** | Teardown completion timer | Force transition, log warning |
| **HMI Hardware Failure** | I2C communication failure | Disable HMI, continue operation |
| **Authentication Failure** | Session validation | Reject access, log security event |
| **GPIO Conflict** | Resource allocation check | Deny allocation, report conflict |

### 5.3 State-Dependent Behavior

| System State | Feature Behavior |
|-------------|------------------|
| **INIT** | Initialize components, load configuration, establish communication |
| **RUNNING** | Normal state management, full HMI functionality, engineering access |
| **WARNING** | Enhanced monitoring, diagnostic display, limited operations |
| **FAULT** | Minimal operations, fault display, engineering access only |
| **OTA_UPDATE** | Suspend normal operations, display update progress |
| **MC_UPDATE** | Suspend operations, reload configuration after update |
| **TEARDOWN** | Execute teardown sequence, display progress |
| **SERVICE** | Engineering mode, enhanced diagnostic access |
| **SD_DEGRADED** | Continue operations without persistence, display warning |

## 6. Feature Constraints

### 6.1 Timing Constraints

- **State Transition:** Maximum 5 seconds for normal transitions
- **Teardown Sequence:** Maximum 30 seconds for complete teardown
- **HMI Response:** Maximum 200ms for button response
- **Engineering Command:** Maximum 10 seconds for command execution

### 6.2 Resource Constraints

- **Memory Usage:** Maximum 16KB for state management data
- **Display Update:** Maximum 50ms for screen refresh
- **GPIO Resources:** Centralized allocation, no conflicts allowed
- **Session Limit:** Maximum 2 concurrent engineering sessions

### 6.3 Security Constraints

- **Authentication:** All engineering access must be authenticated
- **Command Validation:** All commands validated before execution
- **Audit Logging:** All engineering activities logged
- **Access Control:** Role-based access to system functions

## 7. Interface Specifications

### 7.1 State Manager Public API

```c
// State management
system_state_t stm_getCurrentState(void);
bool stm_requestStateTransition(system_state_t target_state, transition_reason_t reason);
bool stm_isTransitionValid(system_state_t from_state, system_state_t to_state);
const char* stm_getStateName(system_state_t state);

// Teardown coordination
bool stm_initiateTeardown(teardown_reason_t reason);
bool stm_isTeardownInProgress(void);
bool stm_isTeardownComplete(void);
teardown_status_t stm_getTeardownStatus(void);

// Component registration
bool stm_registerStateListener(state_change_callback_t callback);
bool stm_unregisterStateListener(state_change_callback_t callback);
bool stm_registerTeardownParticipant(teardown_participant_t* participant);

// System control
bool stm_requestSystemReboot(reboot_reason_t reason);
bool stm_requestSystemReset(reset_reason_t reason);
```

### 7.2 HMI Controller Public API

```c
// Display management
bool hmi_initialize(void);
bool hmi_updateMainScreen(const system_status_t* status);
bool hmi_displayMessage(const char* message, uint32_t duration_ms);
bool hmi_displayMenu(const menu_item_t* items, size_t item_count);

// Button handling
bool hmi_processButtonInput(button_event_t event);
bool hmi_setButtonCallback(button_callback_t callback);

// Menu navigation
bool hmi_enterMenu(menu_id_t menu_id);
bool hmi_exitMenu(void);
bool hmi_navigateMenu(navigation_direction_t direction);
bool hmi_selectMenuItem(void);

// Status display
bool hmi_showSystemStatus(const system_status_t* status);
bool hmi_showDiagnostics(const diagnostic_summary_t* diagnostics);
bool hmi_showSensorStatus(const sensor_status_t* sensors);
```

### 7.3 Engineering Session API

```c
// Session management
session_handle_t eng_createSession(session_type_t type, const auth_credentials_t* creds);
bool eng_authenticateSession(session_handle_t session, const auth_token_t* token);
bool eng_closeSession(session_handle_t session);
bool eng_isSessionValid(session_handle_t session);

// Command execution
bool eng_executeCommand(session_handle_t session, const command_t* cmd, command_result_t* result);
bool eng_querySystemInfo(session_handle_t session, system_info_t* info);
bool eng_getDiagnosticLogs(session_handle_t session, diagnostic_log_t* logs, size_t* count);

// Configuration access
bool eng_getMachineConstants(session_handle_t session, machine_constants_t* mc);
bool eng_updateMachineConstants(session_handle_t session, const machine_constants_t* mc);
bool eng_validateConfiguration(session_handle_t session, validation_result_t* result);
```

## 8. Testing and Validation

### 8.1 Unit Testing

- **State Machine:** All state transitions and edge cases
- **Teardown Logic:** Sequence execution and timeout handling
- **HMI Components:** Display updates and button handling
- **GPIO Management:** Resource allocation and conflict detection

### 8.2 Integration Testing

- **State Coordination:** Cross-component state awareness
- **Event System Integration:** State change notifications
- **HMI Integration:** Real hardware display and buttons
- **Engineering Access:** Authentication and command execution

### 8.3 System Testing

- **Full State Machine:** All states and transitions under load
- **Teardown Scenarios:** OTA, MC update, fault conditions
- **HMI Usability:** Complete menu navigation and display
- **Security Testing:** Authentication bypass attempts

### 8.4 Acceptance Criteria

- All 11 system states implemented and functional
- State transitions complete within timing constraints
- Teardown sequences preserve data integrity
- HMI provides complete system visibility
- Engineering access properly authenticated and logged
- GPIO conflicts prevented and resolved

## 9. Dependencies

### 9.1 Internal Dependencies

- **Event System:** State change notifications and coordination
- **Data Persistence:** State and configuration storage
- **Diagnostics Task:** System health monitoring
- **Security Manager:** Authentication and access control

### 9.2 External Dependencies

- **ESP-IDF Framework:** GPIO, I2C, UART drivers
- **FreeRTOS:** Task scheduling and synchronization
- **Hardware Components:** OLED display, buttons, GPIO pins
- **Network Stack:** Engineering session communication

## 10. Future Enhancements

### 10.1 Planned Improvements

- **Advanced HMI:** Graphical status displays and charts
- **Remote Management:** Web-based engineering interface
- **Predictive State Management:** AI-based state prediction
- **Enhanced Security:** Biometric authentication support

### 10.2 Scalability Considerations

- **Multi-Hub Management:** Coordinated state management
- **Cloud Integration:** Remote state monitoring and control
- **Advanced Diagnostics:** Predictive maintenance integration
- **Mobile Interface:** Smartphone app for field service

---

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