[Info] Snippet: Perform an access point scan and list

User avatar
kolban
Posts: 1683
Joined: Mon Nov 16, 2015 4:43 pm
Location: Texas, USA

[Info] Snippet: Perform an access point scan and list

Postby kolban » Sat Oct 08, 2016 3:43 am

In this sample snippet of code we test out performing an access point scan. We register an event callback and when a scan done event is raised to indicate that the scan is complete, we log the details.

Code: Select all

#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include "nvs_flash.h"

esp_err_t event_handler(void *ctx, system_event_t *event)
{
   if (event->event_id == SYSTEM_EVENT_SCAN_DONE) {
      printf("Number of access points found: %d\n",
event->event_info.scan_done.number);
      uint16_t apCount = event->event_info.scan_done.number;
      if (apCount == 0) {
         return ESP_OK;
      }
      wifi_ap_list_t *list = (wifi_ap_list_t *)malloc(sizeof(wifi_ap_list_t) * apCount);
      ESP_ERROR_CHECK(esp_wifi_get_ap_list(&apCount, list));
      int i;
      for (i=0; i<apCount; i++) {
         char *authmode;
         switch(list[i].authmode) {
            case WIFI_AUTH_OPEN:
               authmode = "WIFI_AUTH_OPEN";
               break;
            case WIFI_AUTH_WEP:
               authmode = "WIFI_AUTH_WEP";
               break;           
            case WIFI_AUTH_WPA_PSK:
               authmode = "WIFI_AUTH_WPA_PSK";
               break;           
            case WIFI_AUTH_WPA2_PSK:
               authmode = "WIFI_AUTH_WPA2_PSK";
               break;           
            case WIFI_AUTH_WPA_WPA2_PSK:
               authmode = "WIFI_AUTH_WPA_WPA2_PSK";
               break;
            default:
               authmode = "Unknown";
               break;
         }
         printf("ssid=%s, rssi=%d, authmode=%s\n", list[i].ssid, list[i].rssi, authmode);
      }
      free(list);
   }
   return ESP_OK;
}

int app_main(void)
{
   nvs_flash_init();
   system_init();
   tcpip_adapter_init();
   ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
   wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
   ESP_ERROR_CHECK(esp_wifi_init(&cfg));
   ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
   ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
   ESP_ERROR_CHECK(esp_wifi_start());

   // Let us test a WiFi scan ...
   wifi_scan_config_t scanConf = {
      .ssid = NULL,
      .bssid = NULL,
      .channel = 0,
      .show_hidden = true
   };
   ESP_ERROR_CHECK(esp_wifi_scan_start(&scanConf, false));

   return 0;
}
Free book on ESP32 available here: https://leanpub.com/kolban-ESP32

Who is online

Users browsing this forum: No registered users and 4 guests