# System Requirements Specification (SRS)
# ASF Sensor Hub (Sub-Hub) Embedded System

**Document Type:** System Requirements Specification  
**Version:** 1.0  
**Date:** 2025-01-19  
**Platform:** ESP32-S3, ESP-IDF v5.4, C/C++  
**Domain:** Industrial/Agricultural Automation (Smart Poultry Farm)  
**Standard:** ISO/IEC/IEEE 29148:2018  

## 1. Introduction

### 1.1 Purpose

This System Requirements Specification (SRS) defines the complete set of system requirements for the ASF Sensor Hub (Sub-Hub) embedded system. The document serves as the authoritative source for all functional and non-functional requirements that the system must satisfy.

### 1.2 Scope

The ASF Sensor Hub is a distributed sensing node deployed inside a poultry house for environmental monitoring and data collection. The system is responsible for:

- Acquisition of multiple environmental sensor data
- Local preprocessing and validation of sensor data
- Persistent storage of data and configuration
- Secure communication with a Main Hub
- Support for diagnostics, maintenance, and OTA updates
- Safe operation under fault conditions

**Explicitly out of scope:**
- Main Hub processing and control logic
- Cloud analytics and services
- Farm control algorithms
- Actuator management

### 1.3 Definitions and Acronyms

| Term | Definition |
|------|------------|
| **Sub-Hub** | The ASF Sensor Hub embedded system (this system) |
| **Main Hub** | Central processing unit that coordinates multiple Sub-Hubs |
| **MC** | Machine Constants - persistent configuration data |
| **DP** | Data Persistence component |
| **STM** | State Manager component |
| **SAL** | Sensor Abstraction Layer |
| **HMI** | Human-Machine Interface (OLED display + buttons) |
| **OTA** | Over-The-Air firmware update |
| **mTLS** | Mutual Transport Layer Security |
| **CBOR** | Concise Binary Object Representation |

### 1.4 References

- ISO/IEC/IEEE 29148:2018 - Systems and software engineering — Life cycle processes — Requirements engineering
- IEC 61508 - Functional safety of electrical/electronic/programmable electronic safety-related systems
- ESP-IDF v5.4 Programming Guide
- System_Architecture_Documentation.md
- Cross-Feature Constraints.md

## 2. Overall Description

### 2.1 Product Perspective

The ASF Sensor Hub operates as an autonomous embedded system within a distributed poultry farm automation network. It interfaces with:

- **Environmental sensors** via I2C, SPI, UART, and analog interfaces
- **Main Hub** via encrypted Wi-Fi communication
- **Peer Sub-Hubs** via ESP-NOW for limited coordination
- **Local operators** via OLED display and button interface
- **SD Card** for persistent data storage

### 2.2 Product Functions

The system provides the following major functions:

1. **Multi-sensor data acquisition** with high-frequency sampling and filtering
2. **Data quality assurance** through calibration and failure detection
3. **Secure communication** with Main Hub using encrypted protocols
4. **Persistent data storage** with wear-aware management
5. **Over-the-air firmware updates** with rollback capability
6. **Comprehensive diagnostics** and health monitoring
7. **Local human-machine interface** for status and diagnostics
8. **System state management** with controlled transitions
9. **Security enforcement** through hardware-based protection
10. **Power and fault handling** with graceful degradation

### 2.3 User Classes and Characteristics

| User Class | Characteristics | System Interaction |
|------------|-----------------|-------------------|
| **Farm Operators** | Basic technical knowledge, daily monitoring | Local HMI for status checking |
| **Maintenance Engineers** | Advanced technical knowledge, periodic maintenance | Debug sessions, diagnostic access |
| **System Integrators** | Expert technical knowledge, system configuration | Machine constants management, OTA updates |

### 2.4 Operating Environment

- **Hardware Platform:** ESP32-S3 microcontroller
- **Operating System:** FreeRTOS (via ESP-IDF)
- **Development Framework:** ESP-IDF v5.4
- **Programming Language:** C/C++
- **Environmental Conditions:** Industrial poultry house (temperature, humidity, dust)
- **Power Supply:** 12V DC with brownout protection
- **Communication:** Wi-Fi 802.11n (2.4 GHz), ESP-NOW

