# ESP-IDF Firmware Wrappers

## Overview

This directory contains C++ object-oriented wrappers for ESP-IDF peripheral drivers. Each wrapper provides a clean, easy-to-use interface that encapsulates the ESP-IDF C APIs while maintaining full functionality and performance.

## Architecture

The wrapper architecture follows these principles:

- **Object-Oriented Design**: Each peripheral is wrapped in a C++ class
- **RAII Pattern**: Resources are automatically managed through constructors/destructors
- **Error Handling**: Comprehensive error checking with ESP-IDF error code logging
- **Type Safety**: Strong typing with enumerations instead of magic numbers
- **Documentation**: Full Doxygen documentation for all public APIs
- **Naming Convention**: Follows project coding guidelines (snake_case files, PascalCase classes)

## Implemented Modules

### ✅ GPIO Wrapper (`gpio/`)
- **Status**: Complete
- **Features**: Pin configuration, digital I/O, interrupt handling, pin validation
- **Key Classes**: `Gpio`
- **Dependencies**: `driver/gpio.h`, `esp_err.h`, `esp_log.h`

### ✅ UART Wrapper (`uart/`)
- **Status**: Complete  
- **Features**: Multi-port support, configurable parameters, timeout support, flow control
- **Key Classes**: `Uart`
- **Dependencies**: `driver/uart.h`, `esp_err.h`, `esp_log.h`, `freertos/FreeRTOS.h`

### ✅ I2C Wrapper (`i2c/`)
- **Status**: Complete
- **Features**: Master/slave modes, register operations, bus scanning, timeout support
- **Key Classes**: `I2c`
- **Dependencies**: `driver/i2c.h`, `esp_err.h`, `esp_log.h`, `freertos/FreeRTOS.h`

### ✅ SPI Wrapper (`spi/`)
- **Status**: Complete
- **Features**: Multi-host support, device management, DMA support, command/address phases
- **Key Classes**: `Spi`
- **Dependencies**: `driver/spi_master.h`, `esp_err.h`, `esp_log.h`

### ✅ ADC Wrapper (`adc/`)
- **Status**: Complete
- **Features**: Multi-unit/channel support, automatic calibration, averaging, multiple resolutions
- **Key Classes**: `Adc`
- **Dependencies**: `esp_adc/adc_oneshot.h`, `esp_adc/adc_cali.h`, `esp_err.h`, `esp_log.h`

### ✅ WiFi Wrapper (`wifi/`)
- **Status**: Complete
- **Features**: STA/AP/APSTA modes, network scanning, event handling, security support
- **Key Classes**: `Wifi`
- **Dependencies**: `esp_wifi.h`, `esp_netif.h`, `esp_event.h`, `nvs_flash.h`

### ✅ DMA Wrapper (`dma/`)
- **Status**: Complete
- **Features**: GDMA channel management, memory transfers, descriptor management, DMA-capable memory allocation
- **Key Classes**: `Dma`
- **Dependencies**: `driver/gdma.h`, `esp_dma_utils.h`, `esp_hw_support`, `esp_heap_caps.h`

### ✅ Bluetooth Wrapper (`bt/`)
- **Status**: Complete
- **Features**: BLE/Classic/Dual modes, GATT server/client, advertising, scanning, pairing
- **Key Classes**: `Bluetooth`
- **Dependencies**: `esp_bt.h`, `esp_gap_ble_api.h`, `esp_gatts_api.h`, `esp_gattc_api.h`, `nvs_flash.h`

## Directory Structure

```
ESP_IDF_FW_wrappers/
├── README.md                    # This overview document
├── gpio/
│   ├── com/
│   │   ├── gpio.hpp            # GPIO wrapper header
│   │   └── gpio.cpp            # GPIO wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # GPIO module documentation
├── uart/
│   ├── com/
│   │   ├── uart.hpp            # UART wrapper header
│   │   └── uart.cpp            # UART wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # UART module documentation
├── i2c/
│   ├── com/
│   │   ├── i2c.hpp             # I2C wrapper header
│   │   └── i2c.cpp             # I2C wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # I2C module documentation
├── spi/
│   ├── com/
│   │   ├── spi.hpp             # SPI wrapper header
│   │   └── spi.cpp             # SPI wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # SPI module documentation
├── adc/
│   ├── com/
│   │   ├── adc.hpp             # ADC wrapper header
│   │   └── adc.cpp             # ADC wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # ADC module documentation
├── wifi/
│   ├── com/
│   │   ├── wifi.hpp            # WiFi wrapper header
│   │   └── wifi.cpp            # WiFi wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # WiFi module documentation
├── bt/                         # Bluetooth wrapper (✅ Complete)
│   ├── com/
│   │   ├── bt.hpp              # Bluetooth wrapper header
│   │   └── bt.cpp              # Bluetooth wrapper implementation
│   ├── test/                   # Unit tests (empty)
│   ├── CMakeLists.txt          # Build configuration
│   └── README.md               # Bluetooth module documentation
└── dma/                        # DMA wrapper (✅ Complete)
    ├── com/
    │   ├── dma.hpp             # DMA wrapper header
    │   └── dma.cpp             # DMA wrapper implementation
    ├── test/                   # Unit tests (empty)
    ├── CMakeLists.txt          # Build configuration
    └── README.md               # DMA module documentation
```

## Usage Examples

### Basic GPIO Usage
```cpp
#include "gpio.hpp"

Gpio gpio;
gpio.configure(2, GpioMode::OUTPUT);
gpio.setLevel(2, 1);  // Set pin high
```

