From eb4db32b8919df951e50236452876be1e7d77399 Mon Sep 17 00:00:00 2001 From: technyon Date: Sun, 20 Oct 2024 14:03:18 +0200 Subject: [PATCH] add astylerc and apply code formatting --- .astylerc | 2 + src/Gpio.cpp | 465 ++++--- src/NukiDeviceId.cpp | 4 +- src/NukiNetwork.cpp | 1360 ++++++++++-------- src/NukiNetworkLock.cpp | 560 ++++---- src/NukiNetworkOpener.cpp | 743 +++++----- src/NukiOfficial.cpp | 25 +- src/NukiOpenerWrapper.cpp | 1775 +++++++++++++++++------ src/NukiPublisher.cpp | 4 +- src/NukiWrapper.cpp | 1776 ++++++++++++++++++------ src/WebCfgServer.cpp | 1012 ++++++++++---- src/main.cpp | 184 ++- src/networkDevices/EthernetDevice.cpp | 172 +-- src/networkDevices/IPConfiguration.cpp | 14 +- src/networkDevices/WifiDevice.cpp | 107 +- src/util/NetworkDeviceInstantiator.cpp | 286 ++-- src/util/NetworkUtil.cpp | 180 +-- 17 files changed, 5755 insertions(+), 2914 deletions(-) create mode 100644 .astylerc diff --git a/.astylerc b/.astylerc new file mode 100644 index 0000000..d31a299 --- /dev/null +++ b/.astylerc @@ -0,0 +1,2 @@ +--style=allman +--add-braces diff --git a/src/Gpio.cpp b/src/Gpio.cpp index 80189ac..8bf9f9e 100644 --- a/src/Gpio.cpp +++ b/src/Gpio.cpp @@ -12,7 +12,7 @@ Gpio* Gpio::_inst = nullptr; Gpio::Gpio(Preferences* preferences) -: _preferences(preferences) + : _preferences(preferences) { _inst = this; loadPinConfiguration(); @@ -80,35 +80,35 @@ void Gpio::onTimer() { switch(entry.role) { - case PinRole::InputLock: - case PinRole::InputUnlock: - case PinRole::InputUnlatch: - case PinRole::InputLockNgo: - case PinRole::InputLockNgoUnlatch: - case PinRole::InputElectricStrikeActuation: - case PinRole::InputActivateRTO: - case PinRole::InputActivateCM: - case PinRole::InputDeactivateRtoCm: - case PinRole::InputDeactivateRTO: - case PinRole::InputDeactivateCM: - case PinRole::GeneralInputPullDown: - case PinRole::GeneralInputPullUp: - if(isTriggered(entry)) - { - _inst->notify(getGpioAction(entry.role), entry.pin); - } - break; - case PinRole::OutputHighLocked: - case PinRole::OutputHighUnlocked: - case PinRole::OutputHighMotorBlocked: - case PinRole::OutputHighRtoActive: - case PinRole::OutputHighCmActive: - case PinRole::OutputHighRtoOrCmActive: - case PinRole::GeneralOutput: - case PinRole::Ethernet: - // ignore. This case should not occur since pins are configured as output - default: - break; + case PinRole::InputLock: + case PinRole::InputUnlock: + case PinRole::InputUnlatch: + case PinRole::InputLockNgo: + case PinRole::InputLockNgoUnlatch: + case PinRole::InputElectricStrikeActuation: + case PinRole::InputActivateRTO: + case PinRole::InputActivateCM: + case PinRole::InputDeactivateRtoCm: + case PinRole::InputDeactivateRTO: + case PinRole::InputDeactivateCM: + case PinRole::GeneralInputPullDown: + case PinRole::GeneralInputPullUp: + if(isTriggered(entry)) + { + _inst->notify(getGpioAction(entry.role), entry.pin); + } + break; + case PinRole::OutputHighLocked: + case PinRole::OutputHighUnlocked: + case PinRole::OutputHighMotorBlocked: + case PinRole::OutputHighRtoActive: + case PinRole::OutputHighCmActive: + case PinRole::OutputHighRtoOrCmActive: + case PinRole::GeneralOutput: + case PinRole::Ethernet: + // ignore. This case should not occur since pins are configured as output + default: + break; } } } @@ -139,37 +139,37 @@ void Gpio::init() switch(entry.role) { - case PinRole::InputLock: - case PinRole::InputUnlock: - case PinRole::InputUnlatch: - case PinRole::InputLockNgo: - case PinRole::InputLockNgoUnlatch: - case PinRole::InputElectricStrikeActuation: - case PinRole::InputActivateRTO: - case PinRole::InputActivateCM: - case PinRole::InputDeactivateRtoCm: - case PinRole::InputDeactivateRTO: - case PinRole::InputDeactivateCM: - case PinRole::GeneralInputPullUp: - pinMode(entry.pin, INPUT_PULLUP); - hasInputPin = true; - break; - case PinRole::GeneralInputPullDown: - pinMode(entry.pin, INPUT_PULLDOWN); - hasInputPin = true; - break; - case PinRole::OutputHighLocked: - case PinRole::OutputHighUnlocked: - case PinRole::OutputHighMotorBlocked: - case PinRole::OutputHighRtoActive: - case PinRole::OutputHighCmActive: - case PinRole::OutputHighRtoOrCmActive: - case PinRole::GeneralOutput: - pinMode(entry.pin, OUTPUT); - break; - case PinRole::Ethernet: - default: - break; + case PinRole::InputLock: + case PinRole::InputUnlock: + case PinRole::InputUnlatch: + case PinRole::InputLockNgo: + case PinRole::InputLockNgoUnlatch: + case PinRole::InputElectricStrikeActuation: + case PinRole::InputActivateRTO: + case PinRole::InputActivateCM: + case PinRole::InputDeactivateRtoCm: + case PinRole::InputDeactivateRTO: + case PinRole::InputDeactivateCM: + case PinRole::GeneralInputPullUp: + pinMode(entry.pin, INPUT_PULLUP); + hasInputPin = true; + break; + case PinRole::GeneralInputPullDown: + pinMode(entry.pin, INPUT_PULLDOWN); + hasInputPin = true; + break; + case PinRole::OutputHighLocked: + case PinRole::OutputHighUnlocked: + case PinRole::OutputHighMotorBlocked: + case PinRole::OutputHighRtoActive: + case PinRole::OutputHighCmActive: + case PinRole::OutputHighRtoOrCmActive: + case PinRole::GeneralOutput: + pinMode(entry.pin, OUTPUT); + break; + case PinRole::Ethernet: + default: + break; } } @@ -221,7 +221,10 @@ void Gpio::loadPinConfiguration() if(std::find(disabledPins.begin(), disabledPins.end(), entry.pin) == disabledPins.end()) { - if(entry.role == PinRole::Ethernet) entry.role = PinRole::Disabled; + if(entry.role == PinRole::Ethernet) + { + entry.role = PinRole::Disabled; + } entry.role = (PinRole) serialized[(i * 2 + 1)]; Log->println("Not found in Ethernet disabled pins"); Log->print(F("Role: ")); @@ -234,7 +237,10 @@ void Gpio::loadPinConfiguration() Log->print(F("Role: ")); Log->println(getRoleDescription(entry.role)); } - if(entry.role != PinRole::Disabled) _pinConfiguration.push_back(entry); + if(entry.role != PinRole::Disabled) + { + _pinConfiguration.push_back(entry); + } } } @@ -244,90 +250,94 @@ const std::vector Gpio::getDisabledPins() const switch(_preferences->getInt(preference_network_hardware, 0)) { - case 2: - disabledPins.push_back(ETH_PHY_CS_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_IRQ_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_RST_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_SPI_MISO_GENERIC_W5500); - disabledPins.push_back(ETH_PHY_SPI_MOSI_GENERIC_W5500); - break; - case 3: - disabledPins.push_back(ETH_PHY_CS_M5_W5500); - disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); - disabledPins.push_back(ETH_PHY_RST_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); - break; - case 10: - disabledPins.push_back(ETH_PHY_CS_M5_W5500_S3); - disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); - disabledPins.push_back(ETH_PHY_RST_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500_S3); - disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500_S3); - disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500_S3); - break; - case 9: - disabledPins.push_back(ETH_PHY_CS_ETH01EVO); - disabledPins.push_back(ETH_PHY_IRQ_ETH01EVO); - disabledPins.push_back(ETH_PHY_RST_ETH01EVO); - disabledPins.push_back(ETH_PHY_SPI_SCK_ETH01EVO); - disabledPins.push_back(ETH_PHY_SPI_MISO_ETH01EVO); - disabledPins.push_back(ETH_PHY_SPI_MOSI_ETH01EVO); - break; - case 6: - disabledPins.push_back(ETH_PHY_CS_M5_W5500); - disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); - disabledPins.push_back(ETH_PHY_RST_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); - disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); - break; - case 11: - disabledPins.push_back(_preferences->getInt(preference_network_custom_cs, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_irq, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_rst, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_sck, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_miso, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_mosi, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_pwr, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_mdc, -1)); - disabledPins.push_back(_preferences->getInt(preference_network_custom_mdio, -1)); - break; - #if defined(CONFIG_IDF_TARGET_ESP32) - case 4: - disabledPins.push_back(12); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - case 5: - disabledPins.push_back(16); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - case 8: - disabledPins.push_back(5); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - case 7: - disabledPins.push_back(-1); - disabledPins.push_back(ETH_RESET_PIN_LAN8720); - disabledPins.push_back(ETH_PHY_MDC_LAN8720); - disabledPins.push_back(ETH_PHY_MDIO_LAN8720); - break; - #endif - default: - break; + case 2: + disabledPins.push_back(ETH_PHY_CS_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_IRQ_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_RST_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_SPI_MISO_GENERIC_W5500); + disabledPins.push_back(ETH_PHY_SPI_MOSI_GENERIC_W5500); + break; + case 3: + disabledPins.push_back(ETH_PHY_CS_M5_W5500); + disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); + disabledPins.push_back(ETH_PHY_RST_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); + break; + case 10: + disabledPins.push_back(ETH_PHY_CS_M5_W5500_S3); + disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); + disabledPins.push_back(ETH_PHY_RST_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500_S3); + disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500_S3); + disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500_S3); + break; + case 9: + disabledPins.push_back(ETH_PHY_CS_ETH01EVO); + disabledPins.push_back(ETH_PHY_IRQ_ETH01EVO); + disabledPins.push_back(ETH_PHY_RST_ETH01EVO); + disabledPins.push_back(ETH_PHY_SPI_SCK_ETH01EVO); + disabledPins.push_back(ETH_PHY_SPI_MISO_ETH01EVO); + disabledPins.push_back(ETH_PHY_SPI_MOSI_ETH01EVO); + break; + case 6: + disabledPins.push_back(ETH_PHY_CS_M5_W5500); + disabledPins.push_back(ETH_PHY_IRQ_M5_W5500); + disabledPins.push_back(ETH_PHY_RST_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_SCK_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MISO_M5_W5500); + disabledPins.push_back(ETH_PHY_SPI_MOSI_M5_W5500); + break; + case 11: + disabledPins.push_back(_preferences->getInt(preference_network_custom_cs, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_irq, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_rst, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_sck, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_miso, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_mosi, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_pwr, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_mdc, -1)); + disabledPins.push_back(_preferences->getInt(preference_network_custom_mdio, -1)); + break; +#if defined(CONFIG_IDF_TARGET_ESP32) + case 4: + disabledPins.push_back(12); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; + case 5: + disabledPins.push_back(16); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; + case 8: + disabledPins.push_back(5); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; + case 7: + disabledPins.push_back(-1); + disabledPins.push_back(ETH_RESET_PIN_LAN8720); + disabledPins.push_back(ETH_PHY_MDC_LAN8720); + disabledPins.push_back(ETH_PHY_MDIO_LAN8720); + break; +#endif + default: + break; } Log->print(F("GPIO Ethernet disabled pins:")); for_each_n(disabledPins.begin(), disabledPins.size(), - [](int x) { Log->print(" "); Log->print(x); }); + [](int x) + { + Log->print(" "); + Log->print(x); + }); Log->println(); return disabledPins; } @@ -393,52 +403,52 @@ String Gpio::getRoleDescription(const PinRole& role) const { switch(role) { - case PinRole::Disabled: - return "Disabled"; - case PinRole::InputLock: - return "Input: Lock"; - case PinRole::InputUnlock: - return "Input: Unlock"; - case PinRole::InputUnlatch: - return "Input: Unlatch"; - case PinRole::InputLockNgo: - return "Input: Lock n Go"; - case PinRole::InputLockNgoUnlatch: - return "Input: Lock n Go and unlatch"; - case PinRole::InputElectricStrikeActuation: - return "Input: Electric strike actuation"; - case PinRole::InputActivateRTO: - return "Input: Activate RTO"; - case PinRole::InputActivateCM: - return "Input: Activate CM"; - case PinRole::InputDeactivateRtoCm: - return "Input: Deactivate RTO/CM"; - case PinRole::InputDeactivateRTO: - return "Input: Deactivate RTO"; - case PinRole::InputDeactivateCM: - return "Input: Deactivate CM"; - case PinRole::OutputHighLocked: - return "Output: High when locked"; - case PinRole::OutputHighUnlocked: - return "Output: High when unlocked"; - case PinRole::OutputHighMotorBlocked: - return "Output: High when motor blocked"; - case PinRole::OutputHighRtoActive: - return "Output: High when RTO active"; - case PinRole::OutputHighCmActive: - return "Output: High when CM active"; - case PinRole::OutputHighRtoOrCmActive: - return "Output: High when RTO or CM active"; - case PinRole::GeneralOutput: - return "General output"; - case PinRole::GeneralInputPullDown: - return "General input (Pull-down)"; - case PinRole::GeneralInputPullUp: - return "General input (Pull-up)"; - case PinRole::Ethernet: - return "Ethernet"; - default: - return "Unknown"; + case PinRole::Disabled: + return "Disabled"; + case PinRole::InputLock: + return "Input: Lock"; + case PinRole::InputUnlock: + return "Input: Unlock"; + case PinRole::InputUnlatch: + return "Input: Unlatch"; + case PinRole::InputLockNgo: + return "Input: Lock n Go"; + case PinRole::InputLockNgoUnlatch: + return "Input: Lock n Go and unlatch"; + case PinRole::InputElectricStrikeActuation: + return "Input: Electric strike actuation"; + case PinRole::InputActivateRTO: + return "Input: Activate RTO"; + case PinRole::InputActivateCM: + return "Input: Activate CM"; + case PinRole::InputDeactivateRtoCm: + return "Input: Deactivate RTO/CM"; + case PinRole::InputDeactivateRTO: + return "Input: Deactivate RTO"; + case PinRole::InputDeactivateCM: + return "Input: Deactivate CM"; + case PinRole::OutputHighLocked: + return "Output: High when locked"; + case PinRole::OutputHighUnlocked: + return "Output: High when unlocked"; + case PinRole::OutputHighMotorBlocked: + return "Output: High when motor blocked"; + case PinRole::OutputHighRtoActive: + return "Output: High when RTO active"; + case PinRole::OutputHighCmActive: + return "Output: High when CM active"; + case PinRole::OutputHighRtoOrCmActive: + return "Output: High when RTO or CM active"; + case PinRole::GeneralOutput: + return "General output"; + case PinRole::GeneralInputPullDown: + return "General input (Pull-down)"; + case PinRole::GeneralInputPullUp: + return "General input (Pull-up)"; + case PinRole::Ethernet: + return "Ethernet"; + default: + return "Unknown"; } } @@ -447,46 +457,47 @@ GpioAction Gpio::getGpioAction(const PinRole &role) const { switch(role) { - case PinRole::Disabled: - return GpioAction::None; - case PinRole::InputLock: - return GpioAction::Lock; - case PinRole::InputUnlock: - return GpioAction::Unlock; - case PinRole::InputUnlatch: - return GpioAction::Unlatch; - case PinRole::InputLockNgo: - return GpioAction::LockNgo; - case PinRole::InputLockNgoUnlatch: - return GpioAction::LockNgoUnlatch; - case PinRole::InputElectricStrikeActuation: - return GpioAction::ElectricStrikeActuation; - case PinRole::InputActivateRTO: - return GpioAction::ActivateRTO; - case PinRole::InputActivateCM: - return GpioAction::ActivateCM; - case PinRole::InputDeactivateRtoCm: - return GpioAction::DeactivateRtoCm; - case PinRole::InputDeactivateRTO: - return GpioAction::DeactivateRTO; - case PinRole::InputDeactivateCM: - return GpioAction::DeactivateCM; + case PinRole::Disabled: + return GpioAction::None; + case PinRole::InputLock: + return GpioAction::Lock; + case PinRole::InputUnlock: + return GpioAction::Unlock; + case PinRole::InputUnlatch: + return GpioAction::Unlatch; + case PinRole::InputLockNgo: + return GpioAction::LockNgo; + case PinRole::InputLockNgoUnlatch: + return GpioAction::LockNgoUnlatch; + case PinRole::InputElectricStrikeActuation: + return GpioAction::ElectricStrikeActuation; + case PinRole::InputActivateRTO: + return GpioAction::ActivateRTO; + case PinRole::InputActivateCM: + return GpioAction::ActivateCM; + case PinRole::InputDeactivateRtoCm: + return GpioAction::DeactivateRtoCm; + case PinRole::InputDeactivateRTO: + return GpioAction::DeactivateRTO; + case PinRole::InputDeactivateCM: + return GpioAction::DeactivateCM; - case PinRole::GeneralInputPullDown: - case PinRole::GeneralInputPullUp: - return GpioAction::GeneralInput; + case PinRole::GeneralInputPullDown: + case PinRole::GeneralInputPullUp: + return GpioAction::GeneralInput; - case PinRole::GeneralOutput: - case PinRole::Ethernet: - case PinRole::OutputHighLocked: - case PinRole::OutputHighUnlocked: - case PinRole::OutputHighMotorBlocked: - case PinRole::OutputHighRtoActive: - case PinRole::OutputHighCmActive: - case PinRole::OutputHighRtoOrCmActive: - default: - return GpioAction::None; - }} + case PinRole::GeneralOutput: + case PinRole::Ethernet: + case PinRole::OutputHighLocked: + case PinRole::OutputHighUnlocked: + case PinRole::OutputHighMotorBlocked: + case PinRole::OutputHighRtoActive: + case PinRole::OutputHighCmActive: + case PinRole::OutputHighRtoOrCmActive: + default: + return GpioAction::None; + } +} void Gpio::getConfigurationText(String& text, const std::vector& pinConfiguration, const String& linebreak) const diff --git a/src/NukiDeviceId.cpp b/src/NukiDeviceId.cpp index 5c9bd42..6eb01bb 100644 --- a/src/NukiDeviceId.cpp +++ b/src/NukiDeviceId.cpp @@ -5,8 +5,8 @@ #include "PreferencesKeys.h" NukiDeviceId::NukiDeviceId(Preferences* preferences, const std::string& preferencesId) -: _preferences(preferences), - _preferencesId(preferencesId) + : _preferences(preferences), + _preferencesId(preferencesId) { _deviceId = _preferences->getUInt(_preferencesId.c_str(), 0); diff --git a/src/NukiNetwork.cpp b/src/NukiNetwork.cpp index b8498bf..9eec5bb 100644 --- a/src/NukiNetwork.cpp +++ b/src/NukiNetwork.cpp @@ -24,13 +24,13 @@ extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_ #ifndef NUKI_HUB_UPDATER NukiNetwork::NukiNetwork(Preferences *preferences, Gpio* gpio, const String& maintenancePathPrefix, char* buffer, size_t bufferSize) -: _preferences(preferences), - _gpio(gpio), - _buffer(buffer), - _bufferSize(bufferSize) + : _preferences(preferences), + _gpio(gpio), + _buffer(buffer), + _bufferSize(bufferSize) #else NukiNetwork::NukiNetwork(Preferences *preferences) -: _preferences(preferences) + : _preferences(preferences) #endif { // Remove obsolete W5500 hardware detection configuration @@ -43,7 +43,7 @@ NukiNetwork::NukiNetwork(Preferences *preferences) _webEnabled = _preferences->getBool(preference_webserver_enabled, true); _updateFromMQTT = _preferences->getBool(preference_update_from_mqtt, false); - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER memset(_maintenancePathPrefix, 0, sizeof(_maintenancePathPrefix)); size_t len = maintenancePathPrefix.length(); for(int i=0; i < len; i++) @@ -60,7 +60,7 @@ NukiNetwork::NukiNetwork(Preferences *preferences) { _mqttConnectionStateTopic[i] = connectionStateTopic.charAt(i); } - #endif +#endif setupDevice(); } @@ -76,25 +76,25 @@ void NukiNetwork::setupDevice() if(hardwareDetect == 0) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 hardwareDetect = 1; - #else +#else hardwareDetect = 11; - _preferences->putInt(preference_network_custom_addr, 1); - _preferences->putInt(preference_network_custom_cs, 8); - _preferences->putInt(preference_network_custom_irq, 9); - _preferences->putInt(preference_network_custom_rst, 10); - _preferences->putInt(preference_network_custom_sck, 11); - _preferences->putInt(preference_network_custom_miso, 12); - _preferences->putInt(preference_network_custom_mosi, 13); - _preferences->putBool(preference_ntw_reconfigure, true); - #endif + _preferences->putInt(preference_network_custom_addr, 1); + _preferences->putInt(preference_network_custom_cs, 8); + _preferences->putInt(preference_network_custom_irq, 9); + _preferences->putInt(preference_network_custom_rst, 10); + _preferences->putInt(preference_network_custom_sck, 11); + _preferences->putInt(preference_network_custom_miso, 12); + _preferences->putInt(preference_network_custom_mosi, 13); + _preferences->putBool(preference_ntw_reconfigure, true); +#endif _preferences->putInt(preference_network_hardware, hardwareDetect); } if(strcmp(WiFi_fallbackDetect, "wifi_fallback") == 0) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 if(!_firstBootAfterDeviceChange) { Log->println(F("Failed to connect to network. Wi-Fi fallback is disabled, rebooting.")); @@ -105,14 +105,20 @@ void NukiNetwork::setupDevice() Log->println(F("Switching to Wi-Fi device as fallback.")); _networkDeviceType = NetworkDeviceType::WiFi; - #else +#else int custEth = _preferences->getInt(preference_network_custom_phy, 0); - if(custEth<3) custEth++; - else custEth = 0; + if(custEth<3) + { + custEth++; + } + else + { + custEth = 0; + } _preferences->putInt(preference_network_custom_phy, custEth); _preferences->putBool(preference_ntw_reconfigure, true); - #endif +#endif } else { @@ -308,7 +314,8 @@ void NukiNetwork::initialize() } else { - Log->print(F("MQTT: Connecting with user: ")); Log->println(_mqttUser); + Log->print(F("MQTT: Connecting with user: ")); + Log->println(_mqttUser); _mqtt_cfg.credentials.username = _mqttUser; _mqtt_cfg.credentials.authentication.password = _mqttPass; } @@ -364,8 +371,14 @@ bool NukiNetwork::update() { _mqttConnectCounter = 0; - if(!_webEnabled) forceEnableWebServer = true; - if(_restartOnDisconnect && (esp_timer_get_time() / 1000) > 60000) restartEsp(RestartReason::RestartOnDisconnectWatchdog); + if(!_webEnabled) + { + forceEnableWebServer = true; + } + if(_restartOnDisconnect && (esp_timer_get_time() / 1000) > 60000) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } } if(_device->isConnected() && !_mqttClientInitiated && strcmp(_mqttBrokerAddr, "") != 0) @@ -377,9 +390,18 @@ bool NukiNetwork::update() { MqttLoggerMode mode; - if(_preferences->getBool(preference_mqtt_log_enabled, false) && _preferences->getBool(preference_webserial_enabled, false)) mode = MqttLoggerMode::MqttAndSerialAndWeb; - else if (_preferences->getBool(preference_webserial_enabled, false)) mode = MqttLoggerMode::SerialAndWeb; - else mode = MqttLoggerMode::MqttAndSerial; + if(_preferences->getBool(preference_mqtt_log_enabled, false) && _preferences->getBool(preference_webserial_enabled, false)) + { + mode = MqttLoggerMode::MqttAndSerialAndWeb; + } + else if (_preferences->getBool(preference_webserial_enabled, false)) + { + mode = MqttLoggerMode::SerialAndWeb; + } + else + { + mode = MqttLoggerMode::MqttAndSerial; + } char* _path = new char[200]; memset(_path, 0, sizeof(_path)); @@ -401,29 +423,29 @@ bool NukiNetwork::update() { switch (pinEntry.role) { - case PinRole::GeneralInputPullDown: - case PinRole::GeneralInputPullUp: - if(rebGpio) - { - buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_role}); - publishString(_lockPath.c_str(), gpioPath, "input", false); - buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_state}); - publishString(_lockPath.c_str(), gpioPath, std::to_string(digitalRead(pinEntry.pin)).c_str(), false); - } - break; - case PinRole::GeneralOutput: - if(rebGpio) - { - buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_role}); - publishString(_lockPath.c_str(), gpioPath, "output", false); - buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_state}); - publishString(_lockPath.c_str(), gpioPath, "0", false); - } + case PinRole::GeneralInputPullDown: + case PinRole::GeneralInputPullUp: + if(rebGpio) + { + buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_role}); + publishString(_lockPath.c_str(), gpioPath, "input", false); buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_state}); - subscribe(_lockPath.c_str(), gpioPath); - break; - default: - break; + publishString(_lockPath.c_str(), gpioPath, std::to_string(digitalRead(pinEntry.pin)).c_str(), false); + } + break; + case PinRole::GeneralOutput: + if(rebGpio) + { + buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_role}); + publishString(_lockPath.c_str(), gpioPath, "output", false); + buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_state}); + publishString(_lockPath.c_str(), gpioPath, "0", false); + } + buildMqttPath(gpioPath, {mqtt_topic_gpio_prefix, (mqtt_topic_gpio_pin + std::to_string(pinEntry.pin)).c_str(), mqtt_topic_gpio_state}); + subscribe(_lockPath.c_str(), gpioPath); + break; + default: + break; } } _gpio->addCallback([this](const GpioAction& action, const int& pin) @@ -455,7 +477,10 @@ bool NukiNetwork::update() delay(200); restartEsp(RestartReason::ReconfigureWebServer); } - else if(!_webEnabled) forceEnableWebServer = false; + else if(!_webEnabled) + { + forceEnableWebServer = false; + } delay(2000); } @@ -463,7 +488,10 @@ bool NukiNetwork::update() { if(_networkTimeout > 0 && (ts - _lastConnectedTs > _networkTimeout * 1000) && ts > 60000) { - if(!_webEnabled) forceEnableWebServer = true; + if(!_webEnabled) + { + forceEnableWebServer = true; + } Log->println("Network timeout has been reached, restarting ..."); delay(200); restartEsp(RestartReason::NetworkTimeoutWatchdog); @@ -514,21 +542,26 @@ bool NukiNetwork::update() JsonDocument doc; NetworkClientSecure *client = new NetworkClientSecure; - if (client) { + if (client) + { client->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); { HTTPClient https; https.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); https.useHTTP10(true); - if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) { + if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) + { int httpResponseCode = https.GET(); if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_MOVED_PERMANENTLY) { DeserializationError jsonError = deserializeJson(doc, https.getStream()); - if (!jsonError) { otaManifestSuccess = true; } + if (!jsonError) + { + otaManifestSuccess = true; + } } } https.end(); @@ -540,14 +573,29 @@ bool NukiNetwork::update() { String currentVersion = NUKI_HUB_VERSION; - if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) _latestVersion = doc["release"]["fullversion"]; - else if(currentVersion.indexOf("beta") > 0) _latestVersion = doc["beta"]["fullversion"]; - else if(currentVersion.indexOf("master") > 0) _latestVersion = doc["master"]["fullversion"]; - else _latestVersion = doc["release"]["fullversion"]; + if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) + { + _latestVersion = doc["release"]["fullversion"]; + } + else if(currentVersion.indexOf("beta") > 0) + { + _latestVersion = doc["beta"]["fullversion"]; + } + else if(currentVersion.indexOf("master") > 0) + { + _latestVersion = doc["master"]["fullversion"]; + } + else + { + _latestVersion = doc["release"]["fullversion"]; + } publishString(_maintenancePathPrefix, mqtt_topic_info_nuki_hub_latest, _latestVersion, true); - if(strcmp(_latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) _preferences->putString(preference_latest_version, _latestVersion); + if(strcmp(_latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) + { + _preferences->putString(preference_latest_version, _latestVersion); + } } } } @@ -588,7 +636,8 @@ void NukiNetwork::mqtt_event_handler(void *handler_args, esp_event_base_t base, esp_mqtt_event_handle_t event = (esp_mqtt_event_t*)event_data; esp_mqtt_client_handle_t client = event->client; int msg_id; - switch ((esp_mqtt_event_id_t)event_id) { + switch ((esp_mqtt_event_id_t)event_id) + { case MQTT_EVENT_CONNECTED: ESP_LOGI(MQTT_TAG, "MQTT_EVENT_CONNECTED"); Log->println("MQTT Connected"); @@ -619,7 +668,8 @@ void NukiNetwork::mqtt_event_handler(void *handler_args, esp_event_base_t base, break; case MQTT_EVENT_ERROR: ESP_LOGI(MQTT_TAG, "MQTT_EVENT_ERROR"); - if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) { + if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) + { ESP_LOGI(MQTT_TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno)); } break; @@ -968,9 +1018,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - {{(char*)"pl_on", (char*)"1"}, - {(char*)"pl_off", (char*)"0"}, - {(char*)"val_tpl", (char*)"{{value_json.critical}}" }}); + { + {(char*)"pl_on", (char*)"1"}, + {(char*)"pl_off", (char*)"0"}, + {(char*)"val_tpl", (char*)"{{value_json.critical}}" } + }); // Battery voltage publishHassTopic("sensor", @@ -986,8 +1038,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"V"}, - {(char*)"val_tpl", (char*)"{{value_json.batteryVoltage}}" }}); + { + {(char*)"unit_of_meas", (char*)"V"}, + {(char*)"val_tpl", (char*)"{{value_json.batteryVoltage}}" } + }); // Trigger publishHassTopic("sensor", @@ -1003,7 +1057,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" } }); + { { (char*)"en", (char*)"true" } }); // MQTT Connected publishHassTopic("binary_sensor", @@ -1019,9 +1073,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - {{(char*)"pl_on", (char*)"online"}, - {(char*)"pl_off", (char*)"offline"}, - {(char*)"ic", (char*)"mdi:lan-connect"}}); + { + {(char*)"pl_on", (char*)"online"}, + {(char*)"pl_off", (char*)"offline"}, + {(char*)"ic", (char*)"mdi:lan-connect"} + }); // Reset publishHassTopic("switch", @@ -1037,13 +1093,15 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_reset, - { { (char*)"ic", (char*)"mdi:restart" }, - { (char*)"pl_on", (char*)"1" }, - { (char*)"pl_off", (char*)"0" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"ic", (char*)"mdi:restart" }, + { (char*)"pl_on", (char*)"1" }, + { (char*)"pl_off", (char*)"0" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); - // Network device + // Network device publishHassTopic("sensor", "network_device", uidString, @@ -1057,7 +1115,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); // Nuki Hub Webserver enabled publishHassTopic("switch", @@ -1073,12 +1131,14 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", _lockPath + mqtt_topic_webserver_action, - { { (char*)"pl_on", (char*)"1" }, - { (char*)"pl_off", (char*)"0" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"pl_on", (char*)"1" }, + { (char*)"pl_off", (char*)"0" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); - // Uptime + // Uptime publishHassTopic("sensor", "uptime", uidString, @@ -1092,12 +1152,14 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - { (char*)"unit_of_meas", (char*)"min"}}); + { + { (char*)"en", (char*)"true" }, + { (char*)"unit_of_meas", (char*)"min"} + }); if(_preferences->getBool(preference_mqtt_log_enabled, false)) { - // MQTT Log + // MQTT Log publishHassTopic("sensor", "mqtt_log", uidString, @@ -1111,7 +1173,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); } else { @@ -1134,9 +1196,11 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { {(char*)"pl_on", (char*)"1"}, - {(char*)"pl_off", (char*)"0"}, - { (char*)"en", (char*)"true" }}); + { + {(char*)"pl_on", (char*)"1"}, + {(char*)"pl_off", (char*)"0"}, + { (char*)"en", (char*)"true" } + }); } else { @@ -1157,8 +1221,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Hardware version publishHassTopic("sensor", @@ -1174,8 +1240,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Nuki Hub version publishHassTopic("sensor", @@ -1191,8 +1259,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Nuki Hub build publishHassTopic("sensor", @@ -1208,8 +1278,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // Nuki Hub restart reason publishHassTopic("sensor", @@ -1225,7 +1297,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); // Nuki Hub restart reason ESP publishHassTopic("sensor", @@ -1241,7 +1313,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }}); + { { (char*)"en", (char*)"true" }}); if(_checkUpdates) { @@ -1259,8 +1331,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:counter"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:counter"} + }); // NUKI Hub update char latest_version_topic[250]; @@ -1282,10 +1356,12 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, - { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, - { (char*)"l_ver_t", (char*)latest_version_topic }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, + { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, + { (char*)"l_ver_t", (char*)latest_version_topic } + }); } else { @@ -1302,11 +1378,13 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", _lockPath + mqtt_topic_update, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_inst", (char*)"1" }, - { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, - { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, - { (char*)"l_ver_t", (char*)latest_version_topic }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_inst", (char*)"1" }, + { (char*)"ent_pic", (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/master/icon/favicon-32x32.png" }, + { (char*)"rel_u", (char*)GITHUB_LATEST_RELEASE_URL }, + { (char*)"l_ver_t", (char*)latest_version_topic } + }); } } else @@ -1329,8 +1407,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", "", - { { (char*)"en", (char*)"true" }, - {(char*)"ic", (char*)"mdi:ip"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"ic", (char*)"mdi:ip"} + }); // Query Lock State publishHassTopic("button", @@ -1346,8 +1426,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_query_lockstate, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); // Query Config publishHassTopic("button", @@ -1363,8 +1445,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_query_config, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); // Query Lock State Command result publishHassTopic("button", @@ -1380,8 +1464,10 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "", "diagnostic", String("~") + mqtt_topic_query_lockstate_command_result, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); publishHassTopic("sensor", "bluetooth_signal_strength", @@ -1396,7 +1482,7 @@ void NukiNetwork::publishHASSConfig(char* deviceType, const char* baseTopic, cha "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"dBm"} }); + { {(char*)"unit_of_meas", (char*)"dBm"} }); } void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) @@ -1433,8 +1519,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"unlatch" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"unlatch" } + }); } else { @@ -1457,8 +1545,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"lockNgo" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"lockNgo" } + }); } else { @@ -1481,8 +1571,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"lockNgoUnlatch" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"lockNgoUnlatch" } + }); } else { @@ -1503,8 +1595,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "diagnostic", String("~") + mqtt_topic_query_battery, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); if((int)basicLockConfigAclPrefs[6] == 1) { @@ -1522,13 +1616,15 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:led-variant-on" }, - { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:led-variant-on" }, + { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1551,13 +1647,15 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:radiobox-marked" }, - { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:radiobox-marked" }, + { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1580,12 +1678,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoLockEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"autoLockEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoLockEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoLockEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"autoLockEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoLockEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1608,12 +1708,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoUnLockDisabled\": \"0\"}" }, - { (char*)"pl_off", (char*)"{ \"autoUnLockDisabled\": \"1\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoUnLockDisabled}}" }, - { (char*)"stat_on", (char*)"0" }, - { (char*)"stat_off", (char*)"1" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoUnLockDisabled\": \"0\"}" }, + { (char*)"pl_off", (char*)"{ \"autoUnLockDisabled\": \"1\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoUnLockDisabled}}" }, + { (char*)"stat_on", (char*)"0" }, + { (char*)"stat_off", (char*)"1" } + }); } else { @@ -1636,12 +1738,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"singleLock\": \"0\"}" }, - { (char*)"pl_off", (char*)"{ \"singleLock\": \"1\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.singleLock}}" }, - { (char*)"stat_on", (char*)"0" }, - { (char*)"stat_off", (char*)"1" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"singleLock\": \"0\"}" }, + { (char*)"pl_off", (char*)"{ \"singleLock\": \"1\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.singleLock}}" }, + { (char*)"stat_on", (char*)"0" }, + { (char*)"stat_off", (char*)"1" } + }); } else { @@ -1661,8 +1765,10 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"%"}, - {(char*)"val_tpl", (char*)"{{value_json.level}}" }}); + { + {(char*)"unit_of_meas", (char*)"%"}, + {(char*)"val_tpl", (char*)"{{value_json.level}}" } + }); if((int)basicLockConfigAclPrefs[7] == 1) { @@ -1679,12 +1785,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:brightness-6" }, - { (char*)"cmd_tpl", (char*)"{ \"ledBrightness\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.ledBrightness}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:brightness-6" }, + { (char*)"cmd_tpl", (char*)"{ \"ledBrightness\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.ledBrightness}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"5" } + }); } else { @@ -1707,12 +1815,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoUnlatch\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"autoUnlatch\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoUnlatch}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoUnlatch\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"autoUnlatch\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoUnlatch}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1735,12 +1845,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1762,12 +1874,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:timer-cog-outline" }, - { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:timer-cog-outline" }, + { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -1790,12 +1904,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -1949,11 +2065,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"unlockedPositionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.unlockedPositionOffsetDegrees}}" }, - { (char*)"min", (char*)"-90" }, - { (char*)"max", (char*)"180" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"unlockedPositionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.unlockedPositionOffsetDegrees}}" }, + { (char*)"min", (char*)"-90" }, + { (char*)"max", (char*)"180" } + }); } else { @@ -1975,11 +2093,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"lockedPositionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.lockedPositionOffsetDegrees}}" }, - { (char*)"min", (char*)"-180" }, - { (char*)"max", (char*)"90" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"lockedPositionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.lockedPositionOffsetDegrees}}" }, + { (char*)"min", (char*)"-180" }, + { (char*)"max", (char*)"90" } + }); } else { @@ -2001,11 +2121,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"singleLockedPositionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.singleLockedPositionOffsetDegrees}}" }, - { (char*)"min", (char*)"-180" }, - { (char*)"max", (char*)"180" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"singleLockedPositionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.singleLockedPositionOffsetDegrees}}" }, + { (char*)"min", (char*)"-180" }, + { (char*)"max", (char*)"180" } + }); } else { @@ -2027,11 +2149,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"unlockedToLockedTransitionOffsetDegrees\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.unlockedToLockedTransitionOffsetDegrees}}" }, - { (char*)"min", (char*)"-180" }, - { (char*)"max", (char*)"180" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"unlockedToLockedTransitionOffsetDegrees\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.unlockedToLockedTransitionOffsetDegrees}}" }, + { (char*)"min", (char*)"-180" }, + { (char*)"max", (char*)"180" } + }); } else { @@ -2053,11 +2177,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"lockNgoTimeout\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.lockNgoTimeout}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"lockNgoTimeout\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.lockNgoTimeout}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -2120,12 +2246,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"detachedCylinder\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"detachedCylinder\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.detachedCylinder}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"detachedCylinder\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"detachedCylinder\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.detachedCylinder}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2164,12 +2292,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2191,11 +2321,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"unlatchDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.unlatchDuration}}" }, - { (char*)"min", (char*)"1" }, - { (char*)"max", (char*)"30" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"unlatchDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.unlatchDuration}}" }, + { (char*)"min", (char*)"1" }, + { (char*)"max", (char*)"30" } + }); } else { @@ -2217,11 +2349,13 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"autoLockTimeOut\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.autoLockTimeOut}}" }, - { (char*)"min", (char*)"30" }, - { (char*)"max", (char*)"1800" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"autoLockTimeOut\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.autoLockTimeOut}}" }, + { (char*)"min", (char*)"30" }, + { (char*)"max", (char*)"1800" } + }); } else { @@ -2244,12 +2378,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2272,12 +2408,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, - { (char*)"cmd_tpl", (char*)"{ \"nightModeStartTime\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeStartTime}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, + { (char*)"cmd_tpl", (char*)"{ \"nightModeStartTime\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeStartTime}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"5" } + }); } else { @@ -2300,12 +2438,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, - { (char*)"cmd_tpl", (char*)"{ \"nightModeEndTime\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeEndTime}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pattern", (char*)"([0-1][0-9]|2[0-3]):[0-5][0-9]" }, + { (char*)"cmd_tpl", (char*)"{ \"nightModeEndTime\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeEndTime}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"5" } + }); } else { @@ -2328,12 +2468,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeAutoLockEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeAutoLockEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoLockEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeAutoLockEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeAutoLockEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoLockEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2356,12 +2498,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeAutoUnlockDisabled\": \"0\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeAutoUnlockDisabled\": \"1\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoUnlockDisabled}}" }, - { (char*)"stat_on", (char*)"0" }, - { (char*)"stat_off", (char*)"1" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeAutoUnlockDisabled\": \"0\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeAutoUnlockDisabled\": \"1\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeAutoUnlockDisabled}}" }, + { (char*)"stat_on", (char*)"0" }, + { (char*)"stat_off", (char*)"1" } + }); } else { @@ -2384,12 +2528,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"nightModeImmediateLockOnStart\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"nightModeImmediateLockOnStart\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.nightModeImmediateLockOnStart}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"nightModeImmediateLockOnStart\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"nightModeImmediateLockOnStart\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.nightModeImmediateLockOnStart}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2412,12 +2558,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"immediateAutoLockEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"immediateAutoLockEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.immediateAutoLockEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"immediateAutoLockEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"immediateAutoLockEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.immediateAutoLockEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2440,12 +2588,14 @@ void NukiNetwork::publishHASSConfigAdditionalLockEntities(char *deviceType, cons "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"autoUpdateEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"autoUpdateEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.autoUpdateEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"autoUpdateEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"autoUpdateEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.autoUpdateEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2472,9 +2622,11 @@ void NukiNetwork::publishHASSConfigDoorSensor(char *deviceType, const char *base "", "", "", - {{(char*)"pl_on", (char*)"doorOpened"}, - {(char*)"pl_off", (char*)"doorClosed"}, - {(char*)"pl_not_avail", (char*)"unavailable"}}); + { + {(char*)"pl_on", (char*)"doorOpened"}, + {(char*)"pl_off", (char*)"doorClosed"}, + {(char*)"pl_not_avail", (char*)"unavailable"} + }); } void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, const char *baseTopic, char *name, char *uidString) @@ -2510,8 +2662,10 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", String("~") + mqtt_topic_lock_action, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"electricStrikeActuation" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"electricStrikeActuation" } + }); } else { @@ -2531,8 +2685,10 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", "", - {{(char*)"pl_on", (char*)"on"}, - {(char*)"pl_off", (char*)"off"}}); + { + {(char*)"pl_on", (char*)"on"}, + {(char*)"pl_off", (char*)"off"} + }); if((int)aclPrefs[12] == 1 && (int)aclPrefs[13] == 1) { @@ -2549,11 +2705,13 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", String("~") + mqtt_topic_lock_action, - {{ (char*)"en", (char*)"true" }, - {(char*)"stat_on", (char*)"on"}, - {(char*)"stat_off", (char*)"off"}, - {(char*)"pl_on", (char*)"activateCM"}, - {(char*)"pl_off", (char*)"deactivateCM"}}); + { + { (char*)"en", (char*)"true" }, + {(char*)"stat_on", (char*)"on"}, + {(char*)"stat_off", (char*)"off"}, + {(char*)"pl_on", (char*)"activateCM"}, + {(char*)"pl_off", (char*)"deactivateCM"} + }); } else { @@ -2573,8 +2731,10 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "", "", - {{(char*)"pl_on", (char*)"ring"}, - {(char*)"pl_off", (char*)"standby"}}); + { + {(char*)"pl_on", (char*)"ring"}, + {(char*)"pl_off", (char*)"standby"} + }); JsonDocument json; json = createHassJson(uidString, "_ring_event", "Ring", name, baseTopic, String("~") + mqtt_topic_lock_ring, deviceType, "doorbell", "", "", "", {{(char*)"val_tpl", (char*)"{ \"event_type\": \"{{ value }}\" }"}}); @@ -2600,13 +2760,15 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:led-variant-on" }, - { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:led-variant-on" }, + { (char*)"pl_on", (char*)"{ \"ledEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"ledEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.ledEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2629,13 +2791,15 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:radiobox-marked" }, - { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:radiobox-marked" }, + { (char*)"pl_on", (char*)"{ \"buttonEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"buttonEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.buttonEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2657,14 +2821,16 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:volume-source" }, - { (char*)"cmd_tpl", (char*)"{ \"soundLevel\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.soundLevel}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"255" }, - { (char*)"mode", (char*)"slider" }, - { (char*)"step", (char*)"25.5" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:volume-source" }, + { (char*)"cmd_tpl", (char*)"{ \"soundLevel\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.soundLevel}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"255" }, + { (char*)"mode", (char*)"slider" }, + { (char*)"step", (char*)"25.5" } + }); } else { @@ -2687,12 +2853,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"pairingEnabled\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"pairingEnabled\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.pairingEnabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2714,12 +2882,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"ic", (char*)"mdi:timer-cog-outline" }, - { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"ic", (char*)"mdi:timer-cog-outline" }, + { (char*)"cmd_tpl", (char*)"{ \"timeZoneOffset\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.timeZoneOffset}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -2742,12 +2912,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"dstMode\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"dstMode\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.dstMode}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2934,12 +3106,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"busModeSwitch\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"busModeSwitch\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.busModeSwitch}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"busModeSwitch\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"busModeSwitch\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.busModeSwitch}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -2961,10 +3135,12 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"shortCircuitDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.shortCircuitDuration}}" }, - { (char*)"min", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"shortCircuitDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.shortCircuitDuration}}" }, + { (char*)"min", (char*)"0" } + }); } else { @@ -2986,12 +3162,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDelay\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDelay}}" }, - { (char*)"min", (char*)"0" }, - { (char*)"max", (char*)"30000" }, - { (char*)"step", (char*)"3000" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDelay\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDelay}}" }, + { (char*)"min", (char*)"0" }, + { (char*)"max", (char*)"30000" }, + { (char*)"step", (char*)"3000" } + }); } else { @@ -3014,12 +3192,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"randomElectricStrikeDelay\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"randomElectricStrikeDelay\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.randomElectricStrikeDelay}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"randomElectricStrikeDelay\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"randomElectricStrikeDelay\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.randomElectricStrikeDelay}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3041,12 +3221,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDuration}}" }, - { (char*)"min", (char*)"1000" }, - { (char*)"max", (char*)"30000" }, - { (char*)"step", (char*)"3000" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"electricStrikeDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.electricStrikeDuration}}" }, + { (char*)"min", (char*)"1000" }, + { (char*)"max", (char*)"30000" }, + { (char*)"step", (char*)"3000" } + }); } else { @@ -3069,12 +3251,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"disableRtoAfterRing\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"disableRtoAfterRing\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.disableRtoAfterRing}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"disableRtoAfterRing\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"disableRtoAfterRing\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.disableRtoAfterRing}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3096,11 +3280,13 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"rtoTimeout\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.rtoTimeout}}" }, - { (char*)"min", (char*)"5" }, - { (char*)"max", (char*)"60" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"rtoTimeout\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.rtoTimeout}}" }, + { (char*)"min", (char*)"5" }, + { (char*)"max", (char*)"60" } + }); } else { @@ -3143,12 +3329,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"cmd_tpl", (char*)"{ \"doorbellSuppressionDuration\": \"{{ value }}\" }" }, - { (char*)"val_tpl", (char*)"{{value_json.doorbellSuppressionDuration}}" }, - { (char*)"min", (char*)"500" }, - { (char*)"max", (char*)"10000" }, - { (char*)"step", (char*)"1000" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"cmd_tpl", (char*)"{ \"doorbellSuppressionDuration\": \"{{ value }}\" }" }, + { (char*)"val_tpl", (char*)"{{value_json.doorbellSuppressionDuration}}" }, + { (char*)"min", (char*)"500" }, + { (char*)"max", (char*)"10000" }, + { (char*)"step", (char*)"1000" } + }); } else { @@ -3239,12 +3427,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"soundConfirmation\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"soundConfirmation\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.soundConfirmation}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"soundConfirmation\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"soundConfirmation\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.soundConfirmation}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3325,12 +3515,14 @@ void NukiNetwork::publishHASSConfigAdditionalOpenerEntities(char *deviceType, co "", "config", String("~") + mqtt_topic_config_action, - { { (char*)"en", (char*)"true" }, - { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, - { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, - { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + { + { (char*)"en", (char*)"true" }, + { (char*)"pl_on", (char*)"{ \"automaticBatteryTypeDetection\": \"1\"}" }, + { (char*)"pl_off", (char*)"{ \"automaticBatteryTypeDetection\": \"0\"}" }, + { (char*)"val_tpl", (char*)"{{value_json.automaticBatteryTypeDetection}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } else { @@ -3353,8 +3545,10 @@ void NukiNetwork::publishHASSConfigAccessLog(char *deviceType, const char *baseT "", "diagnostic", "", - { { (char*)"ic", (char*)"mdi:format-list-bulleted" }, - { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'LockAction')|selectattr('action', 'in', ['Lock', 'Unlock', 'Unlatch'])|first|default).authorizationName|default }}" }}); + { + { (char*)"ic", (char*)"mdi:format-list-bulleted" }, + { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'LockAction')|selectattr('action', 'in', ['Lock', 'Unlock', 'Unlatch'])|first|default).authorizationName|default }}" } + }); String rollingSate = "~"; rollingSate.concat(mqtt_topic_lock_log_rolling); @@ -3373,30 +3567,34 @@ void NukiNetwork::publishHASSConfigAccessLog(char *deviceType, const char *baseT "", "diagnostic", "", - { { (char*)"ic", (char*)"mdi:format-list-bulleted" }, - { (char*)"json_attr_t", (char*)rollingStateChr }, - { (char*)"val_tpl", (char*)"{{value_json.index}}" }}); + { + { (char*)"ic", (char*)"mdi:format-list-bulleted" }, + { (char*)"json_attr_t", (char*)rollingStateChr }, + { (char*)"val_tpl", (char*)"{{value_json.index}}" } + }); } void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopic, char *name, char *uidString) { // Keypad battery critical - publishHassTopic("binary_sensor", - "keypad_battery_low", - uidString, - "_keypad_battery_low", - "Keypad battery low", - name, - baseTopic, - String("~") + mqtt_topic_battery_basic_json, - deviceType, - "battery", - "", - "diagnostic", - "", - {{(char*)"pl_on", (char*)"1"}, - {(char*)"pl_off", (char*)"0"}, - {(char*)"val_tpl", (char*)"{{value_json.keypadCritical}}" }}); + publishHassTopic("binary_sensor", + "keypad_battery_low", + uidString, + "_keypad_battery_low", + "Keypad battery low", + name, + baseTopic, + String("~") + mqtt_topic_battery_basic_json, + deviceType, + "battery", + "", + "diagnostic", + "", + { + {(char*)"pl_on", (char*)"1"}, + {(char*)"pl_off", (char*)"0"}, + {(char*)"val_tpl", (char*)"{{value_json.keypadCritical}}" } + }); // Query Keypad publishHassTopic("button", @@ -3412,8 +3610,10 @@ void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopi "", "diagnostic", String("~") + mqtt_topic_query_keypad, - { { (char*)"en", (char*)"false" }, - { (char*)"pl_prs", (char*)"1" }}); + { + { (char*)"en", (char*)"false" }, + { (char*)"pl_prs", (char*)"1" } + }); publishHassTopic("sensor", "keypad_status", @@ -3428,8 +3628,10 @@ void NukiNetwork::publishHASSConfigKeypad(char *deviceType, const char *baseTopi "", "diagnostic", "", - { { (char*)"ic", (char*)"mdi:drag-vertical" }, - { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'KeypadAction')|first|default).completionStatus|default }}" }}); + { + { (char*)"ic", (char*)"mdi:drag-vertical" }, + { (char*)"val_tpl", (char*)"{{ (value_json|selectattr('type', 'eq', 'KeypadAction')|first|default).completionStatus|default }}" } + }); } void NukiNetwork::publishHASSWifiRssiConfig(char *deviceType, const char *baseTopic, char *name, char *uidString) @@ -3452,24 +3654,24 @@ void NukiNetwork::publishHASSWifiRssiConfig(char *deviceType, const char *baseTo "measurement", "diagnostic", "", - { {(char*)"unit_of_meas", (char*)"dBm"} }); + { {(char*)"unit_of_meas", (char*)"dBm"} }); } void NukiNetwork::publishHassTopic(const String& mqttDeviceType, - const String& mqttDeviceName, - const String& uidString, - const String& uidStringPostfix, - const String& displayName, - const String& name, - const String& baseTopic, - const String& stateTopic, - const String& deviceType, - const String& deviceClass, - const String& stateClass, - const String& entityCat, - const String& commandTopic, - std::vector> additionalEntries -) + const String& mqttDeviceName, + const String& uidString, + const String& uidStringPostfix, + const String& displayName, + const String& name, + const String& baseTopic, + const String& stateTopic, + const String& deviceType, + const String& deviceClass, + const String& stateClass, + const String& entityCat, + const String& commandTopic, + std::vector> additionalEntries + ) { if(!_mqttClientInitiated) { @@ -3522,10 +3724,10 @@ void NukiNetwork::removeTopic(const String& mqttPath, const String& mqttTopic) path.concat(mqttTopic); esp_mqtt_client_publish(_mqttClient, path.c_str(), "", 0, MQTT_QOS_LEVEL, 1); - #ifdef DEBUG_NUKIHUB +#ifdef DEBUG_NUKIHUB Log->print(F("Removing MQTT topic: ")); Log->println(path.c_str()); - #endif +#endif } @@ -3631,18 +3833,18 @@ void NukiNetwork::removeHASSConfigTopic(char *deviceType, char *name, char *uidS } JsonDocument NukiNetwork::createHassJson(const String& uidString, - const String& uidStringPostfix, - const String& displayName, - const String& name, - const String& baseTopic, - const String& stateTopic, - const String& deviceType, - const String& deviceClass, - const String& stateClass, - const String& entityCat, - const String& commandTopic, - std::vector> additionalEntries -) + const String& uidStringPostfix, + const String& displayName, + const String& name, + const String& baseTopic, + const String& stateTopic, + const String& deviceType, + const String& deviceClass, + const String& stateClass, + const String& entityCat, + const String& commandTopic, + std::vector> additionalEntries + ) { JsonDocument json; json.clear(); @@ -3702,190 +3904,196 @@ JsonDocument NukiNetwork::createHassJson(const String& uidString, return json; } -void NukiNetwork::batteryTypeToString(const Nuki::BatteryType battype, char* str) { - switch (battype) { +void NukiNetwork::batteryTypeToString(const Nuki::BatteryType battype, char* str) +{ + switch (battype) + { case Nuki::BatteryType::Alkali: - strcpy(str, "Alkali"); - break; + strcpy(str, "Alkali"); + break; case Nuki::BatteryType::Accumulators: - strcpy(str, "Accumulators"); - break; + strcpy(str, "Accumulators"); + break; case Nuki::BatteryType::Lithium: - strcpy(str, "Lithium"); - break; + strcpy(str, "Lithium"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetwork::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str) { - switch (advmode) { +void NukiNetwork::advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str) +{ + switch (advmode) + { case Nuki::AdvertisingMode::Automatic: - strcpy(str, "Automatic"); - break; + strcpy(str, "Automatic"); + break; case Nuki::AdvertisingMode::Normal: - strcpy(str, "Normal"); - break; + strcpy(str, "Normal"); + break; case Nuki::AdvertisingMode::Slow: - strcpy(str, "Slow"); - break; + strcpy(str, "Slow"); + break; case Nuki::AdvertisingMode::Slowest: - strcpy(str, "Slowest"); - break; + strcpy(str, "Slowest"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetwork::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) { - switch (timeZoneId) { +void NukiNetwork::timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str) +{ + switch (timeZoneId) + { case Nuki::TimeZoneId::Africa_Cairo: - strcpy(str, "Africa/Cairo"); - break; + strcpy(str, "Africa/Cairo"); + break; case Nuki::TimeZoneId::Africa_Lagos: - strcpy(str, "Africa/Lagos"); - break; + strcpy(str, "Africa/Lagos"); + break; case Nuki::TimeZoneId::Africa_Maputo: - strcpy(str, "Africa/Maputo"); - break; + strcpy(str, "Africa/Maputo"); + break; case Nuki::TimeZoneId::Africa_Nairobi: - strcpy(str, "Africa/Nairobi"); - break; + strcpy(str, "Africa/Nairobi"); + break; case Nuki::TimeZoneId::America_Anchorage: - strcpy(str, "America/Anchorage"); - break; + strcpy(str, "America/Anchorage"); + break; case Nuki::TimeZoneId::America_Argentina_Buenos_Aires: - strcpy(str, "America/Argentina/Buenos_Aires"); - break; + strcpy(str, "America/Argentina/Buenos_Aires"); + break; case Nuki::TimeZoneId::America_Chicago: - strcpy(str, "America/Chicago"); - break; + strcpy(str, "America/Chicago"); + break; case Nuki::TimeZoneId::America_Denver: - strcpy(str, "America/Denver"); - break; + strcpy(str, "America/Denver"); + break; case Nuki::TimeZoneId::America_Halifax: - strcpy(str, "America/Halifax"); - break; + strcpy(str, "America/Halifax"); + break; case Nuki::TimeZoneId::America_Los_Angeles: - strcpy(str, "America/Los_Angeles"); - break; + strcpy(str, "America/Los_Angeles"); + break; case Nuki::TimeZoneId::America_Manaus: - strcpy(str, "America/Manaus"); - break; + strcpy(str, "America/Manaus"); + break; case Nuki::TimeZoneId::America_Mexico_City: - strcpy(str, "America/Mexico_City"); - break; + strcpy(str, "America/Mexico_City"); + break; case Nuki::TimeZoneId::America_New_York: - strcpy(str, "America/New_York"); - break; + strcpy(str, "America/New_York"); + break; case Nuki::TimeZoneId::America_Phoenix: - strcpy(str, "America/Phoenix"); - break; + strcpy(str, "America/Phoenix"); + break; case Nuki::TimeZoneId::America_Regina: - strcpy(str, "America/Regina"); - break; + strcpy(str, "America/Regina"); + break; case Nuki::TimeZoneId::America_Santiago: - strcpy(str, "America/Santiago"); - break; + strcpy(str, "America/Santiago"); + break; case Nuki::TimeZoneId::America_Sao_Paulo: - strcpy(str, "America/Sao_Paulo"); - break; + strcpy(str, "America/Sao_Paulo"); + break; case Nuki::TimeZoneId::America_St_Johns: - strcpy(str, "America/St_Johns"); - break; + strcpy(str, "America/St_Johns"); + break; case Nuki::TimeZoneId::Asia_Bangkok: - strcpy(str, "Asia/Bangkok"); - break; + strcpy(str, "Asia/Bangkok"); + break; case Nuki::TimeZoneId::Asia_Dubai: - strcpy(str, "Asia/Dubai"); - break; + strcpy(str, "Asia/Dubai"); + break; case Nuki::TimeZoneId::Asia_Hong_Kong: - strcpy(str, "Asia/Hong_Kong"); - break; + strcpy(str, "Asia/Hong_Kong"); + break; case Nuki::TimeZoneId::Asia_Jerusalem: - strcpy(str, "Asia/Jerusalem"); - break; + strcpy(str, "Asia/Jerusalem"); + break; case Nuki::TimeZoneId::Asia_Karachi: - strcpy(str, "Asia/Karachi"); - break; + strcpy(str, "Asia/Karachi"); + break; case Nuki::TimeZoneId::Asia_Kathmandu: - strcpy(str, "Asia/Kathmandu"); - break; + strcpy(str, "Asia/Kathmandu"); + break; case Nuki::TimeZoneId::Asia_Kolkata: - strcpy(str, "Asia/Kolkata"); - break; + strcpy(str, "Asia/Kolkata"); + break; case Nuki::TimeZoneId::Asia_Riyadh: - strcpy(str, "Asia/Riyadh"); - break; + strcpy(str, "Asia/Riyadh"); + break; case Nuki::TimeZoneId::Asia_Seoul: - strcpy(str, "Asia/Seoul"); - break; + strcpy(str, "Asia/Seoul"); + break; case Nuki::TimeZoneId::Asia_Shanghai: - strcpy(str, "Asia/Shanghai"); - break; + strcpy(str, "Asia/Shanghai"); + break; case Nuki::TimeZoneId::Asia_Tehran: - strcpy(str, "Asia/Tehran"); - break; + strcpy(str, "Asia/Tehran"); + break; case Nuki::TimeZoneId::Asia_Tokyo: - strcpy(str, "Asia/Tokyo"); - break; + strcpy(str, "Asia/Tokyo"); + break; case Nuki::TimeZoneId::Asia_Yangon: - strcpy(str, "Asia/Yangon"); - break; + strcpy(str, "Asia/Yangon"); + break; case Nuki::TimeZoneId::Australia_Adelaide: - strcpy(str, "Australia/Adelaide"); - break; + strcpy(str, "Australia/Adelaide"); + break; case Nuki::TimeZoneId::Australia_Brisbane: - strcpy(str, "Australia/Brisbane"); - break; + strcpy(str, "Australia/Brisbane"); + break; case Nuki::TimeZoneId::Australia_Darwin: - strcpy(str, "Australia/Darwin"); - break; + strcpy(str, "Australia/Darwin"); + break; case Nuki::TimeZoneId::Australia_Hobart: - strcpy(str, "Australia/Hobart"); - break; + strcpy(str, "Australia/Hobart"); + break; case Nuki::TimeZoneId::Australia_Perth: - strcpy(str, "Australia/Perth"); - break; + strcpy(str, "Australia/Perth"); + break; case Nuki::TimeZoneId::Australia_Sydney: - strcpy(str, "Australia/Sydney"); - break; + strcpy(str, "Australia/Sydney"); + break; case Nuki::TimeZoneId::Europe_Berlin: - strcpy(str, "Europe/Berlin"); - break; + strcpy(str, "Europe/Berlin"); + break; case Nuki::TimeZoneId::Europe_Helsinki: - strcpy(str, "Europe/Helsinki"); - break; + strcpy(str, "Europe/Helsinki"); + break; case Nuki::TimeZoneId::Europe_Istanbul: - strcpy(str, "Europe/Istanbul"); - break; + strcpy(str, "Europe/Istanbul"); + break; case Nuki::TimeZoneId::Europe_London: - strcpy(str, "Europe/London"); - break; + strcpy(str, "Europe/London"); + break; case Nuki::TimeZoneId::Europe_Moscow: - strcpy(str, "Europe/Moscow"); - break; + strcpy(str, "Europe/Moscow"); + break; case Nuki::TimeZoneId::Pacific_Auckland: - strcpy(str, "Pacific/Auckland"); - break; + strcpy(str, "Pacific/Auckland"); + break; case Nuki::TimeZoneId::Pacific_Guam: - strcpy(str, "Pacific/Guam"); - break; + strcpy(str, "Pacific/Guam"); + break; case Nuki::TimeZoneId::Pacific_Honolulu: - strcpy(str, "Pacific/Honolulu"); - break; + strcpy(str, "Pacific/Honolulu"); + break; case Nuki::TimeZoneId::Pacific_Pago_Pago: - strcpy(str, "Pacific/Pago_Pago"); - break; + strcpy(str, "Pacific/Pago_Pago"); + break; case Nuki::TimeZoneId::None: - strcpy(str, "None"); - break; + strcpy(str, "None"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } uint16_t NukiNetwork::subscribe(const char *topic, uint8_t qos) diff --git a/src/NukiNetworkLock.cpp b/src/NukiNetworkLock.cpp index 9a65f18..4397650 100644 --- a/src/NukiNetworkLock.cpp +++ b/src/NukiNetworkLock.cpp @@ -15,11 +15,11 @@ extern const uint8_t x509_crt_imported_bundle_bin_start[] asm("_binary_x509_crt_ extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_bundle_end"); NukiNetworkLock::NukiNetworkLock(NukiNetwork* network, NukiOfficial* nukiOfficial, Preferences* preferences, char* buffer, size_t bufferSize) -: _network(network), - _nukiOfficial(nukiOfficial), - _preferences(preferences), - _buffer(buffer), - _bufferSize(bufferSize) + : _network(network), + _nukiOfficial(nukiOfficial), + _preferences(preferences), + _buffer(buffer), + _bufferSize(bufferSize) { _nukiPublisher = new NukiPublisher(network, _mqttPath); _nukiOfficial->setPublisher(_nukiPublisher); @@ -201,21 +201,26 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, JsonDocument doc; NetworkClientSecure *client = new NetworkClientSecure; - if (client) { + if (client) + { client->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); { HTTPClient https; https.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); https.useHTTP10(true); - if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) { + if (https.begin(*client, GITHUB_OTA_MANIFEST_URL)) + { int httpResponseCode = https.GET(); if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_MOVED_PERMANENTLY) { DeserializationError jsonError = deserializeJson(doc, https.getStream()); - if (!jsonError) { otaManifestSuccess = true; } + if (!jsonError) + { + otaManifestSuccess = true; + } } } https.end(); @@ -296,18 +301,27 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, else if(comparePrefixedPath(topic, mqtt_topic_webserver_action)) { if(strcmp(data, "") == 0 || - strcmp(data, "--") == 0) return; + strcmp(data, "--") == 0) + { + return; + } if(strcmp(data, "1") == 0) { - if(_preferences->getBool(preference_webserver_enabled, true) || forceEnableWebServer) return; + if(_preferences->getBool(preference_webserver_enabled, true) || forceEnableWebServer) + { + return; + } Log->println(F("Webserver enabled, restarting.")); _preferences->putBool(preference_webserver_enabled, true); } else if (strcmp(data, "0") == 0) { - if(!_preferences->getBool(preference_webserver_enabled, true) && !forceEnableWebServer) return; + if(!_preferences->getBool(preference_webserver_enabled, true) && !forceEnableWebServer) + { + return; + } Log->println(F("Webserver disabled, restarting.")); _preferences->putBool(preference_webserver_enabled, false); } @@ -320,9 +334,15 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, else if(comparePrefixedPath(topic, mqtt_topic_lock_log_rolling_last)) { if(strcmp(data, "") == 0 || - strcmp(data, "--") == 0) return; + strcmp(data, "--") == 0) + { + return; + } - if(atoi(data) > 0 && atoi(data) > _lastRollingLog) _lastRollingLog = atoi(data); + if(atoi(data) > 0 && atoi(data) > _lastRollingLog) + { + _lastRollingLog = atoi(data); + } } if(_nukiOfficial->getOffEnabled()) @@ -342,11 +362,14 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, if(comparePrefixedPath(topic, mqtt_topic_lock_action)) { if(strcmp(data, "") == 0 || - strcmp(data, "--") == 0 || - strcmp(data, "ack") == 0 || - strcmp(data, "unknown_action") == 0 || - strcmp(data, "denied") == 0 || - strcmp(data, "error") == 0) return; + strcmp(data, "--") == 0 || + strcmp(data, "ack") == 0 || + strcmp(data, "unknown_action") == 0 || + strcmp(data, "denied") == 0 || + strcmp(data, "error") == 0) + { + return; + } Log->print(F("Lock action received: ")); Log->println(data); @@ -358,18 +381,18 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, switch(lockActionResult) { - case LockActionResult::Success: - publishString(mqtt_topic_lock_action, "ack", false); - break; - case LockActionResult::UnknownAction: - publishString(mqtt_topic_lock_action, "unknown_action", false); - break; - case LockActionResult::AccessDenied: - publishString(mqtt_topic_lock_action, "denied", false); - break; - case LockActionResult::Failed: - publishString(mqtt_topic_lock_action, "error", false); - break; + case LockActionResult::Success: + publishString(mqtt_topic_lock_action, "ack", false); + break; + case LockActionResult::UnknownAction: + publishString(mqtt_topic_lock_action, "unknown_action", false); + break; + case LockActionResult::AccessDenied: + publishString(mqtt_topic_lock_action, "denied", false); + break; + case LockActionResult::Failed: + publishString(mqtt_topic_lock_action, "error", false); + break; } } @@ -379,7 +402,10 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, { if(_keypadCommandReceivedReceivedCallback != nullptr) { - if(strcmp(data, "--") == 0) return; + if(strcmp(data, "--") == 0) + { + return; + } _keypadCommandReceivedReceivedCallback(data, _keypadCommandId, _keypadCommandName, _keypadCommandCode, _keypadCommandEnabled); @@ -439,7 +465,10 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, if(comparePrefixedPath(topic, mqtt_topic_config_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_configUpdateReceivedCallback != NULL) { @@ -451,7 +480,10 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, if(comparePrefixedPath(topic, mqtt_topic_keypad_json_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_keypadJsonCommandReceivedReceivedCallback != NULL) { @@ -463,7 +495,10 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, if(comparePrefixedPath(topic, mqtt_topic_timecontrol_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_timeControlCommandReceivedReceivedCallback != NULL) { @@ -475,7 +510,10 @@ void NukiNetworkLock::onMqttDataReceived(char* topic, int topic_len, char* data, if(comparePrefixedPath(topic, mqtt_topic_auth_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_authCommandReceivedReceivedCallback != NULL) { @@ -633,39 +671,39 @@ void NukiNetworkLock::publishState(NukiLock::LockState lockState) { switch(lockState) { - case NukiLock::LockState::Locked: - publishString(mqtt_topic_lock_ha_state, "locked", true); - publishString(mqtt_topic_lock_binary_state, "locked", true); - break; - case NukiLock::LockState::Locking: - publishString(mqtt_topic_lock_ha_state, "locking", true); - publishString(mqtt_topic_lock_binary_state, "locked", true); - break; - case NukiLock::LockState::Unlocking: - publishString(mqtt_topic_lock_ha_state, "unlocking", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiLock::LockState::Unlocked: - case NukiLock::LockState::UnlockedLnga: - publishString(mqtt_topic_lock_ha_state, "unlocked", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiLock::LockState::Unlatched: - publishString(mqtt_topic_lock_ha_state, "open", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiLock::LockState::Unlatching: - publishString(mqtt_topic_lock_ha_state, "opening", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiLock::LockState::Uncalibrated: - case NukiLock::LockState::Calibration: - case NukiLock::LockState::BootRun: - case NukiLock::LockState::MotorBlocked: - publishString(mqtt_topic_lock_ha_state, "jammed", true); - break; - default: - break; + case NukiLock::LockState::Locked: + publishString(mqtt_topic_lock_ha_state, "locked", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); + break; + case NukiLock::LockState::Locking: + publishString(mqtt_topic_lock_ha_state, "locking", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); + break; + case NukiLock::LockState::Unlocking: + publishString(mqtt_topic_lock_ha_state, "unlocking", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiLock::LockState::Unlocked: + case NukiLock::LockState::UnlockedLnga: + publishString(mqtt_topic_lock_ha_state, "unlocked", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiLock::LockState::Unlatched: + publishString(mqtt_topic_lock_ha_state, "open", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiLock::LockState::Unlatching: + publishString(mqtt_topic_lock_ha_state, "opening", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiLock::LockState::Uncalibrated: + case NukiLock::LockState::Calibration: + case NukiLock::LockState::BootRun: + case NukiLock::LockState::MotorBlocked: + publishString(mqtt_topic_lock_ha_state, "jammed", true); + break; + default: + break; } } @@ -686,7 +724,10 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list authIndex) { @@ -712,7 +753,7 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list().length() == 0 && _authEntries.count(log.authId) > 0) { - entry["authorizationName"] = _authEntries[log.authId]; + entry["authorizationName"] = _authEntries[log.authId]; } entry["timeYear"] = log.timeStampYear; @@ -728,69 +769,75 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list _lastRollingLog) @@ -804,8 +851,14 @@ void NukiNetworkLock::publishAuthorizationInfo(const std::list 0) { @@ -1013,7 +1066,10 @@ void NukiNetworkLock::publishKeypad(const std::list& entr jsonEntry["codeId"] = entry.codeId; - if(publishCode) jsonEntry["code"] = entry.code; + if(publishCode) + { + jsonEntry["code"] = entry.code; + } jsonEntry["enabled"] = entry.enabled; jsonEntry["name"] = entry.name; char createdDT[20]; @@ -1034,7 +1090,8 @@ void NukiNetworkLock::publishKeypad(const std::list& entr uint8_t allowedWeekdaysInt = entry.allowedWeekdays; JsonArray weekdays = jsonEntry["allowedWeekdays"].to(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -1111,24 +1168,26 @@ void NukiNetworkLock::publishKeypad(const std::list& entr std::string displayName = std::string("Keypad - ") + std::string((char*)codeName) + " - " + std::to_string(entry.codeId); _network->publishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_keypad_json_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_keypad_json_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1202,7 +1261,10 @@ void NukiNetworkLock::publishKeypad(const std::list& entr void NukiNetworkLock::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } char codeName[sizeof(entry.name) + 1]; memset(codeName, 0, sizeof(codeName)); @@ -1245,7 +1307,8 @@ void NukiNetworkLock::publishTimeControl(const std::list(); - while(weekdaysInt > 0) { + while(weekdaysInt > 0) + { if(weekdaysInt >= 64) { weekdays.add("mon"); @@ -1319,24 +1382,26 @@ void NukiNetworkLock::publishTimeControl(const std::listpublishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_timecontrol_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_timecontrol_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1393,7 +1458,8 @@ void NukiNetworkLock::publishAuth(const std::list& uint8_t allowedWeekdaysInt = entry.allowedWeekdays; JsonArray weekdays = jsonEntry["allowedWeekdays"].to(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -1466,24 +1532,26 @@ void NukiNetworkLock::publishAuth(const std::list& std::string displayName = std::string("Authorization - ") + std::to_string(entry.authId); _network->publishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_auth_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_auth_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1510,7 +1578,10 @@ void NukiNetworkLock::publishConfigCommandResult(const char* result) void NukiNetworkLock::publishKeypadCommandResult(const char* result) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } publishString(mqtt_topic_keypad_command_result, result, true); } @@ -1551,7 +1622,10 @@ void NukiNetworkLock::setConfigUpdateReceivedCallback(void (*configUpdateReceive void NukiNetworkLock::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } _keypadCommandReceivedReceivedCallback = keypadCommandReceivedReceivedCallback; } @@ -1604,7 +1678,7 @@ bool NukiNetworkLock::comparePrefixedPath(const char *fullPath, const char *subP } void NukiNetworkLock::publishHASSConfig(char *deviceType, const char *baseTopic, char *name, char *uidString, const char *softwareVersion, const char *hardwareVersion, const bool& hasDoorSensor, const bool& hasKeypad, const bool& publishAuthData, char *lockAction, - char *unlockAction, char *openAction) + char *unlockAction, char *openAction) { _network->publishHASSConfig(deviceType, baseTopic, name, uidString, softwareVersion, hardwareVersion, "~/maintenance/mqttConnectionState", hasKeypad, lockAction, unlockAction, openAction); _network->publishHASSConfigAdditionalLockEntities(deviceType, baseTopic, name, uidString); @@ -1618,9 +1692,9 @@ void NukiNetworkLock::publishHASSConfig(char *deviceType, const char *baseTopic, _network->removeHASSConfigTopic((char*)"binary_sensor", (char*)"door_sensor", uidString); } - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 _network->publishHASSWifiRssiConfig(deviceType, baseTopic, name, uidString); - #endif +#endif if(publishAuthData) { @@ -1719,76 +1793,82 @@ uint8_t NukiNetworkLock::queryCommands() return qc; } -void NukiNetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str) { - switch (btnPressAction) { +void NukiNetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str) +{ + switch (btnPressAction) + { case NukiLock::ButtonPressAction::NoAction: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case NukiLock::ButtonPressAction::Intelligent: - strcpy(str, "Intelligent"); - break; + strcpy(str, "Intelligent"); + break; case NukiLock::ButtonPressAction::Unlock: - strcpy(str, "Unlock"); - break; + strcpy(str, "Unlock"); + break; case NukiLock::ButtonPressAction::Lock: - strcpy(str, "Lock"); - break; + strcpy(str, "Lock"); + break; case NukiLock::ButtonPressAction::Unlatch: - strcpy(str, "Unlatch"); - break; + strcpy(str, "Unlatch"); + break; case NukiLock::ButtonPressAction::LockNgo: - strcpy(str, "Lock n Go"); - break; + strcpy(str, "Lock n Go"); + break; case NukiLock::ButtonPressAction::ShowStatus: - strcpy(str, "Show Status"); - break; + strcpy(str, "Show Status"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkLock::homeKitStatusToString(const int hkstatus, char* str) { - switch (hkstatus) { +void NukiNetworkLock::homeKitStatusToString(const int hkstatus, char* str) +{ + switch (hkstatus) + { case 0: - strcpy(str, "Not Available"); - break; + strcpy(str, "Not Available"); + break; case 1: - strcpy(str, "Disabled"); - break; + strcpy(str, "Disabled"); + break; case 2: - strcpy(str, "Enabled"); - break; + strcpy(str, "Enabled"); + break; case 3: - strcpy(str, "Enabled & Paired"); - break; + strcpy(str, "Enabled & Paired"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkLock::fobActionToString(const int fobact, char* str) { - switch (fobact) { +void NukiNetworkLock::fobActionToString(const int fobact, char* str) +{ + switch (fobact) + { case 0: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case 1: - strcpy(str, "Unlock"); - break; + strcpy(str, "Unlock"); + break; case 2: - strcpy(str, "Lock"); - break; + strcpy(str, "Lock"); + break; case 3: - strcpy(str, "Lock n Go"); - break; + strcpy(str, "Lock n Go"); + break; case 4: - strcpy(str, "Intelligent"); - break; + strcpy(str, "Intelligent"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } const uint32_t NukiNetworkLock::getAuthId() const diff --git a/src/NukiNetworkOpener.cpp b/src/NukiNetworkOpener.cpp index 537d281..1d34d46 100644 --- a/src/NukiNetworkOpener.cpp +++ b/src/NukiNetworkOpener.cpp @@ -7,10 +7,10 @@ #include NukiNetworkOpener::NukiNetworkOpener(NukiNetwork* network, Preferences* preferences, char* buffer, size_t bufferSize) - : _preferences(preferences), - _network(network), - _buffer(buffer), - _bufferSize(bufferSize) + : _preferences(preferences), + _network(network), + _buffer(buffer), + _bufferSize(bufferSize) { _nukiPublisher = new NukiPublisher(network, _mqttPath); @@ -124,9 +124,9 @@ void NukiNetworkOpener::initialize() } _network->addReconnectedCallback([&]() - { - _reconnected = true; - }); + { + _reconnected = true; + }); } void NukiNetworkOpener::update() @@ -149,19 +149,28 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat if(comparePrefixedPath(topic, mqtt_topic_lock_log_rolling_last)) { if(strcmp(data, "") == 0 || - strcmp(data, "--") == 0) return; + strcmp(data, "--") == 0) + { + return; + } - if(atoi(data) > 0 && atoi(data) > _lastRollingLog) _lastRollingLog = atoi(data); + if(atoi(data) > 0 && atoi(data) > _lastRollingLog) + { + _lastRollingLog = atoi(data); + } } if(comparePrefixedPath(topic, mqtt_topic_lock_action)) { if(strcmp(data, "") == 0 || - strcmp(data, "--") == 0 || - strcmp(data, "ack") == 0 || - strcmp(data, "unknown_action") == 0 || - strcmp(data, "denied") == 0 || - strcmp(data, "error") == 0) return; + strcmp(data, "--") == 0 || + strcmp(data, "ack") == 0 || + strcmp(data, "unknown_action") == 0 || + strcmp(data, "denied") == 0 || + strcmp(data, "error") == 0) + { + return; + } Log->print(F("Opener action received: ")); Log->println(data); @@ -173,18 +182,18 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat switch(lockActionResult) { - case LockActionResult::Success: - publishString(mqtt_topic_lock_action, "ack", false); - break; - case LockActionResult::UnknownAction: - publishString(mqtt_topic_lock_action, "unknown_action", false); - break; - case LockActionResult::AccessDenied: - publishString(mqtt_topic_lock_action, "denied", false); - break; - case LockActionResult::Failed: - publishString(mqtt_topic_lock_action, "error", false); - break; + case LockActionResult::Success: + publishString(mqtt_topic_lock_action, "ack", false); + break; + case LockActionResult::UnknownAction: + publishString(mqtt_topic_lock_action, "unknown_action", false); + break; + case LockActionResult::AccessDenied: + publishString(mqtt_topic_lock_action, "denied", false); + break; + case LockActionResult::Failed: + publishString(mqtt_topic_lock_action, "error", false); + break; } } @@ -194,7 +203,10 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat { if(_keypadCommandReceivedReceivedCallback != nullptr) { - if(strcmp(data, "--") == 0) return; + if(strcmp(data, "--") == 0) + { + return; + } _keypadCommandReceivedReceivedCallback(data, _keypadCommandId, _keypadCommandName, _keypadCommandCode, _keypadCommandEnabled); @@ -254,7 +266,10 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat if(comparePrefixedPath(topic, mqtt_topic_config_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_configUpdateReceivedCallback != NULL) { @@ -266,7 +281,10 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat if(comparePrefixedPath(topic, mqtt_topic_keypad_json_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_keypadJsonCommandReceivedReceivedCallback != NULL) { @@ -278,7 +296,10 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat if(comparePrefixedPath(topic, mqtt_topic_timecontrol_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_timeControlCommandReceivedReceivedCallback != NULL) { @@ -290,7 +311,10 @@ void NukiNetworkOpener::onMqttDataReceived(char* topic, int topic_len, char* dat if(comparePrefixedPath(topic, mqtt_topic_auth_action)) { - if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) return; + if(strcmp(data, "") == 0 || strcmp(data, "--") == 0) + { + return; + } if(_authCommandReceivedReceivedCallback != NULL) { @@ -329,7 +353,9 @@ void NukiNetworkOpener::publishKeyTurnerState(const NukiOpener::OpenerState& key { publishString(mqtt_topic_lock_continuous_mode, "on", true); json["continuous_mode"] = 1; - } else { + } + else + { publishString(mqtt_topic_lock_continuous_mode, "off", true); json["continuous_mode"] = 0; } @@ -429,28 +455,28 @@ void NukiNetworkOpener::publishState(NukiOpener::OpenerState lockState) { switch (lockState.lockState) { - case NukiOpener::LockState::Locked: - publishString(mqtt_topic_lock_ha_state, "locked", true); - publishString(mqtt_topic_lock_binary_state, "locked", true); - break; - case NukiOpener::LockState::RTOactive: - publishString(mqtt_topic_lock_ha_state, "unlocked", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiOpener::LockState::Open: - publishString(mqtt_topic_lock_ha_state, "open", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiOpener::LockState::Opening: - publishString(mqtt_topic_lock_ha_state, "opening", true); - publishString(mqtt_topic_lock_binary_state, "unlocked", true); - break; - case NukiOpener::LockState::Undefined: - case NukiOpener::LockState::Uncalibrated: - publishString(mqtt_topic_lock_ha_state, "jammed", true); - break; - default: - break; + case NukiOpener::LockState::Locked: + publishString(mqtt_topic_lock_ha_state, "locked", true); + publishString(mqtt_topic_lock_binary_state, "locked", true); + break; + case NukiOpener::LockState::RTOactive: + publishString(mqtt_topic_lock_ha_state, "unlocked", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiOpener::LockState::Open: + publishString(mqtt_topic_lock_ha_state, "open", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiOpener::LockState::Opening: + publishString(mqtt_topic_lock_ha_state, "opening", true); + publishString(mqtt_topic_lock_binary_state, "unlocked", true); + break; + case NukiOpener::LockState::Undefined: + case NukiOpener::LockState::Uncalibrated: + publishString(mqtt_topic_lock_ha_state, "jammed", true); + break; + default: + break; } } } @@ -472,7 +498,10 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list authIndex) { @@ -481,7 +510,7 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list 0) { memset(_authName, 0, sizeof(_authName)); @@ -495,12 +524,12 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list().length() == 0 && _authEntries.count(log.authId) > 0) { - entry["authorizationName"] = _authEntries[log.authId]; + entry["authorizationName"] = _authEntries[log.authId]; } - + entry["timeYear"] = log.timeStampYear; entry["timeMonth"] = log.timeStampMonth; entry["timeDay"] = log.timeStampDay; @@ -514,104 +543,111 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list _lastRollingLog) @@ -625,8 +661,14 @@ void NukiNetworkOpener::publishAuthorizationInfo(const std::list 0) { @@ -858,7 +900,10 @@ void NukiNetworkOpener::publishKeypad(const std::list& en jsonEntry["codeId"] = entry.codeId; - if(publishCode) jsonEntry["code"] = entry.code; + if(publishCode) + { + jsonEntry["code"] = entry.code; + } jsonEntry["enabled"] = entry.enabled; jsonEntry["name"] = entry.name; char createdDT[20]; @@ -879,7 +924,8 @@ void NukiNetworkOpener::publishKeypad(const std::list& en uint8_t allowedWeekdaysInt = entry.allowedWeekdays; JsonArray weekdays = jsonEntry["allowedWeekdays"].to(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -956,24 +1002,26 @@ void NukiNetworkOpener::publishKeypad(const std::list& en std::string displayName = std::string("Keypad - ") + std::string((char*)codeName) + " - " + std::to_string(entry.codeId); _network->publishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"SmartLock", - "", - "", - "diagnostic", - String("~") + mqtt_topic_keypad_json_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"SmartLock", + "", + "", + "diagnostic", + String("~") + mqtt_topic_keypad_json_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1062,7 +1110,8 @@ void NukiNetworkOpener::publishTimeControl(const std::list(); - while(weekdaysInt > 0) { + while(weekdaysInt > 0) + { if(weekdaysInt >= 64) { weekdays.add("mon"); @@ -1134,24 +1183,26 @@ void NukiNetworkOpener::publishTimeControl(const std::listpublishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"Opener", - "", - "", - "diagnostic", - String("~") + mqtt_topic_timecontrol_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"Opener", + "", + "", + "diagnostic", + String("~") + mqtt_topic_timecontrol_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1208,7 +1259,8 @@ void NukiNetworkOpener::publishAuth(const std::list(); - while(allowedWeekdaysInt > 0) { + while(allowedWeekdaysInt > 0) + { if(allowedWeekdaysInt >= 64) { weekdays.add("mon"); @@ -1281,24 +1333,26 @@ void NukiNetworkOpener::publishAuth(const std::listpublishHassTopic("switch", - mqttDeviceName.c_str(), - uidString, - uidStringPostfix.c_str(), - displayName.c_str(), - _nukiName, - baseTopic.c_str(), - String("~") + basePath.c_str(), - (char*)"Opener", - "", - "", - "diagnostic", - String("~") + mqtt_topic_auth_action, - { { (char*)"json_attr_t", (char*)basePathPrefixChr }, - { (char*)"pl_on", (char*)enaCommand.c_str() }, - { (char*)"pl_off", (char*)disCommand.c_str() }, - { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, - { (char*)"stat_on", (char*)"1" }, - { (char*)"stat_off", (char*)"0" }}); + mqttDeviceName.c_str(), + uidString, + uidStringPostfix.c_str(), + displayName.c_str(), + _nukiName, + baseTopic.c_str(), + String("~") + basePath.c_str(), + (char*)"Opener", + "", + "", + "diagnostic", + String("~") + mqtt_topic_auth_action, + { + { (char*)"json_attr_t", (char*)basePathPrefixChr }, + { (char*)"pl_on", (char*)enaCommand.c_str() }, + { (char*)"pl_off", (char*)disCommand.c_str() }, + { (char*)"val_tpl", (char*)"{{value_json.enabled}}" }, + { (char*)"stat_on", (char*)"1" }, + { (char*)"stat_off", (char*)"0" } + }); } ++index; @@ -1325,7 +1379,10 @@ void NukiNetworkOpener::publishConfigCommandResult(const char* result) void NukiNetworkOpener::publishKeypadCommandResult(const char* result) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } publishString(mqtt_topic_keypad_command_result, result, true); } @@ -1361,7 +1418,10 @@ void NukiNetworkOpener::setConfigUpdateReceivedCallback(void (*configUpdateRecei void NukiNetworkOpener::setKeypadCommandReceivedCallback(void (*keypadCommandReceivedReceivedCallback)(const char* command, const uint& id, const String& name, const String& code, const int& enabled)) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } _keypadCommandReceivedReceivedCallback = keypadCommandReceivedReceivedCallback; } @@ -1423,7 +1483,10 @@ void NukiNetworkOpener::publishString(const char* topic, const char* value, bool void NukiNetworkOpener::publishKeypadEntry(const String topic, NukiLock::KeypadEntry entry) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } char codeName[sizeof(entry.name) + 1]; memset(codeName, 0, sizeof(codeName)); @@ -1505,185 +1568,197 @@ uint8_t NukiNetworkOpener::queryCommands() return qc; } -void NukiNetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str) { - switch (btnPressAction) { +void NukiNetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str) +{ + switch (btnPressAction) + { case NukiOpener::ButtonPressAction::NoAction: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case NukiOpener::ButtonPressAction::ToggleRTO: - strcpy(str, "Toggle RTO"); - break; + strcpy(str, "Toggle RTO"); + break; case NukiOpener::ButtonPressAction::ActivateRTO: - strcpy(str, "Activate RTO"); - break; + strcpy(str, "Activate RTO"); + break; case NukiOpener::ButtonPressAction::DeactivateRTO: - strcpy(str, "Deactivate RTO"); - break; + strcpy(str, "Deactivate RTO"); + break; case NukiOpener::ButtonPressAction::ToggleCM: - strcpy(str, "Toggle CM"); - break; + strcpy(str, "Toggle CM"); + break; case NukiOpener::ButtonPressAction::ActivateCM: - strcpy(str, "Activate CM"); - break; + strcpy(str, "Activate CM"); + break; case NukiOpener::ButtonPressAction::DectivateCM: - strcpy(str, "Deactivate CM"); - break; + strcpy(str, "Deactivate CM"); + break; case NukiOpener::ButtonPressAction::Open: - strcpy(str, "Open"); - break; + strcpy(str, "Open"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::fobActionToString(const int fobact, char* str) { - switch (fobact) { +void NukiNetworkOpener::fobActionToString(const int fobact, char* str) +{ + switch (fobact) + { case 0: - strcpy(str, "No Action"); - break; + strcpy(str, "No Action"); + break; case 1: - strcpy(str, "Toggle RTO"); - break; + strcpy(str, "Toggle RTO"); + break; case 2: - strcpy(str, "Activate RTO"); - break; + strcpy(str, "Activate RTO"); + break; case 3: - strcpy(str, "Deactivate RTO"); - break; + strcpy(str, "Deactivate RTO"); + break; case 7: - strcpy(str, "Open"); - break; + strcpy(str, "Open"); + break; case 8: - strcpy(str, "Ring"); - break; + strcpy(str, "Ring"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::capabilitiesToString(const int capabilities, char* str) { - switch (capabilities) { +void NukiNetworkOpener::capabilitiesToString(const int capabilities, char* str) +{ + switch (capabilities) + { case 0: - strcpy(str, "Door opener"); - break; + strcpy(str, "Door opener"); + break; case 1: - strcpy(str, "Both"); - break; + strcpy(str, "Both"); + break; case 2: - strcpy(str, "RTO"); - break; + strcpy(str, "RTO"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::operatingModeToString(const int opmode, char* str) { - switch (opmode) { +void NukiNetworkOpener::operatingModeToString(const int opmode, char* str) +{ + switch (opmode) + { case 0: - strcpy(str, "Generic door opener"); - break; + strcpy(str, "Generic door opener"); + break; case 1: - strcpy(str, "Analogue intercom"); - break; + strcpy(str, "Analogue intercom"); + break; case 2: - strcpy(str, "Digital intercom"); - break; + strcpy(str, "Digital intercom"); + break; case 3: - strcpy(str, "Siedle"); - break; + strcpy(str, "Siedle"); + break; case 4: - strcpy(str, "TCS"); - break; + strcpy(str, "TCS"); + break; case 5: - strcpy(str, "Bticino"); - break; + strcpy(str, "Bticino"); + break; case 6: - strcpy(str, "Siedle HTS"); - break; + strcpy(str, "Siedle HTS"); + break; case 7: - strcpy(str, "STR"); - break; + strcpy(str, "STR"); + break; case 8: - strcpy(str, "Ritto"); - break; + strcpy(str, "Ritto"); + break; case 9: - strcpy(str, "Fermax"); - break; + strcpy(str, "Fermax"); + break; case 10: - strcpy(str, "Comelit"); - break; + strcpy(str, "Comelit"); + break; case 11: - strcpy(str, "Urmet BiBus"); - break; + strcpy(str, "Urmet BiBus"); + break; case 12: - strcpy(str, "Urmet 2Voice"); - break; + strcpy(str, "Urmet 2Voice"); + break; case 13: - strcpy(str, "Golmar"); - break; + strcpy(str, "Golmar"); + break; case 14: - strcpy(str, "SKS"); - break; + strcpy(str, "SKS"); + break; case 15: - strcpy(str, "Spare"); - break; + strcpy(str, "Spare"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) { - switch (dbsupr) { +void NukiNetworkOpener::doorbellSuppressionToString(const int dbsupr, char* str) +{ + switch (dbsupr) + { case 0: - strcpy(str, "Off"); - break; + strcpy(str, "Off"); + break; case 1: - strcpy(str, "CM"); - break; + strcpy(str, "CM"); + break; case 2: - strcpy(str, "RTO"); - break; + strcpy(str, "RTO"); + break; case 3: - strcpy(str, "CM & RTO"); - break; + strcpy(str, "CM & RTO"); + break; case 4: - strcpy(str, "Ring"); - break; + strcpy(str, "Ring"); + break; case 5: - strcpy(str, "CM & Ring"); - break; + strcpy(str, "CM & Ring"); + break; case 6: - strcpy(str, "RTO & Ring"); - break; + strcpy(str, "RTO & Ring"); + break; case 7: - strcpy(str, "CM & RTO & Ring"); - break; + strcpy(str, "CM & RTO & Ring"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } -void NukiNetworkOpener::soundToString(const int sound, char* str) { - switch (sound) { +void NukiNetworkOpener::soundToString(const int sound, char* str) +{ + switch (sound) + { case 0: - strcpy(str, "No Sound"); - break; + strcpy(str, "No Sound"); + break; case 1: - strcpy(str, "Sound 1"); - break; + strcpy(str, "Sound 1"); + break; case 2: - strcpy(str, "Sound 2"); - break; + strcpy(str, "Sound 2"); + break; case 3: - strcpy(str, "Sound 3"); - break; + strcpy(str, "Sound 3"); + break; default: - strcpy(str, "undefined"); - break; - } + strcpy(str, "undefined"); + break; + } } diff --git a/src/NukiOfficial.cpp b/src/NukiOfficial.cpp index 9eaef7d..af10b63 100644 --- a/src/NukiOfficial.cpp +++ b/src/NukiOfficial.cpp @@ -136,7 +136,10 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value Log->print(F("Battery critical: ")); Log->println(offCritical); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_critical, offCritical, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_critical, offCritical, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_batteryCharging) == 0) @@ -146,7 +149,10 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value Log->print(F("Battery charging: ")); Log->println(offCharging); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_charging, offCharging, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_charging, offCharging, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_batteryChargeState) == 0) @@ -156,19 +162,28 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value Log->print(F("Battery level: ")); Log->println(offChargeState); - if(!_disableNonJSON) _publisher->publishInt(mqtt_topic_battery_level, offChargeState, true); + if(!_disableNonJSON) + { + _publisher->publishInt(mqtt_topic_battery_level, offChargeState, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_keypadBatteryCritical) == 0) { offKeypadCritical = (strcmp(value, "true") == 0 ? 1 : 0); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_keypad_critical, offKeypadCritical, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_keypad_critical, offKeypadCritical, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_doorsensorBatteryCritical) == 0) { offDoorsensorCritical = (strcmp(value, "true") == 0 ? 1 : 0); - if(!_disableNonJSON) _publisher->publishBool(mqtt_topic_battery_doorsensor_critical, offDoorsensorCritical, true); + if(!_disableNonJSON) + { + _publisher->publishBool(mqtt_topic_battery_doorsensor_critical, offDoorsensorCritical, true); + } publishBatteryJson = true; } else if(strcmp(topic, mqtt_topic_official_commandResponse) == 0) diff --git a/src/NukiOpenerWrapper.cpp b/src/NukiOpenerWrapper.cpp index c78e0ed..69ee1ae 100644 --- a/src/NukiOpenerWrapper.cpp +++ b/src/NukiOpenerWrapper.cpp @@ -10,13 +10,13 @@ NukiOpenerWrapper* nukiOpenerInst; Preferences* nukiOpenerPreferences = nullptr; NukiOpenerWrapper::NukiOpenerWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkOpener* network, Gpio* gpio, Preferences* preferences) -: _deviceName(deviceName), - _deviceId(deviceId), - _nukiOpener(deviceName, _deviceId->get()), - _bleScanner(scanner), - _network(network), - _gpio(gpio), - _preferences(preferences) + : _deviceName(deviceName), + _deviceId(deviceId), + _nukiOpener(deviceName, _deviceId->get()), + _bleScanner(scanner), + _network(network), + _gpio(gpio), + _preferences(preferences) { Log->print("Device id opener: "); Log->println(_deviceId->get()); @@ -64,14 +64,38 @@ void NukiOpenerWrapper::readSettings() int pwrLvl = _preferences->getInt(preference_ble_tx_power, 9); - if(pwrLvl >= 9) powerLevel = ESP_PWR_LVL_P9; - else if(pwrLvl >= 6) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 3) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 0) powerLevel = ESP_PWR_LVL_P3; - else if(pwrLvl >= -3) powerLevel = ESP_PWR_LVL_N3; - else if(pwrLvl >= -6) powerLevel = ESP_PWR_LVL_N6; - else if(pwrLvl >= -9) powerLevel = ESP_PWR_LVL_N9; - else if(pwrLvl >= -12) powerLevel = ESP_PWR_LVL_N12; + if(pwrLvl >= 9) + { + powerLevel = ESP_PWR_LVL_P9; + } + else if(pwrLvl >= 6) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 3) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 0) + { + powerLevel = ESP_PWR_LVL_P3; + } + else if(pwrLvl >= -3) + { + powerLevel = ESP_PWR_LVL_N3; + } + else if(pwrLvl >= -6) + { + powerLevel = ESP_PWR_LVL_N6; + } + else if(pwrLvl >= -9) + { + powerLevel = ESP_PWR_LVL_N9; + } + else if(pwrLvl >= -12) + { + powerLevel = ESP_PWR_LVL_N12; + } _nukiOpener.setPower(powerLevel); @@ -177,10 +201,10 @@ void NukiOpenerWrapper::update() uint8_t queryCommands = _network->queryCommands(); if(_restartBeaconTimeout > 0 && - ts > 60000 && - lastReceivedBeaconTs > 0 && - _disableBleWatchdogTs < ts && - (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) + ts > 60000 && + lastReceivedBeaconTs > 0 && + _disableBleWatchdogTs < ts && + (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) { Log->print("No BLE beacon received from the opener for "); Log->print((ts - lastReceivedBeaconTs) / 1000); @@ -293,7 +317,10 @@ void NukiOpenerWrapper::update() _nextLockAction = (NukiOpener::LockAction) 0xff; _network->publishRetry("--"); retryCount = 0; - if(_intervalLockstate > 10) _nextLockStateUpdateTs = ts + 10 * 1000; + if(_intervalLockstate > 10) + { + _nextLockStateUpdateTs = ts + 10 * 1000; + } } else { @@ -331,8 +358,14 @@ void NukiOpenerWrapper::activateCM() void NukiOpenerWrapper::deactivateRtoCm() { - if(_keyTurnerState.nukiState == NukiOpener::State::ContinuousMode) _nextLockAction = NukiOpener::LockAction::DeactivateCM; - else if(_keyTurnerState.lockState == NukiOpener::LockState::RTOactive) _nextLockAction = NukiOpener::LockAction::DeactivateRTO; + if(_keyTurnerState.nukiState == NukiOpener::State::ContinuousMode) + { + _nextLockAction = NukiOpener::LockAction::DeactivateCM; + } + else if(_keyTurnerState.lockState == NukiOpener::LockState::RTOactive) + { + _nextLockAction = NukiOpener::LockAction::DeactivateRTO; + } } void NukiOpenerWrapper::deactivateRTO() @@ -409,9 +442,9 @@ void NukiOpenerWrapper::updateKeyTurnerState() _retryLockstateCount = 0; if(_statusUpdated && - _keyTurnerState.lockState == NukiOpener::LockState::Locked && - _lastKeyTurnerState.lockState == NukiOpener::LockState::Locked && - _lastKeyTurnerState.nukiState == _keyTurnerState.nukiState) + _keyTurnerState.lockState == NukiOpener::LockState::Locked && + _lastKeyTurnerState.lockState == NukiOpener::LockState::Locked && + _lastKeyTurnerState.nukiState == _keyTurnerState.nukiState) { Log->println(F("Nuki opener: Ring detected (Locked)")); _network->publishRing(true); @@ -419,8 +452,8 @@ void NukiOpenerWrapper::updateKeyTurnerState() else { if(_keyTurnerState.lockState != _lastKeyTurnerState.lockState && - _keyTurnerState.lockState == NukiOpener::LockState::Open && - _keyTurnerState.trigger == NukiOpener::Trigger::Manual) + _keyTurnerState.lockState == NukiOpener::LockState::Open && + _keyTurnerState.trigger == NukiOpener::Trigger::Manual) { Log->println(F("Nuki opener: Ring detected (Open)")); _network->publishRing(false); @@ -460,10 +493,14 @@ void NukiOpenerWrapper::updateBatteryState() Log->print(F("Querying opener battery state: ")); result = _nukiOpener.requestBatteryReport(&_batteryReport); delay(250); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -500,14 +537,24 @@ void NukiOpenerWrapper::updateConfig() _hasKeypad = _nukiConfig.hasKeypad > 0 || _nukiConfig.hasKeypadV2 > 0; _firmwareVersion = std::to_string(_nukiConfig.firmwareVersion[0]) + "." + std::to_string(_nukiConfig.firmwareVersion[1]) + "." + std::to_string(_nukiConfig.firmwareVersion[2]); _hardwareVersion = std::to_string(_nukiConfig.hardwareRevision[0]) + "." + std::to_string(_nukiConfig.hardwareRevision[1]); - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishConfig(_nukiConfig); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishConfig(_nukiConfig); + } _retryConfigCount = 0; - if(_preferences->getBool(preference_timecontrol_info_enabled, false)) updateTimeControl(false); - if(_preferences->getBool(preference_auth_info_enabled)) updateAuth(false); + if(_preferences->getBool(preference_timecontrol_info_enabled, false)) + { + updateTimeControl(false); + } + if(_preferences->getBool(preference_auth_info_enabled)) + { + updateAuth(false); + } const int pinStatus = _preferences->getInt(preference_opener_pin_status, 4); - if(isPinSet()) { + if(isPinSet()) + { Nuki::CmdResult result = (Nuki::CmdResult)-1; int retryCount = 0; Log->println(F("Nuki opener PIN is set")); @@ -516,23 +563,29 @@ void NukiOpenerWrapper::updateConfig() { result = _nukiOpener.verifySecurityPin(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if(result != Nuki::CmdResult::Success) { Log->println(F("Nuki opener PIN is invalid")); - if(pinStatus != 2) { + if(pinStatus != 2) + { _preferences->putInt(preference_opener_pin_status, 2); } } else { Log->println(F("Nuki opener PIN is valid")); - if(pinStatus != 1) { + if(pinStatus != 1) + { _preferences->putInt(preference_opener_pin_status, 1); } } @@ -540,7 +593,8 @@ void NukiOpenerWrapper::updateConfig() else { Log->println(F("Nuki opener PIN is not set")); - if(pinStatus != 0) { + if(pinStatus != 0) + { _preferences->putInt(preference_opener_pin_status, 0); } } @@ -563,7 +617,10 @@ void NukiOpenerWrapper::updateConfig() if(_nukiAdvancedConfigValid) { - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishAdvancedConfig(_nukiAdvancedConfig); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishAdvancedConfig(_nukiAdvancedConfig); + } } else { @@ -604,10 +661,14 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) Log->print(F("Retrieve log entries: ")); result = _nukiOpener.retrieveLogEntries(0, _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 1, false); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } Log->println(result); @@ -625,11 +686,14 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, 3)); } - log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) + { + return a.index < b.index; + }); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, true); + _network->publishAuthorizationInfo(log, true); } } } @@ -643,14 +707,17 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG)); } - log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiOpener::LogEntry& a, const NukiOpener::LogEntry& b) + { + return a.index < b.index; + }); Log->print(F("Log size: ")); Log->println(log.size()); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, false); + _network->publishAuthorizationInfo(log, false); } } @@ -659,7 +726,10 @@ void NukiOpenerWrapper::updateAuthData(bool retrieved) void NukiOpenerWrapper::updateKeypad(bool retrieved) { - if(!_preferences->getBool(preference_keypad_info_enabled)) return; + if(!_preferences->getBool(preference_keypad_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -677,10 +747,14 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) Log->print(F("Querying opener keypad: ")); result = _nukiOpener.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -697,7 +771,10 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) Log->print(F("Opener keypad codes: ")); Log->println(entries.size()); - entries.sort([](const NukiOpener::KeypadEntry& a, const NukiOpener::KeypadEntry& b) { return a.codeId < b.codeId; }); + entries.sort([](const NukiOpener::KeypadEntry& a, const NukiOpener::KeypadEntry& b) + { + return a.codeId < b.codeId; + }); if(entries.size() > _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)) { @@ -726,7 +803,10 @@ void NukiOpenerWrapper::updateKeypad(bool retrieved) void NukiOpenerWrapper::updateTimeControl(bool retrieved) { - if(!_preferences->getBool(preference_timecontrol_info_enabled)) return; + if(!_preferences->getBool(preference_timecontrol_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -744,10 +824,14 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) Log->print(F("Querying opener timecontrol: ")); result = _nukiOpener.retrieveTimeControlEntries(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -764,7 +848,10 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) Log->print(F("Opener timecontrol entries: ")); Log->println(timeControlEntries.size()); - timeControlEntries.sort([](const NukiOpener::TimeControlEntry& a, const NukiOpener::TimeControlEntry& b) { return a.entryId < b.entryId; }); + timeControlEntries.sort([](const NukiOpener::TimeControlEntry& a, const NukiOpener::TimeControlEntry& b) + { + return a.entryId < b.entryId; + }); if(timeControlEntries.size() > _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL)) { @@ -793,7 +880,10 @@ void NukiOpenerWrapper::updateTimeControl(bool retrieved) void NukiOpenerWrapper::updateAuth(bool retrieved) { - if(!_preferences->getBool(preference_auth_info_enabled)) return; + if(!_preferences->getBool(preference_auth_info_enabled)) + { + return; + } if(!retrieved) { @@ -805,10 +895,14 @@ void NukiOpenerWrapper::updateAuth(bool retrieved) Log->print(F("Querying opener authorization: ")); result = _nukiOpener.retrieveAuthorizationEntries(0, _preferences->getInt(preference_auth_max_entries, MAX_AUTH)); delay(250); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -825,7 +919,10 @@ void NukiOpenerWrapper::updateAuth(bool retrieved) Log->print(F("Opener authorization entries: ")); Log->println(authEntries.size()); - authEntries.sort([](const NukiOpener::AuthorizationEntry& a, const NukiOpener::AuthorizationEntry& b) { return a.authId < b.authId; }); + authEntries.sort([](const NukiOpener::AuthorizationEntry& a, const NukiOpener::AuthorizationEntry& b) + { + return a.authId < b.authId; + }); if(authEntries.size() > _preferences->getInt(preference_auth_max_entries, MAX_AUTH)) { @@ -859,14 +956,38 @@ void NukiOpenerWrapper::postponeBleWatchdog() NukiOpener::LockAction NukiOpenerWrapper::lockActionToEnum(const char *str) { - if(strcmp(str, "activateRTO") == 0 || strcmp(str, "ActivateRTO") == 0) return NukiOpener::LockAction::ActivateRTO; - else if(strcmp(str, "deactivateRTO") == 0 || strcmp(str, "DeactivateRTO") == 0) return NukiOpener::LockAction::DeactivateRTO; - else if(strcmp(str, "electricStrikeActuation") == 0 || strcmp(str, "ElectricStrikeActuation") == 0) return NukiOpener::LockAction::ElectricStrikeActuation; - else if(strcmp(str, "activateCM") == 0 || strcmp(str, "ActivateCM") == 0) return NukiOpener::LockAction::ActivateCM; - else if(strcmp(str, "deactivateCM") == 0 || strcmp(str, "DeactivateCM") == 0) return NukiOpener::LockAction::DeactivateCM; - else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) return NukiOpener::LockAction::FobAction2; - else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) return NukiOpener::LockAction::FobAction1; - else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) return NukiOpener::LockAction::FobAction3; + if(strcmp(str, "activateRTO") == 0 || strcmp(str, "ActivateRTO") == 0) + { + return NukiOpener::LockAction::ActivateRTO; + } + else if(strcmp(str, "deactivateRTO") == 0 || strcmp(str, "DeactivateRTO") == 0) + { + return NukiOpener::LockAction::DeactivateRTO; + } + else if(strcmp(str, "electricStrikeActuation") == 0 || strcmp(str, "ElectricStrikeActuation") == 0) + { + return NukiOpener::LockAction::ElectricStrikeActuation; + } + else if(strcmp(str, "activateCM") == 0 || strcmp(str, "ActivateCM") == 0) + { + return NukiOpener::LockAction::ActivateCM; + } + else if(strcmp(str, "deactivateCM") == 0 || strcmp(str, "DeactivateCM") == 0) + { + return NukiOpener::LockAction::DeactivateCM; + } + else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) + { + return NukiOpener::LockAction::FobAction2; + } + else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) + { + return NukiOpener::LockAction::FobAction1; + } + else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) + { + return NukiOpener::LockAction::FobAction3; + } return (NukiOpener::LockAction)0xff; } @@ -879,11 +1000,20 @@ LockActionResult NukiOpenerWrapper::onLockActionReceivedCallback(const char *val if(strlen(value) > 0) { action = nukiOpenerInst->lockActionToEnum(value); - if((int)action == 0xff) return LockActionResult::UnknownAction; + if((int)action == 0xff) + { + return LockActionResult::UnknownAction; + } + } + else + { + return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; + else + { + return LockActionResult::UnknownAction; + } nukiOpenerPreferences = new Preferences(); nukiOpenerPreferences->begin("nukihub", true); @@ -908,137 +1038,425 @@ void NukiOpenerWrapper::onConfigUpdateReceivedCallback(const char *value) Nuki::AdvertisingMode NukiOpenerWrapper::advertisingModeToEnum(const char *str) { - if(strcmp(str, "Automatic") == 0) return Nuki::AdvertisingMode::Automatic; - else if(strcmp(str, "Normal") == 0) return Nuki::AdvertisingMode::Normal; - else if(strcmp(str, "Slow") == 0) return Nuki::AdvertisingMode::Slow; - else if(strcmp(str, "Slowest") == 0) return Nuki::AdvertisingMode::Slowest; + if(strcmp(str, "Automatic") == 0) + { + return Nuki::AdvertisingMode::Automatic; + } + else if(strcmp(str, "Normal") == 0) + { + return Nuki::AdvertisingMode::Normal; + } + else if(strcmp(str, "Slow") == 0) + { + return Nuki::AdvertisingMode::Slow; + } + else if(strcmp(str, "Slowest") == 0) + { + return Nuki::AdvertisingMode::Slowest; + } return (Nuki::AdvertisingMode)0xff; } Nuki::TimeZoneId NukiOpenerWrapper::timeZoneToEnum(const char *str) { - if(strcmp(str, "Africa/Cairo") == 0) return Nuki::TimeZoneId::Africa_Cairo; - else if(strcmp(str, "Africa/Lagos") == 0) return Nuki::TimeZoneId::Africa_Lagos; - else if(strcmp(str, "Africa/Maputo") == 0) return Nuki::TimeZoneId::Africa_Maputo; - else if(strcmp(str, "Africa/Nairobi") == 0) return Nuki::TimeZoneId::Africa_Nairobi; - else if(strcmp(str, "America/Anchorage") == 0) return Nuki::TimeZoneId::America_Anchorage; - else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; - else if(strcmp(str, "America/Chicago") == 0) return Nuki::TimeZoneId::America_Chicago; - else if(strcmp(str, "America/Denver") == 0) return Nuki::TimeZoneId::America_Denver; - else if(strcmp(str, "America/Halifax") == 0) return Nuki::TimeZoneId::America_Halifax; - else if(strcmp(str, "America/Los_Angeles") == 0) return Nuki::TimeZoneId::America_Los_Angeles; - else if(strcmp(str, "America/Manaus") == 0) return Nuki::TimeZoneId::America_Manaus; - else if(strcmp(str, "America/Mexico_City") == 0) return Nuki::TimeZoneId::America_Mexico_City; - else if(strcmp(str, "America/New_York") == 0) return Nuki::TimeZoneId::America_New_York; - else if(strcmp(str, "America/Phoenix") == 0) return Nuki::TimeZoneId::America_Phoenix; - else if(strcmp(str, "America/Regina") == 0) return Nuki::TimeZoneId::America_Regina; - else if(strcmp(str, "America/Santiago") == 0) return Nuki::TimeZoneId::America_Santiago; - else if(strcmp(str, "America/Sao_Paulo") == 0) return Nuki::TimeZoneId::America_Sao_Paulo; - else if(strcmp(str, "America/St_Johns") == 0) return Nuki::TimeZoneId::America_St_Johns; - else if(strcmp(str, "Asia/Bangkok") == 0) return Nuki::TimeZoneId::Asia_Bangkok; - else if(strcmp(str, "Asia/Dubai") == 0) return Nuki::TimeZoneId::Asia_Dubai; - else if(strcmp(str, "Asia/Hong_Kong") == 0) return Nuki::TimeZoneId::Asia_Hong_Kong; - else if(strcmp(str, "Asia/Jerusalem") == 0) return Nuki::TimeZoneId::Asia_Jerusalem; - else if(strcmp(str, "Asia/Karachi") == 0) return Nuki::TimeZoneId::Asia_Karachi; - else if(strcmp(str, "Asia/Kathmandu") == 0) return Nuki::TimeZoneId::Asia_Kathmandu; - else if(strcmp(str, "Asia/Kolkata") == 0) return Nuki::TimeZoneId::Asia_Kolkata; - else if(strcmp(str, "Asia/Riyadh") == 0) return Nuki::TimeZoneId::Asia_Riyadh; - else if(strcmp(str, "Asia/Seoul") == 0) return Nuki::TimeZoneId::Asia_Seoul; - else if(strcmp(str, "Asia/Shanghai") == 0) return Nuki::TimeZoneId::Asia_Shanghai; - else if(strcmp(str, "Asia/Tehran") == 0) return Nuki::TimeZoneId::Asia_Tehran; - else if(strcmp(str, "Asia/Tokyo") == 0) return Nuki::TimeZoneId::Asia_Tokyo; - else if(strcmp(str, "Asia/Yangon") == 0) return Nuki::TimeZoneId::Asia_Yangon; - else if(strcmp(str, "Australia/Adelaide") == 0) return Nuki::TimeZoneId::Australia_Adelaide; - else if(strcmp(str, "Australia/Brisbane") == 0) return Nuki::TimeZoneId::Australia_Brisbane; - else if(strcmp(str, "Australia/Darwin") == 0) return Nuki::TimeZoneId::Australia_Darwin; - else if(strcmp(str, "Australia/Hobart") == 0) return Nuki::TimeZoneId::Australia_Hobart; - else if(strcmp(str, "Australia/Perth") == 0) return Nuki::TimeZoneId::Australia_Perth; - else if(strcmp(str, "Australia/Sydney") == 0) return Nuki::TimeZoneId::Australia_Sydney; - else if(strcmp(str, "Europe/Berlin") == 0) return Nuki::TimeZoneId::Europe_Berlin; - else if(strcmp(str, "Europe/Helsinki") == 0) return Nuki::TimeZoneId::Europe_Helsinki; - else if(strcmp(str, "Europe/Istanbul") == 0) return Nuki::TimeZoneId::Europe_Istanbul; - else if(strcmp(str, "Europe/London") == 0) return Nuki::TimeZoneId::Europe_London; - else if(strcmp(str, "Europe/Moscow") == 0) return Nuki::TimeZoneId::Europe_Moscow; - else if(strcmp(str, "Pacific/Auckland") == 0) return Nuki::TimeZoneId::Pacific_Auckland; - else if(strcmp(str, "Pacific/Guam") == 0) return Nuki::TimeZoneId::Pacific_Guam; - else if(strcmp(str, "Pacific/Honolulu") == 0) return Nuki::TimeZoneId::Pacific_Honolulu; - else if(strcmp(str, "Pacific/Pago_Pago") == 0) return Nuki::TimeZoneId::Pacific_Pago_Pago; - else if(strcmp(str, "None") == 0) return Nuki::TimeZoneId::None; + if(strcmp(str, "Africa/Cairo") == 0) + { + return Nuki::TimeZoneId::Africa_Cairo; + } + else if(strcmp(str, "Africa/Lagos") == 0) + { + return Nuki::TimeZoneId::Africa_Lagos; + } + else if(strcmp(str, "Africa/Maputo") == 0) + { + return Nuki::TimeZoneId::Africa_Maputo; + } + else if(strcmp(str, "Africa/Nairobi") == 0) + { + return Nuki::TimeZoneId::Africa_Nairobi; + } + else if(strcmp(str, "America/Anchorage") == 0) + { + return Nuki::TimeZoneId::America_Anchorage; + } + else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) + { + return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; + } + else if(strcmp(str, "America/Chicago") == 0) + { + return Nuki::TimeZoneId::America_Chicago; + } + else if(strcmp(str, "America/Denver") == 0) + { + return Nuki::TimeZoneId::America_Denver; + } + else if(strcmp(str, "America/Halifax") == 0) + { + return Nuki::TimeZoneId::America_Halifax; + } + else if(strcmp(str, "America/Los_Angeles") == 0) + { + return Nuki::TimeZoneId::America_Los_Angeles; + } + else if(strcmp(str, "America/Manaus") == 0) + { + return Nuki::TimeZoneId::America_Manaus; + } + else if(strcmp(str, "America/Mexico_City") == 0) + { + return Nuki::TimeZoneId::America_Mexico_City; + } + else if(strcmp(str, "America/New_York") == 0) + { + return Nuki::TimeZoneId::America_New_York; + } + else if(strcmp(str, "America/Phoenix") == 0) + { + return Nuki::TimeZoneId::America_Phoenix; + } + else if(strcmp(str, "America/Regina") == 0) + { + return Nuki::TimeZoneId::America_Regina; + } + else if(strcmp(str, "America/Santiago") == 0) + { + return Nuki::TimeZoneId::America_Santiago; + } + else if(strcmp(str, "America/Sao_Paulo") == 0) + { + return Nuki::TimeZoneId::America_Sao_Paulo; + } + else if(strcmp(str, "America/St_Johns") == 0) + { + return Nuki::TimeZoneId::America_St_Johns; + } + else if(strcmp(str, "Asia/Bangkok") == 0) + { + return Nuki::TimeZoneId::Asia_Bangkok; + } + else if(strcmp(str, "Asia/Dubai") == 0) + { + return Nuki::TimeZoneId::Asia_Dubai; + } + else if(strcmp(str, "Asia/Hong_Kong") == 0) + { + return Nuki::TimeZoneId::Asia_Hong_Kong; + } + else if(strcmp(str, "Asia/Jerusalem") == 0) + { + return Nuki::TimeZoneId::Asia_Jerusalem; + } + else if(strcmp(str, "Asia/Karachi") == 0) + { + return Nuki::TimeZoneId::Asia_Karachi; + } + else if(strcmp(str, "Asia/Kathmandu") == 0) + { + return Nuki::TimeZoneId::Asia_Kathmandu; + } + else if(strcmp(str, "Asia/Kolkata") == 0) + { + return Nuki::TimeZoneId::Asia_Kolkata; + } + else if(strcmp(str, "Asia/Riyadh") == 0) + { + return Nuki::TimeZoneId::Asia_Riyadh; + } + else if(strcmp(str, "Asia/Seoul") == 0) + { + return Nuki::TimeZoneId::Asia_Seoul; + } + else if(strcmp(str, "Asia/Shanghai") == 0) + { + return Nuki::TimeZoneId::Asia_Shanghai; + } + else if(strcmp(str, "Asia/Tehran") == 0) + { + return Nuki::TimeZoneId::Asia_Tehran; + } + else if(strcmp(str, "Asia/Tokyo") == 0) + { + return Nuki::TimeZoneId::Asia_Tokyo; + } + else if(strcmp(str, "Asia/Yangon") == 0) + { + return Nuki::TimeZoneId::Asia_Yangon; + } + else if(strcmp(str, "Australia/Adelaide") == 0) + { + return Nuki::TimeZoneId::Australia_Adelaide; + } + else if(strcmp(str, "Australia/Brisbane") == 0) + { + return Nuki::TimeZoneId::Australia_Brisbane; + } + else if(strcmp(str, "Australia/Darwin") == 0) + { + return Nuki::TimeZoneId::Australia_Darwin; + } + else if(strcmp(str, "Australia/Hobart") == 0) + { + return Nuki::TimeZoneId::Australia_Hobart; + } + else if(strcmp(str, "Australia/Perth") == 0) + { + return Nuki::TimeZoneId::Australia_Perth; + } + else if(strcmp(str, "Australia/Sydney") == 0) + { + return Nuki::TimeZoneId::Australia_Sydney; + } + else if(strcmp(str, "Europe/Berlin") == 0) + { + return Nuki::TimeZoneId::Europe_Berlin; + } + else if(strcmp(str, "Europe/Helsinki") == 0) + { + return Nuki::TimeZoneId::Europe_Helsinki; + } + else if(strcmp(str, "Europe/Istanbul") == 0) + { + return Nuki::TimeZoneId::Europe_Istanbul; + } + else if(strcmp(str, "Europe/London") == 0) + { + return Nuki::TimeZoneId::Europe_London; + } + else if(strcmp(str, "Europe/Moscow") == 0) + { + return Nuki::TimeZoneId::Europe_Moscow; + } + else if(strcmp(str, "Pacific/Auckland") == 0) + { + return Nuki::TimeZoneId::Pacific_Auckland; + } + else if(strcmp(str, "Pacific/Guam") == 0) + { + return Nuki::TimeZoneId::Pacific_Guam; + } + else if(strcmp(str, "Pacific/Honolulu") == 0) + { + return Nuki::TimeZoneId::Pacific_Honolulu; + } + else if(strcmp(str, "Pacific/Pago_Pago") == 0) + { + return Nuki::TimeZoneId::Pacific_Pago_Pago; + } + else if(strcmp(str, "None") == 0) + { + return Nuki::TimeZoneId::None; + } return (Nuki::TimeZoneId)0xff; } uint8_t NukiOpenerWrapper::fobActionToInt(const char *str) { - if(strcmp(str, "No Action") == 0) return 0; - else if(strcmp(str, "Toggle RTO") == 0) return 1; - else if(strcmp(str, "Activate RTO") == 0) return 2; - else if(strcmp(str, "Deactivate RTO") == 0) return 3; - else if(strcmp(str, "Open") == 0) return 7; - else if(strcmp(str, "Ring") == 0) return 8; + if(strcmp(str, "No Action") == 0) + { + return 0; + } + else if(strcmp(str, "Toggle RTO") == 0) + { + return 1; + } + else if(strcmp(str, "Activate RTO") == 0) + { + return 2; + } + else if(strcmp(str, "Deactivate RTO") == 0) + { + return 3; + } + else if(strcmp(str, "Open") == 0) + { + return 7; + } + else if(strcmp(str, "Ring") == 0) + { + return 8; + } return 99; } uint8_t NukiOpenerWrapper::operatingModeToInt(const char *str) { - if(strcmp(str, "Generic door opener") == 0) return 0; - else if(strcmp(str, "Analogue intercom") == 0) return 1; - else if(strcmp(str, "Digital intercom") == 0) return 2; - else if(strcmp(str, "Siedle") == 0) return 3; - else if(strcmp(str, "TCS") == 0) return 4; - else if(strcmp(str, "Bticino") == 0) return 5; - else if(strcmp(str, "Siedle HTS") == 0) return 6; - else if(strcmp(str, "STR") == 0) return 7; - else if(strcmp(str, "Ritto") == 0) return 8; - else if(strcmp(str, "Fermax") == 0) return 9; - else if(strcmp(str, "Comelit") == 0) return 10; - else if(strcmp(str, "Urmet BiBus") == 0) return 11; - else if(strcmp(str, "Urmet 2Voice") == 0) return 12; - else if(strcmp(str, "Golmar") == 0) return 13; - else if(strcmp(str, "SKS") == 0) return 14; - else if(strcmp(str, "Spare") == 0) return 15; + if(strcmp(str, "Generic door opener") == 0) + { + return 0; + } + else if(strcmp(str, "Analogue intercom") == 0) + { + return 1; + } + else if(strcmp(str, "Digital intercom") == 0) + { + return 2; + } + else if(strcmp(str, "Siedle") == 0) + { + return 3; + } + else if(strcmp(str, "TCS") == 0) + { + return 4; + } + else if(strcmp(str, "Bticino") == 0) + { + return 5; + } + else if(strcmp(str, "Siedle HTS") == 0) + { + return 6; + } + else if(strcmp(str, "STR") == 0) + { + return 7; + } + else if(strcmp(str, "Ritto") == 0) + { + return 8; + } + else if(strcmp(str, "Fermax") == 0) + { + return 9; + } + else if(strcmp(str, "Comelit") == 0) + { + return 10; + } + else if(strcmp(str, "Urmet BiBus") == 0) + { + return 11; + } + else if(strcmp(str, "Urmet 2Voice") == 0) + { + return 12; + } + else if(strcmp(str, "Golmar") == 0) + { + return 13; + } + else if(strcmp(str, "SKS") == 0) + { + return 14; + } + else if(strcmp(str, "Spare") == 0) + { + return 15; + } return 99; } uint8_t NukiOpenerWrapper::doorbellSuppressionToInt(const char *str) { - if(strcmp(str, "Off") == 0) return 0; - else if(strcmp(str, "CM") == 0) return 1; - else if(strcmp(str, "RTO") == 0) return 2; - else if(strcmp(str, "CM & RTO") == 0) return 3; - else if(strcmp(str, "Ring") == 0) return 4; - else if(strcmp(str, "CM & Ring") == 0) return 5; - else if(strcmp(str, "RTO & Ring") == 0) return 6; - else if(strcmp(str, "CM & RTO & Ring") == 0) return 7; + if(strcmp(str, "Off") == 0) + { + return 0; + } + else if(strcmp(str, "CM") == 0) + { + return 1; + } + else if(strcmp(str, "RTO") == 0) + { + return 2; + } + else if(strcmp(str, "CM & RTO") == 0) + { + return 3; + } + else if(strcmp(str, "Ring") == 0) + { + return 4; + } + else if(strcmp(str, "CM & Ring") == 0) + { + return 5; + } + else if(strcmp(str, "RTO & Ring") == 0) + { + return 6; + } + else if(strcmp(str, "CM & RTO & Ring") == 0) + { + return 7; + } return 99; } uint8_t NukiOpenerWrapper::soundToInt(const char *str) { - if(strcmp(str, "No Sound") == 0) return 0; - else if(strcmp(str, "Sound 1") == 0) return 1; - else if(strcmp(str, "Sound 2") == 0) return 2; - else if(strcmp(str, "Sound 3") == 0) return 3; + if(strcmp(str, "No Sound") == 0) + { + return 0; + } + else if(strcmp(str, "Sound 1") == 0) + { + return 1; + } + else if(strcmp(str, "Sound 2") == 0) + { + return 2; + } + else if(strcmp(str, "Sound 3") == 0) + { + return 3; + } return 99; } NukiOpener::ButtonPressAction NukiOpenerWrapper::buttonPressActionToEnum(const char* str) { - if(strcmp(str, "No Action") == 0) return NukiOpener::ButtonPressAction::NoAction; - else if(strcmp(str, "Toggle RTO") == 0) return NukiOpener::ButtonPressAction::ToggleRTO; - else if(strcmp(str, "Activate RTO") == 0) return NukiOpener::ButtonPressAction::ActivateRTO; - else if(strcmp(str, "Deactivate RTO") == 0) return NukiOpener::ButtonPressAction::DeactivateRTO; - else if(strcmp(str, "Toggle CM") == 0) return NukiOpener::ButtonPressAction::ToggleCM; - else if(strcmp(str, "Activate CM") == 0) return NukiOpener::ButtonPressAction::ActivateCM; - else if(strcmp(str, "Deactivate CM") == 0) return NukiOpener::ButtonPressAction::DectivateCM; - else if(strcmp(str, "Open") == 0) return NukiOpener::ButtonPressAction::Open; + if(strcmp(str, "No Action") == 0) + { + return NukiOpener::ButtonPressAction::NoAction; + } + else if(strcmp(str, "Toggle RTO") == 0) + { + return NukiOpener::ButtonPressAction::ToggleRTO; + } + else if(strcmp(str, "Activate RTO") == 0) + { + return NukiOpener::ButtonPressAction::ActivateRTO; + } + else if(strcmp(str, "Deactivate RTO") == 0) + { + return NukiOpener::ButtonPressAction::DeactivateRTO; + } + else if(strcmp(str, "Toggle CM") == 0) + { + return NukiOpener::ButtonPressAction::ToggleCM; + } + else if(strcmp(str, "Activate CM") == 0) + { + return NukiOpener::ButtonPressAction::ActivateCM; + } + else if(strcmp(str, "Deactivate CM") == 0) + { + return NukiOpener::ButtonPressAction::DectivateCM; + } + else if(strcmp(str, "Open") == 0) + { + return NukiOpener::ButtonPressAction::Open; + } return (NukiOpener::ButtonPressAction)0xff; } Nuki::BatteryType NukiOpenerWrapper::batteryTypeToEnum(const char* str) { - if(strcmp(str, "Alkali") == 0) return Nuki::BatteryType::Alkali; - else if(strcmp(str, "Accumulators") == 0) return Nuki::BatteryType::Accumulators; - else if(strcmp(str, "Lithium") == 0) return Nuki::BatteryType::Lithium; + if(strcmp(str, "Alkali") == 0) + { + return Nuki::BatteryType::Alkali; + } + else if(strcmp(str, "Accumulators") == 0) + { + return Nuki::BatteryType::Accumulators; + } + else if(strcmp(str, "Lithium") == 0) + { + return Nuki::BatteryType::Lithium; + } return (Nuki::BatteryType)0xff; } @@ -1104,10 +1522,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) { if(strlen(jsonchar) <= 32) { - if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setName(std::string(jsonchar)); + if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setName(std::string(jsonchar)); + } + } + else + { + jsonResult[basicKeys[i]] = "valueTooLong"; } - else jsonResult[basicKeys[i]] = "valueTooLong"; } else if(strcmp(basicKeys[i], "latitude") == 0) { @@ -1115,10 +1542,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.latitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setLatitude(keyvalue); + if(_nukiConfig.latitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setLatitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "longitude") == 0) { @@ -1126,10 +1562,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.longitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setLongitude(keyvalue); + if(_nukiConfig.longitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setLongitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "pairingEnabled") == 0) { @@ -1137,10 +1582,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.pairingEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enablePairing((keyvalue > 0)); + if(_nukiConfig.pairingEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enablePairing((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "buttonEnabled") == 0) { @@ -1148,10 +1602,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.buttonEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enableButton((keyvalue > 0)); + if(_nukiConfig.buttonEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableButton((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "ledFlashEnabled") == 0) { @@ -1159,10 +1622,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.ledFlashEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enableLedFlash((keyvalue > 0)); + if(_nukiConfig.ledFlashEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableLedFlash((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZoneOffset") == 0) { @@ -1170,10 +1642,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 60) { - if(_nukiConfig.timeZoneOffset == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setTimeZoneOffset(keyvalue); + if(_nukiConfig.timeZoneOffset == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setTimeZoneOffset(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "dstMode") == 0) { @@ -1181,10 +1662,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.dstMode == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.enableDst((keyvalue > 0)); + if(_nukiConfig.dstMode == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableDst((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction1") == 0) { @@ -1192,10 +1682,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(fobAct1 != 99) { - if(_nukiConfig.fobAction1 == fobAct1) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setFobAction(1, fobAct1); + if(_nukiConfig.fobAction1 == fobAct1) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setFobAction(1, fobAct1); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction2") == 0) { @@ -1203,10 +1702,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(fobAct2 != 99) { - if(_nukiConfig.fobAction2 == fobAct2) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setFobAction(2, fobAct2); + if(_nukiConfig.fobAction2 == fobAct2) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setFobAction(2, fobAct2); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction3") == 0) { @@ -1214,10 +1722,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(fobAct3 != 99) { - if(_nukiConfig.fobAction3 == fobAct3) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setFobAction(3, fobAct3); + if(_nukiConfig.fobAction3 == fobAct3) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setFobAction(3, fobAct3); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "operatingMode") == 0) { @@ -1225,10 +1742,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(opmode != 99) { - if(_nukiConfig.operatingMode == opmode) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setOperatingMode(opmode); + if(_nukiConfig.operatingMode == opmode) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setOperatingMode(opmode); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "advertisingMode") == 0) { @@ -1236,10 +1762,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)advmode != 0xff) { - if(_nukiConfig.advertisingMode == advmode) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setAdvertisingMode(advmode); + if(_nukiConfig.advertisingMode == advmode) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setAdvertisingMode(advmode); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZone") == 0) { @@ -1247,27 +1782,47 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)tzid != 0xff) { - if(_nukiConfig.timeZoneId == tzid) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiOpener.setTimeZoneId(tzid); + if(_nukiConfig.timeZoneId == tzid) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setTimeZoneId(tzid); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + if(cmdResult != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) basicUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + basicUpdated = true; + } - if(!jsonResult[basicKeys[i]]) { + if(!jsonResult[basicKeys[i]]) + { char resultStr[15] = {0}; NukiOpener::cmdResultToString(cmdResult, resultStr); jsonResult[basicKeys[i]] = resultStr; } } - else jsonResult[basicKeys[i]] = "accessDenied"; + else + { + jsonResult[basicKeys[i]] = "accessDenied"; + } } } @@ -1296,10 +1851,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0) { - if(_nukiAdvancedConfig.intercomID == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setIntercomID(keyvalue); + if(_nukiAdvancedConfig.intercomID == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setIntercomID(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "busModeSwitch") == 0) { @@ -1307,10 +1871,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.busModeSwitch == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setBusModeSwitch((keyvalue > 0)); + if(_nukiAdvancedConfig.busModeSwitch == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setBusModeSwitch((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "shortCircuitDuration") == 0) { @@ -1318,10 +1891,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0) { - if(_nukiAdvancedConfig.shortCircuitDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setShortCircuitDuration(keyvalue); + if(_nukiAdvancedConfig.shortCircuitDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setShortCircuitDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "electricStrikeDelay") == 0) { @@ -1329,10 +1911,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 30000) { - if(_nukiAdvancedConfig.electricStrikeDelay == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setElectricStrikeDelay(keyvalue); + if(_nukiAdvancedConfig.electricStrikeDelay == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setElectricStrikeDelay(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "randomElectricStrikeDelay") == 0) { @@ -1340,10 +1931,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.randomElectricStrikeDelay == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.enableRandomElectricStrikeDelay((keyvalue > 0)); + if(_nukiAdvancedConfig.randomElectricStrikeDelay == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableRandomElectricStrikeDelay((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "electricStrikeDuration") == 0) { @@ -1351,10 +1951,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 1000 && keyvalue <= 30000) { - if(_nukiAdvancedConfig.electricStrikeDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setElectricStrikeDuration(keyvalue); + if(_nukiAdvancedConfig.electricStrikeDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setElectricStrikeDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "disableRtoAfterRing") == 0) { @@ -1362,10 +1971,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.disableRtoAfterRing == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.disableRtoAfterRing((keyvalue > 0)); + if(_nukiAdvancedConfig.disableRtoAfterRing == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.disableRtoAfterRing((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "rtoTimeout") == 0) { @@ -1373,10 +1991,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 5 && keyvalue <= 60) { - if(_nukiAdvancedConfig.rtoTimeout == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setRtoTimeout(keyvalue); + if(_nukiAdvancedConfig.rtoTimeout == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setRtoTimeout(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doorbellSuppression") == 0) { @@ -1384,10 +2011,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(dbsupr != 99) { - if(_nukiAdvancedConfig.doorbellSuppression == dbsupr) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setDoorbellSuppression(dbsupr); + if(_nukiAdvancedConfig.doorbellSuppression == dbsupr) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setDoorbellSuppression(dbsupr); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doorbellSuppressionDuration") == 0) { @@ -1395,10 +2031,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 500 && keyvalue <= 10000) { - if(_nukiAdvancedConfig.doorbellSuppressionDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setDoorbellSuppressionDuration(keyvalue); + if(_nukiAdvancedConfig.doorbellSuppressionDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setDoorbellSuppressionDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundRing") == 0) { @@ -1406,10 +2051,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundRing == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundRing(sound); + if(_nukiAdvancedConfig.soundRing == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundRing(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundOpen") == 0) { @@ -1417,10 +2071,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundOpen == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundOpen(sound); + if(_nukiAdvancedConfig.soundOpen == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundOpen(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundRto") == 0) { @@ -1428,10 +2091,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundRto == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundRto(sound); + if(_nukiAdvancedConfig.soundRto == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundRto(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundCm") == 0) { @@ -1439,10 +2111,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(sound != 99) { - if(_nukiAdvancedConfig.soundCm == sound) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundCm(sound); + if(_nukiAdvancedConfig.soundCm == sound) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundCm(sound); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundConfirmation") == 0) { @@ -1450,10 +2131,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.soundConfirmation == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.enableSoundConfirmation((keyvalue > 0)); + if(_nukiAdvancedConfig.soundConfirmation == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableSoundConfirmation((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "soundLevel") == 0) { @@ -1461,10 +2151,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 255) { - if(_nukiAdvancedConfig.soundLevel == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSoundLevel(keyvalue); + if(_nukiAdvancedConfig.soundLevel == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSoundLevel(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "singleButtonPressAction") == 0) { @@ -1472,10 +2171,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)sbpa != 0xff) { - if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setSingleButtonPressAction(sbpa); + if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setSingleButtonPressAction(sbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doubleButtonPressAction") == 0) { @@ -1483,10 +2191,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)dbpa != 0xff) { - if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setDoubleButtonPressAction(dbpa); + if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setDoubleButtonPressAction(dbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "batteryType") == 0) { @@ -1494,10 +2211,19 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if((int)battype != 0xff) { - if(_nukiAdvancedConfig.batteryType == battype) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.setBatteryType(battype); + if(_nukiAdvancedConfig.batteryType == battype) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.setBatteryType(battype); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "automaticBatteryTypeDetection") == 0) { @@ -1505,33 +2231,58 @@ void NukiOpenerWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiOpener.enableAutoBatteryTypeDetection((keyvalue > 0)); + if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiOpener.enableAutoBatteryTypeDetection((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } if(cmdResult != Nuki::CmdResult::Success) { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) advancedUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + advancedUpdated = true; + } - if(!jsonResult[advancedKeys[j]]) { + if(!jsonResult[advancedKeys[j]]) + { char resultStr[15] = {0}; NukiOpener::cmdResultToString(cmdResult, resultStr); jsonResult[advancedKeys[j]] = resultStr; } } - else jsonResult[advancedKeys[j]] = "accessDenied"; + else + { + jsonResult[advancedKeys[j]] = "accessDenied"; + } } } - if(basicUpdated || advancedUpdated) jsonResult["general"] = "success"; - else jsonResult["general"] = "noChange"; + if(basicUpdated || advancedUpdated) + { + jsonResult["general"] = "success"; + } + else + { + jsonResult["general"] = "noChange"; + } _nextConfigUpdateTs = (esp_timer_get_time() / 1000) + 300; @@ -1565,30 +2316,33 @@ void NukiOpenerWrapper::gpioActionCallback(const GpioAction &action, const int& { switch(action) { - case GpioAction::ElectricStrikeActuation: - nukiOpenerInst->electricStrikeActuation(); - break; - case GpioAction::ActivateRTO: - nukiOpenerInst->activateRTO(); - break; - case GpioAction::ActivateCM: - nukiOpenerInst->activateCM(); - break; - case GpioAction::DeactivateRtoCm: - nukiOpenerInst->deactivateRtoCm(); - break; - case GpioAction::DeactivateRTO: - nukiOpenerInst->deactivateRTO(); - break; - case GpioAction::DeactivateCM: - nukiOpenerInst->deactivateCM(); - break; + case GpioAction::ElectricStrikeActuation: + nukiOpenerInst->electricStrikeActuation(); + break; + case GpioAction::ActivateRTO: + nukiOpenerInst->activateRTO(); + break; + case GpioAction::ActivateCM: + nukiOpenerInst->activateCM(); + break; + case GpioAction::DeactivateRtoCm: + nukiOpenerInst->deactivateRtoCm(); + break; + case GpioAction::DeactivateRTO: + nukiOpenerInst->deactivateRTO(); + break; + case GpioAction::DeactivateCM: + nukiOpenerInst->deactivateCM(); + break; } } void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint &id, const String &name, const String &code, const int& enabled) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } if(!_preferences->getBool(preference_keypad_control_enabled, false)) { @@ -1703,10 +2457,14 @@ void NukiOpenerWrapper::onKeypadCommandReceived(const char *command, const uint return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -1772,21 +2530,57 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json["code"].is()) code = json["code"].as(); - else code = 12; + if(json["code"].is()) + { + code = json["code"].as(); + } + else + { + code = 12; + } - if(json["enabled"].is()) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json["timeLimited"].is()) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json["name"].is()) name = json["name"].as(); - if(json["allowedFrom"].is()) allowedFrom = json["allowedFrom"].as(); - if(json["allowedUntil"].is()) allowedUntil = json["allowedUntil"].as(); - if(json["allowedWeekdays"].is()) allowedWeekdays = json["allowedWeekdays"].as(); - if(json["allowedFromTime"].is()) allowedFromTime = json["allowedFromTime"].as(); - if(json["allowedUntilTime"].is()) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -1802,7 +2596,8 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) while(retryCount < _nrOfRetries + 1) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiOpener.deleteKeypadEntry(codeId); @@ -1939,13 +2734,34 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) } } - if(allowedWeekdays.indexOf("mon") >= 0) allowedWeekdaysInt += 64; - if(allowedWeekdays.indexOf("tue") >= 0) allowedWeekdaysInt += 32; - if(allowedWeekdays.indexOf("wed") >= 0) allowedWeekdaysInt += 16; - if(allowedWeekdays.indexOf("thu") >= 0) allowedWeekdaysInt += 8; - if(allowedWeekdays.indexOf("fri") >= 0) allowedWeekdaysInt += 4; - if(allowedWeekdays.indexOf("sat") >= 0) allowedWeekdaysInt += 2; - if(allowedWeekdays.indexOf("sun") >= 0) allowedWeekdaysInt += 1; + if(allowedWeekdays.indexOf("mon") >= 0) + { + allowedWeekdaysInt += 64; + } + if(allowedWeekdays.indexOf("tue") >= 0) + { + allowedWeekdaysInt += 32; + } + if(allowedWeekdays.indexOf("wed") >= 0) + { + allowedWeekdaysInt += 16; + } + if(allowedWeekdays.indexOf("thu") >= 0) + { + allowedWeekdaysInt += 8; + } + if(allowedWeekdays.indexOf("fri") >= 0) + { + allowedWeekdaysInt += 4; + } + if(allowedWeekdays.indexOf("sat") >= 0) + { + allowedWeekdaysInt += 2; + } + if(allowedWeekdays.indexOf("sun") >= 0) + { + allowedWeekdaysInt += 1; + } } if(strcmp(action, "add") == 0) @@ -2020,17 +2836,32 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) for(const auto& entry : entries) { - if (codeId != entry.codeId) continue; - else foundExisting = true; + if (codeId != entry.codeId) + { + continue; + } + else + { + foundExisting = true; + } if(name.length() < 1) { memset(oldName, 0, sizeof(oldName)); memcpy(oldName, entry.name, sizeof(entry.name)); } - if(code == 12) code = entry.code; - if(enabled == 2) enabled = entry.enabled; - if(timeLimited == 2) timeLimited = entry.timeLimited; + if(code == 12) + { + code = entry.code; + } + if(enabled == 2) + { + enabled = entry.enabled; + } + if(timeLimited == 2) + { + timeLimited = entry.timeLimited; + } if(allowedFrom.length() < 1) { allowedFrom = "old"; @@ -2051,7 +2882,10 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) allowedUntilAr[4] = entry.allowedUntilMin; allowedUntilAr[5] = entry.allowedUntilSec; } - if(allowedWeekdays.length() < 1) allowedWeekdaysInt = entry.allowedWeekdays; + if(allowedWeekdays.length() < 1) + { + allowedWeekdaysInt = entry.allowedWeekdays; + } if(allowedFromTime.length() < 1) { allowedFromTime = "old"; @@ -2149,10 +2983,14 @@ void NukiOpenerWrapper::onKeypadJsonCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } updateKeypad(false); @@ -2209,12 +3047,27 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) String lockAction; NukiOpener::LockAction timeControlLockAction; - if(json["enabled"].is()) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json["weekdays"].is()) weekdays = json["weekdays"].as(); - if(json["time"].is()) time = json["time"].as(); - if(json["lockAction"].is()) lockAction = json["lockAction"].as(); + if(json["weekdays"].is()) + { + weekdays = json["weekdays"].as(); + } + if(json["time"].is()) + { + time = json["time"].as(); + } + if(json["lockAction"].is()) + { + lockAction = json["lockAction"].as(); + } if(lockAction.length() > 0) { @@ -2241,7 +3094,8 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) while(retryCount < _nrOfRetries + 1) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiOpener.removeTimeControlEntry(entryId); @@ -2281,13 +3135,34 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) } } - if(weekdays.indexOf("mon") >= 0) weekdaysInt += 64; - if(weekdays.indexOf("tue") >= 0) weekdaysInt += 32; - if(weekdays.indexOf("wed") >= 0) weekdaysInt += 16; - if(weekdays.indexOf("thu") >= 0) weekdaysInt += 8; - if(weekdays.indexOf("fri") >= 0) weekdaysInt += 4; - if(weekdays.indexOf("sat") >= 0) weekdaysInt += 2; - if(weekdays.indexOf("sun") >= 0) weekdaysInt += 1; + if(weekdays.indexOf("mon") >= 0) + { + weekdaysInt += 64; + } + if(weekdays.indexOf("tue") >= 0) + { + weekdaysInt += 32; + } + if(weekdays.indexOf("wed") >= 0) + { + weekdaysInt += 16; + } + if(weekdays.indexOf("thu") >= 0) + { + weekdaysInt += 8; + } + if(weekdays.indexOf("fri") >= 0) + { + weekdaysInt += 4; + } + if(weekdays.indexOf("sat") >= 0) + { + weekdaysInt += 2; + } + if(weekdays.indexOf("sun") >= 0) + { + weekdaysInt += 1; + } if(strcmp(action, "add") == 0) { @@ -2325,18 +3200,33 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) for(const auto& entry : timeControlEntries) { - if (entryId != entry.entryId) continue; - else foundExisting = true; + if (entryId != entry.entryId) + { + continue; + } + else + { + foundExisting = true; + } - if(enabled == 2) enabled = entry.enabled; - if(weekdays.length() < 1) weekdaysInt = entry.weekdays; + if(enabled == 2) + { + enabled = entry.enabled; + } + if(weekdays.length() < 1) + { + weekdaysInt = entry.weekdays; + } if(time.length() < 1) { time = "old"; timeAr[0] = entry.timeHour; timeAr[1] = entry.timeMin; } - if(lockAction.length() < 1) timeControlLockAction = entry.lockAction; + if(lockAction.length() < 1) + { + timeControlLockAction = entry.lockAction; + } } if(!foundExisting) @@ -2375,10 +3265,14 @@ void NukiOpenerWrapper::onTimeControlCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -2443,22 +3337,58 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json["remoteAllowed"].is()) remoteAllowed = json["remoteAllowed"].as(); - else remoteAllowed = 2; + if(json["remoteAllowed"].is()) + { + remoteAllowed = json["remoteAllowed"].as(); + } + else + { + remoteAllowed = 2; + } - if(json["enabled"].is()) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json["timeLimited"].is()) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json["name"].is()) name = json["name"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } //if(json["sharedKey"].is()) sharedKey = json["sharedKey"].as(); - if(json["allowedFrom"].is()) allowedFrom = json["allowedFrom"].as(); - if(json["allowedUntil"].is()) allowedUntil = json["allowedUntil"].as(); - if(json["allowedWeekdays"].is()) allowedWeekdays = json["allowedWeekdays"].as(); - if(json["allowedFromTime"].is()) allowedFromTime = json["allowedFromTime"].as(); - if(json["allowedUntilTime"].is()) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -2610,13 +3540,34 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) } } - if(allowedWeekdays.indexOf("mon") >= 0) allowedWeekdaysInt += 64; - if(allowedWeekdays.indexOf("tue") >= 0) allowedWeekdaysInt += 32; - if(allowedWeekdays.indexOf("wed") >= 0) allowedWeekdaysInt += 16; - if(allowedWeekdays.indexOf("thu") >= 0) allowedWeekdaysInt += 8; - if(allowedWeekdays.indexOf("fri") >= 0) allowedWeekdaysInt += 4; - if(allowedWeekdays.indexOf("sat") >= 0) allowedWeekdaysInt += 2; - if(allowedWeekdays.indexOf("sun") >= 0) allowedWeekdaysInt += 1; + if(allowedWeekdays.indexOf("mon") >= 0) + { + allowedWeekdaysInt += 64; + } + if(allowedWeekdays.indexOf("tue") >= 0) + { + allowedWeekdaysInt += 32; + } + if(allowedWeekdays.indexOf("wed") >= 0) + { + allowedWeekdaysInt += 16; + } + if(allowedWeekdays.indexOf("thu") >= 0) + { + allowedWeekdaysInt += 8; + } + if(allowedWeekdays.indexOf("fri") >= 0) + { + allowedWeekdaysInt += 4; + } + if(allowedWeekdays.indexOf("sat") >= 0) + { + allowedWeekdaysInt += 2; + } + if(allowedWeekdays.indexOf("sun") >= 0) + { + allowedWeekdaysInt += 1; + } } if(strcmp(action, "add") == 0) @@ -2705,17 +3656,32 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) for(const auto& entry : entries) { - if (authId != entry.authId) continue; - else foundExisting = true; + if (authId != entry.authId) + { + continue; + } + else + { + foundExisting = true; + } if(name.length() < 1) { memset(oldName, 0, sizeof(oldName)); memcpy(oldName, entry.name, sizeof(entry.name)); } - if(remoteAllowed == 2) remoteAllowed = entry.remoteAllowed; - if(enabled == 2) enabled = entry.enabled; - if(timeLimited == 2) timeLimited = entry.timeLimited; + if(remoteAllowed == 2) + { + remoteAllowed = entry.remoteAllowed; + } + if(enabled == 2) + { + enabled = entry.enabled; + } + if(timeLimited == 2) + { + timeLimited = entry.timeLimited; + } if(allowedFrom.length() < 1) { allowedFrom = "old"; @@ -2736,7 +3702,10 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) allowedUntilAr[4] = entry.allowedUntilMinute; allowedUntilAr[5] = entry.allowedUntilSecond; } - if(allowedWeekdays.length() < 1) allowedWeekdaysInt = entry.allowedWeekdays; + if(allowedWeekdays.length() < 1) + { + allowedWeekdaysInt = entry.allowedWeekdays; + } if(allowedFromTime.length() < 1) { allowedFromTime = "old"; @@ -2834,10 +3803,14 @@ void NukiOpenerWrapper::onAuthCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } updateAuth(false); @@ -2902,10 +3875,14 @@ void NukiOpenerWrapper::readConfig() result = _nukiOpener.requestConfig(&_nukiConfig); _nukiConfigValid = result == Nuki::CmdResult::Success; - if(!_nukiConfigValid) { + if(!_nukiConfigValid) + { ++retryCount; } - else break; + else + { + break; + } } char resultStr[20]; @@ -2925,13 +3902,17 @@ void NukiOpenerWrapper::readAdvancedConfig() while(retryCount < _nrOfRetries + 1) { - result = _nukiOpener.requestAdvancedConfig(&_nukiAdvancedConfig); + result = _nukiOpener.requestAdvancedConfig(&_nukiAdvancedConfig); _nukiAdvancedConfigValid = result == Nuki::CmdResult::Success; - if(!_nukiAdvancedConfigValid) { + if(!_nukiAdvancedConfigValid) + { ++retryCount; } - else break; + else + { + break; + } } char resultStr[20]; @@ -2943,15 +3924,27 @@ void NukiOpenerWrapper::readAdvancedConfig() void NukiOpenerWrapper::setupHASS() { - if(!_nukiConfigValid) return; - if(_preferences->getUInt(preference_nuki_id_opener, 0) != _nukiConfig.nukiId) return; + if(!_nukiConfigValid) + { + return; + } + if(_preferences->getUInt(preference_nuki_id_opener, 0) != _nukiConfig.nukiId) + { + return; + } String baseTopic = _preferences->getString(preference_mqtt_opener_path); char uidString[20]; itoa(_nukiConfig.nukiId, uidString, 16); - if(_preferences->getBool(preference_opener_continuous_mode, false)) _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateCM", (char*)"activateCM", (char*)"electricStrikeActuation"); - else _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateRTO", (char*)"activateRTO", (char*)"electricStrikeActuation"); + if(_preferences->getBool(preference_opener_continuous_mode, false)) + { + _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateCM", (char*)"activateCM", (char*)"electricStrikeActuation"); + } + else + { + _network->publishHASSConfig((char*)"Opener", baseTopic.c_str(), (char*)_nukiConfig.name, uidString, _firmwareVersion.c_str(), _hardwareVersion.c_str(), _publishAuthData, _hasKeypad, (char*)"deactivateRTO", (char*)"activateRTO", (char*)"electricStrikeActuation"); + } _hassSetupCompleted = true; @@ -3002,15 +3995,15 @@ void NukiOpenerWrapper::updateGpioOutputs() { switch(entry.role) { - case PinRole::OutputHighRtoActive: - _gpio->setPinOutput(entry.pin, rtoActive ? HIGH : LOW); - break; - case PinRole::OutputHighCmActive: - _gpio->setPinOutput(entry.pin, cmActive ? HIGH : LOW); - break; - case PinRole::OutputHighRtoOrCmActive: - _gpio->setPinOutput(entry.pin, rtoActive || cmActive ? HIGH : LOW); - break; + case PinRole::OutputHighRtoActive: + _gpio->setPinOutput(entry.pin, rtoActive ? HIGH : LOW); + break; + case PinRole::OutputHighCmActive: + _gpio->setPinOutput(entry.pin, cmActive ? HIGH : LOW); + break; + case PinRole::OutputHighRtoOrCmActive: + _gpio->setPinOutput(entry.pin, rtoActive || cmActive ? HIGH : LOW); + break; } } } \ No newline at end of file diff --git a/src/NukiPublisher.cpp b/src/NukiPublisher.cpp index 78376ec..2ee3289 100644 --- a/src/NukiPublisher.cpp +++ b/src/NukiPublisher.cpp @@ -2,8 +2,8 @@ NukiPublisher::NukiPublisher(NukiNetwork *network, const char* mqttPath) -: _network(network), - _mqttPath(mqttPath) + : _network(network), + _mqttPath(mqttPath) { } diff --git a/src/NukiWrapper.cpp b/src/NukiWrapper.cpp index 4167aef..b710dc8 100644 --- a/src/NukiWrapper.cpp +++ b/src/NukiWrapper.cpp @@ -12,14 +12,14 @@ NukiWrapper* nukiInst = nullptr; NukiWrapper::NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkLock* network, NukiOfficial* nukiOfficial, Gpio* gpio, Preferences* preferences) -: _deviceName(deviceName), - _deviceId(deviceId), - _bleScanner(scanner), - _nukiLock(deviceName, _deviceId->get()), - _network(network), - _nukiOfficial(nukiOfficial), - _gpio(gpio), - _preferences(preferences) + : _deviceName(deviceName), + _deviceId(deviceId), + _bleScanner(scanner), + _nukiLock(deviceName, _deviceId->get()), + _network(network), + _nukiOfficial(nukiOfficial), + _gpio(gpio), + _preferences(preferences) { Log->print("Device id lock: "); Log->println(_deviceId->get()); @@ -61,24 +61,27 @@ void NukiWrapper::initialize(const bool& firstStart) if(firstStart) { Log->println("First start, setting preference defaults"); - - #ifndef CONFIG_IDF_TARGET_ESP32H2 + +#ifndef CONFIG_IDF_TARGET_ESP32H2 wifi_config_t wifi_cfg; - if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) { + if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { Log->println("Failed to get Wi-Fi configuration in RAM"); } - if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK) { + if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK) + { Log->println("Failed to set storage Wi-Fi"); } memset(wifi_cfg.sta.ssid, 0, sizeof(wifi_cfg.sta.ssid)); memset(wifi_cfg.sta.password, 0, sizeof(wifi_cfg.sta.password)); - if (esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) { + if (esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { Log->println("Failed to clear NVS Wi-Fi configuration"); } - #endif +#endif _preferences->putBool(preference_check_updates, true); _preferences->putBool(preference_opener_continuous_mode, false); _preferences->putBool(preference_official_hybrid_enabled, false); @@ -130,14 +133,38 @@ void NukiWrapper::readSettings() esp_power_level_t powerLevel; int pwrLvl = _preferences->getInt(preference_ble_tx_power, 9); - if(pwrLvl >= 9) powerLevel = ESP_PWR_LVL_P9; - else if(pwrLvl >= 6) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 3) powerLevel = ESP_PWR_LVL_P6; - else if(pwrLvl >= 0) powerLevel = ESP_PWR_LVL_P3; - else if(pwrLvl >= -3) powerLevel = ESP_PWR_LVL_N3; - else if(pwrLvl >= -6) powerLevel = ESP_PWR_LVL_N6; - else if(pwrLvl >= -9) powerLevel = ESP_PWR_LVL_N9; - else if(pwrLvl >= -12) powerLevel = ESP_PWR_LVL_N12; + if(pwrLvl >= 9) + { + powerLevel = ESP_PWR_LVL_P9; + } + else if(pwrLvl >= 6) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 3) + { + powerLevel = ESP_PWR_LVL_P6; + } + else if(pwrLvl >= 0) + { + powerLevel = ESP_PWR_LVL_P3; + } + else if(pwrLvl >= -3) + { + powerLevel = ESP_PWR_LVL_N3; + } + else if(pwrLvl >= -6) + { + powerLevel = ESP_PWR_LVL_N6; + } + else if(pwrLvl >= -9) + { + powerLevel = ESP_PWR_LVL_N9; + } + else if(pwrLvl >= -12) + { + powerLevel = ESP_PWR_LVL_N12; + } _nukiLock.setPower(powerLevel); @@ -252,10 +279,10 @@ void NukiWrapper::update() uint8_t queryCommands = _network->queryCommands(); if(_restartBeaconTimeout > 0 && - ts > 60000 && - lastReceivedBeaconTs > 0 && - _disableBleWatchdogTs < ts && - (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) + ts > 60000 && + lastReceivedBeaconTs > 0 && + _disableBleWatchdogTs < ts && + (ts - lastReceivedBeaconTs > _restartBeaconTimeout * 1000)) { Log->print("No BLE beacon received from the lock for "); Log->print((ts - lastReceivedBeaconTs) / 1000); @@ -309,9 +336,16 @@ void NukiWrapper::update() _nextLockAction = (NukiLock::LockAction) 0xff; _network->publishRetry("--"); retryCount = 0; - if(!_nukiOfficial->getOffConnected()) _statusUpdated = true; Log->println(F("Lock: updating status after action")); + if(!_nukiOfficial->getOffConnected()) + { + _statusUpdated = true; + } + Log->println(F("Lock: updating status after action")); _statusUpdatedTs = ts; - if(_intervalLockstate > 10) _nextLockStateUpdateTs = ts + 10 * 1000; + if(_intervalLockstate > 10) + { + _nextLockStateUpdateTs = ts + 10 * 1000; + } } else { @@ -496,13 +530,16 @@ void NukiWrapper::updateKeyTurnerState() const NukiLock::LockState& lockState = _keyTurnerState.lockState; - if(lockState != _lastKeyTurnerState.lockState) _statusUpdatedTs = esp_timer_get_time() / 1000; + if(lockState != _lastKeyTurnerState.lockState) + { + _statusUpdatedTs = esp_timer_get_time() / 1000; + } if(lockState == NukiLock::LockState::Locked || - lockState == NukiLock::LockState::Unlocked || - lockState == NukiLock::LockState::Calibration || - lockState == NukiLock::LockState::BootRun || - lockState == NukiLock::LockState::MotorBlocked) + lockState == NukiLock::LockState::Unlocked || + lockState == NukiLock::LockState::Calibration || + lockState == NukiLock::LockState::BootRun || + lockState == NukiLock::LockState::MotorBlocked) { if(_publishAuthData && (lockState == NukiLock::LockState::Locked || lockState == NukiLock::LockState::Unlocked)) { @@ -543,10 +580,14 @@ void NukiWrapper::updateBatteryState() Log->print("): "); result = _nukiLock.requestBatteryReport(&_batteryReport); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -583,13 +624,23 @@ void NukiWrapper::updateConfig() _hasKeypad = _nukiConfig.hasKeypad > 0 || _nukiConfig.hasKeypadV2 > 0; _firmwareVersion = std::to_string(_nukiConfig.firmwareVersion[0]) + "." + std::to_string(_nukiConfig.firmwareVersion[1]) + "." + std::to_string(_nukiConfig.firmwareVersion[2]); _hardwareVersion = std::to_string(_nukiConfig.hardwareRevision[0]) + "." + std::to_string(_nukiConfig.hardwareRevision[1]); - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishConfig(_nukiConfig); - if(_preferences->getBool(preference_timecontrol_info_enabled)) updateTimeControl(false); - if(_preferences->getBool(preference_auth_info_enabled)) updateAuth(false); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishConfig(_nukiConfig); + } + if(_preferences->getBool(preference_timecontrol_info_enabled)) + { + updateTimeControl(false); + } + if(_preferences->getBool(preference_auth_info_enabled)) + { + updateAuth(false); + } const int pinStatus = _preferences->getInt(preference_lock_pin_status, 4); - if(isPinSet()) { + if(isPinSet()) + { Nuki::CmdResult result = (Nuki::CmdResult)-1; int retryCount = 0; Log->println(F("Nuki Lock PIN is set")); @@ -597,23 +648,29 @@ void NukiWrapper::updateConfig() while(retryCount < _nrOfRetries + 1) { result = _nukiLock.verifySecurityPin(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if(result != Nuki::CmdResult::Success) { Log->println(F("Nuki Lock PIN is invalid")); - if(pinStatus != 2) { + if(pinStatus != 2) + { _preferences->putInt(preference_lock_pin_status, 2); } } else { Log->println(F("Nuki Lock PIN is valid")); - if(pinStatus != 1) { + if(pinStatus != 1) + { _preferences->putInt(preference_lock_pin_status, 1); } } @@ -621,7 +678,8 @@ void NukiWrapper::updateConfig() else { Log->println(F("Nuki Lock PIN is not set")); - if(pinStatus != 0) { + if(pinStatus != 0) + { _preferences->putInt(preference_lock_pin_status, 0); } } @@ -644,7 +702,10 @@ void NukiWrapper::updateConfig() if(_nukiAdvancedConfigValid) { - if(_preferences->getBool(preference_conf_info_enabled, true)) _network->publishAdvancedConfig(_nukiAdvancedConfig); + if(_preferences->getBool(preference_conf_info_enabled, true)) + { + _network->publishAdvancedConfig(_nukiAdvancedConfig); + } } else { @@ -684,10 +745,14 @@ void NukiWrapper::updateAuthData(bool retrieved) { Log->print(F("Retrieve log entries: ")); result = _nukiLock.retrieveLogEntries(0, _preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG), 1, false); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -704,11 +769,14 @@ void NukiWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, 3)); } - log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) + { + return a.index < b.index; + }); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, true); + _network->publishAuthorizationInfo(log, true); } } } @@ -722,14 +790,17 @@ void NukiWrapper::updateAuthData(bool retrieved) log.resize(_preferences->getInt(preference_authlog_max_entries, MAX_AUTHLOG)); } - log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) { return a.index < b.index; }); + log.sort([](const NukiLock::LogEntry& a, const NukiLock::LogEntry& b) + { + return a.index < b.index; + }); Log->print(F("Log size: ")); Log->println(log.size()); if(log.size() > 0) { - _network->publishAuthorizationInfo(log, false); + _network->publishAuthorizationInfo(log, false); } } @@ -738,7 +809,10 @@ void NukiWrapper::updateAuthData(bool retrieved) void NukiWrapper::updateKeypad(bool retrieved) { - if(!_preferences->getBool(preference_keypad_info_enabled)) return; + if(!_preferences->getBool(preference_keypad_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -755,10 +829,14 @@ void NukiWrapper::updateKeypad(bool retrieved) { Log->print(F("Querying lock keypad: ")); result = _nukiLock.retrieveKeypadEntries(0, _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -775,7 +853,10 @@ void NukiWrapper::updateKeypad(bool retrieved) Log->print(F("Lock keypad codes: ")); Log->println(entries.size()); - entries.sort([](const NukiLock::KeypadEntry& a, const NukiLock::KeypadEntry& b) { return a.codeId < b.codeId; }); + entries.sort([](const NukiLock::KeypadEntry& a, const NukiLock::KeypadEntry& b) + { + return a.codeId < b.codeId; + }); if(entries.size() > _preferences->getInt(preference_keypad_max_entries, MAX_KEYPAD)) { @@ -804,7 +885,10 @@ void NukiWrapper::updateKeypad(bool retrieved) void NukiWrapper::updateTimeControl(bool retrieved) { - if(!_preferences->getBool(preference_timecontrol_info_enabled)) return; + if(!_preferences->getBool(preference_timecontrol_info_enabled)) + { + return; + } if(!isPinValid()) { @@ -821,10 +905,14 @@ void NukiWrapper::updateTimeControl(bool retrieved) { Log->print(F("Querying lock timecontrol: ")); result = _nukiLock.retrieveTimeControlEntries(); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -841,7 +929,10 @@ void NukiWrapper::updateTimeControl(bool retrieved) Log->print(F("Lock timecontrol entries: ")); Log->println(timeControlEntries.size()); - timeControlEntries.sort([](const NukiLock::TimeControlEntry& a, const NukiLock::TimeControlEntry& b) { return a.entryId < b.entryId; }); + timeControlEntries.sort([](const NukiLock::TimeControlEntry& a, const NukiLock::TimeControlEntry& b) + { + return a.entryId < b.entryId; + }); if(timeControlEntries.size() > _preferences->getInt(preference_timecontrol_max_entries, MAX_TIMECONTROL)) { @@ -870,7 +961,10 @@ void NukiWrapper::updateTimeControl(bool retrieved) void NukiWrapper::updateAuth(bool retrieved) { - if(!_preferences->getBool(preference_auth_info_enabled)) return; + if(!_preferences->getBool(preference_auth_info_enabled)) + { + return; + } if(!retrieved) { @@ -882,10 +976,14 @@ void NukiWrapper::updateAuth(bool retrieved) Log->print(F("Querying lock authorization: ")); result = _nukiLock.retrieveAuthorizationEntries(0, _preferences->getInt(preference_auth_max_entries, MAX_AUTH)); delay(250); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } printCommandResult(result); @@ -902,7 +1000,10 @@ void NukiWrapper::updateAuth(bool retrieved) Log->print(F("Lock authorization entries: ")); Log->println(authEntries.size()); - authEntries.sort([](const NukiLock::AuthorizationEntry& a, const NukiLock::AuthorizationEntry& b) { return a.authId < b.authId; }); + authEntries.sort([](const NukiLock::AuthorizationEntry& a, const NukiLock::AuthorizationEntry& b) + { + return a.authId < b.authId; + }); if(authEntries.size() > _preferences->getInt(preference_auth_max_entries, MAX_AUTH)) { @@ -936,15 +1037,42 @@ void NukiWrapper::postponeBleWatchdog() NukiLock::LockAction NukiWrapper::lockActionToEnum(const char *str) { - if(strcmp(str, "unlock") == 0 || strcmp(str, "Unlock") == 0) return NukiLock::LockAction::Unlock; - else if(strcmp(str, "lock") == 0 || strcmp(str, "Lock") == 0) return NukiLock::LockAction::Lock; - else if(strcmp(str, "unlatch") == 0 || strcmp(str, "Unlatch") == 0) return NukiLock::LockAction::Unlatch; - else if(strcmp(str, "lockNgo") == 0 || strcmp(str, "LockNgo") == 0) return NukiLock::LockAction::LockNgo; - else if(strcmp(str, "lockNgoUnlatch") == 0 || strcmp(str, "LockNgoUnlatch") == 0) return NukiLock::LockAction::LockNgoUnlatch; - else if(strcmp(str, "fullLock") == 0 || strcmp(str, "FullLock") == 0) return NukiLock::LockAction::FullLock; - else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) return NukiLock::LockAction::FobAction2; - else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) return NukiLock::LockAction::FobAction1; - else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) return NukiLock::LockAction::FobAction3; + if(strcmp(str, "unlock") == 0 || strcmp(str, "Unlock") == 0) + { + return NukiLock::LockAction::Unlock; + } + else if(strcmp(str, "lock") == 0 || strcmp(str, "Lock") == 0) + { + return NukiLock::LockAction::Lock; + } + else if(strcmp(str, "unlatch") == 0 || strcmp(str, "Unlatch") == 0) + { + return NukiLock::LockAction::Unlatch; + } + else if(strcmp(str, "lockNgo") == 0 || strcmp(str, "LockNgo") == 0) + { + return NukiLock::LockAction::LockNgo; + } + else if(strcmp(str, "lockNgoUnlatch") == 0 || strcmp(str, "LockNgoUnlatch") == 0) + { + return NukiLock::LockAction::LockNgoUnlatch; + } + else if(strcmp(str, "fullLock") == 0 || strcmp(str, "FullLock") == 0) + { + return NukiLock::LockAction::FullLock; + } + else if(strcmp(str, "fobAction2") == 0 || strcmp(str, "FobAction2") == 0) + { + return NukiLock::LockAction::FobAction2; + } + else if(strcmp(str, "fobAction1") == 0 || strcmp(str, "FobAction1") == 0) + { + return NukiLock::LockAction::FobAction1; + } + else if(strcmp(str, "fobAction3") == 0 || strcmp(str, "FobAction3") == 0) + { + return NukiLock::LockAction::FobAction3; + } return (NukiLock::LockAction)0xff; } @@ -962,18 +1090,30 @@ LockActionResult NukiWrapper::onLockActionReceived(const char *value) if(strlen(value) > 0) { action = nukiInst->lockActionToEnum(value); - if((int)action == 0xff) return LockActionResult::UnknownAction; + if((int)action == 0xff) + { + return LockActionResult::UnknownAction; + } + } + else + { + return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; } - else return LockActionResult::UnknownAction; + else + { + return LockActionResult::UnknownAction; + } uint32_t aclPrefs[17]; _preferences->getBytes(preference_acl, &aclPrefs, sizeof(aclPrefs)); if((action == NukiLock::LockAction::Lock && (int)aclPrefs[0] == 1) || (action == NukiLock::LockAction::Unlock && (int)aclPrefs[1] == 1) || (action == NukiLock::LockAction::Unlatch && (int)aclPrefs[2] == 1) || (action == NukiLock::LockAction::LockNgo && (int)aclPrefs[3] == 1) || (action == NukiLock::LockAction::LockNgoUnlatch && (int)aclPrefs[4] == 1) || (action == NukiLock::LockAction::FullLock && (int)aclPrefs[5] == 1) || (action == NukiLock::LockAction::FobAction1 && (int)aclPrefs[6] == 1) || (action == NukiLock::LockAction::FobAction2 && (int)aclPrefs[7] == 1) || (action == NukiLock::LockAction::FobAction3 && (int)aclPrefs[8] == 1)) { - if(!_nukiOfficial->getOffConnected()) nukiInst->_nextLockAction = action; + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->_nextLockAction = action; + } else { if(_preferences->getBool(preference_official_hybrid_actions, false)) @@ -1010,92 +1150,290 @@ bool NukiWrapper::offConnected() Nuki::AdvertisingMode NukiWrapper::advertisingModeToEnum(const char *str) { - if(strcmp(str, "Automatic") == 0) return Nuki::AdvertisingMode::Automatic; - else if(strcmp(str, "Normal") == 0) return Nuki::AdvertisingMode::Normal; - else if(strcmp(str, "Slow") == 0) return Nuki::AdvertisingMode::Slow; - else if(strcmp(str, "Slowest") == 0) return Nuki::AdvertisingMode::Slowest; + if(strcmp(str, "Automatic") == 0) + { + return Nuki::AdvertisingMode::Automatic; + } + else if(strcmp(str, "Normal") == 0) + { + return Nuki::AdvertisingMode::Normal; + } + else if(strcmp(str, "Slow") == 0) + { + return Nuki::AdvertisingMode::Slow; + } + else if(strcmp(str, "Slowest") == 0) + { + return Nuki::AdvertisingMode::Slowest; + } return (Nuki::AdvertisingMode)0xff; } Nuki::TimeZoneId NukiWrapper::timeZoneToEnum(const char *str) { - if(strcmp(str, "Africa/Cairo") == 0) return Nuki::TimeZoneId::Africa_Cairo; - else if(strcmp(str, "Africa/Lagos") == 0) return Nuki::TimeZoneId::Africa_Lagos; - else if(strcmp(str, "Africa/Maputo") == 0) return Nuki::TimeZoneId::Africa_Maputo; - else if(strcmp(str, "Africa/Nairobi") == 0) return Nuki::TimeZoneId::Africa_Nairobi; - else if(strcmp(str, "America/Anchorage") == 0) return Nuki::TimeZoneId::America_Anchorage; - else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; - else if(strcmp(str, "America/Chicago") == 0) return Nuki::TimeZoneId::America_Chicago; - else if(strcmp(str, "America/Denver") == 0) return Nuki::TimeZoneId::America_Denver; - else if(strcmp(str, "America/Halifax") == 0) return Nuki::TimeZoneId::America_Halifax; - else if(strcmp(str, "America/Los_Angeles") == 0) return Nuki::TimeZoneId::America_Los_Angeles; - else if(strcmp(str, "America/Manaus") == 0) return Nuki::TimeZoneId::America_Manaus; - else if(strcmp(str, "America/Mexico_City") == 0) return Nuki::TimeZoneId::America_Mexico_City; - else if(strcmp(str, "America/New_York") == 0) return Nuki::TimeZoneId::America_New_York; - else if(strcmp(str, "America/Phoenix") == 0) return Nuki::TimeZoneId::America_Phoenix; - else if(strcmp(str, "America/Regina") == 0) return Nuki::TimeZoneId::America_Regina; - else if(strcmp(str, "America/Santiago") == 0) return Nuki::TimeZoneId::America_Santiago; - else if(strcmp(str, "America/Sao_Paulo") == 0) return Nuki::TimeZoneId::America_Sao_Paulo; - else if(strcmp(str, "America/St_Johns") == 0) return Nuki::TimeZoneId::America_St_Johns; - else if(strcmp(str, "Asia/Bangkok") == 0) return Nuki::TimeZoneId::Asia_Bangkok; - else if(strcmp(str, "Asia/Dubai") == 0) return Nuki::TimeZoneId::Asia_Dubai; - else if(strcmp(str, "Asia/Hong_Kong") == 0) return Nuki::TimeZoneId::Asia_Hong_Kong; - else if(strcmp(str, "Asia/Jerusalem") == 0) return Nuki::TimeZoneId::Asia_Jerusalem; - else if(strcmp(str, "Asia/Karachi") == 0) return Nuki::TimeZoneId::Asia_Karachi; - else if(strcmp(str, "Asia/Kathmandu") == 0) return Nuki::TimeZoneId::Asia_Kathmandu; - else if(strcmp(str, "Asia/Kolkata") == 0) return Nuki::TimeZoneId::Asia_Kolkata; - else if(strcmp(str, "Asia/Riyadh") == 0) return Nuki::TimeZoneId::Asia_Riyadh; - else if(strcmp(str, "Asia/Seoul") == 0) return Nuki::TimeZoneId::Asia_Seoul; - else if(strcmp(str, "Asia/Shanghai") == 0) return Nuki::TimeZoneId::Asia_Shanghai; - else if(strcmp(str, "Asia/Tehran") == 0) return Nuki::TimeZoneId::Asia_Tehran; - else if(strcmp(str, "Asia/Tokyo") == 0) return Nuki::TimeZoneId::Asia_Tokyo; - else if(strcmp(str, "Asia/Yangon") == 0) return Nuki::TimeZoneId::Asia_Yangon; - else if(strcmp(str, "Australia/Adelaide") == 0) return Nuki::TimeZoneId::Australia_Adelaide; - else if(strcmp(str, "Australia/Brisbane") == 0) return Nuki::TimeZoneId::Australia_Brisbane; - else if(strcmp(str, "Australia/Darwin") == 0) return Nuki::TimeZoneId::Australia_Darwin; - else if(strcmp(str, "Australia/Hobart") == 0) return Nuki::TimeZoneId::Australia_Hobart; - else if(strcmp(str, "Australia/Perth") == 0) return Nuki::TimeZoneId::Australia_Perth; - else if(strcmp(str, "Australia/Sydney") == 0) return Nuki::TimeZoneId::Australia_Sydney; - else if(strcmp(str, "Europe/Berlin") == 0) return Nuki::TimeZoneId::Europe_Berlin; - else if(strcmp(str, "Europe/Helsinki") == 0) return Nuki::TimeZoneId::Europe_Helsinki; - else if(strcmp(str, "Europe/Istanbul") == 0) return Nuki::TimeZoneId::Europe_Istanbul; - else if(strcmp(str, "Europe/London") == 0) return Nuki::TimeZoneId::Europe_London; - else if(strcmp(str, "Europe/Moscow") == 0) return Nuki::TimeZoneId::Europe_Moscow; - else if(strcmp(str, "Pacific/Auckland") == 0) return Nuki::TimeZoneId::Pacific_Auckland; - else if(strcmp(str, "Pacific/Guam") == 0) return Nuki::TimeZoneId::Pacific_Guam; - else if(strcmp(str, "Pacific/Honolulu") == 0) return Nuki::TimeZoneId::Pacific_Honolulu; - else if(strcmp(str, "Pacific/Pago_Pago") == 0) return Nuki::TimeZoneId::Pacific_Pago_Pago; - else if(strcmp(str, "None") == 0) return Nuki::TimeZoneId::None; + if(strcmp(str, "Africa/Cairo") == 0) + { + return Nuki::TimeZoneId::Africa_Cairo; + } + else if(strcmp(str, "Africa/Lagos") == 0) + { + return Nuki::TimeZoneId::Africa_Lagos; + } + else if(strcmp(str, "Africa/Maputo") == 0) + { + return Nuki::TimeZoneId::Africa_Maputo; + } + else if(strcmp(str, "Africa/Nairobi") == 0) + { + return Nuki::TimeZoneId::Africa_Nairobi; + } + else if(strcmp(str, "America/Anchorage") == 0) + { + return Nuki::TimeZoneId::America_Anchorage; + } + else if(strcmp(str, "America/Argentina/Buenos_Aires") == 0) + { + return Nuki::TimeZoneId::America_Argentina_Buenos_Aires; + } + else if(strcmp(str, "America/Chicago") == 0) + { + return Nuki::TimeZoneId::America_Chicago; + } + else if(strcmp(str, "America/Denver") == 0) + { + return Nuki::TimeZoneId::America_Denver; + } + else if(strcmp(str, "America/Halifax") == 0) + { + return Nuki::TimeZoneId::America_Halifax; + } + else if(strcmp(str, "America/Los_Angeles") == 0) + { + return Nuki::TimeZoneId::America_Los_Angeles; + } + else if(strcmp(str, "America/Manaus") == 0) + { + return Nuki::TimeZoneId::America_Manaus; + } + else if(strcmp(str, "America/Mexico_City") == 0) + { + return Nuki::TimeZoneId::America_Mexico_City; + } + else if(strcmp(str, "America/New_York") == 0) + { + return Nuki::TimeZoneId::America_New_York; + } + else if(strcmp(str, "America/Phoenix") == 0) + { + return Nuki::TimeZoneId::America_Phoenix; + } + else if(strcmp(str, "America/Regina") == 0) + { + return Nuki::TimeZoneId::America_Regina; + } + else if(strcmp(str, "America/Santiago") == 0) + { + return Nuki::TimeZoneId::America_Santiago; + } + else if(strcmp(str, "America/Sao_Paulo") == 0) + { + return Nuki::TimeZoneId::America_Sao_Paulo; + } + else if(strcmp(str, "America/St_Johns") == 0) + { + return Nuki::TimeZoneId::America_St_Johns; + } + else if(strcmp(str, "Asia/Bangkok") == 0) + { + return Nuki::TimeZoneId::Asia_Bangkok; + } + else if(strcmp(str, "Asia/Dubai") == 0) + { + return Nuki::TimeZoneId::Asia_Dubai; + } + else if(strcmp(str, "Asia/Hong_Kong") == 0) + { + return Nuki::TimeZoneId::Asia_Hong_Kong; + } + else if(strcmp(str, "Asia/Jerusalem") == 0) + { + return Nuki::TimeZoneId::Asia_Jerusalem; + } + else if(strcmp(str, "Asia/Karachi") == 0) + { + return Nuki::TimeZoneId::Asia_Karachi; + } + else if(strcmp(str, "Asia/Kathmandu") == 0) + { + return Nuki::TimeZoneId::Asia_Kathmandu; + } + else if(strcmp(str, "Asia/Kolkata") == 0) + { + return Nuki::TimeZoneId::Asia_Kolkata; + } + else if(strcmp(str, "Asia/Riyadh") == 0) + { + return Nuki::TimeZoneId::Asia_Riyadh; + } + else if(strcmp(str, "Asia/Seoul") == 0) + { + return Nuki::TimeZoneId::Asia_Seoul; + } + else if(strcmp(str, "Asia/Shanghai") == 0) + { + return Nuki::TimeZoneId::Asia_Shanghai; + } + else if(strcmp(str, "Asia/Tehran") == 0) + { + return Nuki::TimeZoneId::Asia_Tehran; + } + else if(strcmp(str, "Asia/Tokyo") == 0) + { + return Nuki::TimeZoneId::Asia_Tokyo; + } + else if(strcmp(str, "Asia/Yangon") == 0) + { + return Nuki::TimeZoneId::Asia_Yangon; + } + else if(strcmp(str, "Australia/Adelaide") == 0) + { + return Nuki::TimeZoneId::Australia_Adelaide; + } + else if(strcmp(str, "Australia/Brisbane") == 0) + { + return Nuki::TimeZoneId::Australia_Brisbane; + } + else if(strcmp(str, "Australia/Darwin") == 0) + { + return Nuki::TimeZoneId::Australia_Darwin; + } + else if(strcmp(str, "Australia/Hobart") == 0) + { + return Nuki::TimeZoneId::Australia_Hobart; + } + else if(strcmp(str, "Australia/Perth") == 0) + { + return Nuki::TimeZoneId::Australia_Perth; + } + else if(strcmp(str, "Australia/Sydney") == 0) + { + return Nuki::TimeZoneId::Australia_Sydney; + } + else if(strcmp(str, "Europe/Berlin") == 0) + { + return Nuki::TimeZoneId::Europe_Berlin; + } + else if(strcmp(str, "Europe/Helsinki") == 0) + { + return Nuki::TimeZoneId::Europe_Helsinki; + } + else if(strcmp(str, "Europe/Istanbul") == 0) + { + return Nuki::TimeZoneId::Europe_Istanbul; + } + else if(strcmp(str, "Europe/London") == 0) + { + return Nuki::TimeZoneId::Europe_London; + } + else if(strcmp(str, "Europe/Moscow") == 0) + { + return Nuki::TimeZoneId::Europe_Moscow; + } + else if(strcmp(str, "Pacific/Auckland") == 0) + { + return Nuki::TimeZoneId::Pacific_Auckland; + } + else if(strcmp(str, "Pacific/Guam") == 0) + { + return Nuki::TimeZoneId::Pacific_Guam; + } + else if(strcmp(str, "Pacific/Honolulu") == 0) + { + return Nuki::TimeZoneId::Pacific_Honolulu; + } + else if(strcmp(str, "Pacific/Pago_Pago") == 0) + { + return Nuki::TimeZoneId::Pacific_Pago_Pago; + } + else if(strcmp(str, "None") == 0) + { + return Nuki::TimeZoneId::None; + } return (Nuki::TimeZoneId)0xff; } uint8_t NukiWrapper::fobActionToInt(const char *str) { - if(strcmp(str, "No Action") == 0) return 0; - else if(strcmp(str, "Unlock") == 0) return 1; - else if(strcmp(str, "Lock") == 0) return 2; - else if(strcmp(str, "Lock n Go") == 0) return 3; - else if(strcmp(str, "Intelligent") == 0) return 4; + if(strcmp(str, "No Action") == 0) + { + return 0; + } + else if(strcmp(str, "Unlock") == 0) + { + return 1; + } + else if(strcmp(str, "Lock") == 0) + { + return 2; + } + else if(strcmp(str, "Lock n Go") == 0) + { + return 3; + } + else if(strcmp(str, "Intelligent") == 0) + { + return 4; + } return 99; } NukiLock::ButtonPressAction NukiWrapper::buttonPressActionToEnum(const char* str) { - if(strcmp(str, "No Action") == 0) return NukiLock::ButtonPressAction::NoAction; - else if(strcmp(str, "Intelligent") == 0) return NukiLock::ButtonPressAction::Intelligent; - else if(strcmp(str, "Unlock") == 0) return NukiLock::ButtonPressAction::Unlock; - else if(strcmp(str, "Lock") == 0) return NukiLock::ButtonPressAction::Lock; - else if(strcmp(str, "Unlatch") == 0) return NukiLock::ButtonPressAction::Unlatch; - else if(strcmp(str, "Lock n Go") == 0) return NukiLock::ButtonPressAction::LockNgo; - else if(strcmp(str, "Show Status") == 0) return NukiLock::ButtonPressAction::ShowStatus; + if(strcmp(str, "No Action") == 0) + { + return NukiLock::ButtonPressAction::NoAction; + } + else if(strcmp(str, "Intelligent") == 0) + { + return NukiLock::ButtonPressAction::Intelligent; + } + else if(strcmp(str, "Unlock") == 0) + { + return NukiLock::ButtonPressAction::Unlock; + } + else if(strcmp(str, "Lock") == 0) + { + return NukiLock::ButtonPressAction::Lock; + } + else if(strcmp(str, "Unlatch") == 0) + { + return NukiLock::ButtonPressAction::Unlatch; + } + else if(strcmp(str, "Lock n Go") == 0) + { + return NukiLock::ButtonPressAction::LockNgo; + } + else if(strcmp(str, "Show Status") == 0) + { + return NukiLock::ButtonPressAction::ShowStatus; + } return (NukiLock::ButtonPressAction)0xff; } Nuki::BatteryType NukiWrapper::batteryTypeToEnum(const char* str) { - if(strcmp(str, "Alkali") == 0) return Nuki::BatteryType::Alkali; - else if(strcmp(str, "Accumulators") == 0) return Nuki::BatteryType::Accumulators; - else if(strcmp(str, "Lithium") == 0) return Nuki::BatteryType::Lithium; + if(strcmp(str, "Alkali") == 0) + { + return Nuki::BatteryType::Alkali; + } + else if(strcmp(str, "Accumulators") == 0) + { + return Nuki::BatteryType::Accumulators; + } + else if(strcmp(str, "Lithium") == 0) + { + return Nuki::BatteryType::Lithium; + } return (Nuki::BatteryType)0xff; } @@ -1165,10 +1503,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) { if(strlen(jsonchar) <= 32) { - if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setName(std::string(jsonchar)); + if(strcmp((const char*)_nukiConfig.name, jsonchar) == 0) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setName(std::string(jsonchar)); + } + } + else + { + jsonResult[basicKeys[i]] = "valueTooLong"; } - else jsonResult[basicKeys[i]] = "valueTooLong"; } else if(strcmp(basicKeys[i], "latitude") == 0) { @@ -1176,10 +1523,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.latitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setLatitude(keyvalue); + if(_nukiConfig.latitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLatitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "longitude") == 0) { @@ -1187,10 +1543,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue > 0) { - if(_nukiConfig.longitude == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setLongitude(keyvalue); + if(_nukiConfig.longitude == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLongitude(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "autoUnlatch") == 0) { @@ -1198,10 +1563,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.autoUnlatch == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoUnlatch((keyvalue > 0)); + if(_nukiConfig.autoUnlatch == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoUnlatch((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "pairingEnabled") == 0) { @@ -1209,10 +1583,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.pairingEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enablePairing((keyvalue > 0)); + if(_nukiConfig.pairingEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enablePairing((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "buttonEnabled") == 0) { @@ -1220,10 +1603,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.buttonEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableButton((keyvalue > 0)); + if(_nukiConfig.buttonEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableButton((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "ledEnabled") == 0) { @@ -1231,10 +1623,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.ledEnabled == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableLedFlash((keyvalue > 0)); + if(_nukiConfig.ledEnabled == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableLedFlash((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "ledBrightness") == 0) { @@ -1242,10 +1643,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 5) { - if(_nukiConfig.ledBrightness == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setLedBrightness(keyvalue); + if(_nukiConfig.ledBrightness == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLedBrightness(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZoneOffset") == 0) { @@ -1253,10 +1663,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 0 && keyvalue <= 60) { - if(_nukiConfig.timeZoneOffset == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setTimeZoneOffset(keyvalue); + if(_nukiConfig.timeZoneOffset == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setTimeZoneOffset(keyvalue); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "dstMode") == 0) { @@ -1264,10 +1683,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.dstMode == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableDst((keyvalue > 0)); + if(_nukiConfig.dstMode == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableDst((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction1") == 0) { @@ -1275,10 +1703,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(fobAct1 != 99) { - if(_nukiConfig.fobAction1 == fobAct1) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setFobAction(1, fobAct1); + if(_nukiConfig.fobAction1 == fobAct1) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setFobAction(1, fobAct1); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction2") == 0) { @@ -1286,10 +1723,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(fobAct2 != 99) { - if(_nukiConfig.fobAction2 == fobAct2) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setFobAction(2, fobAct2); + if(_nukiConfig.fobAction2 == fobAct2) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setFobAction(2, fobAct2); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "fobAction3") == 0) { @@ -1297,10 +1743,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(fobAct3 != 99) { - if(_nukiConfig.fobAction3 == fobAct3) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setFobAction(3, fobAct3); + if(_nukiConfig.fobAction3 == fobAct3) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setFobAction(3, fobAct3); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "singleLock") == 0) { @@ -1308,10 +1763,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiConfig.singleLock == keyvalue) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.enableSingleLock((keyvalue > 0)); + if(_nukiConfig.singleLock == keyvalue) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableSingleLock((keyvalue > 0)); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "advertisingMode") == 0) { @@ -1319,10 +1783,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)advmode != 0xff) { - if(_nukiConfig.advertisingMode == advmode) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setAdvertisingMode(advmode); + if(_nukiConfig.advertisingMode == advmode) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setAdvertisingMode(advmode); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } else if(strcmp(basicKeys[i], "timeZone") == 0) { @@ -1330,27 +1803,47 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)tzid != 0xff) { - if(_nukiConfig.timeZoneId == tzid) jsonResult[basicKeys[i]] = "unchanged"; - else cmdResult = _nukiLock.setTimeZoneId(tzid); + if(_nukiConfig.timeZoneId == tzid) + { + jsonResult[basicKeys[i]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setTimeZoneId(tzid); + } + } + else + { + jsonResult[basicKeys[i]] = "invalidValue"; } - else jsonResult[basicKeys[i]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + if(cmdResult != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) basicUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + basicUpdated = true; + } - if(!jsonResult[basicKeys[i]]) { + if(!jsonResult[basicKeys[i]]) + { char resultStr[15] = {0}; NukiLock::cmdResultToString(cmdResult, resultStr); jsonResult[basicKeys[i]] = resultStr; } } - else jsonResult[basicKeys[i]] = "accessDenied"; + else + { + jsonResult[basicKeys[i]] = "accessDenied"; + } } } @@ -1379,10 +1872,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -90 && keyvalue <= 180) { - if(_nukiAdvancedConfig.unlockedPositionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setUnlockedPositionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.unlockedPositionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setUnlockedPositionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "lockedPositionOffsetDegrees") == 0) { @@ -1390,10 +1892,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -180 && keyvalue <= 90) { - if(_nukiAdvancedConfig.lockedPositionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setLockedPositionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.lockedPositionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLockedPositionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "singleLockedPositionOffsetDegrees") == 0) { @@ -1401,10 +1912,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -180 && keyvalue <= 180) { - if(_nukiAdvancedConfig.singleLockedPositionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setSingleLockedPositionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.singleLockedPositionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setSingleLockedPositionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "unlockedToLockedTransitionOffsetDegrees") == 0) { @@ -1412,10 +1932,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= -180 && keyvalue <= 180) { - if(_nukiAdvancedConfig.unlockedToLockedTransitionOffsetDegrees == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setUnlockedToLockedTransitionOffsetDegrees(keyvalue); + if(_nukiAdvancedConfig.unlockedToLockedTransitionOffsetDegrees == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setUnlockedToLockedTransitionOffsetDegrees(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "lockNgoTimeout") == 0) { @@ -1423,10 +1952,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 5 && keyvalue <= 60) { - if(_nukiAdvancedConfig.lockNgoTimeout == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setLockNgoTimeout(keyvalue); + if(_nukiAdvancedConfig.lockNgoTimeout == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setLockNgoTimeout(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "singleButtonPressAction") == 0) { @@ -1434,10 +1972,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)sbpa != 0xff) { - if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setSingleButtonPressAction(sbpa); + if(_nukiAdvancedConfig.singleButtonPressAction == sbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setSingleButtonPressAction(sbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "doubleButtonPressAction") == 0) { @@ -1445,10 +1992,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)dbpa != 0xff) { - if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setDoubleButtonPressAction(dbpa); + if(_nukiAdvancedConfig.doubleButtonPressAction == dbpa) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setDoubleButtonPressAction(dbpa); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "detachedCylinder") == 0) { @@ -1456,10 +2012,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.detachedCylinder == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableDetachedCylinder((keyvalue > 0)); + if(_nukiAdvancedConfig.detachedCylinder == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableDetachedCylinder((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "batteryType") == 0) { @@ -1467,10 +2032,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if((int)battype != 0xff) { - if(_nukiAdvancedConfig.batteryType == battype) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setBatteryType(battype); + if(_nukiAdvancedConfig.batteryType == battype) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setBatteryType(battype); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "automaticBatteryTypeDetection") == 0) { @@ -1478,10 +2052,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoBatteryTypeDetection((keyvalue > 0)); + if(_nukiAdvancedConfig.automaticBatteryTypeDetection == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoBatteryTypeDetection((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "unlatchDuration") == 0) { @@ -1489,10 +2072,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 1 && keyvalue <= 30) { - if(_nukiAdvancedConfig.unlatchDuration == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setUnlatchDuration(keyvalue); + if(_nukiAdvancedConfig.unlatchDuration == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setUnlatchDuration(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoLockTimeOut") == 0) { @@ -1500,10 +2092,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue >= 30 && keyvalue <= 1800) { - if(_nukiAdvancedConfig.autoLockTimeOut == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setAutoLockTimeOut(keyvalue); + if(_nukiAdvancedConfig.autoLockTimeOut == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setAutoLockTimeOut(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoUnLockDisabled") == 0) { @@ -1511,10 +2112,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.autoUnLockDisabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.disableAutoUnlock((keyvalue > 0)); + if(_nukiAdvancedConfig.autoUnLockDisabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.disableAutoUnlock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeEnabled") == 0) { @@ -1522,10 +2132,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableNightMode((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableNightMode((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeStartTime") == 0) { @@ -1535,10 +2154,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) keyvalue[1] = (uint8_t)keystr.substring(3, 5).toInt(); if(keyvalue[0] >= 0 && keyvalue[0] <= 23 && keyvalue[1] >= 0 && keyvalue[1] <= 59) { - if(_nukiAdvancedConfig.nightModeStartTime == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setNightModeStartTime(keyvalue); + if(_nukiAdvancedConfig.nightModeStartTime == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setNightModeStartTime(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeEndTime") == 0) { @@ -1548,10 +2176,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) keyvalue[1] = (uint8_t)keystr.substring(3, 5).toInt(); if(keyvalue[0] >= 0 && keyvalue[0] <= 23 && keyvalue[1] >= 0 && keyvalue[1] <= 59) { - if(_nukiAdvancedConfig.nightModeEndTime == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.setNightModeEndTime(keyvalue); + if(_nukiAdvancedConfig.nightModeEndTime == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.setNightModeEndTime(keyvalue); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeAutoLockEnabled") == 0) { @@ -1559,10 +2196,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeAutoLockEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableNightModeAutoLock((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeAutoLockEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableNightModeAutoLock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeAutoUnlockDisabled") == 0) { @@ -1570,10 +2216,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeAutoUnlockDisabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.disableNightModeAutoUnlock((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeAutoUnlockDisabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.disableNightModeAutoUnlock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "nightModeImmediateLockOnStart") == 0) { @@ -1581,10 +2236,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.nightModeImmediateLockOnStart == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableNightModeImmediateLockOnStart((keyvalue > 0)); + if(_nukiAdvancedConfig.nightModeImmediateLockOnStart == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableNightModeImmediateLockOnStart((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoLockEnabled") == 0) { @@ -1592,10 +2256,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.autoLockEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoLock((keyvalue > 0)); + if(_nukiAdvancedConfig.autoLockEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoLock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "immediateAutoLockEnabled") == 0) { @@ -1603,10 +2276,19 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.immediateAutoLockEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableImmediateAutoLock((keyvalue > 0)); + if(_nukiAdvancedConfig.immediateAutoLockEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableImmediateAutoLock((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } else if(strcmp(advancedKeys[j], "autoUpdateEnabled") == 0) { @@ -1614,32 +2296,58 @@ void NukiWrapper::onConfigUpdateReceived(const char *value) if(keyvalue == 0 || keyvalue == 1) { - if(_nukiAdvancedConfig.autoUpdateEnabled == keyvalue) jsonResult[advancedKeys[j]] = "unchanged"; - else cmdResult = _nukiLock.enableAutoUpdate((keyvalue > 0)); + if(_nukiAdvancedConfig.autoUpdateEnabled == keyvalue) + { + jsonResult[advancedKeys[j]] = "unchanged"; + } + else + { + cmdResult = _nukiLock.enableAutoUpdate((keyvalue > 0)); + } + } + else + { + jsonResult[advancedKeys[j]] = "invalidValue"; } - else jsonResult[advancedKeys[j]] = "invalidValue"; } - if(cmdResult != Nuki::CmdResult::Success) { + if(cmdResult != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } - if(cmdResult == Nuki::CmdResult::Success) advancedUpdated = true; + if(cmdResult == Nuki::CmdResult::Success) + { + advancedUpdated = true; + } - if(!jsonResult[advancedKeys[j]]) { + if(!jsonResult[advancedKeys[j]]) + { char resultStr[15] = {0}; NukiLock::cmdResultToString(cmdResult, resultStr); jsonResult[advancedKeys[j]] = resultStr; } } - else jsonResult[advancedKeys[j]] = "accessDenied"; + else + { + jsonResult[advancedKeys[j]] = "accessDenied"; + } } } - if(basicUpdated || advancedUpdated) jsonResult["general"] = "success"; - else jsonResult["general"] = "noChange"; + if(basicUpdated || advancedUpdated) + { + jsonResult["general"] = "success"; + } + else + { + jsonResult["general"] = "noChange"; + } _nextConfigUpdateTs = (esp_timer_get_time() / 1000) + 300; @@ -1679,57 +2387,75 @@ void NukiWrapper::onGpioActionReceived(const GpioAction &action, const int &pin) { switch(action) { - case GpioAction::Lock: - if(!_nukiOfficial->getOffConnected()) nukiInst->lock(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::Lock; - _network->publishOffAction(2); - } - break; - case GpioAction::Unlock: - if(!_nukiOfficial->getOffConnected()) nukiInst->unlock(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::Unlock; - _network->publishOffAction(1); - } - break; - case GpioAction::Unlatch: - if(!_nukiOfficial->getOffConnected()) nukiInst->unlatch(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::Unlatch; - _network->publishOffAction(3); - } - break; - case GpioAction::LockNgo: - if(!_nukiOfficial->getOffConnected()) nukiInst->lockngo(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::LockNgo; - _network->publishOffAction(4); - } - break; - case GpioAction::LockNgoUnlatch: - if(!_nukiOfficial->getOffConnected()) nukiInst->lockngounlatch(); - else - { - _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); - _offCommand = NukiLock::LockAction::LockNgoUnlatch; - _network->publishOffAction(5); - } - break; + case GpioAction::Lock: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->lock(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); + _offCommand = NukiLock::LockAction::Lock; + _network->publishOffAction(2); + } + break; + case GpioAction::Unlock: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->unlock(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); + _offCommand = NukiLock::LockAction::Unlock; + _network->publishOffAction(1); + } + break; + case GpioAction::Unlatch: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->unlatch(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); + _offCommand = NukiLock::LockAction::Unlatch; + _network->publishOffAction(3); + } + break; + case GpioAction::LockNgo: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->lockngo(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); + _offCommand = NukiLock::LockAction::LockNgo; + _network->publishOffAction(4); + } + break; + case GpioAction::LockNgoUnlatch: + if(!_nukiOfficial->getOffConnected()) + { + nukiInst->lockngounlatch(); + } + else + { + _nukiOfficial->setOffCommandExecutedTs((esp_timer_get_time() / 1000) + 2000); + _offCommand = NukiLock::LockAction::LockNgoUnlatch; + _network->publishOffAction(5); + } + break; } } void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, const String &name, const String &code, const int& enabled) { - if(_disableNonJSON) return; + if(_disableNonJSON) + { + return; + } if(!_preferences->getBool(preference_keypad_control_enabled)) { @@ -1844,10 +2570,14 @@ void NukiWrapper::onKeypadCommandReceived(const char *command, const uint &id, c return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -1913,21 +2643,57 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json["code"].is()) code = json["code"].as(); - else code = 12; + if(json["code"].is()) + { + code = json["code"].as(); + } + else + { + code = 12; + } - if(json["enabled"].is()) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json["timeLimited"].is()) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json["name"].is()) name = json["name"].as(); - if(json["allowedFrom"].is()) allowedFrom = json["allowedFrom"].as(); - if(json["allowedUntil"].is()) allowedUntil = json["allowedUntil"].as(); - if(json["allowedWeekdays"].is()) allowedWeekdays = json["allowedWeekdays"].as(); - if(json["allowedFromTime"].is()) allowedFromTime = json["allowedFromTime"].as(); - if(json["allowedUntilTime"].is()) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -1943,7 +2709,8 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) while(retryCount < _nrOfRetries + 1) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiLock.deleteKeypadEntry(codeId); @@ -2080,13 +2847,34 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) } } - if(allowedWeekdays.indexOf("mon") >= 0) allowedWeekdaysInt += 64; - if(allowedWeekdays.indexOf("tue") >= 0) allowedWeekdaysInt += 32; - if(allowedWeekdays.indexOf("wed") >= 0) allowedWeekdaysInt += 16; - if(allowedWeekdays.indexOf("thu") >= 0) allowedWeekdaysInt += 8; - if(allowedWeekdays.indexOf("fri") >= 0) allowedWeekdaysInt += 4; - if(allowedWeekdays.indexOf("sat") >= 0) allowedWeekdaysInt += 2; - if(allowedWeekdays.indexOf("sun") >= 0) allowedWeekdaysInt += 1; + if(allowedWeekdays.indexOf("mon") >= 0) + { + allowedWeekdaysInt += 64; + } + if(allowedWeekdays.indexOf("tue") >= 0) + { + allowedWeekdaysInt += 32; + } + if(allowedWeekdays.indexOf("wed") >= 0) + { + allowedWeekdaysInt += 16; + } + if(allowedWeekdays.indexOf("thu") >= 0) + { + allowedWeekdaysInt += 8; + } + if(allowedWeekdays.indexOf("fri") >= 0) + { + allowedWeekdaysInt += 4; + } + if(allowedWeekdays.indexOf("sat") >= 0) + { + allowedWeekdaysInt += 2; + } + if(allowedWeekdays.indexOf("sun") >= 0) + { + allowedWeekdaysInt += 1; + } } if(strcmp(action, "add") == 0) @@ -2161,17 +2949,32 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) for(const auto& entry : entries) { - if (codeId != entry.codeId) continue; - else foundExisting = true; + if (codeId != entry.codeId) + { + continue; + } + else + { + foundExisting = true; + } if(name.length() < 1) { memset(oldName, 0, sizeof(oldName)); memcpy(oldName, entry.name, sizeof(entry.name)); } - if(code == 12) code = entry.code; - if(enabled == 2) enabled = entry.enabled; - if(timeLimited == 2) timeLimited = entry.timeLimited; + if(code == 12) + { + code = entry.code; + } + if(enabled == 2) + { + enabled = entry.enabled; + } + if(timeLimited == 2) + { + timeLimited = entry.timeLimited; + } if(allowedFrom.length() < 1) { allowedFrom = "old"; @@ -2192,7 +2995,10 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) allowedUntilAr[4] = entry.allowedUntilMin; allowedUntilAr[5] = entry.allowedUntilSec; } - if(allowedWeekdays.length() < 1) allowedWeekdaysInt = entry.allowedWeekdays; + if(allowedWeekdays.length() < 1) + { + allowedWeekdaysInt = entry.allowedWeekdays; + } if(allowedFromTime.length() < 1) { allowedFromTime = "old"; @@ -2290,10 +3096,14 @@ void NukiWrapper::onKeypadJsonCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } updateKeypad(false); @@ -2350,12 +3160,27 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) String lockAction; NukiLock::LockAction timeControlLockAction; - if(json["enabled"].is()) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json["weekdays"].is()) weekdays = json["weekdays"].as(); - if(json["time"].is()) time = json["time"].as(); - if(json["lockAction"].is()) lockAction = json["lockAction"].as(); + if(json["weekdays"].is()) + { + weekdays = json["weekdays"].as(); + } + if(json["time"].is()) + { + time = json["time"].as(); + } + if(json["lockAction"].is()) + { + lockAction = json["lockAction"].as(); + } if(lockAction.length() > 0) { @@ -2382,7 +3207,8 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) while(retryCount < _nrOfRetries + 1) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiLock.removeTimeControlEntry(entryId); @@ -2422,13 +3248,34 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) } } - if(weekdays.indexOf("mon") >= 0) weekdaysInt += 64; - if(weekdays.indexOf("tue") >= 0) weekdaysInt += 32; - if(weekdays.indexOf("wed") >= 0) weekdaysInt += 16; - if(weekdays.indexOf("thu") >= 0) weekdaysInt += 8; - if(weekdays.indexOf("fri") >= 0) weekdaysInt += 4; - if(weekdays.indexOf("sat") >= 0) weekdaysInt += 2; - if(weekdays.indexOf("sun") >= 0) weekdaysInt += 1; + if(weekdays.indexOf("mon") >= 0) + { + weekdaysInt += 64; + } + if(weekdays.indexOf("tue") >= 0) + { + weekdaysInt += 32; + } + if(weekdays.indexOf("wed") >= 0) + { + weekdaysInt += 16; + } + if(weekdays.indexOf("thu") >= 0) + { + weekdaysInt += 8; + } + if(weekdays.indexOf("fri") >= 0) + { + weekdaysInt += 4; + } + if(weekdays.indexOf("sat") >= 0) + { + weekdaysInt += 2; + } + if(weekdays.indexOf("sun") >= 0) + { + weekdaysInt += 1; + } if(strcmp(action, "add") == 0) { @@ -2467,18 +3314,33 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) for(const auto& entry : timeControlEntries) { - if (entryId != entry.entryId) continue; - else foundExisting = true; + if (entryId != entry.entryId) + { + continue; + } + else + { + foundExisting = true; + } - if(enabled == 2) enabled = entry.enabled; - if(weekdays.length() < 1) weekdaysInt = entry.weekdays; + if(enabled == 2) + { + enabled = entry.enabled; + } + if(weekdays.length() < 1) + { + weekdaysInt = entry.weekdays; + } if(time.length() < 1) { time = "old"; timeAr[0] = entry.timeHour; timeAr[1] = entry.timeMin; } - if(lockAction.length() < 1) timeControlLockAction = entry.lockAction; + if(lockAction.length() < 1) + { + timeControlLockAction = entry.lockAction; + } } if(!foundExisting) @@ -2518,10 +3380,14 @@ void NukiWrapper::onTimeControlCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } if((int)result != -1) @@ -2586,22 +3452,58 @@ void NukiWrapper::onAuthCommandReceived(const char *value) String allowedFromTime; String allowedUntilTime; - if(json["remoteAllowed"].is()) remoteAllowed = json["remoteAllowed"].as(); - else remoteAllowed = 2; + if(json["remoteAllowed"].is()) + { + remoteAllowed = json["remoteAllowed"].as(); + } + else + { + remoteAllowed = 2; + } - if(json["enabled"].is()) enabled = json["enabled"].as(); - else enabled = 2; + if(json["enabled"].is()) + { + enabled = json["enabled"].as(); + } + else + { + enabled = 2; + } - if(json["timeLimited"].is()) timeLimited = json["timeLimited"].as(); - else timeLimited = 2; + if(json["timeLimited"].is()) + { + timeLimited = json["timeLimited"].as(); + } + else + { + timeLimited = 2; + } - if(json["name"].is()) name = json["name"].as(); + if(json["name"].is()) + { + name = json["name"].as(); + } //if(json["sharedKey"].is()) sharedKey = json["sharedKey"].as(); - if(json["allowedFrom"].is()) allowedFrom = json["allowedFrom"].as(); - if(json["allowedUntil"].is()) allowedUntil = json["allowedUntil"].as(); - if(json["allowedWeekdays"].is()) allowedWeekdays = json["allowedWeekdays"].as(); - if(json["allowedFromTime"].is()) allowedFromTime = json["allowedFromTime"].as(); - if(json["allowedUntilTime"].is()) allowedUntilTime = json["allowedUntilTime"].as(); + if(json["allowedFrom"].is()) + { + allowedFrom = json["allowedFrom"].as(); + } + if(json["allowedUntil"].is()) + { + allowedUntil = json["allowedUntil"].as(); + } + if(json["allowedWeekdays"].is()) + { + allowedWeekdays = json["allowedWeekdays"].as(); + } + if(json["allowedFromTime"].is()) + { + allowedFromTime = json["allowedFromTime"].as(); + } + if(json["allowedUntilTime"].is()) + { + allowedUntilTime = json["allowedUntilTime"].as(); + } if(action) { @@ -2617,7 +3519,8 @@ void NukiWrapper::onAuthCommandReceived(const char *value) while(retryCount < _nrOfRetries) { - if(strcmp(action, "delete") == 0) { + if(strcmp(action, "delete") == 0) + { if(idExists) { result = _nukiLock.deleteAuthorizationEntry(authId); @@ -2753,13 +3656,34 @@ void NukiWrapper::onAuthCommandReceived(const char *value) } } - if(allowedWeekdays.indexOf("mon") >= 0) allowedWeekdaysInt += 64; - if(allowedWeekdays.indexOf("tue") >= 0) allowedWeekdaysInt += 32; - if(allowedWeekdays.indexOf("wed") >= 0) allowedWeekdaysInt += 16; - if(allowedWeekdays.indexOf("thu") >= 0) allowedWeekdaysInt += 8; - if(allowedWeekdays.indexOf("fri") >= 0) allowedWeekdaysInt += 4; - if(allowedWeekdays.indexOf("sat") >= 0) allowedWeekdaysInt += 2; - if(allowedWeekdays.indexOf("sun") >= 0) allowedWeekdaysInt += 1; + if(allowedWeekdays.indexOf("mon") >= 0) + { + allowedWeekdaysInt += 64; + } + if(allowedWeekdays.indexOf("tue") >= 0) + { + allowedWeekdaysInt += 32; + } + if(allowedWeekdays.indexOf("wed") >= 0) + { + allowedWeekdaysInt += 16; + } + if(allowedWeekdays.indexOf("thu") >= 0) + { + allowedWeekdaysInt += 8; + } + if(allowedWeekdays.indexOf("fri") >= 0) + { + allowedWeekdaysInt += 4; + } + if(allowedWeekdays.indexOf("sat") >= 0) + { + allowedWeekdaysInt += 2; + } + if(allowedWeekdays.indexOf("sun") >= 0) + { + allowedWeekdaysInt += 1; + } } if(strcmp(action, "add") == 0) @@ -2849,17 +3773,32 @@ void NukiWrapper::onAuthCommandReceived(const char *value) for(const auto& entry : entries) { - if (authId != entry.authId) continue; - else foundExisting = true; + if (authId != entry.authId) + { + continue; + } + else + { + foundExisting = true; + } if(name.length() < 1) { memset(oldName, 0, sizeof(oldName)); memcpy(oldName, entry.name, sizeof(entry.name)); } - if(remoteAllowed == 2) remoteAllowed = entry.remoteAllowed; - if(enabled == 2) enabled = entry.enabled; - if(timeLimited == 2) timeLimited = entry.timeLimited; + if(remoteAllowed == 2) + { + remoteAllowed = entry.remoteAllowed; + } + if(enabled == 2) + { + enabled = entry.enabled; + } + if(timeLimited == 2) + { + timeLimited = entry.timeLimited; + } if(allowedFrom.length() < 1) { allowedFrom = "old"; @@ -2880,7 +3819,10 @@ void NukiWrapper::onAuthCommandReceived(const char *value) allowedUntilAr[4] = entry.allowedUntilMinute; allowedUntilAr[5] = entry.allowedUntilSecond; } - if(allowedWeekdays.length() < 1) allowedWeekdaysInt = entry.allowedWeekdays; + if(allowedWeekdays.length() < 1) + { + allowedWeekdaysInt = entry.allowedWeekdays; + } if(allowedFromTime.length() < 1) { allowedFromTime = "old"; @@ -2979,10 +3921,14 @@ void NukiWrapper::onAuthCommandReceived(const char *value) return; } - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; } - else break; + else + { + break; + } } updateAuth(false); @@ -3054,12 +4000,16 @@ void NukiWrapper::readConfig() Log->print(F("Lock config result: ")); Log->println(resultStr); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; Log->println("Failed to retrieve lock config, retrying in 1s"); delay(1000); } - else break; + else + { + break; + } } } @@ -3070,7 +4020,7 @@ void NukiWrapper::readAdvancedConfig() while(retryCount < _nrOfRetries + 1) { - result = _nukiLock.requestAdvancedConfig(&_nukiAdvancedConfig); + result = _nukiLock.requestAdvancedConfig(&_nukiAdvancedConfig); _nukiAdvancedConfigValid = result == Nuki::CmdResult::Success; char resultStr[20]; @@ -3078,19 +4028,29 @@ void NukiWrapper::readAdvancedConfig() Log->print(F("Lock advanced config result: ")); Log->println(resultStr); - if(result != Nuki::CmdResult::Success) { + if(result != Nuki::CmdResult::Success) + { ++retryCount; Log->println("Failed to retrieve lock advanced config, retrying in 1s"); delay(1000); } - else break; + else + { + break; + } } } void NukiWrapper::setupHASS() { - if(!_nukiConfigValid) return; - if(_preferences->getUInt(preference_nuki_id_lock, 0) != _nukiConfig.nukiId) return; + if(!_nukiConfigValid) + { + return; + } + if(_preferences->getUInt(preference_nuki_id_lock, 0) != _nukiConfig.nukiId) + { + return; + } String baseTopic = _preferences->getString(preference_mqtt_lock_path); char uidString[20]; @@ -3155,15 +4115,15 @@ void NukiWrapper::updateGpioOutputs() { switch(entry.role) { - case PinRole::OutputHighLocked: - _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? HIGH : LOW); - break; - case PinRole::OutputHighUnlocked: - _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? LOW : HIGH); - break; - case PinRole::OutputHighMotorBlocked: - _gpio->setPinOutput(entry.pin, lockState == LockState::MotorBlocked ? HIGH : LOW); - break; + case PinRole::OutputHighLocked: + _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? HIGH : LOW); + break; + case PinRole::OutputHighUnlocked: + _gpio->setPinOutput(entry.pin, lockState == LockState::Locked || lockState == LockState::Locking ? LOW : HIGH); + break; + case PinRole::OutputHighMotorBlocked: + _gpio->setPinOutput(entry.pin, lockState == LockState::MotorBlocked ? HIGH : LOW); + break; } } } diff --git a/src/WebCfgServer.cpp b/src/WebCfgServer.cpp index 7aed68c..d4cf0d0 100644 --- a/src/WebCfgServer.cpp +++ b/src/WebCfgServer.cpp @@ -22,21 +22,21 @@ extern const uint8_t x509_crt_imported_bundle_bin_end[] asm("_binary_x509_crt_ #include "ArduinoJson.h" WebCfgServer::WebCfgServer(NukiWrapper* nuki, NukiOpenerWrapper* nukiOpener, NukiNetwork* network, Gpio* gpio, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, PsychicHttpServer* psychicServer) -: _nuki(nuki), - _nukiOpener(nukiOpener), - _network(network), - _gpio(gpio), - _preferences(preferences), - _allowRestartToPortal(allowRestartToPortal), - _partitionType(partitionType), - _psychicServer(psychicServer) + : _nuki(nuki), + _nukiOpener(nukiOpener), + _network(network), + _gpio(gpio), + _preferences(preferences), + _allowRestartToPortal(allowRestartToPortal), + _partitionType(partitionType), + _psychicServer(psychicServer) #else WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool allowRestartToPortal, uint8_t partitionType, PsychicHttpServer* psychicServer) -: _network(network), - _preferences(preferences), - _allowRestartToPortal(allowRestartToPortal), - _partitionType(partitionType), - _psychicServer(psychicServer) + : _network(network), + _preferences(preferences), + _allowRestartToPortal(allowRestartToPortal), + _partitionType(partitionType), + _psychicServer(psychicServer) #endif { _hostname = _preferences->getString(preference_hostname, ""); @@ -58,7 +58,7 @@ WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool _confirmCode = generateConfirmCode(); - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER _pinsConfigured = true; if(_nuki != nullptr && !_nuki->isPinSet()) @@ -71,45 +71,64 @@ WebCfgServer::WebCfgServer(NukiNetwork* network, Preferences* preferences, bool } _brokerConfigured = _preferences->getString(preference_mqtt_broker).length() > 0 && _preferences->getInt(preference_mqtt_broker_port) > 0; - #endif +#endif } void WebCfgServer::initialize() { - _psychicServer->on("/", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } if(!_network->isApOpen()) { - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER return buildHtml(request); - #else +#else return buildOtaHtml(request); - #endif +#endif } - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 else { return buildWifiConnectHtml(request); } - #endif +#endif }); - _psychicServer->on("/style.css", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/style.css", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return sendCss(request); }); - _psychicServer->on("/favicon.ico", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/favicon.ico", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return sendFavicon(request); }); - _psychicServer->on("/reboot", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); - + _psychicServer->on("/reboot", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + String value = ""; if(request->hasParam("CONFIRMTOKEN")) { const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); - if(p->value() != "") value = p->value(); + if(p->value() != "") + { + value = p->value(); + } } else { @@ -128,13 +147,21 @@ void WebCfgServer::initialize() if(_network->isApOpen()) { - #ifndef CONFIG_IDF_TARGET_ESP32H2 - _psychicServer->on("/ssidlist", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + _psychicServer->on("/ssidlist", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildSSIDListHtml(request); }); - _psychicServer->on("/savewifi", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/savewifi", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } String message = ""; bool connected = processWiFi(request, message); esp_err_t res = buildConfirmHtml(request, message, 10, true); @@ -147,64 +174,116 @@ void WebCfgServer::initialize() } return res; }); - #endif +#endif } else { - #ifndef NUKI_HUB_UPDATER - _psychicServer->on("/import", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); +#ifndef NUKI_HUB_UPDATER + _psychicServer->on("/import", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } String message = ""; bool restart = processImport(request, message); return buildConfirmHtml(request, message, 3, true); }); - _psychicServer->on("/export", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/export", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return sendSettings(request); }); - _psychicServer->on("/impexpcfg", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/impexpcfg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildImportExportHtml(request); }); - _psychicServer->on("/status", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/status", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildStatusHtml(request); }); - _psychicServer->on("/acclvl", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/acclvl", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildAccLvlHtml(request); }); - _psychicServer->on("/custntw", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/custntw", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildCustomNetworkConfigHtml(request); }); - _psychicServer->on("/advanced", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/advanced", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildAdvancedConfigHtml(request); }); - _psychicServer->on("/cred", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/cred", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildCredHtml(request); }); - _psychicServer->on("/mqttconfig", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/mqttconfig", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildMqttConfigHtml(request); }); - _psychicServer->on("/nukicfg", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/nukicfg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildNukiConfigHtml(request); }); - _psychicServer->on("/gpiocfg", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/gpiocfg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildGpioConfigHtml(request); }); - #ifndef CONFIG_IDF_TARGET_ESP32H2 - _psychicServer->on("/wifi", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); +#ifndef CONFIG_IDF_TARGET_ESP32H2 + _psychicServer->on("/wifi", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildConfigureWifiHtml(request); }); - _psychicServer->on("/wifimanager", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/wifimanager", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } if(_allowRestartToPortal) { esp_err_t res = buildConfirmHtml(request, "Restarting. Connect to ESP access point (\"NukiHub\" with password \"NukiHubESP32\") to reconfigure Wi-Fi.", 0); @@ -214,41 +293,73 @@ void WebCfgServer::initialize() } return(ESP_OK); }); - #endif - _psychicServer->on("/unpairlock", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); +#endif + _psychicServer->on("/unpairlock", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return processUnpair(request, false); }); - _psychicServer->on("/unpairopener", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/unpairopener", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return processUnpair(request, true); }); - _psychicServer->on("/factoryreset", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/factoryreset", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return processFactoryReset(request); }); - _psychicServer->on("/infopg", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/infopg", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildInfoHtml(request); }); - _psychicServer->on("/debugon", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/debugon", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } _preferences->putBool(preference_publish_debug_info, true); return buildConfirmHtml(request, "Debug On", 3, true); }); - _psychicServer->on("/debugoff", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/debugoff", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } _preferences->putBool(preference_publish_debug_info, false); return buildConfirmHtml(request, "Debug Off", 3, true); }); - _psychicServer->on("/savecfg", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/savecfg", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } String message = ""; bool restart = processArgs(request, message); return buildConfirmHtml(request, message, 3, true); }); - _psychicServer->on("/savegpiocfg", HTTP_POST, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/savegpiocfg", HTTP_POST, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } processGpioArgs(request); esp_err_t res = buildConfirmHtml(request, "Saving GPIO configuration. Restarting.", 3, true); Log->println(F("Restarting")); @@ -256,22 +367,37 @@ void WebCfgServer::initialize() restartEsp(RestartReason::GpioConfigurationUpdated); return res; }); - #endif - _psychicServer->on("/ota", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); +#endif + _psychicServer->on("/ota", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildOtaHtml(request); }); - _psychicServer->on("/otadebug", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/otadebug", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } return buildOtaHtml(request, true); }); - _psychicServer->on("/reboottoota", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + _psychicServer->on("/reboottoota", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } String value = ""; if(request->hasParam("CONFIRMTOKEN")) { const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); - if(p->value() != "") value = p->value(); + if(p->value() != "") + { + value = p->value(); + } } else { @@ -288,25 +414,36 @@ void WebCfgServer::initialize() restartEsp(RestartReason::OTAReboot); return res; }); - _psychicServer->on("/autoupdate", HTTP_GET, [&](PsychicRequest *request){ - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); - #ifndef NUKI_HUB_UPDATER + _psychicServer->on("/autoupdate", HTTP_GET, [&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } +#ifndef NUKI_HUB_UPDATER return processUpdate(request); - #else +#else return request->redirect("/"); - #endif +#endif }); PsychicUploadHandler *updateHandler = new PsychicUploadHandler(); updateHandler->onUpload([&](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final) - { - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); - return handleOtaUpload(request, filename, index, data, len, final); - } - ); + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } + return handleOtaUpload(request, filename, index, data, len, final); + } + ); - updateHandler->onRequest([&](PsychicRequest *request) { - if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + updateHandler->onRequest([&](PsychicRequest *request) + { + if(strlen(_credUser) > 0 && strlen(_credPassword) > 0) if(!request->authenticate(_credUser, _credPassword)) + { + return request->requestAuthentication(BASIC_AUTH, "Nuki Hub", "You must log in."); + } String result; if (!Update.hasError()) @@ -318,7 +455,8 @@ void WebCfgServer::initialize() restartEsp(RestartReason::OTACompleted); return res; } - else { + else + { result = " Update.errorString() " + String(Update.errorString()); Log->print("ERROR : error "); Log->println(result.c_str()); @@ -464,7 +602,10 @@ bool WebCfgServer::processWiFi(PsychicRequest *request, String& message) if(index < params -1) { const PsychicWebParameter* next = request->getParam(index+1); - if(key == next->name()) continue; + if(key == next->name()) + { + continue; + } } if(key == "WIFISSID") @@ -532,8 +673,8 @@ bool WebCfgServer::processWiFi(PsychicRequest *request, String& message) int loop = 0; while(!_network->isConnected() && loop < 150) { - delay(100); - loop++; + delay(100); + loop++; } if (!_network->isConnected()) @@ -578,10 +719,16 @@ esp_err_t WebCfgServer::buildOtaHtml(PsychicRequest *request, bool debug) if(request->hasParam("errored")) { const PsychicWebParameter* p = request->getParam("errored"); - if(p->value() != "") errored = true; + if(p->value() != "") + { + errored = true; + } } - if(errored) response.print("
Over-the-air update errored. Please check the logs for more info

"); + if(errored) + { + response.print("
Over-the-air update errored. Please check the logs for more info

"); + } if(_partitionType == 0) { @@ -592,12 +739,13 @@ esp_err_t WebCfgServer::buildOtaHtml(PsychicRequest *request, bool debug) return response.endSend(); } - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER bool manifestSuccess = false; JsonDocument doc; NetworkClientSecure *clientOTAUpdate = new NetworkClientSecure; - if (clientOTAUpdate) { + if (clientOTAUpdate) + { clientOTAUpdate->setCACertBundle(x509_crt_imported_bundle_bin_start, x509_crt_imported_bundle_bin_end - x509_crt_imported_bundle_bin_start); { HTTPClient httpsOTAClient; @@ -605,13 +753,17 @@ esp_err_t WebCfgServer::buildOtaHtml(PsychicRequest *request, bool debug) httpsOTAClient.setTimeout(2500); httpsOTAClient.useHTTP10(true); - if (httpsOTAClient.begin(*clientOTAUpdate, GITHUB_OTA_MANIFEST_URL)) { + if (httpsOTAClient.begin(*clientOTAUpdate, GITHUB_OTA_MANIFEST_URL)) + { int httpResponseCodeOTA = httpsOTAClient.GET(); if (httpResponseCodeOTA == HTTP_CODE_OK || httpResponseCodeOTA == HTTP_CODE_MOVED_PERMANENTLY) { DeserializationError jsonError = deserializeJson(doc, httpsOTAClient.getStream()); - if (!jsonError) { manifestSuccess = true; } + if (!jsonError) + { + manifestSuccess = true; + } } httpsOTAClient.end(); } @@ -626,14 +778,20 @@ esp_err_t WebCfgServer::buildOtaHtml(PsychicRequest *request, bool debug) String release_type; - if(debug) release_type = "debug"; - else release_type = "release"; + if(debug) + { + release_type = "debug"; + } + else + { + release_type = "release"; + } - #ifndef DEBUG_NUKIHUB +#ifndef DEBUG_NUKIHUB String build_type = "release"; - #else +#else String build_type = "debug"; - #endif +#endif response.print("

"); response.print("

"); response.print("

"); @@ -686,14 +844,29 @@ esp_err_t WebCfgServer::buildOtaHtml(PsychicRequest *request, bool debug) String currentVersion = NUKI_HUB_VERSION; const char* latestVersion; - if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) latestVersion = doc["release"]["fullversion"]; - else if(currentVersion.indexOf("beta") > 0) latestVersion = doc["beta"]["fullversion"]; - else if(currentVersion.indexOf("master") > 0) latestVersion = doc["master"]["fullversion"]; - else latestVersion = doc["release"]["fullversion"]; + if(atof(doc["release"]["version"]) >= atof(currentVersion.c_str())) + { + latestVersion = doc["release"]["fullversion"]; + } + else if(currentVersion.indexOf("beta") > 0) + { + latestVersion = doc["beta"]["fullversion"]; + } + else if(currentVersion.indexOf("master") > 0) + { + latestVersion = doc["master"]["fullversion"]; + } + else + { + latestVersion = doc["release"]["fullversion"]; + } - if(strcmp(latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) _preferences->putString(preference_latest_version, latestVersion); + if(strcmp(latestVersion, _preferences->getString(preference_latest_version).c_str()) != 0) + { + _preferences->putString(preference_latest_version, latestVersion); + } } - #endif +#endif response.print("
"); if(_partitionType == 1) @@ -777,7 +950,10 @@ void WebCfgServer::buildHtmlHeader(PsychicStreamResponse *response, String addit { response->print(""); response->print(""); - if(strcmp(additionalHeader.c_str(), "") != 0) response->print(additionalHeader); + if(strcmp(additionalHeader.c_str(), "") != 0) + { + response->print(additionalHeader); + } response->print(""); response->print("Nuki Hub"); } @@ -798,13 +974,17 @@ void WebCfgServer::waitAndProcess(const bool blocking, const uint32_t duration) } } -void WebCfgServer::printProgress(size_t prg, size_t sz) { - Log->printf("Progress: %d%%\n", (prg*100)/_otaContentLen); +void WebCfgServer::printProgress(size_t prg, size_t sz) +{ + Log->printf("Progress: %d%%\n", (prg*100)/_otaContentLen); } esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final) { - if(!request->url().endsWith("/uploadota")) return(ESP_FAIL); + if(!request->url().endsWith("/uploadota")) + { + return(ESP_FAIL); + } if(filename == "") { @@ -812,8 +992,10 @@ esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& f return(ESP_FAIL); } - if (!Update.hasError()) { - if (!index){ + if (!Update.hasError()) + { + if (!index) + { Update.clearError(); Log->println("Starting manual OTA update"); @@ -831,14 +1013,15 @@ esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& f } _otaStartTs = esp_timer_get_time() / 1000; - esp_task_wdt_config_t twdt_config = { + esp_task_wdt_config_t twdt_config = + { .timeout_ms = 30000, .idle_core_mask = 0, .trigger_panic = false, }; esp_task_wdt_reconfigure(&twdt_config); - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER _network->disableAutoRestarts(); _network->disableMqtt(); if(_nuki != nullptr) @@ -849,11 +1032,12 @@ esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& f { _nukiOpener->disableWatchdog(); } - #endif +#endif Log->print("handleFileUpload Name: "); Log->println(filename); - if (!Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH)) { + if (!Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH)) + { if (!Update.hasError()) { Update.abort(); @@ -864,8 +1048,10 @@ esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& f } } - if ((len) && (!Update.hasError())) { - if (Update.write(data, len) != len) { + if ((len) && (!Update.hasError())) + { + if (Update.write(data, len) != len) + { if (!Update.hasError()) { Update.abort(); @@ -876,13 +1062,16 @@ esp_err_t WebCfgServer::handleOtaUpload(PsychicRequest *request, const String& f } } - if ((final) && (!Update.hasError())) { - if (Update.end(true)) { + if ((final) && (!Update.hasError())) + { + if (Update.end(true)) + { Log->print("Update Success: "); Log->print(index+len); Log->println(" written"); } - else { + else + { if (!Update.hasError()) { Update.abort(); @@ -988,8 +1177,8 @@ void WebCfgServer::printInputField(PsychicStreamResponse *response, } if(strcmp(value, "") != 0) { - response->print(" value=\""); - response->print(value); + response->print(" value=\""); + response->print(value); } response->print("\" name=\""); response->print(token); @@ -1020,12 +1209,18 @@ esp_err_t WebCfgServer::sendSettings(PsychicRequest *request) if(request->hasParam("redacted")) { const PsychicWebParameter* p = request->getParam("redacted"); - if(p->value() == "1") redacted = true; + if(p->value() == "1") + { + redacted = true; + } } if(request->hasParam("pairing")) { const PsychicWebParameter* p = request->getParam("pairing"); - if(p->value() == "1") pairing = true; + if(p->value() == "1") + { + pairing = true; + } } JsonDocument json; @@ -1040,47 +1235,68 @@ esp_err_t WebCfgServer::sendSettings(PsychicRequest *request) for(const auto& key : keysPrefs) { - if(strcmp(key, preference_show_secrets) == 0) continue; - if(strcmp(key, preference_latest_version) == 0) continue; - if(strcmp(key, preference_device_id_lock) == 0) continue; - if(strcmp(key, preference_device_id_opener) == 0) continue; - if(!redacted) if(std::find(redactedPrefs.begin(), redactedPrefs.end(), key) != redactedPrefs.end()) continue; - if(!_preferences->isKey(key)) json[key] = ""; - else if(std::find(boolPrefs.begin(), boolPrefs.end(), key) != boolPrefs.end()) json[key] = _preferences->getBool(key) ? "1" : "0"; + if(strcmp(key, preference_show_secrets) == 0) + { + continue; + } + if(strcmp(key, preference_latest_version) == 0) + { + continue; + } + if(strcmp(key, preference_device_id_lock) == 0) + { + continue; + } + if(strcmp(key, preference_device_id_opener) == 0) + { + continue; + } + if(!redacted) if(std::find(redactedPrefs.begin(), redactedPrefs.end(), key) != redactedPrefs.end()) + { + continue; + } + if(!_preferences->isKey(key)) + { + json[key] = ""; + } + else if(std::find(boolPrefs.begin(), boolPrefs.end(), key) != boolPrefs.end()) + { + json[key] = _preferences->getBool(key) ? "1" : "0"; + } else { switch(_preferences->getType(key)) { - case PT_I8: - json[key] = String(_preferences->getChar(key)); - break; - case PT_I16: - json[key] = String(_preferences->getShort(key)); - break; - case PT_I32: - json[key] = String(_preferences->getInt(key)); - break; - case PT_I64: - json[key] = String(_preferences->getLong64(key)); - break; - case PT_U8: - json[key] = String(_preferences->getUChar(key)); - break; - case PT_U16: - json[key] = String(_preferences->getUShort(key)); - break; - case PT_U32: - json[key] = String(_preferences->getUInt(key)); - break; - case PT_U64: - json[key] = String(_preferences->getULong64(key)); - break; - case PT_STR: - json[key] = _preferences->getString(key); - break; - default: - json[key] = _preferences->getString(key); - break; + case PT_I8: + json[key] = String(_preferences->getChar(key)); + break; + case PT_I16: + json[key] = String(_preferences->getShort(key)); + break; + case PT_I32: + json[key] = String(_preferences->getInt(key)); + break; + case PT_I64: + json[key] = String(_preferences->getLong64(key)); + break; + case PT_U8: + json[key] = String(_preferences->getUChar(key)); + break; + case PT_U16: + json[key] = String(_preferences->getUShort(key)); + break; + case PT_U32: + json[key] = String(_preferences->getUInt(key)); + break; + case PT_U64: + json[key] = String(_preferences->getULong64(key)); + break; + case PT_STR: + json[key] = _preferences->getString(key); + break; + default: + json[key] = _preferences->getString(key); + break; } } } @@ -1102,21 +1318,24 @@ esp_err_t WebCfgServer::sendSettings(PsychicRequest *request) nukiBlePref.end(); char text[255]; text[0] = '\0'; - for(int i = 0 ; i < 6 ; i++) { + for(int i = 0 ; i < 6 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", currentBleAddress[i]); } json["bleAddressLock"] = text; memset(text, 0, sizeof(text)); text[0] = '\0'; - for(int i = 0 ; i < 32 ; i++) { + for(int i = 0 ; i < 32 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", secretKeyK[i]); } json["secretKeyKLock"] = text; memset(text, 0, sizeof(text)); text[0] = '\0'; - for(int i = 0 ; i < 4 ; i++) { + for(int i = 0 ; i < 4 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", authorizationId[i]); } @@ -1139,21 +1358,24 @@ esp_err_t WebCfgServer::sendSettings(PsychicRequest *request) nukiBlePref.end(); char text[255]; text[0] = '\0'; - for(int i = 0 ; i < 6 ; i++) { + for(int i = 0 ; i < 6 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", currentBleAddressOpn[i]); } json["bleAddressOpener"] = text; memset(text, 0, sizeof(text)); text[0] = '\0'; - for(int i = 0 ; i < 32 ; i++) { + for(int i = 0 ; i < 32 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", secretKeyKOpn[i]); } json["secretKeyKOpener"] = text; memset(text, 0, sizeof(text)); text[0] = '\0'; - for(int i = 0 ; i < 4 ; i++) { + for(int i = 0 ; i < 4 ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", authorizationIdOpn[i]); } @@ -1166,14 +1388,21 @@ esp_err_t WebCfgServer::sendSettings(PsychicRequest *request) for(const auto& key : bytePrefs) { size_t storedLength = _preferences->getBytesLength(key); - if(storedLength == 0) continue; + if(storedLength == 0) + { + continue; + } uint8_t serialized[storedLength]; memset(serialized, 0, sizeof(serialized)); size_t size = _preferences->getBytes(key, serialized, sizeof(serialized)); - if(size == 0) continue; + if(size == 0) + { + continue; + } char text[255]; text[0] = '\0'; - for(int i = 0 ; i < size ; i++) { + for(int i = 0 ; i < size ; i++) + { size_t offset = strlen(text); sprintf(&(text[offset]), "%02x", serialized[i]); } @@ -1223,7 +1452,10 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message) if(index < params -1) { const PsychicWebParameter* next = request->getParam(index+1); - if(key == next->name()) continue; + if(key == next->name()) + { + continue; + } } if(key == "MQTTSERVER") @@ -1333,7 +1565,10 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message) if(value.toInt() > 1) { networkReconfigure = true; - if(value.toInt() != 11) _preferences->putInt(preference_network_custom_phy, 0); + if(value.toInt() != 11) + { + _preferences->putInt(preference_network_custom_phy, 0); + } } _preferences->putInt(preference_network_hardware, value.toInt()); Log->print(F("Setting changed: ")); @@ -1497,8 +1732,14 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message) { if(_preferences->getString(preference_mqtt_hass_discovery, "") != value) { - if (_nuki != nullptr) _nuki->disableHASS(); - if (_nukiOpener != nullptr) _nukiOpener->disableHASS(); + if (_nuki != nullptr) + { + _nuki->disableHASS(); + } + if (_nukiOpener != nullptr) + { + _nukiOpener->disableHASS(); + } _preferences->putString(preference_mqtt_hass_discovery, value); Log->print(F("Setting changed: ")); Log->println(key); @@ -1600,7 +1841,10 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message) if(_preferences->getBool(preference_official_hybrid_enabled, false) != (value == "1")) { _preferences->putBool(preference_official_hybrid_enabled, (value == "1")); - if((value == "1")) _preferences->putBool(preference_register_as_app, true); + if((value == "1")) + { + _preferences->putBool(preference_register_as_app, true); + } Log->print(F("Setting changed: ")); Log->println(key); configChanged = true; @@ -1611,7 +1855,10 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message) if(_preferences->getBool(preference_official_hybrid_actions, false) != (value == "1")) { _preferences->putBool(preference_official_hybrid_actions, (value == "1")); - if(value == "1") _preferences->putBool(preference_register_as_app, true); + if(value == "1") + { + _preferences->putBool(preference_register_as_app, true); + } Log->print(F("Setting changed: ")); Log->println(key); //configChanged = true; @@ -2510,27 +2757,45 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message) } else if(key == "LCKBLEADDR") { - if(value.length() == 12) for(int i=0; i().length() > 0) _preferences->putBool(key, (doc[key].as() == "1" ? true : false)); - else _preferences->remove(key); + if (doc[key].as().length() > 0) + { + _preferences->putBool(key, (doc[key].as() == "1" ? true : false)); + } + else + { + _preferences->remove(key); + } continue; } if(std::find(intPrefs.begin(), intPrefs.end(), key) != intPrefs.end()) { - if (doc[key].as().length() > 0) _preferences->putInt(key, doc[key].as()); - else _preferences->remove(key); + if (doc[key].as().length() > 0) + { + _preferences->putInt(key, doc[key].as()); + } + else + { + _preferences->remove(key); + } continue; } - if (doc[key].as().length() > 0) _preferences->putString(key, doc[key].as()); - else _preferences->remove(key); + if (doc[key].as().length() > 0) + { + _preferences->putString(key, doc[key].as()); + } + else + { + _preferences->remove(key); + } } for(const auto& key : bytePrefs) @@ -2774,7 +3072,10 @@ bool WebCfgServer::processImport(PsychicRequest *request, String& message) { String value = doc[key].as(); unsigned char tmpchar[32]; - for(int i=0; iputBytes(key, (byte*)(&tmpchar), (value.length() / 2)); memset(tmpchar, 0, sizeof(tmpchar)); } @@ -2788,7 +3089,10 @@ bool WebCfgServer::processImport(PsychicRequest *request, String& message) if (doc["bleAddressLock"].as().length() == 12) { String value = doc["bleAddressLock"].as(); - for(int i=0; i().length() == 64) { String value = doc["secretKeyKLock"].as(); - for(int i=0; i().length() == 8) { String value = doc["authorizationIdLock"].as(); - for(int i=0; i().length() > 0) _nuki->setPin(doc["securityPinCodeLock"].as()); - else _nuki->setPin(0xffff); + if(doc["securityPinCodeLock"].as().length() > 0) + { + _nuki->setPin(doc["securityPinCodeLock"].as()); + } + else + { + _nuki->setPin(0xffff); + } } nukiBlePref.begin("NukiHubopener", false); if(!doc["bleAddressOpener"].isNull()) @@ -2822,7 +3138,10 @@ bool WebCfgServer::processImport(PsychicRequest *request, String& message) if (doc["bleAddressOpener"].as().length() == 12) { String value = doc["bleAddressOpener"].as(); - for(int i=0; i().length() == 64) { String value = doc["secretKeyKOpener"].as(); - for(int i=0; i().length() == 8) { String value = doc["authorizationIdOpener"].as(); - for(int i=0; i().length() > 0) _nukiOpener->setPin(doc["securityPinCodeOpener"].as()); - else _nukiOpener->setPin(0xffff); + if(doc["securityPinCodeOpener"].as().length() > 0) + { + _nukiOpener->setPin(doc["securityPinCodeOpener"].as()); + } + else + { + _nukiOpener->setPin(0xffff); + } } configChanged = true; @@ -2917,12 +3248,12 @@ esp_err_t WebCfgServer::buildCustomNetworkConfigHtml(PsychicRequest *request) response.print(""); printDropDown(&response, "NWCUSTPHY", "PHY", String(_preferences->getInt(preference_network_custom_phy)), getNetworkCustomPHYOptions(), ""); printInputField(&response, "NWCUSTADDR", "ADDR", _preferences->getInt(preference_network_custom_addr, 1), 6, ""); - #if defined(CONFIG_IDF_TARGET_ESP32) +#if defined(CONFIG_IDF_TARGET_ESP32) printDropDown(&response, "NWCUSTCLK", "CLK", String(_preferences->getInt(preference_network_custom_clk, 0)), getNetworkCustomCLKOptions(), "internalopt"); printInputField(&response, "NWCUSTPWR", "PWR", _preferences->getInt(preference_network_custom_pwr, 12), 6, "class=\"internalopt\""); printInputField(&response, "NWCUSTMDIO", "MDIO", _preferences->getInt(preference_network_custom_mdio), 6, "class=\"internalopt\""); printInputField(&response, "NWCUSTMDC", "MDC", _preferences->getInt(preference_network_custom_mdc), 6, "class=\"internalopt\""); - #endif +#endif printInputField(&response, "NWCUSTIRQ", "IRQ", _preferences->getInt(preference_network_custom_irq, -1), 6, "class=\"externalopt\""); printInputField(&response, "NWCUSTRST", "RST", _preferences->getInt(preference_network_custom_rst, -1), 6, "class=\"externalopt\""); printInputField(&response, "NWCUSTCS", "CS", _preferences->getInt(preference_network_custom_cs, -1), 6, "class=\"externalopt\""); @@ -2950,9 +3281,9 @@ esp_err_t WebCfgServer::buildHtml(PsychicRequest *request) { response.print("
WEBSERIAL IS ENABLED, ONLY ENABLE WHEN DEBUGGING AND DISABLE ASAP
"); } - #ifdef DEBUG_NUKIHUB +#ifdef DEBUG_NUKIHUB response.print("
RUNNING DEBUG BUILD, SWITCH TO RELEASE BUILD ASAP
"); - #endif +#endif response.print("

Info


"); response.print(""); printParameter(&response, "Hostname", _hostname.c_str(), "", "hostname"); @@ -3022,12 +3353,12 @@ esp_err_t WebCfgServer::buildHtml(PsychicRequest *request) { buildNavigationMenuEntry(&response, "Open Webserial", "/webserial"); } - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 if(_allowRestartToPortal) { buildNavigationMenuEntry(&response, "Configure Wi-Fi", "/wifi"); } - #endif +#endif String rebooturl = "/reboot?CONFIRMTOKEN=" + _confirmCode; buildNavigationMenuEntry(&response, "Reboot Nuki Hub", rebooturl.c_str()); response.print(""); @@ -3094,9 +3425,9 @@ esp_err_t WebCfgServer::buildCredHtml(PsychicRequest *request) } response.print("

Factory reset Nuki Hub

"); response.print("

This will reset all settings to default and unpair Nuki Lock and/or Opener."); - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 response.print("Optionally will also reset WiFi settings and reopen WiFi manager portal."); - #endif +#endif response.print("

"); response.print(""); response.print("
"); @@ -3104,9 +3435,9 @@ esp_err_t WebCfgServer::buildCredHtml(PsychicRequest *request) message.concat(_confirmCode); message.concat(" to confirm factory reset"); printInputField(&response, "CONFIRMTOKEN", message.c_str(), "", 10, ""); - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 printCheckBox(&response, "WIFI", "Also reset WiFi settings", false, ""); - #endif +#endif response.print("
"); response.print("
"); response.print(""); @@ -3132,14 +3463,17 @@ esp_err_t WebCfgServer::buildMqttConfigHtml(PsychicRequest *request) response.print(""); printInputField(&response, "HASSDISCOVERY", "Home Assistant discovery topic (empty to disable; usually homeassistant)", _preferences->getString(preference_mqtt_hass_discovery).c_str(), 30, ""); printInputField(&response, "HASSCUURL", "Home Assistant device configuration URL (empty to use http://LOCALIP; fill when using a reverse proxy for example)", _preferences->getString(preference_mqtt_hass_cu_url).c_str(), 261, ""); - if(_preferences->getBool(preference_opener_enabled, false)) printCheckBox(&response, "OPENERCONT", "Set Nuki Opener Lock/Unlock action in Home Assistant to Continuous mode", _preferences->getBool(preference_opener_continuous_mode), ""); + if(_preferences->getBool(preference_opener_enabled, false)) + { + printCheckBox(&response, "OPENERCONT", "Set Nuki Opener Lock/Unlock action in Home Assistant to Continuous mode", _preferences->getBool(preference_opener_continuous_mode), ""); + } printTextarea(&response, "MQTTCA", "MQTT SSL CA Certificate (*, optional)", _preferences->getString(preference_mqtt_ca).c_str(), TLS_CA_MAX_SIZE, true, true); printTextarea(&response, "MQTTCRT", "MQTT SSL Client Certificate (*, optional)", _preferences->getString(preference_mqtt_crt).c_str(), TLS_CERT_MAX_SIZE, true, true); printTextarea(&response, "MQTTKEY", "MQTT SSL Client Key (*, optional)", _preferences->getString(preference_mqtt_key).c_str(), TLS_KEY_MAX_SIZE, true, true); printDropDown(&response, "NWHW", "Network hardware", String(_preferences->getInt(preference_network_hardware)), getNetworkDetectionOptions(), ""); - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 printInputField(&response, "RSSI", "RSSI Publish interval (seconds; -1 to disable)", _preferences->getInt(preference_rssi_publish_interval), 6, ""); - #endif +#endif 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, "MQTTLOG", "Enable MQTT logging", _preferences->getBool(preference_mqtt_log_enabled), ""); @@ -3230,7 +3564,10 @@ esp_err_t WebCfgServer::buildStatusHtml(PsychicRequest *request) json["mqttState"] = "Yes"; mqttDone = true; } - else json["mqttState"] = "No"; + else + { + json["mqttState"] = "No"; + } if(_nuki != nullptr) { @@ -3244,11 +3581,20 @@ esp_err_t WebCfgServer::buildStatusHtml(PsychicRequest *request) if(_nuki->isPaired()) { json["lockPin"] = pinStateToString(_preferences->getInt(preference_lock_pin_status, 4)); - if(strcmp(lockStateArr, "undefined") != 0) lockDone = true; + if(strcmp(lockStateArr, "undefined") != 0) + { + lockDone = true; + } + } + else + { + json["lockPin"] = "Not Paired"; } - else json["lockPin"] = "Not Paired"; } - else lockDone = true; + else + { + lockDone = true; + } if(_nukiOpener != nullptr) { char openerStateArr[20]; @@ -3257,42 +3603,64 @@ esp_err_t WebCfgServer::buildStatusHtml(PsychicRequest *request) String openerPaired = (_nukiOpener->isPaired() ? ("Yes (BLE Address " + _nukiOpener->getBleAddress().toString() + ")").c_str() : "No"); json["openerPaired"] = openerPaired; - if(_nukiOpener->keyTurnerState().nukiState == NukiOpener::State::ContinuousMode) json["openerState"] = "Open (Continuous Mode)"; - else json["openerState"] = openerState; + if(_nukiOpener->keyTurnerState().nukiState == NukiOpener::State::ContinuousMode) + { + json["openerState"] = "Open (Continuous Mode)"; + } + else + { + json["openerState"] = openerState; + } if(_nukiOpener->isPaired()) { json["openerPin"] = pinStateToString(_preferences->getInt(preference_opener_pin_status, 4)); - if(strcmp(openerStateArr, "undefined") != 0) openerDone = true; + if(strcmp(openerStateArr, "undefined") != 0) + { + openerDone = true; + } + } + else + { + json["openerPin"] = "Not Paired"; } - else json["openerPin"] = "Not Paired"; } - else openerDone = true; + else + { + openerDone = true; + } if(_preferences->getBool(preference_check_updates)) { json["latestFirmware"] = _preferences->getString(preference_latest_version); latestDone = true; } - else latestDone = true; + else + { + latestDone = true; + } - if(mqttDone && lockDone && openerDone && latestDone) json["stop"] = 1; + if(mqttDone && lockDone && openerDone && latestDone) + { + json["stop"] = 1; + } serializeJson(json, jsonStr); return request->reply(200, "application/json", jsonStr.c_str()); } -String WebCfgServer::pinStateToString(uint8_t value) { +String WebCfgServer::pinStateToString(uint8_t value) +{ switch(value) { - case 0: - return String("PIN not set"); - case 1: - return String("PIN valid"); - case 2: - return String("PIN set but invalid"); - default: - return String("Unknown"); + case 0: + return String("PIN not set"); + case 1: + return String("PIN valid"); + case 2: + return String("PIN set but invalid"); + default: + return String("Unknown"); } } @@ -3485,9 +3853,15 @@ esp_err_t WebCfgServer::buildNukiConfigHtml(PsychicRequest *request) response.print("

Basic Nuki Configuration

"); response.print("
"); printCheckBox(&response, "LOCKENA", "Nuki Lock enabled", _preferences->getBool(preference_lock_enabled), ""); - if(_preferences->getBool(preference_lock_enabled)) printInputField(&response, "MQTTPATH", "MQTT Nuki Lock Path", _preferences->getString(preference_mqtt_lock_path).c_str(), 180, ""); + if(_preferences->getBool(preference_lock_enabled)) + { + printInputField(&response, "MQTTPATH", "MQTT Nuki Lock Path", _preferences->getString(preference_mqtt_lock_path).c_str(), 180, ""); + } printCheckBox(&response, "OPENA", "Nuki Opener enabled", _preferences->getBool(preference_opener_enabled), ""); - if(_preferences->getBool(preference_opener_enabled)) printInputField(&response, "MQTTOPPATH", "MQTT Nuki Opener Path", _preferences->getString(preference_mqtt_opener_path).c_str(), 180, ""); + if(_preferences->getBool(preference_opener_enabled)) + { + printInputField(&response, "MQTTOPPATH", "MQTT Nuki Opener Path", _preferences->getString(preference_mqtt_opener_path).c_str(), 180, ""); + } response.print("

"); response.print("

Advanced Nuki Configuration

"); response.print(""); @@ -3501,8 +3875,14 @@ esp_err_t WebCfgServer::buildNukiConfigHtml(PsychicRequest *request) } printInputField(&response, "NRTRY", "Number of retries if command failed", _preferences->getInt(preference_command_nr_of_retries), 10, ""); printInputField(&response, "TRYDLY", "Delay between retries (milliseconds)", _preferences->getInt(preference_command_retry_delay), 10, ""); - if(_preferences->getBool(preference_lock_enabled, true)) printCheckBox(&response, "REGAPP", "Lock: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_as_app), ""); - if(_preferences->getBool(preference_opener_enabled, false)) printCheckBox(&response, "REGAPPOPN", "Opener: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_opener_as_app), ""); + if(_preferences->getBool(preference_lock_enabled, true)) + { + printCheckBox(&response, "REGAPP", "Lock: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_as_app), ""); + } + if(_preferences->getBool(preference_opener_enabled, false)) + { + printCheckBox(&response, "REGAPPOPN", "Opener: Nuki Bridge is running alongside Nuki Hub (needs re-pairing if changed)", _preferences->getBool(preference_register_opener_as_app), ""); + } printInputField(&response, "RSBC", "Restart if bluetooth beacons not received (seconds; -1 to disable)", _preferences->getInt(preference_restart_ble_beacon_lost), 10, ""); printInputField(&response, "TXPWR", "BLE transmit power in dB (minimum -12, maximum 9)", _preferences->getInt(preference_ble_tx_power, 9), 10, ""); @@ -3591,11 +3971,11 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) response.print(NUKI_HUB_VERSION); response.print("\nBuild: "); response.print(NUKI_HUB_BUILD); - #ifndef DEBUG_NUKIHUB +#ifndef DEBUG_NUKIHUB response.print("\nBuild type: Release"); - #else +#else response.print("\nBuild type: Debug"); - #endif +#endif response.print("\nBuild date: "); response.print(NUKI_HUB_DATE); response.print("\nUpdater version: "); @@ -3616,7 +3996,7 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) response.print(ESP.getFreeHeap()); response.print("\nTotal internal heap: "); response.print(ESP.getHeapSize()); - #ifdef CONFIG_SOC_SPIRAM_SUPPORTED +#ifdef CONFIG_SOC_SPIRAM_SUPPORTED if(esp_psram_get_size() > 0) { response.print("\nPSRAM Available: Yes"); @@ -3631,9 +4011,9 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) { response.print("\nPSRAM Available: No"); } - #else +#else response.print("\nPSRAM Available: No"); - #endif +#endif response.print("\nNetwork task stack high watermark: "); response.print(uxTaskGetStackHighWaterMark(networkTaskHandle)); response.print("\nNuki task stack high watermark: "); @@ -3675,14 +4055,14 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) if(_network->networkDeviceName() == "Built-in Wi-Fi") { - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 response.print("\nSSID: "); response.print(WiFi.SSID()); response.print("\nBSSID of AP: "); response.print(_network->networkBSSID()); response.print("\nESP32 MAC address: "); response.print(WiFi.macAddress()); - #endif +#endif } else { @@ -3692,7 +4072,10 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) response.print("\n\n------------ NETWORK SETTINGS ------------"); response.print("\nNuki Hub hostname: "); response.print(_preferences->getString(preference_hostname, "")); - if(_preferences->getBool(preference_ip_dhcp_enabled, true)) response.print("\nDHCP enabled: Yes"); + if(_preferences->getBool(preference_ip_dhcp_enabled, true)) + { + response.print("\nDHCP enabled: Yes"); + } else { response.print("\nDHCP enabled: No"); @@ -3706,20 +4089,32 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) response.print(_preferences->getString(preference_ip_dns_server, "")); } - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 if(_network->networkDeviceName() == "Built-in Wi-Fi") { response.print("\nRSSI Publish interval (s): "); - if(_preferences->getInt(preference_rssi_publish_interval, 60) < 0) response.print("Disabled"); - else response.print(_preferences->getInt(preference_rssi_publish_interval, 60)); + if(_preferences->getInt(preference_rssi_publish_interval, 60) < 0) + { + response.print("Disabled"); + } + else + { + response.print(_preferences->getInt(preference_rssi_publish_interval, 60)); + } } - #endif +#endif response.print("\nRestart ESP32 on network disconnect enabled: "); response.print(_preferences->getBool(preference_restart_on_disconnect, false) ? "Yes" : "No"); response.print("\nMQTT Timeout until restart (s): "); - if(_preferences->getInt(preference_network_timeout, 60) < 0) response.print("Disabled"); - else response.print(_preferences->getInt(preference_network_timeout, 60)); + if(_preferences->getInt(preference_network_timeout, 60) < 0) + { + response.print("Disabled"); + } + else + { + response.print(_preferences->getInt(preference_network_timeout, 60)); + } response.print("\n\n------------ MQTT ------------"); response.print("\nMQTT connected: "); response.print(_network->mqttConnectionState() > 0 ? "Yes" : "No"); @@ -3803,9 +4198,15 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) response.print("\nNuki Hub configuration URL for HA: "); response.print(_preferences->getString(preference_mqtt_hass_cu_url, "").length() > 0 ? _preferences->getString(preference_mqtt_hass_cu_url, "") : "http://" + _network->localIP()); } - else response.print("No"); + else + { + response.print("No"); + } response.print("\n\n------------ NUKI LOCK ------------"); - if(_nuki == nullptr || !_preferences->getBool(preference_lock_enabled, true)) response.print("\nLock enabled: No"); + if(_nuki == nullptr || !_preferences->getBool(preference_lock_enabled, true)) + { + response.print("\nLock enabled: No"); + } else { response.print("\nLock enabled: Yes"); @@ -3835,7 +4236,10 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) response.print("\nRegister as: "); response.print(_preferences->getBool(preference_register_as_app, false) ? "App" : "Bridge"); response.print("\n\n------------ HYBRID MODE ------------"); - if(!_preferences->getBool(preference_official_hybrid_enabled, false)) response.print("\nHybrid mode enabled: No"); + if(!_preferences->getBool(preference_official_hybrid_enabled, false)) + { + response.print("\nHybrid mode enabled: No"); + } else { response.print("\nHybrid mode enabled: Yes"); @@ -3992,7 +4396,10 @@ esp_err_t WebCfgServer::buildInfoHtml(PsychicRequest *request) } response.print("\n\n------------ NUKI OPENER ------------"); - if(_nukiOpener == nullptr || !_preferences->getBool(preference_opener_enabled, false)) response.print("\nOpener enabled: No"); + if(_nukiOpener == nullptr || !_preferences->getBool(preference_opener_enabled, false)) + { + response.print("\nOpener enabled: No"); + } else { response.print("\nOpener enabled: Yes"); @@ -4159,7 +4566,10 @@ esp_err_t WebCfgServer::processUnpair(PsychicRequest *request, bool opener) if(request->hasParam("CONFIRMTOKEN")) { const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); - if(p->value() != "") value = p->value(); + if(p->value() != "") + { + value = p->value(); + } } if(value != _confirmCode) @@ -4191,7 +4601,10 @@ esp_err_t WebCfgServer::processUpdate(PsychicRequest *request) if(request->hasParam("token")) { const PsychicWebParameter* p = request->getParam("token"); - if(p->value() != "") value = p->value(); + if(p->value() != "") + { + value = p->value(); + } } if(value != _confirmCode) @@ -4256,7 +4669,10 @@ esp_err_t WebCfgServer::processFactoryReset(PsychicRequest *request) if(request->hasParam("CONFIRMTOKEN")) { const PsychicWebParameter* p = request->getParam("CONFIRMTOKEN"); - if(p->value() != "") value = p->value(); + if(p->value() != "") + { + value = p->value(); + } } bool resetWifi = false; @@ -4270,7 +4686,10 @@ esp_err_t WebCfgServer::processFactoryReset(PsychicRequest *request) if(request->hasParam("WIFI")) { const PsychicWebParameter* p = request->getParam("WIFI"); - if(p->value() != "") value = p->value(); + if(p->value() != "") + { + value = p->value(); + } } if(value2 == "1") @@ -4299,12 +4718,12 @@ esp_err_t WebCfgServer::processFactoryReset(PsychicRequest *request) _preferences->clear(); - #ifndef CONFIG_IDF_TARGET_ESP32H2 +#ifndef CONFIG_IDF_TARGET_ESP32H2 if(resetWifi) { _network->reconfigureDevice(); } - #endif +#endif waitAndProcess(false, 3000); restartEsp(RestartReason::NukiHubReset); @@ -4365,8 +4784,14 @@ void WebCfgServer::printDropDown(PsychicStreamResponse *response, const char *to for(const auto& option : options) { - if(option.first == preselectedValue) response->print(""); - if(strcmp(id, "") == 0) response->print("
"); response->print(description); response->print(""); + if(strcmp(id, "") == 0) + { + response->print(""); + } else { response->print("print(id); response->print("\">"); } - if(strcmp(link, "") == 0) response->print(value); + if(strcmp(link, "") == 0) + { + response->print(value); + } else { response->print("> WebCfgServer::getNetworkCustomPHYOp options.push_back(std::make_pair("1", "W5500")); options.push_back(std::make_pair("2", "DN9051")); options.push_back(std::make_pair("3", "KSZ8851SNL")); - #if defined(CONFIG_IDF_TARGET_ESP32) +#if defined(CONFIG_IDF_TARGET_ESP32) options.push_back(std::make_pair("4", "LAN8720")); options.push_back(std::make_pair("5", "RTL8201")); options.push_back(std::make_pair("6", "TLK110")); options.push_back(std::make_pair("7", "DP83848")); options.push_back(std::make_pair("8", "KSZ8041")); options.push_back(std::make_pair("9", "KSZ8081")); - #endif +#endif return options; } diff --git a/src/main.cpp b/src/main.cpp index 32d6b4e..173acd6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -77,8 +77,8 @@ TaskHandle_t networkTaskHandle = nullptr; #ifndef NUKI_HUB_UPDATER ssize_t write_fn(void* cookie, const char* buf, ssize_t size) { - Log->write((uint8_t *)buf, (size_t)size); - return size; + Log->write((uint8_t *)buf, (size_t)size); + return size; } void ets_putc_handler(char c) @@ -87,21 +87,25 @@ void ets_putc_handler(char c) static size_t buf_pos = 0; buf[buf_pos] = c; buf_pos++; - if (c == '\n' || buf_pos == sizeof(buf)) { + if (c == '\n' || buf_pos == sizeof(buf)) + { write_fn(NULL, buf, buf_pos); buf_pos = 0; } } -int _log_vprintf(const char *fmt, va_list args) { +int _log_vprintf(const char *fmt, va_list args) +{ int ret = vsnprintf(log_print_buffer, sizeof(log_print_buffer), fmt, args); - if (ret >= 0){ + if (ret >= 0) + { Log->write((uint8_t *)log_print_buffer, (size_t)ret); } return 0; //return vprintf(fmt, args); } -void setReroute(){ +void setReroute() +{ esp_log_set_vprintf(_log_vprintf); if(preferences->getBool(preference_mqtt_log_enabled)) { @@ -152,7 +156,10 @@ void networkTask(void *pvParameters) setReroute(); } #endif - if(connected && openerEnabled) networkOpener->update(); + if(connected && openerEnabled) + { + networkOpener->update(); + } #endif if((esp_timer_get_time() / 1000) - networkLoopTs > 120000) @@ -229,10 +236,10 @@ void bootloopDetection() } if(esp_reset_reason() == esp_reset_reason_t::ESP_RST_PANIC || - esp_reset_reason() == esp_reset_reason_t::ESP_RST_INT_WDT || - esp_reset_reason() == esp_reset_reason_t::ESP_RST_TASK_WDT || - true || - esp_reset_reason() == esp_reset_reason_t::ESP_RST_WDT) + esp_reset_reason() == esp_reset_reason_t::ESP_RST_INT_WDT || + esp_reset_reason() == esp_reset_reason_t::ESP_RST_TASK_WDT || + true || + esp_reset_reason() == esp_reset_reason_t::ESP_RST_WDT) { bootloopCounter++; Log->print(F("Bootloop counter incremented: ")); @@ -263,38 +270,48 @@ uint8_t checkPartition() Log->print(F("Partition subtype: ")); Log->println(running_partition->subtype); - if(running_partition->size == 1966080) return 0; //OLD PARTITION TABLE - else if(running_partition->subtype == ESP_PARTITION_SUBTYPE_APP_OTA_0) return 1; //NEW PARTITION TABLE, RUNNING MAIN APP - else return 2; //NEW PARTITION TABLE, RUNNING UPDATER APP + if(running_partition->size == 1966080) + { + return 0; //OLD PARTITION TABLE + } + else if(running_partition->subtype == ESP_PARTITION_SUBTYPE_APP_OTA_0) + { + return 1; //NEW PARTITION TABLE, RUNNING MAIN APP + } + else + { + return 2; //NEW PARTITION TABLE, RUNNING UPDATER APP + } } esp_err_t _http_event_handler(esp_http_client_event_t *evt) { - switch (evt->event_id) { - case HTTP_EVENT_ERROR: - Log->println("HTTP_EVENT_ERROR"); - break; - case HTTP_EVENT_ON_CONNECTED: - Log->println("HTTP_EVENT_ON_CONNECTED"); - break; - case HTTP_EVENT_HEADER_SENT: - Log->println("HTTP_EVENT_HEADER_SENT"); - break; - case HTTP_EVENT_ON_HEADER: - Log->println("HTTP_EVENT_ON_HEADER"); - break; - case HTTP_EVENT_ON_DATA: - Log->println("HTTP_EVENT_ON_DATA"); - break; - case HTTP_EVENT_ON_FINISH: - Log->println("HTTP_EVENT_ON_FINISH"); - break; - case HTTP_EVENT_DISCONNECTED: - Log->println("HTTP_EVENT_DISCONNECTED"); - break; - case HTTP_EVENT_REDIRECT: - Log->println("HTTP_EVENT_REDIRECT"); - break; + switch (evt->event_id) + { + case HTTP_EVENT_ERROR: + Log->println("HTTP_EVENT_ERROR"); + break; + case HTTP_EVENT_ON_CONNECTED: + Log->println("HTTP_EVENT_ON_CONNECTED"); + break; + case HTTP_EVENT_HEADER_SENT: + Log->println("HTTP_EVENT_HEADER_SENT"); + break; + case HTTP_EVENT_ON_HEADER: + Log->println("HTTP_EVENT_ON_HEADER"); + break; + case HTTP_EVENT_ON_DATA: + Log->println("HTTP_EVENT_ON_DATA"); + break; + case HTTP_EVENT_ON_FINISH: + Log->println("HTTP_EVENT_ON_FINISH"); + break; + case HTTP_EVENT_DISCONNECTED: + Log->println("HTTP_EVENT_DISCONNECTED"); + break; + case HTTP_EVENT_REDIRECT: + Log->println("HTTP_EVENT_REDIRECT"); + break; } return ESP_OK; } @@ -315,14 +332,16 @@ void otaTask(void *pvParameter) preferences->putString(preference_ota_main_url, ""); } Log->println("Starting OTA task"); - esp_http_client_config_t config = { + esp_http_client_config_t config = + { .url = updateUrl.c_str(), .event_handler = _http_event_handler, .crt_bundle_attach = esp_crt_bundle_attach, .keep_alive_enable = true, }; - esp_https_ota_config_t ota_config = { + esp_https_ota_config_t ota_config = + { .http_config = &config, }; Log->print(F("Attempting to download update from ")); @@ -334,19 +353,23 @@ void otaTask(void *pvParameter) while (retryCount <= retryMax) { esp_err_t ret = esp_https_ota(&ota_config); - if (ret == ESP_OK) { + if (ret == ESP_OK) + { Log->println("OTA Succeeded, Rebooting..."); esp_ota_set_boot_partition(esp_ota_get_next_update_partition(NULL)); restartEsp(RestartReason::OTACompleted); break; - } else { + } + else + { Log->println("Firmware upgrade failed, retrying in 5 seconds"); retryCount++; esp_task_wdt_reset(); delay(5000); continue; } - while (1) { + while (1) + { vTaskDelay(1000 / portTICK_PERIOD_MS); } } @@ -359,7 +382,8 @@ void otaTask(void *pvParameter) void setupTasks(bool ota) { // configMAX_PRIORITIES is 25 - esp_task_wdt_config_t twdt_config = { + esp_task_wdt_config_t twdt_config = + { .timeout_ms = 300000, .idle_core_mask = 0, .trigger_panic = true, @@ -375,13 +399,13 @@ void setupTasks(bool ota) { xTaskCreatePinnedToCore(networkTask, "ntw", preferences->getInt(preference_task_size_network, NETWORK_TASK_SIZE), NULL, 3, &networkTaskHandle, 1); esp_task_wdt_add(networkTaskHandle); - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER if(!network->isApOpen()) { xTaskCreatePinnedToCore(nukiTask, "nuki", preferences->getInt(preference_task_size_nuki, NUKI_TASK_SIZE), NULL, 2, &nukiTaskHandle, 0); esp_task_wdt_add(nukiTaskHandle); } - #endif +#endif } } @@ -392,13 +416,13 @@ void setup() Serial.begin(115200); Log = &Serial; - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER stdout = funopen(NULL, NULL, &write_fn, NULL, NULL); static char linebuf[1024]; setvbuf(stdout, linebuf, _IOLBF, sizeof(linebuf)); esp_rom_install_channel_putc(1, &ets_putc_handler); //ets_install_putc1(&ets_putc_handler); - #endif +#endif preferences = new Preferences(); preferences->begin("nukihub", false); @@ -408,24 +432,36 @@ void setup() initializeRestartReason(); - if((partitionType==1 && preferences->getString(preference_ota_updater_url, "").length() > 0) || (partitionType==2 && preferences->getString(preference_ota_main_url, "").length() > 0)) doOta = true; + if((partitionType==1 && preferences->getString(preference_ota_updater_url, "").length() > 0) || (partitionType==2 && preferences->getString(preference_ota_main_url, "").length() > 0)) + { + doOta = true; + } - #ifndef NUKI_HUB_UPDATER +#ifndef NUKI_HUB_UPDATER if(preferences->getBool(preference_enable_bootloop_reset, false)) { bootloopDetection(); } - #endif +#endif - #ifdef NUKI_HUB_UPDATER +#ifdef NUKI_HUB_UPDATER Log->print(F("Nuki Hub OTA version ")); Log->println(NUKI_HUB_VERSION); Log->print(F("Nuki Hub OTA build ")); Log->println(); - if(preferences->getString(preference_updater_version, "") != NUKI_HUB_VERSION) preferences->putString(preference_updater_version, NUKI_HUB_VERSION); - if(preferences->getString(preference_updater_build, "") != NUKI_HUB_BUILD) preferences->putString(preference_updater_build, NUKI_HUB_BUILD); - if(preferences->getString(preference_updater_date, "") != NUKI_HUB_DATE) preferences->putString(preference_updater_date, NUKI_HUB_DATE); + if(preferences->getString(preference_updater_version, "") != NUKI_HUB_VERSION) + { + preferences->putString(preference_updater_version, NUKI_HUB_VERSION); + } + if(preferences->getString(preference_updater_build, "") != NUKI_HUB_BUILD) + { + preferences->putString(preference_updater_build, NUKI_HUB_BUILD); + } + if(preferences->getString(preference_updater_date, "") != NUKI_HUB_DATE) + { + preferences->putString(preference_updater_date, NUKI_HUB_DATE); + } network = new NukiNetwork(preferences); network->initialize(); @@ -436,9 +472,12 @@ void setup() webCfgServer = new WebCfgServer(network, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType, psychicServer); webCfgServer->initialize(); psychicServer->listen(80); - psychicServer->onNotFound([](PsychicRequest* request) { return request->redirect("/"); }); + psychicServer->onNotFound([](PsychicRequest* request) + { + return request->redirect("/"); + }); } - #else +#else Log->print(F("Nuki Hub version ")); Log->println(NUKI_HUB_VERSION); Log->print(F("Nuki Hub build ")); @@ -466,7 +505,7 @@ void setup() network = new NukiNetwork(preferences, gpio, mqttLockPath, CharBuffer::get(), buffer_size); network->initialize(); - + lockEnabled = preferences->getBool(preference_lock_enabled); openerEnabled = preferences->getBool(preference_opener_enabled); @@ -477,7 +516,7 @@ void setup() lockEnabled = false; openerEnabled = false; } - + bleScanner = new BleScanner::Scanner(); // Scan interval and window according to Nuki recommendations: // https://developer.nuki.io/t/bluetooth-specification-questions/1109/27 @@ -522,10 +561,13 @@ void setup() { webCfgServer = new WebCfgServer(nuki, nukiOpener, network, gpio, preferences, network->networkDeviceType() == NetworkDeviceType::WiFi, partitionType, psychicServer); webCfgServer->initialize(); - psychicServer->onNotFound([](PsychicRequest* request) { return request->redirect("/"); }); + psychicServer->onNotFound([](PsychicRequest* request) + { + return request->redirect("/"); + }); } /* - #ifdef DEBUG_NUKIHUB +#ifdef DEBUG_NUKIHUB else psychicServer->onNotFound([](PsychicRequest* request) { return request->redirect("/webserial"); }); if(preferences->getBool(preference_webserial_enabled, false)) @@ -534,21 +576,27 @@ void setup() WebSerial.begin(asyncServer); WebSerial.setBuffer(1024); } - #endif +#endif */ } } - #endif +#endif - if(doOta) setupTasks(true); - else setupTasks(false); + if(doOta) + { + setupTasks(true); + } + else + { + setupTasks(false); + } - #ifdef DEBUG_NUKIHUB +#ifdef DEBUG_NUKIHUB Log->print("Task Name\tStatus\tPrio\tHWM\tTask\tAffinity\n"); char stats_buffer[1024]; vTaskList(stats_buffer); Log->println(stats_buffer); - #endif +#endif } void loop() diff --git a/src/networkDevices/EthernetDevice.cpp b/src/networkDevices/EthernetDevice.cpp index 9a31c7f..1a0c78b 100644 --- a/src/networkDevices/EthernetDevice.cpp +++ b/src/networkDevices/EthernetDevice.cpp @@ -7,44 +7,44 @@ RTC_NOINIT_ATTR bool criticalEthFailure; extern char WiFi_fallbackDetect[14]; EthernetDevice::EthernetDevice(const String& hostname, Preferences* preferences, const IPConfiguration* ipConfiguration, const std::string& deviceName, uint8_t phy_addr, int power, int mdc, int mdio, eth_phy_type_t ethtype, eth_clock_mode_t clock_mode) -: NetworkDevice(hostname, ipConfiguration), - _deviceName(deviceName), - _phy_addr(phy_addr), - _power(power), - _mdc(mdc), - _mdio(mdio), - _type(ethtype), - _clock_mode(clock_mode), - _useSpi(false), - _preferences(preferences) + : NetworkDevice(hostname, ipConfiguration), + _deviceName(deviceName), + _phy_addr(phy_addr), + _power(power), + _mdc(mdc), + _mdio(mdio), + _type(ethtype), + _clock_mode(clock_mode), + _useSpi(false), + _preferences(preferences) { init(); } EthernetDevice::EthernetDevice(const String &hostname, - Preferences *preferences, - const IPConfiguration *ipConfiguration, - const std::string &deviceName, - uint8_t phy_addr, - int cs, - int irq, - int rst, - int spi_sck, - int spi_miso, - int spi_mosi, - eth_phy_type_t ethtype) - : NetworkDevice(hostname, ipConfiguration), - _deviceName(deviceName), - _phy_addr(phy_addr), - _cs(cs), - _irq(irq), - _rst(rst), - _spi_sck(spi_sck), - _spi_miso(spi_miso), - _spi_mosi(spi_mosi), - _type(ethtype), - _useSpi(true), - _preferences(preferences) + Preferences *preferences, + const IPConfiguration *ipConfiguration, + const std::string &deviceName, + uint8_t phy_addr, + int cs, + int irq, + int rst, + int spi_sck, + int spi_miso, + int spi_mosi, + eth_phy_type_t ethtype) + : NetworkDevice(hostname, ipConfiguration), + _deviceName(deviceName), + _phy_addr(phy_addr), + _cs(cs), + _irq(irq), + _rst(rst), + _spi_sck(spi_sck), + _spi_miso(spi_miso), + _spi_mosi(spi_mosi), + _type(ethtype), + _useSpi(true), + _preferences(preferences) { init(); } @@ -78,7 +78,7 @@ void EthernetDevice::initialize() _hardwareInitialized = ETH.begin(_type, _phy_addr, _cs, _irq, _rst, SPI); criticalEthFailure = false; } - #ifdef CONFIG_IDF_TARGET_ESP32 +#ifdef CONFIG_IDF_TARGET_ESP32 else { Log->println(F("Use RMII")); @@ -90,7 +90,7 @@ void EthernetDevice::initialize() _checkIpTs = (esp_timer_get_time() / 1000) + 2000; } } - #endif +#endif if(_hardwareInitialized) { @@ -138,55 +138,56 @@ void EthernetDevice::update() void EthernetDevice::onNetworkEvent(arduino_event_id_t event, arduino_event_info_t info) { - switch (event) { - case ARDUINO_EVENT_ETH_START: - Log->println("ETH Started"); - ETH.setHostname(_hostname.c_str()); - break; - case ARDUINO_EVENT_ETH_CONNECTED: - Log->println("ETH Connected"); - if(!localIP().equals("0.0.0.0")) - { - _connected = true; - } - break; - case ARDUINO_EVENT_ETH_GOT_IP: - Log->printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); - Log->println(ETH); - - // For RMII devices, this check is handled in the update() method. - if(_useSpi && !_ipConfiguration->dhcpEnabled() && _ipConfiguration->ipAddress() != ETH.localIP()) - { - Log->printf("Static IP not used, retrying to set static IP"); - ETH.config(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); - ETH.begin(_type, _phy_addr, _cs, _irq, _rst, SPI); - } - + switch (event) + { + case ARDUINO_EVENT_ETH_START: + Log->println("ETH Started"); + ETH.setHostname(_hostname.c_str()); + break; + case ARDUINO_EVENT_ETH_CONNECTED: + Log->println("ETH Connected"); + if(!localIP().equals("0.0.0.0")) + { _connected = true; - if(_preferences->getBool(preference_ntw_reconfigure, false)) - { - _preferences->putBool(preference_ntw_reconfigure, false); - } - break; - case ARDUINO_EVENT_ETH_LOST_IP: - Log->println("ETH Lost IP"); - _connected = false; - onDisconnected(); - break; - case ARDUINO_EVENT_ETH_DISCONNECTED: - Log->println("ETH Disconnected"); - _connected = false; - onDisconnected(); - break; - case ARDUINO_EVENT_ETH_STOP: - Log->println("ETH Stopped"); - _connected = false; - onDisconnected(); - break; - default: - Log->print("ETH Event: "); - Log->println(event); - break; + } + break; + case ARDUINO_EVENT_ETH_GOT_IP: + Log->printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); + Log->println(ETH); + + // For RMII devices, this check is handled in the update() method. + if(_useSpi && !_ipConfiguration->dhcpEnabled() && _ipConfiguration->ipAddress() != ETH.localIP()) + { + Log->printf("Static IP not used, retrying to set static IP"); + ETH.config(_ipConfiguration->ipAddress(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet(), _ipConfiguration->dnsServer()); + ETH.begin(_type, _phy_addr, _cs, _irq, _rst, SPI); + } + + _connected = true; + if(_preferences->getBool(preference_ntw_reconfigure, false)) + { + _preferences->putBool(preference_ntw_reconfigure, false); + } + break; + case ARDUINO_EVENT_ETH_LOST_IP: + Log->println("ETH Lost IP"); + _connected = false; + onDisconnected(); + break; + case ARDUINO_EVENT_ETH_DISCONNECTED: + Log->println("ETH Disconnected"); + _connected = false; + onDisconnected(); + break; + case ARDUINO_EVENT_ETH_STOP: + Log->println("ETH Stopped"); + _connected = false; + onDisconnected(); + break; + default: + Log->print("ETH Event: "); + Log->println(event); + break; } } @@ -212,7 +213,10 @@ bool EthernetDevice::isApOpen() void EthernetDevice::onDisconnected() { - if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); + if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } } int8_t EthernetDevice::signalStrength() diff --git a/src/networkDevices/IPConfiguration.cpp b/src/networkDevices/IPConfiguration.cpp index 4f374ad..fadcfb6 100644 --- a/src/networkDevices/IPConfiguration.cpp +++ b/src/networkDevices/IPConfiguration.cpp @@ -3,7 +3,7 @@ #include "../Logger.h" IPConfiguration::IPConfiguration(Preferences *preferences) -: _preferences(preferences) + : _preferences(preferences) { if(!dhcpEnabled() && _preferences->getString(preference_ip_address, "").length() <= 0) { @@ -23,10 +23,14 @@ IPConfiguration::IPConfiguration(Preferences *preferences) } else { - Log->print(F("IP address: ")); Log->print(ipAddress()); - Log->print(F(", Subnet: ")); Log->print(subnet()); - Log->print(F(", Gateway: ")); Log->print(defaultGateway()); - Log->print(F(", DNS: ")); Log->println(dnsServer()); + Log->print(F("IP address: ")); + Log->print(ipAddress()); + Log->print(F(", Subnet: ")); + Log->print(subnet()); + Log->print(F(", Gateway: ")); + Log->print(defaultGateway()); + Log->print(F(", DNS: ")); + Log->println(dnsServer()); } } diff --git a/src/networkDevices/WifiDevice.cpp b/src/networkDevices/WifiDevice.cpp index 5c7e893..46513af 100644 --- a/src/networkDevices/WifiDevice.cpp +++ b/src/networkDevices/WifiDevice.cpp @@ -6,8 +6,8 @@ #include "../RestartReason.h" WifiDevice::WifiDevice(const String& hostname, Preferences* preferences, const IPConfiguration* ipConfiguration) -: NetworkDevice(hostname, ipConfiguration), - _preferences(preferences) + : NetworkDevice(hostname, ipConfiguration), + _preferences(preferences) { } @@ -52,10 +52,10 @@ void WifiDevice::initialize() for (int i = 0; i < _foundNetworks; i++) { Log->println(String(F("SSID ")) + WiFi.SSID(i) + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(i)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + - String(F(" and channel: ")) + String(WiFi.channel(i))); + String(WiFi.RSSI(i)) + String(F("(")) + + String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + + String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + + String(F(" and channel: ")) + String(WiFi.channel(i))); } if (_connectOnScanDone && _foundNetworks > 0) @@ -78,11 +78,13 @@ void WifiDevice::initialize() _preferences->putBool(preference_wifi_converted, true); wifi_config_t wifi_cfg; - if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) { + if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { Log->println("Failed to get Wi-Fi configuration in RAM"); } - if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK) { + if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK) + { Log->println("Failed to set storage Wi-Fi"); } @@ -107,7 +109,8 @@ void WifiDevice::initialize() memset(wifi_cfg.sta.ssid, 0, sizeof(wifi_cfg.sta.ssid)); memset(wifi_cfg.sta.password, 0, sizeof(wifi_cfg.sta.password)); - if (esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) { + if (esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK) + { Log->println("Failed to clear NVS Wi-Fi configuration"); } @@ -159,7 +162,7 @@ void WifiDevice::initialize() void WifiDevice::scan(bool passive, bool async) { - if(!_connecting) + if(!_connecting) { WiFi.scanDelete(); WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); @@ -210,10 +213,10 @@ bool WifiDevice::connect() if (ssid == WiFi.SSID(i)) { Log->println(String(F("Saved SSID ")) + ssid + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(i)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + - String(F(" and channel: ")) + String(WiFi.channel(i))); + String(WiFi.RSSI(i)) + String(F("(")) + + String(constrain((100.0 + WiFi.RSSI(i)) * 2, 0, 100)) + + String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(i) + + String(F(" and channel: ")) + String(WiFi.channel(i))); if (bestConnection == -1) { bestConnection = i; @@ -232,7 +235,10 @@ bool WifiDevice::connect() { Log->print("No network found with SSID: "); Log->println(ssid); - if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); + if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } _connectOnScanDone = true; _openAP = false; scan(false, true); @@ -243,42 +249,42 @@ bool WifiDevice::connect() _connecting = true; esp_wifi_scan_stop(); Log->println(String(F("Trying to connect to SSID ")) + ssid + String(F(" found with RSSI: ")) + - String(WiFi.RSSI(bestConnection)) + String(F("(")) + - String(constrain((100.0 + WiFi.RSSI(bestConnection)) * 2, 0, 100)) + - String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(bestConnection) + - String(F(" and channel: ")) + String(WiFi.channel(bestConnection))); - - + String(WiFi.RSSI(bestConnection)) + String(F("(")) + + String(constrain((100.0 + WiFi.RSSI(bestConnection)) * 2, 0, 100)) + + String(F(" %) and BSSID: ")) + WiFi.BSSIDstr(bestConnection) + + String(F(" and channel: ")) + String(WiFi.channel(bestConnection))); + + if(!_ipConfiguration->dhcpEnabled()) { WiFi.config(_ipConfiguration->ipAddress(), _ipConfiguration->dnsServer(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet()); } - + WiFi.begin(ssid, pass); auto status = WiFi.waitForConnectResult(10000); - + switch (status) { - case WL_CONNECTED: + case WL_CONNECTED: Log->println("WiFi connected"); break; - case WL_NO_SSID_AVAIL: + case WL_NO_SSID_AVAIL: Log->println("WiFi SSID not available"); break; - case WL_CONNECT_FAILED: + case WL_CONNECT_FAILED: Log->println("WiFi connection failed"); break; - case WL_IDLE_STATUS: + case WL_IDLE_STATUS: Log->println("WiFi changing status"); break; - case WL_DISCONNECTED: + case WL_DISCONNECTED: Log->println("WiFi disconnected"); break; - default: + default: Log->println("WiFi timeout"); break; } - + if (status != WL_CONNECTED) { if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) @@ -326,7 +332,7 @@ bool WifiDevice::isConnected() { return false; } - + return true; } @@ -350,12 +356,12 @@ void WifiDevice::onDisconnected() _connecting = true; String ssid = _preferences->getString(preference_wifi_ssid, ""); String pass = _preferences->getString(preference_wifi_pass, ""); - + if(!_ipConfiguration->dhcpEnabled()) { WiFi.config(_ipConfiguration->ipAddress(), _ipConfiguration->dnsServer(), _ipConfiguration->defaultGateway(), _ipConfiguration->subnet()); } - + WiFi.begin(ssid, pass); int loop = 0; @@ -371,26 +377,29 @@ void WifiDevice::onDisconnected() if(!isConnected()) { - if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) restartEsp(RestartReason::RestartOnDisconnectWatchdog); + if(_preferences->getBool(preference_restart_on_disconnect, false) && ((esp_timer_get_time() / 1000) > 60000)) + { + restartEsp(RestartReason::RestartOnDisconnectWatchdog); + } - WiFi.disconnect(true); - WiFi.mode(WIFI_STA); - WiFi.disconnect(); - delay(500); + WiFi.disconnect(true); + WiFi.mode(WIFI_STA); + WiFi.disconnect(); + delay(500); - wifi_mode_t wifiMode; - esp_wifi_get_mode(&wifiMode); + wifi_mode_t wifiMode; + esp_wifi_get_mode(&wifiMode); - while (wifiMode != WIFI_MODE_STA || WiFi.status() == WL_CONNECTED) - { - delay(500); - Log->println(F("Waiting for WiFi mode change or disconnection.")); - esp_wifi_get_mode(&wifiMode); - } + while (wifiMode != WIFI_MODE_STA || WiFi.status() == WL_CONNECTED) + { + delay(500); + Log->println(F("Waiting for WiFi mode change or disconnection.")); + esp_wifi_get_mode(&wifiMode); + } - _connectOnScanDone = true; - _openAP = false; - scan(false, true); + _connectOnScanDone = true; + _openAP = false; + scan(false, true); } } } diff --git a/src/util/NetworkDeviceInstantiator.cpp b/src/util/NetworkDeviceInstantiator.cpp index 0b46666..af4fda5 100644 --- a/src/util/NetworkDeviceInstantiator.cpp +++ b/src/util/NetworkDeviceInstantiator.cpp @@ -13,153 +13,153 @@ NetworkDevice *NetworkDeviceInstantiator::Create(NetworkDeviceType networkDevice switch (networkDeviceType) { - case NetworkDeviceType::W5500: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "Generic W5500", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_GENERIC_W5500, - ETH_PHY_IRQ_GENERIC_W5500, - ETH_PHY_RST_GENERIC_W5500, - ETH_PHY_SPI_SCK_GENERIC_W5500, - ETH_PHY_SPI_MISO_GENERIC_W5500, - ETH_PHY_SPI_MOSI_GENERIC_W5500, - ETH_PHY_W5500); - break; - case NetworkDeviceType::W5500M5: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_M5_W5500, - ETH_PHY_IRQ_M5_W5500, - ETH_PHY_RST_M5_W5500, - ETH_PHY_SPI_SCK_M5_W5500, - ETH_PHY_SPI_MISO_M5_W5500, - ETH_PHY_SPI_MOSI_M5_W5500, - ETH_PHY_W5500); - break; - case NetworkDeviceType::W5500M5S3: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE S3", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_M5_W5500_S3, - ETH_PHY_IRQ_M5_W5500, - ETH_PHY_RST_M5_W5500, - ETH_PHY_SPI_SCK_M5_W5500_S3, - ETH_PHY_SPI_MISO_M5_W5500_S3, - ETH_PHY_SPI_MOSI_M5_W5500_S3, - ETH_PHY_W5500); - break; - case NetworkDeviceType::ETH01_Evo: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "ETH01-Evo", - ETH_PHY_ADDR_ETH01EVO, - ETH_PHY_CS_ETH01EVO, - ETH_PHY_IRQ_ETH01EVO, - ETH_PHY_RST_ETH01EVO, - ETH_PHY_SPI_SCK_ETH01EVO, - ETH_PHY_SPI_MISO_ETH01EVO, - ETH_PHY_SPI_MOSI_ETH01EVO, - ETH_PHY_TYPE_DM9051); - break; - case NetworkDeviceType::M5STACK_PoESP32_Unit: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5STACK PoESP32 Unit", - ETH_PHY_ADDR_W5500, - ETH_PHY_CS_M5_W5500, - ETH_PHY_IRQ_M5_W5500, - ETH_PHY_RST_M5_W5500, - ETH_PHY_SPI_SCK_M5_W5500, - ETH_PHY_SPI_MISO_M5_W5500, - ETH_PHY_SPI_MOSI_M5_W5500, - ETH_PHY_W5500); - break; - case NetworkDeviceType::CUSTOM: + case NetworkDeviceType::W5500: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "Generic W5500", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_GENERIC_W5500, + ETH_PHY_IRQ_GENERIC_W5500, + ETH_PHY_RST_GENERIC_W5500, + ETH_PHY_SPI_SCK_GENERIC_W5500, + ETH_PHY_SPI_MISO_GENERIC_W5500, + ETH_PHY_SPI_MOSI_GENERIC_W5500, + ETH_PHY_W5500); + break; + case NetworkDeviceType::W5500M5: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_M5_W5500, + ETH_PHY_IRQ_M5_W5500, + ETH_PHY_RST_M5_W5500, + ETH_PHY_SPI_SCK_M5_W5500, + ETH_PHY_SPI_MISO_M5_W5500, + ETH_PHY_SPI_MOSI_M5_W5500, + ETH_PHY_W5500); + break; + case NetworkDeviceType::W5500M5S3: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5Stack Atom POE S3", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_M5_W5500_S3, + ETH_PHY_IRQ_M5_W5500, + ETH_PHY_RST_M5_W5500, + ETH_PHY_SPI_SCK_M5_W5500_S3, + ETH_PHY_SPI_MISO_M5_W5500_S3, + ETH_PHY_SPI_MOSI_M5_W5500_S3, + ETH_PHY_W5500); + break; + case NetworkDeviceType::ETH01_Evo: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "ETH01-Evo", + ETH_PHY_ADDR_ETH01EVO, + ETH_PHY_CS_ETH01EVO, + ETH_PHY_IRQ_ETH01EVO, + ETH_PHY_RST_ETH01EVO, + ETH_PHY_SPI_SCK_ETH01EVO, + ETH_PHY_SPI_MISO_ETH01EVO, + ETH_PHY_SPI_MOSI_ETH01EVO, + ETH_PHY_TYPE_DM9051); + break; + case NetworkDeviceType::M5STACK_PoESP32_Unit: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "M5STACK PoESP32 Unit", + ETH_PHY_ADDR_W5500, + ETH_PHY_CS_M5_W5500, + ETH_PHY_IRQ_M5_W5500, + ETH_PHY_RST_M5_W5500, + ETH_PHY_SPI_SCK_M5_W5500, + ETH_PHY_SPI_MISO_M5_W5500, + ETH_PHY_SPI_MOSI_M5_W5500, + ETH_PHY_W5500); + break; + case NetworkDeviceType::CUSTOM: + { + int custPHY = preferences->getInt(preference_network_custom_phy, 0); + + if(custPHY >= 1 && custPHY <= 3) { - int custPHY = preferences->getInt(preference_network_custom_phy, 0); + std::string custName; + eth_phy_type_t custEthtype; - if(custPHY >= 1 && custPHY <= 3) + switch(custPHY) { - std::string custName; - eth_phy_type_t custEthtype; - - switch(custPHY) - { - case 1: - custName = "Custom (W5500)"; - custEthtype = ETH_PHY_W5500; - break; - case 2: - custName = "Custom (DN9051)"; - custEthtype = ETH_PHY_DM9051; - break; - case 3: - custName = "Custom (KSZ8851SNL)"; - custEthtype = ETH_PHY_KSZ8851; - break; - default: - custName = "Custom (W5500)"; - custEthtype = ETH_PHY_W5500; - break; - } - - device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, - preferences->getInt(preference_network_custom_addr, -1), - preferences->getInt(preference_network_custom_cs, -1), - preferences->getInt(preference_network_custom_irq, -1), - preferences->getInt(preference_network_custom_rst, -1), - preferences->getInt(preference_network_custom_sck, -1), - preferences->getInt(preference_network_custom_miso, -1), - preferences->getInt(preference_network_custom_mosi, -1), - custEthtype); - } -#if defined(CONFIG_IDF_TARGET_ESP32) - else if(custPHY >= 4 && custPHY <= 9) - { - int custCLKpref = preferences->getInt(preference_network_custom_clk, 0); - - std::string custName = NetworkUtil::GetCustomEthernetDeviceName(custPHY); - eth_phy_type_t custEthtype = NetworkUtil::GetCustomEthernetType(custPHY); - eth_clock_mode_t custCLK = NetworkUtil::GetCustomClock(custCLKpref); - - device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, preferences->getInt(preference_network_custom_addr, -1), preferences->getInt(preference_network_custom_pwr, -1), preferences->getInt(preference_network_custom_mdc, -1), preferences->getInt(preference_network_custom_mdio, -1), custEthtype, custCLK); - } -#endif -#ifndef CONFIG_IDF_TARGET_ESP32H2 - else - { - device = new WifiDevice(hostname, preferences, ipConfiguration); - } -#endif - } - break; -#if defined(CONFIG_IDF_TARGET_ESP32) - case NetworkDeviceType::Olimex_LAN8720: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "Olimex (LAN8720)", ETH_PHY_ADDR_LAN8720, 12, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); - break; - case NetworkDeviceType::WT32_LAN8720: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "WT32-ETH01", 1, 16); - break; - case NetworkDeviceType::GL_S10: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "GL-S10", 1, 5, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_IP101, ETH_CLOCK_GPIO0_IN); - break; - case NetworkDeviceType::LilyGO_T_ETH_POE: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "LilyGO T-ETH-POE", 0, -1, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); - break; -#endif -#ifndef CONFIG_IDF_TARGET_ESP32H2 - case NetworkDeviceType::WiFi: - device = new WifiDevice(hostname, preferences, ipConfiguration); - break; - default: - device = new WifiDevice(hostname, preferences, ipConfiguration); - break; -#else + case 1: + custName = "Custom (W5500)"; + custEthtype = ETH_PHY_W5500; + break; + case 2: + custName = "Custom (DN9051)"; + custEthtype = ETH_PHY_DM9051; + break; + case 3: + custName = "Custom (KSZ8851SNL)"; + custEthtype = ETH_PHY_KSZ8851; + break; default: - device = new EthernetDevice(hostname, preferences, ipConfiguration, "Custom (W5500)", - preferences->getInt(preference_network_custom_addr, -1), - preferences->getInt(preference_network_custom_cs, -1), - preferences->getInt(preference_network_custom_irq, -1), - preferences->getInt(preference_network_custom_rst, -1), - preferences->getInt(preference_network_custom_sck, -1), - preferences->getInt(preference_network_custom_miso, -1), - preferences->getInt(preference_network_custom_mosi, -1), - ETH_PHY_W5500); - break; + custName = "Custom (W5500)"; + custEthtype = ETH_PHY_W5500; + break; + } + + device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, + preferences->getInt(preference_network_custom_addr, -1), + preferences->getInt(preference_network_custom_cs, -1), + preferences->getInt(preference_network_custom_irq, -1), + preferences->getInt(preference_network_custom_rst, -1), + preferences->getInt(preference_network_custom_sck, -1), + preferences->getInt(preference_network_custom_miso, -1), + preferences->getInt(preference_network_custom_mosi, -1), + custEthtype); + } +#if defined(CONFIG_IDF_TARGET_ESP32) + else if(custPHY >= 4 && custPHY <= 9) + { + int custCLKpref = preferences->getInt(preference_network_custom_clk, 0); + + std::string custName = NetworkUtil::GetCustomEthernetDeviceName(custPHY); + eth_phy_type_t custEthtype = NetworkUtil::GetCustomEthernetType(custPHY); + eth_clock_mode_t custCLK = NetworkUtil::GetCustomClock(custCLKpref); + + device = new EthernetDevice(hostname, preferences, ipConfiguration, custName, preferences->getInt(preference_network_custom_addr, -1), preferences->getInt(preference_network_custom_pwr, -1), preferences->getInt(preference_network_custom_mdc, -1), preferences->getInt(preference_network_custom_mdio, -1), custEthtype, custCLK); + } +#endif +#ifndef CONFIG_IDF_TARGET_ESP32H2 + else + { + device = new WifiDevice(hostname, preferences, ipConfiguration); + } +#endif + } + break; +#if defined(CONFIG_IDF_TARGET_ESP32) + case NetworkDeviceType::Olimex_LAN8720: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "Olimex (LAN8720)", ETH_PHY_ADDR_LAN8720, 12, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); + break; + case NetworkDeviceType::WT32_LAN8720: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "WT32-ETH01", 1, 16); + break; + case NetworkDeviceType::GL_S10: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "GL-S10", 1, 5, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_IP101, ETH_CLOCK_GPIO0_IN); + break; + case NetworkDeviceType::LilyGO_T_ETH_POE: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "LilyGO T-ETH-POE", 0, -1, ETH_PHY_MDC_LAN8720, ETH_PHY_MDIO_LAN8720, ETH_PHY_TYPE_LAN8720, ETH_CLOCK_GPIO17_OUT); + break; +#endif +#ifndef CONFIG_IDF_TARGET_ESP32H2 + case NetworkDeviceType::WiFi: + device = new WifiDevice(hostname, preferences, ipConfiguration); + break; + default: + device = new WifiDevice(hostname, preferences, ipConfiguration); + break; +#else + default: + device = new EthernetDevice(hostname, preferences, ipConfiguration, "Custom (W5500)", + preferences->getInt(preference_network_custom_addr, -1), + preferences->getInt(preference_network_custom_cs, -1), + preferences->getInt(preference_network_custom_irq, -1), + preferences->getInt(preference_network_custom_rst, -1), + preferences->getInt(preference_network_custom_sck, -1), + preferences->getInt(preference_network_custom_miso, -1), + preferences->getInt(preference_network_custom_mosi, -1), + ETH_PHY_W5500); + break; #endif } diff --git a/src/util/NetworkUtil.cpp b/src/util/NetworkUtil.cpp index 603b4e8..1dc057d 100644 --- a/src/util/NetworkUtil.cpp +++ b/src/util/NetworkUtil.cpp @@ -6,50 +6,50 @@ NetworkDeviceType NetworkUtil::GetDeviceTypeFromPreference(int hardwareDetect, i { switch (hardwareDetect) { - case 1: + case 1: + return NetworkDeviceType::WiFi; + break; + case 2: + return NetworkDeviceType::W5500; + break; + case 3: + return NetworkDeviceType::W5500M5; + break; + case 4: + return NetworkDeviceType::Olimex_LAN8720; + break; + case 5: + return NetworkDeviceType::WT32_LAN8720; + break; + case 6: + return NetworkDeviceType::M5STACK_PoESP32_Unit; + break; + case 7: + return NetworkDeviceType::LilyGO_T_ETH_POE; + break; + case 8: + return NetworkDeviceType::GL_S10; + break; + case 9: + return NetworkDeviceType::ETH01_Evo; + break; + case 10: + return NetworkDeviceType::W5500M5S3; + break; + case 11: + if(customPhy> 0) + { + return NetworkDeviceType::CUSTOM; + } + else + { return NetworkDeviceType::WiFi; - break; - case 2: - return NetworkDeviceType::W5500; - break; - case 3: - return NetworkDeviceType::W5500M5; - break; - case 4: - return NetworkDeviceType::Olimex_LAN8720; - break; - case 5: - return NetworkDeviceType::WT32_LAN8720; - break; - case 6: - return NetworkDeviceType::M5STACK_PoESP32_Unit; - break; - case 7: - return NetworkDeviceType::LilyGO_T_ETH_POE; - break; - case 8: - return NetworkDeviceType::GL_S10; - break; - case 9: - return NetworkDeviceType::ETH01_Evo; - break; - case 10: - return NetworkDeviceType::W5500M5S3; - break; - case 11: - if(customPhy> 0) - { - return NetworkDeviceType::CUSTOM; - } - else - { - return NetworkDeviceType::WiFi; - } - break; - default: - Log->println(F("Unknown hardware selected, falling back to Wi-Fi.")); - return NetworkDeviceType::WiFi; - break; + } + break; + default: + Log->println(F("Unknown hardware selected, falling back to Wi-Fi.")); + return NetworkDeviceType::WiFi; + break; } } @@ -57,20 +57,20 @@ std::string NetworkUtil::GetCustomEthernetDeviceName(int custPHY) { switch(custPHY) { - case 4: - return "Custom (LAN8720)"; - case 5: - return"Custom (RTL8201)"; - case 6: - return "Custom (TLK110)"; - case 7: - return "Custom (DP83848)"; - case 8: - return "Custom (KSZ8041)"; - case 9: - return "Custom (KSZ8081)"; - default: - return"Custom (LAN8720)"; + case 4: + return "Custom (LAN8720)"; + case 5: + return"Custom (RTL8201)"; + case 6: + return "Custom (TLK110)"; + case 7: + return "Custom (DP83848)"; + case 8: + return "Custom (KSZ8041)"; + case 9: + return "Custom (KSZ8081)"; + default: + return"Custom (LAN8720)"; } } @@ -79,27 +79,27 @@ eth_phy_type_t NetworkUtil::GetCustomEthernetType(int custPHY) { switch(custPHY) { - case 4: - return ETH_PHY_TYPE_LAN8720; - break; - case 5: - return ETH_PHY_RTL8201; - break; - case 6: - return ETH_PHY_TLK110; - break; - case 7: - return ETH_PHY_DP83848; - break; - case 8: - return ETH_PHY_KSZ8041; - break; - case 9: - return ETH_PHY_KSZ8081; - break; - default: - return ETH_PHY_TYPE_LAN8720; - break; + case 4: + return ETH_PHY_TYPE_LAN8720; + break; + case 5: + return ETH_PHY_RTL8201; + break; + case 6: + return ETH_PHY_TLK110; + break; + case 7: + return ETH_PHY_DP83848; + break; + case 8: + return ETH_PHY_KSZ8041; + break; + case 9: + return ETH_PHY_KSZ8081; + break; + default: + return ETH_PHY_TYPE_LAN8720; + break; } } @@ -107,18 +107,18 @@ eth_clock_mode_t NetworkUtil::GetCustomClock(int custCLKpref) { switch(custCLKpref) { - case 0: - return ETH_CLOCK_GPIO0_IN; - break; - case 2: - return ETH_CLOCK_GPIO16_OUT; - break; - case 3: - return ETH_CLOCK_GPIO17_OUT; - break; - default: - return ETH_CLOCK_GPIO17_OUT; - break; + case 0: + return ETH_CLOCK_GPIO0_IN; + break; + case 2: + return ETH_CLOCK_GPIO16_OUT; + break; + case 3: + return ETH_CLOCK_GPIO17_OUT; + break; + default: + return ETH_CLOCK_GPIO17_OUT; + break; } } #endif \ No newline at end of file