components

This commit is contained in:
2026-02-01 23:37:00 +01:00
parent 304371c6b8
commit 80236fa840
11 changed files with 5501 additions and 0 deletions

View File

@@ -0,0 +1,750 @@
# Hardware Abstraction Layer (HAL) Component Specification
**Component ID:** C-HAL-001
**Component Name:** Hardware Abstraction Layer
**Version:** 1.0
**Date:** 2025-02-01
**Location:** `drivers/hal/`
## 1. Component Overview
### 1.1 Purpose
The Hardware Abstraction Layer (HAL) provides a unified, platform-independent interface for accessing hardware peripherals on the ESP32-S3. It abstracts the ESP-IDF hardware APIs and provides consistent interfaces for I2C, SPI, UART, GPIO, ADC, and other peripherals used by the ASF Sensor Hub.
### 1.2 Scope
- Hardware peripheral abstraction (I2C, SPI, UART, GPIO, ADC, PWM, Timers)
- Platform-independent hardware interface definitions
- Resource management and conflict resolution
- Hardware configuration and initialization
- Error handling and hardware fault detection
- Performance optimization for embedded constraints
### 1.3 Responsibilities
- Provide unified interfaces for hardware peripherals
- Abstract ESP-IDF specific implementations
- Manage hardware resource allocation and sharing
- Handle hardware initialization and configuration
- Implement hardware error detection and recovery
- Optimize hardware operations for performance and power
## 2. Component Architecture
### 2.1 Static View
```mermaid
graph TB
subgraph "Hardware Abstraction Layer"
HC[HAL Controller]
I2C[I2C Interface]
SPI[SPI Interface]
UART[UART Interface]
GPIO[GPIO Interface]
ADC[ADC Interface]
PWM[PWM Interface]
TIMER[Timer Interface]
RM[Resource Manager]
end
subgraph "ESP-IDF Layer"
I2C_DRV[I2C Driver]
SPI_DRV[SPI Driver]
UART_DRV[UART Driver]
GPIO_DRV[GPIO Driver]
ADC_DRV[ADC Driver]
PWM_DRV[PWM Driver]
TIMER_DRV[Timer Driver]
end
subgraph "Hardware"
ESP32S3[ESP32-S3 MCU]
SENSORS[Sensors]
STORAGE[Storage]
DISPLAY[Display]
end
HC --> I2C
HC --> SPI
HC --> UART
HC --> GPIO
HC --> ADC
HC --> PWM
HC --> TIMER
HC --> RM
I2C --> I2C_DRV
SPI --> SPI_DRV
UART --> UART_DRV
GPIO --> GPIO_DRV
ADC --> ADC_DRV
PWM --> PWM_DRV
TIMER --> TIMER_DRV
I2C_DRV --> ESP32S3
SPI_DRV --> ESP32S3
UART_DRV --> ESP32S3
GPIO_DRV --> ESP32S3
ADC_DRV --> ESP32S3
PWM_DRV --> ESP32S3
TIMER_DRV --> ESP32S3
ESP32S3 --> SENSORS
ESP32S3 --> STORAGE
ESP32S3 --> DISPLAY
```
### 2.2 Internal Components
#### 2.2.1 HAL Controller
- Central coordination of hardware abstraction operations
- Hardware subsystem initialization and management
- Cross-peripheral coordination and resource arbitration
#### 2.2.2 I2C Interface
- I2C bus management and communication
- Multi-master and multi-slave support
- Clock stretching and error recovery
#### 2.2.3 SPI Interface
- SPI bus management and communication
- Multiple SPI device support
- DMA integration for high-speed transfers
#### 2.2.4 UART Interface
- Serial communication management
- Multiple UART port support
- Flow control and buffering
#### 2.2.5 GPIO Interface
- Digital I/O pin management
- Interrupt handling and debouncing
- Pin multiplexing and configuration
#### 2.2.6 ADC Interface
- Analog-to-digital conversion
- Multi-channel sampling
- Calibration and noise filtering
#### 2.2.7 PWM Interface
- Pulse-width modulation generation
- Multiple channel support
- Frequency and duty cycle control
#### 2.2.8 Timer Interface
- Hardware timer management
- Periodic and one-shot timers
- High-resolution timing
#### 2.2.9 Resource Manager
- Hardware resource allocation tracking
- Conflict detection and resolution
- Resource sharing coordination
## 3. Interfaces
### 3.1 Provided Interfaces
#### 3.1.1 IHAL
```cpp
class IHAL {
public:
virtual ~IHAL() = default;
// System Management
virtual Result<void> initialize() = 0;
virtual Result<void> shutdown() = 0;
virtual HardwareStatus getHardwareStatus() const = 0;
// Interface Access
virtual II2C* getI2CInterface(I2CPort port) = 0;
virtual ISPI* getSPIInterface(SPIPort port) = 0;
virtual IUART* getUARTInterface(UARTPort port) = 0;
virtual IGPIO* getGPIOInterface() = 0;
virtual IADC* getADCInterface() = 0;
virtual IPWM* getPWMInterface() = 0;
virtual ITimer* getTimerInterface() = 0;
// Resource Management
virtual Result<void> reserveResource(HardwareResource resource, ComponentId component) = 0;
virtual Result<void> releaseResource(HardwareResource resource, ComponentId component) = 0;
virtual bool isResourceAvailable(HardwareResource resource) const = 0;
virtual std::vector<HardwareResource> getAvailableResources() const = 0;
};
```
#### 3.1.2 II2C
```cpp
class II2C {
public:
virtual ~II2C() = default;
// Configuration
virtual Result<void> configure(const I2CConfig& config) = 0;
virtual Result<void> setClockSpeed(uint32_t frequency_hz) = 0;
virtual Result<void> setTimeout(std::chrono::milliseconds timeout) = 0;
// Communication
virtual Result<void> write(uint8_t device_address, const uint8_t* data, size_t length) = 0;
virtual Result<void> read(uint8_t device_address, uint8_t* data, size_t length) = 0;
virtual Result<void> writeRead(uint8_t device_address,
const uint8_t* write_data, size_t write_length,
uint8_t* read_data, size_t read_length) = 0;
// Device Management
virtual Result<bool> probeDevice(uint8_t device_address) = 0;
virtual std::vector<uint8_t> scanBus() = 0;
// Status and Control
virtual bool isBusy() const = 0;
virtual I2CStatus getStatus() const = 0;
virtual Result<void> reset() = 0;
};
```
#### 3.1.3 ISPI
```cpp
class ISPI {
public:
virtual ~ISPI() = default;
// Configuration
virtual Result<void> configure(const SPIConfig& config) = 0;
virtual Result<void> addDevice(const SPIDeviceConfig& device_config) = 0;
virtual Result<void> removeDevice(SPIDeviceHandle device) = 0;
// Communication
virtual Result<void> transmit(SPIDeviceHandle device, const uint8_t* data, size_t length) = 0;
virtual Result<void> receive(SPIDeviceHandle device, uint8_t* data, size_t length) = 0;
virtual Result<void> transmitReceive(SPIDeviceHandle device,
const uint8_t* tx_data, uint8_t* rx_data, size_t length) = 0;
// DMA Support
virtual Result<void> transmitDMA(SPIDeviceHandle device, const uint8_t* data, size_t length) = 0;
virtual Result<void> receiveDMA(SPIDeviceHandle device, uint8_t* data, size_t length) = 0;
virtual bool isDMATransferComplete() const = 0;
// Status and Control
virtual SPIStatus getStatus() const = 0;
virtual Result<void> reset() = 0;
};
```
#### 3.1.4 IUART
```cpp
class IUART {
public:
virtual ~IUART() = default;
// Configuration
virtual Result<void> configure(const UARTConfig& config) = 0;
virtual Result<void> setBaudRate(uint32_t baud_rate) = 0;
virtual Result<void> setFlowControl(UARTFlowControl flow_control) = 0;
// Communication
virtual Result<size_t> write(const uint8_t* data, size_t length) = 0;
virtual Result<size_t> read(uint8_t* data, size_t length) = 0;
virtual Result<size_t> writeString(const std::string& str) = 0;
virtual Result<std::string> readString(size_t max_length) = 0;
// Buffering
virtual size_t getAvailableBytes() const = 0;
virtual size_t getTxBufferSpace() const = 0;
virtual Result<void> flush() = 0;
virtual Result<void> clearBuffers() = 0;
// Status and Control
virtual UARTStatus getStatus() const = 0;
virtual bool isConnected() const = 0;
};
```
#### 3.1.5 IGPIO
```cpp
class IGPIO {
public:
virtual ~IGPIO() = default;
// Pin Configuration
virtual Result<void> configurePin(GPIOPin pin, GPIOMode mode, GPIOPull pull = GPIOPull::NONE) = 0;
virtual Result<void> setDirection(GPIOPin pin, GPIODirection direction) = 0;
virtual Result<void> setPull(GPIOPin pin, GPIOPull pull) = 0;
virtual Result<void> setDriveStrength(GPIOPin pin, GPIODriveStrength strength) = 0;
// Digital I/O
virtual Result<void> writePin(GPIOPin pin, bool value) = 0;
virtual Result<bool> readPin(GPIOPin pin) = 0;
virtual Result<void> togglePin(GPIOPin pin) = 0;
// Interrupt Management
virtual Result<void> enableInterrupt(GPIOPin pin, GPIOInterruptType type,
GPIOInterruptHandler handler) = 0;
virtual Result<void> disableInterrupt(GPIOPin pin) = 0;
// Status
virtual GPIOPinStatus getPinStatus(GPIOPin pin) const = 0;
virtual std::vector<GPIOPin> getAvailablePins() const = 0;
};
```
#### 3.1.6 IADC
```cpp
class IADC {
public:
virtual ~IADC() = default;
// Configuration
virtual Result<void> configure(const ADCConfig& config) = 0;
virtual Result<void> configureChannel(ADCChannel channel, const ADCChannelConfig& config) = 0;
virtual Result<void> setAttenuation(ADCChannel channel, ADCAttenuation attenuation) = 0;
// Single Conversion
virtual Result<uint16_t> readRaw(ADCChannel channel) = 0;
virtual Result<float> readVoltage(ADCChannel channel) = 0;
virtual Result<float> readCalibrated(ADCChannel channel) = 0;
// Continuous Conversion
virtual Result<void> startContinuous(const std::vector<ADCChannel>& channels) = 0;
virtual Result<void> stopContinuous() = 0;
virtual Result<std::vector<uint16_t>> readContinuous() = 0;
// Calibration
virtual Result<void> calibrate(ADCChannel channel) = 0;
virtual Result<void> setCalibrationData(ADCChannel channel, const ADCCalibrationData& data) = 0;
// Status
virtual ADCStatus getStatus() const = 0;
virtual bool isChannelAvailable(ADCChannel channel) const = 0;
};
```
### 3.2 Required Interfaces
#### 3.2.1 ESP-IDF Hardware Drivers
- I2C driver APIs for I2C communication
- SPI driver APIs for SPI communication
- UART driver APIs for serial communication
- GPIO driver APIs for digital I/O
- ADC driver APIs for analog input
- PWM driver APIs for pulse generation
- Timer driver APIs for timing operations
#### 3.2.2 ILogger
- Hardware operation logging
- Error condition reporting
- Performance metrics logging
#### 3.2.3 IErrorHandler
- Hardware error reporting and classification
- Hardware fault recovery coordination
- Error escalation for critical hardware failures
## 4. Dynamic View
### 4.1 Hardware Initialization Sequence
```mermaid
sequenceDiagram
participant SYS as System Controller
participant HAL as HAL Controller
participant I2C as I2C Interface
participant SPI as SPI Interface
participant GPIO as GPIO Interface
participant RM as Resource Manager
SYS->>HAL: initialize()
HAL->>RM: initializeResourceManager()
RM-->>HAL: resource_manager_ready
par Parallel Initialization
HAL->>I2C: initialize(I2C_CONFIG)
I2C->>I2C: configureHardware()
I2C-->>HAL: i2c_ready
and
HAL->>SPI: initialize(SPI_CONFIG)
SPI->>SPI: configureHardware()
SPI-->>HAL: spi_ready
and
HAL->>GPIO: initialize(GPIO_CONFIG)
GPIO->>GPIO: configureHardware()
GPIO-->>HAL: gpio_ready
end
HAL->>HAL: validateHardwareStatus()
HAL-->>SYS: initialization_complete
```
### 4.2 I2C Communication Sequence
```mermaid
sequenceDiagram
participant SENSOR as Sensor Driver
participant I2C as I2C Interface
participant ESP_I2C as ESP-IDF I2C
participant HW as Hardware
SENSOR->>I2C: writeRead(device_addr, cmd_data, response_buffer)
I2C->>I2C: validateParameters()
I2C->>ESP_I2C: i2c_master_write_read_device()
ESP_I2C->>HW: hardware_transaction
HW-->>ESP_I2C: transaction_result
ESP_I2C-->>I2C: operation_result
alt Transaction Successful
I2C-->>SENSOR: success(response_data)
else Transaction Failed
I2C->>I2C: analyzeError()
I2C->>I2C: attemptRecovery()
I2C-->>SENSOR: error(error_code)
end
```
### 4.3 Resource Management Sequence
```mermaid
sequenceDiagram
participant COMP1 as Component 1
participant COMP2 as Component 2
participant RM as Resource Manager
participant HAL as HAL Controller
COMP1->>RM: reserveResource(I2C_PORT_0, COMPONENT_SENSOR)
RM->>RM: checkResourceAvailability(I2C_PORT_0)
RM->>RM: allocateResource(I2C_PORT_0, COMPONENT_SENSOR)
RM-->>COMP1: resource_reserved
COMP2->>RM: reserveResource(I2C_PORT_0, COMPONENT_DISPLAY)
RM->>RM: checkResourceAvailability(I2C_PORT_0)
RM-->>COMP2: resource_unavailable(already_allocated)
COMP1->>RM: releaseResource(I2C_PORT_0, COMPONENT_SENSOR)
RM->>RM: deallocateResource(I2C_PORT_0)
RM-->>COMP1: resource_released
COMP2->>RM: reserveResource(I2C_PORT_0, COMPONENT_DISPLAY)
RM->>RM: allocateResource(I2C_PORT_0, COMPONENT_DISPLAY)
RM-->>COMP2: resource_reserved
```
## 5. Hardware Resource Management
### 5.1 Resource Types
```cpp
enum class HardwareResource {
// Communication Interfaces
I2C_PORT_0,
I2C_PORT_1,
SPI_PORT_2,
SPI_PORT_3,
UART_PORT_0,
UART_PORT_1,
UART_PORT_2,
// GPIO Pins
GPIO_PIN_0,
GPIO_PIN_1,
// ... (all available GPIO pins)
// ADC Channels
ADC1_CHANNEL_0,
ADC1_CHANNEL_1,
// ... (all ADC channels)
// PWM Channels
PWM_CHANNEL_0,
PWM_CHANNEL_1,
// ... (all PWM channels)
// Timers
TIMER_GROUP_0_TIMER_0,
TIMER_GROUP_0_TIMER_1,
TIMER_GROUP_1_TIMER_0,
TIMER_GROUP_1_TIMER_1
};
```
### 5.2 Resource Allocation
```cpp
class ResourceManager {
public:
Result<void> reserveResource(HardwareResource resource, ComponentId component);
Result<void> releaseResource(HardwareResource resource, ComponentId component);
bool isResourceAvailable(HardwareResource resource) const;
ComponentId getResourceOwner(HardwareResource resource) const;
std::vector<HardwareResource> getResourcesByComponent(ComponentId component) const;
private:
std::map<HardwareResource, ComponentId> resource_allocations_;
std::mutex allocation_mutex_;
};
```
### 5.3 Conflict Resolution
- **Exclusive Access**: Most resources require exclusive access
- **Shared Access**: Some resources (like GPIO) can be shared with coordination
- **Priority-Based**: Higher priority components can preempt lower priority ones
- **Time-Based**: Resources can be allocated for specific time periods
## 6. Hardware Configuration
### 6.1 I2C Configuration
```cpp
struct I2CConfig {
uint32_t clock_speed_hz; // Clock frequency (100kHz, 400kHz, 1MHz)
GPIOPin sda_pin; // SDA pin number
GPIOPin scl_pin; // SCL pin number
bool pullup_enable; // Enable internal pullups
std::chrono::milliseconds timeout; // Transaction timeout
uint8_t slave_address; // Slave address (for slave mode)
I2CMode mode; // Master or slave mode
};
```
### 6.2 SPI Configuration
```cpp
struct SPIConfig {
uint32_t clock_speed_hz; // Clock frequency
GPIOPin mosi_pin; // MOSI pin number
GPIOPin miso_pin; // MISO pin number
GPIOPin sclk_pin; // SCLK pin number
SPIMode mode; // SPI mode (0, 1, 2, 3)
SPIBitOrder bit_order; // MSB or LSB first
bool use_dma; // Enable DMA transfers
size_t dma_buffer_size; // DMA buffer size
};
struct SPIDeviceConfig {
GPIOPin cs_pin; // Chip select pin
uint32_t clock_speed_hz; // Device-specific clock speed
SPIMode mode; // Device-specific SPI mode
uint8_t command_bits; // Command phase bits
uint8_t address_bits; // Address phase bits
uint8_t dummy_bits; // Dummy phase bits
};
```
### 6.3 UART Configuration
```cpp
struct UARTConfig {
uint32_t baud_rate; // Baud rate
UARTDataBits data_bits; // Data bits (5, 6, 7, 8)
UARTStopBits stop_bits; // Stop bits (1, 1.5, 2)
UARTParity parity; // Parity (none, even, odd)
UARTFlowControl flow_control; // Flow control (none, RTS/CTS)
GPIOPin tx_pin; // TX pin number
GPIOPin rx_pin; // RX pin number
GPIOPin rts_pin; // RTS pin number (if flow control enabled)
GPIOPin cts_pin; // CTS pin number (if flow control enabled)
size_t tx_buffer_size; // TX buffer size
size_t rx_buffer_size; // RX buffer size
};
```
### 6.4 GPIO Configuration
```cpp
enum class GPIOMode {
INPUT, // Input mode
OUTPUT, // Output mode
INPUT_OUTPUT, // Bidirectional mode
ANALOG // Analog mode (for ADC)
};
enum class GPIOPull {
NONE, // No pull resistor
PULLUP, // Pull-up resistor
PULLDOWN // Pull-down resistor
};
enum class GPIODriveStrength {
WEAK, // 5mA drive strength
MEDIUM, // 10mA drive strength
STRONG, // 20mA drive strength
MAXIMUM // 40mA drive strength
};
```
### 6.5 ADC Configuration
```cpp
struct ADCConfig {
ADCResolution resolution; // Resolution (9, 10, 11, 12 bits)
ADCAttenuation attenuation; // Attenuation (0dB, 2.5dB, 6dB, 11dB)
uint32_t sample_rate_hz; // Sample rate for continuous mode
bool enable_calibration; // Enable automatic calibration
};
struct ADCChannelConfig {
ADCAttenuation attenuation; // Channel-specific attenuation
uint32_t samples_per_read; // Number of samples to average
bool enable_filter; // Enable digital filter
};
```
## 7. Error Handling and Recovery
### 7.1 Hardware Error Types
```cpp
enum class HardwareError {
// Communication Errors
I2C_TIMEOUT,
I2C_NACK,
I2C_BUS_ERROR,
SPI_TIMEOUT,
SPI_DMA_ERROR,
UART_FRAME_ERROR,
UART_PARITY_ERROR,
UART_OVERRUN,
// Configuration Errors
INVALID_PIN_CONFIG,
RESOURCE_CONFLICT,
CLOCK_CONFIG_ERROR,
// Hardware Faults
PERIPHERAL_NOT_RESPONDING,
POWER_SUPPLY_ERROR,
CLOCK_FAILURE,
HARDWARE_FAULT
};
```
### 7.2 Recovery Strategies
```cpp
class HardwareErrorHandler {
public:
Result<void> handleError(HardwareError error, HardwareResource resource);
Result<void> resetPeripheral(HardwareResource resource);
Result<void> reinitializePeripheral(HardwareResource resource);
bool isRecoveryPossible(HardwareError error) const;
private:
Result<void> recoverI2CBus(I2CPort port);
Result<void> recoverSPIBus(SPIPort port);
Result<void> recoverUARTPort(UARTPort port);
Result<void> resetGPIOPin(GPIOPin pin);
};
```
### 7.3 Hardware Monitoring
- **Bus State Monitoring**: Monitor I2C/SPI bus states for errors
- **Signal Quality**: Monitor signal integrity and noise levels
- **Power Supply Monitoring**: Monitor supply voltages and current
- **Temperature Monitoring**: Monitor MCU temperature for thermal protection
## 8. Performance Optimization
### 8.1 DMA Integration
- **SPI DMA**: High-speed SPI transfers using DMA
- **UART DMA**: Efficient serial communication with DMA
- **ADC DMA**: Continuous ADC sampling with DMA
- **Memory Management**: Efficient DMA buffer management
### 8.2 Interrupt Handling
- **GPIO Interrupts**: Efficient GPIO interrupt handling
- **Communication Interrupts**: I2C/SPI/UART interrupt handling
- **Timer Interrupts**: Precise timing with hardware timers
- **Interrupt Prioritization**: Proper interrupt priority configuration
### 8.3 Power Management
- **Clock Gating**: Disable unused peripheral clocks
- **Sleep Modes**: Support for various sleep modes
- **Dynamic Frequency Scaling**: Adjust clock frequencies based on load
- **Peripheral Power Control**: Enable/disable peripherals as needed
## 9. Configuration
### 9.1 HAL Configuration
```cpp
struct HALConfig {
// I2C Configuration
std::map<I2CPort, I2CConfig> i2c_configs;
// SPI Configuration
std::map<SPIPort, SPIConfig> spi_configs;
// UART Configuration
std::map<UARTPort, UARTConfig> uart_configs;
// GPIO Configuration
std::map<GPIOPin, GPIOMode> gpio_configs;
// ADC Configuration
ADCConfig adc_config;
std::map<ADCChannel, ADCChannelConfig> adc_channel_configs;
// PWM Configuration
std::map<PWMChannel, PWMConfig> pwm_configs;
// Timer Configuration
std::map<TimerHandle, TimerConfig> timer_configs;
// Resource Management
bool strict_resource_checking;
bool allow_resource_sharing;
std::chrono::milliseconds resource_timeout;
};
```
## 10. Performance Characteristics
### 10.1 Timing Requirements
- **I2C Operations**: Standard (100kHz), Fast (400kHz), Fast+ (1MHz)
- **SPI Operations**: Up to 80MHz clock speed
- **UART Operations**: Up to 5Mbps baud rate
- **GPIO Operations**: < 1μs for digital I/O operations
- **ADC Operations**: Up to 83.3kSPS sample rate
### 10.2 Resource Usage
- **Memory**: < 16KB for HAL data structures and buffers
- **CPU**: Hardware-accelerated operations minimize CPU usage
- **Power**: Optimized for low-power operation with sleep modes
## 11. Testing Strategy
### 11.1 Unit Tests
- Individual peripheral interface functionality
- Resource management correctness
- Configuration validation
- Error handling and recovery
### 11.2 Integration Tests
- Multi-peripheral coordination
- Resource sharing scenarios
- Hardware fault injection
- Performance benchmarking
### 11.3 Hardware-in-the-Loop Tests
- Real hardware peripheral testing
- Signal integrity validation
- Timing accuracy verification
- Power consumption measurement
## 12. Dependencies
### 12.1 Internal Dependencies
- Logger for hardware operation logging
- Error Handler for hardware fault reporting
- Configuration Manager for hardware settings
### 12.2 External Dependencies
- ESP-IDF hardware driver APIs
- FreeRTOS for interrupt handling and synchronization
- Hardware peripheral specifications
- ESP32-S3 technical reference manual
## 13. Constraints and Assumptions
### 13.1 Constraints
- Limited to ESP32-S3 hardware capabilities
- Resource sharing limited by hardware design
- Performance limited by hardware specifications
- Power consumption constraints for battery operation
### 13.2 Assumptions
- Proper hardware design and connections
- Adequate power supply for all peripherals
- Proper signal integrity and noise immunity
- Hardware components within operating specifications
---
**Document Status:** Final for Implementation
**Dependencies:** ESP-IDF Hardware Drivers, Logger, Error Handler, Configuration Manager
**Next Review:** After component implementation and hardware validation