#include "esp_event.h" #include "esp_log.h" #include "esp_wifi.h" #include "freertos/task.h" #include "secrets.h" static const char *TAG = "wifi"; // Logs are coming from this wifi module static uint32_t WIFI_CONNECTED = 0; static int s_retry_num = 0; #define MAX_RETRY 5 static void wifi_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(); } if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { if (s_retry_num < MAX_RETRY) { esp_wifi_connect(); s_retry_num++; ESP_LOGI(TAG, "Trying to reconnect to WiFi."); } else { ESP_LOGI(TAG, "Could not connect to WiFi. Giving up."); } } if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { s_retry_num = 0; WIFI_CONNECTED = 1; } } void wifi_connect(void) { ESP_LOGI(TAG, "Attempting to connect to WiFi"); // Initialise network interface layer (Internet Layer) once Link Layer // established (in standard TCP/IP architecture) ESP_ERROR_CHECK(esp_netif_init()); // Create default event dispatcher ESP_ERROR_CHECK(esp_event_loop_create_default()); // Having established interface layer, create an interface instance esp_netif_create_default_wifi_sta(); // Initialise WiFi driver (Link Layer) wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL)); wifi_config_t wifi_config = { .sta = { .ssid = SECRETS_WIFI_SSID, .password = SECRETS_WIFI_PASS, }, }; // Set WiFi mode to 'station' (basically a client connecting to a WiFi access // point) ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); // Give connection config to WiFi driver ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); // Begin the connection which triggers WIFI_EVENT_STA_START (the event which // is the basis for the actual connection defined in the event handler) ESP_ERROR_CHECK(esp_wifi_start()); // Block main execution until WiFi connection est ESP_LOGI(TAG, "Waiting for WiFi connection..."); while (!WIFI_CONNECTED) { vTaskDelay(pdMS_TO_TICKS(100)); } }