# WiFi Wrapper Module

## Overview

The WiFi wrapper module provides a C++ object-oriented interface for ESP-IDF WiFi functionality. This module encapsulates the ESP-IDF WiFi driver functions and provides a clean, easy-to-use API for WiFi station and access point operations.

## Features

- **Multiple Modes**: Station (STA), Access Point (AP), and combined (AP+STA) modes
- **Network Scanning**: Scan for available WiFi networks
- **Event Handling**: Asynchronous event callbacks for connection status
- **Security Support**: Multiple authentication modes (Open, WEP, WPA/WPA2/WPA3)
- **Network Information**: IP address, MAC address, RSSI retrieval
- **AP Management**: Connected stations monitoring in AP mode
- **Error Handling**: Comprehensive error checking and logging

## Architecture

### Class Diagram

```
┌─────────────────────────────────────┐
│              Wifi                   │
├─────────────────────────────────────┤
│ - m_isInitialized_: bool            │
│ - m_connectionStatus_: Status       │
│ - m_config_: WifiConfig             │
│ - m_netifSta_: esp_netif_t*         │
│ - m_netifAp_: esp_netif_t*          │
│ - m_eventCallback_: Callback        │
│ - m_eventCallbackArg_: void*        │
├─────────────────────────────────────┤
│ + Wifi()                            │
│ + ~Wifi()                           │
│ + initialize(config): bool          │
│ + deinitialize(): bool              │
│ + start(): bool                     │
│ + stop(): bool                      │
│ + connect(): bool                   │
│ + disconnect(): bool                │
│ + scan(...): int32_t                │
│ + getConnectionStatus(): Status     │
│ + isConnected(): bool               │
│ + getRssi(): int32_t                │
│ + getIpAddress(ip, len): bool       │
│ + getMacAddress(mac, mode): bool    │
│ + setEventCallback(cb, arg): void   │
│ + getConnectedStations(): int32_t   │
│ + isInitialized(): bool             │
│ + getDefaultStaConfig(): StaConfig  │
│ + getDefaultApConfig(): ApConfig    │
│ - convertMode(mode): wifi_mode_t    │
│ - convertAuthMode(auth): wifi_auth  │
│ - wifiEventHandler(...): void       │
│ - ipEventHandler(...): void         │
└─────────────────────────────────────┘
```

### Enumerations

#### WifiMode
- `NONE`: WiFi disabled
- `STA`: Station mode (client)
- `AP`: Access Point mode (server)
- `APSTA`: Combined AP + STA mode

#### WifiAuthMode
- `OPEN`: No authentication
- `WEP`: WEP encryption
- `WPA_PSK`: WPA with pre-shared key
- `WPA2_PSK`: WPA2 with pre-shared key
- `WPA_WPA2_PSK`: WPA/WPA2 mixed mode
- `WPA3_PSK`: WPA3 with pre-shared key
- `WPA2_WPA3_PSK`: WPA2/WPA3 mixed mode

#### WifiConnectionStatus
- `DISCONNECTED`: Not connected
- `CONNECTING`: Connection in progress
- `CONNECTED`: Successfully connected
- `FAILED`: Connection failed

### Configuration Structures

#### WifiStaConfig
```cpp
struct WifiStaConfig {
    char ssid[32];             // SSID of target AP
    char password[64];         // Password of target AP
    WifiAuthMode authMode;     // Authentication mode
    bool pmfRequired;          // Protected Management Frame required
    uint8_t channel;           // Channel of target AP (0 = auto)
    int8_t rssiThreshold;      // Minimum RSSI threshold
};
```

#### WifiApConfig
```cpp
struct WifiApConfig {
    char ssid[32];             // SSID of AP
    char password[64];         // Password of AP
    WifiAuthMode authMode;     // Authentication mode
    uint8_t channel;           // Channel number
    uint8_t maxConnections;    // Maximum number of connections
    bool ssidHidden;           // Hide SSID
};
```

#### WifiConfig
```cpp
struct WifiConfig {
    WifiMode mode;             // WiFi mode
    WifiStaConfig staConfig;   // Station configuration
    WifiApConfig apConfig;     // Access Point configuration
};
```

## Usage Examples

### Station Mode (Client)

```cpp
#include "wifi.hpp"

// WiFi event callback
void wifiEventCallback(WifiConnectionStatus status, void* arg) {
    switch (status) {
        case WifiConnectionStatus::CONNECTED:
            printf("WiFi connected!\n");
            break;
        case WifiConnectionStatus::DISCONNECTED:
            printf("WiFi disconnected!\n");
            break;
        default:
            break;
    }
}

// Create WiFi instance
Wifi wifi;

// Configure WiFi
WifiConfig config = {};
config.mode = WifiMode::STA;
config.staConfig = Wifi::getDefaultStaConfig();
strcpy(config.staConfig.ssid, "MyWiFiNetwork");
strcpy(config.staConfig.password, "MyPassword");
config.staConfig.authMode = WifiAuthMode::WPA2_PSK;

// Set event callback
wifi.setEventCallback(wifiEventCallback, nullptr);

// Initialize and start WiFi
wifi.initialize(config);
wifi.start();
wifi.connect();

// Get IP address when connected
char ip[16];
if (wifi.getIpAddress(ip, sizeof(ip))) {
    printf("IP Address: %s\n", ip);
}
```

