# System State Manager (STM) Component Specification

**Component ID:** C-STM-001  
**Version:** 1.0  
**Date:** 2025-02-01  
**Location:** `application_layer/business_stack/STM/`

## 1. Component Overview and Scope

The System State Manager (STM) is the central coordinator for system lifecycle states in the ASF Sensor Hub. It implements the system finite state machine (FSM), enforces valid state transitions, coordinates teardown sequences, and ensures state-aware execution across all system components.

**Primary Purpose:** Provide centralized system state management and lifecycle coordination for the Sensor Hub embedded system.

**Scope:** System-wide state management, state transition control, teardown coordination, and state-aware execution enforcement.

## 2. Responsibilities and Functions

### 2.1 Primary Responsibilities

- **System State Machine Implementation:** Implement and maintain the system FSM with states: INIT, BOOT_FAILURE, RUNNING, WARNING, FAULT, OTA_PREP, OTA_UPDATE, MC_UPDATE, TEARDOWN, SERVICE, SD_DEGRADED
- **State Transition Control:** Enforce valid state transitions according to the System State Machine Specification
- **Teardown Coordination:** Execute controlled teardown sequences before firmware updates, configuration changes, or system resets
- **State Change Notification:** Notify all registered components of state transitions via Event System
- **State-Aware Execution:** Provide state query interface for components to adapt behavior based on current system state

### 2.2 Non-Responsibilities

- **Feature Logic:** Does not implement sensor acquisition, communication, or persistence logic
- **Hardware Access:** Does not directly access hardware resources
- **Fault Detection:** Does not detect faults (receives fault notifications from Error Handler)
- **Business Logic:** Does not implement application-specific business rules

## 3. Provided Interfaces

### 3.1 State Query Interface

```c
/**
 * @brief Get current system state
 * @return Current system state
 */
system_state_t stm_getCurrentState(void);

/**
 * @brief Check if a state is valid
 * @param state State to validate
 * @return true if state is valid, false otherwise
 */
bool stm_isStateValid(system_state_t state);

/**
 * @brief Check if system is in operational state
 * @return true if in RUNNING, WARNING, or SERVICE state
 */
bool stm_isOperational(void);

/**
 * @brief Check if teardown is in progress
 * @return true if in TEARDOWN state
 */
bool stm_isTeardownInProgress(void);
```

### 3.2 State Transition Interface

```c
/**
 * @brief Request a state transition
 * @param target_state Desired target state
 * @param reason Reason for transition
 * @return true if transition accepted, false if invalid
 */
bool stm_requestTransition(system_state_t target_state, transition_reason_t reason);

/**
 * @brief Validate if transition is allowed
 * @param from_state Source state
 * @param to_state Target state
 * @return true if transition is valid, false otherwise
 */
bool stm_validateTransition(system_state_t from_state, system_state_t to_state);

/**
 * @brief Force immediate state transition (emergency use only)
 * @param target_state Target state
 * @param reason Emergency reason
 * @return true if transition completed
 */
bool stm_forceTransition(system_state_t target_state, emergency_reason_t reason);
```

### 3.3 Teardown Coordination Interface

```c
/**
 * @brief Initiate controlled teardown sequence
 * @param reason Reason for teardown
 * @return true if teardown initiated, false on error
 */
bool stm_initiateTeardown(teardown_reason_t reason);

/**
 * @brief Check if teardown is complete
 * @return true if all components have completed teardown
 */
bool stm_isTeardownComplete(void);

/**
 * @brief Register component for teardown coordination
 * @param component_id Component identifier
 * @param teardown_callback Callback for teardown notification
 * @return true if registered successfully
 */
bool stm_registerTeardownComponent(component_id_t component_id, teardown_callback_t teardown_callback);
```

### 3.4 Component Registration Interface

```c
/**
 * @brief Register for state change notifications
 * @param listener State change callback function
 * @return true if registered successfully
 */
bool stm_registerStateListener(state_listener_t listener);

/**
 * @brief Unregister from state change notifications
 * @param listener State change callback function
 * @return true if unregistered successfully
 */
bool stm_unregisterStateListener(state_listener_t listener);
```

## 4. Required Interfaces

### 4.1 Event System Interface

- **Interface:** Event System publish/subscribe
- **Provider:** Event System component
- **Usage:** Publish state change events, subscribe to system events
- **Data Types:** `event_type_t`, `state_change_event_t`

