72 lines
2.3 KiB
C++
72 lines
2.3 KiB
C++
#include "wifi_manager.h"
|
|
#include "esp_wifi.h"
|
|
#include "esp_log.h"
|
|
#include "esp_event.h"
|
|
#include "esp_netif.h"
|
|
#include "nvs_flash.h"
|
|
|
|
static bool connected = false;
|
|
|
|
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();
|
|
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
|
ESP_LOGI("WIFI", "Disconnected, reconnecting...");
|
|
connected = false;
|
|
esp_wifi_connect();
|
|
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
|
|
connected = true;
|
|
|
|
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
|
|
ESP_LOGI("WIFI", "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
|
|
}
|
|
}
|
|
|
|
static const char* s_ssid = nullptr;
|
|
static const char* s_pass = nullptr;
|
|
|
|
void init_wifi(const char* ssid, const char* pass) {
|
|
|
|
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);
|
|
|
|
s_ssid = ssid;
|
|
s_pass = pass;
|
|
|
|
esp_netif_init();
|
|
esp_event_loop_create_default();
|
|
esp_netif_create_default_wifi_sta();
|
|
|
|
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
|
esp_wifi_init(&cfg);
|
|
|
|
esp_event_handler_instance_t instance_any_id;
|
|
esp_event_handler_instance_t instance_got_ip;
|
|
|
|
esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
|
|
&wifi_event_handler, nullptr, &instance_any_id);
|
|
esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
|
|
&wifi_event_handler, nullptr, &instance_got_ip);
|
|
|
|
wifi_config_t wifi_config = {};
|
|
|
|
strcpy(reinterpret_cast<char*>(wifi_config.sta.ssid), s_ssid);
|
|
strcpy(reinterpret_cast<char*>(wifi_config.sta.password), s_pass);
|
|
|
|
esp_wifi_set_mode(WIFI_MODE_STA);
|
|
esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
|
|
esp_wifi_start();
|
|
|
|
while(!connected) {
|
|
vTaskDelay(500 / portTICK_PERIOD_MS);
|
|
}
|
|
}
|
|
|
|
bool wifi_connected() {return connected;}; |