Refractor

This commit is contained in:
iranl
2024-11-07 23:11:47 +01:00
parent d764ef313a
commit c2d3a3e77d
28 changed files with 827 additions and 705 deletions

View File

@@ -202,7 +202,6 @@ In a browser navigate to the IP address assigned to the ESP32.
- MQTT Password : If using authentication on the MQTT broker set to the password belonging to a username with read/write rights on the MQTT broker, set to # to clear
- MQTT NukiHub Path: Set to the preferred MQTT root topic for NukiHub, defaults to "nukihub". Make sure this topic is unique when using multiple ESP32 NukiHub devices
- Enable Home Assistant auto discovery: Enable Home Assistant MQTT auto discovery. Will automatically create entities in Home Assistant for NukiHub and connected Nuki Lock and/or Opener when enabled.
- Use Home Assistant device based discovery: Use Home Assistant Device discovery instead of single component discovery. Recommended, but requires Home Assistant 2024.11 or newer.
#### Advanced MQTT Configuration

View File

@@ -49,6 +49,7 @@ set(SRCFILES
../src/util/NetworkUtil.cpp
../src/enums/NetworkDeviceType.h
../src/util/NetworkDeviceInstantiator.cpp
../src/HomeAssistantDiscovery.cpp
../src/NukiOfficial.cpp
../src/NukiPublisher.cpp
../src/EspMillis.h

View File

@@ -4,7 +4,7 @@
#define NUKI_HUB_VERSION "9.02"
#define NUKI_HUB_BUILD "unknownbuildnr"
#define NUKI_HUB_DATE "2024-11-06"
#define NUKI_HUB_DATE "2024-11-08"
#define GITHUB_LATEST_RELEASE_URL (char*)"https://github.com/technyon/nuki_hub/releases/latest"
#define GITHUB_OTA_MANIFEST_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/manifest.json"
@@ -22,6 +22,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32c3.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32c3.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32c3.bin"
#define NUKI_HUB_HW (char*)"ESP32-C3"
#elif defined(CONFIG_IDF_TARGET_ESP32S3)
#if defined(CONFIG_SPIRAM_MODE_OCT)
#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_esp32s3oct.bin"
@@ -36,6 +37,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32s3oct.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32s3oct.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32s3oct.bin"
#define NUKI_HUB_HW (char*)"ESP32-S3 (Octal PSRAM)"
#else
#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_esp32s3.bin"
#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_updater_esp32s3.bin"
@@ -49,6 +51,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32s3.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32s3.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32s3.bin"
#define NUKI_HUB_HW (char*)"ESP32-S3"
#endif
#elif defined(CONFIG_IDF_TARGET_ESP32C6)
#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_esp32c6.bin"
@@ -63,6 +66,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32c6.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32c6.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32c6.bin"
#define NUKI_HUB_HW (char*)"ESP32-C6"
#elif defined(CONFIG_IDF_TARGET_ESP32H2)
#define GITHUB_LATEST_RELEASE_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_esp32h2.bin"
#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_updater_esp32h2.bin"
@@ -76,6 +80,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32h2.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32h2.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32h2.bin"
#define NUKI_HUB_HW (char*)"ESP32-H2"
#else
#if defined(CONFIG_FREERTOS_UNICORE)
#define GITHUB_LATEST_RELEASE_BINARY_URL "https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_esp32-solo1.bin"
@@ -90,6 +95,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32-solo1.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32-solo1.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32-solo1.bin"
#define NUKI_HUB_HW (char*)"ESP32-SOLO1"
#else
#define GITHUB_LATEST_RELEASE_BINARY_URL "https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_esp32.bin"
#define GITHUB_LATEST_UPDATER_BINARY_URL (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/nuki_hub_updater_esp32.bin"
@@ -103,6 +109,7 @@
#define GITHUB_BETA_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/beta/nuki_hub_updater_esp32.bin"
#define GITHUB_MASTER_RELEASE_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_esp32.bin"
#define GITHUB_MASTER_UPDATER_BINARY_URL_DBG (char*)"https://raw.githubusercontent.com/technyon/nuki_hub/binary/ota/debug/master/nuki_hub_updater_esp32.bin"
#define NUKI_HUB_HW (char*)"ESP32"
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,15 @@
void setupHASS(int type=0);
#pragma once
#include <Preferences.h>
#include <ArduinoJson.h>
#include "networkDevices/NetworkDevice.h"
class HomeAssistantDiscovery
{
public:
explicit HomeAssistantDiscovery(NetworkDevice* device, Preferences* preferences, char* buffer, size_t bufferSize);
void setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad);
void disableHASS();
void publishHASSConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const bool& publishAuthData, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction);
void removeHASSConfig(char* uidString);
void publishHASSConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const char* availabilityTopic, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction);
void publishHASSConfigAdditionalLockEntities(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigDoorSensor(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigAdditionalOpenerEntities(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigAccessLog(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigKeypad(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSWifiRssiConfig(char* deviceType, const char* baseTopic, char* name, char* uidString);
void removeHASSConfig(char* uidString);
void removeHASSConfigTopic(char* deviceType, char* name, char* uidString);
void removeHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString);
void publishHassTopic(const String& mqttDeviceType,
const String& mqttDeviceName,
const String& uidString,
@@ -25,19 +24,51 @@
const String& entityCat = "",
const String& commandTopic = "",
std::vector<std::pair<char*, char*>> additionalEntries = {}
);
void removeHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString);
);
private:
void 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);
void publishHASSDeviceConfig(char* deviceType, const char* baseTopic, char* name, char* uidString, const char *softwareVersion, const char *hardwareVersion, const char* availabilityTopic, const bool& hasKeypad, char* lockAction, char* unlockAction, char* openAction);
void publishHASSNukiHubConfig();
void publishHASSConfigAdditionalLockEntities(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigDoorSensor(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigAdditionalOpenerEntities(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigAccessLog(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigKeypad(char* deviceType, const char* baseTopic, char* name, char* uidString);
void publishHASSConfigWifiRssi(char* deviceType, const char* baseTopic, char* name, char* uidString);
void removeHASSConfig(char* uidString);
void removeHASSConfigTopic(char* deviceType, char* name, char* uidString);
String createHassTopicPath(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString);
JsonDocument 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<std::pair<char*, char*>> 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<std::pair<char*, char*>> additionalEntries = {}
);
NetworkDevice* _device = nullptr;
Preferences* _preferences = nullptr;
String _discoveryTopic;
String _baseTopic;
String _hostname;
char _nukiHubUidString[20];
bool _offEnabled = false;
bool _checkUpdates = false;
bool _updateFromMQTT = false;
char* _buffer;
const size_t _bufferSize;
};

View File

@@ -1,7 +1,5 @@
#pragma once
#include <Arduino.h>
class MqttReceiver
{
public:

View File

@@ -110,7 +110,7 @@
#define mqtt_topic_restart_reason_esp "/maintenance/restartReasonNukiEsp"
#define mqtt_topic_mqtt_connection_state "/maintenance/mqttConnectionState"
#define mqtt_topic_network_device "/maintenance/networkDevice"
#define mqtt_hybrid_state "/hybridConnected"
#define mqtt_topic_hybrid_state "/hybridConnected"
#define mqtt_topic_gpio_prefix "/gpio"
#define mqtt_topic_gpio_pin "/pin_"

View File

@@ -11,12 +11,7 @@
#endif
#include "networkDevices/EthernetDevice.h"
#ifndef NUKI_HUB_UPDATER
#include <ArduinoJson.h>
#endif
NukiNetwork* NukiNetwork::_inst = nullptr;
HomeAssistantDiscovery* HomeAssistantDiscovery::_hadiscovery = nullptr;
extern bool wifiFallback;
extern bool disableNetwork;
@@ -42,9 +37,7 @@ NukiNetwork::NukiNetwork(Preferences *preferences)
}
_inst = this;
_hadiscovery = new HomeAssistantDiscovery(_inst, _preferences);
_webEnabled = _preferences->getBool(preference_webserver_enabled, true);
_updateFromMQTT = _preferences->getBool(preference_update_from_mqtt, false);
#ifndef NUKI_HUB_UPDATER
memset(_maintenancePathPrefix, 0, sizeof(_maintenancePathPrefix));
@@ -148,7 +141,10 @@ void NukiNetwork::setupDevice()
{
onMqttDisconnect(reason);
});
_hadiscovery = new HomeAssistantDiscovery(_device, _preferences, _buffer, _bufferSize);
#endif
}
void NukiNetwork::reconfigureDevice()
@@ -246,7 +242,7 @@ void NukiNetwork::initialize()
{
_nukiHubPath[i] = mqttPath.charAt(i);
}
_hostname = _preferences->getString(preference_hostname, "");
if(_hostname == "")
@@ -339,8 +335,6 @@ void NukiNetwork::initialize()
}
}
_discoveryTopic = _preferences->getString(preference_mqtt_hass_discovery, "");
_offEnabled = _preferences->getBool(preference_official_hybrid_enabled, false);
readSettings();
}
}
@@ -640,7 +634,7 @@ bool NukiNetwork::reconnect()
_device->mqttSetCredentials(_mqttUser, _mqttPass);
}
_device->setWill(_mqttConnectionStateTopic, 1, true, _lastWillPayload);
_device->mqttSetWill(_mqttConnectionStateTopic, 1, true, _lastWillPayload);
_device->mqttSetServer(_mqttBrokerAddr, _mqttPort);
_device->mqttConnect();
@@ -683,7 +677,12 @@ bool NukiNetwork::reconnect()
publishString(_maintenancePathPrefix, mqtt_topic_network_device, _device->deviceName().c_str(), true);
for(const auto& it : _initTopics)
{
_device->mqttPublish(it.first.c_str(), MQTT_QOS_LEVEL, true, it.second.c_str());
publish(it.first.c_str(), it.second.c_str(), true);
}
if(_preferences->getBool(preference_mqtt_hass_enabled, false))
{
setupHASS(0, 0, {0}, {0}, {0}, false, false);
}
}
@@ -804,7 +803,7 @@ void NukiNetwork::onMqttDataReceived(const espMqttClientTypes::MessageProperties
if(_mqttConnectedTs == -1 || (millis() - _mqttConnectedTs < 2000)) return;
parseGpioTopics(properties, topic, payload, len, index, total);
onMqttDataReceived(topic, (byte*)payload, index);
for(auto receiver : _mqttReceivers)
@@ -816,7 +815,7 @@ void NukiNetwork::onMqttDataReceived(const espMqttClientTypes::MessageProperties
void NukiNetwork::onMqttDataReceived(const char* topic, byte* payload, const unsigned int length)
{
char* data = (char*)payload;
if(comparePrefixedPath(topic, mqtt_topic_reset) && strcmp(data, "1") == 0)
{
Log->println(F("Restart requested via MQTT."));
@@ -960,7 +959,7 @@ void NukiNetwork::onMqttDataReceived(const char* topic, byte* payload, const uns
clearWifiFallback();
delay(200);
restartEsp(RestartReason::ReconfigureWebServer);
}
}
}
void NukiNetwork::parseGpioTopics(const espMqttClientTypes::MessageProperties &properties, const char *topic, const uint8_t *payload, size_t& len, size_t& index, size_t& total)
@@ -1027,7 +1026,7 @@ void NukiNetwork::publishFloat(const char* prefix, const char* topic, const floa
dtostrf(value, 0, precision, str);
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str);
publish(path, str, retain);
}
void NukiNetwork::publishInt(const char* prefix, const char *topic, const int value, bool retain)
@@ -1036,7 +1035,7 @@ void NukiNetwork::publishInt(const char* prefix, const char *topic, const int va
itoa(value, str, 10);
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str);
publish(path, str, retain);
}
void NukiNetwork::publishUInt(const char* prefix, const char *topic, const unsigned int value, bool retain)
@@ -1045,7 +1044,7 @@ void NukiNetwork::publishUInt(const char* prefix, const char *topic, const unsig
utoa(value, str, 10);
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str);
publish(path, str, retain);
}
void NukiNetwork::publishULong(const char* prefix, const char *topic, const unsigned long value, bool retain)
@@ -1054,7 +1053,7 @@ void NukiNetwork::publishULong(const char* prefix, const char *topic, const unsi
utoa(value, str, 10);
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str);
publish(path, str, retain);
}
void NukiNetwork::publishLongLong(const char* prefix, const char *topic, int64_t value, bool retain)
@@ -1075,7 +1074,7 @@ void NukiNetwork::publishLongLong(const char* prefix, const char *topic, int64_t
}
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, result);
publish(path, result, retain);
}
void NukiNetwork::publishBool(const char* prefix, const char *topic, const bool value, bool retain)
@@ -1084,21 +1083,26 @@ void NukiNetwork::publishBool(const char* prefix, const char *topic, const bool
str[0] = value ? '1' : '0';
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, str);
publish(path, str, retain);
}
void NukiNetwork::publishString(const char* prefix, const char *topic, const char *value, bool retain)
{
char path[200] = {0};
buildMqttPath(path, { prefix, topic });
_device->mqttPublish(path, MQTT_QOS_LEVEL, retain, value);
publish(path, value, retain);
}
void NukiNetwork::publish(const char *topic, const char *value, bool retain)
{
_device->mqttPublish(topic, MQTT_QOS_LEVEL, retain, value);
}
void NukiNetwork::removeTopic(const String& mqttPath, const String& mqttTopic)
{
String path = mqttPath;
path.concat(mqttTopic);
_device->mqttPublish(path.c_str(), MQTT_QOS_LEVEL, true, "");
publish(path.c_str(), "", true);
#ifdef DEBUG_NUKIHUB
Log->print(F("Removing MQTT topic: "));
@@ -1106,9 +1110,9 @@ void NukiNetwork::removeTopic(const String& mqttPath, const String& mqttTopic)
#endif
}
void NukiNetwork::setupHASS(int type)
void NukiNetwork::setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad)
{
_hadiscovery->setupHASS(type);
_hadiscovery->setupHASS(type, nukiId, nukiName, firmwareVersion, hardwareVersion, hasDoorSensor, hasKeypad);
}
void NukiNetwork::disableHASS()
@@ -1354,7 +1358,7 @@ void NukiNetwork::addReconnectedCallback(std::function<void()> reconnectedCallba
void NukiNetwork::disableMqtt()
{
_device->disableMqtt();
_device->mqttDisable();
_mqttEnabled = false;
}

View File

@@ -15,6 +15,7 @@
#include "Gpio.h"
#include <ArduinoJson.h>
#include "NukiConstants.h"
#include "HomeAssistantDiscovery.h"
#endif
class NukiNetwork
@@ -56,11 +57,31 @@ public:
void publishLongLong(const char* prefix, const char* topic, int64_t value, bool retain);
void publishBool(const char* prefix, const char* topic, const bool value, bool retain);
void publishString(const char* prefix, const char* topic, const char* value, bool retain);
void publish(const char *topic, const char *value, bool retain);
void removeTopic(const String& mqttPath, const String& mqttTopic);
void batteryTypeToString(const Nuki::BatteryType battype, char* str);
void advertisingModeToString(const Nuki::AdvertisingMode advmode, char* str);
void timeZoneIdToString(const Nuki::TimeZoneId timeZoneId, char* str);
void setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad);
void disableHASS();
void 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<std::pair<char*, char*>> additionalEntries
);
void removeHassTopic(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString);
int mqttConnectionState(); // 0 = not connected; 1 = connected; 2 = connected and mqtt processed
bool mqttRecentlyConnected();
bool pathEquals(const char* prefix, const char* path, const char* referencePath);
@@ -87,8 +108,6 @@ private:
NetworkDeviceType _networkDeviceType = (NetworkDeviceType)-1;
bool _firstBootAfterDeviceChange = false;
bool _webEnabled = true;
bool _updateFromMQTT = false;
bool _offEnabled = false;
#ifndef NUKI_HUB_UPDATER
static void onMqttDataReceivedCallback(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t len, size_t index, size_t total);
@@ -99,30 +118,16 @@ private:
void parseGpioTopics(const espMqttClientTypes::MessageProperties& properties, const char* topic, const uint8_t* payload, size_t& len, size_t& index, size_t& total);
void gpioActionCallback(const GpioAction& action, const int& pin);
bool comparePrefixedPath(const char* fullPath, const char* subPath);
String createHassTopicPath(const String& mqttDeviceType, const String& mqttDeviceName, const String& uidString);
JsonDocument 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<std::pair<char*, char*>> additionalEntries = {}
);
void buildMqttPath(char* outPath, std::initializer_list<const char*> paths);
void buildMqttPath(const char *path, char *outPath);
void buildMqttPath(char* outPath, std::initializer_list<const char*> paths);
const char* _lastWillPayload = "offline";
char _mqttConnectionStateTopic[211] = {0};
String _lockPath;
String _discoveryTopic;
String _brokerAddr;
HomeAssistantDiscovery* _hadiscovery = nullptr;
Gpio* _gpio;
int _mqttConnectionState = 0;

