From 8e513bb501630381a3d1a56c3478c49a8c6c6488 Mon Sep 17 00:00:00 2001 From: iranl Date: Wed, 31 Jul 2024 13:15:26 +0200 Subject: [PATCH] Reconnect network on MQTT failure (#435) --- README.md | 5 +++-- lib/WiFiManager/WiFiManager.cpp | 9 +++++++- lib/WiFiManager/WiFiManager.h | 3 +++ src/NukiNetwork.cpp | 13 ++++++++--- src/NukiNetwork.h | 3 +++ src/PreferencesKeys.h | 7 ++++-- src/WebCfgServer.cpp | 6 +++++ src/networkDevices/EthLan8720Device.cpp | 2 +- src/networkDevices/EthLan8720Device.h | 2 +- src/networkDevices/NetworkDevice.h | 2 +- src/networkDevices/W5500Device.cpp | 2 +- src/networkDevices/W5500Device.h | 2 +- src/networkDevices/WifiDevice.cpp | 30 ++++++++++--------------- src/networkDevices/WifiDevice.h | 2 +- 14 files changed, 56 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index dd2d0c3..eac85c4 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ In a browser navigate to the IP address assigned to the ESP32. - RSSI Publish interval: Set to a positive integer to set the amount of seconds between updates to the maintenance/wifiRssi MQTT topic with the current Wi-Fi RSSI, set to -1 to disable, default 60. - MQTT Timeout until restart: Set to a positive integer to restart the Nuki Hub after the set amount of seconds has passed without an active connection to the MQTT broker, set to -1 to disable, default 60. - Restart on disconnect: Enable to restart the Nuki Hub when disconnected from the network. +- Reconnect network on MQTT connection failure: Enable to force reconnection to the network when connection to the MQTT broker fails (after 15 tries). - Enable MQTT logging: Enable to fill the maintenance/log MQTT topic with debug log information. - Check for Firmware Updates every 24h: Enable to allow the Nuki Hub to check the latest release of the Nuki Hub firmware on boot and every 24 hours. Requires the Nuki Hub to be able to connect to github.com. The latest version will be published to MQTT and will be visible on the main page of the Web Configurator. - Allow updating using MQTT: Enable to allow starting the Nuki Hub update process using MQTT. Will also enable the Home Assistant update functionality if auto discovery is enabled. @@ -440,8 +441,8 @@ After about a minute the new firmware should be installed afterwhich the ESP wil Selecting the wrong binary will lead to an unsuccessfull update

Note for users upgrading from Nuki Hub 8.35 or lower:
-Updating to version 8.36 requires a change to the partition table of the ESP32.
-Please follow the instructions for the [First time installation](#first-time-installation) once when updating to Nuki Hub 8.36 from an earlier version.
+Updating to version 9.00 requires a change to the partition table of the ESP32.
+Please follow the instructions for the [First time installation](#first-time-installation) once when updating to Nuki Hub 9.00 from an earlier version.
Your settings will not be affected when updating using the above instructions (do not select erase device when updating using Webflash).
## MQTT Encryption (optional; Wi-Fi and LAN8720 only) diff --git a/lib/WiFiManager/WiFiManager.cpp b/lib/WiFiManager/WiFiManager.cpp index 9369a5c..32ea7a8 100644 --- a/lib/WiFiManager/WiFiManager.cpp +++ b/lib/WiFiManager/WiFiManager.cpp @@ -1124,6 +1124,9 @@ bool WiFiManager::wifiConnectNew(String ssid, String pass,bool connect){ WiFi.persistent(true); if (_findBestRSSI) { + WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); + WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("find best RSSI: TRUE")); #endif @@ -1691,6 +1694,10 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ return false; } +void WiFiManager::resetScan(){ + _numNetworks = 0; +} + String WiFiManager::WiFiManager::getScanItemOut(){ String page; @@ -4013,7 +4020,7 @@ String WiFiManager::WiFi_psk(bool persistent) const { #ifdef WM_DEBUG_LEVEL DEBUG_WM(WM_DEBUG_VERBOSE,F("[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting")); #endif - WiFi.reconnect(); + //WiFi.reconnect(); #endif } else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE && _asyncScan){ diff --git a/lib/WiFiManager/WiFiManager.h b/lib/WiFiManager/WiFiManager.h index 4e8d580..6263434 100644 --- a/lib/WiFiManager/WiFiManager.h +++ b/lib/WiFiManager/WiFiManager.h @@ -279,6 +279,9 @@ class WiFiManager // erase wifi credentials void resetSettings(); + + // reset wifi scan + void resetScan(); // reboot esp void reboot(); diff --git a/src/NukiNetwork.cpp b/src/NukiNetwork.cpp index 1e4519b..5a4b263 100644 --- a/src/NukiNetwork.cpp +++ b/src/NukiNetwork.cpp @@ -237,6 +237,8 @@ bool NukiNetwork::update() void NukiNetwork::initialize() { _restartOnDisconnect = _preferences->getBool(preference_restart_on_disconnect, false); + _checkUpdates = _preferences->getBool(preference_check_updates, false); + _reconnectNetworkOnMqttDisconnect = _preferences->getBool(preference_recon_netw_on_mqtt_discon, false); _rssiPublishInterval = _preferences->getInt(preference_rssi_publish_interval) * 1000; _hostname = _preferences->getString(preference_hostname); @@ -358,8 +360,10 @@ bool NukiNetwork::update() return true; } - if(!_device->isConnected()) + if(!_device->isConnected() || (_mqttConnectCounter > 15 && _reconnectNetworkOnMqttDisconnect && !_firstConnect)) { + _mqttConnectCounter = 0; + if(_firstDisconnected) { _firstDisconnected = false; _device->mqttDisconnect(true); @@ -371,7 +375,7 @@ bool NukiNetwork::update() } Log->println(F("Network not connected. Trying reconnect.")); - ReconnectStatus reconnectStatus = _device->reconnect(); + ReconnectStatus reconnectStatus = _device->reconnect(true); switch(reconnectStatus) { @@ -405,8 +409,11 @@ bool NukiNetwork::update() bool success = reconnect(); if(!success) { + delay(2000); + _mqttConnectCounter++; return false; } + _mqttConnectCounter = 0; delay(2000); } @@ -471,7 +478,7 @@ bool NukiNetwork::update() _lastMaintenanceTs = ts; } - if(_preferences->getBool(preference_check_updates)) + if(_checkUpdates) { if(_lastUpdateCheckTs == 0 || (ts - _lastUpdateCheckTs) > 86400000) { diff --git a/src/NukiNetwork.h b/src/NukiNetwork.h index d285a9f..54daece 100644 --- a/src/NukiNetwork.h +++ b/src/NukiNetwork.h @@ -159,6 +159,7 @@ private: Gpio* _gpio; int _mqttConnectionState = 0; + int _mqttConnectCounter = 0; long _mqttConnectedTs = -1; bool _connectReplyReceived = false; bool _firstDisconnected = true; @@ -172,6 +173,8 @@ private: int _networkTimeout = 0; std::vector _mqttReceivers; bool _restartOnDisconnect = false; + bool _checkUpdates = false; + bool _reconnectNetworkOnMqttDisconnect = false; bool _firstConnect = true; bool _publishDebugInfo = false; bool _logIp = true; diff --git a/src/PreferencesKeys.h b/src/PreferencesKeys.h index a349e38..39ad41e 100644 --- a/src/PreferencesKeys.h +++ b/src/PreferencesKeys.h @@ -97,6 +97,7 @@ #define preference_ota_updater_url (char*)"otaUpdUrl" #define preference_update_from_mqtt (char*)"updMqtt" #define preference_show_secrets (char*)"showSecr" +#define preference_recon_netw_on_mqtt_discon (char*)"recNtwMqttDis" inline bool initPreferences(Preferences* preferences) { @@ -248,7 +249,8 @@ private: preference_cred_password, preference_disable_non_json, preference_publish_authdata, preference_publish_debug_info, preference_presence_detection_timeout, preference_official_hybrid, preference_query_interval_hybrid_lockstate, preference_official_hybrid_actions, preference_official_hybrid_retry, preference_has_mac_saved, preference_has_mac_byte_0, preference_has_mac_byte_1, preference_has_mac_byte_2, preference_latest_version, preference_task_size_network, preference_task_size_nuki, - preference_authlog_max_entries, preference_keypad_max_entries, preference_timecontrol_max_entries, preference_update_from_mqtt, preference_show_secrets + preference_authlog_max_entries, preference_keypad_max_entries, preference_timecontrol_max_entries, preference_update_from_mqtt, preference_show_secrets, + preference_recon_netw_on_mqtt_discon }; std::vector _redact = { @@ -262,7 +264,8 @@ private: preference_restart_on_disconnect, preference_keypad_control_enabled, preference_keypad_info_enabled, preference_keypad_publish_code, preference_show_secrets, preference_timecontrol_control_enabled, preference_timecontrol_info_enabled, preference_register_as_app, preference_register_opener_as_app, preference_ip_dhcp_enabled, preference_publish_authdata, preference_has_mac_saved, preference_publish_debug_info, preference_network_wifi_fallback_disabled, preference_official_hybrid, - preference_official_hybrid_actions, preference_official_hybrid_retry, preference_conf_info_enabled, preference_disable_non_json, preference_update_from_mqtt + preference_official_hybrid_actions, preference_official_hybrid_retry, preference_conf_info_enabled, preference_disable_non_json, preference_update_from_mqtt, + preference_recon_netw_on_mqtt_discon }; std::vector _bytePrefs = { diff --git a/src/WebCfgServer.cpp b/src/WebCfgServer.cpp index db68321..382e198 100644 --- a/src/WebCfgServer.cpp +++ b/src/WebCfgServer.cpp @@ -1013,6 +1013,11 @@ bool WebCfgServer::processArgs(String& message) _preferences->putBool(preference_restart_on_disconnect, (value == "1")); configChanged = true; } + else if(key == "RECNWTMQTTDIS") + { + _preferences->putBool(preference_recon_netw_on_mqtt_discon, (value == "1")); + configChanged = true; + } else if(key == "MQTTLOG") { _preferences->putBool(preference_mqtt_log_enabled, (value == "1")); @@ -2159,6 +2164,7 @@ void WebCfgServer::buildMqttConfigHtml(String &response) printInputField(response, "RSSI", "RSSI Publish interval (seconds; -1 to disable)", _preferences->getInt(preference_rssi_publish_interval), 6, ""); printInputField(response, "NETTIMEOUT", "MQTT Timeout until restart (seconds; -1 to disable)", _preferences->getInt(preference_network_timeout), 5, ""); printCheckBox(response, "RSTDISC", "Restart on disconnect", _preferences->getBool(preference_restart_on_disconnect), ""); + printCheckBox(response, "RECNWTMQTTDIS", "Reconnect network on MQTT connection failure", _preferences->getBool(preference_recon_netw_on_mqtt_discon), ""); printCheckBox(response, "MQTTLOG", "Enable MQTT logging", _preferences->getBool(preference_mqtt_log_enabled), ""); printCheckBox(response, "CHECKUPDATE", "Check for Firmware Updates every 24h", _preferences->getBool(preference_check_updates), ""); printCheckBox(response, "UPDATEMQTT", "Allow updating using MQTT", _preferences->getBool(preference_update_from_mqtt), ""); diff --git a/src/networkDevices/EthLan8720Device.cpp b/src/networkDevices/EthLan8720Device.cpp index ab4763c..c399355 100644 --- a/src/networkDevices/EthLan8720Device.cpp +++ b/src/networkDevices/EthLan8720Device.cpp @@ -143,7 +143,7 @@ bool EthLan8720Device::isConnected() return ETH.linkUp(); } -ReconnectStatus EthLan8720Device::reconnect() +ReconnectStatus EthLan8720Device::reconnect(bool force) { if(!_hardwareInitialized) { diff --git a/src/networkDevices/EthLan8720Device.h b/src/networkDevices/EthLan8720Device.h index 5cc64a2..22062c8 100644 --- a/src/networkDevices/EthLan8720Device.h +++ b/src/networkDevices/EthLan8720Device.h @@ -55,7 +55,7 @@ public: virtual void initialize(); virtual void reconfigure(); - virtual ReconnectStatus reconnect(); + virtual ReconnectStatus reconnect(bool force = false); bool supportsEncryption() override; virtual bool isConnected(); diff --git a/src/networkDevices/NetworkDevice.h b/src/networkDevices/NetworkDevice.h index 26d15ba..fdf9065 100644 --- a/src/networkDevices/NetworkDevice.h +++ b/src/networkDevices/NetworkDevice.h @@ -24,7 +24,7 @@ public: virtual const String deviceName() const = 0; virtual void initialize() = 0; - virtual ReconnectStatus reconnect() = 0; + virtual ReconnectStatus reconnect(bool force = false) = 0; virtual void reconfigure() = 0; virtual void printError(); virtual bool supportsEncryption() = 0; diff --git a/src/networkDevices/W5500Device.cpp b/src/networkDevices/W5500Device.cpp index 4071bc9..1d0a08e 100644 --- a/src/networkDevices/W5500Device.cpp +++ b/src/networkDevices/W5500Device.cpp @@ -79,7 +79,7 @@ void W5500Device::initialize() reconnect(); } -ReconnectStatus W5500Device::reconnect() +ReconnectStatus W5500Device::reconnect(bool force) { _hasDHCPAddress = false; diff --git a/src/networkDevices/W5500Device.h b/src/networkDevices/W5500Device.h index a1acce5..f0b4e9f 100644 --- a/src/networkDevices/W5500Device.h +++ b/src/networkDevices/W5500Device.h @@ -23,7 +23,7 @@ public: const String deviceName() const override; virtual void initialize(); - virtual ReconnectStatus reconnect(); + virtual ReconnectStatus reconnect(bool force = false); virtual void reconfigure(); bool supportsEncryption() override; diff --git a/src/networkDevices/WifiDevice.cpp b/src/networkDevices/WifiDevice.cpp index 800d1da..d2a82e4 100644 --- a/src/networkDevices/WifiDevice.cpp +++ b/src/networkDevices/WifiDevice.cpp @@ -72,6 +72,7 @@ void WifiDevice::initialize() _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled)); // reduced timeout if ESP is set to restart on disconnect _wm.setFindBestRSSI(_preferences->getBool(preference_find_best_rssi)); + _wm.setConnectTimeout(5); _wm.setConfigPortalTimeout(_restartOnDisconnect ? 60 * 3 : 60 * 30); _wm.setShowInfoUpdate(false); _wm.setMenu(wm_menu); @@ -141,32 +142,25 @@ bool WifiDevice::isConnected() return WiFi.isConnected(); } -ReconnectStatus WifiDevice::reconnect() +ReconnectStatus WifiDevice::reconnect(bool force) { - if(!isConnected() && !_isReconnecting) + if((!isConnected() || force) && !_isReconnecting) { _isReconnecting = true; WiFi.disconnect(); - delay(1000); - if(!_preferences->getBool(preference_find_best_rssi, false)) WiFi.reconnect(); - else + int loop = 0; + + while(isConnected() && loop <20) { - if(WiFi.getMode() & WIFI_STA){ - WiFi.mode(WIFI_OFF); - int timeout = (esp_timer_get_time() / 1000)+1200; - while(WiFi.getMode()!= WIFI_OFF && (esp_timer_get_time() / 1000) (esp_timer_get_time() / 1000) - 120000) _wm.setEnableConfigPortal(_startAp || !_preferences->getBool(preference_network_wifi_fallback_disabled)); return isConnected() ? ReconnectStatus::Success : ReconnectStatus::Failure; } diff --git a/src/networkDevices/WifiDevice.h b/src/networkDevices/WifiDevice.h index 080b53d..1d4ce8e 100644 --- a/src/networkDevices/WifiDevice.h +++ b/src/networkDevices/WifiDevice.h @@ -23,7 +23,7 @@ public: virtual void initialize(); virtual void reconfigure(); - virtual ReconnectStatus reconnect(); + virtual ReconnectStatus reconnect(bool force = false); bool supportsEncryption() override; virtual bool isConnected();