refactor: Fixed the file hierarchy and switched to platform.io
This commit is contained in:
@@ -0,0 +1,610 @@
|
||||
#include "Networking.hpp"
|
||||
|
||||
#define TAG "Networking"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include "../Logging/Logging.hpp"
|
||||
#include <WiFiManager.h>
|
||||
#include <SPI.h>
|
||||
|
||||
// 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)
|
||||
, _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() {
|
||||
LOG_INFO(TAG, "Attempting WiFi connection...");
|
||||
setState(NetworkState::CONNECTING_WIFI);
|
||||
|
||||
// ALWAYS try default credentials first (for bundled router deployment)
|
||||
auto& netConfig = _configManager.getNetworkConfig();
|
||||
|
||||
LOG_INFO(TAG, "Using DEFAULT WiFi credentials - SSID: %s", netConfig.defaultWifiSsid.c_str());
|
||||
|
||||
applyNetworkConfig(false); // false = WiFi config
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(netConfig.defaultWifiSsid.c_str(), netConfig.defaultWifiPsk.c_str());
|
||||
|
||||
_lastConnectionAttempt = millis();
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
|
||||
// Original WiFiManager fallback code (DISABLED for fixed deployment):
|
||||
// // First, try default credentials if this is the first boot attempt
|
||||
// if (!_bootSequenceComplete && !hasValidWiFiCredentials()) {
|
||||
// LOG_INFO(TAG, "No saved credentials - trying default WiFi credentials");
|
||||
// auto& netConfig = _configManager.getNetworkConfig();
|
||||
//
|
||||
// applyNetworkConfig(false); // false = WiFi config
|
||||
// WiFi.mode(WIFI_STA);
|
||||
// WiFi.begin(netConfig.defaultWifiSsid.c_str(), netConfig.defaultWifiPsk.c_str());
|
||||
//
|
||||
// _lastConnectionAttempt = millis();
|
||||
// xTimerStart(_reconnectionTimer, 0);
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// // Check if we have valid saved credentials
|
||||
// if (!hasValidWiFiCredentials()) {
|
||||
// LOG_WARNING(TAG, "No valid WiFi credentials found");
|
||||
// if (!_bootSequenceComplete) {
|
||||
// // No credentials during boot - start portal
|
||||
// startWiFiPortal();
|
||||
// }
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// // Get and log saved credentials (for debugging)
|
||||
// String savedSSID = _wifiManager->getWiFiSSID(true);
|
||||
// LOG_INFO(TAG, "Using WiFiManager saved credentials - SSID: %s", savedSSID.c_str());
|
||||
//
|
||||
// applyNetworkConfig(false); // false = WiFi config
|
||||
// WiFi.mode(WIFI_STA);
|
||||
//
|
||||
// // Let WiFiManager handle credentials (uses saved SSID/password)
|
||||
// WiFi.begin();
|
||||
//
|
||||
// _lastConnectionAttempt = millis();
|
||||
//
|
||||
// // Start reconnection timer to handle timeout
|
||||
// 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 = "Vesper-" + _configManager.getDeviceUID();
|
||||
|
||||
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 = "<br/><br/><h3>Network Mode</h3>";
|
||||
customHTML += "<p>Choose how to operate this device:</p>";
|
||||
customHTML += "<form action='/settings' method='get'>";
|
||||
customHTML += "<button type='submit' style='width:100%; padding:15px; margin:10px 0; background:#667eea; color:white; border:none; border-radius:8px; cursor:pointer; font-size:16px;'>";
|
||||
customHTML += "Open Settings (Switch to Permanent AP Mode)";
|
||||
customHTML += "</button>";
|
||||
customHTML += "</form>";
|
||||
customHTML += "<br/><p style='font-size:12px; color:#666;'>Note: You can configure network mode later at <b>http://192.168.4.1/settings</b> (AP mode) or <b>http://{device-ip}/settings</b> (Router mode)</p>";
|
||||
|
||||
_wifiManager->setCustomHeadElement(customHTML.c_str());
|
||||
|
||||
if (_wifiManager->autoConnect(apName.c_str(), netConfig.apPass.c_str())) {
|
||||
LOG_INFO(TAG, "WiFi configured successfully via portal");
|
||||
onWiFiConnected();
|
||||
} 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);
|
||||
|
||||
// After 3 failed attempts during boot, start portal
|
||||
if (_wifiConnectionFailures >= MAX_WIFI_FAILURES) {
|
||||
LOG_ERROR(TAG, "Multiple WiFi connection failures - credentials may be invalid");
|
||||
|
||||
if (!_bootSequenceComplete) {
|
||||
// Boot not complete yet - open portal
|
||||
LOG_INFO(TAG, "Opening WiFi portal for reconfiguration");
|
||||
_wifiConnectionFailures = 0; // Reset counter
|
||||
startWiFiPortal();
|
||||
} else {
|
||||
// Boot already complete - just keep retrying
|
||||
LOG_WARNING(TAG, "WiFi connection lost - continuing retry attempts");
|
||||
// Reset counter after extended failure to prevent overflow
|
||||
if (_wifiConnectionFailures > 10) {
|
||||
_wifiConnectionFailures = 3;
|
||||
}
|
||||
_lastConnectionAttempt = now;
|
||||
startWiFiConnection(); // startWiFiConnection re-arms the timer
|
||||
}
|
||||
} else {
|
||||
// Retry WiFi connection — startWiFiConnection re-arms the timer
|
||||
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());
|
||||
setState(NetworkState::CONNECTED_WIFI);
|
||||
setActiveConnection(ConnectionType::WIFI);
|
||||
|
||||
// Reset failure counter on successful connection
|
||||
_wifiConnectionFailures = 0;
|
||||
|
||||
// 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:
|
||||
LOG_WARNING(TAG, "WiFi Disconnected");
|
||||
_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<Networking*>(param);
|
||||
net->handleReconnection();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void Networking::reconnectionTimerCallback(TimerHandle_t xTimer) {
|
||||
if (_instance) {
|
||||
xTaskCreate(networkReconnectTaskFn, "netRecon", 3072, _instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* NETWORKING.HPP - Intelligent Network Connection Manager
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🌐 THE NETWORK BRAIN OF VESPER 🌐
|
||||
*
|
||||
* This class provides intelligent network connectivity management with
|
||||
* automatic failover between Ethernet and WiFi. It handles all aspects
|
||||
* of network connectivity, configuration, and state management.
|
||||
*
|
||||
* 🏗️ INTELLIGENT CONNECTIVITY:
|
||||
* • Dual-stack support: Ethernet (primary) + WiFi (fallback)
|
||||
* • Automatic failover and recovery
|
||||
* • Smart connection prioritization
|
||||
* • State machine-based connection management
|
||||
* • Comprehensive event handling
|
||||
*
|
||||
* 🔄 AUTO-RECOVERY FEATURES:
|
||||
* • Automatic reconnection on connection loss
|
||||
* • Exponential backoff for failed attempts
|
||||
* • Cable detection for Ethernet
|
||||
* • WiFi portal fallback for configuration
|
||||
* • Boot timeout handling
|
||||
*
|
||||
* ⚙️ CONFIGURATION MANAGEMENT:
|
||||
* • Static IP configuration support
|
||||
* • Dynamic IP with DHCP fallback
|
||||
* • DNS configuration
|
||||
* • Hostname management
|
||||
* • WiFi credential management
|
||||
*
|
||||
* 📊 STATE MONITORING:
|
||||
* • Real-time connection status tracking
|
||||
* • Connection type identification
|
||||
* • Network quality monitoring
|
||||
* • Event-driven status updates
|
||||
* • Comprehensive logging
|
||||
*
|
||||
* 🔗 INTEGRATION:
|
||||
* • Clean callback interface for status changes
|
||||
* • ConfigManager integration for settings
|
||||
* • WiFiManager integration for portal mode
|
||||
* • Event-driven architecture
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Intelligent dual-stack networking)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <ETH.h>
|
||||
#include <functional>
|
||||
|
||||
class ConfigManager;
|
||||
class WiFiManager; // Forward declaration
|
||||
|
||||
enum class NetworkState {
|
||||
DISCONNECTED,
|
||||
CONNECTING_ETHERNET,
|
||||
CONNECTING_WIFI,
|
||||
WIFI_PORTAL_MODE,
|
||||
CONNECTED_ETHERNET,
|
||||
CONNECTED_WIFI,
|
||||
RECONNECTING,
|
||||
AP_MODE_PERMANENT
|
||||
};
|
||||
|
||||
enum class ConnectionType {
|
||||
NONE,
|
||||
ETHERNET,
|
||||
WIFI,
|
||||
AP
|
||||
};
|
||||
|
||||
class Networking {
|
||||
public:
|
||||
explicit Networking(ConfigManager& configManager);
|
||||
~Networking(); // Destructor to clean up WiFiManager
|
||||
|
||||
void begin();
|
||||
|
||||
// Returns whether the network is currently connected
|
||||
bool isConnected() const;
|
||||
String getLocalIP() const;
|
||||
String getGateway() const;
|
||||
ConnectionType getActiveConnection() const { return _activeConnection; }
|
||||
NetworkState getState() const { return _state; }
|
||||
|
||||
// Network event callbacks
|
||||
void setNetworkCallbacks(std::function<void()> onConnected, std::function<void()> onDisconnected) {
|
||||
_onNetworkConnected = onConnected;
|
||||
_onNetworkDisconnected = onDisconnected;
|
||||
}
|
||||
|
||||
// Manual connection control (for testing/debugging)
|
||||
void forceReconnect();
|
||||
|
||||
// AP Mode control
|
||||
void startPermanentAPMode();
|
||||
bool isInAPMode() const { return _state == NetworkState::AP_MODE_PERMANENT; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if Networking is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
// Static instance for callbacks
|
||||
static Networking* _instance;
|
||||
|
||||
// Static event handler
|
||||
static void networkEventHandler(arduino_event_id_t event, arduino_event_info_t info);
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
ConfigManager& _configManager;
|
||||
WiFiManager* _wifiManager;
|
||||
|
||||
// State
|
||||
NetworkState _state;
|
||||
ConnectionType _activeConnection;
|
||||
unsigned long _lastConnectionAttempt;
|
||||
bool _bootSequenceComplete;
|
||||
bool _ethernetCableConnected;
|
||||
int _wifiConnectionFailures; // Track consecutive WiFi failures
|
||||
|
||||
// Callbacks
|
||||
std::function<void()> _onNetworkConnected;
|
||||
std::function<void()> _onNetworkDisconnected;
|
||||
|
||||
// Timers
|
||||
TimerHandle_t _reconnectionTimer;
|
||||
|
||||
// Connection methods
|
||||
void startEthernetConnection();
|
||||
void startWiFiConnection();
|
||||
void startWiFiPortal();
|
||||
void handleReconnection();
|
||||
|
||||
// State management
|
||||
void setState(NetworkState newState);
|
||||
void setActiveConnection(ConnectionType type);
|
||||
void notifyConnectionChange(bool connected);
|
||||
|
||||
// Event handlers
|
||||
void onEthernetConnected();
|
||||
void onEthernetDisconnected();
|
||||
void onWiFiConnected();
|
||||
void onWiFiDisconnected();
|
||||
void onEthernetCableChange(bool connected);
|
||||
|
||||
// Utility methods
|
||||
void applyNetworkConfig(bool ethernet = false);
|
||||
bool hasValidWiFiCredentials();
|
||||
|
||||
// Timer callback and its task function
|
||||
static void reconnectionTimerCallback(TimerHandle_t xTimer);
|
||||
static void networkReconnectTaskFn(void* param);
|
||||
|
||||
// Constants
|
||||
static const unsigned long RECONNECTION_INTERVAL = 5000; // 5 seconds
|
||||
static const int MAX_WIFI_FAILURES = 3; // Portal after 3 failures
|
||||
};
|
||||
Reference in New Issue
Block a user