View File

@@ -1598,6 +1598,11 @@ uint8_t NukiNetworkLock::queryCommands()
return qc;
}
void NukiNetworkLock::setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad)
{
_network->setupHASS(type, nukiId, nukiName, firmwareVersion, hardwareVersion, hasDoorSensor, hasKeypad);
}
void NukiNetworkLock::buttonPressActionToString(const NukiLock::ButtonPressAction btnPressAction, char* str)
{
switch (btnPressAction)

View File

@@ -56,6 +56,7 @@ public:
void setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char* value));
void setAuthCommandReceivedCallback(void (*authCommandReceivedReceivedCallback)(const char* value));
void onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) override;
void setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad);
void publishFloat(const char* topic, const float value, bool retain, const uint8_t precision = 2);
void publishInt(const char* topic, const int value, bool retain);

View File

@@ -1556,6 +1556,11 @@ uint8_t NukiNetworkOpener::queryCommands()
return qc;
}
void NukiNetworkOpener::setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad)
{
_network->setupHASS(type, nukiId, nukiName, firmwareVersion, hardwareVersion, hasDoorSensor, hasKeypad);
}
void NukiNetworkOpener::buttonPressActionToString(const NukiOpener::ButtonPressAction btnPressAction, char* str)
{
switch (btnPressAction)

View File

@@ -47,6 +47,7 @@ public:
void setTimeControlCommandReceivedCallback(void (*timeControlCommandReceivedReceivedCallback)(const char* value));
void setAuthCommandReceivedCallback(void (*authCommandReceivedReceivedCallback)(const char* value));
void onMqttDataReceived(const char* topic, byte* payload, const unsigned int length) override;
void setupHASS(int type, uint32_t nukiId, char* nukiName, const char* firmwareVersion, const char* hardwareVersion, bool hasDoorSensor, bool hasKeypad);
int mqttConnectionState();
bool reconnected(); //SETBACK

View File

@@ -13,7 +13,6 @@ NukiOfficial::NukiOfficial(Preferences *preferences)
_disableNonJSON = preferences->getBool(preference_disable_non_json, false);
}
void NukiOfficial::setUid(const uint32_t& uid)
{
char uidString[20];
@@ -43,7 +42,6 @@ void NukiOfficial::setPublisher(NukiPublisher *publisher)
_publisher = publisher;
}
const char *NukiOfficial::getMqttPath() const
{
return mqttPath;
@@ -99,14 +97,14 @@ void NukiOfficial::onOfficialUpdateReceived(const char *topic, const char *value
Log->print(F("Connected: "));
Log->println((strcmp(value, "true") == 0 ? 1 : 0));
offConnected = (strcmp(value, "true") == 0 ? 1 : 0);
_publisher->publishBool(mqtt_hybrid_state, offConnected, true);
_publisher->publishBool(mqtt_topic_hybrid_state, offConnected, true);
}
else if(strcmp(topic, mqtt_topic_official_state) == 0)
{
offState = atoi(value);
_statusUpdated = true;
Log->println(F("Lock: Updating status on Hybrid state change"));
_publisher->publishBool(mqtt_hybrid_state, offConnected, true);
_publisher->publishBool(mqtt_topic_hybrid_state, offConnected, true);
NukiLock::lockstateToString((NukiLock::LockState)offState, str);
_publisher->publishString(mqtt_topic_lock_state, str, true);

View File

@@ -54,7 +54,7 @@ void NukiOpenerWrapper::initialize()
_nukiOpener.setConnectTimeout(3);
_nukiOpener.setDisconnectTimeout(5000);
_hassEnabled = _preferences->getString(preference_mqtt_hass_discovery) != "";
_hassEnabled = _preferences->getBool(preference_mqtt_hass_enabled, false);
readSettings();
}
@@ -313,7 +313,7 @@ void NukiOpenerWrapper::update()
}
if(_hassEnabled && _nukiConfigValid && _nukiAdvancedConfigValid && !_hassSetupCompleted)
{
_network->setupHASS(2);
_network->setupHASS(2, _nukiConfig.nukiId, (char*)_nukiConfig.name, _firmwareVersion.c_str(), _hardwareVersion.c_str(), false, _hasKeypad);
_hassSetupCompleted = true;
}
if(_rssiPublishInterval > 0 && (_nextRssiTs == 0 || ts > _nextRssiTs))

