# Bluetooth Wrapper Module

## Overview

The Bluetooth wrapper module provides a C++ object-oriented interface for ESP-IDF Bluetooth functionality. This module encapsulates the ESP-IDF Bluetooth and BLE (Bluetooth Low Energy) driver functions and provides a clean, easy-to-use API for Bluetooth Classic, BLE, and dual-mode operations.

## Features

- **Multiple Modes**: Bluetooth Classic, BLE, and dual-mode support
- **BLE Advertising**: Configurable advertising parameters and data
- **BLE Scanning**: Network discovery and device scanning
- **GATT Server**: Create services and characteristics
- **GATT Client**: Connect to and interact with remote devices
- **Event Handling**: Comprehensive event callbacks for all operations
- **Security Support**: Pairing, bonding, and encryption
- **Power Management**: Configurable TX power levels

## Architecture

### Class Diagram

```
┌─────────────────────────────────────┐
│            Bluetooth                │
├─────────────────────────────────────┤
│ - m_isInitialized_: bool            │
│ - m_mode_: BtMode                   │
│ - m_connectionState_: State         │
│ - m_connectedDeviceCount_: uint8_t  │
│ - m_gattsIf_: esp_gatt_if_t         │
│ - m_gattcIf_: esp_gatt_if_t         │
│ - m_appId_: uint16_t                │
│ - m_gapCallback_: Callback          │
│ - m_gattsCallback_: Callback        │
│ - m_gattcCallback_: Callback        │
├─────────────────────────────────────┤
│ + Bluetooth()                       │
│ + ~Bluetooth()                      │
│ + initialize(mode): bool            │
│ + deinitialize(): bool              │
│ + setDeviceName(name): bool         │
│ + getDeviceName(name, len): bool    │
│ + setAdvParams(params): bool        │
│ + setAdvData(data): bool            │
│ + startAdvertising(): bool          │
│ + stopAdvertising(): bool           │
│ + startScanning(duration): bool     │
│ + stopScanning(): bool              │
│ + createGattService(svc): uint16_t  │
│ + addCharacteristic(...): uint16_t  │
│ + startGattService(handle): bool    │
│ + stopGattService(handle): bool     │
│ + sendNotification(...): bool       │
│ + sendIndication(...): bool         │
│ + connectToDevice(...): bool        │
│ + disconnectDevice(connId): bool    │
│ + getConnectionState(): State       │
│ + isConnected(): bool               │
│ + getConnectedDeviceCount(): uint8_t│
│ + setGapEventCallback(...): void    │
│ + setGattsEventCallback(...): void  │
│ + setGattcEventCallback(...): void  │
│ + getMacAddress(mac): bool          │
│ + setTxPower(type, level): bool     │
│ + getTxPower(type): esp_power_level │
│ + isInitialized(): bool             │
│ + getDefaultAdvParams(): Params     │
│ + getDefaultAdvData(): Data         │
│ + getDefaultGattService(): Service  │
│ + getDefaultGattChar(): Char        │
│ - gapEventHandler(...): void        │
│ - gattsEventHandler(...): void      │
│ - gattcEventHandler(...): void      │
│ - convertMode(mode): esp_bt_mode_t  │
│ - convertAdvType(type): esp_adv_t   │
└─────────────────────────────────────┘
```

### Enumerations

#### BtMode
- `CLASSIC`: Bluetooth Classic mode
- `BLE`: Bluetooth Low Energy mode
- `DUAL`: Dual mode (Classic + BLE)

#### BleAdvType
- `ADV_IND`: Connectable undirected advertising
- `ADV_DIRECT_IND_HIGH`: Connectable directed advertising (high duty cycle)
- `ADV_SCAN_IND`: Scannable undirected advertising
- `ADV_NONCONN_IND`: Non-connectable undirected advertising
- `ADV_DIRECT_IND_LOW`: Connectable directed advertising (low duty cycle)