### 2.5 Design and Implementation Constraints

- **Memory:** 512KB SRAM, 8MB Flash (ESP32-S3)
- **Real-time:** Deterministic sensor sampling within 1-second cycles
- **Security:** Hardware-enforced Secure Boot V2 and Flash Encryption
- **Reliability:** 99.9% uptime requirement in normal operating conditions
- **Safety:** IEC 61508 SIL-1 compliance for sensor data integrity
- **Environmental:** IP65 enclosure rating, -10°C to +60°C operating range

## 3. System Requirements

### 3.1 Functional Requirements

#### 3.1.1 Sensor Data Acquisition Requirements

**SR-DAQ-001: Multi-Sensor Support**  
The system SHALL support simultaneous data acquisition from the following sensor types:
- Temperature sensors
- Humidity sensors  
- Carbon Dioxide (CO₂) sensors
- Ammonia (NH₃) sensors
- Volatile Organic Compounds (VOC) sensors
- Particulate Matter (PM) sensors
- Light Intensity sensors

**SR-DAQ-002: High-Frequency Sampling**  
The system SHALL sample each enabled sensor a minimum of 10 times per acquisition cycle to enable local filtering.

**SR-DAQ-003: Local Data Filtering**  
The system SHALL apply configurable filtering algorithms (median filter, moving average) to raw sensor samples to produce representative values.

**SR-DAQ-004: Timestamped Data Generation**  
The system SHALL associate each processed sensor value with a timestamp accurate to ±1 second of system time.

**SR-DAQ-005: Sensor State Management**  
The system SHALL maintain operational state for each sensor (enabled/disabled, present/absent, healthy/faulty).

#### 3.1.2 Data Quality & Calibration Requirements

**SR-DQC-001: Automatic Sensor Detection**  
The system SHALL automatically detect the presence of sensors based on hardware detection signals during initialization and runtime.

**SR-DQC-002: Sensor Type Enforcement**  
The system SHALL enforce sensor-slot compatibility to prevent incorrect sensor installation and usage.

**SR-DQC-003: Sensor Failure Detection**  
The system SHALL detect sensor failures including communication errors, out-of-range values, and non-responsive sensors.

**SR-DQC-004: Machine Constants Management**  
The system SHALL maintain persistent Machine Constants (MC) data including:
- Installed sensor type definitions
- Sensor calibration parameters
- Communication configuration parameters
- System identity parameters

**SR-DQC-005: Calibration Parameter Application**  
The system SHALL apply calibration parameters from MC data to raw sensor readings to produce calibrated values.

#### 3.1.3 Communication Requirements

**SR-COM-001: Main Hub Communication**  
The system SHALL provide bidirectional encrypted communication with a Main Hub to:
- Send sensor data using CBOR encoding
- Send diagnostic information
- Receive configuration updates
- Receive firmware updates

**SR-COM-002: Secure Communication Protocols**  
The system SHALL use mTLS 1.2 with X.509 certificates for all Main Hub communication.

**SR-COM-003: On-Demand Data Broadcasting**  
The system SHALL transmit the most recent sensor dataset upon request from the Main Hub within 5 seconds.

**SR-COM-004: Peer Communication**  
The system SHALL support limited peer-to-peer communication with other Sub-Hubs using ESP-NOW for:
- Connectivity checks
- Time synchronization support
- Basic status exchange

**SR-COM-005: Communication Fault Tolerance**  
The system SHALL continue autonomous operation during Main Hub communication failures for up to 24 hours.

#### 3.1.4 Persistence & Data Management Requirements

**SR-DATA-001: Persistent Sensor Data Storage**  
The system SHALL store sensor data persistently on SD Card using FAT32 file system with wear-aware batch writing.

**SR-DATA-002: Data Persistence Abstraction**  
The system SHALL provide a unified Data Persistence (DP) component that abstracts storage media access for all persistent data operations.

