#include "Networking.hpp" #define TAG "Networking" #include "../ConfigManager/ConfigManager.hpp" #include "../Logging/Logging.hpp" #include #include // Static instance for callbacks (with safety checks) Networking* Networking::_instance = nullptr; Networking::Networking(ConfigManager& configManager) : _configManager(configManager) , _state(NetworkState::DISCONNECTED) , _activeConnection(ConnectionType::NONE) , _lastConnectionAttempt(0) , _bootSequenceComplete(false) , _ethernetCableConnected(false) , _wifiConnectionFailures(0) , _triedSavedCredentials(false) , _wifiManager(nullptr) , _reconnectionTimer(nullptr) { // Safety check for multiple instances if (_instance != nullptr) { LOG_WARNING(TAG, "Multiple Networking instances detected! Previous instance will be overridden."); } _instance = this; _wifiManager = new WiFiManager(); } Networking::~Networking() { // Clear static instance safely if (_instance == this) { _instance = nullptr; } // Cleanup timer if (_reconnectionTimer) { xTimerDelete(_reconnectionTimer, portMAX_DELAY); _reconnectionTimer = nullptr; } // Cleanup WiFiManager if (_wifiManager) { delete _wifiManager; _wifiManager = nullptr; } } void Networking::begin() { LOG_INFO(TAG, "Initializing Networking System"); // Create reconnection timer (one-shot — restarted manually only when still disconnected) _reconnectionTimer = xTimerCreate("reconnectionTimer", pdMS_TO_TICKS(RECONNECTION_INTERVAL), pdFALSE, (void*)0, reconnectionTimerCallback); // Setup network event handler WiFi.onEvent(networkEventHandler); // Configure WiFiManager _wifiManager->setDebugOutput(false); _wifiManager->setConfigPortalTimeout(300); // 5 minutes // Clear Previous Settings, USE once to test. //_wifiManager->resetSettings(); // Check if permanent AP mode is enabled if (_configManager.getPermanentAPMode()) { LOG_INFO(TAG, "Permanent AP mode enabled - starting AP mode on 192.168.4.1"); startPermanentAPMode(); return; } // ETHERNET DISABLED - WiFi only mode // Start Ethernet hardware // auto& hwConfig = _configManager.getHardwareConfig(); // ETH.begin(hwConfig.ethPhyType, hwConfig.ethPhyAddr, hwConfig.ethPhyCs, // hwConfig.ethPhyIrq, hwConfig.ethPhyRst, SPI); // Start connection sequence - Skip Ethernet, go directly to WiFi LOG_INFO(TAG, "Starting WiFi connection (Ethernet disabled)..."); startWiFiConnection(); } void Networking::startEthernetConnection() { // ETHERNET DISABLED - Skip to WiFi immediately LOG_DEBUG(TAG, "Ethernet connection disabled - falling back to WiFi"); startWiFiConnection(); // Original Ethernet code (DISABLED): // LOG_INFO(TAG, "Attempting Ethernet connection..."); // setState(NetworkState::CONNECTING_ETHERNET); // // // Check if Ethernet hardware initialization failed // if (!ETH.linkUp()) { // LOG_WARNING(TAG, "Ethernet hardware not detected or failed to initialize"); // LOG_INFO(TAG, "Falling back to WiFi immediately"); // startWiFiConnection(); // return; // } // // // Ethernet will auto-connect via events // // Set timeout for Ethernet attempt (5 seconds) // _lastConnectionAttempt = millis(); // // // Start reconnection timer to handle timeout // xTimerStart(_reconnectionTimer, 0); } void Networking::startWiFiConnection() { // If bootOtaCheck (or any pre-init code) already connected WiFi, adopt it // instead of tearing it down with WiFi.mode(WIFI_STA). if (WiFi.status() == WL_CONNECTED) { LOG_INFO(TAG, "WiFi already connected - adopting existing connection"); onWiFiConnected(); return; } LOG_INFO(TAG, "Attempting WiFi connection..."); setState(NetworkState::CONNECTING_WIFI); applyNetworkConfig(false); WiFi.mode(WIFI_STA); auto& netConfig = _configManager.getNetworkConfig(); if (!_triedSavedCredentials && hasValidWiFiCredentials()) { // Stage 1: try saved credentials (WiFiManager's stored SSID+password) String savedSSID = _wifiManager->getWiFiSSID(true); LOG_INFO(TAG, "Using saved WiFi credentials - SSID: %s", savedSSID.c_str()); WiFi.begin(); // WiFiManager's saved SSID+password } else { // Stage 2: saved creds exhausted (or none saved) — try hardcoded failsafe LOG_INFO(TAG, "Trying hardcoded failsafe WiFi - SSID: %s", netConfig.defaultWifiSsid.c_str()); WiFi.begin(netConfig.defaultWifiSsid.c_str(), netConfig.defaultWifiPsk.c_str()); } _lastConnectionAttempt = millis(); xTimerStart(_reconnectionTimer, 0); } void Networking::startWiFiPortal() { LOG_INFO(TAG, "Starting WiFi configuration portal..."); setState(NetworkState::WIFI_PORTAL_MODE); WiFi.mode(WIFI_AP_STA); auto& netConfig = _configManager.getNetworkConfig(); String apName = netConfig.apSsid; LOG_INFO(TAG, "WiFi Portal: SSID='%s', Password='%s'", apName.c_str(), netConfig.apPass.c_str()); // Add custom HTML to WiFiManager portal for permanent AP mode toggle String customHTML = "

