diff --git a/include/esp32-wifi-manager.h b/include/esp32-wifi-manager.h index d4955fd..c143543 100644 --- a/include/esp32-wifi-manager.h +++ b/include/esp32-wifi-manager.h @@ -11,6 +11,7 @@ void wifi_manager_reset_store(); #define WIFI_CONNECTING (BIT1) #define AP_AVAILABLE (BIT2) #define WIFI_IDLE (BIT3) +#define WIFI_SCANNING (BIT4) uint8_t wifi_manager_ap_count(); uint8_t wifi_manager_add_ap(char *essid, char *password); diff --git a/main/esp32-wifi-manager.c b/main/esp32-wifi-manager.c index 12aaa36..0843dc8 100644 --- a/main/esp32-wifi-manager.c +++ b/main/esp32-wifi-manager.c @@ -78,6 +78,8 @@ static esp_err_t wifi_event_handler(void *ctx, system_event_t *event) { wifi_manager_connect(); } break; + case SYSTEM_EVENT_SCAN_DONE: + ESP_LOGI(TAG, "SYSTEM_EVENT_SCAN_DONE"); default: break; } @@ -101,14 +103,22 @@ uint8_t wifi_manager_add_ap(char *ssid, char *password) { }; void wifi_manager_connect() { + ESP_ERROR_CHECK(esp_wifi_start()); + wifi_config_t wifi_config = { .sta = { } }; + wifi_scan_config_t scan_config = { 0 }; - xEventGroupSetBits(wm_event_group, WIFI_CONNECTING); + ESP_ERROR_CHECK(esp_wifi_scan_start(&scan_config, false)); + + ESP_LOGI(TAG, "setting WIFI_SCANNING bit"); + xEventGroupSetBits(wm_event_group, WIFI_SCANNING); xEventGroupClearBits(wm_event_group, WIFI_IDLE); + return; + ESP_LOGI(TAG, "connecting to AP %d of %d", ap_store.last + 1, ap_store.count); memcpy((char *)&wifi_config.sta.ssid, ap_store.aps[ap_store.last].ssid, strlen(ap_store.aps[ap_store.last].ssid) + 1); @@ -116,7 +126,6 @@ void wifi_manager_connect() { ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) ); - ESP_ERROR_CHECK(esp_wifi_start()); ESP_LOGI(TAG, "wifi_init_sta finished."); ESP_LOGI(TAG, "connect to ap SSID:%s password:%s", @@ -127,11 +136,14 @@ void wifi_manager_connect() { void wifi_manager_main_loop() { ap_store.last = 0; + vTaskDelay(3000 / portTICK_PERIOD_MS); while(true) { EventBits_t ev_bits = xEventGroupGetBits(wm_event_group); - if(ev_bits & AP_AVAILABLE && (ev_bits & WIFI_CONNECTING) == 0) { + if(ev_bits & AP_AVAILABLE && + !(ev_bits & (WIFI_SCANNING|WIFI_CONNECTED|WIFI_CONNECTING)) + ) { ESP_LOGI(TAG, "AP Available, starting WiFi connect"); wifi_manager_connect(); @@ -168,8 +180,11 @@ void wifi_manager_reset_store() { memset(&ap_store, 0, sizeof(ap_store)); + xEventGroupClearBits(wm_event_group, AP_AVAILABLE); + ap_store.magic = WIFI_MANAGER_MAGIC; ap_store.last = -1; + ap_store.count = 0; wifi_manager_save_config(); }; @@ -197,10 +212,9 @@ void wifi_manager_load_config() { } uint8_t i = 0; + ESP_LOGI(TAG, "load_config found %d APs", ap_store.count); for(; i < ap_store.count; i++) ESP_LOGI(TAG, "AP: %s", ap_store.aps[i].ssid); - - ESP_LOGI(TAG, "load_config found %d APs", ap_store.count); }; EventGroupHandle_t wifi_manager_start() {