Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
cziter15 committed Jun 16, 2024
2 parents 72e94db + dea0c86 commit 28fc323
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 47 deletions.
23 changes: 19 additions & 4 deletions platformio/libsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
# https://github.com/cziter15/ksIotFrameworkLib/blob/master/LICENSE

from logger import *
ksPrintLog(Colors.Green, "Running extra script for library.")

try:
Import("projenv", "env")
ksPrintLog(Colors.Green, "Running extra script for library.")

ksPrintLog(Colors.Magenta, "Building library environment list.")
environments = [env, DefaultEnvironment(), projenv]

for lb in env.GetLibBuilders():
environments.append(lb.env)

Expand All @@ -26,9 +26,24 @@
e.ProcessFlags("-DCORE_DEBUG_LEVEL=0")
e.ProcessFlags("-DNO_GLOBAL_ARDUINO_OTA=1")
e.ProcessFlags("-DWEBSOCKETS_SAVE_RAM=1")

# ESP32 version of Arduino has some changes for class names
if e["PIOPLATFORM"].startswith("espressif32"):
cpp_defines_dict = {}
for item in e["CPPDEFINES"]:
if isinstance(item, tuple):
key, value = item
cpp_defines_dict[key] = value
elif isinstance(item, str):
cpp_defines_dict[item] = 1
if (int(cpp_defines_dict.get('ARDUINO', None)) >= 10812):
e.ProcessFlags("-DWiFiClientSecure=NetworkClientSecure")
e.ProcessFlags("-DWiFiClient=NetworkClient")
e.ProcessFlags("-DWiFiServer=NetworkServer")
e.ProcessFlags("-DWiFiUDP=NetworkUDP")
e.ProcessFlags("-DARDUINO_3_OR_ABOVE=1")

ksPrintLog(Colors.Magenta, "Successfully manipulated flags on [" + str(len(environments)) + "] environments.")

ksPrintLog(Colors.Magenta, "Successfully tweaked platform settings for [" + str(len(environments)) + "] environments.")
ksPrintLog(Colors.Green, "Extra script finished.")
except BaseException as err:
ksPrintLog(Colors.Red, "Error while executing script. Are you on newest platformio core?")
Expand Down
3 changes: 0 additions & 3 deletions src/ksf/comp/ksMqttConfigProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@
#pragma once

#include "ksConfigProvider.h"

class WiFiManager;

namespace ksf::comps
{
class ksMqttConnector;
Expand Down
48 changes: 24 additions & 24 deletions src/ksf/comp/ksMqttConnector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ namespace ksf::comps
cfgProvider.setupMqttConnector(*this);

/*
Object mqttClientSp is created by setupConnection method.
Object mqttClientUq is created by setupConnection method.
That means init will return false when no MQTT config file found.
*/
return mqttClientSp != nullptr;
return mqttClientUq != nullptr;
}

bool ksMqttConnector::postInit(ksApplication* app)
Expand All @@ -69,18 +69,18 @@ namespace ksf::comps
certFingerprint = std::make_unique<ksCertFingerprintHolder>();

if (certFingerprint->setup(secureClient.get(), fingerprint))
wifiClientSp = std::move(secureClient);
wifiClientUq = std::move(secureClient);
}
else
{
wifiClientSp = std::make_unique<WiFiClient>();
wifiClientUq = std::make_unique<WiFiClient>();
}

/* Whoops, it looks like fingerprint validation failed. */
if (!wifiClientSp)
if (!wifiClientUq)
return;

mqttClientSp = std::make_unique<PubSubClient>(*wifiClientSp.get());
mqttClientUq = std::make_unique<PubSubClient>(*wifiClientUq.get());

this->login = std::move(login);
this->password = std::move(password);
Expand All @@ -104,9 +104,9 @@ namespace ksf::comps
*/

#if ESP32
wifiClientSp->setTimeout(KSF_MQTT_TIMEOUT_SEC);
wifiClientUq->setTimeout(KSF_MQTT_TIMEOUT_SEC);
#elif ESP8266
wifiClientSp->setTimeout(KSF_SEC_TO_MS(KSF_MQTT_TIMEOUT_SEC));
wifiClientUq->setTimeout(KSF_SEC_TO_MS(KSF_MQTT_TIMEOUT_SEC));
#else
#error Platform not implemented.
#endif
Expand All @@ -118,7 +118,7 @@ namespace ksf::comps
void ksMqttConnector::mqttConnectedInternal()
{
lastSuccessConnectionTime = millis64();
mqttClientSp->setCallback(std::bind(&ksMqttConnector::mqttMessageInternal, this, _1, _2, _3));
mqttClientUq->setCallback(std::bind(&ksMqttConnector::mqttMessageInternal, this, _1, _2, _3));
onConnected->broadcast();
}

Expand Down Expand Up @@ -155,12 +155,12 @@ namespace ksf::comps
void ksMqttConnector::subscribe(const std::string& topic, bool skipDevicePrefix, ksMqttConnector::QosLevel qos)
{
uint8_t qosLevel{static_cast<uint8_t>(qos)};
mqttClientSp->subscribe(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str(), qosLevel);
mqttClientUq->subscribe(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str(), qosLevel);
}

void ksMqttConnector::unsubscribe(const std::string& topic, bool skipDevicePrefix)
{
mqttClientSp->unsubscribe(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str());
mqttClientUq->unsubscribe(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str());
}

void ksMqttConnector::publish(const std::string& topic, const std::string& payload, bool retain, bool skipDevicePrefix)
Expand All @@ -177,7 +177,7 @@ namespace ksf::comps
out += payload;
});
#endif
mqttClientSp->publish(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str(), reinterpret_cast<const uint8_t*>(payload.c_str()), payload.length(), retain);
mqttClientUq->publish(skipDevicePrefix ? topic.c_str() : std::string(prefix + topic).c_str(), reinterpret_cast<const uint8_t*>(payload.c_str()), payload.length(), retain);
}

