WiFi Manager
Overview
The WifiManager class provides a simplified interface for WiFi operations on the ESP32. It handles
connecting, disconnecting, and automatic reconnection to a specified WiFi network using stored
credentials. The class includes timeout handling for connection attempts and provides debug logging
for connection status.
Features
- Automatic Connection Management: Establishes and maintains WiFi connections
- Connection Timeout Handling: Uses a timeout for connection attempts to avoid indefinite blocking
- Reconnection Support: Provides automatic reconnection capabilities
- Power Management: Powers down WiFi radio when disconnecting to save energy
- Debug Logging: Uses "DEBUG.h" for detailed connection status output during development
Dependencies
- "WiFi.h": WiFi functionality for ESP32
- "DEBUG.h": Custom debug logging (optional but recommended)
Class Definition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
Constructor
WifiManager(const String& ssid, const String& password)
Creates a new WifiManager instance with the specified network credentials.
Parameters:
ssid: WiFi network name to connect topassword: WiFi network password for authentication
Example:
1 2 3 4 | |
Public Methods
void Connect()
Establishes a connection to the configured WiFi network.
Behavior:
- Initiates WiFi connection using stored credentials
- Implements timeout for connection attempts
- Logs connection progress with dots (.) during attempt
- Displays network information upon successful connection
- Returns immediately if connection fails after timeout
Example:
1 2 3 4 5 | |
void Disconnect()
Gracefully disconnects from the WiFi network and powers down the WiFi radio.
Behavior:
- Closes existing WiFi connection
- Sets WiFi mode to
WIFI_OFFto save power
Example:
1 | |
void Reconnect()
Attempts to reconnect to the configured WiFi network.
Behavior:
- Equivalent to calling
Connect()when disconnected - Implements same 10-second timeout as
Connect() - Used for recovering from connection loss
- Logs reconnection attempts and results
Usage:
1 2 3 4 | |
Error Handling
The WifiManager implements several error handling strategies:
Connection Timeout
- Timeout Duration: 10 seconds
- Behavior: Returns without connection if timeout exceeded
- Recovery: Call
Connect()orReconnect()again
Network Unavailable
- Detection: Connection fails within timeout period
- Logging: Logs "Failed to connect to WiFi" or "Failed to reconnect to network"
- Recovery: Retry connection after delay
Debug Information
The WifiManager provides detailed debug output when DEBUG.h is included:
1 2 3 4 5 6 7 | |