Files
project-vesper/src/Networking/Networking.hpp
T
bonamin 959cb77d81 feat(Telemetry,Networking,OTAManager,CommunicationRouter): diagnostics report — CPU temp, WiFi reconnects, OTA state, stack high-water mark
Console requested four more Health-tab metrics beyond F-054's free_heap/ping
work. None needed 30s heartbeat freshness, so this adds a separate low-frequency
report instead of growing the heartbeat further: published every 5 min to
status/info (diagnostics_report) and queryable on-demand via a new
telemetry.get_diagnostics command.

Only CPU temperature needs local sampling (15s, via a min/max/avg RunningStats
accumulator on Telemetry) — a thermal spike could occur and subside entirely
within a 5-minute gap. The other three fields are monotonic/self-tracking
(WiFi reconnect counter, FreeRTOS's own stack high-water mark, rarely-changing
OTA state) so a single read at report time loses no information.

Verified: pio run on all four board variants.
2026-07-17 13:09:16 +03:00

193 lines
7.5 KiB
C++

/*
* ═══════════════════════════════════════════════════════════════════════════════════
* 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; }
// 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<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 = 2; // Move to next stage after 2 failures
};