Reformat project using clang-format

This commit is contained in:
Lorow
2026-01-06 22:51:24 +01:00
parent 567d3ebd75
commit 555e290d71
70 changed files with 3282 additions and 3428 deletions

View File

@@ -2,14 +2,13 @@
#include <cstring>
#include "esp_timer.h"
static const char *TAG = "WiFiScanner";
static const char* TAG = "WiFiScanner";
WiFiScanner::WiFiScanner() {}
void WiFiScanner::scanResultCallback(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
void WiFiScanner::scanResultCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
auto *scanner = static_cast<WiFiScanner *>(arg);
auto* scanner = static_cast<WiFiScanner*>(arg);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE)
{
uint16_t ap_count = 0;
@@ -21,14 +20,14 @@ void WiFiScanner::scanResultCallback(void *arg, esp_event_base_t event_base,
return;
}
wifi_ap_record_t *ap_records = new wifi_ap_record_t[ap_count];
wifi_ap_record_t* ap_records = new wifi_ap_record_t[ap_count];
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&ap_count, ap_records));
scanner->networks.clear();
for (uint16_t i = 0; i < ap_count; i++)
{
WiFiNetwork network;
network.ssid = std::string(reinterpret_cast<char *>(ap_records[i].ssid));
network.ssid = std::string(reinterpret_cast<char*>(ap_records[i].ssid));
network.channel = ap_records[i].primary;
network.rssi = ap_records[i].rssi;
memcpy(network.mac, ap_records[i].bssid, 6);
@@ -63,7 +62,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
esp_wifi_scan_stop();
// Try sequential channel scanning as a workaround
bool try_sequential_scan = true; // Enable sequential scan
bool try_sequential_scan = true; // Enable sequential scan
if (!try_sequential_scan)
{
@@ -71,17 +70,17 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
wifi_scan_config_t scan_config = {
.ssid = nullptr,
.bssid = nullptr,
.channel = 0, // 0 means scan all channels
.channel = 0, // 0 means scan all channels
.show_hidden = true,
.scan_type = WIFI_SCAN_TYPE_ACTIVE, // Active scan
.scan_time = {
.active = {
.min = 120, // Min per channel
.max = 300 // Max per channel
},
.passive = 360},
.home_chan_dwell_time = 0, // 0 for default
.channel_bitmap = 0 // 0 for all channels
.scan_type = WIFI_SCAN_TYPE_ACTIVE, // Active scan
.scan_time = {.active =
{
.min = 120, // Min per channel
.max = 300 // Max per channel
},
.passive = 360},
.home_chan_dwell_time = 0, // 0 for default
.channel_bitmap = 0 // 0 for all channels
};
err = esp_wifi_scan_start(&scan_config, false);
@@ -95,7 +94,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
{
// Sequential channel scan - scan each channel individually with timeout tracking
std::vector<wifi_ap_record_t> all_records;
int64_t start_time = esp_timer_get_time() / 1000; // Convert to ms
int64_t start_time = esp_timer_get_time() / 1000; // Convert to ms
for (uint8_t ch = 1; ch <= 13; ch++)
{
@@ -109,28 +108,23 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
break;
}
wifi_scan_config_t scan_config = {
.ssid = nullptr,
.bssid = nullptr,
.channel = ch,
.show_hidden = true,
.scan_type = WIFI_SCAN_TYPE_ACTIVE,
.scan_time = {
.active = {
.min = 100,
.max = 200},
.passive = 300},
.home_chan_dwell_time = 0,
.channel_bitmap = 0};
wifi_scan_config_t scan_config = {.ssid = nullptr,
.bssid = nullptr,
.channel = ch,
.show_hidden = true,
.scan_type = WIFI_SCAN_TYPE_ACTIVE,
.scan_time = {.active = {.min = 100, .max = 200}, .passive = 300},
.home_chan_dwell_time = 0,
.channel_bitmap = 0};
err = esp_wifi_scan_start(&scan_config, true); // Blocking scan
err = esp_wifi_scan_start(&scan_config, true); // Blocking scan
if (err == ESP_OK)
{
uint16_t ch_count = 0;
esp_wifi_scan_get_ap_num(&ch_count);
if (ch_count > 0)
{
wifi_ap_record_t *ch_records = new wifi_ap_record_t[ch_count];
wifi_ap_record_t* ch_records = new wifi_ap_record_t[ch_count];
if (esp_wifi_scan_get_ap_records(&ch_count, ch_records) == ESP_OK)
{
for (uint16_t i = 0; i < ch_count; i++)
@@ -145,10 +139,10 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
}
// Process all collected records
for (const auto &record : all_records)
for (const auto& record : all_records)
{
WiFiNetwork network;
network.ssid = std::string(reinterpret_cast<const char *>(record.ssid));
network.ssid = std::string(reinterpret_cast<const char*>(record.ssid));
network.channel = record.primary;
network.rssi = record.rssi;
memcpy(network.mac, record.bssid, 6);
@@ -164,7 +158,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
}
// Wait for scan completion with timeout
int64_t start_time = esp_timer_get_time() / 1000; // Convert to ms
int64_t start_time = esp_timer_get_time() / 1000; // Convert to ms
int64_t elapsed_ms = 0;
bool scan_done = false;
@@ -206,7 +200,7 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
return scan_results;
}
wifi_ap_record_t *ap_records = new wifi_ap_record_t[ap_count];
wifi_ap_record_t* ap_records = new wifi_ap_record_t[ap_count];
err = esp_wifi_scan_get_ap_records(&ap_count, ap_records);
if (err != ESP_OK)
{
@@ -216,12 +210,12 @@ std::vector<WiFiNetwork> WiFiScanner::scanNetworks(int timeout_ms)
}
// Build the results vector and track channels found
bool channels_found[15] = {false}; // Track channels 0-14
bool channels_found[15] = {false}; // Track channels 0-14
for (uint16_t i = 0; i < ap_count; i++)
{
WiFiNetwork network;
network.ssid = std::string(reinterpret_cast<char *>(ap_records[i].ssid));
network.ssid = std::string(reinterpret_cast<char*>(ap_records[i].ssid));
network.channel = ap_records[i].primary;
network.rssi = ap_records[i].rssi;
memcpy(network.mac, ap_records[i].bssid, 6);

View File

@@ -2,10 +2,10 @@
#ifndef WIFI_SCANNER_HPP
#define WIFI_SCANNER_HPP
#include <vector>
#include <string>
#include "esp_wifi.h"
#include <vector>
#include "esp_log.h"
#include "esp_wifi.h"
struct WiFiNetwork
{
@@ -18,12 +18,12 @@ struct WiFiNetwork
class WiFiScanner
{
public:
public:
WiFiScanner();
std::vector<WiFiNetwork> scanNetworks(int timeout_ms = 15000);
static void scanResultCallback(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
static void scanResultCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
private:
private:
std::vector<WiFiNetwork> networks;
};

View File

@@ -5,409 +5,392 @@ static auto WIFI_MANAGER_TAG = "[WIFI_MANAGER]";
int s_retry_num = 0;
EventGroupHandle_t s_wifi_event_group;
void WiFiManagerHelpers::event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
void WiFiManagerHelpers::event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Trying to connect, got event: %d", (int)event_id);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
{
if (const auto err = esp_wifi_connect(); err != ESP_OK)
ESP_LOGI(WIFI_MANAGER_TAG, "Trying to connect, got event: %d", (int)event_id);
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
{
ESP_LOGI(WIFI_MANAGER_TAG, "esp_wifi_connect() failed: %s", esp_err_to_name(err));
if (const auto err = esp_wifi_connect(); err != ESP_OK)
{
ESP_LOGI(WIFI_MANAGER_TAG, "esp_wifi_connect() failed: %s", esp_err_to_name(err));
}
}
}
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{
const auto *disconnected = static_cast<wifi_event_sta_disconnected_t *>(event_data);
ESP_LOGI(WIFI_MANAGER_TAG, "Disconnect reason: %d", disconnected->reason);
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY)
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(WIFI_MANAGER_TAG, "retry to connect to the AP");
const auto* disconnected = static_cast<wifi_event_sta_disconnected_t*>(event_data);
ESP_LOGI(WIFI_MANAGER_TAG, "Disconnect reason: %d", disconnected->reason);
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY)
{
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(WIFI_MANAGER_TAG, "retry to connect to the AP");
}
else
{
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(WIFI_MANAGER_TAG, "connect to the AP fail");
}
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
{
const auto* event = static_cast<ip_event_got_ip_t*>(event_data);
ESP_LOGI(WIFI_MANAGER_TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
WiFiManager::WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager* stateManager)
: deviceConfig(deviceConfig), eventQueue(eventQueue), stateManager(stateManager), wifiScanner(std::make_unique<WiFiScanner>())
{
}
void WiFiManager::SetCredentials(const char* ssid, const char* password)
{
// Clear the config first
memset(&_wifi_cfg, 0, sizeof(_wifi_cfg));
// Copy SSID with null termination
size_t ssid_len = std::min(strlen(ssid), sizeof(_wifi_cfg.sta.ssid) - 1);
memcpy(_wifi_cfg.sta.ssid, ssid, ssid_len);
_wifi_cfg.sta.ssid[ssid_len] = '\0';
// Copy password with null termination
size_t pass_len = std::min(strlen(password), sizeof(_wifi_cfg.sta.password) - 1);
memcpy(_wifi_cfg.sta.password, password, pass_len);
_wifi_cfg.sta.password[pass_len] = '\0';
// Set other required fields
// Use open auth if no password, otherwise allow any WPA variant
if (strlen(password) == 0)
{
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_OPEN;
}
else
{
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
// IMPORTANT: Set threshold to WEP to accept ANY security mode >= WEP
// This allows WPA, WPA2, WPA3, etc. The driver will negotiate the highest common mode
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_WEP;
}
ESP_LOGI(WIFI_MANAGER_TAG, "connect to the AP fail");
}
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
{
const auto *event = static_cast<ip_event_got_ip_t *>(event_data);
ESP_LOGI(WIFI_MANAGER_TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
// CRITICAL: Disable PMF completely - this often causes handshake timeouts
_wifi_cfg.sta.pmf_cfg.capable = false;
_wifi_cfg.sta.pmf_cfg.required = false;
WiFiManager::WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager *stateManager)
: deviceConfig(deviceConfig), eventQueue(eventQueue), stateManager(stateManager), wifiScanner(std::make_unique<WiFiScanner>()) {}
// OPTIMIZATION: Use fast scan instead of all channel scan for quicker connection
_wifi_cfg.sta.scan_method = WIFI_FAST_SCAN;
_wifi_cfg.sta.bssid_set = 0; // Don't use specific BSSID
_wifi_cfg.sta.channel = 0; // Auto channel detection
void WiFiManager::SetCredentials(const char *ssid, const char *password)
{
// Clear the config first
memset(&_wifi_cfg, 0, sizeof(_wifi_cfg));
// Additional settings that might help with compatibility
_wifi_cfg.sta.listen_interval = 0; // Default listen interval
_wifi_cfg.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL; // Connect to strongest signal
// Copy SSID with null termination
size_t ssid_len = std::min(strlen(ssid), sizeof(_wifi_cfg.sta.ssid) - 1);
memcpy(_wifi_cfg.sta.ssid, ssid, ssid_len);
_wifi_cfg.sta.ssid[ssid_len] = '\0';
// IMPORTANT: For WPA/WPA2 Personal networks
_wifi_cfg.sta.threshold.rssi = -127; // Accept any signal strength
_wifi_cfg.sta.sae_pwe_h2e = WPA3_SAE_PWE_UNSPECIFIED; // Let driver decide SAE mode
// Copy password with null termination
size_t pass_len = std::min(strlen(password), sizeof(_wifi_cfg.sta.password) - 1);
memcpy(_wifi_cfg.sta.password, password, pass_len);
_wifi_cfg.sta.password[pass_len] = '\0';
// Set other required fields
// Use open auth if no password, otherwise allow any WPA variant
if (strlen(password) == 0)
{
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_OPEN;
}
else
{
// IMPORTANT: Set threshold to WEP to accept ANY security mode >= WEP
// This allows WPA, WPA2, WPA3, etc. The driver will negotiate the highest common mode
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_WEP;
}
// CRITICAL: Disable PMF completely - this often causes handshake timeouts
_wifi_cfg.sta.pmf_cfg.capable = false;
_wifi_cfg.sta.pmf_cfg.required = false;
// OPTIMIZATION: Use fast scan instead of all channel scan for quicker connection
_wifi_cfg.sta.scan_method = WIFI_FAST_SCAN;
_wifi_cfg.sta.bssid_set = 0; // Don't use specific BSSID
_wifi_cfg.sta.channel = 0; // Auto channel detection
// Additional settings that might help with compatibility
_wifi_cfg.sta.listen_interval = 0; // Default listen interval
_wifi_cfg.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL; // Connect to strongest signal
// IMPORTANT: For WPA/WPA2 Personal networks
_wifi_cfg.sta.threshold.rssi = -127; // Accept any signal strength
_wifi_cfg.sta.sae_pwe_h2e = WPA3_SAE_PWE_UNSPECIFIED; // Let driver decide SAE mode
// Log what we're trying to connect to with detailed debugging
ESP_LOGI(WIFI_MANAGER_TAG, "Setting credentials for SSID: '%s' (length: %d)", ssid, (int)strlen(ssid));
ESP_LOGI(WIFI_MANAGER_TAG, "Password: '%s' (length: %d)", password, (int)strlen(password));
ESP_LOGI(WIFI_MANAGER_TAG, "Auth mode: %d, PMF capable: %d",
_wifi_cfg.sta.threshold.authmode, _wifi_cfg.sta.pmf_cfg.capable);
// Log what we're trying to connect to with detailed debugging
ESP_LOGI(WIFI_MANAGER_TAG, "Setting credentials for SSID: '%s' (length: %d)", ssid, (int)strlen(ssid));
ESP_LOGI(WIFI_MANAGER_TAG, "Password: '%s' (length: %d)", password, (int)strlen(password));
ESP_LOGI(WIFI_MANAGER_TAG, "Auth mode: %d, PMF capable: %d", _wifi_cfg.sta.threshold.authmode, _wifi_cfg.sta.pmf_cfg.capable);
}
void WiFiManager::ConnectWithHardcodedCredentials()
{
SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConnect};
this->SetCredentials(CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD);
SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConnect};
this->SetCredentials(CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD);
wifi_mode_t mode;
if (esp_wifi_get_mode(&mode) == ESP_OK) {
esp_wifi_stop();
}
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg));
xQueueSend(this->eventQueue, &event, 10);
esp_wifi_start();
event.value = WiFiState_e::WiFiState_Connecting;
xQueueSend(this->eventQueue, &event, 10);
// Use shorter timeout for faster startup - 8 seconds should be enough for most networks
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
pdMS_TO_TICKS(8000));
/* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
* happened. */
if (bits & WIFI_CONNECTED_BIT)
{
ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%p password:%p",
_wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Connected;
xQueueSend(this->eventQueue, &event, 10);
}
else if (bits & WIFI_FAIL_BIT)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%p, password:%p",
_wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Error;
xQueueSend(this->eventQueue, &event, 10);
}
else
{
ESP_LOGE(WIFI_MANAGER_TAG, "UNEXPECTED EVENT");
}
}
void WiFiManager::ConnectWithStoredCredentials()
{
SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConnect};
auto const networks = this->deviceConfig->getWifiConfigs();
if (networks.empty())
{
event.value = WiFiState_e::WiFiState_Disconnected;
xQueueSend(this->eventQueue, &event, 10);
ESP_LOGE(WIFI_MANAGER_TAG, "No networks stored, cannot connect");
return;
}
// Stop WiFi once before the loop
esp_wifi_stop();
vTaskDelay(pdMS_TO_TICKS(100));
// Ensure we're in STA mode
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
for (const auto &network : networks)
{
// Reset retry counter for each network attempt
s_retry_num = 0;
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
this->SetCredentials(network.ssid.c_str(), network.password.c_str());
// Update config without stopping WiFi again
ESP_LOGI(WIFI_MANAGER_TAG, "Attempting to connect to SSID: '%s'", network.ssid.c_str());
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg));
xQueueSend(this->eventQueue, &event, 10);
// Start WiFi if not already started
esp_err_t start_err = esp_wifi_start();
if (start_err != ESP_OK && start_err != ESP_ERR_WIFI_STATE)
wifi_mode_t mode;
if (esp_wifi_get_mode(&mode) == ESP_OK)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to start WiFi: %s", esp_err_to_name(start_err));
continue;
esp_wifi_stop();
}
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg));
xQueueSend(this->eventQueue, &event, 10);
esp_wifi_start();
event.value = WiFiState_e::WiFiState_Connecting;
xQueueSend(this->eventQueue, &event, 10);
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
pdMS_TO_TICKS(10000)); // 10 second timeout for faster failover
// Use shorter timeout for faster startup - 8 seconds should be enough for most networks
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE, pdMS_TO_TICKS(8000));
/* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
* happened. */
if (bits & WIFI_CONNECTED_BIT)
{
ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%s",
network.ssid.c_str());
ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%p password:%p", _wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Connected;
xQueueSend(this->eventQueue, &event, 10);
return;
event.value = WiFiState_e::WiFiState_Connected;
xQueueSend(this->eventQueue, &event, 10);
}
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%s, trying next stored network",
network.ssid.c_str());
// Disconnect before trying next network
esp_wifi_disconnect();
else if (bits & WIFI_FAIL_BIT)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%p, password:%p", _wifi_cfg.sta.ssid, _wifi_cfg.sta.password);
event.value = WiFiState_e::WiFiState_Error;
xQueueSend(this->eventQueue, &event, 10);
}
else
{
ESP_LOGE(WIFI_MANAGER_TAG, "UNEXPECTED EVENT");
}
}
void WiFiManager::ConnectWithStoredCredentials()
{
SystemEvent event = {EventSource::WIFI, WiFiState_e::WiFiState_ReadyToConnect};
auto const networks = this->deviceConfig->getWifiConfigs();
if (networks.empty())
{
event.value = WiFiState_e::WiFiState_Disconnected;
xQueueSend(this->eventQueue, &event, 10);
ESP_LOGE(WIFI_MANAGER_TAG, "No networks stored, cannot connect");
return;
}
// Stop WiFi once before the loop
esp_wifi_stop();
vTaskDelay(pdMS_TO_TICKS(100));
}
event.value = WiFiState_e::WiFiState_Error;
xQueueSend(this->eventQueue, &event, 10);
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to all saved networks");
// Ensure we're in STA mode
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
for (const auto& network : networks)
{
// Reset retry counter for each network attempt
s_retry_num = 0;
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
this->SetCredentials(network.ssid.c_str(), network.password.c_str());
// Update config without stopping WiFi again
ESP_LOGI(WIFI_MANAGER_TAG, "Attempting to connect to SSID: '%s'", network.ssid.c_str());
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &_wifi_cfg));
xQueueSend(this->eventQueue, &event, 10);
// Start WiFi if not already started
esp_err_t start_err = esp_wifi_start();
if (start_err != ESP_OK && start_err != ESP_ERR_WIFI_STATE)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to start WiFi: %s", esp_err_to_name(start_err));
continue;
}
event.value = WiFiState_e::WiFiState_Connecting;
xQueueSend(this->eventQueue, &event, 10);
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE,
pdMS_TO_TICKS(10000)); // 10 second timeout for faster failover
if (bits & WIFI_CONNECTED_BIT)
{
ESP_LOGI(WIFI_MANAGER_TAG, "connected to ap SSID:%s", network.ssid.c_str());
event.value = WiFiState_e::WiFiState_Connected;
xQueueSend(this->eventQueue, &event, 10);
return;
}
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to SSID:%s, trying next stored network", network.ssid.c_str());
// Disconnect before trying next network
esp_wifi_disconnect();
vTaskDelay(pdMS_TO_TICKS(100));
}
event.value = WiFiState_e::WiFiState_Error;
xQueueSend(this->eventQueue, &event, 10);
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to connect to all saved networks");
}
void WiFiManager::SetupAccessPoint()
{
ESP_LOGI(WIFI_MANAGER_TAG, "Connection to stored credentials failed, starting AP");
ESP_LOGI(WIFI_MANAGER_TAG, "Connection to stored credentials failed, starting AP");
esp_netif_create_default_wifi_ap();
wifi_init_config_t esp_wifi_ap_init_config = WIFI_INIT_CONFIG_DEFAULT();
esp_netif_create_default_wifi_ap();
wifi_init_config_t esp_wifi_ap_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_ap_init_config));
ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_ap_init_config));
wifi_config_t ap_wifi_config = {
.ap = {
.ssid = CONFIG_WIFI_AP_SSID,
.password = CONFIG_WIFI_AP_PASSWORD,
.max_connection = 1,
wifi_config_t ap_wifi_config = {
.ap =
{
.ssid = CONFIG_WIFI_AP_SSID,
.password = CONFIG_WIFI_AP_PASSWORD,
.max_connection = 1,
},
};
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(WIFI_MANAGER_TAG, "AP started.");
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(WIFI_MANAGER_TAG, "AP started.");
}
std::vector<WiFiNetwork> WiFiManager::ScanNetworks(int timeout_ms)
{
wifi_mode_t current_mode;
esp_err_t err = esp_wifi_get_mode(&current_mode);
wifi_mode_t current_mode;
esp_err_t err = esp_wifi_get_mode(&current_mode);
if (err == ESP_ERR_WIFI_NOT_INIT)
{
ESP_LOGE(WIFI_MANAGER_TAG, "WiFi not initialized for scanning");
return std::vector<WiFiNetwork>();
}
// If we're in AP-only mode, we need STA interface for scanning
if (current_mode == WIFI_MODE_AP)
{
ESP_LOGI(WIFI_MANAGER_TAG, "AP mode detected, checking for STA interface");
// Check if STA netif already exists
esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
bool sta_netif_exists = (sta_netif != nullptr);
if (!sta_netif_exists)
if (err == ESP_ERR_WIFI_NOT_INIT)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Creating STA interface for scanning");
sta_netif = esp_netif_create_default_wifi_sta();
ESP_LOGE(WIFI_MANAGER_TAG, "WiFi not initialized for scanning");
return std::vector<WiFiNetwork>();
}
ESP_LOGI(WIFI_MANAGER_TAG, "Switching to APSTA mode for scanning");
err = esp_wifi_set_mode(WIFI_MODE_APSTA);
if (err != ESP_OK)
// If we're in AP-only mode, we need STA interface for scanning
if (current_mode == WIFI_MODE_AP)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to set APSTA mode: %s", esp_err_to_name(err));
if (!sta_netif_exists && sta_netif)
{
esp_netif_destroy(sta_netif);
}
return std::vector<WiFiNetwork>();
ESP_LOGI(WIFI_MANAGER_TAG, "AP mode detected, checking for STA interface");
// Check if STA netif already exists
esp_netif_t* sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
bool sta_netif_exists = (sta_netif != nullptr);
if (!sta_netif_exists)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Creating STA interface for scanning");
sta_netif = esp_netif_create_default_wifi_sta();
}
ESP_LOGI(WIFI_MANAGER_TAG, "Switching to APSTA mode for scanning");
err = esp_wifi_set_mode(WIFI_MODE_APSTA);
if (err != ESP_OK)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to set APSTA mode: %s", esp_err_to_name(err));
if (!sta_netif_exists && sta_netif)
{
esp_netif_destroy(sta_netif);
}
return std::vector<WiFiNetwork>();
}
// Configure STA with empty config to prevent auto-connect
wifi_config_t empty_config = {};
esp_wifi_set_config(WIFI_IF_STA, &empty_config);
// Ensure STA is disconnected and not trying to connect
esp_wifi_disconnect();
// Longer delay for mode to stabilize and enable all channels
vTaskDelay(pdMS_TO_TICKS(2000));
// Perform scan
auto networks = wifiScanner->scanNetworks(timeout_ms);
// Restore AP-only mode
ESP_LOGI(WIFI_MANAGER_TAG, "Restoring AP-only mode");
esp_wifi_set_mode(WIFI_MODE_AP);
// Clean up STA interface if we created it
if (!sta_netif_exists && sta_netif)
{
esp_netif_destroy(sta_netif);
}
return networks;
}
// Configure STA with empty config to prevent auto-connect
wifi_config_t empty_config = {};
esp_wifi_set_config(WIFI_IF_STA, &empty_config);
// Ensure STA is disconnected and not trying to connect
esp_wifi_disconnect();
// Longer delay for mode to stabilize and enable all channels
vTaskDelay(pdMS_TO_TICKS(2000));
// Perform scan
auto networks = wifiScanner->scanNetworks(timeout_ms);
// Restore AP-only mode
ESP_LOGI(WIFI_MANAGER_TAG, "Restoring AP-only mode");
esp_wifi_set_mode(WIFI_MODE_AP);
// Clean up STA interface if we created it
if (!sta_netif_exists && sta_netif)
{
esp_netif_destroy(sta_netif);
}
return networks;
}
// If already in STA or APSTA mode, scan directly
return wifiScanner->scanNetworks(timeout_ms);
// If already in STA or APSTA mode, scan directly
return wifiScanner->scanNetworks(timeout_ms);
}
WiFiState_e WiFiManager::GetCurrentWiFiState()
{
return this->stateManager->GetWifiState();
return this->stateManager->GetWifiState();
}
void WiFiManager::TryConnectToStoredNetworks()
{
ESP_LOGI(WIFI_MANAGER_TAG, "Manual WiFi connection attempt requested");
ESP_LOGI(WIFI_MANAGER_TAG, "Manual WiFi connection attempt requested");
// Check current WiFi mode
wifi_mode_t current_mode;
esp_err_t err = esp_wifi_get_mode(&current_mode);
if (err != ESP_OK)
{
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to get WiFi mode: %s", esp_err_to_name(err));
return;
}
// If in AP mode, we need to properly transition to STA mode
if (current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Currently in AP mode, transitioning to STA mode");
// Stop WiFi first
esp_wifi_stop();
vTaskDelay(pdMS_TO_TICKS(100));
// Check if STA interface exists, create if needed
esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
if (sta_netif == nullptr)
// Check current WiFi mode
wifi_mode_t current_mode;
esp_err_t err = esp_wifi_get_mode(&current_mode);
if (err != ESP_OK)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Creating STA interface");
sta_netif = esp_netif_create_default_wifi_sta();
ESP_LOGE(WIFI_MANAGER_TAG, "Failed to get WiFi mode: %s", esp_err_to_name(err));
return;
}
// Set to STA mode
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
vTaskDelay(pdMS_TO_TICKS(100));
}
// If in AP mode, we need to properly transition to STA mode
if (current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Currently in AP mode, transitioning to STA mode");
// Reset retry counter and clear all event bits
s_retry_num = 0;
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
this->ConnectWithStoredCredentials();
// Stop WiFi first
esp_wifi_stop();
vTaskDelay(pdMS_TO_TICKS(100));
// Check if STA interface exists, create if needed
esp_netif_t* sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
if (sta_netif == nullptr)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Creating STA interface");
sta_netif = esp_netif_create_default_wifi_sta();
}
// Set to STA mode
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
vTaskDelay(pdMS_TO_TICKS(100));
}
// Reset retry counter and clear all event bits
s_retry_num = 0;
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
this->ConnectWithStoredCredentials();
}
void WiFiManager::Begin()
{
s_wifi_event_group = xEventGroupCreate();
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
auto netif = esp_netif_create_default_wifi_sta();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
auto netif = esp_netif_create_default_wifi_sta();
wifi_init_config_t esp_wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_init_config));
wifi_init_config_t esp_wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&esp_wifi_init_config));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&WiFiManagerHelpers::event_handler,
nullptr,
&instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&WiFiManagerHelpers::event_handler,
nullptr,
&instance_got_ip));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &WiFiManagerHelpers::event_handler, nullptr, &instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &WiFiManagerHelpers::event_handler, nullptr, &instance_got_ip));
_wifi_cfg = {};
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_OPEN; // Start with open, will be set properly by SetCredentials
_wifi_cfg.sta.pmf_cfg.capable = false; // Disable PMF by default
_wifi_cfg.sta.pmf_cfg.required = false;
_wifi_cfg = {};
_wifi_cfg.sta.threshold.authmode = WIFI_AUTH_OPEN; // Start with open, will be set properly by SetCredentials
_wifi_cfg.sta.pmf_cfg.capable = false; // Disable PMF by default
_wifi_cfg.sta.pmf_cfg.required = false;
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_LOGI(WIFI_MANAGER_TAG, "Beginning setup");
const auto hasHardcodedCredentials = strlen(CONFIG_WIFI_SSID) > 0;
if (hasHardcodedCredentials)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Detected hardcoded credentials, trying them out");
this->ConnectWithHardcodedCredentials();
}
ESP_LOGI(WIFI_MANAGER_TAG, "Beginning setup");
const auto hasHardcodedCredentials = strlen(CONFIG_WIFI_SSID) > 0;
if (hasHardcodedCredentials)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Detected hardcoded credentials, trying them out");
this->ConnectWithHardcodedCredentials();
}
if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected || !hasHardcodedCredentials)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Hardcoded credentials failed or missing, trying stored credentials");
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
this->ConnectWithStoredCredentials();
}
if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected || !hasHardcodedCredentials)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Hardcoded credentials failed or missing, trying stored credentials");
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
this->ConnectWithStoredCredentials();
}
if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Stored netoworks failed or hardcoded credentials missing, starting AP");
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
esp_netif_destroy(netif);
this->SetupAccessPoint();
}
if (this->stateManager->GetWifiState() != WiFiState_e::WiFiState_Connected)
{
ESP_LOGI(WIFI_MANAGER_TAG, "Stored netoworks failed or hardcoded credentials missing, starting AP");
xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
esp_netif_destroy(netif);
this->SetupAccessPoint();
}
}