**SR-DATA-003: Safe Data Handling During Transitions**  
The system SHALL ensure all critical data is safely persisted before:
- Firmware updates
- Configuration updates  
- System teardown
- Reset or restart operations

**SR-DATA-004: Data Integrity Protection**  
The system SHALL implement data integrity mechanisms including checksums and atomic write operations to prevent data corruption.

**SR-DATA-005: Storage Capacity Management**  
The system SHALL manage storage capacity by implementing circular logging with configurable retention periods.

#### 3.1.5 Firmware Update (OTA) Requirements

**SR-OTA-001: OTA Update Negotiation**  
The system SHALL implement an OTA handshake mechanism with the Main Hub to acknowledge update availability and signal readiness.

**SR-OTA-002: Firmware Reception and Storage**  
The system SHALL securely receive firmware images and store them temporarily on SD Card before activation.

**SR-OTA-003: Firmware Integrity Validation**  
The system SHALL validate firmware integrity using SHA-256 checksums before activation.

**SR-OTA-004: Safe Firmware Activation**  
The system SHALL implement A/B partitioning with automatic rollback capability for safe firmware activation.

**SR-OTA-005: OTA State Management**  
The system SHALL coordinate OTA operations with the system state machine to ensure safe transitions and data preservation.

#### 3.1.6 Security & Safety Requirements

**SR-SEC-001: Secure Boot**  
The system SHALL implement Secure Boot V2 to ensure only authenticated firmware is executed.

**SR-SEC-002: Flash Encryption**  
The system SHALL implement Flash Encryption using AES-256 to protect sensitive data and intellectual property.

**SR-SEC-003: Certificate Management**  
The system SHALL manage X.509 certificates for mTLS communication with secure storage and validation.

**SR-SEC-004: Security Violation Handling**  
The system SHALL detect and respond to security violations including:
- Boot verification failures
- Certificate validation failures
- Unauthorized access attempts

#### 3.1.7 Diagnostics & Health Monitoring Requirements

**SR-DIAG-001: Diagnostic Code Management**  
The system SHALL implement structured diagnostics with:
- Unique diagnostic codes (format: 0xSCCC)
- Severity levels (INFO, WARNING, ERROR, FATAL)
- Root cause hierarchy
- Timestamp information

**SR-DIAG-002: Diagnostic Data Storage**  
The system SHALL persistently store diagnostic events in a circular log with configurable retention.

**SR-DIAG-003: Diagnostic Session Support**  
The system SHALL provide diagnostic sessions allowing authorized engineers to:
- Retrieve diagnostic data
- Inspect system health status
- Clear diagnostic records

**SR-DIAG-004: Layered Watchdog System**  
The system SHALL implement multiple watchdog levels:
- Task-level watchdogs for critical tasks
- Interrupt watchdog for system responsiveness
- RTC watchdog for ultimate system recovery

#### 3.1.8 System Management Requirements

**SR-SYS-001: System State Machine**  
The system SHALL implement a finite state machine with the following states:
- INIT, BOOT_FAILURE, RUNNING, WARNING, FAULT
- OTA_PREP, OTA_UPDATE, MC_UPDATE, TEARDOWN
- SERVICE, SD_DEGRADED

**SR-SYS-002: State-Aware Operation**  
The system SHALL restrict feature operations based on current system state according to defined state transition rules.

**SR-SYS-003: Controlled Teardown**  
The system SHALL execute a controlled teardown sequence that:
- Stops sensor acquisition
- Flushes all critical data
- Ensures storage consistency
- Prepares for target state transition

**SR-SYS-004: Local Human-Machine Interface**  
The system SHALL provide local status indication using:
- OLED display (128x64, I2C interface)
- Three-button navigation (Up, Down, Select)
- Menu system for diagnostics and sensor status

**SR-SYS-005: Engineering Access**  
The system SHALL support authenticated engineering sessions for:
- Log inspection
- Machine constants inspection and update
- Controlled debugging operations

#### 3.1.9 Power & Fault Handling Requirements

