/* * WiFi Manager Module Implementation - see wifi_manager.h for the radio rules. */ #include "wifi_manager.h" #include "espnow_link.h" #include "settings_manager.h" #include "serial_lock.h" #include "protocol/automotive_data.h" // ESPNOW_CHANNEL #include #include #include #include #include #include #include namespace WiFiManager { // ============================================================================ // PRIVATE MODULE STATE // ============================================================================ typedef enum { CMD_ENABLE, CMD_DISABLE, CMD_SCAN, CMD_CONNECT, CMD_CONNECT_SAVED, CMD_FORGET } cmd_type_t; typedef struct { cmd_type_t type; char ssid[33]; char pass[65]; } cmd_t; static const char* NVS_NAMESPACE = "wifi"; static QueueHandle_t g_queue = NULL; static SemaphoreHandle_t g_mutex = NULL; // Guarded by g_mutex static status_t g_status = {}; static network_t g_networks[WIFI_SCAN_MAX_NETWORKS]; static uint8_t g_network_count = 0; // Owned by the Wi-Fi task (and init) static bool g_enabled = false; static char g_saved_pass[65] = {0}; static volatile uint8_t g_disc_reason = 0; // last STA_DISCONNECTED reason (event task) static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); } static void unlock() { xSemaphoreGive(g_mutex); } static void print(const char* fmt, ...) { char buf[160]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); SerialLock::lock(); Serial.println(buf); SerialLock::unlock(); } static void copyStr(char* dst, const char* src, size_t n) { strncpy(dst, src ? src : "", n - 1); dst[n - 1] = 0; } static void setLink(link_t link, const char* ssid, const char* error = "") { lock(); g_status.link = link; if (ssid) copyStr(g_status.ssid, ssid, sizeof(g_status.ssid)); copyStr(g_status.error, error, sizeof(g_status.error)); unlock(); } static link_t currentLink() { lock(); link_t l = g_status.link; unlock(); return l; } // ============================================================================ // SAVED NETWORK (NVS) // ============================================================================ static void loadSaved() { Preferences p; p.begin(NVS_NAMESPACE, true); String ssid = p.getString("ssid", ""); String pass = p.getString("pass", ""); p.end(); lock(); copyStr(g_status.saved_ssid, ssid.c_str(), sizeof(g_status.saved_ssid)); unlock(); copyStr(g_saved_pass, pass.c_str(), sizeof(g_saved_pass)); } bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n) { lock(); copyStr(ssid, g_status.saved_ssid, ssid_n); unlock(); copyStr(pass, g_saved_pass, pass_n); return ssid[0] != 0; } static void storeSaved(const char* ssid, const char* pass) { Preferences p; p.begin(NVS_NAMESPACE, false); p.putString("ssid", ssid); p.putString("pass", pass ? pass : ""); p.end(); lock(); copyStr(g_status.saved_ssid, ssid, sizeof(g_status.saved_ssid)); unlock(); copyStr(g_saved_pass, pass, sizeof(g_saved_pass)); } static void clearSaved() { Preferences p; p.begin(NVS_NAMESPACE, false); p.clear(); p.end(); lock(); g_status.saved_ssid[0] = 0; unlock(); memset(g_saved_pass, 0, sizeof(g_saved_pass)); } // ============================================================================ // RADIO // ============================================================================ static void onDisconnected(arduino_event_id_t event, arduino_event_info_t info) { (void)event; g_disc_reason = info.wifi_sta_disconnected.reason; } /** Leave any AP and park the radio back on the ESP-NOW channel B expects. */ static void dropToEspNowChannel() { WiFi.disconnect(); // NOT (true): that powers the radio off and kills ESP-NOW delay(50); esp_wifi_set_channel(ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE); } static const char* reasonText(uint8_t r) { switch (r) { case WIFI_REASON_AUTH_EXPIRE: case WIFI_REASON_AUTH_FAIL: case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: case WIFI_REASON_HANDSHAKE_TIMEOUT: case WIFI_REASON_MIC_FAILURE: return "Wrong password"; case WIFI_REASON_NO_AP_FOUND: return "Network not in range"; case 210: // NO_AP_FOUND_W_COMPATIBLE_SECURITY case 211: // NO_AP_FOUND_IN_AUTHMODE_THRESHOLD return "Security type not supported"; case 212: // NO_AP_FOUND_IN_RSSI_THRESHOLD return "Signal too weak"; case WIFI_REASON_ASSOC_FAIL: return "Network refused the connection"; default: return NULL; } } static void waitForScanToFinish() { uint32_t t0 = millis(); while (WiFi.scanComplete() == WIFI_SCAN_RUNNING && millis() - t0 < 8000) vTaskDelay(pdMS_TO_TICKS(100)); WiFi.scanDelete(); lock(); g_status.scanning = false; unlock(); } /** One join attempt, blocking the Wi-Fi task for up to WIFI_CONNECT_TIMEOUT_MS. */ static bool doConnect(const char* ssid, const char* pass, bool remember, const char* fail_prefix = NULL) { setLink(LINK_CONNECTING, ssid); print("[wifi] joining '%s'...", ssid); waitForScanToFinish(); WiFi.disconnect(); delay(150); // let the leave event land before we watch for failures g_disc_reason = 0; WiFi.begin(ssid, (pass && *pass) ? pass : NULL); uint32_t t0 = millis(), reason_ms = 0; while (millis() - t0 < WIFI_CONNECT_TIMEOUT_MS) { if (WiFi.status() == WL_CONNECTED) break; if (g_disc_reason != 0 && g_disc_reason != WIFI_REASON_ASSOC_LEAVE && reason_ms == 0) reason_ms = millis(); if (reason_ms && millis() - reason_ms > 1500) break; // one attempt only: autoreconnect is off vTaskDelay(pdMS_TO_TICKS(200)); } if (WiFi.status() == WL_CONNECTED) { setLink(LINK_CONNECTED, ssid); print("[wifi] connected to '%s', IP %s, %d dBm, channel %d", ssid, WiFi.localIP().toString().c_str(), (int)WiFi.RSSI(), (int)WiFi.channel()); if (remember) { bool same; lock(); same = strcmp(g_status.saved_ssid, ssid) == 0; unlock(); if (!same || strcmp(g_saved_pass, pass ? pass : "") != 0) { storeSaved(ssid, pass); print("[wifi] '%s' remembered - joins automatically at boot", ssid); } } return true; } uint8_t r = g_disc_reason; const char* why = reasonText(r); char err[48]; if (why) snprintf(err, sizeof(err), "%s%s", fail_prefix ? fail_prefix : "", why); else if (r) snprintf(err, sizeof(err), "%sCouldn't connect (code %u)", fail_prefix ? fail_prefix : "", r); else snprintf(err, sizeof(err), "%sNo answer from the network", fail_prefix ? fail_prefix : ""); dropToEspNowChannel(); setLink(LINK_FAILED, ssid, err); print("[wifi] '%s' failed: %s", ssid, err); return false; } static void collectScan(int16_t n) { network_t tmp[WIFI_SCAN_MAX_NETWORKS]; uint8_t count = 0; for (int16_t i = 0; i < n; i++) { String s = WiFi.SSID(i); if (s.length() == 0) continue; // hidden int8_t rssi = (int8_t)WiFi.RSSI(i); bool secured = WiFi.encryptionType(i) != WIFI_AUTH_OPEN; int dup = -1; // mesh APs repeat an SSID: keep the strongest for (uint8_t j = 0; j < count; j++) if (s == tmp[j].ssid) { dup = j; break; } if (dup >= 0) { if (rssi > tmp[dup].rssi) tmp[dup].rssi = rssi; continue; } if (count >= WIFI_SCAN_MAX_NETWORKS) continue; copyStr(tmp[count].ssid, s.c_str(), sizeof(tmp[count].ssid)); tmp[count].rssi = rssi; tmp[count].secured = secured; count++; } for (uint8_t i = 1; i < count; i++) { // strongest first network_t k = tmp[i]; int j = i - 1; while (j >= 0 && tmp[j].rssi < k.rssi) { tmp[j + 1] = tmp[j]; j--; } tmp[j + 1] = k; } lock(); memcpy(g_networks, tmp, sizeof(network_t) * count); g_network_count = count; g_status.scanning = false; g_status.scan_gen++; unlock(); print("[wifi] scan: %u networks", count); for (uint8_t i = 0; i < count; i++) { print("[wifi] %4d dBm %s%s", tmp[i].rssi, tmp[i].ssid, tmp[i].secured ? "" : " (open)"); } } // ============================================================================ // TASK (Core 0) // ============================================================================ static void wifiTask(void* parameter) { (void)parameter; cmd_t cmd; uint32_t scan_t0 = 0; uint32_t lost_since = 0; // Boot: join the remembered network once if Wi-Fi is on - after setup() has // brought ESP-NOW up, so the two don't configure the radio at the same time. vTaskDelay(pdMS_TO_TICKS(3000)); if (g_enabled) { char ssid[33]; lock(); copyStr(ssid, g_status.saved_ssid, sizeof(ssid)); unlock(); if (ssid[0]) doConnect(ssid, g_saved_pass, false); } while (true) { if (xQueueReceive(g_queue, &cmd, pdMS_TO_TICKS(200)) == pdTRUE) { switch (cmd.type) { case CMD_ENABLE: { g_enabled = true; SettingsManager::saveWiFiState(true); char ssid[33]; lock(); copyStr(ssid, g_status.saved_ssid, sizeof(ssid)); unlock(); if (ssid[0]) doConnect(ssid, g_saved_pass, false); else setLink(LINK_IDLE, ""); break; } case CMD_DISABLE: g_enabled = false; SettingsManager::saveWiFiState(false); waitForScanToFinish(); dropToEspNowChannel(); setLink(LINK_OFF, ""); print("[wifi] off (radio stays up for ESP-NOW)"); break; case CMD_SCAN: if (g_enabled && WiFi.scanComplete() != WIFI_SCAN_RUNNING) { lock(); g_status.scanning = true; unlock(); WiFi.scanNetworks(true, false); // async, no hidden networks scan_t0 = millis(); } else if (!g_enabled) { lock(); g_status.scanning = false; // requestScan() raced a switch-off unlock(); } break; case CMD_CONNECT: if (!g_enabled) { // joining implies switching Wi-Fi on g_enabled = true; SettingsManager::saveWiFiState(true); } doConnect(cmd.ssid, cmd.pass, true); break; case CMD_CONNECT_SAVED: { char ssid[33]; lock(); copyStr(ssid, g_status.saved_ssid, sizeof(ssid)); unlock(); if (g_enabled && ssid[0]) doConnect(ssid, g_saved_pass, false); break; } case CMD_FORGET: clearSaved(); dropToEspNowChannel(); setLink(g_enabled ? LINK_IDLE : LINK_OFF, ""); print("[wifi] saved network forgotten"); break; } memset(cmd.pass, 0, sizeof(cmd.pass)); } // Scan completion bool scanning; lock(); scanning = g_status.scanning; unlock(); if (scanning) { int16_t r = WiFi.scanComplete(); if (r >= 0) { collectScan(r); WiFi.scanDelete(); } else if (r == WIFI_SCAN_FAILED || millis() - scan_t0 > 10000) { WiFi.scanDelete(); lock(); g_status.scanning = false; g_status.scan_gen++; unlock(); print("[wifi] scan failed"); } } // A dropped connection gets one rejoin, then we stay put (an endless // reconnect would keep hopping channels under the ESP-NOW link). if (currentLink() == LINK_CONNECTED && WiFi.status() != WL_CONNECTED) { if (lost_since == 0) lost_since = millis(); if (millis() - lost_since > 3000) { lost_since = 0; char ssid[33]; lock(); copyStr(ssid, g_status.ssid, sizeof(ssid)); unlock(); print("[wifi] connection to '%s' lost - one retry", ssid); doConnect(ssid, g_saved_pass, false, "Connection lost: "); } } else { lost_since = 0; } } } // ============================================================================ // PUBLIC API // ============================================================================ static void send(cmd_type_t type, const char* ssid = NULL, const char* pass = NULL) { if (g_queue == NULL) return; cmd_t c = {}; c.type = type; copyStr(c.ssid, ssid, sizeof(c.ssid)); copyStr(c.pass, pass, sizeof(c.pass)); if (xQueueSend(g_queue, &c, pdMS_TO_TICKS(50)) != pdTRUE) print("[wifi] busy - request dropped"); memset(c.pass, 0, sizeof(c.pass)); } void init(bool enabled) { g_mutex = xSemaphoreCreateMutex(); g_queue = xQueueCreate(6, sizeof(cmd_t)); g_enabled = enabled; WiFi.mode(WIFI_STA); // radio stays up for the ESP-NOW link (EspNowLink) WiFi.persistent(false); // our own NVS copy; don't let the driver write flash on every begin() WiFi.setAutoReconnect(false); // no endless channel hopping under ESP-NOW WiFi.onEvent(onDisconnected, ARDUINO_EVENT_WIFI_STA_DISCONNECTED); loadSaved(); lock(); g_status.link = enabled ? LINK_IDLE : LINK_OFF; unlock(); print("[wifi] %s, saved network: %s", enabled ? "on" : "off", g_status.saved_ssid[0] ? g_status.saved_ssid : "(none)"); xTaskCreatePinnedToCore(wifiTask, "WiFi_Task", WIFI_TASK_STACK_SIZE, NULL, WIFI_TASK_PRIORITY, NULL, WIFI_TASK_CORE); } void setEnabled(bool on) { // Reflect the switch at once; the task does the (slow) radio work. if (on) { lock(); bool has_saved = g_status.saved_ssid[0] != 0; if (has_saved) { g_status.link = LINK_CONNECTING; copyStr(g_status.ssid, g_status.saved_ssid, sizeof(g_status.ssid)); } else { g_status.link = LINK_IDLE; } unlock(); } else { setLink(LINK_OFF, ""); } send(on ? CMD_ENABLE : CMD_DISABLE); } bool isEnabled() { return currentLink() != LINK_OFF; } void requestScan() { lock(); bool busy = g_status.scanning || g_status.link == LINK_OFF; if (!busy) g_status.scanning = true; // shown at once; the task starts it unlock(); if (!busy) send(CMD_SCAN); } void connect(const char* ssid, const char* pass) { if (ssid == NULL || !*ssid) return; setLink(LINK_CONNECTING, ssid); send(CMD_CONNECT, ssid, pass); } void connectSaved() { lock(); bool ok = g_status.saved_ssid[0] != 0 && g_status.link != LINK_OFF; if (ok) { g_status.link = LINK_CONNECTING; copyStr(g_status.ssid, g_status.saved_ssid, sizeof(g_status.ssid)); } unlock(); if (ok) send(CMD_CONNECT_SAVED); } void forget() { send(CMD_FORGET); } status_t getStatus() { status_t s; lock(); s = g_status; unlock(); s.ip[0] = 0; s.rssi = 0; if (s.link == LINK_CONNECTED && WiFi.status() == WL_CONNECTED) { copyStr(s.ip, WiFi.localIP().toString().c_str(), sizeof(s.ip)); s.rssi = WiFi.RSSI(); } return s; } uint8_t getNetworks(network_t* out, uint8_t max) { lock(); uint8_t n = g_network_count < max ? g_network_count : max; memcpy(out, g_networks, sizeof(network_t) * n); unlock(); return n; } // ============================================================================ // CONSOLE (`wifi ...`) // ============================================================================ static const char* linkName(link_t l) { switch (l) { case LINK_OFF: return "off"; case LINK_IDLE: return "not connected"; case LINK_CONNECTING: return "connecting"; case LINK_CONNECTED: return "connected"; case LINK_FAILED: return "failed"; default: return "?"; } } bool handleCommand(const char* line) { char buf[128]; copyStr(buf, line, sizeof(buf)); char* argv[4] = {0}; int argc = 0; for (char* t = strtok(buf, " \t"); t && argc < 4; t = strtok(NULL, " \t")) argv[argc++] = t; if (argc == 0 || strcmp(argv[0], "wifi") != 0) return false; if (argc >= 3 && !strcmp(argv[1], "join")) { // SSIDs with spaces aren't supported here; use the Settings screen. connect(argv[2], argc >= 4 ? argv[3] : NULL); // result logged by the Wi-Fi task } else if (argc == 2 && !strcmp(argv[1], "forget")) { forget(); } else if (argc == 2 && !strcmp(argv[1], "on")) { setEnabled(true); } else if (argc == 2 && !strcmp(argv[1], "off")) { setEnabled(false); } else if (argc == 2 && !strcmp(argv[1], "scan")) { requestScan(); } else if (argc == 2 && !strcmp(argv[1], "status")) { status_t s = getStatus(); if (s.link == LINK_CONNECTED) { print("[wifi] connected to '%s', IP %s, RSSI %d dBm, channel %d", s.ssid, s.ip, s.rssi, (int)WiFi.channel()); } else { print("[wifi] %s%s%s, channel %d", linkName(s.link), s.error[0] ? ": " : "", s.error, (int)WiFi.channel()); } print("[wifi] saved network: %s", s.saved_ssid[0] ? s.saved_ssid : "(none)"); print("[wifi] ESP-NOW %s, sent %lu, failed %lu", EspNowLink::isReady() ? "ready" : "DOWN", (unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount()); } else { print("wifi status connection, saved network, ESP-NOW health"); print("wifi join [pass] join + remember a network (no spaces in the SSID)"); print("wifi forget drop the remembered network"); print("wifi scan list networks in range"); print("wifi on | off Wi-Fi switch (radio stays on for ESP-NOW)"); } return true; } } // namespace WiFiManager