/* * ═══════════════════════════════════════════════════════════════════════════════════ * 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 #include #include #include 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 onConnected, std::function 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; } // Wipe WiFiManager stored credentials (SSID + password) void clearWiFiCredentials(); // ═══════════════════════════════════════════════════════════════════════════════ // HEALTH CHECK METHOD // ═══════════════════════════════════════════════════════════════════════════════ /** @brief Check if Networking is in healthy state */ bool isHealthy() const; // ═══════════════════════════════════════════════════════════════════════════════ // DIAGNOSTICS — lifetime WiFi reconnect count + last disconnect reason // ═══════════════════════════════════════════════════════════════════════════════ // Cumulative, in-memory only (resets on reboot — a fresh boot legitimately // starts a new "how flaky has this session been" count; lifetime boot // count already answers "how many times has this device restarted, ever"). uint32_t getReconnectCount() const { return _reconnectCount; } // Human-readable reason for the most recent disconnect, e.g. "AUTH_EXPIRE" // (via WiFi.disconnectReasonName()). Empty string if no disconnect yet this boot. String getLastDisconnectReason() const { return _lastDisconnectReason; } // millis() at the time of the most recent disconnect, or 0 if none yet this boot. uint32_t getLastDisconnectUptimeMs() const { return _lastDisconnectUptimeMs; } // 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 bool _triedSavedCredentials; // True once saved-creds phase has been exhausted // Diagnostics — see getReconnectCount() etc. above uint32_t _reconnectCount = 0; String _lastDisconnectReason = ""; uint32_t _lastDisconnectUptimeMs = 0; // Callbacks std::function _onNetworkConnected; std::function _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 = 2; // Move to next stage after 2 failures };