fix: harden configuration and runtime state handling

This commit is contained in:
Yurii committed 2026-11-25 03:36:46 +03:00
1 parent f3f8ce5861
commit 65df4b7f5a
9 files changed
+372 -275

No files matched your search

+16 -6
View File
@@ -188,6 +188,10 @@ public:
return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI;
}
static bool isEqualAddress(const uint8_t* addr1, const uint8_t* addr2, const uint8_t length = 8) {
return memcmp(addr1, addr2, length) == 0;
}
static bool isDifferent(const Settings& previous, const Settings& current) {
return previous.enabled != current.enabled
|| strcmp(previous.name, current.name) != 0
@@ -195,7 +199,7 @@ public:
|| previous.purpose != current.purpose
|| previous.type != current.type
|| previous.gpio != current.gpio
|| memcmp(previous.address, current.address, sizeof(previous.address)) != 0
|| !isEqualAddress(previous.address, current.address)
|| isFloatDifferent(previous.offset, current.offset, 0.0001f)
|| isFloatDifferent(previous.factor, current.factor, 0.0001f)
|| previous.filtering != current.filtering
@@ -553,7 +557,7 @@ public:
return false;
}
if (memcmp(settings[sensorId].address, address, sizeof(Settings::address)) == 0) {
if (isEqualAddress(settings[sensorId].address, address)) {
return true;
}
@@ -609,19 +613,25 @@ public:
uint8_t amount = 0;
if (avgType == AverageType::MEAN) {
float sum = 0.0f;
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
auto& sSensor = settings[id];
auto& rSensor = results[id];
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
sum += rSensor.values[valueId];
const float reading = rSensor.values[valueId];
amount++;
// Opposite-sign readings can overflow when subtracted.
if ((value < 0.0f) != (reading < 0.0f)) {
value -= value / amount;
value += reading / amount;
} else {
value += (reading - value) / amount;
}
}
}
value = amount == 1 ? sum : (sum / amount);
} else if (avgType == AverageType::MINIMUM) {
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
auto& sSensor = settings[id];
+6
View File
@@ -14,6 +14,12 @@ enum class ChannelDisablingAction : uint8_t {
OFF_AND_ZERO_SETPOINT = 2
};
enum class PumpStartReason {
NONE,
HEATING,
ANTISTUCK
};
enum class EthernetType : uint8_t {
NONE = 0,
W5500 = 1
+189 -149
View File
@@ -5,6 +5,7 @@
#include <FileData.h>
#include <LittleFS.h>
#include <cmath>
#include <cstring>
#include <string>
#include <string_view>
@@ -373,11 +374,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_HOSTNAME].is<JsonString>()) {
const JsonString value = src[S_HOSTNAME].as<JsonString>();
if (value.size() < sizeof(dst.hostname) && isHostnameValid(value.c_str())) {
result.accepted = true;
if (strcmp(value.c_str(), dst.hostname) != 0) {
strcpy(dst.hostname, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.hostname) && isHostnameValid(value.c_str())) {
result.accepted = true;
if (strcmp(value.c_str(), dst.hostname) != 0) {
strcpy(dst.hostname, value.c_str());
result.changed = true;
}
}
}
}
@@ -398,11 +401,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_STATIC_CONFIG][S_IP].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_IP].as<JsonString>();
if (value.size() < sizeof(dst.staticConfig.ip)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.ip) != 0) {
strcpy(dst.staticConfig.ip, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.ip)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.ip) != 0) {
strcpy(dst.staticConfig.ip, value.c_str());
result.changed = true;
}
}
}
}
@@ -410,11 +415,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_STATIC_CONFIG][S_GATEWAY].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_GATEWAY].as<JsonString>();
if (value.size() < sizeof(dst.staticConfig.gateway)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.gateway) != 0) {
strcpy(dst.staticConfig.gateway, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.gateway)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.gateway) != 0) {
strcpy(dst.staticConfig.gateway, value.c_str());
result.changed = true;
}
}
}
}
@@ -422,11 +429,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_STATIC_CONFIG][S_SUBNET].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_SUBNET].as<JsonString>();
if (value.size() < sizeof(dst.staticConfig.subnet)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.subnet) != 0) {
strcpy(dst.staticConfig.subnet, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.subnet)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.subnet) != 0) {
strcpy(dst.staticConfig.subnet, value.c_str());
result.changed = true;
}
}
}
}
@@ -434,11 +443,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (src[S_STATIC_CONFIG][S_DNS].is<JsonString>()) {
const JsonString value = src[S_STATIC_CONFIG][S_DNS].as<JsonString>();
if (value.size() < sizeof(dst.staticConfig.dns)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.dns) != 0) {
strcpy(dst.staticConfig.dns, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.staticConfig.dns)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.staticConfig.dns) != 0) {
strcpy(dst.staticConfig.dns, value.c_str());
result.changed = true;
}
}
}
}
@@ -452,11 +463,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (ap[S_SSID].is<JsonString>()) {
const JsonString value = ap[S_SSID].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.wifi.ap.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.ap.ssid) != 0) {
strcpy(dst.wifi.ap.ssid, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.wifi.ap.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.ap.ssid) != 0) {
strcpy(dst.wifi.ap.ssid, value.c_str());
result.changed = true;
}
}
}
}
@@ -464,11 +477,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (ap[S_PASSWORD].is<JsonString>()) {
const JsonString value = ap[S_PASSWORD].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.wifi.ap.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.ap.password) != 0) {
strcpy(dst.wifi.ap.password, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.wifi.ap.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.ap.password) != 0) {
strcpy(dst.wifi.ap.password, value.c_str());
result.changed = true;
}
}
}
}
@@ -491,11 +506,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (sta[S_SSID].is<JsonString>()) {
const JsonString value = sta[S_SSID].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.wifi.sta.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.sta.ssid) != 0) {
strcpy(dst.wifi.sta.ssid, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.wifi.sta.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.sta.ssid) != 0) {
strcpy(dst.wifi.sta.ssid, value.c_str());
result.changed = true;
}
}
}
}
@@ -503,11 +520,13 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
if (sta[S_PASSWORD].is<JsonString>()) {
const JsonString value = sta[S_PASSWORD].as<JsonString>();
if (value.size() < sizeof(dst.wifi.sta.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.sta.password) != 0) {
strcpy(dst.wifi.sta.password, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.wifi.sta.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.wifi.sta.password) != 0) {
strcpy(dst.wifi.sta.password, value.c_str());
result.changed = true;
}
}
}
}
@@ -651,11 +670,13 @@ SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) {
if (src[S_NTP][S_SERVER].is<JsonString>()) {
const JsonString value = src[S_NTP][S_SERVER].as<JsonString>();
if (value.size() < sizeof(dst.ntp.server)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ntp.server) != 0) {
strcpy(dst.ntp.server, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.ntp.server)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ntp.server) != 0) {
strcpy(dst.ntp.server, value.c_str());
result.changed = true;
}
}
}
}
@@ -663,11 +684,13 @@ SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) {
if (src[S_NTP][S_TIMEZONE].is<JsonString>()) {
const JsonString value = src[S_NTP][S_TIMEZONE].as<JsonString>();
if (value.size() < sizeof(dst.ntp.timezone)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ntp.timezone) != 0) {
strcpy(dst.ntp.timezone, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.ntp.timezone)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ntp.timezone) != 0) {
strcpy(dst.ntp.timezone, value.c_str());
result.changed = true;
}
}
}
}
@@ -750,11 +773,13 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
if (src[S_LOGIN].is<JsonString>()) {
const JsonString value = src[S_LOGIN].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.login)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.login) != 0) {
strcpy(dst.login, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.login)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.login) != 0) {
strcpy(dst.login, value.c_str());
result.changed = true;
}
}
}
}
@@ -762,11 +787,13 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) {
if (src[S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_PASSWORD].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.password) != 0) {
strcpy(dst.password, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.password) != 0) {
strcpy(dst.password, value.c_str());
result.changed = true;
}
}
}
}
@@ -1206,11 +1233,13 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
if (src[S_SERVER].is<JsonString>()) {
const JsonString value = src[S_SERVER].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.server)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.server) != 0) {
strcpy(dst.server, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.server)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.server) != 0) {
strcpy(dst.server, value.c_str());
result.changed = true;
}
}
}
}
@@ -1230,11 +1259,13 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
if (src[S_USER].is<JsonString>()) {
const JsonString value = src[S_USER].as<JsonString>();
if (value.size() < sizeof(dst.user)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.user) != 0) {
strcpy(dst.user, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.user)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.user) != 0) {
strcpy(dst.user, value.c_str());
result.changed = true;
}
}
}
}
@@ -1242,11 +1273,13 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
if (src[S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_PASSWORD].as<JsonString>();
if (value.size() < sizeof(dst.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.password) != 0) {
strcpy(dst.password, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() < sizeof(dst.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.password) != 0) {
strcpy(dst.password, value.c_str());
result.changed = true;
}
}
}
}
@@ -1254,11 +1287,13 @@ SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) {
if (src[S_PREFIX].is<JsonString>()) {
const JsonString value = src[S_PREFIX].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.prefix)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.prefix) != 0) {
strcpy(dst.prefix, value.c_str());
result.changed = true;
if (strlen(value.c_str()) == value.size()) {
if (value.size() && value.size() < sizeof(dst.prefix)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.prefix) != 0) {
strcpy(dst.prefix, value.c_str());
result.changed = true;
}
}
}
}
@@ -3129,31 +3164,34 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
// name
if (src[S_NAME].is<JsonString>()) {
const auto raw = src[S_NAME].as<JsonString>();
const auto value = Sensors::cleanName(std::string_view(raw.c_str(), raw.size()));
const JsonString raw = src[S_NAME].as<JsonString>();
if (value.size() < sizeof(dst.name) && value != dst.name) {
const auto slug = Sensors::makeSlug(value);
bool unique = true;
if (Sensors::settings != nullptr && !slug.empty()) {
// The caller holds Sensors::mutex while checking configured sensor slugs.
for (uint8_t id = 0; id <= Sensors::getMaxSensorId(); id++) {
if (&Sensors::settings[id] != &dst && slug == Sensors::settings[id].slug) {
unique = false;
break;
if (strlen(raw.c_str()) == raw.size()) {
const auto value = Sensors::cleanName(std::string_view(raw.c_str(), raw.size()));
if (value.size() < sizeof(dst.name) && value != dst.name) {
const auto slug = Sensors::makeSlug(value);
bool unique = true;
if (Sensors::settings != nullptr && !slug.empty()) {
// The caller holds Sensors::mutex while checking configured sensor slugs.
for (uint8_t id = 0; id <= Sensors::getMaxSensorId(); id++) {
if (&Sensors::settings[id] != &dst && slug == Sensors::settings[id].slug) {
unique = false;
break;
}
}
}
}
if (unique) {
if (unique) {
result.accepted = true;
strcpy(dst.name, value.c_str());
strcpy(dst.slug, slug.c_str());
result.changed = true;
}
} else if (value.size() < sizeof(dst.name)) {
result.accepted = true;
strcpy(dst.name, value.c_str());
strcpy(dst.slug, slug.c_str());
result.changed = true;
}
} else if (value.size() < sizeof(dst.name)) {
result.accepted = true;
}
}
@@ -3290,58 +3328,60 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
if (src[S_ADDRESS].is<JsonString>()) {
const JsonString value = src[S_ADDRESS].as<JsonString>();
if (dst.type == Sensors::Type::DALLAS_TEMP) {
uint8_t tmp[8];
int parsed = sscanf(
value.c_str(),
"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
&tmp[0], &tmp[1], &tmp[2], &tmp[3],
&tmp[4], &tmp[5], &tmp[6], &tmp[7]
);
if (strlen(value.c_str()) == value.size()) {
if (dst.type == Sensors::Type::DALLAS_TEMP) {
uint8_t tmp[8];
int parsed = sscanf(
value.c_str(),
"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
&tmp[0], &tmp[1], &tmp[2], &tmp[3],
&tmp[4], &tmp[5], &tmp[6], &tmp[7]
);
if (parsed == 8) {
result.accepted = true;
for (uint8_t i = 0; i < parsed; i++) {
if (dst.address[i] != tmp[i]) {
dst.address[i] = tmp[i];
result.changed = true;
if (parsed == 8) {
result.accepted = true;
for (uint8_t i = 0; i < parsed; i++) {
if (dst.address[i] != tmp[i]) {
dst.address[i] = tmp[i];
result.changed = true;
}
}
}
} else {
// reset
for (uint8_t i = 0; i < sizeof(dst.address); i++) {
dst.address[i] = 0x00;
}
result.changed = true;
}
} else if (dst.type == Sensors::Type::BLUETOOTH) {
uint8_t tmp[6];
int parsed = sscanf(
value.c_str(),
"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
&tmp[0], &tmp[1], &tmp[2],
&tmp[3], &tmp[4], &tmp[5]
);
if (parsed == 6) {
result.accepted = true;
for (uint8_t i = 0; i < parsed; i++) {
if (dst.address[i] != tmp[i]) {
dst.address[i] = tmp[i];
result.changed = true;
} else {
// reset
for (uint8_t i = 0; i < sizeof(dst.address); i++) {
dst.address[i] = 0x00;
}
result.changed = true;
}
} else {
// reset
for (uint8_t i = 0; i < sizeof(dst.address); i++) {
dst.address[i] = 0x00;
}
} else if (dst.type == Sensors::Type::BLUETOOTH) {
uint8_t tmp[6];
int parsed = sscanf(
value.c_str(),
"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
&tmp[0], &tmp[1], &tmp[2],
&tmp[3], &tmp[4], &tmp[5]
);
result.changed = true;
if (parsed == 6) {
result.accepted = true;
for (uint8_t i = 0; i < parsed; i++) {
if (dst.address[i] != tmp[i]) {
dst.address[i] = tmp[i];
result.changed = true;
}
}
} else {
// reset
for (uint8_t i = 0; i < sizeof(dst.address); i++) {
dst.address[i] = 0x00;
}
result.changed = true;
}
}
}
}
+7 -7
View File
@@ -1,13 +1,12 @@
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <app.h>
#include <esp_timer.h>
#include <algorithm>
Variables vars;
enum class PumpStartReason {NONE, HEATING, ANTISTUCK};
static bool heatingEnabled = false;
static unsigned long heatingDisabledTime = 0;
static PumpStartReason extPumpStartReason = PumpStartReason::NONE;
@@ -352,6 +351,7 @@ static Task cascadeTask("Cascade", [](void*) {
static Task externalPumpTask("External pump", [](void*) {
static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED;
const uint32_t now = esp_timer_get_time() / 1000000;
if (settings.externalPump.gpio != configuredGpio) {
if (configuredGpio != GPIO_IS_NOT_CONFIGURED) {
@@ -371,7 +371,7 @@ static Task externalPumpTask("External pump", [](void*) {
if (configuredGpio == GPIO_IS_NOT_CONFIGURED) {
if (vars.externalPump.state) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = millis();
vars.externalPump.lastEnabledTime = now;
ESP_LOGI(L_EXTPUMP, "Disabled: use = off");
}
@@ -390,7 +390,7 @@ static Task externalPumpTask("External pump", [](void*) {
if (!settings.externalPump.use) {
if (vars.externalPump.state) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = millis();
vars.externalPump.lastEnabledTime = now;
ESP_LOGI(L_EXTPUMP, "Disabled: use = off");
}
@@ -398,13 +398,13 @@ static Task externalPumpTask("External pump", [](void*) {
} else if (vars.externalPump.state && !heatingEnabled) {
if (extPumpStartReason == PumpStartReason::HEATING && millis() - heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = millis();
vars.externalPump.lastEnabledTime = now;
ESP_LOGI(L_EXTPUMP, "Disabled: expired post circulation time");
} else if (extPumpStartReason == PumpStartReason::ANTISTUCK && millis() - externalPumpStartTime >= (settings.externalPump.antiStuckTime * 1000u)) {
vars.externalPump.state = false;
vars.externalPump.lastEnabledTime = millis();
vars.externalPump.lastEnabledTime = now;
ESP_LOGI(L_EXTPUMP, "Disabled: expired anti stuck time");
}
@@ -419,7 +419,7 @@ static Task externalPumpTask("External pump", [](void*) {
ESP_LOGI(L_EXTPUMP, "Enabled: heating on");
} else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || millis() - vars.externalPump.lastEnabledTime >= (settings.externalPump.antiStuckInterval * 1000lu))) {
} else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || now - vars.externalPump.lastEnabledTime >= settings.externalPump.antiStuckInterval)) {
vars.externalPump.state = true;
externalPumpStartTime = millis();
extPumpStartReason = PumpStartReason::ANTISTUCK;
+50 -21
View File
@@ -83,29 +83,28 @@ std::string mqttTopic(std::initializer_list<std::string_view> parts) {
return topic;
}
static void publishValue(const std::string& topic, std::string_view value) {
mqttClient->publish(topic.c_str(), value, true);
static bool publishValue(const std::string& topic, std::string_view value) {
return mqttClient->publish(topic.c_str(), value, true);
}
static void publishValue(const std::string& topic, const char* value) {
publishValue(topic, std::string_view(value));
static bool publishValue(const std::string& topic, const char* value) {
return publishValue(topic, std::string_view(value));
}
static void publishValue(const std::string& topic, bool value) {
publishValue(topic, value ? S_TRUE : S_FALSE);
static bool publishValue(const std::string& topic, bool value) {
return publishValue(topic, value ? S_TRUE : S_FALSE);
}
static void publishValue(const std::string& topic, float value, uint8_t decimals = 2) {
static bool publishValue(const std::string& topic, float value, uint8_t decimals = 2) {
if (!std::isfinite(value)) {
// Remove an obsolete retained reading instead of publishing nan/inf.
publishValue(topic, "");
return;
return publishValue(topic, "");
}
char payload[64];
const int length = snprintf(payload, sizeof(payload), "%.*f", decimals, value);
if (length < 0 || static_cast<size_t>(length) >= sizeof(payload)) {
return;
return false;
}
if (decimals) {
@@ -117,7 +116,8 @@ static void publishValue(const std::string& topic, float value, uint8_t decimals
*end = '\0';
}
}
publishValue(topic, payload);
return publishValue(topic, payload);
}
static void publishHeatingSettings() {
@@ -354,19 +354,24 @@ static bool isCommandValid(const std::string& topic, std::string_view payload) {
return true;
}
static void publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) {
static bool publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) {
if (!sensor.slug[0]) {
return;
return false;
}
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED), result.connected)) {
return false;
}
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED), result.connected);
if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DALLAS_TEMP
|| sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) {
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY), std::to_string(result.signalQuality));
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY), std::to_string(result.signalQuality))) {
return false;
}
}
if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) {
publishValue(
const bool published = publishValue(
mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE),
convertTemp(
result.values[static_cast<uint8_t>(Sensors::ValueType::TEMPERATURE)],
@@ -374,15 +379,27 @@ static void publishSensor(const Sensors::Settings& sensor, const Sensors::Result
),
3
);
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast<uint8_t>(Sensors::ValueType::HUMIDITY)], 3);
if (!published) {
return false;
}
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast<uint8_t>(Sensors::ValueType::HUMIDITY)], 3)) {
return false;
}
if (sensor.type == Sensors::Type::BLUETOOTH) {
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast<uint8_t>(Sensors::ValueType::BATTERY)], 1);
publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast<uint8_t>(Sensors::ValueType::RSSI)], 0);
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast<uint8_t>(Sensors::ValueType::BATTERY)], 1)) {
return false;
}
if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast<uint8_t>(Sensors::ValueType::RSSI)], 0)) {
return false;
}
}
} else {
publishValue(
const bool published = publishValue(
mqttTopic(S_SENSORS, sensor.slug, S_VALUE),
Sensors::convertValue(
sensor, Sensors::ValueType::PRIMARY,
@@ -391,7 +408,13 @@ static void publishSensor(const Sensors::Settings& sensor, const Sensors::Result
),
3
);
if (!published) {
return false;
}
}
return true;
}
static bool purgeSensor(const char* slug) {
@@ -1047,7 +1070,13 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
mqttPublishedSensorAt[sensorId] = snapshotAt;
}
publishSensor(snapshot->settings, snapshot->result);
if (!publishSensor(snapshot->settings, snapshot->result)) {
{
std::lock_guard<std::mutex> lock(mqttSensorsMutex);
mqttPublishedSensorAt[sensorId] = 0;
}
ESP_LOGD(L_MQTT, "Sensor publication deferred");
}
}
});
+73 -60
View File
@@ -243,6 +243,64 @@ static Task initializeSlaveTask("Initialize slave", [](void*) {
initializedTime = millis();
});
static void onDisconnectSlave() {
if (vars.slave.connected) {
ESP_LOGW(
L_OT,
"Disconnected, uptime: %lu s.",
(millis() - connectedTime) / 1000
);
// Mark sensors as disconnected
Sensors::setConnectionStatusByType(Sensors::Type::OT_OUTDOOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_RETURN_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_FLOW_RATE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CH2_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_PRESSURE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_MODULATION_LEVEL, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CURRENT_POWER, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_CO2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_CURRENT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_COOLING_HOURS, false);
initializeSlaveTask.resume();
disconnectedTime = millis();
vars.slave.connected = false;
}
vars.slave.heating.enabled = false;
vars.slave.heating.active = false;
vars.slave.dhw.enabled = false;
vars.slave.dhw.active = false;
vars.slave.ch2.active = false;
vars.slave.flame = false;
vars.slave.cooling.active = false;
vars.slave.cooling.setpoint = 0;
vars.slave.fault.active = false;
vars.slave.fault.code = 0;
vars.slave.diag.active = false;
vars.slave.diag.code = 0;
}
static bool isSlaveReady() {
return canUseBus() && vars.slave.connected && !initializeSlaveTask.scheduled();
}
@@ -300,6 +358,8 @@ static Task configureDriverTask("Configure OpenTherm driver", Task::Type::ONCE,
return;
}
onDisconnectSlave();
if (!GPIO_IS_VALID_INPUT(settings.opentherm.inGpio) || !GPIO_IS_VALID_OUTPUT(settings.opentherm.outGpio)) {
ESP_LOGW(
L_OT,
@@ -383,6 +443,9 @@ static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) {
initializeSlaveTask.resume();
}
// Apply channel settings even while the bus is unavailable.
updateMasterState();
if (slave.getConfig().rxGpio != settings.opentherm.inGpio ||
slave.getConfig().txGpio != settings.opentherm.outGpio) {
maintainOpenThermTask.setInterval(5000);
@@ -390,6 +453,8 @@ static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) {
} else if (!slave.isInitialized()) {
// A fatal error can leave the RMT worker alive until end() succeeds.
onDisconnectSlave();
if (!slave.end() || !slave.begin()) {
ESP_LOGW(L_OT, "Failed begin");
@@ -415,8 +480,6 @@ static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) {
configuredRxLedGpio.store(settings.opentherm.rxLedGpio);
}
}
updateMasterState();
});
static Task readStatusTask("Read boiler status", [](void*) {
@@ -503,11 +566,6 @@ static Task readStatusTask("Read boiler status", [](void*) {
);
}
// 5 request retries
// 1000ms maximum response waiting time
// 100ms delay between requests
// +15%
// 5 * (1000 + 100) * 1.15 = 6325 ms
if (!vars.slave.connected && validStatus) {
ESP_LOGI(
L_OT,
@@ -517,64 +575,19 @@ static Task readStatusTask("Read boiler status", [](void*) {
connectedTime = millis();
vars.slave.connected = true;
}
} else if (vars.slave.connected && !validStatus && millis() - lastSuccessStatusResponse > 6325) {
ESP_LOGW(
L_OT,
"Disconnected, uptime: %lu s.",
(millis() - connectedTime) / 1000
);
// Mark sensors as disconnected
Sensors::setConnectionStatusByType(Sensors::Type::OT_OUTDOOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_RETURN_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_TEMP2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_FLOW_RATE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CH2_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_PRESSURE, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_MODULATION_LEVEL, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_CURRENT_POWER, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_CO2, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_FAN_SPEED_CURRENT, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_STARTS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_BURNER_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_HEATING_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_DHW_PUMP_HOURS, false);
Sensors::setConnectionStatusByType(Sensors::Type::OT_COOLING_HOURS, false);
initializeSlaveTask.resume();
disconnectedTime = millis();
vars.slave.connected = false;
// 5 request retries
// 1000ms maximum response waiting time
// 100ms delay between requests
// +15%
// 5 * (1000 + 100) * 1.15 = 6325 ms
if (vars.slave.connected && !validStatus && millis() - lastSuccessStatusResponse > 6325) {
onDisconnectSlave();
}
// If boiler is disconnected, no need try setting other OT stuff
if (!vars.slave.connected) {
vars.slave.heating.enabled = false;
vars.slave.heating.active = false;
vars.slave.dhw.enabled = false;
vars.slave.dhw.active = false;
vars.slave.flame = false;
vars.slave.cooling.active = false;
vars.slave.cooling.setpoint = 0;
vars.slave.fault.active = false;
vars.slave.fault.code = 0;
vars.slave.diag.active = false;
vars.slave.diag.code = 0;
// reset bus
if (millis() - disconnectedTime > resetBusInterval) {
if (millis() - resetBusTime > resetBusInterval) {
+26 -14
View File
@@ -402,7 +402,7 @@ static void restApi() {
return request->send(503);
}
if (requestDoc.isNull() || !requestDoc.size()) {
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
return request->send(400);
}
@@ -715,7 +715,7 @@ static void restApi() {
return request->send(503);
}
if (requestDoc.isNull() || !requestDoc.size()) {
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
return request->send(400);
}
@@ -729,30 +729,42 @@ static void restApi() {
return request->send(404);
}
const auto previousSettings = Sensors::getSettings(*sensorId);
if (!previousSettings) {
return request->send(404);
}
Sensors::Settings previousSettings;
bool isDifferent = false;
SettingResult result;
{
std::lock_guard<std::mutex> lock(Sensors::mutex);
if (Sensors::settings == nullptr || Sensors::results == nullptr) {
return request->send(404);
}
auto& sensor = Sensors::settings[*sensorId];
previousSettings = sensor;
result = fromJson(requestDoc, sensor);
if (result.changed) {
isDifferent |= previousSettings->enabled != sensor.enabled;
isDifferent |= strcmp(previousSettings->name, sensor.name) != 0;
isDifferent |= strcmp(previousSettings->slug, sensor.slug) != 0;
isDifferent |= previousSettings->purpose != sensor.purpose;
isDifferent |= previousSettings->type != sensor.type;
isDifferent |= previousSettings.enabled != sensor.enabled;
isDifferent |= strcmp(previousSettings.name, sensor.name) != 0;
isDifferent |= strcmp(previousSettings.slug, sensor.slug) != 0;
isDifferent |= previousSettings.purpose != sensor.purpose;
isDifferent |= previousSettings.type != sensor.type;
bool resetResult = previousSettings.enabled != sensor.enabled;
resetResult |= previousSettings.type != sensor.type;
resetResult |= previousSettings.gpio != sensor.gpio;
resetResult |= !Sensors::isEqualAddress(previousSettings.address, sensor.address);
// A different source must provide its own readings and filter baseline.
if (resetResult) {
Sensors::results[*sensorId] = {};
Sensors::results[*sensorId].updatedAt = millis();
}
}
}
if (result.changed) {
if (isDifferent) {
requestReconfigureMqttSensor(*sensorId, *previousSettings);
requestReconfigureMqttSensor(*sensorId, previousSettings);
}
requestSaveSensorsSettings();
@@ -872,7 +884,7 @@ static void restApi() {
return request->send(503);
}
if (requestDoc.isNull() || !requestDoc.size()) {
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
return request->send(400);
}
+3 -2
View File
@@ -207,9 +207,10 @@ static Task regulatorTask("Regulator", [](void*) {
turbo();
hysteresis();
vars.master.heating.targetTemp = settings.heating.target;
const float setpointTemp = getHeatingSetpointTemp();
vars.master.heating.targetTemp = settings.opentherm.options.nativeOTC
? setpointTemp
: settings.heating.target;
vars.master.heating.setpointTemp = roundf(constrain(
setpointTemp,
getHeatingMinSetpointTemp(),
+2 -16
View File
@@ -349,20 +349,6 @@ static NimBLEScan* pBLEScan = nullptr;
static bool activeScanBle = false;
#endif
static bool isEqualAddress(const uint8_t *addr1, const uint8_t *addr2, const uint8_t length = 8) {
return memcmp(addr1, addr2, length) == 0;
/*bool result = true;
for (uint8_t i = 0; i < length; i++) {
if (addr1[i] != addr2[i]) {
result = false;
break;
}
}
return result;*/
}
static bool isEmptyAddress(const uint8_t *addr, const uint8_t length = 8) {
bool result = true;
@@ -437,7 +423,7 @@ static void makeDallasInstances() {
continue;
}
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) {
if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED || !GPIO_IS_VALID_OUTPUT(sSensor->gpio)) {
continue;
} else if (dallasInstances.count(sSensor->gpio)) {
@@ -571,7 +557,7 @@ static void fillingAddressesDallasSensors() {
continue;
}
if (isEqualAddress(sCheckingSensor->address, devAddr)) {
if (Sensors::isEqualAddress(sCheckingSensor->address, devAddr)) {
freeAddress = false;
break;
}