software design

This commit is contained in:
2026-01-25 23:48:46 +01:00
parent 2a2fba3473
commit c631110349
305 changed files with 40333 additions and 0 deletions

View File

@@ -0,0 +1,445 @@
# Feature Specification: Sensor Data Acquisition
# Feature ID: F-DAQ (F-DAQ-001 to F-DAQ-005)
**Document Type:** Feature Specification
**Version:** 1.0
**Date:** 2025-01-19
**Feature Category:** Sensor Data Acquisition
## 1. Feature Overview
### 1.1 Feature Purpose
The Sensor Data Acquisition feature provides comprehensive environmental sensor data collection, processing, and preparation capabilities for the ASF Sensor Hub. This feature ensures reliable, high-quality sensor data is available for persistence, communication, and system monitoring.
### 1.2 Feature Scope
**In Scope:**
- Multi-sensor data acquisition from 7 sensor types
- High-frequency sampling with configurable parameters
- Local data filtering and noise reduction
- Timestamped data record generation
- Sensor state management and lifecycle control
**Out of Scope:**
- Sensor hardware design and manufacturing
- Main Hub data processing and analytics
- Control algorithm implementation
- Actuator management
## 2. Sub-Features
### 2.1 F-DAQ-001: Multi-Sensor Data Acquisition
**Description:** Simultaneous data acquisition from multiple heterogeneous environmental sensors.
**Supported Sensor Types:**
- Temperature sensors (I2C/Analog)
- Humidity sensors (I2C)
- Carbon Dioxide (CO₂) sensors (UART/I2C)
- Ammonia (NH₃) sensors (Analog/I2C)
- Volatile Organic Compounds (VOC) sensors (I2C)
- Particulate Matter (PM) sensors (UART/I2C)
- Light Intensity sensors (Analog/I2C)
**Key Capabilities:**
- Concurrent sensor handling without blocking
- Modular sensor driver architecture
- Runtime sensor presence awareness
- Per-sensor enable/disable control
### 2.2 F-DAQ-002: High-Frequency Sampling
**Description:** Multiple raw readings per acquisition cycle with configurable sampling parameters.
**Sampling Characteristics:**
- Default: 10 samples per sensor per cycle
- Configurable sampling count (5-20 samples)
- Bounded sampling time window (max 800ms)
- Deterministic sampling intervals
**Benefits:**
- Noise reduction through oversampling
- Statistical confidence in measurements
- Outlier detection capability
### 2.3 F-DAQ-003: Local Data Filtering
**Description:** Configurable filtering algorithms applied to raw sensor samples.
**Available Filters:**
- **Median Filter:** Removes outliers and impulse noise
- **Moving Average:** Smooths data and reduces random noise
- **Rate-of-Change Limiter:** Prevents unrealistic value jumps
**Filter Configuration:**
- Filter type selectable per sensor
- Filter parameters configurable via Machine Constants
- Real-time filter switching capability
### 2.4 F-DAQ-004: Timestamped Data Generation
**Description:** Association of processed sensor values with accurate timestamps.
**Timestamp Characteristics:**
- Generated after filtering completion
- System time based (RTC or synchronized)
- Accuracy: ±1 second
- ISO 8601 format for persistence
**Data Record Structure:**
```c
typedef struct {
uint8_t sensor_id;
sensor_type_t sensor_type;
float filtered_value;
char unit[8];
uint64_t timestamp_ms;
data_validity_t validity;
uint16_t sample_count;
float raw_min, raw_max;
} sensor_data_record_t;
```
### 2.5 F-DAQ-005: Sensor State Management
**Description:** Comprehensive sensor lifecycle and state management.
**Sensor States:**
- **UNKNOWN:** Initial state, not yet detected
- **DETECTED:** Sensor presence confirmed
- **INITIALIZED:** Driver loaded and configured
- **ENABLED:** Active data acquisition
- **DISABLED:** Present but not acquiring data
- **FAULTY:** Detected failure condition
- **REMOVED:** Previously present, now absent
**State Transitions:**
```mermaid
stateDiagram-v2
[*] --> UNKNOWN
UNKNOWN --> DETECTED : Presence detected
DETECTED --> INITIALIZED : Driver loaded
INITIALIZED --> ENABLED : Acquisition started
ENABLED --> DISABLED : Manual disable
DISABLED --> ENABLED : Manual enable
ENABLED --> FAULTY : Failure detected
FAULTY --> ENABLED : Recovery successful
DETECTED --> REMOVED : Presence lost
INITIALIZED --> REMOVED : Presence lost
ENABLED --> REMOVED : Presence lost
DISABLED --> REMOVED : Presence lost
FAULTY --> REMOVED : Presence lost
REMOVED --> DETECTED : Presence restored
```
## 3. Requirements Coverage
### 3.1 System Requirements (SR-XXX)
| Feature | System Requirements | Description |
|---------|-------------------|-------------|
| **F-DAQ-001** | SR-DAQ-001 | Multi-sensor support for 7 sensor types |
| **F-DAQ-002** | SR-DAQ-002 | High-frequency sampling (min 10 samples/cycle) |
| **F-DAQ-003** | SR-DAQ-003 | Local data filtering with configurable algorithms |
| **F-DAQ-004** | SR-DAQ-004 | Timestamped data generation (±1 second accuracy) |
| **F-DAQ-005** | SR-DAQ-005 | Sensor state management and lifecycle control |
### 3.2 Software Requirements (SWR-XXX)
| Feature | Software Requirements | Implementation Details |
|---------|---------------------|----------------------|
| **F-DAQ-001** | SWR-DAQ-001, SWR-DAQ-002, SWR-DAQ-003 | Sensor driver abstraction, type enumeration, concurrent handling |
| **F-DAQ-002** | SWR-DAQ-004, SWR-DAQ-005, SWR-DAQ-006 | Configurable sampling, time windows, buffer management |
| **F-DAQ-003** | SWR-DAQ-007, SWR-DAQ-008, SWR-DAQ-009 | Median filter, moving average, filter selection |
| **F-DAQ-004** | SWR-DAQ-010, SWR-DAQ-011, SWR-DAQ-012 | Time interface, timestamp API, data record structure |
| **F-DAQ-005** | SWR-DAQ-013, SWR-DAQ-014, SWR-DAQ-015 | State enumeration, transition logic, persistence interface |
## 4. Component Implementation Mapping
### 4.1 Primary Components
| Component | Responsibility | Location |
|-----------|---------------|----------|
| **Sensor Manager** | Acquisition coordination, filtering, state management | `application_layer/business_stack/sensor_manager/` |
| **Sensor Drivers** | Hardware interface, raw data acquisition | `drivers/sensor_drivers/` |
| **Event System** | Data publication, component coordination | `application_layer/business_stack/event_system/` |
| **Data Pool** | Latest sensor data storage | `application_layer/DP_stack/data_pool/` |
### 4.2 Supporting Components
| Component | Support Role | Interface |
|-----------|-------------|-----------|
| **Time Utils** | Timestamp generation | `utils/time_utils/` |
| **Logger** | Debug and diagnostic logging | `utils/logger/` |
| **Machine Constant Manager** | Filter configuration, sensor parameters | `application_layer/business_stack/mc_manager/` |
### 4.3 Component Interaction Diagram
```mermaid
graph TB
subgraph "Sensor Data Acquisition Feature"
SM[Sensor Manager]
SD[Sensor Drivers]
ES[Event System]
DP[Data Pool]
TU[Time Utils]
MCM[MC Manager]
end
subgraph "External Interfaces"
SENSORS[Physical Sensors]
PERSIST[Persistence]
COMM[Communication]
end
SENSORS -->|I2C/SPI/UART/ADC| SD
SD -->|Raw Samples| SM
MCM -->|Filter Config| SM
TU -->|Timestamp| SM
SM -->|Filtered Data| ES
ES -->|Data Update Event| DP
ES -->|Data Update Event| PERSIST
ES -->|Data Update Event| COMM
SM -.->|State Changes| ES
SM -.->|Diagnostics| ES
```
### 4.4 Data Flow Sequence
```mermaid
sequenceDiagram
participant Sensor as Physical Sensor
participant Driver as Sensor Driver
participant Manager as Sensor Manager
participant MCMgr as MC Manager
participant TimeUtil as Time Utils
participant EventSys as Event System
participant DataPool as Data Pool
Note over Sensor,DataPool: Acquisition Cycle (1 second)
Manager->>MCMgr: getSamplingConfig(sensor_id)
MCMgr-->>Manager: sampling_config
loop 10 samples
Manager->>Driver: readSensor(sensor_id)
Driver->>Sensor: I2C/SPI/UART read
Sensor-->>Driver: raw_value
Driver-->>Manager: raw_sample
end
Manager->>Manager: applyFilter(raw_samples)
Manager->>TimeUtil: getCurrentTimestamp()
TimeUtil-->>Manager: timestamp
Manager->>Manager: createDataRecord()
Manager->>EventSys: publish(SENSOR_DATA_UPDATE, record)
EventSys->>DataPool: updateSensorData(record)
Note over Manager,DataPool: Data available for persistence and communication
```
## 5. Feature Behavior
### 5.1 Normal Operation Flow
1. **Initialization Phase:**
- Load sensor configuration from Machine Constants
- Initialize sensor drivers for detected sensors
- Configure sampling and filtering parameters
- Transition sensors to ENABLED state
2. **Acquisition Cycle (1 second):**
- For each enabled sensor:
- Perform high-frequency sampling (10 samples)
- Apply configured filter to raw samples
- Generate timestamp for filtered value
- Create sensor data record
- Publish data update event
3. **State Management:**
- Monitor sensor health during acquisition
- Detect and handle sensor failures
- Update sensor states based on conditions
- Report state changes via events
### 5.2 Error Handling
| Error Condition | Detection Method | Response Action |
|----------------|------------------|-----------------|
| **Sensor Communication Failure** | Timeout or invalid response | Mark sensor as FAULTY, continue with other sensors |
| **Out-of-Range Values** | Range validation | Mark data as invalid, log diagnostic event |
| **Sampling Timeout** | Bounded time window exceeded | Use partial samples, mark data quality degraded |
| **Filter Failure** | Exception in filter algorithm | Use raw average, log diagnostic event |
| **Memory Allocation Failure** | Buffer allocation failure | Skip cycle, trigger system diagnostic |
### 5.3 State-Dependent Behavior
| System State | Feature Behavior |
|-------------|------------------|
| **INIT** | Initialize sensors, load configuration |
| **RUNNING** | Normal acquisition cycles |
| **WARNING** | Continue acquisition, increase diagnostic reporting |
| **FAULT** | Stop acquisition, preserve sensor states |
| **OTA_UPDATE** | Stop acquisition, save sensor states |
| **MC_UPDATE** | Stop acquisition, reload configuration after update |
| **TEARDOWN** | Stop acquisition, flush pending data |
| **SERVICE** | Limited acquisition for diagnostics |
| **SD_DEGRADED** | Continue acquisition, no persistence |
## 6. Feature Constraints
### 6.1 Timing Constraints
- **Acquisition Cycle:** Must complete within 1 second
- **Sampling Window:** Maximum 800ms per sensor
- **Filter Processing:** Maximum 50ms per sensor
- **Event Publication:** Maximum 10ms delay
### 6.2 Resource Constraints
- **Memory Usage:** Maximum 32KB for sensor data buffers
- **CPU Usage:** Maximum 20% of available CPU time
- **I/O Bandwidth:** Shared among all sensors, priority-based
### 6.3 Quality Constraints
- **Data Accuracy:** Within sensor specification limits
- **Timestamp Accuracy:** ±1 second of system time
- **Filter Effectiveness:** >90% noise reduction for median filter
- **State Consistency:** 100% accurate state representation
## 7. Interface Specifications
### 7.1 Sensor Manager Public API
```c
// Initialization and configuration
bool sensorMgr_initialize(void);
bool sensorMgr_loadConfiguration(const machine_constants_t* mc);
bool sensorMgr_detectSensors(void);
// Acquisition control
bool sensorMgr_startAcquisition(void);
bool sensorMgr_stopAcquisition(void);
bool sensorMgr_pauseAcquisition(void);
bool sensorMgr_resumeAcquisition(void);
// Sensor control
bool sensorMgr_enableSensor(uint8_t sensor_id);
bool sensorMgr_disableSensor(uint8_t sensor_id);
bool sensorMgr_configureSensor(uint8_t sensor_id, const sensor_config_t* config);
// Data access
bool sensorMgr_getLatestData(uint8_t sensor_id, sensor_data_record_t* record);
bool sensorMgr_getAllSensorData(sensor_data_record_t* records, size_t* count);
// State management
sensor_state_t sensorMgr_getSensorState(uint8_t sensor_id);
bool sensorMgr_isSensorPresent(uint8_t sensor_id);
bool sensorMgr_isSensorEnabled(uint8_t sensor_id);
bool sensorMgr_isSensorHealthy(uint8_t sensor_id);
// Statistics and diagnostics
bool sensorMgr_getSensorStatistics(uint8_t sensor_id, sensor_stats_t* stats);
bool sensorMgr_resetSensorStatistics(uint8_t sensor_id);
```
### 7.2 Event System Integration
**Published Events:**
- `EVENT_SENSOR_DATA_UPDATE`: New sensor data available
- `EVENT_SENSOR_STATE_CHANGED`: Sensor state transition
- `EVENT_SENSOR_FAULT_DETECTED`: Sensor failure detected
- `EVENT_SENSOR_RECOVERY`: Sensor recovered from fault
**Subscribed Events:**
- `EVENT_STATE_CHANGED`: System state transitions
- `EVENT_MC_UPDATED`: Machine constants updated
- `EVENT_TEARDOWN_INITIATED`: System teardown requested
### 7.3 Data Pool Integration
**Data Storage:**
- Latest sensor data records for all sensors
- Sensor state information
- Acquisition statistics and health metrics
**Access Patterns:**
- Write: Sensor Manager updates after each acquisition cycle
- Read: Communication and Persistence components access latest data
- Query: HMI and Diagnostics access for display and analysis
## 8. Testing and Validation
### 8.1 Unit Testing
- **Sensor Driver Interface:** Mock sensors for driver testing
- **Filtering Algorithms:** Known input/output validation
- **State Machine:** All state transitions and edge cases
- **Data Record Generation:** Structure and content validation
### 8.2 Integration Testing
- **Sensor Manager + Drivers:** Real sensor hardware testing
- **Event System Integration:** Event publication and subscription
- **Data Pool Integration:** Data storage and retrieval
- **State Management:** Cross-component state coordination
### 8.3 System Testing
- **Multi-Sensor Acquisition:** All 7 sensor types simultaneously
- **Performance Testing:** Timing constraints under load
- **Fault Injection:** Sensor failure scenarios
- **Long-Duration Testing:** 24-hour continuous operation
### 8.4 Acceptance Criteria
- All sensor types successfully detected and initialized
- Acquisition cycles complete within 1-second constraint
- Filter algorithms reduce noise by >90%
- State transitions occur correctly under all conditions
- No memory leaks during continuous operation
- Graceful handling of all error conditions
## 9. Dependencies
### 9.1 Internal Dependencies
- **Machine Constant Manager:** Sensor configuration and parameters
- **Event System:** Inter-component communication
- **Data Pool:** Data storage and access
- **Time Utils:** Timestamp generation
- **Logger:** Debug and diagnostic output
### 9.2 External Dependencies
- **ESP-IDF Framework:** Hardware abstraction and drivers
- **FreeRTOS:** Task scheduling and timing
- **Hardware Sensors:** Physical sensor devices
- **System State Manager:** State-aware operation control
## 10. Future Enhancements
### 10.1 Planned Improvements
- **Adaptive Filtering:** Machine learning-based filter optimization
- **Predictive Maintenance:** Sensor degradation prediction
- **Advanced Calibration:** Multi-point calibration support
- **Sensor Fusion:** Cross-sensor validation and fusion
### 10.2 Scalability Considerations
- **Additional Sensor Types:** Framework supports easy extension
- **Higher Sampling Rates:** Configurable for future requirements
- **Distributed Processing:** Support for sensor processing offload
- **Cloud Integration:** Direct sensor data streaming capability
---
**Document Status:** Final for Implementation Phase
**Component Dependencies:** Verified against architecture
**Requirements Traceability:** Complete (45 SR, 122 SWR)
**Next Review:** After component implementation