### UART Communication
```cpp
#include "uart.hpp"

Uart uart;
UartConfig config = Uart::getDefaultConfig();
config.baudrate = UartBaudrate::BAUD_115200;
config.txPin = 1;
config.rxPin = 3;

uart.initialize(UartPort::PORT_0, config);
uart.transmit(UartPort::PORT_0, (uint8_t*)"Hello", 5);
```

### I2C Device Communication
```cpp
#include "i2c.hpp"

I2c i2c;
I2cConfig config = I2c::getDefaultConfig();
i2c.initialize(I2cPort::PORT_0, config);

uint8_t data[] = {0x01, 0x02};
i2c.write(I2cPort::PORT_0, 0x48, data, sizeof(data));
```

### SPI Device Communication
```cpp
#include "spi.hpp"

Spi spi;
SpiBusConfig busConfig = Spi::getDefaultBusConfig();
spi.initializeBus(SpiHost::SPI2_HOST, busConfig);

SpiDeviceConfig deviceConfig = Spi::getDefaultDeviceConfig();
spi_device_handle_t device;
spi.addDevice(SpiHost::SPI2_HOST, deviceConfig, &device);

uint8_t txData[] = {0xAA, 0x55};
uint8_t rxData[2];
spi.transmit(device, txData, rxData, 2);
```

### ADC Reading
```cpp
#include "adc.hpp"

Adc adc;
adc.initializeUnit(AdcUnit::UNIT_1, AdcBitwidth::WIDTH_12BIT);

AdcChannelConfig config = Adc::getDefaultChannelConfig();
adc.configureChannel(config);

int32_t voltage = adc.readVoltage(AdcUnit::UNIT_1, AdcChannel::CHANNEL_0);
```

### WiFi Connection
```cpp
#include "wifi.hpp"

Wifi wifi;
WifiConfig config = {};
config.mode = WifiMode::STA;
config.staConfig = Wifi::getDefaultStaConfig();
strcpy(config.staConfig.ssid, "MyNetwork");
strcpy(config.staConfig.password, "MyPassword");

wifi.initialize(config);
wifi.start();
wifi.connect();
```

## Build Integration

Each wrapper is a separate ESP-IDF component with its own `CMakeLists.txt`. To use a wrapper in your application:

1. Add the wrapper component to your project's `CMakeLists.txt`:
```cmake
set(EXTRA_COMPONENT_DIRS "components/ESP_IDF_FW_wrappers/gpio")
```

2. Include the wrapper in your component's dependencies:
```cmake
idf_component_register(
    SRCS "main.cpp"
    INCLUDE_DIRS "."
    REQUIRES gpio_wrapper
)
```

3. Include the header in your code:
```cpp
#include "gpio.hpp"
```

## Design Patterns

### RAII (Resource Acquisition Is Initialization)
All wrappers follow RAII principles:
- Resources are acquired in constructors
- Resources are released in destructors
- Exception safety through automatic cleanup

### Error Handling
Consistent error handling across all wrappers:
- Boolean return values for success/failure
- Negative return values for error conditions
- ESP-IDF error codes logged with descriptive messages
- Input parameter validation

### Configuration Structures
Each wrapper provides configuration structures:
- Default configuration functions
- Type-safe enumerations
- Clear parameter documentation

## Testing

Each wrapper includes a `test/` directory for unit tests (currently empty). Future development should include:
- Unit tests for all public APIs
- Integration tests with real hardware
- Performance benchmarks
- Memory usage tests

## Future Development

### All Core Modules Implemented

All 8 core ESP-IDF peripheral wrapper modules have been successfully implemented:
- GPIO, UART, I2C, SPI, ADC, WiFi, DMA, and Bluetooth wrappers are complete
- Each module includes full functionality, documentation, and usage examples

### Enhancements for Existing Modules

1. **GPIO**
   - Matrix keyboard support
   - PWM integration
   - Capacitive touch support

2. **UART**
   - RS485 support
   - Pattern detection
   - DMA integration

3. **I2C**
   - Multi-master support
   - Clock stretching
   - 10-bit addressing

4. **SPI**
   - Slave mode support
   - Quad SPI support
   - LCD interface support

5. **ADC**
   - Continuous mode
   - DMA integration
   - Multi-channel simultaneous sampling

6. **WiFi**
   - WPS support
   - Mesh networking
   - Enterprise security

## Contributing

When contributing to the wrapper modules:

1. Follow the established coding guidelines in `6 Guidelines.md`
2. Maintain consistent API design across modules
3. Include comprehensive documentation
4. Add unit tests for new functionality
5. Update the module's README.md file
6. Ensure thread safety where applicable

## Performance Considerations

- All wrappers provide minimal overhead over direct ESP-IDF calls
- RAII pattern ensures efficient resource management
- Inline functions used where appropriate
- No dynamic memory allocation in critical paths
- Direct ESP-IDF function calls for optimal performance

## Memory Usage

- Fixed memory footprint per wrapper instance
- No hidden dynamic allocations
- Resource handles managed efficiently
- Stack-based configuration structures

## Thread Safety

- GPIO: Not thread-safe, requires external synchronization
- UART: Thread-safe (ESP-IDF driver is thread-safe)
- I2C: Thread-safe for different ports, synchronize access to same port
- SPI: Thread-safe (ESP-IDF driver is thread-safe)
- ADC: Thread-safe (ESP-IDF driver is thread-safe)
- WiFi: Thread-safe (ESP-IDF driver is thread-safe)

## Compatibility

- **ESP-IDF Version**: v5.x
- **ESP32 Variants**: ESP32, ESP32-S2, ESP32-S3, ESP32-C3, ESP32-C6
- **Compiler**: GCC with C++11 or later
- **Build System**: CMake-based ESP-IDF build system