Wi-Fi AP模式入门(基于ESP-IDF)
主要参考资料:
Wi-Fi 库: https://docs.espressif.com/projects/esp-idf/zh_CN/v4.4/esp32s3/api-reference/network/esp_wifi.html
ESP-NETIF: https://docs.espressif.com/projects/esp-idf/zh_CN/v4.4/esp32s3/api-reference/network/esp_netif.html
Wi-Fi 初始化 AP
void wifi_init_softap(void)
{//初始化底层TCP/IP堆栈ESP_ERROR_CHECK(esp_netif_init());ESP_ERROR_CHECK(esp_event_loop_create_default());//初始化代码以及为默认接口(如softAP和station)注册事件处理程序,在两个单独的api中提供,以方便大多数应用程序的简单启动代码:esp_netif_create_default_wifi_ap();wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();//为WiFi驱动分配资源,如WiFi控制结构、RX/TX缓冲区、WiFi NVS结构等。这个WiFi也会启动WiFi任务。ESP_ERROR_CHECK(esp_wifi_init(&cfg));ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,ESP_EVENT_ANY_ID,&wifi_event_handler,NULL,NULL));wifi_config_t wifi_config = {.ap = {.ssid = EXAMPLE_ESP_WIFI_SSID,.ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),.channel = EXAMPLE_ESP_WIFI_CHANNEL,.password = EXAMPLE_ESP_WIFI_PASS,.max_connection = EXAMPLE_MAX_STA_CONN,.authmode = WIFI_AUTH_WPA_WPA2_PSK},};//如果不设置莫玛,就是开放模式if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0) {wifi_config.ap.authmode = WIFI_AUTH_OPEN;}//设置Wi-Fi运行模式为station, soft-AP 或者 station+soft-AP,默认模式为station.ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));//根据当前配置启动WiFi,如果模式为WIFI_MODE_AP,则创建soft-ap控制块并启动soft-ap;ESP_ERROR_CHECK(esp_wifi_start());ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d",EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS, EXAMPLE_ESP_WIFI_CHANNEL);
}
Wi-Fi 事件回调
static void wifi_event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data)
{if (event_id == WIFI_EVENT_AP_STACONNECTED) {wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;ESP_LOGI(TAG, "station "MACSTR" join, AID=%d",MAC2STR(event->mac), event->aid);} else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) {wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;ESP_LOGI(TAG, "station "MACSTR" leave, AID=%d",MAC2STR(event->mac), event->aid);}
}