#include "EspIdfUtils.h" #if defined(IDF_VER) #include // #include "esp_event.h" #include "esp_netif.h" #include "esp_wifi.h" #include "string.h" const char* hotspotSSID = "Roboid"; const char* hotspotPassword = "alchemy7000"; esp_netif_t* wifi_netif = nullptr; // Semaphore to signal Wi-Fi connection status SemaphoreHandle_t wifi_semaphore; static bool wifi_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) { if (event_id == WIFI_EVENT_STA_START) esp_wifi_connect(); else if (event_id == WIFI_EVENT_STA_DISCONNECTED) esp_wifi_connect(); } else if (event_base == IP_EVENT) { if (event_id == IP_EVENT_STA_GOT_IP) { //ip_event_got_ip_t* event = (ip_event_got_ip_t*)event_data; //const char* ipaddr = IP2STR(&event->ip_info.ip); std::cout << "Wifi connected, IP address (tbd)\n"; wifi_connected = true; xSemaphoreGive(wifi_semaphore); // Signal that connection is established } } } // void log_dots_task(void* pvParameters) { // while (!wifi_connected) { // printf("."); // Log a dot // vTaskDelay(500 / portTICK_PERIOD_MS); // Wait 500ms // } // printf("\nWi-Fi connected!\n"); // vTaskDelete(NULL); // } bool StartWifi(const char* wifiSsid, const char* wifiPassword) { std::cout << "Connecting to WiFi" << wifiSsid << "\n"; esp_netif_init(); esp_event_loop_create_default(); wifi_netif = esp_netif_create_default_wifi_sta(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); esp_wifi_init(&cfg); esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL); esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL); wifi_config_t wifi_config = {.sta = {.bssid_set = false}}; // Copy the ssid in the config strncpy((char*)wifi_config.sta.ssid, wifiSsid, sizeof(wifiSsid)); // Copy the wifiPassword in the config strncpy((char*)wifi_config.sta.password, wifiPassword, sizeof(wifiPassword)); esp_wifi_set_mode(WIFI_MODE_STA); esp_wifi_set_config(WIFI_IF_STA, &wifi_config); esp_wifi_start(); // Wait for connection with a timeout of 10 seconds TickType_t xLastWakeTime = xTaskGetTickCount(); bool success = false; for (int i = 0; i < 20; i++) { // 20 iterations, each 500ms if (wifi_connected) { success = true; break; } printf("."); // Log a dot vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(500)); // Wait 500ms } if (!wifi_connected) std::cout << "\nCould not connect to home network.\n"; return success; } #endif