refactor: migrate ESP32 firmware to task-managed services

Split the header-based firmware into services for OpenTherm, heating control, sensors, networking, logging, and the portal. Run these services with MycilaTaskManager and use ESP32OT for the boiler bus.

Move MQTT and Home Assistant discovery to Mycila libraries, expose native crash metrics, and align the board profiles and build hooks with the new dependencies.
This commit is contained in:
Yurii committed 2026-11-22 02:34:37 +03:00
1 parent b10d91b8fa
commit 3fb433d3eb
48 files changed
+14464 -12650

No files matched your search

+806
View File
@@ -0,0 +1,806 @@
#pragma once
#include <Arduino.h>
#include <esp_log.h>
#include <errno.h>
#include <cmath>
#include <functional>
#include <math.h>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <stdlib.h>
#include <string.h>
#include "macros.h"
#include "utils.h"
#include "strings_shared.h"
class Sensors {
protected:
static uint8_t maxSensors;
public:
enum class Type : uint8_t {
OT_OUTDOOR_TEMP = 0,
OT_HEATING_TEMP = 1,
OT_HEATING_RETURN_TEMP = 2,
OT_DHW_TEMP = 3,
OT_DHW_TEMP2 = 4,
OT_DHW_FLOW_RATE = 5,
OT_CH2_TEMP = 6,
OT_EXHAUST_TEMP = 7,
OT_HEAT_EXCHANGER_TEMP = 8,
OT_PRESSURE = 9,
OT_MODULATION_LEVEL = 10,
OT_CURRENT_POWER = 11,
OT_EXHAUST_CO2 = 12,
OT_EXHAUST_FAN_SPEED = 13,
OT_SUPPLY_FAN_SPEED = 14,
OT_SOLAR_STORAGE_TEMP = 15,
OT_SOLAR_COLLECTOR_TEMP = 16,
OT_FAN_SPEED_SETPOINT = 17,
OT_FAN_SPEED_CURRENT = 18,
OT_BURNER_STARTS = 19,
OT_DHW_BURNER_STARTS = 20,
OT_HEATING_PUMP_STARTS = 21,
OT_DHW_PUMP_STARTS = 22,
OT_BURNER_HOURS = 23,
OT_DHW_BURNER_HOURS = 24,
OT_HEATING_PUMP_HOURS = 25,
OT_DHW_PUMP_HOURS = 26,
OT_COOLING_HOURS = 27,
NTC_10K_TEMP = 50,
DALLAS_TEMP = 51,
BLUETOOTH = 52,
DHT11 = 53,
DHT22 = 54,
HEATING_SETPOINT_TEMP = 253,
MANUAL = 254,
NOT_CONFIGURED = 255
};
enum class Purpose : uint8_t {
OUTDOOR_TEMP = 0,
INDOOR_TEMP = 1,
HEATING_TEMP = 2,
HEATING_RETURN_TEMP = 3,
DHW_TEMP = 4,
DHW_RETURN_TEMP = 5,
DHW_FLOW_RATE = 6,
EXHAUST_TEMP = 7,
MODULATION_LEVEL = 8,
NUMBER = 247,
POWER_FACTOR = 248,
POWER = 249,
FAN_SPEED = 250,
CO2 = 251,
PRESSURE = 252,
HUMIDITY = 253,
TEMPERATURE = 254,
NOT_CONFIGURED = 255
};
enum class ValueType : uint8_t {
PRIMARY = 0,
TEMPERATURE = 0,
HUMIDITY = 1,
BATTERY = 2,
RSSI = 3
};
enum class AverageType : uint8_t {
MEAN = 0,
MINIMUM = 1,
MAXIMUM = 2
};
typedef struct {
bool enabled = false;
char name[33];
char slug[33] = {};
Purpose purpose = Purpose::NOT_CONFIGURED;
Type type = Type::NOT_CONFIGURED;
uint8_t gpio = GPIO_IS_NOT_CONFIGURED;
uint8_t address[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
float offset = 0.0f;
float factor = 1.0f;
bool filtering = false;
float filteringFactor = 0.15f;
} Settings;
typedef struct {
bool connected = false;
unsigned long activityAt = 0;
unsigned long updatedAt = 0;
uint8_t signalQuality = 100;
//float raw[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float values[4] = {0.0f, 0.0f, 0.0f, 0.0f};
} Result;
struct Snapshot {
Settings settings;
Result result;
};
// Set the backing pointers before starting workers.
// Methods lock internally; hold mutex when accessing the arrays directly.
static Settings* settings;
static Result* results;
static std::mutex mutex;
static std::optional<Settings> getSettings(uint8_t sensorId) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || !isValidSensorId(sensorId)) {
return std::nullopt;
}
return settings[sensorId];
}
static std::optional<Snapshot> getSnapshot(uint8_t sensorId) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
return std::nullopt;
}
return Snapshot{settings[sensorId], results[sensorId]};
}
static inline void setMaxSensors(uint8_t value) {
// The slot count and backing arrays are configured before starting workers.
maxSensors = value;
}
static inline uint8_t getMaxSensors() {
return maxSensors;
}
static uint8_t getMaxSensorId() {
uint8_t maxSensors = getMaxSensors();
return maxSensors > 1 ? (maxSensors - 1) : 0;
}
template <class T>
static bool isValidSensorId(const T id) {
return id >= 0 && id <= getMaxSensorId();
}
static std::optional<uint8_t> parseId(const char* value) {
if (!isDigit(value)) {
return std::nullopt;
}
errno = 0;
const unsigned long parsed = strtoul(value, nullptr, 10);
if (errno == ERANGE || !isValidSensorId(parsed)) {
return std::nullopt;
}
return static_cast<uint8_t>(parsed);
}
static inline bool isValidValueId(const uint8_t id) {
return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI;
}
static bool isDifferent(const Settings& previous, const Settings& current) {
return previous.enabled != current.enabled
|| strcmp(previous.name, current.name) != 0
|| strcmp(previous.slug, current.slug) != 0
|| previous.purpose != current.purpose
|| previous.type != current.type
|| previous.gpio != current.gpio
|| memcmp(previous.address, current.address, sizeof(previous.address)) != 0
|| isFloatDifferent(previous.offset, current.offset, 0.0001f)
|| isFloatDifferent(previous.factor, current.factor, 0.0001f)
|| previous.filtering != current.filtering
|| isFloatDifferent(previous.filteringFactor, current.filteringFactor, 0.0001f);
}
static bool hasEnabledAndValid(const Settings& sensor) {
return sensor.enabled
&& sensor.slug[0] != '\0'
&& sensor.type != Type::NOT_CONFIGURED
&& sensor.purpose != Purpose::NOT_CONFIGURED;
}
static bool hasEnabledAndValid(const uint8_t id) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || !isValidSensorId(id)) {
return false;
}
return hasEnabledAndValid(settings[id]);
}
static uint8_t getAmountByType(Type type, bool onlyEnabled = false) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr) {
return 0;
}
uint8_t amount = 0;
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
if (settings[id].type == type && (!onlyEnabled || settings[id].enabled)) {
amount++;
}
}
return amount;
}
static std::optional<uint8_t> getIdByName(const char* name) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr) {
return std::nullopt;
}
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
if (strcmp(settings[id].name, name) == 0) {
return id;
}
}
return std::nullopt;
}
static std::optional<uint8_t> getIdBySlug(const char* slug) {
if (slug == nullptr || !slug[0]) {
return std::nullopt;
}
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr) {
return std::nullopt;
}
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
if (strcmp(settings[id].slug, slug) == 0) {
return id;
}
}
return std::nullopt;
}
static float convertValue(const Settings& sensor, const ValueType valueType, float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
if (valueType != ValueType::PRIMARY || unitFrom == unitTo) {
return value;
}
if (sensor.type == Type::HEATING_SETPOINT_TEMP && value == 0) {
return 0;
}
Purpose purpose = sensor.purpose;
if (sensor.type != Type::MANUAL) {
switch (sensor.type) {
case Type::OT_OUTDOOR_TEMP:
case Type::OT_HEATING_TEMP:
case Type::OT_HEATING_RETURN_TEMP:
case Type::OT_DHW_TEMP:
case Type::OT_DHW_TEMP2:
case Type::OT_CH2_TEMP:
case Type::OT_EXHAUST_TEMP:
case Type::OT_HEAT_EXCHANGER_TEMP:
case Type::OT_SOLAR_STORAGE_TEMP:
case Type::OT_SOLAR_COLLECTOR_TEMP:
case Type::NTC_10K_TEMP:
case Type::DALLAS_TEMP:
case Type::BLUETOOTH:
case Type::DHT11:
case Type::DHT22:
case Type::HEATING_SETPOINT_TEMP:
purpose = Purpose::TEMPERATURE;
break;
case Type::OT_PRESSURE:
purpose = Purpose::PRESSURE;
break;
case Type::OT_DHW_FLOW_RATE:
purpose = Purpose::DHW_FLOW_RATE;
break;
default:
return value;
}
}
switch (purpose) {
case Purpose::OUTDOOR_TEMP:
case Purpose::INDOOR_TEMP:
case Purpose::HEATING_TEMP:
case Purpose::HEATING_RETURN_TEMP:
case Purpose::DHW_TEMP:
case Purpose::DHW_RETURN_TEMP:
case Purpose::EXHAUST_TEMP:
case Purpose::TEMPERATURE:
return convertTemp(value, unitFrom, unitTo);
case Purpose::PRESSURE:
return convertPressure(value, unitFrom, unitTo);
case Purpose::DHW_FLOW_RATE:
return convertVolume(value, unitFrom, unitTo);
default:
return value;
}
}
static bool setValueById(const uint8_t sensorId, float value, const ValueType valueType, const bool updateActivityAt = false, const bool markConnected = false) {
const uint8_t valueId = static_cast<uint8_t>(valueType);
char name[sizeof(Settings::name)];
float compensatedValue = value;
float loggedValue;
bool connectedChanged;
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId) || !isValidValueId(valueId)) {
return false;
}
const auto& sensor = settings[sensorId];
auto& result = results[sensorId];
if (sensor.type == Type::HEATING_SETPOINT_TEMP || sensor.type == Type::MANUAL) {
result.values[valueId] = compensatedValue;
} else {
if (valueType == ValueType::PRIMARY) {
if (fabsf(sensor.factor) > 0.001f) {
compensatedValue *= sensor.factor;
}
if (fabsf(sensor.offset) > 0.001f) {
compensatedValue += sensor.offset;
}
} else if (valueType == ValueType::RSSI) {
if (sensor.type == Type::BLUETOOTH) {
result.signalQuality = Sensors::bluetoothRssiToQuality(value);
}
}
if (sensor.filtering && fabsf(result.values[valueId]) >= 0.1f) {
result.values[valueId] += (compensatedValue - result.values[valueId]) * sensor.filteringFactor;
} else {
result.values[valueId] = compensatedValue;
}
}
const auto now = millis();
result.updatedAt = now;
if (updateActivityAt) {
result.activityAt = now;
}
connectedChanged = markConnected && !result.connected;
if (connectedChanged) {
result.connected = true;
}
memcpy(name, sensor.name, sizeof(name));
loggedValue = result.values[valueId];
}
if (connectedChanged) {
logConnectionStatus(sensorId, name, true);
}
ESP_LOGI(
L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f",
sensorId, name, valueId, loggedValue, compensatedValue, value
);
return true;
}
static bool setManualValueById(uint8_t sensorId, float value, const UnitSystem srcUnit) {
char name[sizeof(Settings::name)];
bool connectedChanged;
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
return false;
}
const auto& sensor = settings[sensorId];
if (!sensor.enabled || sensor.type != Type::MANUAL) {
return false;
}
value = convertValue(sensor, ValueType::PRIMARY, value, srcUnit, UnitSystem::METRIC);
if (!std::isfinite(value)) {
return false;
}
results[sensorId].values[static_cast<uint8_t>(ValueType::PRIMARY)] = value;
connectedChanged = applyConnectionStatus(sensorId, true, true);
memcpy(name, sensor.name, sizeof(name));
}
if (connectedChanged) {
logConnectionStatus(sensorId, name, true);
}
ESP_LOGI(
L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f",
sensorId, name, static_cast<uint8_t>(ValueType::PRIMARY), value, value, value
);
return true;
}
static std::optional<uint8_t> setManualValueBySlug(std::string_view slug, float value, const UnitSystem srcUnit) {
if (slug.empty()) {
return std::nullopt;
}
std::optional<uint8_t> sensorId;
char name[sizeof(Settings::name)];
bool connectedChanged = false;
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr) {
return std::nullopt;
}
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
const auto& sensor = settings[id];
if (!sensor.enabled || sensor.type != Type::MANUAL) {
continue;
}
if (slug != sensor.slug) {
continue;
}
value = convertValue(sensor, ValueType::PRIMARY, value, srcUnit, UnitSystem::METRIC);
if (!std::isfinite(value)) {
return std::nullopt;
}
sensorId = id;
results[id].values[static_cast<uint8_t>(ValueType::PRIMARY)] = value;
connectedChanged = applyConnectionStatus(id, true, true);
memcpy(name, sensor.name, sizeof(name));
break;
}
}
if (!sensorId) {
return std::nullopt;
}
if (connectedChanged) {
logConnectionStatus(*sensorId, name, true);
}
ESP_LOGI(
L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f",
*sensorId, name, static_cast<uint8_t>(ValueType::PRIMARY), value, value, value
);
return sensorId;
}
static uint8_t setValueByType(Type type, float value, const ValueType valueType, const bool updateActivityAt = false, const bool markConnected = false) {
uint8_t updated = 0;
for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) {
const auto sensor = getSettings(sensorId);
if (!sensor || !sensor->enabled || sensor->type != type) {
continue;
}
if (setValueById(sensorId, value, valueType, updateActivityAt, markConnected)) {
updated++;
}
}
return updated;
}
static bool getConnectionStatusById(const uint8_t sensorId) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
return false;
}
return results[sensorId].connected;
}
static bool setConnectionStatusById(const uint8_t sensorId, const bool status, const bool updateActivityAt = true) {
char name[sizeof(Settings::name)];
bool changed;
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
return false;
}
changed = applyConnectionStatus(sensorId, status, updateActivityAt);
memcpy(name, settings[sensorId].name, sizeof(name));
}
if (changed) {
logConnectionStatus(sensorId, name, status);
}
return true;
}
static uint8_t setConnectionStatusByType(Type type, const bool status, const bool updateActivityAt = true) {
uint8_t updated = 0;
for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) {
char name[sizeof(Settings::name)];
bool changed;
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr) {
return updated;
}
const auto& sensor = settings[sensorId];
if (!sensor.enabled || sensor.type != type) {
continue;
}
changed = applyConnectionStatus(sensorId, status, updateActivityAt);
memcpy(name, sensor.name, sizeof(name));
}
if (changed) {
logConnectionStatus(sensorId, name, status);
}
updated++;
}
return updated;
}
static bool adjustSignalQuality(uint8_t sensorId, int8_t delta) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId)) {
return false;
}
int value = constrain(results[sensorId].signalQuality + delta, 0, 100);
if (value != results[sensorId].signalQuality) {
results[sensorId].signalQuality = static_cast<uint8_t>(value);
results[sensorId].updatedAt = millis();
}
return true;
}
static bool setAddressById(uint8_t sensorId, const uint8_t* address, const std::function<void()>& onUpdated = nullptr) {
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || address == nullptr || !isValidSensorId(sensorId)) {
return false;
}
if (memcmp(settings[sensorId].address, address, sizeof(Settings::address)) == 0) {
return true;
}
memcpy(settings[sensorId].address, address, sizeof(Settings::address));
}
if (onUpdated) {
onUpdated();
}
return true;
}
static bool updateConnectionStatusById(uint8_t sensorId, unsigned long wiredTimeout, unsigned long wirelessTimeout) {
char name[sizeof(Settings::name)];
{
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr || !isValidSensorId(sensorId) || !results[sensorId].connected) {
return false;
}
const auto& sensor = settings[sensorId];
const auto& result = results[sensorId];
bool disconnected = !hasEnabledAndValid(sensor);
if (!disconnected) {
const auto timeout = sensor.type == Type::MANUAL || sensor.type == Type::BLUETOOTH
? wirelessTimeout
: wiredTimeout;
disconnected = millis() - result.activityAt > timeout;
}
if (!disconnected) {
return false;
}
applyConnectionStatus(sensorId, false, false);
memcpy(name, sensor.name, sizeof(name));
}
logConnectionStatus(sensorId, name, false);
return true;
}
static float getMeanValueByPurpose(Purpose purpose, const ValueType valueType, const AverageType avgType = AverageType::MEAN, const bool onlyConnected = true, const float defaultValue = NAN) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr) {
return defaultValue;
}
uint8_t valueId = (uint8_t) valueType;
if (!isValidValueId(valueId)) {
return defaultValue;
}
float value = 0.0f;
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];
amount++;
}
}
value = amount == 1 ? sum : (sum / amount);
} else if (avgType == AverageType::MINIMUM) {
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
auto& sSensor = settings[id];
auto& rSensor = results[id];
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
if (amount == 0 || rSensor.values[valueId] < value) {
value = rSensor.values[valueId];
amount++;
}
}
}
} else if (avgType == AverageType::MAXIMUM) {
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
auto& sSensor = settings[id];
auto& rSensor = results[id];
if (sSensor.purpose == purpose && (!onlyConnected || rSensor.connected)) {
if (amount == 0 || rSensor.values[valueId] > value) {
value = rSensor.values[valueId];
amount++;
}
}
}
}
return amount > 0 ? value : defaultValue;
}
static bool existsConnectedSensorsByPurpose(Purpose purpose) {
std::lock_guard<std::mutex> lock(mutex);
if (settings == nullptr || results == nullptr) {
return false;
}
for (uint8_t id = 0; id <= getMaxSensorId(); id++) {
if (settings[id].purpose == purpose && results[id].connected) {
return true;
}
}
return false;
}
static std::string& cleanName(std::string& value, char space = ' ') {
for (char& symbol : value) {
if (symbol >= '0' && symbol <= '9') {
continue;
}
if (symbol >= 'A' && symbol <= 'Z') {
continue;
}
if (symbol >= 'a' && symbol <= 'z') {
continue;
}
if (symbol == '_' || symbol == '-' || symbol == space) {
continue;
}
symbol = space;
}
// trim
const auto first = value.find_first_not_of(" \t\r\n\f\v");
if (first == std::string::npos) {
value.clear();
return value;
}
value.erase(value.find_last_not_of(" \t\r\n\f\v") + 1);
value.erase(0, first);
return value;
}
static std::string cleanName(std::string_view value, char space = ' ') {
std::string result(value);
cleanName(result, space);
return result;
}
static std::string& makeSlug(std::string& result, std::string_view value, char separator = '_') {
result.assign(value);
cleanName(result);
for (char& symbol : result) {
if (symbol >= 'A' && symbol <= 'Z') {
symbol += 'a' - 'A';
}
if (symbol == ' ') {
symbol = separator;
}
}
return result;
}
static std::string makeSlug(std::string_view value, char separator = '_') {
std::string result;
makeSlug(result, value, separator);
return result;
}
static std::string makeSlugWithSuffix(std::string_view value, std::string_view suffix, char separator = '_') {
std::string result;
result.reserve(value.size() + 1 + suffix.size());
makeSlug(result, value, separator);
result += separator;
result.append(suffix);
return result;
}
static std::string& makeSlugWithSuffix(std::string& result, std::string_view value, std::string_view suffix, char separator = '_') {
result = makeSlugWithSuffix(value, suffix, separator);
return result;
}
static std::string makeSlugWithPrefix(std::string_view value, std::string_view prefix, char separator = '_') {
std::string result;
result.reserve(prefix.size() + 1 + value.size());
makeSlug(result, value, separator);
result.insert(0, 1, separator);
result.insert(0, prefix);
return result;
}
static std::string& makeSlugWithPrefix(std::string& result, std::string_view value, std::string_view prefix, char separator = '_') {
result = makeSlugWithPrefix(value, prefix, separator);
return result;
}
static uint8_t bluetoothRssiToQuality(int rssi) {
return constrain(map(rssi, -110, -50, 0, 100), 0, 100);;
}
private:
// The caller holds mutex; the status log is emitted after it is released.
static bool applyConnectionStatus(uint8_t sensorId, bool status, bool updateActivityAt) {
auto& result = results[sensorId];
const bool changed = result.connected != status;
result.connected = status;
if (changed || updateActivityAt) {
const auto now = millis();
result.updatedAt = now;
if (updateActivityAt) {
result.activityAt = now;
}
}
return changed;
}
static void logConnectionStatus(uint8_t sensorId, const char* name, bool status) {
ESP_LOGI(
L_SENSORS, "#%hhu '%s' new status: %s",
sensorId, name, status ? "CONNECTED" : "DISCONNECTED"
);
}
static constexpr bool isDigit(const char* value) {
if (value == nullptr || *value == '\0') {
return false;
}
while (*value != '\0') {
if (*value < '0' || *value > '9') {
return false;
}
value++;
}
return true;
}
};
inline uint8_t Sensors::maxSensors = 0;
inline Sensors::Settings* Sensors::settings = nullptr;
inline Sensors::Result* Sensors::results = nullptr;
inline std::mutex Sensors::mutex;
+390
View File
@@ -0,0 +1,390 @@
#pragma once
#include <esp_log.h>
#include <atomic>
#include "macros.h"
#include "types.h"
#include "Sensors.h"
struct NetworkSettings {
char hostname[25] = DEFAULT_HOSTNAME;
bool useDhcp = true;
struct {
char ip[16] = "192.168.0.100";
char gateway[16] = "192.168.0.1";
char subnet[16] = "255.255.255.0";
char dns[16] = "192.168.0.1";
} staticConfig;
struct {
char ssid[33] = DEFAULT_AP_SSID;
char password[65] = DEFAULT_AP_PASSWORD;
uint8_t channel = 6;
} ap;
struct {
char ssid[33] = DEFAULT_STA_SSID;
char password[65] = DEFAULT_STA_PASSWORD;
uint8_t channel = 0;
} sta;
};
struct SystemSettings {
esp_log_level_t logLevel = static_cast<esp_log_level_t>(DEFAULT_LOG_LEVEL);
struct {
bool enabled = DEFAULT_SERIAL_ENABLED;
unsigned int baudrate = DEFAULT_SERIAL_BAUD;
} serial;
struct {
bool enabled = DEFAULT_WEBSERIAL_ENABLED;
} webSerial;
struct {
char server[49] = "pool.ntp.org";
char timezone[49] = "UTC0";
} ntp;
UnitSystem unitSystem = UnitSystem::METRIC;
uint8_t statusLedGpio = DEFAULT_STATUS_LED_GPIO;
};
struct PortalSettings {
bool auth = false;
char login[13] = DEFAULT_PORTAL_LOGIN;
char password[33] = DEFAULT_PORTAL_PASSWORD;
bool mdns = true;
};
struct OpenThermSettings {
uint8_t inGpio = DEFAULT_OT_IN_GPIO;
uint8_t outGpio = DEFAULT_OT_OUT_GPIO;
uint8_t rxLedGpio = DEFAULT_OT_RX_LED_GPIO;
uint8_t memberId = 0;
uint8_t flags = 0;
ChannelDisablingAction heatingDisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT;
ChannelDisablingAction dhwDisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT;
ChannelDisablingAction ch2DisablingAction = ChannelDisablingAction::OFF_AND_ZERO_SETPOINT;
float minPower = 0.0f;
float maxPower = 0.0f;
struct {
bool dhwSupport = true;
bool coolingSupport = false;
bool summerWinterMode = false;
bool heatingStateToSummerWinterMode = false;
bool ch2AlwaysEnabled = true;
bool heatingToCh2 = false;
bool dhwToCh2 = false;
bool dhwBlocking = false;
bool dhwStateAsDhwBlocking = false;
bool maxTempSyncWithTargetTemp = true;
bool getMinMaxTemp = true;
bool ignoreDiagState = false;
bool autoFaultReset = false;
bool autoDiagReset = false;
bool setDateAndTime = false;
bool alwaysSendIndoorTemp = true;
bool nativeOTC = false;
bool immergasFix = false;
} options;
};
struct MqttSettings {
bool enabled = DEFAULT_MQTT_ENABLED;
char server[81] = DEFAULT_MQTT_SERVER;
unsigned short port = DEFAULT_MQTT_PORT;
char user[33] = DEFAULT_MQTT_USER;
char password[33] = DEFAULT_MQTT_PASSWORD;
char prefix[33] = DEFAULT_MQTT_PREFIX;
unsigned short interval = 5;
bool homeAssistantDiscovery = true;
};
struct EmergencySettings {
float target = DEFAULT_HEATING_TARGET_TEMP;
unsigned short tresholdTime = 120;
};
struct HeatingSettings {
bool enabled = true;
bool turbo = false;
float target = DEFAULT_HEATING_TARGET_TEMP;
float turboFactor = 7.5f;
uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP;
uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP;
uint8_t maxModulation = 100;
Sensors::AverageType indoorTempAvgType = Sensors::AverageType::MEAN;
Sensors::AverageType outdoorTempAvgType = Sensors::AverageType::MEAN;
struct {
bool enabled = true;
float value = 0.5f;
} hysteresis;
struct {
uint8_t highTemp = 95;
uint8_t lowTemp = 90;
} overheatProtection;
struct {
uint8_t highTemp = 15;
uint8_t lowTemp = 10;
} freezeProtection;
};
struct DhwSettings {
bool enabled = true;
float target = DEFAULT_DHW_TARGET_TEMP;
uint8_t minTemp = DEFAULT_DHW_MIN_TEMP;
uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP;
uint8_t maxModulation = 100;
struct {
uint8_t highTemp = 95;
uint8_t lowTemp = 90;
} overheatProtection;
};
struct PidSettings {
bool enabled = false;
float p_factor = 2.0f;
float i_factor = 0.002f;
float d_factor = 0.0f;
unsigned short dt = 300;
short minTemp = 0;
short maxTemp = DEFAULT_HEATING_MAX_TEMP;
struct {
bool enabled = true;
float p_multiplier = 1.0f;
float i_multiplier = 0.05f;
float d_multiplier = 1.0f;
float thresholdHigh = 0.5f;
float thresholdLow = 1.0f;
} deadband;
};
struct EquithermSettings {
bool enabled = false;
float slope = 0.7f;
float exponent = 1.3f;
float shift = 0.0f;
float targetDiffFactor = 2.0f;
};
struct ExternalPumpSettings {
bool use = false;
uint8_t gpio = DEFAULT_EXT_PUMP_GPIO;
bool invertState = false;
unsigned short postCirculationTime = 600;
unsigned int antiStuckInterval = 2592000;
unsigned short antiStuckTime = 300;
};
struct CascadeControlSettings {
struct {
bool enabled = false;
uint8_t gpio = GPIO_IS_NOT_CONFIGURED;
bool invertState = false;
unsigned short thresholdTime = 60;
} input;
struct {
bool enabled = false;
uint8_t gpio = GPIO_IS_NOT_CONFIGURED;
bool invertState = false;
unsigned short thresholdTime = 60;
bool onFault = true;
bool onLossConnection = true;
bool onEnabledHeating = false;
} output;
};
struct Settings {
SystemSettings system;
PortalSettings portal;
OpenThermSettings opentherm;
MqttSettings mqtt;
EmergencySettings emergency;
HeatingSettings heating;
DhwSettings dhw;
PidSettings pid;
EquithermSettings equitherm;
ExternalPumpSettings externalPump;
CascadeControlSettings cascadeControl;
char validationValue[8] = SETTINGS_VALID_VALUE;
};
struct Variables {
struct {
int8_t rssi = 0;
} network;
struct {
bool state = false;
} emergency;
struct {
bool state = false;
unsigned long lastEnabledTime = 0;
} externalPump;
struct {
bool input = false;
bool output = false;
} cascadeControl;
struct {
uint8_t memberId = 0;
uint8_t flags = 0;
uint8_t type = 0x01;
uint8_t appVersion = 0x3F;
float protocolVersion = 2.2f;
struct {
bool blocking = false;
bool enabled = false;
bool indoorTempControl = false;
bool overheat = false;
bool freezing = false;
float setpointTemp = 0.0f;
float targetTemp = 0.0f;
float currentTemp = 0.0f;
float returnTemp = 0.0f;
float indoorTemp = 0.0f;
float outdoorTemp = 0.0f;
float minTemp = 0.0f;
float maxTemp = 0.0f;
} heating;
struct {
bool enabled = false;
bool overheat = false;
float targetTemp = 0.0f;
float currentTemp = 0.0f;
float returnTemp = 0.0f;
} dhw;
struct {
bool enabled = false;
float targetTemp = 0.0f;
} ch2;
} master;
struct {
uint8_t memberId = 0;
uint8_t flags = 0;
uint8_t type = 0;
uint8_t appVersion = 0;
float protocolVersion = 0.0f;
bool connected = false;
bool flame = false;
float pressure = 0.0f;
float heatExchangerTemp = 0.0f;
struct {
bool active = false;
uint8_t setpoint = 0;
} cooling;
struct {
bool active = false;
uint8_t code = 0;
} fault;
struct {
bool active = false;
uint16_t code = 0;
} diag;
struct {
uint8_t current = 0;
uint8_t min = 0;
uint8_t max = 100;
} modulation;
struct {
float current = 0.0f;
float min = 0.0f;
float max = 0.0f;
} power;
struct {
float temp = 0.0f;
uint16_t co2 = 0;
uint16_t fanSpeed = 0;
} exhaust;
struct {
float storage = 0.0f;
float collector = 0.0f;
} solar;
struct {
uint8_t setpoint = 0;
uint8_t current = 0;
uint16_t supply = 0;
} fanSpeed;
struct {
uint16_t burnerStarts = 0;
uint16_t dhwBurnerStarts = 0;
uint16_t heatingPumpStarts = 0;
uint16_t dhwPumpStarts = 0;
uint16_t coolingHours = 0;
uint16_t burnerHours = 0;
uint16_t dhwBurnerHours = 0;
uint16_t heatingPumpHours = 0;
uint16_t dhwPumpHours = 0;
} stats;
struct {
bool active = false;
bool enabled = false;
float targetTemp = 0.0f;
float roomTargetTemp = 0.0f;
float currentTemp = 0.0f;
float returnTemp = 0.0f;
float indoorTemp = 0.0f;
float outdoorTemp = 0.0f;
uint8_t minTemp = DEFAULT_HEATING_MIN_TEMP;
uint8_t maxTemp = DEFAULT_HEATING_MAX_TEMP;
} heating;
struct {
bool active = false;
bool enabled = false;
float targetTemp = 0.0f;
float currentTemp = 0.0f;
float currentTemp2 = 0.0f;
float returnTemp = 0.0f;
float flowRate = 0.0f;
uint8_t minTemp = DEFAULT_DHW_MIN_TEMP;
uint8_t maxTemp = DEFAULT_DHW_MAX_TEMP;
} dhw;
struct {
bool active = false;
bool enabled = false;
float targetTemp = 0.0f;
float roomTargetTemp = 0.0f;
float currentTemp = 0.0f;
float indoorTemp = 0.0f;
} ch2;
} slave;
struct {
bool resetFault = false;
bool resetDiagnostic = false;
} actions;
struct {
std::atomic<bool> upgrading{false};
} states;
};
+150
View File
@@ -0,0 +1,150 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <MycilaHADiscovery.h>
#include <MycilaTaskManager.h>
#include <esp_log.h>
#include <functional>
#include <initializer_list>
#include <mutex>
#include <string>
#include <string_view>
#include "macros.h"
#include "types.h"
#include "strings_shared.h"
#include "Settings.h"
#include "utils.h"
using namespace Mycila;
class AsyncWebServer;
class WebSerial;
// Configuration
extern NetworkSettings networkSettings;
extern Settings settings;
extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT];
void initConfig();
void saveSettingsNow();
void requestSaveNetworkSettings();
void requestSaveSettings();
// Call after releasing lifecycle, MQTT queue and Sensors data locks.
void requestSaveSensorsSettings();
JsonVariant toJson(const NetworkSettings& src, JsonVariant dst);
JsonVariant toJson(const SystemSettings& src, JsonVariant dst);
JsonVariant toJson(const PortalSettings& src, JsonVariant dst);
JsonVariant toJson(const OpenThermSettings& src, JsonVariant dst);
JsonVariant toJson(const MqttSettings& src, JsonVariant dst);
JsonVariant toJson(const EmergencySettings& src, JsonVariant dst);
JsonVariant toJson(const HeatingSettings& src, JsonVariant dst);
JsonVariant toJson(const DhwSettings& src, JsonVariant dst);
JsonVariant toJson(const PidSettings& src, JsonVariant dst);
JsonVariant toJson(const EquithermSettings& src, JsonVariant dst);
JsonVariant toJson(const ExternalPumpSettings& src, JsonVariant dst);
JsonVariant toJson(const CascadeControlSettings& src, JsonVariant dst);
SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst);
SettingResult fromJson(JsonVariantConst src, SystemSettings& dst);
SettingResult fromJson(JsonVariantConst src, PortalSettings& dst);
SettingResult fromJson(JsonVariantConst src, OpenThermSettings& dst);
SettingResult fromJson(JsonVariantConst src, MqttSettings& dst);
SettingResult fromJson(JsonVariantConst src, EmergencySettings& dst);
SettingResult fromJson(JsonVariantConst src, HeatingSettings& dst);
SettingResult fromJson(JsonVariantConst src, DhwSettings& dst);
SettingResult fromJson(JsonVariantConst src, PidSettings& dst);
SettingResult fromJson(JsonVariantConst src, EquithermSettings& dst);
SettingResult fromJson(JsonVariantConst src, ExternalPumpSettings& dst);
SettingResult fromJson(JsonVariantConst src, CascadeControlSettings& dst);
SettingResult applySetting(Settings& dst, std::string_view path, bool value);
SettingResult applySetting(Settings& dst, std::string_view path, float value);
bool normalizeSettings(Settings& dst);
JsonVariant toJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst);
// Caller holds Sensors::mutex while accessing shared settings and checking slug uniqueness.
SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst);
JsonVariant toJson(const Sensors::Settings& sensor, const Sensors::Result& result, JsonVariant dst);
JsonVariant toJson(const uint8_t sensorId, JsonVariant dst);
JsonVariant toJson(const Variables& src, JsonVariant dst);
SettingResult fromJson(const JsonVariantConst src, Variables& dst);
bool applyAction(std::string_view action, bool value);
// Application state and task managers
extern Variables vars;
extern TaskManager coreTaskManager;
extern TaskManager systemTaskManager;
extern TaskManager openthermTaskManager;
extern TaskManager sensorsTaskManager;
// Schedule once with resume(delay); scheduled() also covers the delay before restart.
// Request only outside OTA and while the task is not already scheduled.
extern Task restartTask;
void initSystem();
std::string getResetReason();
// Control and regulation
void initControl();
void initRegulator();
void initLeds();
// Sensors
void initSensors();
// OpenTherm
extern Task writeRoomTemperatureTask;
extern Task writeRoomTemperatureCh2Task;
void initOpenTherm();
// Logging
extern WebSerial* webSerial;
extern Task configureLoggingTask;
bool initLogging();
void drainLoggingSerial();
// Web server and MQTT
extern AsyncWebServer* webServer;
void initPortal();
extern Task mqttConfigureTask;
// Protect MQTT client and task pointers while checking and using them.
extern std::mutex mqttMutex;
extern Task* mqttPublishSettingsTask;
extern Task* mqttPublishStateTask;
extern Task* mqttPublishSensorsTask;
void initMqtt();
void stopMqtt(bool destroy);
bool isMqttConnected();
void requestReconfigureMqtt();
void requestReconfigureMqttSensor(uint8_t sensorId, std::optional<Sensors::Settings> previousSettings = std::nullopt);
void requestPublishMqttSensor(uint8_t sensorId);
std::string mqttTopic(std::initializer_list<std::string_view> parts);
template <typename... Parts>
std::string mqttTopic(const Parts&... parts) {
return mqttTopic({std::string_view(parts)...});
}
// Home Assistant discovery
extern HA::Discovery haDiscovery;
void publishHaEntity(HaEntity entityId, bool remove);
void publishDynamicSensor(
const Sensors::Settings& sensor,
Sensors::ValueType valueType = Sensors::ValueType::PRIMARY, bool enabledByDefault = true
);
void publishDynamicManualSensor(const Sensors::Settings& sensor, bool enabledByDefault = true);
void deleteDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType = Sensors::ValueType::PRIMARY);
void publishConnectionDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault = true);
void deleteConnectionDynamicSensor(const Sensors::Settings& sensor);
void publishSignalQualityDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault = false);
void deleteSignalQualityDynamicSensor(const Sensors::Settings& sensor);
// Network
void initNetwork();
// Register during setup, before starting systemTaskManager.
// Callbacks run on the system worker: only signal client owners, without blocking.
void onNetworkEvent(NetworkEventCallback callback);
void onNetworkStateChange(NetworkStateCallback callback);
NetworkState getNetworkState(NetworkMode mode = NetworkMode::STA);
NetworkMode getNetworkMode();
bool isNetworkInterfaceStarted(NetworkMode mode);
// Last state published by the system worker, including during event callbacks.
bool isNetworkConnected();
void reconnectNetwork();
+171
View File
@@ -0,0 +1,171 @@
#pragma once
#include <Arduino.h>
#include <driver/gpio.h>
#define PROJECT_NAME "OpenTherm Gateway"
#define PROJECT_REPO "https://github.com/Laxilef/OTGateway"
#define MQTT_RECONNECT_INTERVAL 15000
#define MQTT_SENSOR_REPUBLISH_INTERVAL 300000u
#define CONFIG_URL "http://%s/"
#define SETTINGS_VALID_VALUE "stvalid" // only 8 chars!
#define GPIO_IS_NOT_CONFIGURED 0xff
#define DEFAULT_HEATING_TARGET_TEMP 40
#define DEFAULT_HEATING_MIN_TEMP 20
#define DEFAULT_HEATING_MAX_TEMP 90
#define DEFAULT_DHW_TARGET_TEMP 40
#define DEFAULT_DHW_MIN_TEMP 30
#define DEFAULT_DHW_MAX_TEMP 60
#define THERMOSTAT_INDOOR_DEFAULT_TEMP 20
#define THERMOSTAT_INDOOR_MIN_TEMP 5
#define THERMOSTAT_INDOOR_MAX_TEMP 40
#define DEFAULT_NTC_NOMINAL_RESISTANCE 10000.0f
#define DEFAULT_NTC_NOMINAL_TEMP 25.0f
#define DEFAULT_NTC_REF_RESISTANCE 10000.0f
#define DEFAULT_NTC_BETA_FACTOR 3950.0f
#define DEFAULT_NTC_VREF 3300.0f
#define DEFAULT_NTC_VLOW_TRESHOLD 25.0f
#define DEFAULT_NTC_VHIGH_TRESHOLD 3298.0f
#ifndef BUILD_VERSION
#define BUILD_VERSION "0.0.0"
#endif
#ifndef BUILD_COMMIT
#define BUILD_COMMIT "undefined"
#endif
#ifndef BUILD_ENV
#define BUILD_ENV "undefined"
#endif
#ifndef LOGGING_QUEUE_SIZE
#define LOGGING_QUEUE_SIZE 4096
#endif
#ifndef DEFAULT_SERIAL_ENABLED
#define DEFAULT_SERIAL_ENABLED true
#endif
#ifndef DEFAULT_SERIAL_BAUD
#define DEFAULT_SERIAL_BAUD 115200
#endif
#ifndef DEFAULT_WEBSERIAL_ENABLED
#define DEFAULT_WEBSERIAL_ENABLED true
#endif
#ifndef USE_BLE
#define USE_BLE false
#endif
#ifndef DEFAULT_HOSTNAME
#define DEFAULT_HOSTNAME ""
#endif
#ifndef DEFAULT_AP_SSID
#define DEFAULT_AP_SSID "OpenTherm Gateway"
#endif
#ifndef DEFAULT_AP_PASSWORD
#define DEFAULT_AP_PASSWORD "otgateway123456"
#endif
#ifndef DEFAULT_STA_SSID
#define DEFAULT_STA_SSID ""
#endif
#ifndef DEFAULT_STA_PASSWORD
#define DEFAULT_STA_PASSWORD ""
#endif
#ifndef DEFAULT_LOG_LEVEL
#define DEFAULT_LOG_LEVEL ESP_LOG_VERBOSE
#endif
#ifndef DEFAULT_STATUS_LED_GPIO
#define DEFAULT_STATUS_LED_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_PORTAL_LOGIN
#define DEFAULT_PORTAL_LOGIN ""
#endif
#ifndef DEFAULT_PORTAL_PASSWORD
#define DEFAULT_PORTAL_PASSWORD ""
#endif
#ifndef DEFAULT_MQTT_ENABLED
#define DEFAULT_MQTT_ENABLED false
#endif
#ifndef DEFAULT_MQTT_SERVER
#define DEFAULT_MQTT_SERVER ""
#endif
#ifndef DEFAULT_MQTT_PORT
#define DEFAULT_MQTT_PORT 1883
#endif
#ifndef DEFAULT_MQTT_USER
#define DEFAULT_MQTT_USER ""
#endif
#ifndef DEFAULT_MQTT_PASSWORD
#define DEFAULT_MQTT_PASSWORD ""
#endif
#ifndef DEFAULT_MQTT_PREFIX
#define DEFAULT_MQTT_PREFIX ""
#endif
#ifndef DEFAULT_OT_IN_GPIO
#define DEFAULT_OT_IN_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_OT_OUT_GPIO
#define DEFAULT_OT_OUT_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_OT_RX_LED_GPIO
#define DEFAULT_OT_RX_LED_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_OT_FAULT_STATE_GPIO
#define DEFAULT_OT_FAULT_STATE_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_SENSOR_OUTDOOR_GPIO
#define DEFAULT_SENSOR_OUTDOOR_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_SENSOR_INDOOR_GPIO
#define DEFAULT_SENSOR_INDOOR_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef SENSORS_AMOUNT
#define SENSORS_AMOUNT 20
#endif
#ifndef DEFAULT_EXT_PUMP_GPIO
#define DEFAULT_EXT_PUMP_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef GPIO_IS_VALID_OUTPUT_GPIO
#define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((gpio_num) >= 0 && (gpio_num) < SOC_GPIO_PIN_COUNT && \
(((1ULL << (gpio_num)) & SOC_GPIO_VALID_OUTPUT_GPIO_MASK) != 0))
#endif
#ifndef GPIO_IS_VALID_INPUT_GPIO
// ESP-IDF uses the general GPIO mask for digital input capability.
#define GPIO_IS_VALID_INPUT_GPIO(gpio_num) GPIO_IS_VALID_GPIO(gpio_num)
#endif
#define GPIO_IS_VALID(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_GPIO(gpioNum))
#define GPIO_IS_VALID_INPUT(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_INPUT_GPIO(gpioNum))
#define GPIO_IS_VALID_OUTPUT(gpioNum) ((gpioNum) != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_OUTPUT_GPIO(gpioNum))
+104
View File
@@ -0,0 +1,104 @@
#pragma once
#include <Arduino.h>
#include <esp_arduino_version.h>
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <mutex>
#include <stdint.h>
struct HeapMetrics : multi_heap_info_t {
size_t total;
size_t minLargestBlock = SIZE_MAX;
uint8_t fragmentation;
};
struct MemoryMetrics {
bool captured;
uint64_t uptime;
HeapMetrics heap;
HeapMetrics psram;
};
struct CrashMetrics {
bool captured;
uint32_t core;
uint64_t uptime;
};
struct CoreDumpBuildInfo {
char version[sizeof(BUILD_VERSION)] = BUILD_VERSION;
char date[sizeof("Mmm dd yyyy hh:mm:ss")];
char commit[sizeof(BUILD_COMMIT)] = BUILD_COMMIT;
char env[sizeof(BUILD_ENV)] = BUILD_ENV;
char core[sizeof(ESP_ARDUINO_VERSION_STR)];
char sdk[64];
char chipModel[16];
uint16_t chipRevision;
uint8_t chipCores;
uint32_t cpuFreqMHz;
uint32_t flashChipSize;
};
// Keep one shared instance of each record in the native core dump.
inline COREDUMP_DRAM_ATTR MemoryMetrics memoryMetrics __attribute__((used)) = {};
inline COREDUMP_DRAM_ATTR CrashMetrics crashMetrics __attribute__((used)) = {};
inline COREDUMP_DRAM_ATTR CoreDumpBuildInfo coreDumpBuildInfo __attribute__((used)) = {};
inline std::mutex memoryMetricsMutex;
// Refresh and copy under the same lock: System and HTTP run on different tasks.
inline MemoryMetrics getMemoryMetrics() {
std::lock_guard<std::mutex> lock(memoryMetricsMutex);
// A panic during the update must not report partially written statistics.
__atomic_store_n(&memoryMetrics.captured, false, __ATOMIC_SEQ_CST);
heap_caps_get_info(&memoryMetrics.heap, MALLOC_CAP_INTERNAL);
if (memoryMetrics.psram.total) {
heap_caps_get_info(&memoryMetrics.psram, MALLOC_CAP_SPIRAM);
}
if (memoryMetrics.heap.largest_free_block < memoryMetrics.heap.minLargestBlock) {
memoryMetrics.heap.minLargestBlock = memoryMetrics.heap.largest_free_block;
}
if (memoryMetrics.psram.largest_free_block < memoryMetrics.psram.minLargestBlock) {
memoryMetrics.psram.minLargestBlock = memoryMetrics.psram.largest_free_block;
}
memoryMetrics.heap.fragmentation = memoryMetrics.heap.total_free_bytes
? 100 - memoryMetrics.heap.largest_free_block * 100.0 / memoryMetrics.heap.total_free_bytes
: 0;
memoryMetrics.psram.fragmentation = memoryMetrics.psram.total_free_bytes
? 100 - memoryMetrics.psram.largest_free_block * 100.0 / memoryMetrics.psram.total_free_bytes
: 0;
memoryMetrics.uptime = esp_timer_get_time() / 1000;
__atomic_store_n(&memoryMetrics.captured, true, __ATOMIC_RELEASE);
return memoryMetrics;
}
static void IRAM_ATTR captureCoreDumpMetrics(arduino_panic_info_t* info, void*) {
crashMetrics.core = info->core;
crashMetrics.uptime = esp_timer_get_time() / 1000;
__atomic_store_n(&crashMetrics.captured, true, __ATOMIC_RELEASE);
}
static inline void initCoreDumpMetrics() {
// Keep the timestamp local to the calling translation unit, outside shared types.
strlcpy(coreDumpBuildInfo.date, __DATE__ " " __TIME__, sizeof(coreDumpBuildInfo.date));
strlcpy(coreDumpBuildInfo.core, ESP.getCoreVersion(), sizeof(coreDumpBuildInfo.core));
strlcpy(coreDumpBuildInfo.sdk, ESP.getSdkVersion(), sizeof(coreDumpBuildInfo.sdk));
strlcpy(coreDumpBuildInfo.chipModel, ESP.getChipModel(), sizeof(coreDumpBuildInfo.chipModel));
coreDumpBuildInfo.chipRevision = ESP.getChipRevision();
coreDumpBuildInfo.chipCores = ESP.getChipCores();
coreDumpBuildInfo.cpuFreqMHz = ESP.getCpuFreqMHz();
coreDumpBuildInfo.flashChipSize = ESP.getFlashChipSize();
// Arduino has registered the memory regions before this one-time initialization.
memoryMetrics.heap.total = heap_caps_get_total_size(MALLOC_CAP_INTERNAL);
memoryMetrics.psram.total = psramFound() ? heap_caps_get_total_size(MALLOC_CAP_SPIRAM) : 0;
getMemoryMetrics();
set_arduino_panic_handler(captureCoreDumpMetrics, nullptr);
}
+228
View File
@@ -0,0 +1,228 @@
#pragma once
inline const char L_SETTINGS[] = "SETTINGS";
inline const char L_SETTINGS_OT[] = "SETTINGS.OT";
inline const char L_SETTINGS_DHW[] = "SETTINGS.DHW";
inline const char L_SETTINGS_HEATING[] = "SETTINGS.HEATING";
inline const char L_NETWORK[] = "NETWORK";
inline const char L_NETWORK_SETTINGS[] = "NETWORK.SETTINGS";
inline const char L_PORTAL_WEBSERVER[] = "PORTAL.WEBSERVER";
inline const char L_PORTAL_DNSSERVER[] = "PORTAL.DNSSERVER";
inline const char L_PORTAL_CAPTIVE[] = "PORTAL.CAPTIVE";
inline const char L_PORTAL_OTA[] = "PORTAL.OTA";
inline const char L_MAIN[] = "MAIN";
inline const char L_MQTT[] = "MQTT";
inline const char L_MQTT_HA[] = "MQTT.HA";
inline const char L_MQTT_MSG[] = "MQTT.MSG";
inline const char L_OT[] = "OT";
inline const char L_OT_DHW[] = "OT.DHW";
inline const char L_OT_HEATING[] = "OT.HEATING";
inline const char L_OT_CH2[] = "OT.CH2";
inline const char L_SENSORS[] = "SENSORS";
inline const char L_SENSORS_SETTINGS[] = "SENSORS.SETTINGS";
inline const char L_SENSORS_DALLAS[] = "SENSORS.DALLAS";
inline const char L_SENSORS_DHT[] = "SENSORS.DHT";
inline const char L_SENSORS_NTC[] = "SENSORS.NTC";
inline const char L_SENSORS_BLE[] = "SENSORS.BLE";
inline const char L_REGULATOR[] = "REGULATOR";
inline const char L_REGULATOR_PID[] = "REGULATOR.PID";
inline const char L_REGULATOR_EQUITHERM[] = "REGULATOR.EQUITHERM";
inline const char L_CASCADE_INPUT[] = "CASCADE.INPUT";
inline const char L_CASCADE_OUTPUT[] = "CASCADE.OUTPUT";
inline const char L_EXTPUMP[] = "EXTPUMP";
inline const char S_ACTIONS[] = "actions";
inline const char S_ACTIVE[] = "active";
inline const char S_ADDRESS[] = "address";
inline const char S_ANTI_STUCK_INTERVAL[] = "antistuck_interval";
inline const char S_ANTI_STUCK_TIME[] = "antistuck_time";
inline const char S_AP[] = "ap";
inline const char S_APP_VERSION[] = "app_version";
inline const char S_AUTH[] = "auth";
inline const char S_AUTO_DIAG_RESET[] = "auto_diag_reset";
inline const char S_AUTO_FAULT_RESET[] = "auto_fault_reset";
inline const char S_BACKTRACE[] = "backtrace";
inline const char S_BATTERY[] = "battery";
inline const char S_BAUDRATE[] = "baudrate";
inline const char S_BLOCKING[] = "blocking";
inline const char S_BSSID[] = "bssid";
inline const char S_BUILD[] = "build";
inline const char S_CASCADE_CONTROL[] = "cascade_control";
inline const char S_CHANNEL[] = "channel";
inline const char S_CH2_ALWAYS_ENABLED[] = "ch2_always_enabled";
inline const char S_CH2_DISABLING_ACTION[] = "ch2_disabling_action";
inline const char S_CHIP[] = "chip";
inline const char S_CODE[] = "code";
inline const char S_COMMIT[] = "commit";
inline const char S_CONNECTED[] = "connected";
inline const char S_CONTINUES[] = "continues";
inline const char S_COOLING[] = "cooling";
inline const char S_COOLING_SUPPORT[] = "cooling_support";
inline const char S_CORE[] = "core";
inline const char S_CORES[] = "cores";
inline const char S_CRASH[] = "crash";
inline const char S_CURRENT_TEMP[] = "current_temp";
inline const char S_DATA[] = "data";
inline const char S_DATE[] = "date";
inline const char S_DEADBAND[] = "deadband";
inline const char S_DHW[] = "dhw";
inline const char S_DHW_BLOCKING[] = "dhw_blocking";
inline const char S_DHW_DISABLING_ACTION[] = "dhw_disabling_action";
inline const char S_DHW_STATE_AS_DHW_BLOCKING[] = "dhw_state_as_dhw_blocking";
inline const char S_DHW_SUPPORT[] = "dhw_support";
inline const char S_DHW_TO_CH2[] = "dhw_to_ch2";
inline const char S_DIAG[] = "diag";
inline const char S_DNS[] = "dns";
inline const char S_DT[] = "dt";
inline const char S_D_FACTOR[] = "d_factor";
inline const char S_D_MULTIPLIER[] = "d_multiplier";
inline const char S_EMERGENCY[] = "emergency";
inline const char S_ENABLED[] = "enabled";
inline const char S_ENV[] = "env";
inline const char S_EPC[] = "epc";
inline const char S_EQUITHERM[] = "equitherm";
inline const char S_EXPONENT[] = "exponent";
inline const char S_EXTERNAL_PUMP[] = "ext_pump";
inline const char S_FACTOR[] = "factor";
inline const char S_FALSE[] = "false";
inline const char S_FAULT[] = "fault";
inline const char S_FREEZE_PROTECTION[] = "freeze_protection";
inline const char S_FREEZING[] = "freezing";
inline const char S_FILTERING[] = "filtering";
inline const char S_FILTERING_FACTOR[] = "filtering_factor";
inline const char S_FLAGS[] = "flags";
inline const char S_FLAME[] = "flame";
inline const char S_FLASH[] = "flash";
inline const char S_FREE[] = "free";
inline const char S_FREQ[] = "freq";
inline const char S_GATEWAY[] = "gateway";
inline const char S_GET_MIN_MAX_TEMP[] = "get_min_max_temp";
inline const char S_GPIO[] = "gpio";
inline const char S_HEAP[] = "heap";
inline const char S_HEATING[] = "heating";
inline const char S_HEATING_DISABLING_ACTION[] = "heating_disabling_action";
inline const char S_HEATING_TO_CH2[] = "heating_to_ch2";
inline const char S_HEATING_STATE_TO_SUMMER_WINTER_MODE[] = "heating_state_to_summer_winter_mode";
inline const char S_HIDDEN[] = "hidden";
inline const char S_HIGH_TEMP[] = "high_temp";
inline const char S_HOME_ASSISTANT_DISCOVERY[] = "ha_discovery";
inline const char S_HOSTNAME[] = "hostname";
inline const char S_HUMIDITY[] = "humidity";
inline const char S_HYSTERESIS[] = "hysteresis";
inline const char S_ID[] = "id";
inline const char S_IGNORE_DIAG_STATE[] = "ignore_diag_state";
inline const char S_IMMERGAS_FIX[] = "immergas_fix";
inline const char S_ALWAYS_SEND_INDOOR_TEMP[] = "always_send_indoor_temp";
inline const char S_INDOOR_TEMP[] = "indoor_temp";
inline const char S_INDOOR_TEMP_AVG_TYPE[] = "indoor_temp_avg_type";
inline const char S_INDOOR_TEMP_CONTROL[] = "indoor_temp_control";
inline const char S_IN_GPIO[] = "in_gpio";
inline const char S_INPUT[] = "input";
inline const char S_INTERVAL[] = "interval";
inline const char S_INVERT_STATE[] = "invert_state";
inline const char S_IP[] = "ip";
inline const char S_I_FACTOR[] = "i_factor";
inline const char S_I_MULTIPLIER[] = "i_multiplier";
inline const char S_LOGIN[] = "login";
inline const char S_LOG_LEVEL[] = "loglevel";
inline const char S_LOW_TEMP[] = "low_temp";
inline const char S_MAC[] = "mac";
inline const char S_MASTER[] = "master";
inline const char S_MAX[] = "max";
inline const char S_MAX_FREE_BLOCK[] = "max_free_block";
inline const char S_MAX_MODULATION[] = "max_modulation";
inline const char S_MAX_POWER[] = "max_power";
inline const char S_MAX_TEMP[] = "max_temp";
inline const char S_MAX_TEMP_SYNC_WITH_TARGET_TEMP[] = "max_temp_sync_with_target_temp";
inline const char S_MDNS[] = "mdns";
inline const char S_MEMBER_ID[] = "member_id";
inline const char S_MIN[] = "min";
inline const char S_MIN_FREE[] = "min_free";
inline const char S_MIN_MAX_FREE_BLOCK[] = "min_max_free_block";
inline const char S_MIN_POWER[] = "min_power";
inline const char S_MIN_TEMP[] = "min_temp";
inline const char S_MODEL[] = "model";
inline const char S_MODULATION[] = "modulation";
inline const char S_MQTT[] = "mqtt";
inline const char S_NAME[] = "name";
inline const char S_SLUG[] = "slug";
inline const char S_NATIVE_OTC[] = "native_otc";
inline const char S_NETWORK[] = "network";
inline const char S_NTP[] = "ntp";
inline const char S_OFFSET[] = "offset";
inline const char S_ON_ENABLED_HEATING[] = "on_enabled_heating";
inline const char S_ON_FAULT[] = "on_fault";
inline const char S_ON_LOSS_CONNECTION[] = "on_loss_connection";
inline const char S_OPENTHERM[] = "opentherm";
inline const char S_OPTIONS[] = "options";
inline const char S_OUTDOOR_TEMP[] = "outdoor_temp";
inline const char S_OUTDOOR_TEMP_AVG_TYPE[] = "outdoor_temp_avg_type";
inline const char S_OUT_GPIO[] = "out_gpio";
inline const char S_OUTPUT[] = "output";
inline const char S_OVERHEAT[] = "overheat";
inline const char S_OVERHEAT_PROTECTION[] = "overheat_protection";
inline const char S_PASSWORD[] = "password";
inline const char S_PID[] = "pid";
inline const char S_PORT[] = "port";
inline const char S_PORTAL[] = "portal";
inline const char S_POST_CIRCULATION_TIME[] = "post_circulation_time";
inline const char S_POWER[] = "power";
inline const char S_PREFIX[] = "prefix";
inline const char S_PROTOCOL_VERSION[] = "protocol_version";
inline const char S_PURPOSE[] = "purpose";
inline const char S_PSRAM[] = "psram";
inline const char S_P_FACTOR[] = "p_factor";
inline const char S_P_MULTIPLIER[] = "p_multiplier";
inline const char S_REASON[] = "reason";
inline const char S_RESET_DIAGNOSTIC[] = "reset_diagnostic";
inline const char S_RESET_FAULT[] = "reset_fault";
inline const char S_RESET_REASON[] = "reset_reason";
inline const char S_RESTART[] = "restart";
inline const char S_RETURN_TEMP[] = "return_temp";
inline const char S_REV[] = "rev";
inline const char S_RSSI[] = "rssi";
inline const char S_RX_LED_GPIO[] = "rx_led_gpio";
inline const char S_SDK[] = "sdk";
inline const char S_SENSORS[] = "sensors";
inline const char S_SERIAL[] = "serial";
inline const char S_SERVER[] = "server";
inline const char S_SETTINGS[] = "settings";
inline const char S_SET_DATE_AND_TIME[] = "set_date_and_time";
inline const char S_SHIFT[] = "shift";
inline const char S_SIGNAL_QUALITY[] = "signal_quality";
inline const char S_SIZE[] = "size";
inline const char S_SLAVE[] = "slave";
inline const char S_SLOPE[] = "slope";
inline const char S_SSID[] = "ssid";
inline const char S_STA[] = "sta";
inline const char S_STATE[] = "state";
inline const char S_STATIC_CONFIG[] = "static_config";
inline const char S_STATUS_LED_GPIO[] = "status_led_gpio";
inline const char S_SETPOINT[] = "setpoint";
inline const char S_SETPOINT_TEMP[] = "setpoint_temp";
inline const char S_SUBNET[] = "subnet";
inline const char S_SUMMER_WINTER_MODE[] = "summer_winter_mode";
inline const char S_SYSTEM[] = "system";
inline const char S_TARGET[] = "target";
inline const char S_TARGET_DIFF_FACTOR[] = "target_diff_factor";
inline const char S_TARGET_TEMP[] = "target_temp";
inline const char S_TEMPERATURE[] = "temperature";
inline const char S_THRESHOLD_HIGH[] = "threshold_high";
inline const char S_THRESHOLD_LOW[] = "threshold_low";
inline const char S_THRESHOLD_TIME[] = "threshold_time";
inline const char S_TIMEZONE[] = "timezone";
inline const char S_TOTAL[] = "total";
inline const char S_TRESHOLD_TIME[] = "treshold_time";
inline const char S_TRUE[] = "true";
inline const char S_TURBO[] = "turbo";
inline const char S_TURBO_FACTOR[] = "turbo_factor";
inline const char S_TYPE[] = "type";
inline const char S_UNIT_SYSTEM[] = "unit_system";
inline const char S_UPTIME[] = "uptime";
inline const char S_USE[] = "use";
inline const char S_USE_DHCP[] = "use_dhcp";
inline const char S_USER[] = "user";
inline const char S_VALUE[] = "value";
inline const char S_VERSION[] = "version";
inline const char S_WEBSERIAL[] = "web_serial";
+117
View File
@@ -0,0 +1,117 @@
#pragma once
#include <stdint.h>
#include <functional>
enum class UnitSystem : uint8_t {
METRIC = 0,
IMPERIAL = 1
};
enum class ChannelDisablingAction : uint8_t {
OFF = 0,
ZERO_SETPOINT = 1,
OFF_AND_ZERO_SETPOINT = 2
};
struct SettingResult {
bool changed = false;
bool accepted = false;
};
enum HaEntity : uint8_t {
HA_ENTITY_HEATING_TURBO,
HA_ENTITY_HEATING_HYSTERESIS_ENABLED,
HA_ENTITY_HEATING_HYSTERESIS_VALUE,
HA_ENTITY_HEATING_TURBO_FACTOR,
HA_ENTITY_HEATING_MIN_TEMP,
HA_ENTITY_HEATING_MAX_TEMP,
HA_ENTITY_PID_ENABLED,
HA_ENTITY_PID_P_FACTOR,
HA_ENTITY_PID_I_FACTOR,
HA_ENTITY_PID_D_FACTOR,
HA_ENTITY_PID_DT,
HA_ENTITY_PID_MIN_TEMP,
HA_ENTITY_PID_MAX_TEMP,
HA_ENTITY_EQUITHERM_ENABLED,
HA_ENTITY_EQUITHERM_SLOPE,
HA_ENTITY_EQUITHERM_EXPONENT,
HA_ENTITY_EQUITHERM_SHIFT,
HA_ENTITY_EQUITHERM_TARGET_DIFF_FACTOR,
HA_ENTITY_STATUS,
HA_ENTITY_EMERGENCY,
HA_ENTITY_OPENTHERM_STATUS,
HA_ENTITY_HEATING,
HA_ENTITY_FLAME,
HA_ENTITY_FAULT,
HA_ENTITY_DIAGNOSTIC,
HA_ENTITY_EXTERNAL_PUMP,
HA_ENTITY_FAULT_CODE,
HA_ENTITY_DIAGNOSTIC_CODE,
HA_ENTITY_RSSI,
HA_ENTITY_UPTIME,
HA_ENTITY_RESTART,
HA_ENTITY_RESET_FAULT,
HA_ENTITY_RESET_DIAGNOSTIC,
HA_ENTITY_HEATING_CLIMATE,
HA_ENTITY_DHW_MIN_TEMP,
HA_ENTITY_DHW_MAX_TEMP,
HA_ENTITY_DHW,
HA_ENTITY_DHW_CLIMATE,
HA_ENTITY_HEATING_BLOCKING,
HA_ENTITY_HEATING_OVERHEAT,
HA_ENTITY_HEATING_FREEZING,
HA_ENTITY_DHW_OVERHEAT,
HA_ENTITY_CASCADE_CONTROL_INPUT,
HA_ENTITY_CASCADE_CONTROL_OUTPUT,
HA_ENTITY_COUNT
};
enum class NetworkEvent : uint8_t {
CONNECTED,
DISCONNECTED,
STA_STARTED,
STA_STOPPED,
STA_CONNECTED,
STA_DISCONNECTED,
STA_GOT_IP,
STA_LOST_IP,
STA_GOT_IP6,
AP_STARTED,
AP_STOPPED,
AP_CLIENT_CONNECTED,
AP_CLIENT_DISCONNECTED,
AP_CLIENT_GOT_IP,
AP_GOT_IP6,
PORTAL_STARTED,
PORTAL_STOPPED,
MDNS_STARTED,
MDNS_STOPPED,
EVENTS_OVERFLOW
};
enum class NetworkState : uint8_t {
NETWORK_DISABLED,
NETWORK_ENABLED,
NETWORK_CONNECTING,
NETWORK_TIMEOUT,
NETWORK_CONNECTED,
NETWORK_DISCONNECTED,
NETWORK_RECONNECTING,
AP_STARTING,
AP_STARTED,
PORTAL_STARTING,
PORTAL_STARTED,
PORTAL_COMPLETE,
PORTAL_TIMEOUT
};
enum class NetworkMode : uint8_t {
NONE,
AP,
STA,
ETH
};
using NetworkEventCallback = void (*)(NetworkEvent);
using NetworkStateCallback = std::function<void(NetworkMode mode, NetworkState previous, NetworkState state)>;
+178
View File
@@ -0,0 +1,178 @@
#pragma once
#include <Arduino.h>
#include <cmath>
#include <stdio.h>
#include <string>
#include <string.h>
#include <time.h>
#include "types.h"
inline std::string getChipId(const char* prefix = nullptr, const char* suffix = nullptr) {
std::string chipId;
chipId.reserve(
6
+ (prefix != nullptr ? strlen(prefix) : 0)
+ (suffix != nullptr ? strlen(suffix) : 0)
);
if (prefix != nullptr) {
chipId += prefix;
}
uint32_t cid = 0;
// https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/ChipID/GetChipID/GetChipID.ino
for (uint8_t i = 0; i < 17; i = i + 8) {
cid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
}
char hexId[7];
snprintf(hexId, sizeof(hexId), "%lx", static_cast<unsigned long>(cid));
chipId += hexId;
if (suffix != nullptr) {
chipId += suffix;
}
chipId.erase(chipId.find_last_not_of(" \t\n\r\f\v") + 1);
chipId.erase(0, chipId.find_first_not_of(" \t\n\r\f\v"));
return chipId;
}
inline bool isLeapYear(short year) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
return (year % 400) == 0;
}
// convert UTC tm time to time_t epoch time
// source: https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/timekeeper.cpp
inline time_t mkgmtime(const struct tm *ptm) {
const int SecondsPerMinute = 60;
const int SecondsPerHour = 3600;
const int SecondsPerDay = 86400;
const int DaysOfMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
time_t secs = 0;
// tm_year is years since 1900
int year = ptm->tm_year + 1900;
for (int y = 1970; y < year; ++y) {
secs += (isLeapYear(y) ? 366 : 365) * SecondsPerDay;
}
// tm_mon is month from 0..11
for (int m = 0; m < ptm->tm_mon; ++m) {
secs += DaysOfMonth[m] * SecondsPerDay;
if (m == 1 && isLeapYear(year)) {
secs += SecondsPerDay;
}
}
secs += (ptm->tm_mday - 1) * SecondsPerDay;
secs += ptm->tm_hour * SecondsPerHour;
secs += ptm->tm_min * SecondsPerMinute;
secs += ptm->tm_sec;
return secs;
}
inline float liter2gallon(float value) {
return value / 3.785411784f;
}
inline float gallon2liter(float value) {
return value * 3.785411784f;
}
inline float convertVolume(float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) {
value = liter2gallon(value);
} else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) {
value = gallon2liter(value);
}
return value;
}
inline float bar2psi(float value) {
return value * 14.5038f;
}
inline float psi2bar(float value) {
return value / 14.5038f;
}
inline float convertPressure(float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) {
value = bar2psi(value);
} else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) {
value = psi2bar(value);
}
return value;
}
inline float c2f(float value) {
return (9.0f / 5.0f) * value + 32.0f;
}
inline float f2c(float value) {
return (value - 32.0f) * 5.0f / 9.0f;
}
inline float convertTemp(float value, const UnitSystem unitFrom, const UnitSystem unitTo) {
if (unitFrom == UnitSystem::METRIC && unitTo == UnitSystem::IMPERIAL) {
value = c2f(value);
} else if (unitFrom == UnitSystem::IMPERIAL && unitTo == UnitSystem::METRIC) {
value = f2c(value);
}
return value;
}
inline bool isValidTemp(const float value, UnitSystem unit, const float min = 0.1f, const float max = 99.9f, const UnitSystem minMaxUnit = UnitSystem::METRIC) {
return value >= convertTemp(min, minMaxUnit, unit) && value <= convertTemp(max, minMaxUnit, unit);
}
inline bool isFloatDifferent(float first, float second, float tolerance) {
return fabsf(first - second) > tolerance;
}
inline float roundf(float value, uint8_t decimals = 2) {
if (decimals == 0) {
return std::round(value);
} else if (abs(value) < 0.00000001f) {
return 0.0f;
}
const float multiplier = pow10(decimals);
const float scaled = value * multiplier;
return std::isfinite(scaled) ? std::round(scaled) / multiplier : value;
}
template <class T>
void arr2str(String& str, T arr[], size_t length) {
char buffer[12];
for (size_t i = 0; i < length; i++) {
auto addr = arr[i];
if (!addr) {
continue;
}
sprintf(buffer, "0x%08X ", addr);
str.concat(buffer);
}
str.trim();
}
inline uint8_t rssiToSignalQuality(int16_t rssi) {
return constrain(map(rssi, -100, -50, 0, 100), 0, 100);
}