#### BleConnectionState
- `DISCONNECTED`: Not connected
- `CONNECTING`: Connection in progress
- `CONNECTED`: Successfully connected
- `DISCONNECTING`: Disconnection in progress

### Configuration Structures

#### BleAdvParams
```cpp
struct BleAdvParams {
    uint16_t advIntMin;         // Minimum advertising interval
    uint16_t advIntMax;         // Maximum advertising interval
    BleAdvType advType;         // Advertising type
    uint8_t ownAddrType;        // Own address type
    uint8_t peerAddrType;       // Peer address type
    uint8_t peerAddr[6];        // Peer address
    uint8_t channelMap;         // Channel map
    uint8_t advFilterPolicy;    // Advertising filter policy
};
```

#### BleAdvData
```cpp
struct BleAdvData {
    bool setName;               // Set device name in advertising data
    bool setTxPower;            // Set TX power in advertising data
    bool includeUuid;           // Include service UUID
    bool setManufacturerData;   // Set manufacturer data
    uint16_t appearance;        // Device appearance
    uint16_t manufacturerId;    // Manufacturer ID
    uint8_t manufacturerDataLen; // Manufacturer data length
    uint8_t* manufacturerData;  // Manufacturer data
    uint8_t serviceUuidLen;     // Service UUID length
    uint8_t* serviceUuid;       // Service UUID
    char* deviceName;           // Device name
};
```

#### GattService
```cpp
struct GattService {
    uint16_t serviceId;         // Service ID
    uint16_t serviceUuid;       // Service UUID
    uint16_t numHandles;        // Number of handles
    bool isPrimary;             // Primary service flag
};
```

#### GattCharacteristic
```cpp
struct GattCharacteristic {
    uint16_t charUuid;          // Characteristic UUID
    uint8_t properties;         // Characteristic properties
    uint8_t permissions;        // Characteristic permissions
    uint16_t maxLen;            // Maximum value length
    bool autoRsp;               // Auto response flag
};
```

## Usage Examples

### Basic BLE Advertising

```cpp
#include "bt.hpp"

// BLE event callback
void bleGapCallback(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param, void* userData) {
    switch (event) {
        case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
            printf("Advertising started\n");
            break;
        case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT:
            printf("Advertising stopped\n");
            break;
        default:
            break;
    }
}

// Create Bluetooth instance
Bluetooth bt;

// Initialize BLE
bt.initialize(BtMode::BLE);

// Set device name
bt.setDeviceName("ESP32-BLE-Device");

// Set event callback
bt.setGapEventCallback(bleGapCallback, nullptr);

// Configure advertising
BleAdvParams advParams = Bluetooth::getDefaultAdvParams();
advParams.advIntMin = 0x20;  // 20ms
advParams.advIntMax = 0x40;  // 40ms

bt.setAdvParams(advParams);

// Set advertising data
BleAdvData advData = Bluetooth::getDefaultAdvData();
advData.setName = true;
advData.setTxPower = true;

bt.setAdvData(advData);

// Start advertising
bt.startAdvertising();
```

### BLE GATT Server

```cpp
// GATT server event callback
void bleGattsCallback(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, 
                      esp_ble_gatts_cb_param_t* param, void* userData) {
    switch (event) {
        case ESP_GATTS_CONNECT_EVT:
            printf("Client connected\n");
            break;
        case ESP_GATTS_DISCONNECT_EVT:
            printf("Client disconnected\n");
            break;
        case ESP_GATTS_READ_EVT:
            printf("Characteristic read request\n");
            break;
        case ESP_GATTS_WRITE_EVT:
            printf("Characteristic write request\n");
            break;
        default:
            break;
    }
}

// Set GATT server callback
bt.setGattsEventCallback(bleGattsCallback, nullptr);

// Create a service
GattService service = Bluetooth::getDefaultGattService();
service.serviceUuid = 0x180F;  // Battery Service
service.numHandles = 4;

uint16_t serviceHandle = bt.createGattService(service);

// Add characteristic
GattCharacteristic characteristic = Bluetooth::getDefaultGattCharacteristic();
characteristic.charUuid = 0x2A19;  // Battery Level
characteristic.properties = ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY;

uint16_t charHandle = bt.addCharacteristic(serviceHandle, characteristic);

// Start the service
bt.startGattService(serviceHandle);
```

