feat: two-tier factory reset, WiFi fallback chain, SettingsWebServer

Factory reset (F-015):
- InputManager gains MEDIUM_PRESSED state with mediumPressMs=5000
- 5s hold: wipe WiFi credentials only, restart on release
- 10s hold: full factory reset (WiFi wipe already done at 5s mark)
- New callbacks: setFactoryResetMediumPressCallback,
  setFactoryResetMediumPressReleaseCallback

WiFi fallback chain (F-016):
- Connection now cycles: saved creds → hardcoded failsafe → portal
- MAX_WIFI_FAILURES reduced 3→2 per stage
- Portal now reboots after saving credentials (fixes port 80 conflict
  between WiFiManager and AsyncWebServer)
- AP SSID sourced from netConfig.apSsid instead of hardcoded pattern
- clearWiFiCredentials() added to Networking for 5s reset gesture

SettingsWebServer (F-017):
- Instantiated in main.cpp alongside CommunicationRouter
- begin() called when network becomes ready (both WiFi paths)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-30 09:52:17 +03:00
co-authored by Claude Sonnet 4.6
parent ee73d4d2c4
commit df8426fce6
5 changed files with 183 additions and 124 deletions
+64 -39
View File
@@ -14,8 +14,8 @@ InputManager::InputManager()
: _initialized(false)
, _inputTaskHandle(nullptr) {
// Initialize factory reset button configuration
// GPIO 0, Active LOW (pull-up), 50ms debounce, 10s long press
_factoryResetButton.config = ButtonConfig(0, false, 50, 10000);
// GPIO 0, Active LOW (pull-up), 50ms debounce, 5s medium press, 10s long press
_factoryResetButton.config = ButtonConfig(0, false, 50, 5000, 10000);
_instance = this;
}
@@ -40,6 +40,7 @@ bool InputManager::begin() {
_factoryResetButton.lastRawState = false;
_factoryResetButton.stateChangeTime = millis();
_factoryResetButton.pressStartTime = 0;
_factoryResetButton.mediumPressTriggered = false;
_factoryResetButton.longPressTriggered = false;
// Create FreeRTOS task for input polling
@@ -81,6 +82,16 @@ void InputManager::setFactoryResetPressCallback(ButtonCallback callback) {
LOG_DEBUG(TAG, "InputManager: Factory reset press callback registered");
}
void InputManager::setFactoryResetMediumPressCallback(ButtonCallback callback) {
_factoryResetButton.config.onMediumPress = callback;
LOG_DEBUG(TAG, "InputManager: Factory reset medium press callback registered");
}
void InputManager::setFactoryResetMediumPressReleaseCallback(ButtonCallback callback) {
_factoryResetButton.config.onMediumPressRelease = callback;
LOG_DEBUG(TAG, "InputManager: Factory reset medium press release callback registered");
}
void InputManager::setFactoryResetLongPressCallback(ButtonCallback callback) {
_factoryResetButton.config.onLongPress = callback;
LOG_DEBUG(TAG, "InputManager: Factory reset long press callback registered");
@@ -175,94 +186,108 @@ bool InputManager::readButtonState(const ButtonData& button) const {
void InputManager::updateButton(ButtonData& button) {
uint32_t now = millis();
bool currentState = readButtonState(button);
// State machine for button handling
switch (button.state) {
case ButtonState::IDLE:
// Waiting for button press
if (currentState && !button.lastRawState) {
// Button just pressed - start debouncing
button.state = ButtonState::DEBOUNCING_PRESS;
button.stateChangeTime = now;
LOG_DEBUG(TAG, "InputManager: Button press detected on GPIO %d - debouncing",
LOG_DEBUG(TAG, "InputManager: Button press detected on GPIO %d - debouncing",
button.config.pin);
}
break;
case ButtonState::DEBOUNCING_PRESS:
// Debouncing press
if (!currentState) {
// Button released during debounce - false trigger
button.state = ButtonState::IDLE;
LOG_DEBUG(TAG, "InputManager: False trigger on GPIO %d (released during debounce)",
LOG_DEBUG(TAG, "InputManager: False trigger on GPIO %d (released during debounce)",
button.config.pin);
} else if (now - button.stateChangeTime >= button.config.debounceMs) {
// Debounce time passed - confirm press
button.state = ButtonState::LONG_PRESS_PENDING;
button.pressStartTime = now;
button.mediumPressTriggered = false;
button.longPressTriggered = false;
LOG_INFO(TAG, "InputManager: Button press confirmed on GPIO %d",
LOG_INFO(TAG, "InputManager: Button press confirmed on GPIO %d",
button.config.pin);
}
break;
case ButtonState::LONG_PRESS_PENDING:
// Button is pressed, waiting to see if it's a long press
if (!currentState) {
// Button released before long press threshold - it's a short press
// Released before medium press threshold — short press
button.state = ButtonState::DEBOUNCING_RELEASE;
button.stateChangeTime = now;
LOG_INFO(TAG, "InputManager: Short press detected on GPIO %d (held for %lums)",
LOG_INFO(TAG, "InputManager: Short press on GPIO %d (held %lums)",
button.config.pin, now - button.pressStartTime);
} else if (now - button.pressStartTime >= button.config.mediumPressMs) {
// Medium press threshold reached
button.state = ButtonState::MEDIUM_PRESSED;
button.mediumPressTriggered = true;
LOG_WARNING(TAG, "InputManager: MEDIUM PRESS on GPIO %d (held %lums)",
button.config.pin, now - button.pressStartTime);
if (button.config.onMediumPress) {
button.config.onMediumPress();
}
}
break;
case ButtonState::MEDIUM_PRESSED:
if (!currentState) {
// Released between medium and long threshold
button.state = ButtonState::DEBOUNCING_RELEASE;
button.stateChangeTime = now;
LOG_INFO(TAG, "InputManager: Medium press released on GPIO %d (held %lums)",
button.config.pin, now - button.pressStartTime);
} else if (now - button.pressStartTime >= button.config.longPressMs) {
// Long press threshold reached
button.state = ButtonState::LONG_PRESSED;
button.longPressTriggered = true;
LOG_WARNING(TAG, "InputManager: LONG PRESS DETECTED on GPIO %d (held for %lums)",
LOG_WARNING(TAG, "InputManager: LONG PRESS on GPIO %d (held %lums)",
button.config.pin, now - button.pressStartTime);
// Trigger long press callback
if (button.config.onLongPress) {
button.config.onLongPress();
}
}
break;
case ButtonState::LONG_PRESSED:
// Long press has been triggered, waiting for release
if (!currentState) {
button.state = ButtonState::DEBOUNCING_RELEASE;
button.stateChangeTime = now;
LOG_INFO(TAG, "InputManager: Long press released on GPIO %d (total duration: %lums)",
LOG_INFO(TAG, "InputManager: Long press released on GPIO %d (held %lums)",
button.config.pin, now - button.pressStartTime);
}
break;
case ButtonState::DEBOUNCING_RELEASE:
// Debouncing release
if (currentState) {
// Button pressed again during release debounce - go back to pressed state
// Re-pressed during release debounce
button.state = ButtonState::LONG_PRESS_PENDING;
LOG_DEBUG(TAG, "InputManager: Button re-pressed during release debounce on GPIO %d",
LOG_DEBUG(TAG, "InputManager: Button re-pressed during release debounce on GPIO %d",
button.config.pin);
} else if (now - button.stateChangeTime >= button.config.debounceMs) {
// Debounce time passed - confirm release
button.state = ButtonState::IDLE;
// If it was a short press (not long press), trigger the press callback
if (!button.longPressTriggered && button.config.onPress) {
LOG_INFO(TAG, "InputManager: Triggering press callback for GPIO %d",
button.config.pin);
button.config.onPress();
if (!button.mediumPressTriggered && !button.longPressTriggered) {
// Short press
if (button.config.onPress) {
LOG_INFO(TAG, "InputManager: Short press callback for GPIO %d", button.config.pin);
button.config.onPress();
}
} else if (button.mediumPressTriggered && !button.longPressTriggered) {
// Released between medium and long threshold
if (button.config.onMediumPressRelease) {
LOG_INFO(TAG, "InputManager: Medium press release callback for GPIO %d", button.config.pin);
button.config.onMediumPressRelease();
}
}
LOG_DEBUG(TAG, "InputManager: Button release confirmed on GPIO %d",
button.config.pin);
// Long press: action already fired at threshold, no release callback needed
LOG_DEBUG(TAG, "InputManager: Button release confirmed on GPIO %d", button.config.pin);
}
break;
}
// Store last raw state for edge detection
button.lastRawState = currentState;
}
+27 -12
View File
@@ -52,13 +52,16 @@ public:
uint8_t pin; // GPIO pin number
bool activeHigh; // true = active high, false = active low
uint32_t debounceMs; // Debounce time in milliseconds
uint32_t mediumPressMs; // Medium press threshold in milliseconds
uint32_t longPressMs; // Long press threshold in milliseconds
ButtonCallback onPress; // Callback for normal press
ButtonCallback onLongPress; // Callback for long press
ButtonConfig(uint8_t p = 0, bool ah = false, uint32_t db = 50, uint32_t lp = 10000)
: pin(p), activeHigh(ah), debounceMs(db), longPressMs(lp),
onPress(nullptr), onLongPress(nullptr) {}
ButtonCallback onPress; // Callback for short press (released before medium threshold)
ButtonCallback onMediumPress; // Callback fired when medium threshold is crossed (while still held)
ButtonCallback onMediumPressRelease;// Callback fired on release between medium and long threshold
ButtonCallback onLongPress; // Callback fired when long threshold is crossed (while still held)
ButtonConfig(uint8_t p = 0, bool ah = false, uint32_t db = 50, uint32_t mp = 5000, uint32_t lp = 10000)
: pin(p), activeHigh(ah), debounceMs(db), mediumPressMs(mp), longPressMs(lp),
onPress(nullptr), onMediumPress(nullptr), onMediumPressRelease(nullptr), onLongPress(nullptr) {}
};
// ═══════════════════════════════════════════════════════════════════════════════
@@ -89,6 +92,16 @@ public:
*/
void setFactoryResetPressCallback(ButtonCallback callback);
/**
* @brief Set callback for factory reset button medium press (fired at 5s while still held)
*/
void setFactoryResetMediumPressCallback(ButtonCallback callback);
/**
* @brief Set callback for factory reset button medium press release (released between 5s and 10s)
*/
void setFactoryResetMediumPressReleaseCallback(ButtonCallback callback);
/**
* @brief Set callback for factory reset button long press
* @param callback Function to call on long press (10s)
@@ -126,22 +139,24 @@ private:
IDLE, // Button not pressed
DEBOUNCING_PRESS, // Waiting for debounce on press
PRESSED, // Button confirmed pressed (short)
LONG_PRESS_PENDING, // Button held, waiting for long press threshold
LONG_PRESS_PENDING, // Button held, waiting for medium/long press threshold
MEDIUM_PRESSED, // Medium press confirmed and triggered, still held
LONG_PRESSED, // Long press confirmed and triggered
DEBOUNCING_RELEASE // Waiting for debounce on release
};
struct ButtonData {
ButtonConfig config;
ButtonState state;
bool lastRawState; // Last raw reading from pin
uint32_t stateChangeTime; // When state last changed
uint32_t pressStartTime; // When button was first pressed
bool mediumPressTriggered; // Has medium press callback been fired?
bool longPressTriggered; // Has long press callback been fired?
ButtonData() : state(ButtonState::IDLE), lastRawState(false),
stateChangeTime(0), pressStartTime(0),
longPressTriggered(false) {}
ButtonData() : state(ButtonState::IDLE), lastRawState(false),
stateChangeTime(0), pressStartTime(0),
mediumPressTriggered(false), longPressTriggered(false) {}
};
// ═══════════════════════════════════════════════════════════════════════════════
+62 -67
View File
@@ -17,6 +17,7 @@ Networking::Networking(ConfigManager& configManager)
, _bootSequenceComplete(false)
, _ethernetCableConnected(false)
, _wifiConnectionFailures(0)
, _triedSavedCredentials(false)
, _wifiManager(nullptr)
, _reconnectionTimer(nullptr) {
@@ -110,60 +111,35 @@ void Networking::startEthernetConnection() {
}
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);
// ALWAYS try default credentials first (for bundled router deployment)
applyNetworkConfig(false);
WiFi.mode(WIFI_STA);
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());
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);
// 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() {
@@ -173,7 +149,7 @@ void Networking::startWiFiPortal() {
WiFi.mode(WIFI_AP_STA);
auto& netConfig = _configManager.getNetworkConfig();
String apName = "Vesper-" + _configManager.getDeviceUID();
String apName = netConfig.apSsid;
LOG_INFO(TAG, "WiFi Portal: SSID='%s', Password='%s'", apName.c_str(), netConfig.apPass.c_str());
@@ -190,8 +166,12 @@ void Networking::startWiFiPortal() {
_wifiManager->setCustomHeadElement(customHTML.c_str());
if (_wifiManager->autoConnect(apName.c_str(), netConfig.apPass.c_str())) {
LOG_INFO(TAG, "WiFi configured successfully via portal");
onWiFiConnected();
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);
@@ -226,29 +206,36 @@ void Networking::handleReconnection() {
_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");
// 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) {
// Boot not complete yet - open portal
LOG_INFO(TAG, "Opening WiFi portal for reconfiguration");
_wifiConnectionFailures = 0; // Reset counter
_triedSavedCredentials = false; // reset for next boot
_wifiConnectionFailures = 0;
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
// Post-boot: reset and retry from saved creds again
LOG_WARNING(TAG, "WiFi connection lost - restarting credential cycle");
_triedSavedCredentials = false;
_wifiConnectionFailures = 0;
startWiFiConnection();
}
} else {
// Retry WiFi connection — startWiFiConnection re-arms the timer
startWiFiConnection();
return;
}
// Still within a phase — keep retrying
startWiFiConnection();
} else {
// Still within timeout window — re-arm timer to check again later
xTimerStart(_reconnectionTimer, 0);
@@ -387,9 +374,10 @@ void Networking::onWiFiConnected() {
setState(NetworkState::CONNECTED_WIFI);
setActiveConnection(ConnectionType::WIFI);
// Reset failure counter on successful connection
// Reset failure/phase counters on successful connection
_wifiConnectionFailures = 0;
_triedSavedCredentials = false;
// Stop reconnection timer
xTimerStop(_reconnectionTimer, 0);
@@ -550,6 +538,13 @@ void Networking::reconnectionTimerCallback(TimerHandle_t xTimer) {
}
}
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);
+6 -2
View File
@@ -103,6 +103,9 @@ public:
// 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
@@ -128,7 +131,8 @@ private:
unsigned long _lastConnectionAttempt;
bool _bootSequenceComplete;
bool _ethernetCableConnected;
int _wifiConnectionFailures; // Track consecutive WiFi failures
int _wifiConnectionFailures; // Track consecutive WiFi failures
bool _triedSavedCredentials; // True once saved-creds phase has been exhausted
// Callbacks
std::function<void()> _onNetworkConnected;
@@ -165,5 +169,5 @@ private:
// Constants
static const unsigned long RECONNECTION_INTERVAL = 5000; // 5 seconds
static const int MAX_WIFI_FAILURES = 3; // Portal after 3 failures
static const int MAX_WIFI_FAILURES = 2; // Move to next stage after 2 failures
};
+24 -4
View File
@@ -126,6 +126,7 @@
#include "HealthMonitor/HealthMonitor.hpp"
#include "FirmwareValidator/FirmwareValidator.hpp"
#include "InputManager/InputManager.hpp"
#include "SettingsWebServer/SettingsWebServer.hpp"
#include "Version.hpp"
#include "NvsMigration/NvsMigration.hpp"
#if HAS_RF
@@ -150,6 +151,7 @@ AsyncWebSocket ws("/ws");
AsyncUDP udp;
Networking networking(configManager);
CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp);
SettingsWebServer settingsWebServer(server, configManager, networking);
HealthMonitor healthMonitor;
FirmwareValidator firmwareValidator;
InputManager inputManager;
@@ -422,11 +424,25 @@ static void bootOtaCheck() {
Serial.println("[BootOTA] All servers failed during flash — continuing normal boot");
}
// Called at 5s hold: wipe WiFi credentials only (restart triggered on release)
void handleWiFiCredsReset() {
LOG_WARNING(TAG, "Factory Reset: WiFi credentials cleared (5s press)");
networking.clearWiFiCredentials();
}
// Called on release after 5s but before 10s: restart after WiFi wipe
void handleWiFiCredsResetRelease() {
LOG_WARNING(TAG, "Factory Reset: Restarting after WiFi credentials wipe");
delay(1000);
ESP.restart();
}
// Called at 10s hold: WiFi creds were already cleared at 5s, now clear all settings too
void handleFactoryReset() {
if (configManager.resetAllToDefaults()) {
delay(3000);
ESP.restart();
}
LOG_WARNING(TAG, "Factory Reset: Full reset triggered (10s press)");
configManager.resetAllToDefaults();
delay(1000);
ESP.restart();
}
#if HAS_RTC
@@ -491,6 +507,8 @@ void setup()
LOG_INFO(TAG, "Log level set to %d from configuration", logLevel);
inputManager.begin();
inputManager.setFactoryResetMediumPressCallback(handleWiFiCredsReset);
inputManager.setFactoryResetMediumPressReleaseCallback(handleWiFiCredsResetRelease);
inputManager.setFactoryResetLongPressCallback(handleFactoryReset);
// ═══════════════════════════════════════════════════════════════════════════════
@@ -663,6 +681,7 @@ void setup()
// Start AsyncWebServer when network becomes available (only once!)
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
settingsWebServer.begin();
LOG_INFO(TAG, "🚀 Starting AsyncWebServer on port 80...");
server.begin();
LOG_INFO(TAG, "✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str());
@@ -689,6 +708,7 @@ void setup()
// 🔥 CRITICAL: Start AsyncWebServer ONLY when network is ready
// Do NOT start if WiFiManager portal is active (port 80 conflict!)
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
settingsWebServer.begin();
LOG_INFO(TAG, "🚀 Starting AsyncWebServer on port 80...");
server.begin();
LOG_INFO(TAG, "✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str());