tuanpmt/esp_wifi_manager

2.0.0

Latest
uploaded 3 hours ago
WiFi Manager component with multi-network support, auto-reconnect, SoftAP captive portal, and REST API configuration

Readme

# ESP WiFi Manager

[![Component Registry](https://components.espressif.com/components/tuanpmt/esp_wifi_manager/badge.svg)](https://components.espressif.com/components/tuanpmt/esp_wifi_manager)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

WiFi Manager component for ESP-IDF with multi-network support, auto-reconnect, SoftAP captive portal, Web UI, CLI, BLE, and REST API.

## Features

- **Multi-network support**: Save multiple WiFi networks with priority-based auto-connect
- **Auto-reconnect**: Automatic retry with exponential backoff and failover between saved networks
- **SoftAP mode**: Captive portal for initial configuration (triggers OS popup)
- **Web UI**: Embedded responsive web interface (Preact-based, ~10KB gzipped)
- **CLI interface**: Serial console commands for configuration
- **BLE GATT**: Configure WiFi via Bluetooth Low Energy (smartphone or Python CLI)
- **REST API**: HTTP endpoints for remote configuration with CORS support
- **Basic Auth**: Optional authentication for HTTP endpoints
- **mDNS**: Access device via hostname (e.g., `esp32-abc123.local`)
- **Custom variables**: Key-value storage for application settings
- **NVS persistence**: Networks, variables, and AP config stored in flash
- **esp_bus integration**: Event-driven architecture with actions and events

## Architecture

```
┌──────────────────────────────────────────────────────────────────────┐
│                        ESP_WIFI_MANAGER                              │
│  ┌────────────────────────────────────────────────────────────────┐  │
│  │  WiFi Core                    │  NVS Storage                   │  │
│  │  ─────────                    │  ───────────                   │  │
│  │  • Multi-network              │  • Saved networks              │  │
│  │  • Auto retry + backoff       │  • AP configuration            │  │
│  │  • Reconnect logic            │  • Custom variables            │  │
│  │  • Captive portal + DNS       │                                │  │
│  └────────────────────────────────────────────────────────────────┘  │
│                                                                      │
│  ┌─────────────── Configuration Interfaces ───────────────────────┐  │
│  │                                                                │  │
│  │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐       │  │
│  │  │ Web UI │ │  HTTP  │ │  CLI   │ │  BLE   │ │  mDNS  │       │  │
│  │  │(Preact)│ │  API   │ │(Console│ │  GATT  │ │        │       │  │
│  │  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘       │  │
│  │       │          │          │          │          │           │  │
│  │       └──────────┴──────────┴──────────┴──────────┘           │  │
│  │                              │                                │  │
│  │                              ▼                                │  │
│  │                 ┌─────────────────────────┐                   │  │
│  │                 │  WiFi Manager Core API  │                   │  │
│  │                 └─────────────────────────┘                   │  │
│  └────────────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────────┘
         │                              │
         │ events                       │ requests
         ▼                              ▼
┌──────────────────────────────────────────────────────────────────────┐
│                             ESP_BUS                                  │
└──────────────────────────────────────────────────────────────────────┘
```

## Installation

### Using ESP-IDF Component Manager (Recommended)

Add to your project's `idf_component.yml`:

```yaml
dependencies:
  tuanpmt/esp_wifi_manager: "*"
```

### Manual Installation

Clone into your project's `components/` directory:

```bash
cd components
git clone https://github.com/tuanpmt/esp_wifi_manager.git
```

## Quick Start

```c
#include "esp_wifi_manager.h"
#include "esp_bus.h"
#include "nvs_flash.h"

void app_main(void)
{
    // Initialize NVS (required)
    nvs_flash_init();

    // Initialize esp_bus (required before wifi_manager_init)
    esp_bus_init();

    // Subscribe to WiFi events (optional)
    esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_CONNECTED), on_connected_cb, NULL);
    esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_GOT_IP), on_got_ip_cb, NULL);

    // Initialize WiFi Manager
    wifi_manager_init(&(wifi_manager_config_t){
        .default_networks = (wifi_network_t[]){
            {"HomeWifi", "password123", 10},   // priority 10 (highest)
            {"OfficeWifi", "office456", 5},    // priority 5 (fallback)
        },
        .default_network_count = 2,

        // Enable HTTP REST API
        .http = {
            .enable = true,
            .api_base_path = "/api/wifi",
        },

        // Enable captive portal if no networks available
        .enable_captive_portal = true,
    });

    // Wait for connection (30 second timeout)
    if (wifi_manager_wait_connected(30000) == ESP_OK) {
        ESP_LOGI(TAG, "WiFi connected!");
    }
}
```

## Examples

| Example | Description |
|---------|-------------|
| [basic](examples/basic/) | Minimal setup with default configuration |
| [with_cli](examples/with_cli/) | CLI interface with ESP Console REPL |
| [with_webui](examples/with_webui/) | Embedded Web UI (no external files needed) |
| [with_webui_customize](examples/with_webui_customize/) | Custom frontend from LittleFS |
| [with_ble](examples/with_ble/) | BLE GATT interface for smartphone/Python CLI |
| [with_ble_deinit](examples/with_ble_deinit/) | NimBLE, app-owned stack kept running after WiFi Manager deinit |

> Upgrading from 1.x? See [CHANGELOG.md](CHANGELOG.md#migrating-from-1x) for breaking changes.

## Configuration

### Kconfig Options

Configure via `idf.py menuconfig` → WiFi Manager:

| Option | Default | Description |
|--------|---------|-------------|
| `WIFI_MGR_MAX_NETWORKS` | 5 | Maximum saved networks |
| `WIFI_MGR_MAX_VARS` | 10 | Maximum custom variables |
| `WIFI_MGR_DEFAULT_RETRY` | 3 | Retries per network |
| `WIFI_MGR_RETRY_INTERVAL_MS` | 5000 | Base retry interval (ms) |
| `WIFI_MGR_AP_SSID` | "ESP32-Config" | Default AP SSID |
| `WIFI_MGR_AP_PASSWORD` | "" | Default AP password |
| `WIFI_MGR_AP_IP` | "192.168.4.1" | Default AP IP |
| `WIFI_MGR_MDNS_HOSTNAME` | "esp32-{id}" | mDNS hostname template |
| `WIFI_MGR_ENABLE_CLI` | n | Enable CLI interface |
| `WIFI_MGR_ENABLE_WEBUI` | n | Enable embedded Web UI |
| `WIFI_MGR_WEBUI_CUSTOM_PATH` | "" | Custom Web UI path (LittleFS/SPIFFS) |
| `WIFI_MGR_ENABLE_BLE` | n | Enable BLE GATT interface |
| `WIFI_MGR_BLE_DEVICE_NAME` | "ESP32-WiFi-{id}" | BLE device name (supports {id}) |
| `WIFI_MGR_BLE_RELEASE_CLASSIC_BT_MEM` | n | Bluedroid: release Classic BT memory (saves RAM on ESP32, disables Classic BT until reboot) |
| `WIFI_MGR_MAX_SCAN_RESULTS` | 20 | Max scan results returned by REST/BLE/CLI |
| `WIFI_MGR_HTTP_MAX_CONTENT_LEN` | 2048 | Max HTTP request body (bytes) |
| `WIFI_MGR_HTTP_MAX_URI_HANDLERS` | 40 | `max_uri_handlers` for the httpd created by WiFi Manager |
| `WIFI_MGR_TASK_STACK_SIZE` | 4096 | Manager and DNS task stack size |
| `WIFI_MGR_TASK_PRIORITY` | 5 | Manager and DNS task priority |

All options also have built-in defaults, so the component can be used without running menuconfig.

**Recommended for captive portal:** `CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024`. Recent Android/Chrome probes send headers larger than the 512-byte default; the server then answers `431` and the portal popup never opens. WiFi Manager logs a warning when the value is lower.

### Runtime Configuration

```c
wifi_manager_config_t config = {
    // Default networks (fallback if NVS empty)
    .default_networks = networks,
    .default_network_count = 2,

    // Default variables
    .default_vars = (wifi_var_t[]){
        {"server_url", "https://api.example.com"},
        {"device_name", "my-device"},
    },
    .default_var_count = 2,

    // Retry config with exponential backoff
    .max_retry_per_network = 3,
    .retry_interval_ms = 5000,      // Base interval
    .retry_max_interval_ms = 60000, // Max backoff
    .auto_reconnect = true,

    // SoftAP config (supports {id} placeholder for MAC suffix)
    .default_ap = {
        .ssid = "MyDevice-{id}",
        .password = "",
        .ip = "192.168.4.1",
    },
    .enable_captive_portal = true,
    .stop_ap_on_connect = true,

    // Optional: validate variables before they are saved (any interface)
    .on_before_var_set = my_var_validator,   // return ESP_OK to accept
    .var_validator_ctx = NULL,

    // HTTP interface
    .http = {
        .enable = true,
        .api_base_path = "/api/wifi",
        .enable_auth = true,
        .auth_username = "admin",
        .auth_password = "secret",
        // Optional: runs before every API handler (after CORS, before auth);
        // return non-ESP_OK to reject with 403
        .pre_request_hook = my_api_hook,
        .hook_ctx = NULL,
    },

    // mDNS (supports {id} placeholder)
    .mdns = {
        .enable = true,
        .hostname = "esp32-{id}",
    },

    // BLE GATT (requires CONFIG_WIFI_MGR_ENABLE_BLE=y)
    .ble = {
        .enable = true,
        .device_name = "ESP32-WiFi-{id}",  // NULL uses Kconfig default
    },
};

wifi_manager_init(&config);
```

## C API Reference

```c
// Initialization
esp_err_t wifi_manager_init(const wifi_manager_config_t *config);
// deinit_wifi=false keeps the STA connection (and netifs) alive and only
// tears down the manager, HTTP handlers, BLE service and mDNS
esp_err_t wifi_manager_deinit(bool deinit_wifi);

// Status
bool wifi_manager_is_connected(void);
wifi_state_t wifi_manager_get_state(void);
esp_err_t wifi_manager_get_status(wifi_status_t *status);
esp_err_t wifi_manager_wait_connected(uint32_t timeout_ms);

// Connection
esp_err_t wifi_manager_connect(const char *ssid);  // NULL for auto-connect
esp_err_t wifi_manager_disconnect(void);
esp_err_t wifi_manager_scan(wifi_scan_result_t *results, size_t max, size_t *count);

// Network management (removing the connected network disconnects from it)
esp_err_t wifi_manager_add_network(const wifi_network_t *network);
esp_err_t wifi_manager_update_network(const wifi_network_t *network);
esp_err_t wifi_manager_remove_network(const char *ssid);
esp_err_t wifi_manager_list_networks(wifi_network_t *networks, size_t max, size_t *count);

// SoftAP
esp_err_t wifi_manager_start_ap(const wifi_mgr_ap_config_t *config);
esp_err_t wifi_manager_stop_ap(void);
esp_err_t wifi_manager_get_ap_status(wifi_ap_status_t *status);

// Custom variables
esp_err_t wifi_manager_set_var(const char *key, const char *value);
esp_err_t wifi_manager_get_var(const char *key, char *value, size_t max_len);
esp_err_t wifi_manager_del_var(const char *key);

// Factory reset
esp_err_t wifi_manager_factory_reset(void);

// Shared HTTP server (for adding custom endpoints)
httpd_handle_t wifi_manager_get_httpd(void);
```

## esp_bus Integration

**Events (pub/sub):**

```c
void on_connected(const char *event, const void *data, size_t len, void *ctx) {
    wifi_connected_t *info = (wifi_connected_t *)data;
    ESP_LOGI(TAG, "Connected to %s, RSSI: %d", info->ssid, info->rssi);
}

esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_CONNECTED), on_connected, NULL);
esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_DISCONNECTED), on_disconnected, NULL);
esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_GOT_IP), on_got_ip, NULL);
esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_SCAN_DONE), on_scan_done, NULL);
esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_NETWORK_ADDED), on_network_added, NULL);
esp_bus_sub(WIFI_EVT(WIFI_MGR_EVT_VAR_CHANGED), on_var_changed, NULL);
```

## CLI Commands

Enable with `CONFIG_WIFI_MGR_ENABLE_CLI=y`:

| Command | Description |
|---------|-------------|
| `wifi status` | Show connection status |
| `wifi scan` | Scan available networks |
| `wifi list` | List saved networks |
| `wifi add <ssid> [password] [priority]` | Add network |
| `wifi del <ssid>` | Remove network |
| `wifi connect [ssid]` | Connect (auto or specific) |
| `wifi disconnect` | Disconnect |
| `wifi ap start` | Start SoftAP |
| `wifi ap stop` | Stop SoftAP |
| `wifi reset` | Factory reset |
| `wifi var get <key>` | Get variable |
| `wifi var set <key> <value>` | Set variable |

## BLE GATT Interface

Enable with `CONFIG_WIFI_MGR_ENABLE_BLE=y`. Both Bluedroid and NimBLE host stacks are supported. Requires Bluetooth enabled in sdkconfig:

**Bluedroid** (~100KB flash / ~40KB RAM):

```kconfig
CONFIG_BT_ENABLED=y
CONFIG_BT_BLUEDROID_ENABLED=y
```

**NimBLE** (~50KB flash / ~20KB RAM):

```kconfig
CONFIG_BT_ENABLED=y
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE=6144
```


The device advertises the WiFi Service UUID (`0xFFE0`), allowing clients to scan and filter by service UUID — the standard BLE discovery pattern. The device name (configurable via `CONFIG_WIFI_MGR_BLE_DEVICE_NAME`) is also included in the advertising data for further filtering.

### Stack Ownership & Deinitialization

The BLE interface supports two modes of operation depending on whether the application manages the BLE stack independently:

| Mode | Init behavior | Deinit behavior | Use case |
|------|---------------|-----------------|----------|
| **Owns the stack** (default) | Initializes BLE host stack + registers GATT service | Tears down everything (service, advertising, host stack, controller) | App doesn't use BLE for anything else |
| **Service only** | Detects host stack already running, registers GATT service only | Unregisters service and stops advertising, leaves host stack running | App manages the BLE lifecycle |

> **Experimental:** service-only mode has known limitations that still need hardware validation: on NimBLE the service is added after the GATT server has started and deinit calls `ble_gatts_reset()` (which also removes the application's services); on Bluedroid WiFi Manager registers its own GAP/GATTS callbacks, which replaces the application's. Prefer letting WiFi Manager own the stack unless you can test your exact setup.

The mode is detected automatically: if the BLE host stack is already initialized when `wifi_manager_init()` is called, the WiFi Manager registers only its GATT service and leaves the stack alone on deinit. This mirrors the HTTP interface's shared server pattern — if you pass an existing `httpd_handle_t`, the HTTP handlers are unregistered on deinit without stopping the server.

**NimBLE:**

```c
// App-owned BLE stack: init NimBLE before WiFi Manager
nimble_port_init();
nimble_port_freertos_init(nimble_host_task);

wifi_manager_init(&(wifi_manager_config_t){
    .ble = { .enable = true },
});

// Later: WiFi Manager removes its GATT service but NimBLE keeps running
wifi_manager_deinit(false);

// App can continue using BLE for its own services
```

**Bluedroid:**

```c
// App-owned BLE stack: init Bluedroid before WiFi Manager
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BLE);
esp_bluedroid_init();
esp_bluedroid_enable();

wifi_manager_init(&(wifi_manager_config_t){
    .ble = { .enable = true },
});

// Later: WiFi Manager unregisters its GATT app but Bluedroid keeps running
wifi_manager_deinit(false);

// App can continue using BLE for its own services
```

### Service & Characteristics

| UUID | Name | Properties | Description |
|------|------|------------|-------------|
| 0xFFE0 | WiFi Service | - | Main service |
| 0xFFE1 | Status | Read, Notify | Current WiFi status (JSON) |
| 0xFFE2 | Command | Write | Send JSON command |
| 0xFFE3 | Response | Notify | Command response (JSON) |

### Commands

Send JSON to the Command characteristic (0xFFE2). Parameters are passed in a `"params"` object. Responses are sent as notifications on the Response characteristic (0xFFE3). Large responses are automatically chunked across multiple notifications.

| Command          | Params | Description |
|------------------|--------|-------------|
| `get_status`     | (none) | Get connection status |
| `scan`           | (none) | Scan available networks |
| `list_networks`  | (none) | List saved networks |
| `add_network`    | `ssid`, `password`?, `priority`? | Add new network |
| `update_network` | `ssid`, `password`?, `priority`? | Update saved network |
| `del_network`    | `ssid` | Remove network |
| `connect`        | `ssid`? | Connect (auto or specific SSID) |
| `disconnect`     | (none) | Disconnect |
| `get_ap_status`  | (none) | Get AP status |
| `start_ap`       | `ssid`?, `password`? | Start SoftAP |
| `stop_ap`        | (none) | Stop SoftAP |
| `get_var`        | `key` | Get variable |
| `set_var`        | `key`, `value` | Set variable |
| `list_vars`      | (none) | List all variables |
| `del_var`        | `key` | Delete variable |
| `factory_reset`  | (none) | Factory reset |

### Example Commands

```json
{"cmd": "get_status"}
{"cmd": "scan"}
{"cmd": "list_networks"}
{"cmd": "add_network", "params": {"ssid": "MyWiFi", "password": "secret", "priority": 10}}
{"cmd": "update_network", "params": {"ssid": "MyWiFi", "password": "newpass", "priority": 5}}
{"cmd": "del_network", "params": {"ssid": "MyWiFi"}}
{"cmd": "connect", "params": {"ssid": "MyWiFi"}}
{"cmd": "get_var", "params": {"key": "device_name"}}
{"cmd": "set_var", "params": {"key": "device_name", "value": "My ESP32"}}
{"cmd": "list_vars"}
{"cmd": "del_var", "params": {"key": "device_name"}}
{"cmd": "factory_reset"}
```

### Response Format

Successful responses:

```json
{"status": "ok", "data": { ... }}
```

Error responses:

```json
{"status": "error", "error": "Error message"}
```

### Response Examples

**get_status**
```json
{
  "status": "ok",
  "data": {
    "state": "connected",
    "ssid": "MyWiFi",
    "rssi": -65,
    "quality": 70,
    "ip": "192.168.1.100",
    "channel": 6,
    "netmask": "255.255.255.0",
    "gateway": "192.168.1.1",
    "dns": "192.168.1.1",
    "mac": "AA:BB:CC:DD:EE:FF",
    "hostname": "esp32-aabbcc",
    "uptime_ms": 123456,
    "ap_active": false
  }
}
```

**get_ap_status**
```json
{
  "status": "ok",
  "data": {
    "active": true,
    "ssid": "ESP32-AABBCC",
    "ip": "192.168.4.1",
    "channel": 1,
    "sta_count": 2
  }
}
```

**list_vars**
```json
{
  "status": "ok",
  "data": {
    "vars": [
      {"key": "server_url", "value": "https://api.example.com"},
      {"key": "device_name", "value": "My ESP32"}
    ]
  }
}
```

### Python CLI Client

```bash
cd tools/wifi_ble_cli
pip install -r requirements.txt

# Global options: --device/-d (MAC address), --name/-n (name prefix, default "ESP32-WiFi")
python wifi_ble_cli.py --name "ESP32-WiFi" <command>

# Scan for BLE devices
python wifi_ble_cli.py devices

# Get WiFi status
python wifi_ble_cli.py status

# Scan WiFi networks
python wifi_ble_cli.py scan

# List saved networks
python wifi_ble_cli.py list

# Add network (with optional priority)
python wifi_ble_cli.py add "MyWiFi" "password123" --priority 10

# Delete a saved network
python wifi_ble_cli.py delete "MyWiFi"

# Connect (auto or specific SSID)
python wifi_ble_cli.py connect
python wifi_ble_cli.py connect "MyWiFi"

# Disconnect
python wifi_ble_cli.py disconnect

# AP management
python wifi_ble_cli.py ap-status
python wifi_ble_cli.py start-ap
python wifi_ble_cli.py stop-ap

# Custom variables
python wifi_ble_cli.py get-var device_name
python wifi_ble_cli.py set-var device_name "My ESP32"

# Factory reset (with confirmation prompt)
python wifi_ble_cli.py factory-reset
```

## REST API Reference

Base URL: `http://<device-ip>/api/wifi` (configurable via `api_base_path`)

### Authentication

If `enable_auth = true`, all endpoints require Basic Auth:

```bash
curl -u admin:password http://192.168.4.1/api/wifi/status
```

### Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/status` | Get connection status |
| GET | `/scan` | Scan available networks |
| GET | `/networks` | List saved networks |
| POST | `/networks` | Add or update network (upsert; omitted fields keep saved values) |
| PUT | `/networks/:ssid` | Update network (partial) |
| DELETE | `/networks/:ssid` | Remove network |
| POST | `/connect` | Connect (auto or specific SSID) |
| POST | `/disconnect` | Disconnect |
| GET | `/ap/status` | Get AP status |
| GET | `/ap/config` | Get AP configuration |
| PUT | `/ap/config` | Update AP configuration |
| POST | `/ap/start` | Start SoftAP |
| POST | `/ap/stop` | Stop SoftAP |
| GET | `/vars` | List custom variables |
| PUT | `/vars/:key` | Set variable |
| DELETE | `/vars/:key` | Delete variable |
| POST | `/factory_reset` | Factory reset |

`:ssid` and `:key` are URL-encoded path segments (e.g. `My%20WiFi`). Hidden networks are not listed by `/scan`; add them with `POST /networks` using the exact SSID and connect as usual.

### Example Requests

```bash
# Get status
curl http://192.168.4.1/api/wifi/status

# Scan networks
curl http://192.168.4.1/api/wifi/scan

# Add network
curl -X POST http://192.168.4.1/api/wifi/networks \
  -H "Content-Type: application/json" \
  -d '{"ssid": "MyWiFi", "password": "secret123", "priority": 10}'

# Connect to specific network
curl -X POST http://192.168.4.1/api/wifi/connect \
  -H "Content-Type: application/json" \
  -d '{"ssid": "MyWiFi"}'

# Auto-connect (highest priority)
curl -X POST http://192.168.4.1/api/wifi/connect

# Delete network
curl -X DELETE http://192.168.4.1/api/wifi/networks/MyWiFi

# Set custom variable
curl -X PUT http://192.168.4.1/api/wifi/vars/device_name \
  -H "Content-Type: application/json" \
  -d '{"value": "Living Room"}'
```

### Response Examples

**GET /status**
```json
{
  "state": "connected",
  "ssid": "MyWiFi",
  "ip": "192.168.1.100",
  "gateway": "192.168.1.1",
  "netmask": "255.255.255.0",
  "dns": "192.168.1.1",
  "rssi": -65,
  "quality": 70,
  "channel": 6,
  "mac": "AA:BB:CC:DD:EE:FF",
  "hostname": "esp32-aabbcc",
  "uptime_ms": 123456,
  "ap_active": false
}
```

**GET /scan**
```json
{
  "networks": [
    {"ssid": "MyWiFi", "rssi": -65, "auth": "WPA2"},
    {"ssid": "Neighbor", "rssi": -80, "auth": "WPA/WPA2"},
    {"ssid": "OpenNet", "rssi": -70, "auth": "OPEN"}
  ]
}
```

**GET /ap/status**
```json
{
  "active": true,
  "ssid": "ESP32-AABBCC",
  "ip": "192.168.4.1",
  "channel": 1,
  "sta_count": 2,
  "clients": [
    {"mac": "AA:BB:CC:DD:EE:01", "ip": "192.168.4.2"},
    {"mac": "AA:BB:CC:DD:EE:02", "ip": "192.168.4.3"}
  ]
}
```

### Error Responses

```json
{"error": "Error message"}
```

| HTTP Code | Description |
|-----------|-------------|
| 400 | Bad Request - Invalid JSON, missing field |
| 401 | Unauthorized - Auth required |
| 403 | Forbidden - Rejected by `pre_request_hook` |
| 404 | Not Found - Network/Variable does not exist, or `/connect` to an unsaved SSID |
| 500 | Internal Error - Operation failed |

## Connection Flow

```
boot → load saved networks → try connect →
  ├── success → emit CONNECTED event → emit GOT_IP event
  └── fail all → start captive portal (if enabled)

Auto-connect logic:
1. Load saved networks from NVS (sorted by priority DESC)
2. For each network:
   a. Try connect (max_retry_per_network times)
   b. Exponential backoff between retries
   c. If success → done
   d. If fail → try next network
3. If all fail and captive_portal enabled → start AP,
   otherwise keep retrying in the background with backoff (if auto_reconnect)
4. If connected and disconnected → auto-reconnect if enabled
```

Disconnect events from failed attempts are ignored once the sequence has
connected to a lower-priority network, so a fallback connection is not torn
down by stale events from the primary network.

## Captive Portal

When no networks are configured or all connections fail, the device starts a SoftAP with captive portal:

1. Connect to AP (e.g., "ESP32-AABBCC")
2. OS automatically opens captive portal popup
3. Configure WiFi via Web UI or REST API
4. Device connects and AP stops (if `stop_ap_on_connect = true`)

Supported captive portal detection:
- Android: `/generate_204`, `/gen_204`
- iOS/macOS: `/hotspot-detect.html`, `/library/test/success.html`
- Windows: `/ncsi.txt`, `/connecttest.txt`, `/redirect`
- Firefox: `/success.txt`, `/canonical.html`
- Any other unknown path while the AP is active, when WiFi Manager owns the HTTP server (404 handler redirects to the portal)

When you pass your own `httpd` handle, create it with `uri_match_fn = httpd_uri_match_wildcard` and enough `max_uri_handlers` (about 32); WiFi Manager unregisters exactly the handlers it registered on deinit and never replaces your 404 handler.

## Dependencies

- ESP-IDF >= 5.0.0
- [esp_bus](https://components.espressif.com/components/tuanpmt/esp_bus) - Event bus component
- cJSON - JSON parsing (included in ESP-IDF)
- mbedTLS - Base64 for Basic Auth (included in ESP-IDF)

## License

MIT License - see [LICENSE](LICENSE) file.

Links

Maintainer

  • tuanpmt
To add this component to your project, run:

idf.py add-dependency "tuanpmt/esp_wifi_manager^2.0.0"

download archive

Stats

  • Archive size
    Archive size ~ 153.14 KB
  • Downloaded in total
    Downloaded in total 478 times
  • Weekly Downloads Weekly Downloads (All Versions)
  • Downloaded this version
    This version: 0 times

Badge

tuanpmt/esp_wifi_manager version: 2.0.0
|