### BLE Scanning

```cpp
// Scanning callback
void bleScanCallback(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param, void* userData) {
    switch (event) {
        case ESP_GAP_BLE_SCAN_RESULT_EVT: {
            esp_ble_gap_cb_param_t* scanResult = param;
            if (scanResult->scan_rst.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
                printf("Found device: ");
                for (int i = 0; i < 6; i++) {
                    printf("%02X", scanResult->scan_rst.bda[i]);
                    if (i < 5) printf(":");
                }
                printf(" RSSI: %d\n", scanResult->scan_rst.rssi);
            }
            break;
        }
        case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
            printf("Scan started\n");
            break;
        case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
            printf("Scan stopped\n");
            break;
        default:
            break;
    }
}

// Set scan callback
bt.setGapEventCallback(bleScanCallback, nullptr);

// Start scanning for 10 seconds
bt.startScanning(10);
```

### BLE Client Connection

```cpp
// GATT client callback
void bleGattcCallback(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, 
                      esp_ble_gattc_cb_param_t* param, void* userData) {
    switch (event) {
        case ESP_GATTC_CONNECT_EVT:
            printf("Connected to server\n");
            break;
        case ESP_GATTC_DISCONNECT_EVT:
            printf("Disconnected from server\n");
            break;
        case ESP_GATTC_SEARCH_CMPL_EVT:
            printf("Service discovery complete\n");
            break;
        default:
            break;
    }
}

// Set GATT client callback
bt.setGattcEventCallback(bleGattcCallback, nullptr);

// Connect to remote device
uint8_t remoteAddr[6] = {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC};
bt.connectToDevice(remoteAddr, BLE_ADDR_TYPE_PUBLIC);
```

### Dual Mode Operation

```cpp
// Initialize in dual mode
bt.initialize(BtMode::DUAL);

// Set up BLE advertising
bt.setDeviceName("ESP32-Dual-Mode");
bt.startAdvertising();

// Also available for Bluetooth Classic operations
// (Classic Bluetooth APIs would be used here)
```

## API Reference

### Constructor/Destructor

- **Bluetooth()**: Initialize Bluetooth wrapper instance
- **~Bluetooth()**: Clean up resources and deinitialize Bluetooth

### Initialization Methods

- **initialize(mode)**: Initialize Bluetooth stack with specified mode
- **deinitialize()**: Deinitialize Bluetooth stack
- **isInitialized()**: Check if Bluetooth is initialized

### Device Configuration

- **setDeviceName(name)**: Set Bluetooth device name
- **getDeviceName(name, maxLen)**: Get current device name
- **getMacAddress(mac)**: Get Bluetooth MAC address

### BLE Advertising

- **setAdvParams(params)**: Set advertising parameters
- **setAdvData(advData)**: Set advertising data
- **startAdvertising()**: Start BLE advertising
- **stopAdvertising()**: Stop BLE advertising

### BLE Scanning

- **startScanning(duration)**: Start BLE scanning
- **stopScanning()**: Stop BLE scanning

### GATT Server

- **createGattService(service)**: Create GATT service
- **addCharacteristic(serviceHandle, characteristic)**: Add characteristic to service
- **startGattService(serviceHandle)**: Start GATT service
- **stopGattService(serviceHandle)**: Stop GATT service
- **sendNotification(connId, attrHandle, data, dataLen)**: Send notification
- **sendIndication(connId, attrHandle, data, dataLen)**: Send indication

### GATT Client