View File

@@ -1,6 +1,3 @@
#ifndef CONFIG_IDF_TARGET_ESP32H2
#include "esp_wifi.h"
#endif
#include "NukiWrapper.h"
#include "PreferencesKeys.h"
#include "MqttTopics.h"
@@ -50,7 +47,7 @@ NukiWrapper::~NukiWrapper()
}
void NukiWrapper::initialize(const bool& firstStart)
void NukiWrapper::initialize()
{
_nukiLock.initialize();
_nukiLock.registerBleScanner(_bleScanner);
@@ -58,75 +55,7 @@ void NukiWrapper::initialize(const bool& firstStart)
_nukiLock.setConnectTimeout(3);
_nukiLock.setDisconnectTimeout(5000);
if(firstStart)
{
Log->println("First start, setting preference defaults");
#ifndef CONFIG_IDF_TARGET_ESP32H2
wifi_config_t wifi_cfg;
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)
{
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)
{
Log->println("Failed to clear NVS Wi-Fi configuration");
}
#endif
_preferences->putString(preference_mqtt_lock_path, "nukihub");
_preferences->putBool(preference_check_updates, true);
_preferences->putBool(preference_opener_continuous_mode, false);
_preferences->putBool(preference_official_hybrid_enabled, false);
_preferences->putBool(preference_official_hybrid_actions, false);
_preferences->putBool(preference_official_hybrid_retry, false);
_preferences->putBool(preference_disable_non_json, false);
_preferences->putBool(preference_update_from_mqtt, false);
_preferences->putBool(preference_ip_dhcp_enabled, true);
_preferences->putBool(preference_enable_bootloop_reset, false);
_preferences->putBool(preference_show_secrets, false);
_preferences->putBool(preference_conf_info_enabled, true);
_preferences->putBool(preference_keypad_info_enabled, false);
_preferences->putBool(preference_keypad_topic_per_entry, false);
_preferences->putBool(preference_keypad_publish_code, false);
_preferences->putBool(preference_keypad_control_enabled, false);
_preferences->putBool(preference_timecontrol_info_enabled, false);
_preferences->putBool(preference_timecontrol_topic_per_entry, false);
_preferences->putBool(preference_timecontrol_control_enabled, false);
_preferences->putBool(preference_publish_authdata, false);
_preferences->putBool(preference_register_as_app, false);
_preferences->putBool(preference_register_opener_as_app, false);
_preferences->putInt(preference_mqtt_broker_port, 1883);
_preferences->putInt(preference_buffer_size, CHAR_BUFFER_SIZE);
_preferences->putInt(preference_task_size_network, NETWORK_TASK_SIZE);
_preferences->putInt(preference_task_size_nuki, NUKI_TASK_SIZE);
_preferences->putInt(preference_authlog_max_entries, MAX_AUTHLOG);
_preferences->putInt(preference_keypad_max_entries, MAX_KEYPAD);
_preferences->putInt(preference_timecontrol_max_entries, MAX_TIMECONTROL);
_preferences->putInt(preference_query_interval_hybrid_lockstate, 600);
_preferences->putInt(preference_rssi_publish_interval, 60);
_preferences->putInt(preference_network_timeout, 60);
_preferences->putInt(preference_command_nr_of_retries, 3);
_preferences->putInt(preference_command_retry_delay, 100);
_preferences->putInt(preference_restart_ble_beacon_lost, 60);
_preferences->putInt(preference_query_interval_lockstate, 1800);
_preferences->putInt(preference_query_interval_configuration, 3600);
_preferences->putInt(preference_query_interval_battery, 1800);
_preferences->putInt(preference_query_interval_keypad, 1800);
}
_hassEnabled = _preferences->getString(preference_mqtt_hass_discovery) != "";
_hassEnabled = _preferences->getBool(preference_mqtt_hass_enabled, false);
readSettings();
}
@@ -405,7 +334,7 @@ void NukiWrapper::update()
}
if(_hassEnabled && _nukiConfigValid && _nukiAdvancedConfigValid && !_hassSetupCompleted)
{
_network->setupHASS(1);
_network->setupHASS(1, _nukiConfig.nukiId, (char*)_nukiConfig.name, _firmwareVersion.c_str(), _hardwareVersion.c_str(), hasDoorSensor(), _hasKeypad);
_hassSetupCompleted = true;
}
if(_rssiPublishInterval > 0 && (_nextRssiTs == 0 || ts > _nextRssiTs))

