Files
xInfo/main/WifiManager.h
T
2026-08-31 15:05:13 +08:00

91 lines
2.7 KiB
C++

/**
* @file WifiManager.h
* @brief Provides an interface for managing the ESP32 Wi-Fi connection.
*/
#ifndef WIFI_MANAGER_H
#define WIFI_MANAGER_H
#include "esp_event.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include <string>
/**
* @brief Class responsible for connecting to and monitoring Wi-Fi.
*
* This class abstracts the ESP-IDF Wi-Fi driver and event loop, providing
* synchronous connection methods and accessors for network states like IP
* and MAC addresses.
*/
class WifiManager {
public:
/**
* @brief Constructs a WifiManager instance.
*
* @param ssid The SSID of the target Wi-Fi network.
* @param password The password for the target Wi-Fi network.
*/
WifiManager(const std::string &ssid, const std::string &password);
/**
* @brief Destructor. Cleans up event handlers and FreeRTOS resources.
*/
~WifiManager();
/**
* @brief Starts the Wi-Fi connection process and blocks until connected.
*
* @return true if successfully connected and an IP address was acquired,
* false otherwise.
*/
bool connect();
/** @brief Returns the acquired IPv4 address as a string, or a fallback
* message if not connected. */
std::string getIp() const;
/** @brief Returns the station MAC address as a formatted string (e.g.,
* "AA:BB:CC:DD:EE:FF"). */
std::string getMac() const;
/** @brief Returns the SSID of the currently configured Wi-Fi network. */
std::string getSsid() const;
/** @brief Returns the Received Signal Strength Indicator (RSSI) of the
* connected AP. */
int8_t getRssi() const;
private:
/**
* @brief Static event handler dispatcher registered with the ESP event loop.
*/
static void eventHandler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data);
/**
* @brief Processes Wi-Fi related events (e.g., station start, disconnect).
*/
void handleWifiEvent(int32_t event_id, void *event_data);
/**
* @brief Processes IP related events (e.g., getting an IP address).
*/
void handleIpEvent(int32_t event_id, void *event_data);
std::string ssid_; ///< Stored SSID payload.
std::string password_; ///< Stored password payload.
std::string ip_addr_{"Connecting..."}; ///< Currently assigned IP.
std::string mac_{"N/A"}; ///< Hardware MAC address.
int8_t rssi_{0}; ///< Expected signal strength.
EventGroupHandle_t
wifi_event_group_; ///< FreeRTOS event group to block on connection state.
esp_event_handler_instance_t
instance_any_id_; ///< Handler instance for generic Wi-Fi events.
esp_event_handler_instance_t
instance_got_ip_; ///< Handler instance for successful IP lease event.
};
#endif // WIFI_MANAGER_H