### 4.2 Error Handler Interface

- **Interface:** Fault notification interface
- **Provider:** Error Handler component
- **Usage:** Receive fault notifications that trigger state transitions
- **Data Types:** `fault_severity_t`, `fault_info_t`

### 4.3 Persistence Interface

- **Interface:** Data persistence interface
- **Provider:** Data Persistence component
- **Usage:** Persist system state and restore after reboot
- **Data Types:** `system_state_record_t`

## 5. External Interfaces

### 5.1 Main Hub Communication Interface

- **Interface:** System status reporting
- **Consumer:** Main Hub APIs component
- **Usage:** Report system state changes to Main Hub
- **Protocol:** Encrypted communication channel

### 5.2 Local HMI Interface

- **Interface:** Status display interface
- **Consumer:** HMI component
- **Usage:** Display current system state on OLED
- **Protocol:** I2C display updates

## 6. Internal Interfaces

### 6.1 State Machine Engine Interface

- **Interface:** Internal FSM implementation
- **Usage:** State transition logic and validation
- **Implementation:** Private to STM component

### 6.2 Teardown Coordinator Interface

- **Interface:** Internal teardown management
- **Usage:** Coordinate multi-component teardown sequences
- **Implementation:** Private to STM component

## 7. Static View

### 7.1 Component Structure

```mermaid
graph TB
    subgraph STM["System State Manager"]
        StateMachine[State Machine Engine]
        TransitionValidator[Transition Validator]
        TeardownCoordinator[Teardown Coordinator]
        StateNotifier[State Notifier]
        StateStorage[State Storage]
    end
    
    subgraph External["External Components"]
        EventSys[Event System]
        ErrorHandler[Error Handler]
        Persistence[Persistence]
        Components[Other Components]
    end
    
    StateMachine --> TransitionValidator
    StateMachine --> StateNotifier
    StateMachine --> TeardownCoordinator
    StateStorage --> Persistence
    StateNotifier --> EventSys
    ErrorHandler --> StateMachine
    Components --> StateMachine
    StateMachine --> Components
```

### 7.2 Interface Dependencies

```mermaid
graph LR
    subgraph STM_Interfaces["STM Interfaces"]
        StateQuery[State Query Interface]
        StateTransition[State Transition Interface]
        TeardownCoord[Teardown Coordination Interface]
        ComponentReg[Component Registration Interface]
    end
    
    subgraph Required_Interfaces["Required Interfaces"]
        EventIF[Event System Interface]
        ErrorIF[Error Handler Interface]
        PersistIF[Persistence Interface]
    end
    
    subgraph External_Interfaces["External Interfaces"]
        MainHubIF[Main Hub Interface]
        HMIIF[HMI Interface]
    end
    
    StateQuery --> Components
    StateTransition --> Components
    TeardownCoord --> Components
    ComponentReg --> Components
    
    STM --> EventIF
    STM --> ErrorIF
    STM --> PersistIF
    
    STM --> MainHubIF
    STM --> HMIIF
```

## 8. Dynamic View

### 8.1 State Transition Sequence

```mermaid
sequenceDiagram
    participant Component as Requesting Component
    participant STM as System State Manager
    participant Validator as Transition Validator
    participant EventSys as Event System
    participant Persistence as Persistence
    participant OtherComps as Other Components
    
    Component->>STM: requestTransition(target_state, reason)
    STM->>Validator: validateTransition(current, target)
    Validator-->>STM: validation_result
    
    alt Transition Valid
        STM->>STM: updateCurrentState(target_state)
        STM->>Persistence: persistState(target_state)
        STM->>EventSys: publish(STATE_CHANGED, state_info)
        EventSys->>OtherComps: notify(STATE_CHANGED)
        STM-->>Component: true (success)
    else Transition Invalid
        STM-->>Component: false (rejected)
    end
```

### 8.2 Teardown Coordination Sequence