Network Mode

"; customHTML += "

Choose how to operate this device:

"; customHTML += "
"; customHTML += ""; customHTML += "
"; customHTML += "

Note: You can configure network mode later at http://192.168.4.1/settings (AP mode) or http://{device-ip}/settings (Router mode)

"; _wifiManager->setCustomHeadElement(customHTML.c_str()); if (_wifiManager->autoConnect(apName.c_str(), netConfig.apPass.c_str())) { LOG_INFO(TAG, "WiFi credentials saved via portal - rebooting to apply"); // Reboot so the web server and all services start cleanly on the new network. // WiFiManager holds port 80 during the portal; a reboot is the only reliable // way to release it and let AsyncWebServer bind correctly. delay(1000); ESP.restart(); } else { LOG_ERROR(TAG, "WiFi portal configuration failed"); setState(NetworkState::DISCONNECTED); // Start reconnection timer to try again xTimerStart(_reconnectionTimer, 0); } } void Networking::handleReconnection() { if (_state == NetworkState::CONNECTED_ETHERNET || _state == NetworkState::CONNECTED_WIFI) { return; // Already connected — timer is stopped in onWiFiConnected(), nothing to do } LOG_DEBUG(TAG, "Attempting reconnection..."); // ETHERNET DISABLED - Skip Ethernet timeout checks // Check for Ethernet timeout (fall back to WiFi) // if (_state == NetworkState::CONNECTING_ETHERNET) { // unsigned long now = millis(); // if (now - _lastConnectionAttempt > 5000) { // 5 second timeout // LOG_INFO(TAG, "Ethernet connection timeout - falling back to WiFi"); // startWiFiConnection(); // return; // } // return; // Still waiting for Ethernet // } // Check for WiFi timeout if (_state == NetworkState::CONNECTING_WIFI) { unsigned long now = millis(); if (now - _lastConnectionAttempt > 10000) { // 10 second timeout _wifiConnectionFailures++; LOG_WARNING(TAG, "WiFi connection timeout (failure #%d)", _wifiConnectionFailures); // Stage transition: after MAX_WIFI_FAILURES on saved creds, switch to failsafe if (!_triedSavedCredentials && _wifiConnectionFailures >= MAX_WIFI_FAILURES) { LOG_WARNING(TAG, "Saved credentials failed %d times - switching to hardcoded failsafe", MAX_WIFI_FAILURES); _triedSavedCredentials = true; _wifiConnectionFailures = 0; startWiFiConnection(); // will now use hardcoded creds return; } // Stage transition: after MAX_WIFI_FAILURES on failsafe creds, open portal (boot only) if (_triedSavedCredentials && _wifiConnectionFailures >= MAX_WIFI_FAILURES) { LOG_ERROR(TAG, "All credential attempts failed"); if (!_bootSequenceComplete) { LOG_INFO(TAG, "Opening WiFi portal for reconfiguration"); _triedSavedCredentials = false; // reset for next boot _wifiConnectionFailures = 0; startWiFiPortal(); } else { // Post-boot: reset and retry from saved creds again LOG_WARNING(TAG, "WiFi connection lost - restarting credential cycle"); _triedSavedCredentials = false; _wifiConnectionFailures = 0; startWiFiConnection(); } return; } // Still within a phase — keep retrying startWiFiConnection(); } else { // Still within timeout window — re-arm timer to check again later xTimerStart(_reconnectionTimer, 0); } return; } // State is DISCONNECTED - WiFi only mode (Ethernet disabled) LOG_INFO(TAG, "Disconnected - trying WiFi"); if (hasValidWiFiCredentials()) { startWiFiConnection(); // re-arms timer } else if (!_bootSequenceComplete) { // No credentials during boot - start portal startWiFiPortal(); } else { LOG_WARNING(TAG, "No WiFi credentials and boot sequence complete - waiting"); // Re-arm so we keep checking in case credentials arrive xTimerStart(_reconnectionTimer, 0); } } // ════════════════════════════════════════════════════════════════════════════ // HEALTH CHECK IMPLEMENTATION // ════════════════════════════════════════════════════════════════════════════ bool Networking::isHealthy() const { // Check if we have any active connection if (_activeConnection == ConnectionType::NONE) { LOG_DEBUG(TAG, "Networking: Unhealthy - No active connection"); return false; } // Check connection state (Ethernet disabled, only check WiFi or AP) if (_state != NetworkState::CONNECTED_WIFI && _state != NetworkState::AP_MODE_PERMANENT) { LOG_DEBUG(TAG, "Networking: Unhealthy - Not in connected state"); return false; } // Check IP address validity String ip = getLocalIP(); if (ip == "0.0.0.0" || ip.isEmpty()) { LOG_DEBUG(TAG, "Networking: Unhealthy - Invalid IP address"); return false; } // For WiFi connections, check signal strength if (_activeConnection == ConnectionType::WIFI) { if (WiFi.status() != WL_CONNECTED) { LOG_DEBUG(TAG, "Networking: Unhealthy - WiFi not connected"); return false; } // Check signal strength (RSSI should be better than -80 dBm) int32_t rssi = WiFi.RSSI(); if (rssi < -80) { LOG_DEBUG(TAG, "Networking: Unhealthy - Poor WiFi signal: %d dBm", rssi); return false; } } // ETHERNET DISABLED - Removed Ethernet link check // For Ethernet connections, check link status // if (_activeConnection == ConnectionType::ETHERNET) { // if (!ETH.linkUp()) { // LOG_DEBUG(TAG, "Networking: Unhealthy - Ethernet link down"); // return false; // } // } return true; } void Networking::setState(NetworkState newState) { if (_state != newState) { LOG_DEBUG(TAG, "Network state: %d -> %d", (int)_state, (int)newState); _state = newState; } } void Networking::setActiveConnection(ConnectionType type) { if (_activeConnection != type) { LOG_INFO(TAG, "Active connection changed: %d -> %d", (int)_activeConnection, (int)type); _activeConnection = type; } } void Networking::notifyConnectionChange(bool connected) { if (connected && _onNetworkConnected) { _onNetworkConnected(); } else if (!connected && _onNetworkDisconnected) { _onNetworkDisconnected(); } } // Event handlers (ETHERNET DISABLED) void Networking::onEthernetConnected() { // ETHERNET DISABLED - This should never be called LOG_WARNING(TAG, "Ethernet event received but Ethernet is disabled - ignoring"); // Original code (DISABLED): // LOG_INFO(TAG, "Ethernet connected successfully"); // setState(NetworkState::CONNECTED_ETHERNET); // setActiveConnection(ConnectionType::ETHERNET); // // // Stop WiFi if it was running // if (WiFi.getMode() != WIFI_OFF) { // WiFi.disconnect(true); // WiFi.mode(WIFI_OFF); // } // // // Stop reconnection timer // xTimerStop(_reconnectionTimer, 0); // // notifyConnectionChange(true); } void Networking::onEthernetDisconnected() { // ETHERNET DISABLED - This should never be called LOG_WARNING(TAG, "Ethernet disconnect event received but Ethernet is disabled - ignoring"); // Original code (DISABLED): // LOG_WARNING(TAG, "Ethernet disconnected"); // // if (_activeConnection == ConnectionType::ETHERNET) { // setState(NetworkState::DISCONNECTED); // setActiveConnection(ConnectionType::NONE); // notifyConnectionChange(false); // // // Start reconnection attempts // xTimerStart(_reconnectionTimer, 0); // } } void Networking::onWiFiConnected() { LOG_INFO(TAG, "WiFi connected successfully - IP: %s", WiFi.localIP().toString().c_str()); // A "reconnect" is any successful connect AFTER the initial boot-time // connection — _bootSequenceComplete is only true once that first // connection has already happened, so this correctly excludes it. if (_bootSequenceComplete) { _reconnectCount++; LOG_INFO(TAG, "WiFi reconnected (lifetime count this boot: %lu)", _reconnectCount); } setState(NetworkState::CONNECTED_WIFI); setActiveConnection(ConnectionType::WIFI); // Modem sleep off (the Arduino default is WIFI_PS_MIN_MODEM). With it on, the // radio dozes between AP beacons and inbound packets wait for the next DTIM — // 100ms to 1s+ per packet depending on the AP, which showed up as laggy app // commands and status updates. Mains-powered device; the power cost is moot. // Re-applied on every connect since WiFi.mode() changes can reset it. WiFi.setSleep(false); // Reset failure/phase counters on successful connection _wifiConnectionFailures = 0; _triedSavedCredentials = false; // Stop reconnection timer xTimerStop(_reconnectionTimer, 0); // Mark boot sequence as complete _bootSequenceComplete = true; notifyConnectionChange(true); } void Networking::onWiFiDisconnected() { LOG_WARNING(TAG, "WiFi disconnected"); if (_activeConnection == ConnectionType::WIFI) { setState(NetworkState::DISCONNECTED); setActiveConnection(ConnectionType::NONE); notifyConnectionChange(false); // Start reconnection attempts xTimerStart(_reconnectionTimer, 0); } } void Networking::onEthernetCableChange(bool connected) { // ETHERNET DISABLED - Ignore cable events LOG_DEBUG(TAG, "Ethernet cable event ignored (Ethernet disabled)"); // Original code (DISABLED): // _ethernetCableConnected = connected; // LOG_INFO(TAG, "Ethernet cable %s", connected ? "connected" : "disconnected"); // // if (connected && _activeConnection != ConnectionType::ETHERNET) { // // Cable connected and we're not using Ethernet - try to connect // startEthernetConnection(); // } } // Utility methods void Networking::applyNetworkConfig(bool ethernet) { auto& netConfig = _configManager.getNetworkConfig(); // ETHERNET DISABLED - Only apply WiFi config if (ethernet) { LOG_WARNING(TAG, "applyNetworkConfig called with ethernet=true but Ethernet is disabled"); return; } if (netConfig.useStaticIP) { LOG_INFO(TAG, "Applying static IP configuration"); WiFi.config(netConfig.ip, netConfig.gateway, netConfig.subnet, netConfig.dns1, netConfig.dns2); } else { LOG_INFO(TAG, "Using DHCP configuration"); } WiFi.setHostname(netConfig.hostname.c_str()); } bool Networking::hasValidWiFiCredentials() { // Use WiFiManager's method to check if credentials are saved return _wifiManager->getWiFiIsSaved(); } // Returns if Networking is connected bool Networking::isConnected() const { return _activeConnection != ConnectionType::NONE; } String Networking::getLocalIP() const { switch (_activeConnection) { case ConnectionType::ETHERNET: // ETHERNET DISABLED - Should never reach here LOG_WARNING(TAG, "getLocalIP called with ETHERNET type but Ethernet is disabled"); return "0.0.0.0"; case ConnectionType::WIFI: return WiFi.localIP().toString(); case ConnectionType::AP: return WiFi.softAPIP().toString(); default: return "0.0.0.0"; } } String Networking::getGateway() const { switch (_activeConnection) { case ConnectionType::ETHERNET: // ETHERNET DISABLED - Should never reach here LOG_WARNING(TAG, "getGateway called with ETHERNET type but Ethernet is disabled"); return "0.0.0.0"; case ConnectionType::WIFI: return WiFi.gatewayIP().toString(); default: return "0.0.0.0"; } } void Networking::forceReconnect() { LOG_INFO(TAG, "Forcing reconnection..."); setState(NetworkState::RECONNECTING); setActiveConnection(ConnectionType::NONE); // Disconnect everything if (WiFi.getMode() != WIFI_OFF) { WiFi.disconnect(true); WiFi.mode(WIFI_OFF); } // Restart connection sequence - WiFi only (Ethernet disabled) delay(1000); startWiFiConnection(); } // Static callbacks void Networking::networkEventHandler(arduino_event_id_t event, arduino_event_info_t info) { if (!_instance) return; LOG_DEBUG(TAG, "Network event: %d", event); switch (event) { // ETHERNET EVENTS DISABLED - Ignored case ARDUINO_EVENT_ETH_START: case ARDUINO_EVENT_ETH_CONNECTED: case ARDUINO_EVENT_ETH_GOT_IP: case ARDUINO_EVENT_ETH_DISCONNECTED: case ARDUINO_EVENT_ETH_STOP: LOG_DEBUG(TAG, "Ethernet event ignored (Ethernet disabled)"); break; // WiFi events (ACTIVE) case ARDUINO_EVENT_WIFI_STA_GOT_IP: LOG_INFO(TAG, "WiFi Got IP: %s", WiFi.localIP().toString().c_str()); _instance->onWiFiConnected(); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: { wifi_err_reason_t reason = (wifi_err_reason_t)info.wifi_sta_disconnected.reason; const char* reasonName = WiFi.disconnectReasonName(reason); LOG_WARNING(TAG, "WiFi Disconnected (reason: %s)", reasonName); _instance->_lastDisconnectReason = reasonName; _instance->_lastDisconnectUptimeMs = millis(); _instance->onWiFiDisconnected(); break; } case ARDUINO_EVENT_WIFI_STA_CONNECTED: LOG_DEBUG(TAG, "WiFi STA Connected"); break; default: break; } } void Networking::networkReconnectTaskFn(void* param) { Networking* net = static_cast(param); net->handleReconnection(); vTaskDelete(NULL); } void Networking::reconnectionTimerCallback(TimerHandle_t xTimer) { if (_instance) { // If the task can't be created (fragmented heap), re-arm the one-shot // timer to try again next interval. Before, a single failure ended the // reconnect chain silently. No LOG here — Tmr Svc stack is 2KB. if (xTaskCreate(networkReconnectTaskFn, "netRecon", 3072, _instance, 5, NULL) != pdPASS) { xTimerStart(xTimer, 0); } } } void Networking::clearWiFiCredentials() { if (_wifiManager) { _wifiManager->resetSettings(); LOG_WARNING(TAG, "Networking: WiFi credentials wiped"); } } void Networking::startPermanentAPMode() { LOG_INFO(TAG, "Starting Permanent AP Mode"); setState(NetworkState::AP_MODE_PERMANENT); // Stop any existing connections WiFi.disconnect(true); WiFi.mode(WIFI_OFF); delay(100); // Configure AP mode with fixed 192.168.4.1 IP WiFi.mode(WIFI_AP); auto& netConfig = _configManager.getNetworkConfig(); String apName = netConfig.apSsid; String apPass = netConfig.apPass; // Configure AP with fixed IP: 192.168.4.1 IPAddress local_IP(192, 168, 4, 1); IPAddress gateway(192, 168, 4, 1); IPAddress subnet(255, 255, 255, 0); if (!WiFi.softAPConfig(local_IP, gateway, subnet)) { LOG_ERROR(TAG, "Failed to configure AP IP address"); } // Start AP bool apStarted; if (apPass.isEmpty()) { apStarted = WiFi.softAP(apName.c_str()); LOG_INFO(TAG, "Starting open AP (no password): %s", apName.c_str()); } else { apStarted = WiFi.softAP(apName.c_str(), apPass.c_str()); LOG_INFO(TAG, "Starting AP with password: %s", apName.c_str()); } if (apStarted) { LOG_INFO(TAG, "✅ Permanent AP Mode active"); LOG_INFO(TAG, " SSID: %s", apName.c_str()); LOG_INFO(TAG, " IP: 192.168.4.1"); LOG_INFO(TAG, " Subnet: 255.255.255.0"); setActiveConnection(ConnectionType::AP); // Stop reconnection timer (not needed in permanent AP mode) if (_reconnectionTimer) { xTimerStop(_reconnectionTimer, 0); } // Mark boot sequence as complete _bootSequenceComplete = true; // Notify connected notifyConnectionChange(true); } else { LOG_ERROR(TAG, "❌ Failed to start AP Mode"); setState(NetworkState::DISCONNECTED); } }