#include "esp_log.h" #include "esp_wifi.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #define WIFI_SCAN_TASK_STACK_SIZE 4096 #define WIFI_SCAN_TASK_PRIORITY 5 #define WIFI_SCAN_MAX_APS 20 #define WIFI_SCAN_POLL_INTERVAL_MS 500 #define WIFI_SCAN_DEFAULT_CHANNEL 0 #define WIFI_SCAN_SHOW_HIDDEN true #define WIFI_SCAN_TASK_NAME "wifi_scan_task" /** * @brief Asynchronous WiFi scanning task for ESP32 with FreeRTOS. * * Configures and initiates a non-blocking WiFi scan on the specified or all * channels, including hidden networks if enabled. Periodically polls for scan * completion without blocking other tasks, retrieves discovered access points * up to a defined maximum, and logs each AP's SSID and signal strength (RSSI). * * After logging, the task self-deletes to free system resources. * * This design ensures WiFi scanning runs in the background, preserving system * responsiveness and maintaining real-time operation in embedded applications. * * @param pvParameter Pointer to task parameters (unused). */ static void wifi_scan_task(void *pvParameter) { uint16_t ap_count = WIFI_SCAN_MAX_APS; static wifi_ap_record_t ap_info[WIFI_SCAN_MAX_APS]; wifi_scan_config_t scan_config = { .ssid = NULL, .bssid = NULL, .channel = WIFI_SCAN_DEFAULT_CHANNEL, .show_hidden = WIFI_SCAN_SHOW_HIDDEN, }; ESP_LOGI("wifi_scan", "Starting Wi-Fi scan..."); ESP_ERROR_CHECK(esp_wifi_scan_start(&scan_config, false)); while (true) { uint16_t finished_ap_count = 0; ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&finished_ap_count)); if (finished_ap_count > 0) { break; } vTaskDelay(pdMS_TO_TICKS(WIFI_SCAN_POLL_INTERVAL_MS)); } ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&ap_count, ap_info)); ESP_LOGI("wifi_scan", "Found %d access points:", ap_count); for (uint16_t ap_index = 0; ap_index < ap_count; ++ap_index) { ESP_LOGI("wifi_scan", "%d: SSID: %s, RSSI: %d", ap_index + 1, ap_info[ap_index].ssid, ap_info[ap_index].rssi); } vTaskDelete(NULL); } /** * @brief Starts the WiFi scan task. * * Creates a FreeRTOS task that runs the WiFi scan asynchronously. */ void wifi_scan_start(void) { xTaskCreate(wifi_scan_task, WIFI_SCAN_TASK_NAME, WIFI_SCAN_TASK_STACK_SIZE, NULL, WIFI_SCAN_TASK_PRIORITY, NULL); }