**SR-PWR-001: Brownout Detection**  
The system SHALL detect power supply brownout conditions and initiate controlled shutdown procedures.

**SR-PWR-002: Power-Loss Recovery**  
The system SHALL implement power-loss recovery mechanisms to restore operation after power restoration.

**SR-PWR-003: Fault Classification**  
The system SHALL classify faults into categories:
- Sensor faults, Communication faults, Storage faults
- Power faults, Security faults, Software faults, Hardware faults

**SR-PWR-004: Fault Escalation**  
The system SHALL implement fault escalation procedures based on severity and frequency.

#### 3.1.10 Hardware Abstraction Requirements

**SR-HW-001: Sensor Abstraction Layer**  
The system SHALL implement a Sensor Abstraction Layer (SAL) that provides uniform interfaces for different sensor types.

**SR-HW-002: Hardware Interface Abstraction**  
The system SHALL abstract hardware interfaces (GPIO, I2C, SPI, UART, ADC) through driver layers to enable portability.

**SR-HW-003: GPIO Discipline**  
The system SHALL implement GPIO discipline with defined ownership and access control for hardware resources.

### 3.2 Non-Functional Requirements

#### 3.2.1 Performance Requirements

**SR-PERF-001: Sensor Acquisition Timing**  
The system SHALL complete sensor acquisition cycles within 1 second for all enabled sensors.

**SR-PERF-002: Communication Response Time**  
The system SHALL respond to Main Hub requests within 5 seconds under normal operating conditions.

**SR-PERF-003: Memory Usage**  
The system SHALL operate within 80% of available SRAM (409.6KB) and Flash (6.4MB) capacity.

**SR-PERF-004: Storage Performance**  
The system SHALL achieve minimum 10KB/s write performance to SD Card for data logging.

#### 3.2.2 Reliability Requirements

**SR-REL-001: System Availability**  
The system SHALL achieve 99.9% availability during normal operating conditions.

**SR-REL-002: Mean Time Between Failures**  
The system SHALL achieve MTBF of 8760 hours (1 year) under specified environmental conditions.

**SR-REL-003: Fault Recovery**  
The system SHALL automatically recover from transient faults within 30 seconds.

**SR-REL-004: Data Integrity**  
The system SHALL maintain data integrity with error rate < 1 in 10^6 operations.

#### 3.2.3 Safety Requirements

**SR-SAFE-001: Fail-Safe Operation**  
The system SHALL fail to a safe state (sensor data marked invalid) upon detection of critical faults.

**SR-SAFE-002: Sensor Data Validation**  
The system SHALL validate sensor data ranges and mark out-of-range values as invalid.

**SR-SAFE-003: Watchdog Protection**  
The system SHALL implement multiple watchdog mechanisms to detect and recover from software failures.

#### 3.2.4 Security Requirements

**SR-SEC-005: Authentication**  
The system SHALL authenticate all external communication using certificate-based mutual authentication.

**SR-SEC-006: Data Encryption**  
The system SHALL encrypt all sensitive data at rest using AES-256 encryption.

**SR-SEC-007: Secure Communication**  
The system SHALL encrypt all network communication using TLS 1.2 or higher.

**SR-SEC-008: Access Control**  
The system SHALL implement role-based access control for engineering and diagnostic functions.

#### 3.2.5 Maintainability Requirements

**SR-MAINT-001: Diagnostic Accessibility**  
The system SHALL provide comprehensive diagnostic information accessible through local and remote interfaces.

**SR-MAINT-002: Configuration Management**  
The system SHALL support field configuration updates through authenticated channels.

**SR-MAINT-003: Firmware Updateability**  
The system SHALL support secure over-the-air firmware updates with rollback capability.

#### 3.2.6 Portability Requirements

**SR-PORT-001: Hardware Abstraction**  
The system SHALL abstract hardware dependencies to enable porting to compatible microcontroller platforms.

**SR-PORT-002: Standard Interfaces**  
The system SHALL use standard communication protocols (I2C, SPI, UART) for sensor interfaces.

### 3.3 Interface Requirements