- **connectToDevice(remoteAddr, addrType)**: Connect to remote device
- **disconnectDevice(connId)**: Disconnect from device

### Connection Management

- **getConnectionState()**: Get current connection state
- **isConnected()**: Check if any device is connected
- **getConnectedDeviceCount()**: Get number of connected devices

### Event Handling

- **setGapEventCallback(callback, userData)**: Set GAP event callback
- **setGattsEventCallback(callback, userData)**: Set GATT server callback
- **setGattcEventCallback(callback, userData)**: Set GATT client callback

### Power Management

- **setTxPower(powerType, powerLevel)**: Set TX power level
- **getTxPower(powerType)**: Get current TX power level

### Configuration Methods

- **getDefaultAdvParams()**: Get default advertising parameters
- **getDefaultAdvData()**: Get default advertising data
- **getDefaultGattService()**: Get default GATT service configuration
- **getDefaultGattCharacteristic()**: Get default characteristic configuration

## Error Handling

The module provides comprehensive error handling:
- Initialization status checks
- ESP-IDF error codes are caught and logged
- Return values indicate success/failure for all operations
- Event callbacks for asynchronous status updates
- Automatic cleanup of resources on errors

## Dependencies

- ESP-IDF Bluetooth stack (`esp_bt.h`, `esp_bt_main.h`)
- ESP-IDF BLE GAP API (`esp_gap_ble_api.h`)
- ESP-IDF GATT server API (`esp_gatts_api.h`)
- ESP-IDF GATT client API (`esp_gattc_api.h`)
- NVS flash storage (`nvs_flash.h`)
- ESP-IDF error handling (`esp_err.h`)
- ESP-IDF logging (`esp_log.h`)

## Thread Safety

The Bluetooth wrapper uses ESP-IDF's thread-safe Bluetooth stack. Event callbacks are called from the Bluetooth task context and should be kept short.

## Memory Usage

- Fixed memory footprint per instance
- Bluetooth stack uses significant RAM (configurable)
- GATT database stored in flash/RAM
- Event callbacks use minimal stack space

## Performance Considerations

- Bluetooth operations are asynchronous with event callbacks
- GATT operations have latency depending on connection interval
- Multiple simultaneous connections increase memory usage
- Advertising and scanning affect power consumption

## Security Features

### Pairing and Bonding
- Support for various pairing methods
- Secure Simple Pairing (SSP)
- Out-of-Band (OOB) authentication
- Passkey entry and numeric comparison

### Encryption
- AES-128 encryption for BLE
- Link-level security
- Application-level encryption support

## Power Management

### BLE Power Optimization
- Configurable advertising intervals
- Connection interval optimization
- Sleep mode support
- TX power control

### Connection Parameters
- Minimum/maximum connection intervals
- Slave latency configuration
- Supervision timeout settings

## Common Use Cases

### IoT Sensor Node
- BLE advertising with sensor data
- GATT server for configuration
- Low power operation
- Mobile app connectivity

### BLE Gateway
- Multiple device connections
- Data aggregation and forwarding
- WiFi + BLE dual connectivity
- Cloud integration

### HID Device
- Keyboard/mouse emulation
- Custom HID reports
- Pairing and bonding
- Battery level reporting

### Beacon Applications
- iBeacon/Eddystone protocols
- Proximity detection
- Asset tracking
- Location services

## Troubleshooting

### Common Issues

1. **Initialization Failures**: Check NVS partition and Bluetooth configuration
2. **Connection Issues**: Verify advertising parameters and device compatibility
3. **GATT Errors**: Check service/characteristic UUIDs and permissions
4. **Memory Issues**: Monitor heap usage, especially with multiple connections
5. **Range Problems**: Check TX power settings and antenna configuration

### Debug Tips

1. Enable Bluetooth logging in menuconfig
2. Use ESP-IDF Bluetooth tools for analysis
3. Monitor connection parameters
4. Check for interference on 2.4GHz band
5. Verify security requirements and capabilities