bool ksMqttConnector::connectToBroker()
Expand All @@ -191,51 +191,51 @@ namespace ksf::comps
#endif
/* Handle connection manually. */
if (IPAddress serverIP; serverIP.fromString(this->broker.c_str()))
wifiClientSp->connect(serverIP, portNumber);
wifiClientUq->connect(serverIP, portNumber);
else
wifiClientSp->connect(this->broker.c_str(), portNumber);
wifiClientUq->connect(this->broker.c_str(), portNumber);

/* If not connected, return. */
if (!wifiClientSp->connected())
if (!wifiClientUq->connected())
return false;

/* Verify certificate fingerprint. */
if (certFingerprint && !certFingerprint->verify(reinterpret_cast<WiFiClientSecure*>(wifiClientSp.get())))
if (certFingerprint && !certFingerprint->verify(reinterpret_cast<WiFiClientSecure*>(wifiClientUq.get())))
{
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] Invalid certificate fingerprint! Disconnecting.");
});
#endif
wifiClientSp->stop();
wifiClientUq->stop();
return false;
}

std::string willTopic{prefix + PSTR("connected")};
if (mqttClientSp->connect(WiFi.macAddress().c_str(), login.c_str(), password.c_str(), willTopic.c_str(), 0, true, "0", !usePersistentSession))
if (mqttClientUq->connect(WiFi.macAddress().c_str(), login.c_str(), password.c_str(), willTopic.c_str(), 0, true, "0", !usePersistentSession))
{
#ifdef APP_LOG_ENABLED
app->log([&](std::string& out) {
out += PSTR("[MQTT] Connected successfully to ");
out += wifiClientSp->remoteIP().toString().c_str();
out += wifiClientUq->remoteIP().toString().c_str();
out += PSTR(" on port ");
out += ksf::to_string(wifiClientSp->remotePort());
out += ksf::to_string(wifiClientUq->remotePort());
});
#endif

mqttClientSp->publish(willTopic.c_str(), reinterpret_cast<const uint8_t*>("1"), 1, true);
mqttClientUq->publish(willTopic.c_str(), reinterpret_cast<const uint8_t*>("1"), 1, true);
return true;
}

return false;
}

return mqttClientSp->connect(WiFi.macAddress().c_str(), login.c_str(), password.c_str(), 0, 0, false, 0, !usePersistentSession);
return mqttClientUq->connect(WiFi.macAddress().c_str(), login.c_str(), password.c_str(), 0, 0, false, 0, !usePersistentSession);
}

bool ksMqttConnector::loop(ksApplication* app)
{
if (!mqttClientSp->loop())
if (!mqttClientUq->loop())
{
if (wasConnected)
{
Expand Down Expand Up @@ -265,7 +265,7 @@ namespace ksf::comps

bool ksMqttConnector::isConnected() const
{
return mqttClientSp ? mqttClientSp->connected() : false;
return mqttClientUq ? mqttClientUq->connected() : false;
}

uint32_t ksMqttConnector::getConnectionTimeSeconds() const
Expand Down
4 changes: 2 additions & 2 deletions src/ksf/comp/ksMqttConnector.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ namespace ksf
#if APP_LOG_ENABLED
ksApplication* app{nullptr}; //!< Application pointer.
#endif
std::unique_ptr<WiFiClient> wifiClientSp; //!< Shared pointer to WiFiClient used to connect to MQTT.
std::unique_ptr<PubSubClient> mqttClientSp; //!< Shared pointer to PubSubClient used to connect to MQTT.
std::unique_ptr<WiFiClient> wifiClientUq; //!< Shared pointer to WiFiClient used to connect to MQTT.
std::unique_ptr<PubSubClient> mqttClientUq; //!< Shared pointer to PubSubClient used to connect to MQTT.

std::weak_ptr<ksWifiConnector> wifiConnWp; //!< Weak pointer to WiFi connector.

Expand Down
26 changes: 12 additions & 14 deletions src/ksf/ksConstants.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <esp_phy_init.h>
#include <nvs_flash.h>
#include <esp_task_wdt.h>
#include <esp_arduino_version.h>
#include "sdkconfig.h"
#elif ESP8266
#include <ESP8266WiFi.h>
Expand Down Expand Up @@ -39,20 +40,17 @@ namespace ksf

void initializeFramework()
{
#ifdef ESP32
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)
/* Setup watchdog. */
esp_task_wdt_config_t twdt_config = {
.timeout_ms = KSF_WATCHDOG_TIMEOUT_SECS * 1000,
.idle_core_mask = (1 << CONFIG_SOC_CPU_CORES_NUM) - 1, // Bitmask of all cores
.trigger_panic = false,
};

esp_task_wdt_init(&twdt_config);
#else
/* Setup watchdog. */
esp_task_wdt_init(KSF_WATCHDOG_TIMEOUT_SECS, true);
#endif
#if ESP32
#if (ESP_ARDUINO_VERSION_MAJOR >= 3)
esp_task_wdt_config_t twdt_config = {
.timeout_ms = KSF_WATCHDOG_TIMEOUT_SECS * 1000,
.idle_core_mask = (1 << CONFIG_SOC_CPU_CORES_NUM) - 1,
.trigger_panic = true,
};
esp_task_wdt_init(&twdt_config);
#else
esp_task_wdt_init(KSF_WATCHDOG_TIMEOUT_SECS * 1000, true);
#endif
/* Initialize filesystem. */
LittleFS.begin(true);
#endif
Expand Down

0 comments on commit 28fc323

Please sign in to comment.