#### 3.3.1 Hardware Interfaces

**SR-HW-IF-001: Sensor Interfaces**  
The system SHALL provide the following sensor interfaces:
- 4x I2C interfaces for digital sensors
- 2x SPI interfaces for high-speed sensors  
- 2x UART interfaces for serial sensors
- 4x ADC channels for analog sensors

**SR-HW-IF-002: Communication Interfaces**  
The system SHALL provide:
- Wi-Fi 802.11n (2.4 GHz) interface
- Optional Zigbee/LoRa interface for backup communication

**SR-HW-IF-003: Storage Interfaces**  
The system SHALL provide:
- SD Card interface (SPI-based)
- Internal NVM (encrypted)

**SR-HW-IF-004: User Interface**  
The system SHALL provide:
- OLED display interface (I2C, 128x64 pixels)
- 3x GPIO inputs for buttons (Up, Down, Select)

#### 3.3.2 Software Interfaces

**SR-SW-IF-001: Main Hub Protocol**  
The system SHALL implement the Main Hub communication protocol using:
- MQTT over TLS 1.2 transport
- CBOR message encoding
- Defined message schemas for sensor data, diagnostics, and control

**SR-SW-IF-002: Peer Communication Protocol**  
The system SHALL implement peer communication using ESP-NOW protocol with defined message formats.

**SR-SW-IF-003: Diagnostic Interface**  
The system SHALL provide diagnostic interface supporting:
- Log retrieval commands
- System status queries
- Configuration inspection commands

## 4. System Architecture Requirements

### 4.1 Architectural Constraints

**SR-ARCH-001: Layered Architecture**  
The system SHALL implement a strict layered architecture with dependency flow from Application → Drivers → OSAL → HAL.

**SR-ARCH-002: Hardware Abstraction**  
Application logic SHALL NOT access hardware directly and SHALL use driver abstractions exclusively.

**SR-ARCH-003: State-Aware Execution**  
All system features SHALL be aware of current system state and respect state-based operation restrictions.

**SR-ARCH-004: Event-Driven Communication**  
Internal component communication SHALL use event-driven publish/subscribe mechanisms.

**SR-ARCH-005: Data Persistence Abstraction**  
All persistent data access SHALL be performed through the Data Persistence (DP) component.

### 4.2 Component Requirements

**SR-COMP-001: State Manager Component**  
The system SHALL implement a State Manager (STM) component responsible for:
- System state machine implementation
- State transition validation and coordination
- Teardown sequence management

**SR-COMP-002: Event System Component**  
The system SHALL implement an Event System component providing:
- Publish/subscribe event bus
- Non-blocking event delivery
- Event type management

**SR-COMP-003: Sensor Manager Component**  
The system SHALL implement a Sensor Manager component responsible for:
- Sensor lifecycle management
- Data acquisition scheduling
- Local filtering and validation

**SR-COMP-004: Data Persistence Component**  
The system SHALL implement a Data Persistence (DP) component providing:
- Storage media abstraction
- Data serialization/deserialization
- Wear-aware storage management

## 5. Verification Requirements

### 5.1 Verification Methods

Each system requirement SHALL be verified using one or more of the following methods:
- **Test (T):** Verification by test execution
- **Analysis (A):** Verification by analysis or calculation  
- **Inspection (I):** Verification by inspection or review
- **Demonstration (D):** Verification by demonstration

### 5.2 Verification Levels

- **Unit Level:** Individual component verification
- **Integration Level:** Component interaction verification
- **System Level:** End-to-end system verification
- **Acceptance Level:** User acceptance verification

## 6. Traceability

This SRS provides the foundation for:
- Software Requirements Specification (SWR-XXX requirements)
- Feature specifications (F-XXX features)
- Component specifications (C-XXX components)
- Test specifications and procedures

All system requirements SHALL be traceable to:
- Stakeholder needs and use cases
- Feature definitions in Features.md
- Architectural constraints in Cross-Feature Constraints.md

---

**Document Status:** Final for Implementation Phase  
**Next Review:** After Software Requirements Specification completion