View File

@@ -17,7 +17,7 @@ public:
NukiWrapper(const std::string& deviceName, NukiDeviceId* deviceId, BleScanner::Scanner* scanner, NukiNetworkLock* network, NukiOfficial* nukiOfficial, Gpio* gpio, Preferences* preferences);
virtual ~NukiWrapper();
void initialize(const bool& firstStart);
void initialize();
void readSettings();
void update();

View File

@@ -2,6 +2,9 @@
#include <vector>
#include "Config.h"
#ifndef CONFIG_IDF_TARGET_ESP32H2
#include "esp_wifi.h"
#endif
//CHANGE REQUIRES REBOOT TO TAKE EFFECT
#define preference_ip_dhcp_enabled (char*)"dhcpena"
@@ -129,17 +132,17 @@
#define preference_presence_detection_timeout (char*)"prdtimeout"
#define preference_network_wifi_fallback_disabled (char*)"nwwififb"
inline bool initPreferences(Preferences* preferences)
inline void initPreferences(Preferences* preferences)
{
#ifdef NUKI_HUB_UPDATER
bool firstStart = false;
return firstStart;
return;
#else
bool firstStart = !preferences->getBool(preference_started_before);
#endif
if(firstStart)
{
Serial.println("First start, setting preference defaults");
preferences->putBool(preference_started_before, true);
preferences->putBool(preference_lock_enabled, true);
uint32_t aclPrefs[17] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
@@ -152,6 +155,69 @@ inline bool initPreferences(Preferences* preferences)
preferences->putBytes(preference_conf_lock_advanced_acl, (byte*)(&advancedLockConfigAclPrefs), sizeof(advancedLockConfigAclPrefs));
uint32_t advancedOpenerConfigAclPrefs[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
preferences->putBytes(preference_conf_opener_advanced_acl, (byte*)(&advancedOpenerConfigAclPrefs), sizeof(advancedOpenerConfigAclPrefs));
#ifndef CONFIG_IDF_TARGET_ESP32H2
wifi_config_t wifi_cfg;
if(esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg) != ESP_OK)
{
Serial.println("Failed to get Wi-Fi configuration in RAM");
}
if (esp_wifi_set_storage(WIFI_STORAGE_FLASH) != ESP_OK)
{
Serial.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)
{
Serial.println("Failed to clear NVS Wi-Fi configuration");
}
#endif
preferences->putString(preference_mqtt_lock_path, "nukihub");
preferences->putBool(preference_check_updates, true);
preferences->putBool(preference_opener_continuous_mode, false);
preferences->putBool(preference_official_hybrid_enabled, false);
preferences->putBool(preference_official_hybrid_actions, false);
preferences->putBool(preference_official_hybrid_retry, false);
preferences->putBool(preference_disable_non_json, false);
preferences->putBool(preference_update_from_mqtt, false);
preferences->putBool(preference_ip_dhcp_enabled, true);
preferences->putBool(preference_enable_bootloop_reset, false);
preferences->putBool(preference_show_secrets, false);
preferences->putBool(preference_conf_info_enabled, true);
preferences->putBool(preference_keypad_info_enabled, false);
preferences->putBool(preference_keypad_topic_per_entry, false);
preferences->putBool(preference_keypad_publish_code, false);
preferences->putBool(preference_keypad_control_enabled, false);
preferences->putBool(preference_timecontrol_info_enabled, false);
preferences->putBool(preference_timecontrol_topic_per_entry, false);
preferences->putBool(preference_timecontrol_control_enabled, false);
preferences->putBool(preference_publish_authdata, false);
preferences->putBool(preference_register_as_app, false);
preferences->putBool(preference_register_opener_as_app, false);
preferences->putInt(preference_mqtt_broker_port, 1883);
preferences->putInt(preference_buffer_size, CHAR_BUFFER_SIZE);
preferences->putInt(preference_task_size_network, NETWORK_TASK_SIZE);
preferences->putInt(preference_task_size_nuki, NUKI_TASK_SIZE);
preferences->putInt(preference_authlog_max_entries, MAX_AUTHLOG);
preferences->putInt(preference_keypad_max_entries, MAX_KEYPAD);
preferences->putInt(preference_timecontrol_max_entries, MAX_TIMECONTROL);
preferences->putInt(preference_query_interval_hybrid_lockstate, 600);
preferences->putInt(preference_rssi_publish_interval, 60);
preferences->putInt(preference_network_timeout, 60);
preferences->putInt(preference_command_nr_of_retries, 3);
preferences->putInt(preference_command_retry_delay, 100);
preferences->putInt(preference_restart_ble_beacon_lost, 60);
preferences->putInt(preference_query_interval_lockstate, 1800);
preferences->putInt(preference_query_interval_configuration, 3600);
preferences->putInt(preference_query_interval_battery, 1800);
preferences->putInt(preference_query_interval_keypad, 1800);
}
else
{
@@ -266,8 +332,7 @@ inline bool initPreferences(Preferences* preferences)
preferences->putInt(preference_config_version, atof(NUKI_HUB_VERSION) * 100);
}
}
return firstStart;
#endif
}
class DebugPreferences

