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

149 lines
5.4 KiB
C++

/**
* @file WifiManager.cpp
* @brief Implementation of the WifiManager class.
*/
#include "WifiManager.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include <cstring>
static const char *TAG = "WifiManager";
// Event bits used to signal completion or failure of Wi-Fi connection
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT BIT1
WifiManager::WifiManager(const std::string &ssid, const std::string &password)
: ssid_(ssid), password_(password), wifi_event_group_(nullptr) {}
WifiManager::~WifiManager() {
// Clean up registered event handlers and destroy the FreeRTOS event group.
if (wifi_event_group_) {
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP,
instance_got_ip_);
esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID,
instance_any_id_);
vEventGroupDelete(wifi_event_group_);
}
}
bool WifiManager::connect() {
// Create an event group to block main execution until connection finishes.
wifi_event_group_ = xEventGroupCreate();
// Initialize the underlying TCP/IP stack and default event loop.
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
// Initialize the Wi-Fi driver with standard configuration values.
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
// Register internal event handlers to process Wi-Fi and IP events.
ESP_ERROR_CHECK(esp_event_handler_instance_register(
WIFI_EVENT, ESP_EVENT_ANY_ID, &WifiManager::eventHandler, this,
&instance_any_id_));
ESP_ERROR_CHECK(esp_event_handler_instance_register(
IP_EVENT, IP_EVENT_STA_GOT_IP, &WifiManager::eventHandler, this,
&instance_got_ip_));
// Set up the Wi-Fi station configuration structures.
wifi_config_t wifi_config = {};
strncpy((char *)wifi_config.sta.ssid, ssid_.c_str(),
sizeof(wifi_config.sta.ssid) - 1);
strncpy((char *)wifi_config.sta.password, password_.c_str(),
sizeof(wifi_config.sta.password) - 1);
// Set the hardware mode to station mode (client) and commit settings.
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "wifi_init_sta finished.");
// Wait indefinitely until either the connected or failed bit is set.
EventBits_t bits =
xEventGroupWaitBits(wifi_event_group_, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE, pdFALSE, portMAX_DELAY);
// Evaluate the outcome of the connection process.
if (bits & WIFI_CONNECTED_BIT) {
ESP_LOGI(TAG, "connected to ap SSID:%s", ssid_.c_str());
return true;
} else if (bits & WIFI_FAIL_BIT) {
ESP_LOGI(TAG, "Failed to connect to SSID:%s", ssid_.c_str());
return false;
} else {
ESP_LOGE(TAG, "UNEXPECTED EVENT");
return false;
}
}
void WifiManager::eventHandler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data) {
// Recover the 'this' instance from the void pointer argument.
WifiManager *instance = static_cast<WifiManager *>(arg);
if (!instance)
return;
// Dispatch the event to the appropriate handlers based on its base type.
if (event_base == WIFI_EVENT) {
instance->handleWifiEvent(event_id, event_data);
} else if (event_base == IP_EVENT) {
instance->handleIpEvent(event_id, event_data);
}
}
void WifiManager::handleWifiEvent(int32_t event_id, void *event_data) {
if (event_id == WIFI_EVENT_STA_START) {
// When the station has started, immediately kick off a connection.
esp_wifi_connect();
} else if (event_id == WIFI_EVENT_STA_DISCONNECTED) {
// Attempt continuous reconnection, without giving up.
ESP_LOGI(TAG, "retry to connect to the AP in 3 seconds...");
vTaskDelay(pdMS_TO_TICKS(3000));
esp_wifi_connect();
// Intentionally omit setting WIFI_FAIL_BIT to keep retrying indefinitely,
// ensuring the application never completely terminates due to network
// failure.
}
}
void WifiManager::handleIpEvent(int32_t event_id, void *event_data) {
if (event_id == IP_EVENT_STA_GOT_IP) {
// Received a DHCP lease from the AP.
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
// Convert raw IP address into human-readable string.
char ip_buf[20];
sprintf(ip_buf, IPSTR, IP2STR(&event->ip_info.ip));
ip_addr_ = ip_buf;
// Retrieve and format the MAC address.
uint8_t mac[6];
esp_wifi_get_mac(WIFI_IF_STA, mac);
char mac_buf[20];
sprintf(mac_buf, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2],
mac[3], mac[4], mac[5]);
mac_ = mac_buf;
// Fetch details like RSSI directly from the active AP connection record.
wifi_ap_record_t ap_info;
if (esp_wifi_sta_get_ap_info(&ap_info) == ESP_OK) {
rssi_ = ap_info.rssi;
}
// Signal the main task that the connection sequence has successfully
// completed.
xEventGroupSetBits(wifi_event_group_, WIFI_CONNECTED_BIT);
}
}
// Accessor implementations returning internal state strings.
std::string WifiManager::getIp() const { return ip_addr_; }
std::string WifiManager::getMac() const { return mac_; }
std::string WifiManager::getSsid() const { return ssid_; }
int8_t WifiManager::getRssi() const { return rssi_; }