#include "EspIdfUtils.h" #if defined(IDF_VER) #include // #include "esp_event.h" // #include "esp_log.h" #include "esp_netif.h" #include "esp_wifi.h" // #include "lwip/inet.h" // #include "lwip/ip_addr.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); wifi_connected = true; // xSemaphoreGive(wifi_semaphore); // Signal that connection is // established } } } 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 = {}; strncpy((char*)wifi_config.sta.ssid, wifiSsid, strlen(wifiSsid) + 1); strncpy((char*)wifi_config.sta.password, wifiPassword, strlen(wifiPassword) + 1); 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; std::cout << " Connected.\n"; break; } std::cout << "."; fflush(stdout); // Ensure output is printed immediately vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(500)); // Wait 500ms } if (wifi_connected) { esp_netif_ip_info_t ip_info = {}; esp_netif_t* esp_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); // Get IP information (IP address, netmask, gateway) if (esp_netif_get_ip_info(esp_netif, &ip_info) != ESP_OK) { std::cout << "Failed to get IP info\n"; return false; } // Convert the IP address to string format using inet_ntoa char ip_str[16]; // IPv4 address can have a max of 15 characters + null // terminator snprintf(ip_str, sizeof(ip_str), IPSTR, IP2STR(&ip_info.ip)); std::cout << "IP address = " << ip_str << "\n"; } else std::cout << "\nCould not connect to home network.\n"; return success; } #endif