View File

@@ -1762,8 +1762,6 @@ bool WebCfgServer::processArgs(PsychicRequest *request, String& message)
configChanged = true;
}
}
HADEVDISC
else if(key == "HASSDISCOVERY")
{
if(_preferences->getString(preference_mqtt_hass_discovery, "") != value)
@@ -3539,12 +3537,12 @@ esp_err_t WebCfgServer::buildMqttConfigHtml(PsychicRequest *request)
printInputField(&response, "MQTTPASS", "MQTT Password", "*", 30, "", true, true);
printInputField(&response, "MQTTPATH", "MQTT NukiHub Path", _preferences->getString(preference_mqtt_lock_path).c_str(), 180, "");
printCheckBox(&response, "ENHADISC", "Enable Home Assistant auto discovery", _preferences->getBool(preference_mqtt_hass_enabled), "chkHass");
printCheckBox(&response, "HADEVDISC", "Use Home Assistant device based discovery", _preferences->getBool(preference_hass_device_discovery), "");
response.print("</table><br>");
response.print("<h3>Advanced MQTT Configuration</h3>");
response.print("<table>");
printInputField(&response, "HASSDISCOVERY", "Home Assistant discovery topic (usually \"homeassistant\")", _preferences->getString(preference_mqtt_hass_discovery).c_str(), 30, "class=\"chkHass\"");
//printCheckBox(&response, "HADEVDISC", "Use Home Assistant device based discovery (2024.11+)", _preferences->getBool(preference_hass_device_discovery), "");
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), "");