View File

@@ -2,16 +2,16 @@
#ifndef WIFIHANDLER_HPP
#define WIFIHANDLER_HPP
#include <string>
#include <cstring>
#include <algorithm>
#include <StateManager.hpp>
#include <ProjectConfig.hpp>
#include <StateManager.hpp>
#include <algorithm>
#include <cstring>
#include <string>
#include "WiFiScanner.hpp"
#include "esp_event.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
@@ -21,37 +21,36 @@
namespace WiFiManagerHelpers
{
void event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data);
void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
}
class WiFiManager
{
private:
uint8_t channel;
std::shared_ptr<ProjectConfig> deviceConfig;
QueueHandle_t eventQueue;
StateManager *stateManager;
wifi_init_config_t _wifi_init_cfg = WIFI_INIT_CONFIG_DEFAULT();
wifi_config_t _wifi_cfg = {};
std::unique_ptr<WiFiScanner> wifiScanner;
private:
uint8_t channel;
std::shared_ptr<ProjectConfig> deviceConfig;
QueueHandle_t eventQueue;
StateManager* stateManager;
wifi_init_config_t _wifi_init_cfg = WIFI_INIT_CONFIG_DEFAULT();
wifi_config_t _wifi_cfg = {};
std::unique_ptr<WiFiScanner> wifiScanner;
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
int8_t power;
int8_t power;
void SetCredentials(const char *ssid, const char *password);
void ConnectWithHardcodedCredentials();
void ConnectWithStoredCredentials();
void SetupAccessPoint();
void SetCredentials(const char* ssid, const char* password);
void ConnectWithHardcodedCredentials();
void ConnectWithStoredCredentials();
void SetupAccessPoint();
public:
WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager *stateManager);
void Begin();
std::vector<WiFiNetwork> ScanNetworks(int timeout_ms = 15000);
WiFiState_e GetCurrentWiFiState();
void TryConnectToStoredNetworks();
public:
WiFiManager(std::shared_ptr<ProjectConfig> deviceConfig, QueueHandle_t eventQueue, StateManager* stateManager);
void Begin();
std::vector<WiFiNetwork> ScanNetworks(int timeout_ms = 15000);
WiFiState_e GetCurrentWiFiState();
void TryConnectToStoredNetworks();
};
#endif