```mermaid
sequenceDiagram
    participant Trigger as Teardown Trigger
    participant STM as System State Manager
    participant SensorMgr as Sensor Manager
    participant CommMgr as Communication Manager
    participant Persistence as Persistence
    participant EventSys as Event System
    
    Trigger->>STM: initiateTeardown(reason)
    STM->>STM: transitionTo(TEARDOWN)
    STM->>EventSys: publish(TEARDOWN_INITIATED)
    
    par Parallel Teardown
        STM->>SensorMgr: teardownNotify()
        SensorMgr->>SensorMgr: stopAcquisition()
        SensorMgr-->>STM: teardownComplete()
    and
        STM->>CommMgr: teardownNotify()
        CommMgr->>CommMgr: closeConnections()
        CommMgr-->>STM: teardownComplete()
    and
        STM->>Persistence: teardownNotify()
        Persistence->>Persistence: flushCriticalData()
        Persistence-->>STM: teardownComplete()
    end
    
    STM->>STM: checkAllTeardownComplete()
    STM->>EventSys: publish(TEARDOWN_COMPLETE)
    STM-->>Trigger: teardown_complete
```

### 8.3 Fault-Triggered State Transition

```mermaid
sequenceDiagram
    participant Sensor as Sensor Component
    participant ErrorHandler as Error Handler
    participant STM as System State Manager
    participant EventSys as Event System
    participant MainHub as Main Hub APIs
    
    Sensor->>ErrorHandler: reportFault(SENSOR_CRITICAL_FAILURE)
    ErrorHandler->>ErrorHandler: classifyFault(severity=FATAL)
    ErrorHandler->>STM: requestTransition(FAULT, FAULT_DETECTED)
    
    STM->>STM: validateTransition(RUNNING -> FAULT)
    STM->>STM: transitionTo(FAULT)
    STM->>EventSys: publish(STATE_CHANGED, FAULT)
    
    EventSys->>Sensor: notify(STATE_CHANGED, FAULT)
    EventSys->>MainHub: notify(STATE_CHANGED, FAULT)
    
    Sensor->>Sensor: enterFaultMode()
    MainHub->>MainHub: reportSystemFault()
```

## 9. Interface Definitions

### 9.1 Data Types

```c
// System States
typedef enum {
    SYSTEM_STATE_INIT = 0,
    SYSTEM_STATE_BOOT_FAILURE,
    SYSTEM_STATE_RUNNING,
    SYSTEM_STATE_WARNING,
    SYSTEM_STATE_FAULT,
    SYSTEM_STATE_OTA_PREP,
    SYSTEM_STATE_OTA_UPDATE,
    SYSTEM_STATE_MC_UPDATE,
    SYSTEM_STATE_TEARDOWN,
    SYSTEM_STATE_SERVICE,
    SYSTEM_STATE_SD_DEGRADED,
    SYSTEM_STATE_COUNT
} system_state_t;

// Transition Reasons
typedef enum {
    TRANSITION_REASON_INITIALIZATION_COMPLETE,
    TRANSITION_REASON_BOOT_FAILURE_DETECTED,
    TRANSITION_REASON_WARNING_CONDITION,
    TRANSITION_REASON_FAULT_DETECTED,
    TRANSITION_REASON_OTA_REQUEST,
    TRANSITION_REASON_MC_UPDATE_REQUEST,
    TRANSITION_REASON_SERVICE_REQUEST,
    TRANSITION_REASON_SD_FAILURE,
    TRANSITION_REASON_RECOVERY_COMPLETE,
    TRANSITION_REASON_USER_REQUEST
} transition_reason_t;

// Teardown Reasons
typedef enum {
    TEARDOWN_REASON_OTA_UPDATE,
    TEARDOWN_REASON_MC_UPDATE,
    TEARDOWN_REASON_SYSTEM_RESET,
    TEARDOWN_REASON_EMERGENCY_SHUTDOWN,
    TEARDOWN_REASON_SERVICE_MODE
} teardown_reason_t;

// State Change Event
typedef struct {
    system_state_t previous_state;
    system_state_t current_state;
    transition_reason_t reason;
    uint64_t timestamp;
    uint32_t state_duration_ms;  // Time spent in previous state
} state_change_event_t;

// Component Registration
typedef enum {
    COMPONENT_ID_SENSOR_MANAGER,
    COMPONENT_ID_COMMUNICATION_MANAGER,
    COMPONENT_ID_PERSISTENCE,
    COMPONENT_ID_OTA_MANAGER,
    COMPONENT_ID_DIAGNOSTICS,
    COMPONENT_ID_HMI,
    COMPONENT_ID_COUNT
} component_id_t;

// Callback Types
typedef void (*state_listener_t)(const state_change_event_t* event);
typedef bool (*teardown_callback_t)(teardown_reason_t reason, uint32_t timeout_ms);
```