View File

@@ -2,7 +2,9 @@
#include <Preferences.h>
#include <PsychicHttp.h>
#ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE
#include <PsychicHttpsServer.h>
#endif
#include "esp_ota_ops.h"
#include "Config.h"

View File

@@ -446,7 +446,7 @@ void setup()
preferences = new Preferences();
preferences->begin("nukihub", false);
bool firstStart = initPreferences(preferences);
initPreferences(preferences);
bool doOta = false;
uint8_t partitionType = checkPartition();
@@ -468,13 +468,6 @@ void setup()
doOta = true;
}
#ifndef NUKI_HUB_UPDATER
if(preferences->getBool(preference_enable_bootloop_reset, false))
{
bootloopDetection();
}
#endif
#ifdef NUKI_HUB_UPDATER
Log->print(F("Nuki Hub OTA version "));
Log->println(NUKI_HUB_VERSION);
@@ -511,6 +504,11 @@ void setup()
});
}
#else
if(preferences->getBool(preference_enable_bootloop_reset, false))
{
bootloopDetection();
}
Log->print(F("Nuki Hub version "));
Log->println(NUKI_HUB_VERSION);
Log->print(F("Nuki Hub build "));
@@ -571,7 +569,7 @@ void setup()
}
nuki = new NukiWrapper("NukiHub", deviceIdLock, bleScanner, networkLock, nukiOfficial, gpio, preferences);
nuki->initialize(firstStart);
nuki->initialize();
}
Log->println(openerEnabled ? F("Nuki Opener enabled") : F("Nuki Opener disabled"));

