连接wifi

对于 event_data 根据对应事件类型,到头文件查询,例如如果是 WIFI_ENVENT , 就去查询定义 WIFI_ENEVT 所在的头文件找对应的 structure , 通常都是 structure for EVENT_XXX 的注释, 例如 wifi_event_sta_connected_t *event = (wifi_event_sta_connected_t *)event_data 解析event_data。

image.png

#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "esp_wifi_default.h"
#include "esp_wifi_types_generic.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <assert.h>
#include <stdio.h>

static const char *TAG = "scan";

static void event_handler(void *arg, esp_event_base_t event_base,
                          int32_t event_id, void *event_data) {
  if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
	  // STA开始工作, esp_wifi_connect 只会连接一次
    esp_wifi_connect();
  } else if (event_base == WIFI_EVENT &&
             event_id == WIFI_EVENT_STA_DISCONNECTED) {
    // 或许你可以引入超时机制
    esp_wifi_connect();
  } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
    ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
    ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
  }
}

void wifiInit() {
	// 初始化 netif 和事件轮训
  ESP_ERROR_CHECK(esp_netif_init());
  ESP_ERROR_CHECK(esp_event_loop_create_default());

	// 默认配置设置wifi
  wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  ESP_ERROR_CHECK(esp_wifi_init(&cfg));

	// 注册事件回调
  ESP_ERROR_CHECK(esp_event_handler_instance_register(
      WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, NULL));
  ESP_ERROR_CHECK(esp_event_handler_instance_register(
      IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, NULL));

  // 初始化 sta 和 netif, 个人感觉是为netif接入sta
  esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
  assert(sta_netif);
  ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));

  // sta 配置, 你要连接哪个wifi
  wifi_config_t wifi_config = {
      .sta =
          {
              .ssid = "Man_2.4GHz",
              .password = "liang114514",
          },
  };
  ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
  
  // 开始干活
  ESP_ERROR_CHECK(esp_wifi_start());
}

void app_main() {
  esp_err_t ret = nvs_flash_init();
  if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
      ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
    ESP_ERROR_CHECK(nvs_flash_erase());
    ret = nvs_flash_init();
  }
  ESP_ERROR_CHECK(ret);
  wifiInit();
}