View File

@@ -0,0 +1,640 @@
# 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

View File

@@ -0,0 +1,89 @@
# Features Directory
# ASF Sensor Hub (Sub-Hub) System Features
**Document Type:** Feature Organization Index
**Version:** 1.0
**Date:** 2025-01-19
## Overview
This directory contains the complete feature specifications for the ASF Sensor Hub system. Each feature is documented with:
- Feature description and behavior
- Covered System Requirements (SR-XXX)
- Covered Software Requirements (SWR-XXX)
- Component implementation mapping
- Feature-level constraints
- Mermaid diagrams showing component interactions
## Feature Organization
### Feature Categories
| Category | Feature ID Range | Description |
|----------|------------------|-------------|
| **Sensor Data Acquisition** | F-DAQ-001 to F-DAQ-005 | Environmental sensor data collection and processing |
| **Data Quality & Calibration** | F-DQC-001 to F-DQC-005 | Sensor validation, calibration, and quality assurance |
| **Communication** | F-COM-001 to F-COM-005 | Main Hub and peer communication capabilities |
| **Diagnostics & Health Monitoring** | F-DIAG-001 to F-DIAG-004 | System health monitoring and diagnostic reporting |
| **Persistence & Data Management** | F-DATA-001 to F-DATA-005 | Data storage and persistence management |
| **Firmware Update (OTA)** | F-OTA-001 to F-OTA-005 | Over-the-air firmware update capabilities |
| **Security & Safety** | F-SEC-001 to F-SEC-004 | Security enforcement and safety mechanisms |
| **System Management** | F-SYS-001 to F-SYS-005 | System state management and control |
| **Power & Fault Handling** | F-PWR-001 to F-PWR-004 | Power management and fault handling |
| **Hardware Abstraction** | F-HW-001 to F-HW-003 | Hardware interface abstraction |
### Feature Files
| Feature File | Features Covered | Component Dependencies |
|--------------|------------------|----------------------|
| `F-DAQ_Sensor_Data_Acquisition.md` | F-DAQ-001 to F-DAQ-005 | Sensor Manager, Sensor Drivers, Event System |
| `F-DQC_Data_Quality_Calibration.md` | F-DQC-001 to F-DQC-005 | Machine Constant Manager, Sensor Manager |
| `F-COM_Communication.md` | F-COM-001 to F-COM-005 | Main Hub APIs, Network Stack, Event System |
| `F-DIAG_Diagnostics_Health.md` | F-DIAG-001 to F-DIAG-004 | Diagnostics Task, Error Handler, Persistence |
| `F-DATA_Persistence_Management.md` | F-DATA-001 to F-DATA-005 | Data Pool, Persistence, Storage Drivers |
| `F-OTA_Firmware_Update.md` | F-OTA-001 to F-OTA-005 | OTA Manager, State Manager, Security |
| `F-SEC_Security_Safety.md` | F-SEC-001 to F-SEC-004 | Security components, Boot system |
| `F-SYS_System_Management.md` | F-SYS-001 to F-SYS-005 | State Manager, HMI, Event System |
| `F-PWR_Power_Fault_Handling.md` | F-PWR-001 to F-PWR-004 | Error Handler, Power Management |
| `F-HW_Hardware_Abstraction.md` | F-HW-001 to F-HW-003 | Sensor Abstraction Layer, Drivers |
## Traceability
### Requirements Coverage
- **System Requirements:** All 45 SR-XXX requirements are covered by features
- **Software Requirements:** All 122 SWR-XXX requirements are mapped to features
- **Components:** All components are mapped to implementing features
### Component Integration
Each feature document includes:
- **Component Interaction Diagrams:** Mermaid diagrams showing how components work together
- **Interface Definitions:** Clear specification of component interfaces
- **Data Flow:** How data flows between components within the feature
- **State Dependencies:** How the feature behaves in different system states
## Usage
1. **For Requirements Analysis:** Use feature documents to understand how requirements are implemented
2. **For Architecture Review:** Use component mappings to understand system structure
3. **For Implementation Planning:** Use component interfaces and interactions for development
4. **For Testing:** Use feature behaviors and constraints for test case development
## Document Standards
All feature documents follow:
- ISO/IEC/IEEE 29148:2018 requirements engineering standards
- Consistent formatting and structure
- Complete traceability to requirements
- Mermaid diagrams for visual representation
- Clear component interface specifications
---
**Next Steps:**
1. Review individual feature documents for completeness
2. Validate component mappings against architecture
3. Ensure all requirements are properly traced
4. Update component specifications based on feature requirements