View File

@@ -2,6 +2,7 @@
#include "../PreferencesKeys.h"
#include "../Logger.h"
#include "../RestartReason.h"
#include "../EspMillis.h"
extern bool ethCriticalFailure;
extern bool wifiFallback;
@@ -48,7 +49,9 @@ EthernetDevice::EthernetDevice(const String &hostname,
_useSpi(true),
_preferences(preferences)
{
#ifndef NUKI_HUB_UPDATER
NetworkDevice::init();
#endif
}
const String EthernetDevice::deviceName() const

View File

@@ -11,9 +11,6 @@
#include <NetworkClientSecure.h>
#include <Preferences.h>
#include "NetworkDevice.h"
#ifndef NUKI_HUB_UPDATER
#include "espMqttClient.h"
#endif
class EthernetDevice : public NetworkDevice
{
@@ -65,16 +62,20 @@ private:
void onNetworkEvent(arduino_event_id_t event, arduino_event_info_t info);
bool _connected = false;
char* _path;
bool _hardwareInitialized = false;
bool _useSpi = false;
int64_t _checkIpTs = -1;
const std::string _deviceName;
uint8_t _phy_addr;
eth_phy_type_t _type;
// LAN8720
int _power;
int _mdc;
int _mdio;
eth_clock_mode_t _clock_mode;
// W55000 and DM9051
int _cs;
@@ -83,10 +84,4 @@ private:
int _spi_sck;
int _spi_miso;
int _spi_mosi;
int64_t _checkIpTs = -1;
eth_phy_type_t _type;
eth_clock_mode_t _clock_mode;
bool _useSpi = false;
};

View File

@@ -2,19 +2,19 @@
#ifndef CONFIG_IDF_TARGET_ESP32
typedef enum {
ETH_CLOCK_GPIO0_IN = 0,
ETH_CLOCK_GPIO16_OUT = 2,
ETH_CLOCK_GPIO17_OUT = 3
} eth_clock_mode_t;
ETH_CLOCK_GPIO0_IN = 0,
ETH_CLOCK_GPIO16_OUT = 2,
ETH_CLOCK_GPIO17_OUT = 3
} eth_clock_mode_t;
#define ETH_PHY_TYPE_LAN8720 ETH_PHY_MAX
#define ETH_PHY_TYPE_LAN8720 ETH_PHY_MAX
#else
#define ETH_PHY_TYPE_LAN8720 ETH_PHY_LAN8720
#endif
#define ETH_CLK_MODE_LAN8720 ETH_CLOCK_GPIO0_IN
#define ETH_PHY_ADDR_LAN8720 0
#define ETH_PHY_MDC_LAN8720 23
#define ETH_PHY_MDIO_LAN8720 18
#define ETH_PHY_POWER_LAN8720 -1
#define ETH_RESET_PIN_LAN8720 1
#define ETH_CLK_MODE_LAN8720 ETH_CLOCK_GPIO0_IN
#define ETH_PHY_ADDR_LAN8720 0
#define ETH_PHY_MDC_LAN8720 23
#define ETH_PHY_MDIO_LAN8720 18
#define ETH_PHY_POWER_LAN8720 -1
#define ETH_RESET_PIN_LAN8720 1

View File

