79 lines
2.7 KiB
C
79 lines
2.7 KiB
C
#include "esp_system.h"
|
|
#include "esp_wifi.h"
|
|
#include "esp_event.h"
|
|
#include "esp_log.h"
|
|
#include "nvs_flash.h"
|
|
|
|
#include "lwip/err.h"
|
|
#include "lwip/sys.h"
|
|
|
|
#include "app_lib_wifi_impl.h"
|
|
|
|
EventGroupHandle_t g_wifi_event_group;
|
|
|
|
static uint8_t s_retry_num = 0;
|
|
static const char *TAG = "APP_WIFI";
|
|
|
|
#define APP_WIFI_SSID CONFIG_APP_WIFI_SSID
|
|
#define APP_WIFI_PASS CONFIG_APP_WIFI_PASSWORD
|
|
#define APP_WIFI_RETR CONFIG_APP_WIFI_MAXIMUM_RETRY
|
|
|
|
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) {
|
|
esp_wifi_connect();
|
|
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
|
if (s_retry_num < APP_WIFI_RETR) {
|
|
esp_wifi_connect();
|
|
s_retry_num++;
|
|
ESP_LOGI(TAG, "Connect attempt failed, retrying (%u/%u)...", s_retry_num, APP_WIFI_RETR);
|
|
} else {
|
|
xEventGroupSetBits(g_wifi_event_group, WIFI_ERROR_BIT);
|
|
ESP_LOGI(TAG, "WiFi connection failed, no more retries scheduled.");
|
|
}
|
|
} 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, "Client IP:" IPSTR, IP2STR(&event->ip_info.ip));
|
|
s_retry_num = 0;
|
|
xEventGroupSetBits(g_wifi_event_group, WIFI_CONNECTED_BIT);
|
|
}
|
|
}
|
|
|
|
void app_lib_start_wifi(void) {
|
|
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);
|
|
|
|
g_wifi_event_group = xEventGroupCreate();
|
|
|
|
ESP_ERROR_CHECK(esp_netif_init());
|
|
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
|
esp_netif_create_default_wifi_sta();
|
|
|
|
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
|
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
|
|
|
esp_event_handler_instance_t instance_any_id;
|
|
esp_event_handler_instance_t instance_got_ip;
|
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &instance_any_id));
|
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, &instance_got_ip));
|
|
|
|
wifi_config_t wifi_config = {
|
|
.sta = {
|
|
.ssid = APP_WIFI_SSID,
|
|
.password = APP_WIFI_PASS,
|
|
.threshold.authmode = WIFI_AUTH_WPA2_PSK,
|
|
|
|
.pmf_cfg = {
|
|
.capable = true,
|
|
.required = false
|
|
}
|
|
}
|
|
};
|
|
|
|
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
|
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
|
|
ESP_ERROR_CHECK(esp_wifi_start());
|
|
} |