### Access Point Mode (Server)

```cpp
// Configure as Access Point
WifiConfig apConfig = {};
apConfig.mode = WifiMode::AP;
apConfig.apConfig = Wifi::getDefaultApConfig();
strcpy(apConfig.apConfig.ssid, "ESP32-Hotspot");
strcpy(apConfig.apConfig.password, "12345678");
apConfig.apConfig.authMode = WifiAuthMode::WPA2_PSK;
apConfig.apConfig.channel = 6;
apConfig.apConfig.maxConnections = 4;

wifi.initialize(apConfig);
wifi.start();

// Monitor connected stations
int32_t connectedStations = wifi.getConnectedStations();
printf("Connected stations: %ld\n", connectedStations);
```

### Network Scanning

```cpp
// Scan for available networks
WifiScanResult results[20];
int32_t networkCount = wifi.scan(results, 20, 5000);  // 5 second scan

printf("Found %ld networks:\n", networkCount);
for (int i = 0; i < networkCount; i++) {
    printf("SSID: %s, RSSI: %d dBm, Channel: %d\n", 
           results[i].ssid, results[i].rssi, results[i].channel);
}
```

### Combined AP+STA Mode

```cpp
WifiConfig combinedConfig = {};
combinedConfig.mode = WifiMode::APSTA;

// Configure STA
combinedConfig.staConfig = Wifi::getDefaultStaConfig();
strcpy(combinedConfig.staConfig.ssid, "InternetRouter");
strcpy(combinedConfig.staConfig.password, "RouterPassword");

// Configure AP
combinedConfig.apConfig = Wifi::getDefaultApConfig();
strcpy(combinedConfig.apConfig.ssid, "ESP32-Bridge");
strcpy(combinedConfig.apConfig.password, "BridgePassword");

wifi.initialize(combinedConfig);
wifi.start();
wifi.connect();  // Connect to internet router
```

## API Reference

### Constructor/Destructor

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

### Initialization Methods

- **initialize(config)**: Initialize WiFi with configuration
- **deinitialize()**: Deinitialize WiFi and clean up resources
- **isInitialized()**: Check if WiFi is initialized

### Control Methods

- **start()**: Start WiFi (required after initialization)
- **stop()**: Stop WiFi operations
- **connect()**: Connect to network (STA mode)
- **disconnect()**: Disconnect from network

### Information Methods

- **getConnectionStatus()**: Get current connection status
- **isConnected()**: Check if connected to network
- **getRssi()**: Get signal strength of current connection
- **getIpAddress(ip, maxLen)**: Get IP address string
- **getMacAddress(mac, mode)**: Get MAC address

### Scanning Methods

- **scan(results, maxResults, scanTimeMs)**: Scan for available networks

### Event Handling

- **setEventCallback(callback, arg)**: Set connection event callback

### Access Point Methods

- **getConnectedStations()**: Get number of connected stations (AP mode)

### Configuration Methods

- **getDefaultStaConfig()**: Get default station configuration
- **getDefaultApConfig()**: Get default AP 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
- Detailed logging for debugging and troubleshooting

## Dependencies

- ESP-IDF WiFi driver (`esp_wifi.h`)
- ESP-IDF network interface (`esp_netif.h`)
- ESP-IDF event system (`esp_event.h`)
- NVS flash storage (`nvs_flash.h`)
- ESP-IDF error handling (`esp_err.h`)
- ESP-IDF logging (`esp_log.h`)

## Thread Safety

The WiFi wrapper uses ESP-IDF's thread-safe WiFi driver and event system. Multiple tasks can safely call WiFi functions simultaneously.

## Memory Usage

- Fixed memory footprint per instance
- Network interface handles managed by ESP-IDF
- Event system uses minimal memory for callbacks

## Performance Considerations

- Asynchronous connection process with event callbacks
- Network scanning can take several seconds
- WiFi operations may affect other radio functions (Bluetooth)
- Power management considerations for battery-powered devices

## Security Considerations

- Use WPA2 or WPA3 for secure connections
- Avoid WEP encryption (deprecated and insecure)
- Use strong passwords (minimum 8 characters)
- Consider hiding SSID for AP mode (security through obscurity)
- Enable PMF (Protected Management Frames) when supported

## Power Management

- WiFi can be configured for power saving modes
- AP mode typically consumes more power than STA mode
- Consider WiFi sleep modes for battery-powered applications
- Monitor power consumption in different WiFi modes

## Troubleshooting

### Common Issues

1. **Connection Failures**: Check SSID, password, and authentication mode
2. **Weak Signal**: Monitor RSSI values and consider antenna placement
3. **IP Assignment**: Ensure DHCP is working or configure static IP
4. **Channel Conflicts**: Use WiFi analyzer to find less congested channels
5. **Memory Issues**: Monitor heap usage, especially with many connections