@@ -4,7 +4,7 @@
#ifndef NUKI_HUB_UPDATER
#include "../MqttTopics.h"
#include "espMqttClient.h"
#include "PreferencesKeys.h"
void NetworkDevice::init()
{
@@ -58,17 +58,38 @@ void NetworkDevice::update()
void NetworkDevice::mqttSetClientId(const char *clientId)
{
getMqttClient()->setClientId(clientId);
if (_useEncryption)
{
_mqttClientSecure->setClientId(clientId);
}
else
{
_mqttClient->setClientId(clientId);
}
}
void NetworkDevice::mqttSetCleanSession(bool cleanSession)
{
getMqttClient()->setCleanSession(cleanSession);
if (_useEncryption)
{
_mqttClientSecure->setCleanSession(cleanSession);
}
else
{
_mqttClient->setCleanSession(cleanSession);
}
}
void NetworkDevice::mqttSetKeepAlive(uint16_t keepAlive)
{
getMqttClient()->setKeepAlive(keepAlive);
if (_useEncryption)
{
_mqttClientSecure->setKeepAlive(keepAlive);
}
else
{
_mqttClient->setKeepAlive(keepAlive);
}
}
uint16_t NetworkDevice::mqttPublish(const char *topic, uint8_t qos, bool retain, const char *payload)
@@ -88,7 +109,14 @@ bool NetworkDevice::mqttConnected() const
void NetworkDevice::mqttSetServer(const char *host, uint16_t port)
{
getMqttClient()->setServer(host, port);
if (_useEncryption)
{
_mqttClientSecure->setServer(host, port);
}
else
{
_mqttClient->setServer(host, port);
}
}
bool NetworkDevice::mqttConnect()
@@ -101,29 +129,64 @@ bool NetworkDevice::mqttDisconnect(bool force)
return getMqttClient()->disconnect(force);
}
void NetworkDevice::setWill(const char *topic, uint8_t qos, bool retain, const char *payload)
void NetworkDevice::mqttSetWill(const char *topic, uint8_t qos, bool retain, const char *payload)
{
getMqttClient()->setWill(topic, qos, retain, payload);
if (_useEncryption)
{
_mqttClientSecure->setWill(topic, qos, retain, payload);
}
else
{
_mqttClient->setWill(topic, qos, retain, payload);
}
}
void NetworkDevice::mqttSetCredentials(const char *username, const char *password)
{
getMqttClient()->setCredentials(username, password);
if (_useEncryption)
{
_mqttClientSecure->setCredentials(username, password);
}
else
{
_mqttClient->setCredentials(username, password);
}
}
void NetworkDevice::mqttOnMessage(espMqttClientTypes::OnMessageCallback callback)
{
getMqttClient()->onMessage(callback);
if (_useEncryption)
{
_mqttClientSecure->onMessage(callback);
}
else
{
_mqttClient->onMessage(callback);
}
}
void NetworkDevice::mqttOnConnect(espMqttClientTypes::OnConnectCallback callback)
{
getMqttClient()->onConnect(callback);
if(_useEncryption)
{
_mqttClientSecure->onConnect(callback);
}
else
{
_mqttClient->onConnect(callback);
}
}
void NetworkDevice::mqttOnDisconnect(espMqttClientTypes::OnDisconnectCallback callback)
{
getMqttClient()->onDisconnect(callback);
if (_useEncryption)
{
_mqttClientSecure->onDisconnect(callback);
}
else
{
_mqttClient->onDisconnect(callback);
}
}
uint16_t NetworkDevice::mqttSubscribe(const char *topic, uint8_t qos)
@@ -131,7 +194,7 @@ uint16_t NetworkDevice::mqttSubscribe(const char *topic, uint8_t qos)
return getMqttClient()->subscribe(topic, qos);
}
void NetworkDevice::disableMqtt()
void NetworkDevice::mqttDisable()
{
getMqttClient()->disconnect();
_mqttEnabled = false;

View File

@@ -2,10 +2,8 @@
#ifndef NUKI_HUB_UPDATER
#include "espMqttClient.h"
#include "MqttClientSetup.h"
#endif
#include "IPConfiguration.h"
#include "../EspMillis.h"
class NetworkDevice
{
@@ -31,42 +29,45 @@ public:
virtual String BSSIDstr() = 0;
#ifndef NUKI_HUB_UPDATER
virtual bool mqttConnect();
virtual bool mqttDisconnect(bool force);
virtual void mqttDisable();
virtual bool mqttConnected() const;
virtual uint16_t mqttPublish(const char* topic, uint8_t qos, bool retain, const char* payload);
virtual uint16_t mqttPublish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length);
virtual uint16_t mqttSubscribe(const char* topic, uint8_t qos);
virtual void mqttSetServer(const char* host, uint16_t port);
virtual void mqttSetClientId(const char* clientId);
virtual void mqttSetCleanSession(bool cleanSession);
virtual void mqttSetKeepAlive(uint16_t keepAlive);
virtual uint16_t mqttPublish(const char* topic, uint8_t qos, bool retain, const char* payload);
virtual uint16_t mqttPublish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length);
virtual bool mqttConnected() const;
virtual void mqttSetServer(const char* host, uint16_t port);
virtual bool mqttConnect();
virtual bool mqttDisconnect(bool force);
virtual void setWill(const char* topic, uint8_t qos, bool retain, const char* payload);
virtual void mqttSetWill(const char* topic, uint8_t qos, bool retain, const char* payload);
virtual void mqttSetCredentials(const char* username, const char* password);
virtual void mqttOnMessage(espMqttClientTypes::OnMessageCallback callback);
virtual void mqttOnConnect(espMqttClientTypes::OnConnectCallback callback);
virtual void mqttOnDisconnect(espMqttClientTypes::OnDisconnectCallback callback);
virtual void disableMqtt();
virtual uint16_t mqttSubscribe(const char* topic, uint8_t qos);
#endif
protected:
const IPConfiguration* _ipConfiguration = nullptr;
Preferences* _preferences = nullptr;
#ifndef NUKI_HUB_UPDATER
espMqttClient *_mqttClient = nullptr;
espMqttClientSecure *_mqttClientSecure = nullptr;
bool _useEncryption = false;
bool _mqttEnabled = true;
void init();
MqttClient *getMqttClient() const;
bool _useEncryption = false;
bool _mqttEnabled = true;
char* _path;
char _ca[TLS_CA_MAX_SIZE] = {0};
char _cert[TLS_CERT_MAX_SIZE] = {0};
char _key[TLS_KEY_MAX_SIZE] = {0};
#endif
const String _hostname;
const IPConfiguration* _ipConfiguration = nullptr;
};

View File

@@ -1,9 +1,10 @@
#include "WifiDevice.h"
#include "esp_wifi.h"
#include <WiFi.h>
#include "WifiDevice.h"
#include "../PreferencesKeys.h"
#include "../Logger.h"
#include "../RestartReason.h"
#include "../EspMillis.h"
WifiDevice::WifiDevice(const String& hostname, Preferences* preferences, const IPConfiguration* ipConfiguration)
: NetworkDevice(hostname, preferences, ipConfiguration),

View File

@@ -1,7 +1,5 @@
#pragma once
#include <WiFiClient.h>
#include <NetworkClientSecure.h>
#include <Preferences.h>
#include "NetworkDevice.h"
#include "IPConfiguration.h"
@@ -29,10 +27,10 @@ private:
void onDisconnected();
void onConnected();
bool connect();
char* _path;
Preferences* _preferences = nullptr;
char* _path;
int _foundNetworks = 0;
int _disconnectCount = 0;
bool _connectOnScanDone = false;
@@ -45,4 +43,4 @@ private:
uint8_t _connectedChannel = 0;
uint8_t* _connectedBSSID;
int64_t _disconnectTs = 0;
};
};