### 9.2 State Transition Matrix

| From State | To State | Trigger | Validation |
|------------|----------|---------|------------|
| INIT | RUNNING | Initialization complete | All components ready |
| INIT | BOOT_FAILURE | Boot failure | Critical component failure |
| RUNNING | WARNING | Warning condition | Non-critical fault |
| RUNNING | FAULT | Fault detected | Critical fault |
| RUNNING | OTA_PREP | OTA request | System ready for OTA |
| RUNNING | SERVICE | Service request | Authorized access |
| WARNING | RUNNING | Recovery complete | All warnings cleared |
| WARNING | FAULT | Fault escalation | Warning becomes critical |
| FAULT | RUNNING | Recovery complete | All faults cleared |
| OTA_PREP | TEARDOWN | OTA accepted | OTA validation passed |
| TEARDOWN | OTA_UPDATE | Teardown complete | All components ready |
| OTA_UPDATE | INIT | OTA complete | System reboot |
| SERVICE | RUNNING | Service complete | Normal operation resumed |
| SD_DEGRADED | RUNNING | SD recovery | SD card operational |

### 9.3 State-Dependent Execution Rules

| State | Sensor Acquisition | Communication | Persistence | OTA | Diagnostics |
|-------|-------------------|---------------|-------------|-----|-------------|
| INIT | Disabled | Limited | Limited | Disabled | Limited |
| RUNNING | Enabled | Enabled | Enabled | Disabled | Enabled |
| WARNING | Enabled | Enabled | Enabled | Disabled | Enhanced |
| FAULT | Disabled | Limited | Limited | Disabled | Enhanced |
| OTA_PREP | Enabled | Limited | Enabled | Preparing | Enabled |
| TEARDOWN | Disabled | Closing | Flushing | Disabled | Limited |
| OTA_UPDATE | Disabled | Disabled | Disabled | Active | Disabled |
| SERVICE | Limited | Limited | Enabled | Disabled | Enhanced |
| SD_DEGRADED | Enabled | Enabled | Memory-only | Disabled | Enabled |

## 10. Assumptions and Constraints

### 10.1 Assumptions

- **Single State Manager:** Only one STM instance exists in the system
- **Event System Availability:** Event System is available for state notifications
- **Component Cooperation:** All components respect state-dependent execution rules
- **Persistence Reliability:** State persistence operations complete successfully
- **Time Synchronization:** System time is available for state transition timestamps

### 10.2 Constraints

- **State Transition Atomicity:** State transitions must be atomic operations
- **Non-Blocking Operation:** State queries must be non-blocking
- **Memory Constraints:** STM must operate within 4KB memory limit
- **Real-Time Constraints:** State transitions must complete within 50ms
- **Thread Safety:** STM must be thread-safe for multi-task access

### 10.3 Design Constraints

- **No Dynamic Memory:** STM must not use dynamic memory allocation
- **Hardware Independence:** STM must not directly access hardware
- **State Persistence:** System state must survive power cycles
- **Fault Tolerance:** STM must handle component failures gracefully

## 11. Traceability

### 11.1 System Requirements

- **SR-SYS-001:** System state machine implementation
- **SR-SYS-002:** State transition enforcement
- **SR-SYS-003:** State change notification
- **SR-SYS-004:** Controlled teardown sequences

### 11.2 Software Requirements

- **SWR-SYS-001:** FSM implementation with defined states
- **SWR-SYS-002:** Valid state transition enforcement
- **SWR-SYS-003:** Component notification via Event System
- **SWR-SYS-004:** Teardown sequence execution
- **SWR-SYS-005:** Critical data persistence before teardown

### 11.3 Features

- **F-SYS-01:** System State Management
- **F-SYS-02:** Controlled Teardown Mechanism

### 11.4 Cross-Feature Constraints

- **CFC-ARCH-02:** State-aware execution enforcement
- **CFC-TIME-01:** Non-blocking state queries
- **CFC-DATA-02:** Data consistency during state transitions

---

**Document Status:** Final for Implementation  
**Dependencies:** Event System, Error Handler, Persistence  
**Next Review:** After component implementation and integration testing