diff --git a/include/Sensors.h b/include/Sensors.h new file mode 100644 index 0000000..7f9c34d --- /dev/null +++ b/include/Sensors.h @@ -0,0 +1,806 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 getSettings(uint8_t sensorId) { + std::lock_guard lock(mutex); + if (settings == nullptr || !isValidSensorId(sensorId)) { + return std::nullopt; + } + return settings[sensorId]; + } + + static std::optional getSnapshot(uint8_t sensorId) { + std::lock_guard 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 + static bool isValidSensorId(const T id) { + return id >= 0 && id <= getMaxSensorId(); + } + + static std::optional 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(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 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 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 getIdByName(const char* name) { + std::lock_guard 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 getIdBySlug(const char* slug) { + if (slug == nullptr || !slug[0]) { + return std::nullopt; + } + + std::lock_guard 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(valueType); + char name[sizeof(Settings::name)]; + float compensatedValue = value; + float loggedValue; + bool connectedChanged; + { + std::lock_guard 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 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(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(ValueType::PRIMARY), value, value, value + ); + return true; + } + + static std::optional setManualValueBySlug(std::string_view slug, float value, const UnitSystem srcUnit) { + if (slug.empty()) { + return std::nullopt; + } + + std::optional sensorId; + char name[sizeof(Settings::name)]; + bool connectedChanged = false; + { + std::lock_guard 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(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(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 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 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 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 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(value); + results[sensorId].updatedAt = millis(); + } + return true; + } + + static bool setAddressById(uint8_t sensorId, const uint8_t* address, const std::function& onUpdated = nullptr) { + { + std::lock_guard 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 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 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 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; diff --git a/include/Settings.h b/include/Settings.h new file mode 100644 index 0000000..b6e9bfa --- /dev/null +++ b/include/Settings.h @@ -0,0 +1,390 @@ +#pragma once + +#include +#include + +#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(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 upgrading{false}; + } states; +}; diff --git a/include/app.h b/include/app.h new file mode 100644 index 0000000..f7469d9 --- /dev/null +++ b/include/app.h @@ -0,0 +1,150 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 previousSettings = std::nullopt); +void requestPublishMqttSensor(uint8_t sensorId); +std::string mqttTopic(std::initializer_list parts); +template +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(); diff --git a/src/defines.h b/include/macros.h similarity index 78% rename from src/defines.h rename to include/macros.h index 9f8ec19..8c22766 100644 --- a/src/defines.h +++ b/include/macros.h @@ -1,7 +1,13 @@ +#pragma once + +#include +#include + #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 @@ -38,6 +44,10 @@ #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 @@ -75,7 +85,7 @@ #endif #ifndef DEFAULT_LOG_LEVEL - #define DEFAULT_LOG_LEVEL TinyLoggerLevel::VERBOSE + #define DEFAULT_LOG_LEVEL ESP_LOG_VERBOSE #endif #ifndef DEFAULT_STATUS_LED_GPIO @@ -146,17 +156,16 @@ #define DEFAULT_EXT_PUMP_GPIO GPIO_IS_NOT_CONFIGURED #endif -#include +#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 -#define GPIO_IS_VALID(gpioNum) (gpioNum != GPIO_IS_NOT_CONFIGURED && GPIO_IS_VALID_GPIO(gpioNum)) +#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 -enum class UnitSystem : uint8_t { - METRIC = 0, - IMPERIAL = 1 -}; - -enum class ChannelDisablingAction : uint8_t { - OFF = 0, - ZERO_SETPOINT = 1, - OFF_AND_ZERO_SETPOINT = 2 -}; +#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)) diff --git a/include/metrics.h b/include/metrics.h new file mode 100644 index 0000000..0017b48 --- /dev/null +++ b/include/metrics.h @@ -0,0 +1,104 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +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 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); +} diff --git a/include/strings_shared.h b/include/strings_shared.h new file mode 100644 index 0000000..71e85c3 --- /dev/null +++ b/include/strings_shared.h @@ -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"; diff --git a/include/types.h b/include/types.h new file mode 100644 index 0000000..e217674 --- /dev/null +++ b/include/types.h @@ -0,0 +1,117 @@ +#pragma once + +#include +#include + +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; diff --git a/include/utils.h b/include/utils.h new file mode 100644 index 0000000..3befebf --- /dev/null +++ b/include/utils.h @@ -0,0 +1,178 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#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(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 +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); +} diff --git a/lib/BufferedWebServer/BufferedWebServer.h b/lib/BufferedWebServer/BufferedWebServer.h deleted file mode 100644 index 61e3d8d..0000000 --- a/lib/BufferedWebServer/BufferedWebServer.h +++ /dev/null @@ -1,82 +0,0 @@ -class BufferedWebServer { -public: - explicit BufferedWebServer(WebServer* webServer, size_t bufferSize = 64) { - this->webServer = webServer; - this->bufferSize = bufferSize; - this->buffer = static_cast(malloc(bufferSize * sizeof(*this->buffer))); - } - - ~BufferedWebServer() { - free(this->buffer); - } - - template - void send(int code, T contentType, const JsonVariantConst content, bool pretty = false) { - auto contentLength = pretty ? measureJsonPretty(content) : measureJson(content); - - this->webServer->setContentLength(contentLength); - this->webServer->send(code, contentType, emptyString); - - if (pretty) { - serializeJsonPretty(content, *this); - - } else { - serializeJson(content, *this); - } - - this->flush(); - - this->webServer->sendContent(emptyString); - } - - size_t write(uint8_t c) { - this->buffer[this->bufferPos++] = c; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - return 1; - } - - size_t write(const uint8_t* buffer, size_t length) { - size_t written = 0; - while (written < length) { - size_t copySize = this->bufferSize - this->bufferPos; - if (written + copySize > length) { - copySize = length - written; - } - - memcpy(this->buffer + this->bufferPos, buffer + written, copySize); - this->bufferPos += copySize; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - written += copySize; - } - - return written; - } - - void flush() { - if (this->bufferPos == 0) { - return; - } - - auto& client = this->webServer->client(); - if (client.connected()) { - this->webServer->sendContent((const char*)this->buffer, this->bufferPos); - } - - this->bufferPos = 0; - - } - -protected: - WebServer* webServer = nullptr; - uint8_t* buffer; - size_t bufferSize = 64; - size_t bufferPos = 0; -}; diff --git a/lib/CustomOpenTherm/CustomOpenTherm.h b/lib/CustomOpenTherm/CustomOpenTherm.h deleted file mode 100644 index 7e7a3bc..0000000 --- a/lib/CustomOpenTherm/CustomOpenTherm.h +++ /dev/null @@ -1,195 +0,0 @@ -#include -#include - -class CustomOpenTherm : public OpenTherm { -public: - typedef std::function DelayCallback; - typedef std::function BeforeSendRequestCallback; - typedef std::function AfterSendRequestCallback; - - explicit CustomOpenTherm(int inPin = 4, int outPin = 5, bool isSlave = false, bool alwaysReceive = false) : OpenTherm(inPin, outPin, isSlave, alwaysReceive) {} - ~CustomOpenTherm() {} - - CustomOpenTherm* setDelayCallback(DelayCallback callback = nullptr) { - this->delayCallback = callback; - - return this; - } - - CustomOpenTherm* setBeforeSendRequestCallback(BeforeSendRequestCallback callback = nullptr) { - this->beforeSendRequestCallback = callback; - - return this; - } - - CustomOpenTherm* setAfterSendRequestCallback(AfterSendRequestCallback callback = nullptr) { - this->afterSendRequestCallback = callback; - - return this; - } - - unsigned long sendRequest(unsigned long request) override { - this->sendRequestAttempt++; - - while (!this->isReady()) { - if (this->delayCallback) { - this->delayCallback(150); - } - - this->process(); - } - - if (this->beforeSendRequestCallback) { - this->beforeSendRequestCallback(request, this->sendRequestAttempt); - } - - if (this->sendRequestAsync(request)) { - do { - if (this->delayCallback) { - this->delayCallback(150); - } - - this->process(); - } while (this->status != OpenThermStatus::READY && this->status != OpenThermStatus::DELAY); - } - - if (this->afterSendRequestCallback) { - this->afterSendRequestCallback(request, this->response, this->responseStatus, this->sendRequestAttempt); - } - - if (this->responseStatus == OpenThermResponseStatus::SUCCESS || this->responseStatus == OpenThermResponseStatus::INVALID) { - this->sendRequestAttempt = 0; - return this->response; - - } else if (this->sendRequestAttempt >= this->sendRequestMaxAttempts) { - this->sendRequestAttempt = 0; - return this->response; - - } else { - return this->sendRequest(request); - } - } - - inline auto sendBoilerReset() { - return this->sendRequestCode(1); - } - - inline auto sendServiceReset() { - return this->sendRequestCode(10); - } - - inline auto sendWaterFilling() { - return this->sendRequestCode(2); - } - - bool sendRequestCode(const uint8_t requestCode) { - unsigned long response = this->sendRequest(buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::RemoteRequest, - static_cast(requestCode) << 8 - )); - - if (!isValidResponse(response) || !isValidResponseId(response, OpenThermMessageID::RemoteRequest)) { - return false; - } - - const uint8_t responseRequestCode = (response & 0xFFFF) >> 8; - const uint8_t responseCode = response & 0xFF; - if (responseRequestCode != requestCode || responseCode < 128) { - return false; - } - - // reset - this->sendRequest(buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::RemoteRequest, - 0u << 8 - )); - - return true; - } - - bool getStr(OpenThermMessageID id, char* buffer, uint16_t length = 50) { - if (buffer == nullptr || length == 0) { - return false; - } - - unsigned long response; - uint8_t index = 0; - uint8_t maxIndex = 255; - - while (index <= maxIndex && index < length) { - response = this->sendRequest(buildRequest( - OpenThermMessageType::READ_DATA, - id, - static_cast(index) << 8 - )); - - if (!isValidResponse(response) || !isValidResponseId(response, id)) { - break; - } - - const uint8_t character = response & 0xFF; - if (character == 0) { - break; - } - - if (index == 0) { - maxIndex = (response & 0xFFFF) >> 8; - } - - buffer[index++] = static_cast(character); - } - - buffer[index] = '\0'; - return index > 0; - } - - static bool isCh2Active(unsigned long response) { - return response & 0x20; - } - - static bool isValidResponseId(unsigned long response, OpenThermMessageID id) { - const uint8_t responseId = (response >> 16) & 0xFF; - - return static_cast(id) == responseId; - } - - static uint8_t getResponseMessageTypeId(unsigned long response) { - return (response << 1) >> 29; - } - - static const char* getResponseMessageTypeString(unsigned long response) { - uint8_t msgType = getResponseMessageTypeId(response); - - switch (msgType) { - case static_cast(OpenThermMessageType::READ_ACK): - case static_cast(OpenThermMessageType::WRITE_ACK): - case static_cast(OpenThermMessageType::DATA_INVALID): - case static_cast(OpenThermMessageType::UNKNOWN_DATA_ID): - return CustomOpenTherm::messageTypeToString( - static_cast(msgType) - ); - - default: - return "UNKNOWN"; - } - } - - // converters - template - static unsigned int toFloat(const T val) { - return (unsigned int)(val * 256); - } - - static short getInt(const unsigned long response) { - return response & 0xffff; - } - -protected: - const uint8_t sendRequestMaxAttempts = 5; - uint8_t sendRequestAttempt = 0; - DelayCallback delayCallback; - BeforeSendRequestCallback beforeSendRequestCallback; - AfterSendRequestCallback afterSendRequestCallback; -}; diff --git a/lib/HomeAssistantHelper/HomeAssistantHelper.h b/lib/HomeAssistantHelper/HomeAssistantHelper.h deleted file mode 100644 index 1b21827..0000000 --- a/lib/HomeAssistantHelper/HomeAssistantHelper.h +++ /dev/null @@ -1,180 +0,0 @@ -#pragma once -#include -#include "strings.h" - -class HomeAssistantHelper { -public: - typedef std::function PublishEventCallback; - - HomeAssistantHelper() = default; - - void setWriter() { - this->writer = nullptr; - } - - void setWriter(MqttWriter* writer) { - this->writer = writer; - } - - void setPublishEventCallback(PublishEventCallback callback) { - this->publishEventCallback = callback; - } - - void setDevicePrefix(const char* value) { - this->devicePrefix = value; - } - - void setDeviceVersion(const char* value) { - this->deviceVersion = value; - } - - void setDeviceManufacturer(const char* value) { - this->deviceManufacturer = value; - } - - void setDeviceModel(const char* value) { - this->deviceModel = value; - } - - void setDeviceName(const char* value) { - this->deviceName = value; - } - - void setDeviceConfigUrl(const char* value) { - this->deviceConfigUrl = value; - } - - bool publish(const char* topic, JsonDocument& doc) { - if (this->writer == nullptr) { - if (this->publishEventCallback) { - this->publishEventCallback(topic, false); - } - - return false; - } - - doc[HA_DEVICE][HA_IDENTIFIERS][0] = this->devicePrefix; - doc[HA_DEVICE][HA_SW_VERSION] = this->deviceVersion; - - if (this->deviceManufacturer != nullptr) { - doc[HA_DEVICE][HA_MANUFACTURER] = this->deviceManufacturer; - } - - if (this->deviceModel != nullptr) { - doc[HA_DEVICE][HA_MODEL] = this->deviceModel; - } - - if (this->deviceName != nullptr) { - doc[HA_DEVICE][HA_NAME] = this->deviceName; - } - - if (this->deviceConfigUrl != nullptr) { - doc[HA_DEVICE][HA_CONF_URL] = this->deviceConfigUrl; - } - - bool result = this->writer->publish(topic, doc, true); - doc.clear(); - doc.shrinkToFit(); - - if (this->publishEventCallback) { - this->publishEventCallback(topic, result); - } - - return result; - } - - bool publish(const char* topic) { - if (this->writer == nullptr) { - if (this->publishEventCallback) { - this->publishEventCallback(topic, false); - } - - return false; - } - - bool result = writer->publish(topic, nullptr, 0, true); - if (this->publishEventCallback) { - this->publishEventCallback(topic, result); - } - - return result; - } - - template - String makeConfigTopic(CT category, NT name, char nameSeparator = '/') { - String topic = ""; - topic.concat(this->prefix); - topic.concat('/'); - topic.concat(category); - topic.concat('/'); - topic.concat(this->devicePrefix); - topic.concat(nameSeparator); - topic.concat(name); - topic.concat("/config"); - return topic; - } - - template - String getDeviceTopic(T value, char dpvSeparator = '/') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(dpvSeparator); - topic.concat(value); - return topic; - } - - template - String getDeviceTopic(CT category, NT name, char dpcSeparator = '/', char cnSeparator = '/') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(dpcSeparator); - topic.concat(category); - topic.concat(cnSeparator); - topic.concat(name); - return topic; - } - - template - String getDeviceTopic(CT category, NT name, ST suffix, char dpcSeparator = '/', char cnSeparator = '/', char nsSeparator = '/') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(dpcSeparator); - topic.concat(category); - topic.concat(cnSeparator); - topic.concat(name); - topic.concat(nsSeparator); - topic.concat(suffix); - return topic; - } - - template - String getEntityIdWithPrefix(DT domain, VT value, char separator = '_') { - String topic = ""; - topic.concat(domain); - topic.concat('.'); - topic.concat(this->devicePrefix); - topic.concat(separator); - topic.concat(value); - return topic; - } - - template - String getUniqueIdWithPrefix(T value, char separator = '_') { - String topic = ""; - topic.concat(this->devicePrefix); - topic.concat(separator); - topic.concat(value); - return topic; - } - -protected: - PublishEventCallback publishEventCallback; - MqttWriter* writer = nullptr; - const char* prefix = "homeassistant"; - const char* devicePrefix = ""; - const char* deviceVersion = "1.0"; - const char* deviceManufacturer = nullptr; - const char* deviceModel = nullptr; - const char* deviceName = nullptr; - const char* deviceConfigUrl = nullptr; -}; diff --git a/lib/HomeAssistantHelper/strings.h b/lib/HomeAssistantHelper/strings.h deleted file mode 100644 index 4d4d597..0000000 --- a/lib/HomeAssistantHelper/strings.h +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -const char HA_ENTITY_BINARY_SENSOR[] = "binary_sensor"; -const char HA_ENTITY_BUTTON[] = "button"; -const char HA_ENTITY_FAN[] = "fan"; -const char HA_ENTITY_CLIMATE[] = "climate"; -const char HA_ENTITY_NUMBER[] = "number"; -const char HA_ENTITY_SELECT[] = "select"; -const char HA_ENTITY_SENSOR[] = "sensor"; -const char HA_ENTITY_SWITCH[] = "switch"; - -// https://www.home-assistant.io/integrations/mqtt/#supported-abbreviations-in-mqtt-discovery-messages -const char HA_DEFAULT_ENTITY_ID[] = "def_ent_id"; // "default_entity_id " -const char HA_DEVICE[] = "dev"; // "device" -const char HA_IDENTIFIERS[] = "ids"; // "identifiers" -const char HA_SW_VERSION[] = "sw"; // "sw_version" -const char HA_MANUFACTURER[] = "mf"; // "manufacturer" -const char HA_MODEL[] = "mdl"; // "model" -const char HA_NAME[] = "name"; -const char HA_CONF_URL[] = "cu"; // "configuration_url" -const char HA_COMMAND_TOPIC[] = "cmd_t"; // "command_topic" -const char HA_COMMAND_TEMPLATE[] = "cmd_tpl"; // "command_template" -const char HA_ENABLED_BY_DEFAULT[] = "en"; // "enabled_by_default" -const char HA_UNIQUE_ID[] = "uniq_id"; // "unique_id" -const char HA_ENTITY_CATEGORY[] = "ent_cat"; // "entity_category" -const char HA_ENTITY_CATEGORY_DIAGNOSTIC[] = "diagnostic"; -const char HA_ENTITY_CATEGORY_CONFIG[] = "config"; -const char HA_STATE_TOPIC[] = "stat_t"; // "state_topic" -const char HA_VALUE_TEMPLATE[] = "val_tpl"; // "value_template" -const char HA_OPTIONS[] = "ops"; // "options" -const char HA_AVAILABILITY[] = "avty"; // "availability" -const char HA_AVAILABILITY_MODE[] = "avty_mode"; // "availability_mode" -const char HA_TOPIC[] = "t"; // "topic" -const char HA_DEVICE_CLASS[] = "dev_cla"; // "device_class" -const char HA_UNIT_OF_MEASUREMENT[] = "unit_of_meas"; // "unit_of_measurement" -const char HA_UNIT_OF_MEASUREMENT_C[] = "°C"; -const char HA_UNIT_OF_MEASUREMENT_F[] = "°F"; -const char HA_UNIT_OF_MEASUREMENT_PERCENT[] = "%"; -const char HA_UNIT_OF_MEASUREMENT_L_MIN[] = "L/min"; -const char HA_UNIT_OF_MEASUREMENT_GAL_MIN[] = "gal/min"; -const char HA_ICON[] = "ic"; // "icon" -const char HA_MIN[] = "min"; -const char HA_MAX[] = "max"; -const char HA_STEP[] = "step"; -const char HA_MODE[] = "mode"; -const char HA_MODE_BOX[] = "box"; -const char HA_STATE_ON[] = "stat_on"; // "state_on" -const char HA_STATE_OFF[] = "stat_off"; // "state_off" -const char HA_PAYLOAD_ON[] = "pl_on"; // "payload_on" -const char HA_PAYLOAD_OFF[] = "pl_off"; // "payload_off" -const char HA_STATE_CLASS[] = "stat_cla"; // "state_class" -const char HA_STATE_CLASS_MEASUREMENT[] = "measurement"; -const char HA_EXPIRE_AFTER[] = "exp_aft"; // "expire_after" -const char HA_CURRENT_TEMPERATURE_TOPIC[] = "curr_temp_t"; // "current_temperature_topic" -const char HA_CURRENT_TEMPERATURE_TEMPLATE[] = "curr_temp_tpl"; // "current_temperature_template" -const char HA_TEMPERATURE_COMMAND_TOPIC[] = "temp_cmd_t"; // "temperature_command_topic" -const char HA_TEMPERATURE_COMMAND_TEMPLATE[] = "temp_cmd_tpl"; // "temperature_command_template" -const char HA_TEMPERATURE_STATE_TOPIC[] = "temp_stat_t"; // "temperature_state_topic" -const char HA_TEMPERATURE_STATE_TEMPLATE[] = "temp_stat_tpl"; // "temperature_state_template" -const char HA_TEMPERATURE_UNIT[] = "temp_unit"; // "temperature_unit" -const char HA_MODE_COMMAND_TOPIC[] = "mode_cmd_t"; // "mode_command_topic" -const char HA_MODE_COMMAND_TEMPLATE[] = "mode_cmd_tpl"; // "mode_command_template" -const char HA_MODE_STATE_TOPIC[] = "mode_stat_t"; // "mode_state_topic" -const char HA_MODE_STATE_TEMPLATE[] = "mode_stat_tpl"; // "mode_state_template" -const char HA_MODES[] = "modes"; -const char HA_ACTION_TOPIC[] = "act_t"; // "action_topic" -const char HA_ACTION_TEMPLATE[] = "act_tpl"; // "action_template" -const char HA_MIN_TEMP[] = "min_temp"; -const char HA_MAX_TEMP[] = "max_temp"; -const char HA_TEMP_STEP[] = "temp_step"; -const char HA_PRESET_MODE_COMMAND_TOPIC[] = "pr_mode_cmd_t"; // "preset_mode_command_topic" -const char HA_PRESET_MODE_COMMAND_TEMPLATE[] = "pr_mode_cmd_tpl"; // "preset_mode_command_template" -const char HA_PRESET_MODE_STATE_TOPIC[] = "pr_mode_stat_t"; // "preset_mode_state_topic" -const char HA_PRESET_MODE_VALUE_TEMPLATE[] = "pr_mode_val_tpl"; // "preset_mode_value_template" -const char HA_PRESET_MODES[] = "pr_modes"; // "preset_modes" diff --git a/lib/MqttWriter/MqttWriter.h b/lib/MqttWriter/MqttWriter.h deleted file mode 100644 index 457e49c..0000000 --- a/lib/MqttWriter/MqttWriter.h +++ /dev/null @@ -1,204 +0,0 @@ -#pragma once -#include -#include -#include - - -class MqttWriter { -public: - typedef std::function YieldCallback; - typedef std::function PublishEventCallback; - typedef std::function FlushEventCallback; - - explicit MqttWriter(MqttClient* client, size_t bufferSize = 64) { - this->client = client; - this->bufferSize = bufferSize; - this->buffer = static_cast(malloc(bufferSize * sizeof(*this->buffer))); - - this->mutex = new std::mutex(); - } - - ~MqttWriter() { - free(this->buffer); - - delete this->mutex; - } - - MqttWriter* setYieldCallback(YieldCallback callback = nullptr) { - this->yieldCallback = callback; - - return this; - } - - MqttWriter* setPublishEventCallback(PublishEventCallback callback) { - this->publishEventCallback = callback; - - return this; - } - - MqttWriter* setFlushEventCallback(FlushEventCallback callback) { - this->flushEventCallback = callback; - - return this; - } - - bool lock() { - if (!this->mutex->try_lock()) { - return false; - } - - this->locked = true; - this->writeAfterLock = 0; - this->lockedTime = millis(); - - return true; - } - - bool isLocked() { - return this->locked; - } - - void unlock() { - this->locked = false; - this->mutex->unlock(); - } - - bool publish(const char* topic, const JsonVariantConst doc, bool retained = false) { - if (!this->client->connected()) { - this->bufferPos = 0; - return false; - } - - while (!this->lock()) { - if (this->yieldCallback) { - this->yieldCallback(); - } - } - - this->bufferPos = 0; - size_t docSize = measureJson(doc); - size_t written = 0; - if (this->client->beginMessage(topic, docSize, retained)) { - serializeJson(doc, *this); - this->flush(); - this->client->endMessage(); - - written = this->writeAfterLock; - } - this->unlock(); - - if (this->publishEventCallback) { - this->publishEventCallback(topic, written, docSize, written == docSize); - } - - return written == docSize; - } - - bool publish(const char* topic, const char* buffer, bool retained = false) { - return this->publish(topic, (const uint8_t*) buffer, strlen(buffer), retained); - } - - bool publish(const char* topic, const uint8_t* buffer, size_t length, bool retained = false) { - if (!this->client->connected()) { - this->bufferPos = 0; - return false; - } - - while (!this->lock()) { - if (this->yieldCallback) { - this->yieldCallback(); - } - } - - this->bufferPos = 0; - size_t written = 0; - bool result = false; - if (!length || buffer == nullptr) { - result = this->client->beginMessage(topic, retained) && this->client->endMessage(); - - } else if (this->client->beginMessage(topic, length, retained)) { - this->write(buffer, length); - this->flush(); - this->client->endMessage(); - - written = this->writeAfterLock; - result = written == length; - } - this->unlock(); - - if (this->publishEventCallback) { - this->publishEventCallback(topic, written, length, result); - } - - return result; - } - - size_t write(uint8_t c) { - this->buffer[this->bufferPos++] = c; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - return 1; - } - - size_t write(const uint8_t* buffer, size_t length) { - size_t written = 0; - while (written < length) { - size_t copySize = this->bufferSize - this->bufferPos; - if (written + copySize > length) { - copySize = length - written; - } - - memcpy(this->buffer + this->bufferPos, buffer + written, copySize); - this->bufferPos += copySize; - - if (this->bufferPos >= this->bufferSize) { - this->flush(); - } - - written += copySize; - } - - return written; - } - - bool flush() { - if (this->bufferPos == 0) { - return false; - } - - if (!this->client->connected()) { - this->bufferPos = 0; - } - - size_t length = this->bufferPos; - size_t written = this->client->write(this->buffer, length); - this->client->flush(); - this->bufferPos = 0; - - if (this->isLocked()) { - this->writeAfterLock += written; - } - - if (this->flushEventCallback) { - this->flushEventCallback(written, length); - } - - return written == length; - } - -protected: - YieldCallback yieldCallback; - PublishEventCallback publishEventCallback; - FlushEventCallback flushEventCallback; - MqttClient* client; - uint8_t* buffer; - size_t bufferSize = 64; - size_t bufferPos = 0; - bool locked = false; - mutable std::mutex* mutex; - unsigned long lockedTime = 0; - size_t writeAfterLock = 0; -}; diff --git a/lib/NetworkUtils/NetworkConnection.cpp b/lib/NetworkUtils/NetworkConnection.cpp deleted file mode 100644 index 929d6d2..0000000 --- a/lib/NetworkUtils/NetworkConnection.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "NetworkConnection.h" -using namespace NetworkUtils; - -void NetworkConnection::setup(bool useDhcp) { - setUseDhcp(useDhcp); - - WiFi.onEvent(NetworkConnection::onEvent); -} - -void NetworkConnection::reset() { - status = Status::NONE; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; -} - -void NetworkConnection::setUseDhcp(bool value) { - useDhcp = value; -} - -NetworkConnection::Status NetworkConnection::getStatus() { - return status; -} - -NetworkConnection::DisconnectReason NetworkConnection::getDisconnectReason() { - return disconnectReason; -} - -void NetworkConnection::onEvent(WiFiEvent_t event, WiFiEventInfo_t info) { - switch (event) { - case ARDUINO_EVENT_WIFI_STA_CONNECTED: - status = useDhcp ? Status::CONNECTING : Status::CONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; - break; - - case ARDUINO_EVENT_WIFI_STA_GOT_IP: - case ARDUINO_EVENT_WIFI_STA_GOT_IP6: - status = Status::CONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::NONE; - break; - - case ARDUINO_EVENT_WIFI_STA_LOST_IP: - status = Status::DISCONNECTED; - rawDisconnectReason = 0; - disconnectReason = DisconnectReason::DHCP_TIMEOUT; - break; - - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - status = Status::DISCONNECTED; - rawDisconnectReason = info.wifi_sta_disconnected.reason; - disconnectReason = convertDisconnectReason(info.wifi_sta_disconnected.reason); - break; - - default: - break; - } -} - -NetworkConnection::DisconnectReason NetworkConnection::convertDisconnectReason(uint8_t reason) { - switch (reason) { - case WIFI_REASON_BEACON_TIMEOUT: - return DisconnectReason::BEACON_TIMEOUT; - - case WIFI_REASON_NO_AP_FOUND: - return DisconnectReason::NO_AP_FOUND; - - case WIFI_REASON_AUTH_FAIL: - return DisconnectReason::AUTH_FAIL; - - case WIFI_REASON_ASSOC_FAIL: - return DisconnectReason::ASSOC_FAIL; - - case WIFI_REASON_HANDSHAKE_TIMEOUT: - return DisconnectReason::HANDSHAKE_TIMEOUT; - - default: - return DisconnectReason::OTHER; - } -} - -bool NetworkConnection::useDhcp = false; -NetworkConnection::Status NetworkConnection::status = Status::NONE; -NetworkConnection::DisconnectReason NetworkConnection::disconnectReason = DisconnectReason::NONE; -uint8_t NetworkConnection::rawDisconnectReason = 0; diff --git a/lib/NetworkUtils/NetworkConnection.h b/lib/NetworkUtils/NetworkConnection.h deleted file mode 100644 index ec9439d..0000000 --- a/lib/NetworkUtils/NetworkConnection.h +++ /dev/null @@ -1,38 +0,0 @@ -#include - -namespace NetworkUtils { - struct NetworkConnection { - enum class Status { - CONNECTED, - CONNECTING, - DISCONNECTED, - NONE - }; - - enum class DisconnectReason { - BEACON_TIMEOUT, - NO_AP_FOUND, - AUTH_FAIL, - ASSOC_FAIL, - HANDSHAKE_TIMEOUT, - DHCP_TIMEOUT, - OTHER, - NONE - }; - - static Status status; - static DisconnectReason disconnectReason; - static uint8_t rawDisconnectReason; - - static void setup(bool useDhcp); - static void setUseDhcp(bool value); - static void reset(); - static Status getStatus(); - static DisconnectReason getDisconnectReason(); - static void onEvent(WiFiEvent_t event, WiFiEventInfo_t info); - - protected: - static DisconnectReason convertDisconnectReason(uint8_t reason); - static bool useDhcp; - }; -} diff --git a/lib/NetworkUtils/NetworkMgr.h b/lib/NetworkUtils/NetworkMgr.h deleted file mode 100644 index 5883c41..0000000 --- a/lib/NetworkUtils/NetworkMgr.h +++ /dev/null @@ -1,414 +0,0 @@ -#include -#include -#include - -namespace NetworkUtils { - class NetworkMgr { - public: - typedef std::function YieldCallback; - typedef std::function DelayCallback; - - NetworkMgr() { - NetworkConnection::setup(this->useDhcp); - this->resetWifi(); - } - - NetworkMgr* setYieldCallback(YieldCallback callback = nullptr) { - this->yieldCallback = callback; - - return this; - } - - NetworkMgr* setDelayCallback(DelayCallback callback = nullptr) { - this->delayCallback = callback; - - return this; - } - - NetworkMgr* setHostname(const char* value) { - this->hostname = value; - return this; - } - - NetworkMgr* setApCredentials(const char* ssid, const char* password = nullptr, uint8_t channel = 0) { - this->apName = ssid; - this->apPassword = password; - this->apChannel = channel; - - return this; - } - - NetworkMgr* setStaCredentials(const char* ssid = nullptr, const char* password = nullptr, uint8_t channel = 0) { - this->staSsid = ssid; - this->staPassword = password; - this->staChannel = channel; - - return this; - } - - NetworkMgr* setUseDhcp(bool value) { - this->useDhcp = value; - NetworkConnection::setup(this->useDhcp); - - return this; - } - - NetworkMgr* setStaticConfig(const char* ip, const char* gateway, const char* subnet, const char* dns) { - this->staticIp.fromString(ip); - this->staticGateway.fromString(gateway); - this->staticSubnet.fromString(subnet); - this->staticDns.fromString(dns); - - return this; - } - - NetworkMgr* setStaticConfig(IPAddress& ip, IPAddress& gateway, IPAddress& subnet, IPAddress& dns) { - this->staticIp = ip; - this->staticGateway = gateway; - this->staticSubnet = subnet; - this->staticDns = dns; - - return this; - } - - bool hasStaCredentials() { - return this->staSsid != nullptr; - } - - bool isConnected() { - return this->isStaEnabled() && NetworkConnection::getStatus() == NetworkConnection::Status::CONNECTED; - } - - bool isConnecting() { - return this->isStaEnabled() && NetworkConnection::getStatus() == NetworkConnection::Status::CONNECTING; - } - - bool isStaEnabled() { - return (WiFi.getMode() & WIFI_STA) != 0; - } - - bool isApEnabled() { - return (WiFi.getMode() & WIFI_AP) != 0; - } - - bool hasApClients() { - if (!this->isApEnabled()) { - return false; - } - - return WiFi.softAPgetStationNum() > 0; - } - - short int getRssi() { - return WiFi.RSSI(); - } - - IPAddress getApIp() { - return WiFi.softAPIP(); - } - - IPAddress getStaIp() { - return WiFi.localIP(); - } - - IPAddress getStaSubnet() { - return WiFi.subnetMask(); - } - - IPAddress getStaGateway() { - return WiFi.gatewayIP(); - } - - IPAddress getStaDns() { - return WiFi.dnsIP(); - } - - String getStaMac() { - return WiFi.macAddress(); - } - - const char* getStaSsid() { - return this->staSsid; - } - - const char* getStaPassword() { - return this->staPassword; - } - - uint8_t getStaChannel() { - return this->staChannel; - } - - bool resetWifi() { - // set policy manual for work 13 ch - { - const wifi_country_t country = {"JP", 1, 14, CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER, WIFI_COUNTRY_POLICY_MANUAL}; - esp_wifi_set_country(&country); - } - - WiFi.persistent(false); - #if ESP_ARDUINO_VERSION_MAJOR < 3 - WiFi.setAutoConnect(false); - #endif - WiFi.setAutoReconnect(false); - - WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE); - - WiFi.softAPdisconnect(); - - WiFi.disconnect(false, true); - - #if ESP_ARDUINO_VERSION_MAJOR < 3 - // Nothing. Because memory leaks when turn off WiFi on ESP32 SDK < 3.0.0 - return true; - #else - return WiFi.mode(WIFI_OFF); - #endif - } - - void reconnect() { - this->reconnectFlag = true; - } - - bool connect(bool force = false, unsigned int timeout = 1000u) { - if (this->isConnected() && !force) { - return true; - } - - if (force && !this->isApEnabled()) { - this->resetWifi(); - NetworkConnection::reset(); - - } else { - this->disconnect(); - } - - if (!this->hasStaCredentials()) { - return false; - } - - this->delayCallback(250); - - if (this->setWifiHostname(this->hostname)) { - Log.straceln(L_NETWORK, "Set hostname '%s': success", this->hostname); - - } else { - Log.serrorln(L_NETWORK, "Set hostname '%s': fail", this->hostname); - } - - if (!WiFi.mode((WiFiMode_t)(WiFi.getMode() | WIFI_STA))) { - return false; - } - - this->delayCallback(250); - - WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); - WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); - - if (!this->useDhcp) { - WiFi.begin(this->staSsid, this->staPassword, this->staChannel, nullptr, false); - WiFi.config(this->staticIp, this->staticGateway, this->staticSubnet, this->staticDns); - WiFi.reconnect(); - - } else { - WiFi.begin(this->staSsid, this->staPassword, this->staChannel, nullptr, true); - } - - unsigned long beginConnectionTime = millis(); - while (millis() - beginConnectionTime < timeout) { - this->delayCallback(100); - - NetworkConnection::Status status = NetworkConnection::getStatus(); - if (status != NetworkConnection::Status::CONNECTING && status != NetworkConnection::Status::NONE) { - return status == NetworkConnection::Status::CONNECTED; - } - } - - return false; - } - - void disconnect() { - WiFi.disconnectAsync(false, true); - - const unsigned long start = millis(); - while (WiFi.isConnected() && (millis() - start) < 5000) { - this->delayCallback(100); - } - } - - void loop() { - if (this->reconnectFlag) { - this->delayCallback(5000); - - Log.sinfoln(L_NETWORK, "Reconnecting..."); - this->reconnectFlag = false; - this->disconnect(); - NetworkConnection::reset(); - this->delayCallback(1000); - - } else if (this->isConnected() && !this->hasStaCredentials()) { - Log.sinfoln(L_NETWORK, "Reset"); - this->resetWifi(); - NetworkConnection::reset(); - this->delayCallback(1000); - - } else if (this->isConnected()) { - if (!this->connected) { - this->connectedTime = millis(); - this->connected = true; - - Log.sinfoln( - L_NETWORK, - "Connected, downtime: %lu s., IP: %s, RSSI: %hhd", - (millis() - this->disconnectedTime) / 1000, - WiFi.localIP().toString().c_str(), - WiFi.RSSI() - ); - } - - if (this->isApEnabled() && millis() - this->connectedTime > this->reconnectInterval && !this->hasApClients()) { - Log.sinfoln(L_NETWORK, "Stop AP because STA connected"); - - WiFi.mode(WIFI_STA); - return; - } - - } else { - if (this->connected) { - this->disconnectedTime = millis(); - this->connected = false; - - Log.sinfoln( - L_NETWORK, - "Disconnected, reason: %d, uptime: %lu s.", - NetworkConnection::getDisconnectReason(), - (millis() - this->connectedTime) / 1000 - ); - } - - if (!this->hasStaCredentials() && !this->isApEnabled()) { - Log.sinfoln(L_NETWORK, "No STA credentials, start AP"); - - WiFi.mode(WIFI_AP_STA); - this->delayCallback(250); - WiFi.softAP(this->apName, this->apPassword, this->apChannel); - - } else if (!this->isApEnabled() && millis() - this->disconnectedTime > this->failedConnectTimeout) { - Log.sinfoln(L_NETWORK, "Disconnected for a long time, start AP"); - - WiFi.mode(WIFI_AP_STA); - this->delayCallback(250); - WiFi.softAP(this->apName, this->apPassword, this->apChannel); - - } else if (this->isConnecting() && millis() - this->prevReconnectingTime > this->resetConnectionTimeout) { - Log.swarningln(L_NETWORK, "Connection timeout, reset wifi..."); - this->resetWifi(); - NetworkConnection::reset(); - this->delayCallback(250); - - } else if (!this->isConnecting() && this->hasStaCredentials() && (!this->prevReconnectingTime || millis() - this->prevReconnectingTime > this->reconnectInterval)) { - Log.sinfoln(L_NETWORK, "Try connect..."); - - NetworkConnection::reset(); - if (!this->connect(true, this->connectionTimeout)) { - Log.straceln(L_NETWORK, "Connection failed. Status: %d, reason: %d, raw reason: %d", NetworkConnection::getStatus(), NetworkConnection::getDisconnectReason(), NetworkConnection::rawDisconnectReason); - } - - this->prevReconnectingTime = millis(); - } - } - } - - static uint8_t rssiToSignalQuality(short int rssi) { - return constrain(map(rssi, -100, -50, 0, 100), 0, 100); - } - - static bool isHostnameValid(const char* value) { - if (value == nullptr) { - return false; - } - - size_t len = strlen(value); - if (len == 0 || len > 24 || value[0] == '-' || value[len - 1] == '-') { - return false; - } - - for (size_t i = 0; i < len; i++) { - const char symbol = value[i]; - - // Lowercase ASCII letters. - if (symbol >= 'a' && symbol <= 'z') { - continue; - } - - // Uppercase ASCII letters. - if (symbol >= 'A' && symbol <= 'Z') { - continue; - } - - // Decimal digits. - if (symbol >= '0' && symbol <= '9') { - continue; - } - - // Hyphens are allowed inside the hostname. - if (symbol == '-') { - continue; - } - - // All other characters are invalid. - return false; - } - - return true; - } - - protected: - const unsigned int reconnectInterval = 15000; - const unsigned int failedConnectTimeout = 185000; - const unsigned int connectionTimeout = 10000; - const unsigned int resetConnectionTimeout = 90000; - - YieldCallback yieldCallback = []() { - ::yield(); - }; - DelayCallback delayCallback = [](unsigned int time) { - ::delay(time); - }; - - const char* hostname = "esp"; - const char* apName = "ESP"; - const char* apPassword = nullptr; - uint8_t apChannel = 1; - - const char* staSsid = nullptr; - const char* staPassword = nullptr; - uint8_t staChannel = 0; - - bool useDhcp = true; - IPAddress staticIp; - IPAddress staticGateway; - IPAddress staticSubnet; - IPAddress staticDns; - - bool connected = false; - bool reconnectFlag = false; - unsigned long prevReconnectingTime = 0; - unsigned long connectedTime = 0; - unsigned long disconnectedTime = 0; - - - bool setWifiHostname(const char* hostname) { - if (!this->isHostnameValid(hostname)) { - return false; - } - - if (strcmp(WiFi.getHostname(), hostname) == 0) { - return true; - } - - return WiFi.setHostname(hostname); - } - - }; -} diff --git a/lib/WebServerHandlers/StaticPage.h b/lib/WebServerHandlers/StaticPage.h deleted file mode 100644 index 8d61f91..0000000 --- a/lib/WebServerHandlers/StaticPage.h +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include - -using namespace mime; - -class StaticPage : public RequestHandler { -public: - typedef std::function CanHandleCallback; - typedef std::function BeforeSendCallback; - - template - StaticPage(const char* uri, FS* fs, T path, const char* cacheHeader = nullptr) { - this->uri = uri; - this->fs = fs; - this->path = path; - this->cacheHeader = cacheHeader; - } - - StaticPage* setCanHandleCallback(CanHandleCallback callback = nullptr) { - this->canHandleCallback = callback; - - return this; - } - - StaticPage* setBeforeSendCallback(BeforeSendCallback callback = nullptr) { - this->beforeSendCallback = callback; - - return this; - } - - bool canHandle(WebServer &server, HTTPMethod method, const String &uri) override { - return this->canHandle(method, uri); - } - - bool canHandle(HTTPMethod method, const String& uri) override { - return method == HTTP_GET && uri.equals(this->uri) && (!this->canHandleCallback || this->canHandleCallback(method, uri)); - } - - bool handle(WebServer& server, HTTPMethod method, const String& uri) override { - if (!this->canHandle(method, uri)) { - return false; - } - - if (this->beforeSendCallback && !this->beforeSendCallback()) { - return true; - } - - if (server._eTagEnabled) { - if (this->eTag.isEmpty()) { - if (server._eTagFunction) { - this->eTag = (server._eTagFunction)(*this->fs, this->path); - } - } - - if (!this->eTag.isEmpty() && server.header("If-None-Match").equals(this->eTag.c_str())) { - server.send(304); - return true; - } - } - - if (!this->path.endsWith(mimeTable[gz].endsWith) && !this->fs->exists(path)) { - String pathWithGz = this->path + mimeTable[gz].endsWith; - - if (this->fs->exists(pathWithGz)) { - this->path += mimeTable[gz].endsWith; - } - } - - File file = this->fs->open(this->path, "r"); - if (!file) { - return false; - - } else if (file.isDirectory()) { - file.close(); - return false; - } - - if (this->cacheHeader != nullptr) { - server.sendHeader("Cache-Control", this->cacheHeader); - } - - if (server._eTagEnabled && !this->eTag.isEmpty()) { - server.sendHeader("ETag", this->eTag); - } - - server.streamFile(file, "text/html", 200); - - return true; - } - -protected: - FS* fs = nullptr; - CanHandleCallback canHandleCallback; - BeforeSendCallback beforeSendCallback; - String eTag; - const char* uri = nullptr; - String path; - const char* cacheHeader = nullptr; -}; diff --git a/lib/WebServerHandlers/UpgradeHandler.h b/lib/WebServerHandlers/UpgradeHandler.h index bf6aaf4..e49a653 100644 --- a/lib/WebServerHandlers/UpgradeHandler.h +++ b/lib/WebServerHandlers/UpgradeHandler.h @@ -1,4 +1,6 @@ #include +#include +#include class UpgradeHandler : public AsyncWebHandler { public: @@ -27,12 +29,13 @@ public: } UpgradeResult; typedef std::function BeforeUpgradeCallback; + // A null request reports an upload disconnected after preparation was accepted. typedef std::function AfterUpgradeCallback; explicit UpgradeHandler(AsyncURIMatcher uri) : uri(uri) {} bool canHandle(AsyncWebServerRequest *request) const final { - if (!request->isHTTP()) { + if (!request->isHTTP() || request->method() != HTTP_POST) { return false; } @@ -52,18 +55,28 @@ public: } void handleRequest(AsyncWebServerRequest *request) final { - if (this->afterUpgradeCallback) { - this->afterUpgradeCallback(request, this->firmwareResult, this->filesystemResult); + if (request->getResponse()) { + return; } - this->firmwareResult.status = UpgradeStatus::NONE; - this->firmwareResult.error.clear(); + if (this->activeRequest != request) { + request->send(this->activeRequest ? 409 : 400); + return; + } - this->filesystemResult.status = UpgradeStatus::NONE; - this->filesystemResult.error.clear(); + finishRequest(request); } void handleUpload(AsyncWebServerRequest *request, const String &fileName, size_t index, uint8_t *data, size_t dataLength, bool isFinal) final { + if (request->getResponse()) { + return; + } + if (this->activeRequest && this->activeRequest != request) { + // Keep the rejection on this request even if the active upload finishes first. + request->send(409); + return; + } + UpgradeResult* result = nullptr; if (!request->hasParam(asyncsrv::T_name, true, true)) { @@ -97,6 +110,15 @@ public: return; } + if (!this->activeRequest) { + this->activeRequest = request; + request->onDisconnect([this, request] { + if (this->activeRequest == request) { + finishRequest(nullptr); + } + }); + } + // check result status if (result->status != UpgradeStatus::NONE) { return; @@ -106,6 +128,7 @@ public: result->status = UpgradeStatus::PROHIBITED; return; } + this->preparationAccepted = true; if (!fileName.length()) { result->status = UpgradeStatus::NO_FILE; @@ -132,11 +155,11 @@ public: result->status = UpgradeStatus::ERROR_ON_START; result->error = Update.errorString(); - Log.serrorln(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str()); + ESP_LOGE(L_PORTAL_OTA, "File '%s', on start: %s", fileName.c_str(), result->error.c_str()); return; } - Log.sinfoln(L_PORTAL_OTA, "File '%s', started", fileName.c_str()); + ESP_LOGI(L_PORTAL_OTA, "File '%s', started", fileName.c_str()); } if (dataLength) { @@ -145,7 +168,7 @@ public: result->status = UpgradeStatus::ERROR_ON_WRITE; result->error = Update.errorString(); - Log.serrorln( + ESP_LOGE( L_PORTAL_OTA, "File '%s', on write %d bytes, %d of %d bytes", fileName.c_str(), dataLength, @@ -156,7 +179,7 @@ public: } result->progress += dataLength; - Log.sinfoln( + ESP_LOGI( L_PORTAL_OTA, "File '%s', write %d bytes, %d of %d bytes", fileName.c_str(), dataLength, @@ -170,7 +193,7 @@ public: Update.end(false); result->status = UpgradeStatus::SIZE_MISMATCH; - Log.serrorln( + ESP_LOGE( L_PORTAL_OTA, "File '%s', size mismatch: %d of %d bytes", fileName.c_str(), result->progress, @@ -185,12 +208,12 @@ public: result->status = UpgradeStatus::ERROR_ON_FINISH; result->error = Update.errorString(); - Log.serrorln(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str()); + ESP_LOGE(L_PORTAL_OTA, "File '%s', on finish: %s", fileName.c_str(), result->error.c_str()); return; } result->status = UpgradeStatus::SUCCESS; - Log.sinfoln(L_PORTAL_OTA, "File '%s': finish", fileName.c_str()); + ESP_LOGI(L_PORTAL_OTA, "File '%s': finish", fileName.c_str()); } } @@ -199,10 +222,31 @@ public: } protected: + void finishRequest(AsyncWebServerRequest *request) { + if (request) { + request->onDisconnect(nullptr); + } + if (Update.isRunning()) { + // Abort only the unfinished file; an earlier successful firmware still needs a restart. + Update.abort(); + } + if (this->afterUpgradeCallback && (request || this->preparationAccepted)) { + this->afterUpgradeCallback(request, this->firmwareResult, this->filesystemResult); + } + + this->activeRequest = nullptr; + this->preparationAccepted = false; + this->firmwareResult = {UpgradeType::FIRMWARE, UpgradeStatus::NONE}; + this->filesystemResult = {UpgradeType::FILESYSTEM, UpgradeStatus::NONE}; + } + BeforeUpgradeCallback beforeUpgradeCallback; AfterUpgradeCallback afterUpgradeCallback; AsyncURIMatcher uri; + // Upload, completion and disconnect callbacks share the AsyncTCP worker. + AsyncWebServerRequest* activeRequest = nullptr; + bool preparationAccepted = false; UpgradeResult firmwareResult{UpgradeType::FIRMWARE, UpgradeStatus::NONE}; UpgradeResult filesystemResult{UpgradeType::FILESYSTEM, UpgradeStatus::NONE}; }; diff --git a/platformio.ini b/platformio.ini index 91cb164..3951b96 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,18 +1,19 @@ [platformio] -;extra_configs = secrets.ini -extra_configs = secrets.default.ini +;extra_configs = secrets.ini +extra_configs = secrets.default.ini ;core_dir = .pio [env] -version = 1.6.0-async +custom_version = 2.0.0-dev framework = arduino lib_deps = ESP32Async/AsyncTCP@^3.5.0 ESP32Async/ESPAsyncWebServer@^3.12.1 mathieucarbou/MycilaWebSerial@^8.2.3 bblanchon/ArduinoJson@^7.4.3 ;ihormelnyk/OpenTherm Library@^1.1.5 - https://github.com/Laxilef/opentherm_library#esp32_timer - arduino-libraries/ArduinoMqttClient@^0.1.8 + https://github.com/Laxilef/ESP32OT + https://github.com/mathieucarbou/MycilaMQTT + https://github.com/mathieucarbou/MycilaHADiscovery/ gyverlibs/FileData@^1.0.3 gyverlibs/GyverPID@^3.3.2 gyverlibs/GyverBlinker@^1.1.1 @@ -20,23 +21,12 @@ lib_deps = ESP32Async/AsyncTCP@^3.5.0 https://github.com/pstolarz/OneWireNg.git milesburton/DallasTemperature@^4.0.6 https://github.com/Laxilef/esp32DHT#idf5 - ;laxilef/TinyLogger@^1.1.1 - https://github.com/Laxilef/TinyLogger#custom_handlers lib_ignore = OneWire build_type = ${secrets.build_type} build_flags = ;-mtext-section-literals - -O2 - -Wno-deprecated-declarations - -D MQTT_CLIENT_STD_FUNCTION_CALLBACK=1 - -D WSL_CUSTOM_PAGE ;-D DEBUG_ESP_CORE -D DEBUG_ESP_WIFI -D DEBUG_ESP_HTTP_SERVER -D DEBUG_ESP_PORT=Serial - -D BUILD_VERSION='"${this.version}"' + -D BUILD_VERSION='"${this.custom_version}"' -D BUILD_ENV='"$PIOENV"' - -D CONFIG_ASYNC_TCP_STACK_SIZE=4096 - -D ARDUINOJSON_USE_DOUBLE=0 - -D ARDUINOJSON_USE_LONG_LONG=0 - -D TINYLOGGER_GLOBAL - -D DHT_TASK_STACK_SIZE=4096 -D DEFAULT_SERIAL_ENABLED=${secrets.serial_enabled} -D DEFAULT_SERIAL_BAUD=${secrets.serial_baud} -D DEFAULT_WEBSERIAL_ENABLED=${secrets.webserial_enabled} @@ -65,12 +55,13 @@ check_flags = ;pvs-studio: --analysis-mode=4 --exclude-path=./.pio/l ; Defaults [esp32_defaults] -platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.312-1/platform-espressif32.zip +;platform = https://github.com/pioarduino/platform-espressif32.git#prep_IDF6 +platform = https://github.com/pioarduino/platform-espressif32/releases/download/61.04.00/platform-espressif32.zip platform_packages = ${env.platform_packages} board_build.partitions = esp32_partitions.csv lib_deps = ${env.lib_deps} - laxilef/ESP32Scheduler@^1.0.1 -nimble_lib = https://github.com/h2zero/NimBLE-Arduino + https://github.com/mathieucarbou/MycilaTaskManager#main +nimble_lib = https://github.com/h2zero/NimBLE-Arduino#master lib_ignore = ${env.lib_ignore} BluetoothSerial SimpleBLE @@ -82,6 +73,10 @@ lib_ignore = ${env.lib_ignore} Matter OpenThread dsp +; No release includes the stop/reconnect wakeup fix yet (2026-11-21). +; With the broker unavailable, stop() can wait for reconnect backoff to expire, delaying OTA/restart. +; Fix: https://github.com/espressif/esp-mqtt/commit/c29cdda15f2812207a5740e7ec8f6efdd59d8e77 +custom_component_add = espressif/mqtt@1.1.0 custom_component_remove = espressif/esp_hosted espressif/esp_wifi_remote espressif/esp-dsp @@ -100,16 +95,57 @@ custom_component_remove = espressif/esp_hosted espressif/esp-zboss-lib espressif/esp-zigbee-lib chmorgan/esp-libhelix-mp3 -extra_scripts = pre:tools/add_build_commit.py + espressif/cjson +extra_scripts = pre:tools/after_build_sdk.py + pre:tools/add_build_commit.py post:tools/esp32.py post:tools/build.py build_type = ${env.build_type} +build_unflags = -fno-lto build_flags = ${env.build_flags} + -Os + -Wno-deprecated-declarations + -D WSL_CUSTOM_PAGE + ; Log transport runs on the System worker instead of producer stacks. + -D CONFIG_ASYNC_TCP_STACK_SIZE=5120 + -D ARDUINOJSON_USE_DOUBLE=0 + -D ARDUINOJSON_USE_LONG_LONG=0 + -D DHT_TASK_STACK_SIZE=4096 + -D MYCILA_TASK_MANAGER_NO_STATS + -D MYCILA_MQTT_DEBUG -D MYNEWT_VAL_BLE_MAX_CONNECTIONS=1 -D MYNEWT_VAL_BLE_STORE_MAX_BONDS=1 + ; BLE callbacks format logs; System sends them to transports. + -D MYNEWT_VAL_NIMBLE_HOST_TASK_STACK_SIZE=4608 -D MYNEWT_VAL_BLE_ROLE_CENTRAL=0 - -D CORE_DEBUG_LEVEL=0 + -D CORE_DEBUG_LEVEL=ESP_LOG_ERROR + -D USE_ESP_IDF_LOG -Wl,--wrap=esp_panic_handler + -Wl,--wrap=esp_log_format +custom_app_flags = -D LOG_LOCAL_LEVEL=ESP_LOG_VERBOSE +custom_sdkconfig = '# CONFIG_AUTOSTART_ARDUINO is not set' + ; Async scalar publications must drain faster than the default 1 s MQTT poll. + CONFIG_MQTT_USE_CUSTOM_CONFIG=y + CONFIG_MQTT_PROTOCOL_311=y + CONFIG_MQTT_POLL_READ_TIMEOUT_MS=5 + ; Initialization now runs on the IDF main task instead of loopTask. + CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 + '# CONFIG_LOG_VERSION_1 is not set' + CONFIG_LOG_VERSION_2=y + CONFIG_LOG_VERSION=2 + CONFIG_LOG_COLORS=y + '# CONFIG_LOG_TIMESTAMP_SOURCE_RTOS is not set' + CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM=y + '# CONFIG_OPENTHREAD_ENABLED is not set' + '# CONFIG_ZB_ENABLED is not set' + '# CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT is not set' + '# CONFIG_LWIP_IPV6 is not set' + '# CONFIG_LWIP_IPV6_AUTOCONFIG is not set' + '# CONFIG_LWIP_PPP_SUPPORT is not set' + '# CONFIG_MQTT_TRANSPORT_WEBSOCKET is not set' + '# CONFIG_LWIP_IP_FORWARD is not set' + '# CONFIG_ESP_WIFI_FTM_ENABLE is not set' + '# CONFIG_ESP_WIFI_CSI_ENABLED is not set' check_tool = ${env.check_tool} check_flags = ${env.check_flags} @@ -118,10 +154,14 @@ check_flags = ${env.check_flags} [env:s2_mini] extends = esp32_defaults board = lolin_s2_mini -build_unflags = -DARDUINO_USB_MODE=1 +extra_scripts = ${esp32_defaults.extra_scripts} + pre:tools/tinyusb_s2.py +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + '# CONFIG_BT_ENABLED is not set' + CONFIG_TINYUSB_ENABLED=y + CONFIG_TINYUSB_CDC_ENABLED=y + CONFIG_TINYUSB_CDC_MAX_PORTS=2 build_flags = ${esp32_defaults.build_flags} - -D ARDUINO_USB_MODE=0 - -D ARDUINO_USB_CDC_ON_BOOT=1 -D DEFAULT_OT_IN_GPIO=33 -D DEFAULT_OT_OUT_GPIO=35 -D DEFAULT_SENSOR_OUTDOOR_GPIO=9 @@ -132,11 +172,12 @@ build_flags = ${esp32_defaults.build_flags} [env:s3_mini] extends = esp32_defaults board = lolin_s3_mini +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + '# CONFIG_TINYUSB_ENABLED is not set' lib_deps = ${esp32_defaults.lib_deps} ${esp32_defaults.nimble_lib} -build_unflags = -DARDUINO_USB_MODE=1 build_flags = ${esp32_defaults.build_flags} - -D ARDUINO_USB_MODE=0 + -D ARDUINO_USB_MODE=1 -D ARDUINO_USB_CDC_ON_BOOT=1 -D MYNEWT_VAL_BLE_EXT_ADV=1 -D USE_BLE=1 @@ -147,13 +188,24 @@ build_flags = ${esp32_defaults.build_flags} -D DEFAULT_STATUS_LED_GPIO=11 -D DEFAULT_OT_RX_LED_GPIO=10 +;[env:s3_mini_no_psram] ; FOR TESTS +;extends = env:s3_mini +;build_unflags = ${esp32_defaults.build_unflags} +; -DBOARD_HAS_PSRAM +; -mdisable-hardware-atomics +;custom_sdkconfig = ${env:s3_mini.custom_sdkconfig} +; '# CONFIG_SPIRAM is not set' + [env:c3_mini] extends = esp32_defaults board = lolin_c3_mini lib_deps = ${esp32_defaults.lib_deps} ${esp32_defaults.nimble_lib} -;build_unflags = -mtext-section-literals +build_unflags = ${esp32_defaults.build_unflags} + -mno-save-restore +custom_link_flags = -msave-restore build_flags = ${esp32_defaults.build_flags} + -msave-restore -D MYNEWT_VAL_BLE_EXT_ADV=1 -D USE_BLE=1 -D DEFAULT_OT_IN_GPIO=8 @@ -162,6 +214,8 @@ build_flags = ${esp32_defaults.build_flags} -D DEFAULT_SENSOR_INDOOR_GPIO=1 -D DEFAULT_STATUS_LED_GPIO=4 -D DEFAULT_OT_RX_LED_GPIO=5 +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y [env:nodemcu_32] extends = esp32_defaults @@ -200,8 +254,18 @@ extends = esp32_defaults board = esp32-c6-devkitc-1 lib_deps = ${esp32_defaults.lib_deps} ${esp32_defaults.nimble_lib} -;build_unflags = -mtext-section-literals +build_unflags = ${esp32_defaults.build_unflags} + -mno-save-restore + -fexceptions + -Os +custom_link_flags = -msave-restore + -Oz build_flags = ${esp32_defaults.build_flags} + -msave-restore + -fno-exceptions + -Oz + -D _GLIBCXX20_CONSTEXPR=__attribute__((cold))constexpr + -D _GLIBCXX23_CONSTEXPR=__attribute__((cold))constexpr -D USE_BLE=1 -D DEFAULT_OT_IN_GPIO=15 -D DEFAULT_OT_OUT_GPIO=23 @@ -209,21 +273,34 @@ build_flags = ${esp32_defaults.build_flags} -D DEFAULT_SENSOR_INDOOR_GPIO=0 -D DEFAULT_STATUS_LED_GPIO=11 -D DEFAULT_OT_RX_LED_GPIO=10 -custom_sdkconfig = '# CONFIG_OPENTHREAD_ENABLED is not set' - '# CONFIG_ZB_ENABLED is not set' - '# CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT is not set' - '# CONFIG_LWIP_IPV6 is not set' - '# CONFIG_LWIP_IPV6_AUTOCONFIG is not set' - '# CONFIG_LWIP_PPP_SUPPORT is not set' +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y '# CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS is not set' + '# CONFIG_COMPILER_CXX_EXCEPTIONS is not set' + '# CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT is not set' + '# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set' + CONFIG_MBEDTLS_TLS_CLIENT_ONLY=y + '# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set' + '# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set' + ; Assertions still abort; detailed failure messages are omitted. + '# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE is not set' + '# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set' + CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT=y + ; Use the compact definitions above instead of spaced native metadata. + '# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD_CONSTEXPR is not set' + '# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set' + CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y [env:otthing] extends = esp32_defaults board = lolin_c3_mini lib_deps = ${esp32_defaults.lib_deps} ${esp32_defaults.nimble_lib} -;build_unflags = -mtext-section-literals +build_unflags = ${esp32_defaults.build_unflags} + -mno-save-restore +custom_link_flags = -msave-restore build_flags = ${esp32_defaults.build_flags} + -msave-restore -D MYNEWT_VAL_BLE_EXT_ADV=1 -D USE_BLE=1 -D DEFAULT_OT_IN_GPIO=3 @@ -233,3 +310,5 @@ build_flags = ${esp32_defaults.build_flags} -D DEFAULT_STATUS_LED_GPIO=8 -D DEFAULT_OT_RX_LED_GPIO=2 -D OT_BYPASS_RELAY_GPIO=20 +custom_sdkconfig = ${esp32_defaults.custom_sdkconfig} + CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS=y diff --git a/secrets.default.ini b/secrets.default.ini index 2aaa9f2..b53086b 100644 --- a/secrets.default.ini +++ b/secrets.default.ini @@ -4,7 +4,7 @@ build_type = release serial_enabled = true serial_baud = 115200 webserial_enabled = true -log_level = 5 +log_level = ESP_LOG_INFO hostname = opentherm ap_ssid = OpenTherm Gateway diff --git a/src/CrashRecorder.h b/src/CrashRecorder.h deleted file mode 100644 index b0a106e..0000000 --- a/src/CrashRecorder.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once -#include - -#include "esp_err.h" - -namespace CrashRecorder { - typedef struct { - unsigned int data[32]; - uint8_t length; - bool continues; - } backtrace_t; - - typedef struct { - unsigned int data[4]; - uint8_t length; - } epc_t; - - typedef struct { - uint8_t core; - size_t heap; - unsigned long uptime; - } ext_t; - - - __NOINIT_ATTR volatile static backtrace_t backtrace; // NOLINT - __NOINIT_ATTR volatile static epc_t epc; // NOLINT - __NOINIT_ATTR volatile static ext_t ext; // NOLINT - - uint8_t backtraceMaxLength = sizeof(backtrace.data) / sizeof(*backtrace.data); - uint8_t epcMaxLength = sizeof(epc.data) / sizeof(*epc.data); - - void IRAM_ATTR panicHandler(arduino_panic_info_t *info, void *arg) {; - ext.core = info->core; - ext.heap = ESP.getFreeHeap(); - ext.uptime = millis() / 1000u; - - // Backtrace - backtrace.length = info->backtrace_len < backtraceMaxLength ? info->backtrace_len : backtraceMaxLength; - backtrace.continues = false; - for (unsigned int i = 0; i < info->backtrace_len; i++) { - if (i >= backtraceMaxLength) { - backtrace.continues = true; - break; - } - - backtrace.data[i] = info->backtrace[i]; - } - - // EPC - if (info->pc) { - epc.data[0] = (unsigned int) info->pc; - epc.length = 1; - - } else { - epc.length = 0; - } - } - - void init() { - if (backtrace.length > backtraceMaxLength) { - backtrace.length = 0; - } - - if (epc.length > epcMaxLength) { - epc.length = 0; - } - - set_arduino_panic_handler(panicHandler, nullptr); - } -} diff --git a/src/HaHelper.h b/src/HaHelper.h deleted file mode 100644 index 3334081..0000000 --- a/src/HaHelper.h +++ /dev/null @@ -1,1411 +0,0 @@ -#pragma once -#include - -class HaHelper : public HomeAssistantHelper { -public: - static const uint8_t TEMP_SOURCE_HEATING = 0; - static const uint8_t TEMP_SOURCE_INDOOR = 1; - static const char AVAILABILITY_OT_CONN[]; - static const char AVAILABILITY_SENSOR_CONN[]; - - void updateCachedTopics() { - this->statusTopic = this->getDeviceTopic("status"); - this->stateTopic = this->getDeviceTopic("state"); - this->setStateTopic = this->getDeviceTopic("state/set"); - this->settingsTopic = this->getDeviceTopic("settings"); - this->setSettingsTopic = this->getDeviceTopic("settings/set"); - } - - void setExpireAfter(unsigned short value) { - this->expireAfter = value; - } - - auto getExpireAfter() { - return this->expireAfter; - } - - bool publishDynamicSensor(Sensors::Settings& sSensor, Sensors::ValueType vType = Sensors::ValueType::PRIMARY, UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - - // set device class & unit of measurement - switch (sSensor.purpose) { - case Sensors::Purpose::OUTDOOR_TEMP: - case Sensors::Purpose::INDOOR_TEMP: - case Sensors::Purpose::HEATING_TEMP: - case Sensors::Purpose::HEATING_RETURN_TEMP: - case Sensors::Purpose::DHW_TEMP: - case Sensors::Purpose::DHW_RETURN_TEMP: - case Sensors::Purpose::EXHAUST_TEMP: - case Sensors::Purpose::TEMPERATURE: - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - - if (sSensor.type == Sensors::Type::MANUAL) { - doc[HA_MIN] = -99; - doc[HA_MAX] = 99; - } - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - - if (sSensor.type == Sensors::Type::MANUAL) { - doc[HA_MIN] = -147; - doc[HA_MAX] = 211; - } - } - break; - - case Sensors::Purpose::DHW_FLOW_RATE: - doc[HA_DEVICE_CLASS] = "volume_flow_rate"; - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_L_MIN; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_GAL_MIN; - } - break; - - case Sensors::Purpose::MODULATION_LEVEL: - case Sensors::Purpose::POWER_FACTOR: - doc[HA_DEVICE_CLASS] = "power_factor"; - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_PERCENT; - break; - - case Sensors::Purpose::POWER: - doc[HA_DEVICE_CLASS] = "power"; - doc[HA_UNIT_OF_MEASUREMENT] = "kW"; - break; - - case Sensors::Purpose::FAN_SPEED: - doc[HA_UNIT_OF_MEASUREMENT] = "RPM"; - break; - - case Sensors::Purpose::CO2: - doc[HA_DEVICE_CLASS] = "carbon_dioxide"; - doc[HA_UNIT_OF_MEASUREMENT] = "ppm"; - break; - - case Sensors::Purpose::PRESSURE: - doc[HA_DEVICE_CLASS] = "pressure"; - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = "bar"; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = "psi"; - } - break; - - case Sensors::Purpose::HUMIDITY: - doc[HA_DEVICE_CLASS] = S_HUMIDITY; - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_PERCENT; - break; - - default: - break; - } - - // set icon - switch (sSensor.purpose) { - case Sensors::Purpose::OUTDOOR_TEMP: - doc[HA_ICON] = "mdi:home-thermometer-outline"; - break; - - case Sensors::Purpose::INDOOR_TEMP: - doc[HA_ICON] = "mdi:home-thermometer"; - break; - - case Sensors::Purpose::HEATING_TEMP: - doc[HA_ICON] = "mdi:radiator"; - break; - - case Sensors::Purpose::HEATING_RETURN_TEMP: - doc[HA_ICON] = "mdi:heating-coil"; - break; - - case Sensors::Purpose::DHW_TEMP: - doc[HA_ICON] = "mdi:faucet"; - break; - - case Sensors::Purpose::DHW_RETURN_TEMP: - doc[HA_ICON] = "mdi:heating-coil"; - break; - - case Sensors::Purpose::EXHAUST_TEMP: - doc[HA_ICON] = "mdi:smoke"; - break; - - case Sensors::Purpose::TEMPERATURE: - doc[HA_ICON] = "mdi:thermometer-lines"; - break; - - case Sensors::Purpose::DHW_FLOW_RATE: - doc[HA_ICON] = "mdi:faucet"; - break; - - case Sensors::Purpose::MODULATION_LEVEL: - doc[HA_ICON] = "mdi:fire-circle"; - break; - - case Sensors::Purpose::POWER_FACTOR: - case Sensors::Purpose::POWER: - doc[HA_ICON] = "mdi:chart-bar"; - break; - - case Sensors::Purpose::FAN_SPEED: - doc[HA_ICON] = "mdi:fan"; - break; - - case Sensors::Purpose::PRESSURE: - doc[HA_ICON] = "mdi:gauge"; - break; - - case Sensors::Purpose::HUMIDITY: - doc[HA_ICON] = "mdi:water-percent"; - break; - - default: - break; - } - - String objId = Sensors::makeObjectId(sSensor.name); - - // state topic - doc[HA_STATE_TOPIC] = this->getDeviceTopic( - "sensors", - objId.c_str() - ); - - // set device class, name, value template for Bluetooth/DHT sensors - // or name & value template for another sensors - if (sSensor.type == Sensors::Type::BLUETOOTH || - sSensor.type == Sensors::Type::DHT11 || sSensor.type == Sensors::Type::DHT22) { - // available state topic - doc[HA_AVAILABILITY][1][HA_TOPIC] = doc[HA_STATE_TOPIC]; - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_SENSOR_CONN, true); - - String sName = sSensor.name; - switch (vType) { - case Sensors::ValueType::TEMPERATURE: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, "temp"); - sName += " temperature"; - - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - } - doc[HA_NAME] = sName; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.temperature|float(0)|round(2) }}"; - break; - - case Sensors::ValueType::HUMIDITY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, S_HUMIDITY); - sName += " humidity"; - - doc[HA_DEVICE_CLASS] = S_HUMIDITY; - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_PERCENT; - doc[HA_NAME] = sName; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.humidity|float(0)|round(2) }}"; - break; - - case Sensors::ValueType::BATTERY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, S_BATTERY); - sName += " battery"; - - doc[HA_DEVICE_CLASS] = S_BATTERY; - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_PERCENT; - doc[HA_NAME] = sName; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.battery|float(0)|round(2) }}"; - break; - - case Sensors::ValueType::RSSI: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, S_RSSI); - sName += " RSSI"; - - doc[HA_DEVICE_CLASS] = "signal_strength"; - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_UNIT_OF_MEASUREMENT] = "dBm"; - doc[HA_NAME] = sName; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.rssi|float(0)|round(2) }}"; - break; - - default: - return false; - } - - } else if (sSensor.type == Sensors::Type::MANUAL) { - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_STEP] = 0.01f; - doc[HA_MODE] = HA_MODE_BOX; - - doc[HA_COMMAND_TOPIC] = this->getDeviceTopic( - "sensors", - objId.c_str(), - "set" - ); - doc[HA_COMMAND_TEMPLATE] = "{\"value\": {{ value }}}"; - - doc[HA_NAME] = sSensor.name; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.value|float(0)|round(2) }}"; - - } else { - // available state topic - doc[HA_AVAILABILITY][1][HA_TOPIC] = doc[HA_STATE_TOPIC]; - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_SENSOR_CONN, true); - - doc[HA_NAME] = sSensor.name; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.value|float(0)|round(2) }}"; - } - - // object id's - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix(objId.c_str()); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix( - sSensor.type == Sensors::Type::MANUAL - ? HA_ENTITY_NUMBER - : HA_ENTITY_SENSOR, - objId.c_str() - ); - - const String& configTopic = this->makeConfigTopic( - sSensor.type == Sensors::Type::MANUAL ? HA_ENTITY_NUMBER : HA_ENTITY_SENSOR, - objId.c_str() - ); - objId.clear(); - - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_STATE_CLASS] = HA_STATE_CLASS_MEASUREMENT; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(configTopic.c_str(), doc); - } - - bool deleteDynamicSensor(Sensors::Settings& sSensor, Sensors::ValueType vType = Sensors::ValueType::PRIMARY) { - String objId; - - if (sSensor.type == Sensors::Type::BLUETOOTH) { - switch (vType) { - case Sensors::ValueType::TEMPERATURE: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, "temp"); - break; - - case Sensors::ValueType::HUMIDITY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, S_HUMIDITY); - break; - - case Sensors::ValueType::BATTERY: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, S_BATTERY); - break; - - case Sensors::ValueType::RSSI: - Sensors::makeObjectIdWithSuffix(objId, sSensor.name, S_RSSI); - break; - - default: - return false; - } - - } else { - Sensors::makeObjectId(objId, sSensor.name); - } - - const String& configTopic = this->makeConfigTopic( - sSensor.type == Sensors::Type::MANUAL ? HA_ENTITY_NUMBER : HA_ENTITY_SENSOR, - objId.c_str() - ); - objId.clear(); - - return this->publish(configTopic.c_str()); - } - - bool publishConnectionDynamicSensor(Sensors::Settings& sSensor, bool enabledByDefault = true) { - JsonDocument doc; - String objId = Sensors::makeObjectIdWithSuffix(sSensor.name, "connected"); - - // object id's - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix(objId.c_str()); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, objId.c_str()); - - // state topic - doc[HA_STATE_TOPIC] = this->getDeviceTopic( - "sensors", - Sensors::makeObjectId(sSensor.name).c_str() - ); - - // sensor name - { - String sName = sSensor.name; - sName.trim(); - sName += " connected"; - - doc[HA_NAME] = sName; - } - - const String& configTopic = this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, objId.c_str()); - objId.clear(); - - - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "connectivity"; - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.connected, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(configTopic.c_str(), doc); - } - - bool deleteConnectionDynamicSensor(Sensors::Settings& sSensor) { - const String& configTopic = this->makeConfigTopic( - HA_ENTITY_BINARY_SENSOR, - Sensors::makeObjectIdWithSuffix(sSensor.name, "connected").c_str() - ); - - return this->publish(configTopic.c_str()); - } - - bool publishSignalQualityDynamicSensor(Sensors::Settings& sSensor, bool enabledByDefault = true) { - JsonDocument doc; - String objId = Sensors::makeObjectIdWithSuffix(sSensor.name, "signal_quality"); - - // object id's - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix(objId.c_str()); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SENSOR, objId.c_str()); - - // state topic - doc[HA_STATE_TOPIC] = this->getDeviceTopic( - "sensors", - Sensors::makeObjectId(sSensor.name).c_str() - ); - - // sensor name - { - String sName = sSensor.name; - sName.trim(); - sName += " signal quality"; - - doc[HA_NAME] = sName; - } - - const String& configTopic = this->makeConfigTopic(HA_ENTITY_SENSOR, objId.c_str()); - objId.clear(); - - - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - //doc[HA_DEVICE_CLASS] = "signal_strength"; - doc[HA_STATE_CLASS] = HA_STATE_CLASS_MEASUREMENT; - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_PERCENT; - doc[HA_ICON] = "mdi:signal"; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.signalQuality|float(0)|round(0) }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(configTopic.c_str(), doc); - } - - bool deleteSignalQualityDynamicSensor(Sensors::Settings& sSensor) { - const String& configTopic = this->makeConfigTopic( - HA_ENTITY_SENSOR, - Sensors::makeObjectIdWithSuffix(sSensor.name, "signal_quality").c_str() - ); - - return this->publish(configTopic.c_str()); - } - - - bool publishSwitchHeatingTurbo(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating_turbo"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SWITCH, "heating_turbo"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "Turbo heating"; - doc[HA_ICON] = "mdi:rocket-launch-outline"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_STATE_ON] = true; - doc[HA_STATE_OFF] = false; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.heating.turbo }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_PAYLOAD_ON] = "{\"heating\": {\"turbo\" : true}}"; - doc[HA_PAYLOAD_OFF] = "{\"heating\": {\"turbo\" : false}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SWITCH, "heating_turbo").c_str(), doc); - } - - bool publishSwitchHeatingHysteresis(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating_hysteresis"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SWITCH, "heating_hysteresis"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "Use heating hysteresis"; - doc[HA_ICON] = "mdi:altimeter"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_STATE_ON] = true; - doc[HA_STATE_OFF] = false; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.heating.hysteresis.enabled }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_PAYLOAD_ON] = "{\"heating\": {\"hysteresis\" : {\"enabled\" : true}}}"; - doc[HA_PAYLOAD_OFF] = "{\"heating\": {\"hysteresis\" : {\"enabled\" : false}}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SWITCH, "heating_hysteresis").c_str(), doc); - } - - bool publishInputHeatingHysteresis(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating_hysteresis"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "heating_hysteresis"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - } - - doc[HA_NAME] = "Heating hysteresis"; - doc[HA_ICON] = "mdi:altimeter"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.heating.hysteresis.value|float(0)|round(2) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"heating\": {\"hysteresis\" : {\"value\" : {{ value }}}}}"; - doc[HA_MIN] = 0; - doc[HA_MAX] = 15; - doc[HA_STEP] = 0.01f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "heating_hysteresis").c_str(), doc); - } - - bool publishInputHeatingTurboFactor(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating_turbo_factor"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "heating_turbo_factor"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = "power_factor"; - doc[HA_NAME] = "Heating turbo factor"; - doc[HA_ICON] = "mdi:multiplication-box"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.heating.turboFactor|float(0)|round(2) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"heating\": {\"turboFactor\" : {{ value }}}}"; - doc[HA_MIN] = 1.5; - doc[HA_MAX] = 10; - doc[HA_STEP] = 0.01f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "heating_turbo_factor").c_str(), doc); - } - - bool publishInputHeatingMinTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating_min_temp"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "heating_min_temp"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - doc[HA_MIN] = 0; - doc[HA_MAX] = 99; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - doc[HA_MIN] = 32; - doc[HA_MAX] = 211; - } - - doc[HA_NAME] = "Heating min temp"; - doc[HA_ICON] = "mdi:thermometer-chevron-down"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.heating.minTemp|float(0)|round(1) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"heating\": {\"minTemp\" : {{ value }}}}"; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "heating_min_temp").c_str(), doc); - } - - bool publishInputHeatingMaxTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating_max_temp"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "heating_max_temp"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - doc[HA_MIN] = 1; - doc[HA_MAX] = 100; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - doc[HA_MIN] = 33; - doc[HA_MAX] = 212; - } - - doc[HA_NAME] = "Heating max temp"; - doc[HA_ICON] = "mdi:thermometer-chevron-up"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.heating.maxTemp|float(0)|round(1) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"heating\": {\"maxTemp\" : {{ value }}}}"; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "heating_max_temp").c_str(), doc); - } - - - bool publishInputDhwMinTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("dhw_min_temp"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "dhw_min_temp"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - doc[HA_MIN] = 0; - doc[HA_MAX] = 99; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - doc[HA_MIN] = 32; - doc[HA_MAX] = 211; - } - - doc[HA_NAME] = "DHW min temp"; - doc[HA_ICON] = "mdi:thermometer-chevron-down"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.dhw.minTemp|float(0)|round(1) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"dhw\": {\"minTemp\" : {{ value }}}}"; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "dhw_min_temp").c_str(), doc); - } - - bool publishInputDhwMaxTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("dhw_max_temp"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "dhw_max_temp"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - doc[HA_MIN] = 1; - doc[HA_MAX] = 100; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - doc[HA_MIN] = 33; - doc[HA_MAX] = 212; - } - - doc[HA_NAME] = "DHW max temp"; - doc[HA_ICON] = "mdi:thermometer-chevron-up"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.dhw.maxTemp|float(0)|round(1) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"dhw\": {\"maxTemp\" : {{ value }}}}"; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "dhw_max_temp").c_str(), doc); - } - - - bool publishSwitchPid(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SWITCH, "pid"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "PID"; - doc[HA_ICON] = "mdi:chart-bar-stacked"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_STATE_ON] = true; - doc[HA_STATE_OFF] = false; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.enabled }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_PAYLOAD_ON] = "{\"pid\": {\"enabled\" : true}}"; - doc[HA_PAYLOAD_OFF] = "{\"pid\": {\"enabled\" : false}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SWITCH, "pid").c_str(), doc); - } - - bool publishInputPidFactorP(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid_p"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "pid_p"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "PID factor P"; - doc[HA_ICON] = "mdi:alpha-p-circle-outline"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.p_factor|float(0)|round(3) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"pid\": {\"p_factor\" : {{ value }}}}"; - doc[HA_MIN] = 0.1f; - doc[HA_MAX] = 1000; - doc[HA_STEP] = 0.1f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "pid_p_factor").c_str(), doc); - } - - bool publishInputPidFactorI(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid_i"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "pid_i"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "PID factor I"; - doc[HA_ICON] = "mdi:alpha-i-circle-outline"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.i_factor|float(0)|round(4) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"pid\": {\"i_factor\" : {{ value }}}}"; - doc[HA_MIN] = 0; - doc[HA_MAX] = 100; - doc[HA_STEP] = 0.001f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "pid_i_factor").c_str(), doc); - } - - bool publishInputPidFactorD(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid_d"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "pid_d"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "PID factor D"; - doc[HA_ICON] = "mdi:alpha-d-circle-outline"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.d_factor|float(0)|round(3) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"pid\": {\"d_factor\" : {{ value }}}}"; - doc[HA_MIN] = 0; - doc[HA_MAX] = 100000; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "pid_d_factor").c_str(), doc); - } - - bool publishInputPidDt(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid_dt"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "pid_dt"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = "duration"; - doc[HA_UNIT_OF_MEASUREMENT] = "s"; - doc[HA_NAME] = "PID DT"; - doc[HA_ICON] = "mdi:timer-cog-outline"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.dt|int(0) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"pid\": {\"dt\" : {{ value }}}}"; - doc[HA_MIN] = 30; - doc[HA_MAX] = 1800; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "pid_dt").c_str(), doc); - } - - bool publishInputPidMinTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid_min_temp"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "pid_min_temp"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - doc[HA_MIN] = -99; - doc[HA_MAX] = 99; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - doc[HA_MIN] = -146; - doc[HA_MAX] = 211; - } - - doc[HA_NAME] = "PID min temp"; - doc[HA_ICON] = "mdi:thermometer-chevron-down"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.minTemp|float(0)|round(1) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"pid\": {\"minTemp\" : {{ value }}}}"; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "pid_min_temp").c_str(), doc); - } - - bool publishInputPidMaxTemp(UnitSystem unit = UnitSystem::METRIC, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("pid_max_temp"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "pid_max_temp"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - - if (unit == UnitSystem::METRIC) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_C; - doc[HA_MIN] = 1; - doc[HA_MAX] = 100; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_UNIT_OF_MEASUREMENT] = HA_UNIT_OF_MEASUREMENT_F; - doc[HA_MIN] = 1; - doc[HA_MAX] = 212; - } - - doc[HA_NAME] = "PID max temp"; - doc[HA_ICON] = "mdi:thermometer-chevron-up"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.pid.maxTemp|float(0)|round(1) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"pid\": {\"maxTemp\" : {{ value }}}}"; - doc[HA_STEP] = 1; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "pid_max_temp").c_str(), doc); - } - - - bool publishSwitchEquitherm(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("equitherm"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SWITCH, "equitherm"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "Equitherm"; - doc[HA_ICON] = "mdi:sun-snowflake-variant"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_STATE_ON] = true; - doc[HA_STATE_OFF] = false; - doc[HA_VALUE_TEMPLATE] = "{{ value_json.equitherm.enabled }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_PAYLOAD_ON] = "{\"equitherm\": {\"enabled\" : true}}"; - doc[HA_PAYLOAD_OFF] = "{\"equitherm\": {\"enabled\" : false}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SWITCH, "equitherm").c_str(), doc); - } - - bool publishInputEquithermSlope(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("equitherm_slope"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "equitherm_slope"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "Equitherm slope"; - doc[HA_ICON] = "mdi:slope-uphill"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.equitherm.slope|float(0)|round(3) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"equitherm\": {\"slope\" : {{ value }}}}"; - doc[HA_MIN] = 0.001f; - doc[HA_MAX] = 10; - doc[HA_STEP] = 0.001f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "equitherm_slope").c_str(), doc); - } - - bool publishInputEquithermExponent(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("equitherm_exponent"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "equitherm_exponent"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "Equitherm exponent"; - doc[HA_ICON] = "mdi:exponent"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.equitherm.exponent|float(0)|round(3) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"equitherm\": {\"exponent\" : {{ value }}}}"; - doc[HA_MIN] = 0.1; - doc[HA_MAX] = 2; - doc[HA_STEP] = 0.001f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "equitherm_exponent").c_str(), doc); - } - - bool publishInputEquithermShift(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("equitherm_shift"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "equitherm_shift"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_TEMPERATURE; - doc[HA_NAME] = "Equitherm shift"; - doc[HA_ICON] = "mdi:chart-areaspline"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.equitherm.shift|float(0)|round(2) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"equitherm\": {\"shift\" : {{ value }}}}"; - doc[HA_MIN] = -15; - doc[HA_MAX] = 15; - doc[HA_STEP] = 0.01f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "equitherm_shift").c_str(), doc); - } - - bool publishInputEquithermTargetDiffFactor(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->settingsTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = "{{ iif(value_json.pid.enabled, 'offline', 'online') }}"; - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("equitherm_target_diff_factor"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_NUMBER, "equitherm_target_diff_factor"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_NAME] = "Equitherm target diff factor"; - doc[HA_ICON] = "mdi:chart-timeline-variant-shimmer"; - doc[HA_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.equitherm.targetDiffFactor|float(0)|round(3) }}"; - doc[HA_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"equitherm\": {\"targetDiffFactor\" : {{ value }}}}"; - doc[HA_MIN] = 0; - doc[HA_MAX] = 10; - doc[HA_STEP] = 0.001f; - doc[HA_MODE] = HA_MODE_BOX; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "equitherm_target_diff_factor").c_str(), doc); - } - - - bool publishStatusState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("status"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "status"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "problem"; - doc[HA_NAME] = "Status"; - doc[HA_ICON] = "mdi:list-status"; - doc[HA_STATE_TOPIC] = this->statusTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value == 'online', 'OFF', 'ON') }}"; - doc[HA_EXPIRE_AFTER] = 60; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "status").c_str(), doc); - } - - bool publishEmergencyState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("emergency"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "emergency"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "problem"; - doc[HA_NAME] = "Emergency"; - doc[HA_ICON] = "mdi:alert-rhombus-outline"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.master.emergency.state, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "emergency").c_str(), doc); - } - - bool publishOpenthermConnectedState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("ot_status"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "ot_status"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "connectivity"; - doc[HA_NAME] = "Opentherm status"; - doc[HA_ICON] = "mdi:list-status"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.connected, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "ot_status").c_str(), doc); - } - - bool publishHeatingState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_OT_CONN, true); - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "heating"); - doc[HA_DEVICE_CLASS] = "running"; - doc[HA_NAME] = "Heating"; - doc[HA_ICON] = "mdi:radiator"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.heating.active, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "heating").c_str(), doc); - } - - bool publishDhwState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_OT_CONN, true); - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("dhw"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "dhw"); - doc[HA_DEVICE_CLASS] = "running"; - doc[HA_NAME] = "DHW"; - doc[HA_ICON] = "mdi:faucet"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.dhw.active, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "dhw").c_str(), doc); - } - - bool publishFlameState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_OT_CONN, true); - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("flame"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "flame"); - doc[HA_DEVICE_CLASS] = "running"; - doc[HA_NAME] = "Flame"; - doc[HA_ICON] = "mdi:gas-burner"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.flame, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "flame").c_str(), doc); - } - - bool publishFaultState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_OT_CONN, true); - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("fault"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "fault"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "problem"; - doc[HA_NAME] = "Fault"; - doc[HA_ICON] = "mdi:alert-remove-outline"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.fault.active, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "fault").c_str(), doc); - } - - bool publishDiagState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = JsonString(AVAILABILITY_OT_CONN, true); - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix(HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, HA_ENTITY_CATEGORY_DIAGNOSTIC); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "problem"; - doc[HA_NAME] = "Diagnostic"; - doc[HA_ICON] = "mdi:account-wrench"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.diag.active, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, HA_ENTITY_CATEGORY_DIAGNOSTIC).c_str(), doc); - } - - bool publishExternalPumpState(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("ext_pump"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BINARY_SENSOR, "ext_pump"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "running"; - doc[HA_NAME] = "External pump"; - doc[HA_ICON] = "mdi:pump"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ iif(value_json.master.externalPump.state, 'ON', 'OFF') }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "ext_pump").c_str(), doc); - } - - bool publishFaultCode(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.connected and value_json.slave.fault.active, 'online', 'offline') }}"; - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("fault_code"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SENSOR, "fault_code"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_NAME] = "Fault code"; - doc[HA_ICON] = "mdi:cog-box"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ \"%02d (0x%02X)\"|format(value_json.slave.fault.code, value_json.slave.fault.code) }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SENSOR, "fault_code").c_str(), doc); - } - - bool publishDiagCode(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.connected and value_json.slave.fault.active or value_json.slave.diag.active, 'online', 'offline') }}"; - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("diagnostic_code"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SENSOR, "diagnostic_code"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_NAME] = "Diagnostic code"; - doc[HA_ICON] = "mdi:information-box"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ \"%02d (0x%02X)\"|format(value_json.slave.diag.code, value_json.slave.diag.code) }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SENSOR, "diagnostic_code").c_str(), doc); - } - - bool publishNetworkRssi(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix(S_RSSI); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SENSOR, S_RSSI); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "signal_strength"; - doc[HA_STATE_CLASS] = HA_STATE_CLASS_MEASUREMENT; - doc[HA_UNIT_OF_MEASUREMENT] = "dBm"; - doc[HA_NAME] = "RSSI"; - doc[HA_ICON] = "mdi:signal"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.master.network.rssi|float(0)|round(1) }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SENSOR, S_RSSI).c_str(), doc); - } - - bool publishUptime(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("uptime"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_SENSOR, "uptime"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_DIAGNOSTIC; - doc[HA_DEVICE_CLASS] = "duration"; - doc[HA_STATE_CLASS] = "total_increasing"; - doc[HA_UNIT_OF_MEASUREMENT] = "s"; - doc[HA_NAME] = "Uptime"; - doc[HA_ICON] = "mdi:clock-start"; - doc[HA_STATE_TOPIC] = this->stateTopic.c_str(); - doc[HA_VALUE_TEMPLATE] = "{{ value_json.master.uptime|int(0) }}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_SENSOR, "uptime").c_str(), doc); - } - - - bool publishClimateHeating(UnitSystem unit = UnitSystem::METRIC, uint8_t minTemp = 20, uint8_t maxTemp = 90, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("heating"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_CLIMATE, "heating"); - doc[HA_NAME] = "Heating"; - doc[HA_ICON] = "mdi:radiator"; - - doc[HA_CURRENT_TEMPERATURE_TOPIC] = this->stateTopic.c_str(); - doc[HA_CURRENT_TEMPERATURE_TEMPLATE] = "{{ iif(value_json.master.heating.indoorTempControl, value_json.master.heating.indoorTemp, value_json.master.heating.currentTemp, 0)|float(0)|round(2) }}"; - - doc[HA_TEMPERATURE_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_TEMPERATURE_COMMAND_TEMPLATE] = "{\"heating\": {\"target\" : {{ value }}}}"; - - doc[HA_TEMPERATURE_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_TEMPERATURE_STATE_TEMPLATE] = "{{ value_json.heating.target|float(0)|round(1) }}"; - - if (unit == UnitSystem::METRIC) { - doc[HA_TEMPERATURE_UNIT] = "C"; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_TEMPERATURE_UNIT] = "F"; - } - - doc[HA_MODE_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_MODE_COMMAND_TEMPLATE] = "{% if value == 'heat' %}{\"heating\": {\"enabled\" : true}}" - "{% elif value == 'off' %}{\"heating\": {\"enabled\" : false}}{% endif %}"; - doc[HA_MODE_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_MODE_STATE_TEMPLATE] = "{{ iif(value_json.heating.enabled, 'heat', 'off') }}"; - doc[HA_MODES][0] = "off"; - doc[HA_MODES][1] = "heat"; - - doc[HA_ACTION_TOPIC] = this->stateTopic.c_str(); - doc[HA_ACTION_TEMPLATE] = "{{ iif(value_json.slave.heating.active, 'heating', 'idle') }}"; - - doc[HA_PRESET_MODE_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_PRESET_MODE_COMMAND_TEMPLATE] = "{% if value == 'boost' %}{\"heating\": {\"turbo\" : true}}" - "{% elif value == 'none' %}{\"heating\": {\"turbo\" : false}}{% endif %}"; - doc[HA_PRESET_MODE_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_PRESET_MODE_VALUE_TEMPLATE] = "{{ iif(value_json.heating.turbo, 'boost', 'none') }}"; - doc[HA_PRESET_MODES][0] = "boost"; - - doc[HA_MIN_TEMP] = minTemp; - doc[HA_MAX_TEMP] = maxTemp; - doc[HA_TEMP_STEP] = 0.1f; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_CLIMATE, "heating", '_').c_str(), doc); - } - - bool publishClimateDhw(UnitSystem unit = UnitSystem::METRIC, uint8_t minTemp = 40, uint8_t maxTemp = 60, bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("dhw"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_CLIMATE, "dhw"); - doc[HA_NAME] = "DHW"; - doc[HA_ICON] = "mdi:faucet"; - - doc[HA_CURRENT_TEMPERATURE_TOPIC] = this->stateTopic.c_str(); - doc[HA_CURRENT_TEMPERATURE_TEMPLATE] = "{{ value_json.master.dhw.currentTemp|float(0)|round(1) }}"; - - doc[HA_TEMPERATURE_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_TEMPERATURE_COMMAND_TEMPLATE] = "{\"dhw\": {\"target\" : {{ value|int(0) }}}}"; - - doc[HA_TEMPERATURE_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_TEMPERATURE_STATE_TEMPLATE] = "{{ value_json.dhw.target|float(0)|round(1) }}"; - - if (unit == UnitSystem::METRIC) { - doc[HA_TEMPERATURE_UNIT] = "C"; - - } else if (unit == UnitSystem::IMPERIAL) { - doc[HA_TEMPERATURE_UNIT] = "F"; - } - - doc[HA_MODE_COMMAND_TOPIC] = this->setSettingsTopic.c_str(); - doc[HA_MODE_COMMAND_TEMPLATE] = "{% if value == 'heat' %}{\"dhw\": {\"enabled\" : true}}" - "{% elif value == 'off' %}{\"dhw\": {\"enabled\" : false}}{% endif %}"; - doc[HA_MODE_STATE_TOPIC] = this->settingsTopic.c_str(); - doc[HA_MODE_STATE_TEMPLATE] = "{{ iif(value_json.dhw.enabled, 'heat', 'off') }}"; - doc[HA_MODES][0] = "off"; - doc[HA_MODES][1] = "heat"; - - doc[HA_ACTION_TOPIC] = this->stateTopic.c_str(); - doc[HA_ACTION_TEMPLATE] = "{{ iif(value_json.slave.dhw.active, 'heating', 'idle') }}"; - - doc[HA_MIN_TEMP] = minTemp; - doc[HA_MAX_TEMP] = maxTemp; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_CLIMATE, "dhw", '_').c_str(), doc); - } - - - bool publishRestartButton(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix(S_RESTART); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BUTTON, S_RESTART); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_RESTART; - doc[HA_NAME] = "Restart"; - doc[HA_COMMAND_TOPIC] = this->setStateTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"actions\": {\"restart\": true}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BUTTON, S_RESTART).c_str(), doc); - } - - bool publishResetFaultButton(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.fault.active, 'online', 'offline') }}"; - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("reset_fault"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BUTTON, "reset_fault"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_RESTART; - doc[HA_NAME] = "Reset fault"; - doc[HA_COMMAND_TOPIC] = this->setStateTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"actions\": {\"resetFault\": true}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BUTTON, "reset_fault").c_str(), doc); - } - - bool publishResetDiagButton(bool enabledByDefault = true) { - JsonDocument doc; - doc[HA_AVAILABILITY][0][HA_TOPIC] = this->statusTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_TOPIC] = this->stateTopic.c_str(); - doc[HA_AVAILABILITY][1][HA_VALUE_TEMPLATE] = "{{ iif(value_json.slave.diag.active, 'online', 'offline') }}"; - doc[HA_AVAILABILITY_MODE] = "all"; - doc[HA_ENABLED_BY_DEFAULT] = enabledByDefault; - doc[HA_UNIQUE_ID] = this->getUniqueIdWithPrefix("reset_diagnostic"); - doc[HA_DEFAULT_ENTITY_ID] = this->getEntityIdWithPrefix(HA_ENTITY_BUTTON, "reset_diagnostic"); - doc[HA_ENTITY_CATEGORY] = HA_ENTITY_CATEGORY_CONFIG; - doc[HA_DEVICE_CLASS] = S_RESTART; - doc[HA_NAME] = "Reset diagnostic"; - doc[HA_COMMAND_TOPIC] = this->setStateTopic.c_str(); - doc[HA_COMMAND_TEMPLATE] = "{\"actions\": {\"resetDiagnostic\": true}}"; - doc[HA_EXPIRE_AFTER] = this->expireAfter; - doc.shrinkToFit(); - - return this->publish(this->makeConfigTopic(HA_ENTITY_BUTTON, "reset_diagnostic").c_str(), doc); - } - - - template - bool deleteEntities(CT category) { - return this->publish(this->makeConfigTopic(category).c_str()); - } - - bool deleteSwitchDhw() { - return this->publish(this->makeConfigTopic(HA_ENTITY_SWITCH, "dhw").c_str()); - } - - bool deleteInputDhwMinTemp() { - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "dhw_min_temp").c_str()); - } - - bool deleteInputDhwMaxTemp() { - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "dhw_max_temp").c_str()); - } - - bool deleteDhwState() { - return this->publish(this->makeConfigTopic(HA_ENTITY_BINARY_SENSOR, "dhw").c_str()); - } - - bool deleteInputDhwTarget() { - return this->publish(this->makeConfigTopic(HA_ENTITY_NUMBER, "dhw_target").c_str()); - } - - bool deleteClimateDhw() { - return this->publish(this->makeConfigTopic(HA_ENTITY_CLIMATE, "dhw", '_').c_str()); - } - - protected: - unsigned short expireAfter = 300u; - String statusTopic, stateTopic, setStateTopic, settingsTopic, setSettingsTopic; -}; - -const char HaHelper::AVAILABILITY_OT_CONN[] = "{{ iif(value_json.slave.connected, 'online', 'offline') }}"; -const char HaHelper::AVAILABILITY_SENSOR_CONN[] = "{{ iif(value_json.connected, 'online', 'offline') }}"; diff --git a/src/MainTask.h b/src/MainTask.h deleted file mode 100644 index e1a1cf4..0000000 --- a/src/MainTask.h +++ /dev/null @@ -1,705 +0,0 @@ -#include - -using namespace NetworkUtils; - -extern NetworkMgr* network; -extern MqttTask* tMqtt; -extern OpenThermTask* tOt; -extern FileData fsNetworkSettings, fsSettings, fsSensorsSettings; - - -class MainTask : public Task { -public: - explicit MainTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) { - this->blinker = new Blinker(); - - network->setDelayCallback([this](unsigned int time) { - this->delay(time); - })->setYieldCallback([this]() { - this->yield(); - }); - } - - ~MainTask() { - delete this->blinker; - } - -protected: - enum class PumpStartReason {NONE, HEATING, ANTISTUCK}; - - Blinker* blinker = nullptr; - unsigned long miscRunned = 0; - unsigned long lastHeapInfo = 0; - unsigned int minFreeHeap = 0; - unsigned int minMaxFreeBlockHeap = 0; - bool restartSignalReceived = false; - unsigned long restartSignalReceivedTime = 0; - bool heatingEnabled = false; - unsigned long heatingDisabledTime = 0; - PumpStartReason extPumpStartReason = PumpStartReason::NONE; - unsigned long externalPumpStartTime = 0; - bool ntpStarted = false; - bool emergencyDetected = false; - unsigned long emergencyFlipTime = 0; - - const char* getTaskName() override { - return "Main"; - } - - uint32_t getTaskStackSize() override { - return 6000; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 3; - } - - void setup() {} - - void loop() { - network->loop(); - - if (fsNetworkSettings.tick() == FD_WRITE) { - Log.sinfoln(L_NETWORK_SETTINGS, "Updated"); - } - - if (fsSettings.tick() == FD_WRITE) { - Log.sinfoln(L_SETTINGS, "Updated"); - } - - if (fsSensorsSettings.tick() == FD_WRITE) { - Log.sinfoln(L_SENSORS_SETTINGS, "Updated"); - } - - if (vars.actions.restart) { - this->restartSignalReceivedTime = millis(); - this->restartSignalReceived = true; - vars.actions.restart = false; - - Log.sinfoln(L_MAIN, "Received restart signal"); - } - - if (!vars.states.restarting && this->restartSignalReceived && millis() - this->restartSignalReceivedTime > 5000) { - vars.states.restarting = true; - - // save settings - fsSettings.updateNow(); - - // save sensors settings - fsSensorsSettings.updateNow(); - - // force save network settings - if (fsNetworkSettings.updateNow() == FD_FILE_ERR && LittleFS.begin()) { - fsNetworkSettings.write(); - } - - Log.sinfoln(L_MAIN, "Restart scheduled in 10 sec."); - } - - vars.mqtt.connected = tMqtt->isConnected(); - vars.network.connected = network->isConnected(); - vars.network.rssi = network->isConnected() ? WiFi.RSSI() : 0; - - if (settings.system.logLevel >= TinyLoggerLevel::SILENT && settings.system.logLevel <= TinyLoggerLevel::VERBOSE) { - if (Log.getLevel() != settings.system.logLevel) { - Log.setLevel(static_cast(settings.system.logLevel)); - } - } - - if (network->isConnected()) { - if (!this->ntpStarted) { - if (strlen(settings.system.ntp.server)) { - configTime(0, 0, settings.system.ntp.server); - setenv("TZ", settings.system.ntp.timezone, 1); - tzset(); - - this->ntpStarted = true; - } - } - - if (settings.mqtt.enabled && !tMqtt->isEnabled()) { - tMqtt->enable(); - - } else if (!settings.mqtt.enabled && tMqtt->isEnabled()) { - tMqtt->disable(); - } - - } else { - if (this->ntpStarted) { - this->ntpStarted = false; - } - - if (tMqtt->isEnabled()) { - tMqtt->disable(); - } - - Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false); - } - - this->yield(); - if (this->misc()) { - this->yield(); - } - this->ledStatus(); - - - // anti memory leak - while (Serial.available() > 0) { - Serial.read(); - } - - // heap info - this->heap(); - } - - bool misc() { - if (millis() - this->miscRunned < 1000) { - return false; - } - - // restart if required - if (this->restartSignalReceived && millis() - this->restartSignalReceivedTime > 15000) { - this->restartSignalReceived = false; - - ESP.restart(); - } - - this->heating(); - this->emergency(); - this->cascadeControl(); - this->externalPump(); - this->miscRunned = millis(); - - return true; - } - - void heap() { - unsigned int freeHeap = getFreeHeap(); - unsigned int maxFreeBlockHeap = getMaxFreeBlockHeap(); - - // critical heap - if (!vars.states.restarting && (freeHeap < 2048 || maxFreeBlockHeap < 2048)) { - this->restartSignalReceivedTime = millis(); - this->restartSignalReceived = true; - vars.states.restarting = true; - } - - if (settings.system.logLevel < TinyLoggerLevel::VERBOSE) { - return; - } - - size_t minFreeHeap = getFreeHeap(true); - size_t minFreeHeapDiff = 0; - if (minFreeHeap < this->minFreeHeap || this->minFreeHeap == 0) { - minFreeHeapDiff = this->minFreeHeap - minFreeHeap; - this->minFreeHeap = minFreeHeap; - } - - size_t minMaxFreeBlockHeap = getMaxFreeBlockHeap(true); - size_t minMaxFreeBlockHeapDiff = 0; - if (minMaxFreeBlockHeap < this->minMaxFreeBlockHeap || this->minMaxFreeBlockHeap == 0) { - minMaxFreeBlockHeapDiff = this->minMaxFreeBlockHeap - minMaxFreeBlockHeap; - this->minMaxFreeBlockHeap = minMaxFreeBlockHeap; - } - - if (millis() - this->lastHeapInfo > 20000 || minFreeHeapDiff > 0 || minMaxFreeBlockHeapDiff > 0) { - Log.sverboseln( - L_MAIN, - "Free heap size: %u of %u bytes (min: %u, diff: %u), max free block: %u (min: %u, diff: %u, frag: %hhu%%)", - freeHeap, getTotalHeap(), this->minFreeHeap, minFreeHeapDiff, maxFreeBlockHeap, this->minMaxFreeBlockHeap, minMaxFreeBlockHeapDiff, getHeapFrag() - ); - this->lastHeapInfo = millis(); - } - } - - void heating() { - // freeze protection - { - float lowTemp = 255.0f; - uint8_t availableSensors = 0; - - if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { - auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::INDOOR_TEMP, Sensors::ValueType::PRIMARY, settings.heating.indoorTempAvgType); - if (value < lowTemp) { - lowTemp = value; - } - - availableSensors++; - } - - if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_TEMP)) { - auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_TEMP, Sensors::ValueType::PRIMARY); - if (value < lowTemp) { - lowTemp = value; - } - - availableSensors++; - } - - if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP)) { - auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP, Sensors::ValueType::PRIMARY); - if (value < lowTemp) { - lowTemp = value; - } - - availableSensors++; - } - - if (availableSensors) { - if (vars.master.heating.freezing) { - if (lowTemp - static_cast(settings.heating.freezeProtection.highTemp) + 0.0001f >= 0.0f) { - vars.master.heating.freezing = false; - - Log.sinfoln( - L_MAIN, - "No freezing detected. Current low temp: %.2f, threshold (high): %hhu", - lowTemp, settings.heating.freezeProtection.highTemp - ); - } - - } else { - if (static_cast(settings.heating.freezeProtection.lowTemp) - lowTemp + 0.0001f >= 0.0f) { - vars.master.heating.freezing = true; - - if (!settings.heating.enabled) { - settings.heating.enabled = true; - fsSettings.update(); - } - - Log.sinfoln( - L_MAIN, - "Freezing detected! Current low temp: %.2f, threshold (low): %hhu", - lowTemp, settings.heating.freezeProtection.lowTemp - ); - } - } - - } else if (vars.master.heating.freezing) { - vars.master.heating.freezing = false; - - Log.sinfoln(L_MAIN, "No sensors available, freeze protection unavailable!"); - } - } - } - - void emergency() { - // flags - uint8_t emergencyFlags = 0b00000000; - - // set outdoor sensor flag - if (settings.equitherm.enabled) { - if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP)) { - emergencyFlags |= 0b00000001; - } - } - - // set indoor sensor flags - if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { - if (!settings.equitherm.enabled && settings.pid.enabled) { - emergencyFlags |= 0b00000010; - } - - if (settings.opentherm.options.nativeOTC) { - emergencyFlags |= 0b00000100; - } - } - - // if any flags is true - if ((emergencyFlags & 0b00001111) != 0) { - if (!this->emergencyDetected) { - // flip flag - this->emergencyDetected = true; - this->emergencyFlipTime = millis(); - - } else if (this->emergencyDetected && !vars.emergency.state) { - // enable emergency - if (millis() - this->emergencyFlipTime > (settings.emergency.tresholdTime * 1000)) { - vars.emergency.state = true; - Log.sinfoln(L_MAIN, "Emergency mode enabled (%hhu)", emergencyFlags); - } - } - - } else { - if (this->emergencyDetected) { - // flip flag - this->emergencyDetected = false; - this->emergencyFlipTime = millis(); - - } else if (!this->emergencyDetected && vars.emergency.state) { - // disable emergency - if (millis() - this->emergencyFlipTime > (settings.emergency.tresholdTime * 1000)) { - vars.emergency.state = false; - Log.sinfoln(L_MAIN, "Emergency mode disabled"); - } - } - } - } - - void ledStatus() { - uint8_t errors[4]; - uint8_t errCount = 0; - static uint8_t errPos = 0; - static unsigned long endBlinkTime = 0; - static bool ledOn = false; - static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; - - if (settings.system.statusLedGpio != configuredGpio) { - if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(configuredGpio, LOW); - } - - if (GPIO_IS_VALID(settings.system.statusLedGpio)) { - configuredGpio = settings.system.statusLedGpio; - pinMode(configuredGpio, OUTPUT); - digitalWrite(configuredGpio, LOW); - this->blinker->init(configuredGpio); - - } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - configuredGpio = GPIO_IS_NOT_CONFIGURED; - } - } - - if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { - return; - } - - if (!network->isConnected()) { - errors[errCount++] = 2; - } - - if (!vars.slave.connected) { - errors[errCount++] = 3; - } - - if (vars.slave.fault.active) { - errors[errCount++] = 4; - } - - if (vars.emergency.state) { - errors[errCount++] = 5; - } - - - if (this->blinker->ready()) { - endBlinkTime = millis(); - } - - if (!this->blinker->running() && millis() - endBlinkTime >= 5000) { - if (errCount == 0) { - if (!ledOn) { - digitalWrite(configuredGpio, HIGH); - ledOn = true; - } - - return; - - } else if (ledOn) { - digitalWrite(configuredGpio, LOW); - ledOn = false; - endBlinkTime = millis(); - return; - } - - if (errPos >= errCount) { - errPos = 0; - - // end of error list - this->blinker->blink(10, 50, 50); - - } else { - this->blinker->blink(errors[errPos++], 300, 300); - } - } - - this->blinker->tick(); - } - - void cascadeControl() { - static uint8_t configuredInputGpio = GPIO_IS_NOT_CONFIGURED; - static uint8_t configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; - static bool inputTempValue = false; - static unsigned long inputChangedTs = 0; - static bool outputTempValue = false; - static unsigned long outputChangedTs = 0; - - // input - if (settings.cascadeControl.input.enabled) { - if (settings.cascadeControl.input.gpio != configuredInputGpio) { - if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { - pinMode(configuredInputGpio, OUTPUT); - digitalWrite(configuredInputGpio, LOW); - - Log.sinfoln(L_CASCADE_INPUT, "Deinitialized on GPIO %hhu", configuredInputGpio); - } - - if (GPIO_IS_VALID(settings.cascadeControl.input.gpio)) { - configuredInputGpio = settings.cascadeControl.input.gpio; - pinMode(configuredInputGpio, INPUT); - - Log.sinfoln(L_CASCADE_INPUT, "Initialized on GPIO %hhu", configuredInputGpio); - - } else if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { - configuredInputGpio = GPIO_IS_NOT_CONFIGURED; - - Log.swarningln(L_CASCADE_INPUT, "Failed initialize: GPIO %hhu is not valid!", configuredInputGpio); - } - } - - if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { - bool value; - if (digitalRead(configuredInputGpio) == HIGH) { - value = true ^ settings.cascadeControl.input.invertState; - } else { - value = false ^ settings.cascadeControl.input.invertState; - } - - if (value != vars.cascadeControl.input) { - if (value != inputTempValue) { - inputTempValue = value; - inputChangedTs = millis(); - - } else if (millis() - inputChangedTs >= settings.cascadeControl.input.thresholdTime * 1000u) { - vars.cascadeControl.input = value; - - Log.sinfoln( - L_CASCADE_INPUT, - "State changed to %s", - value ? "TRUE" : "FALSE" - ); - } - - } else if (value != inputTempValue) { - inputTempValue = value; - } - } - } - - if (!settings.cascadeControl.input.enabled || configuredInputGpio == GPIO_IS_NOT_CONFIGURED) { - if (!vars.cascadeControl.input) { - vars.cascadeControl.input = true; - - Log.sinfoln( - L_CASCADE_INPUT, - "Disabled, state changed to %s", - vars.cascadeControl.input ? "TRUE" : "FALSE" - ); - } - } - - - // output - if (settings.cascadeControl.output.enabled) { - if (settings.cascadeControl.output.gpio != configuredOutputGpio) { - if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - pinMode(configuredOutputGpio, OUTPUT); - digitalWrite(configuredOutputGpio, LOW); - - Log.sinfoln(L_CASCADE_OUTPUT, "Deinitialized on GPIO %hhu", configuredOutputGpio); - } - - if (GPIO_IS_VALID(settings.cascadeControl.output.gpio)) { - configuredOutputGpio = settings.cascadeControl.output.gpio; - pinMode(configuredOutputGpio, OUTPUT); - digitalWrite( - configuredOutputGpio, - settings.cascadeControl.output.invertState - ? HIGH - : LOW - ); - - Log.sinfoln(L_CASCADE_OUTPUT, "Initialized on GPIO %hhu", configuredOutputGpio); - - } else if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; - - Log.swarningln(L_CASCADE_OUTPUT, "Failed initialize: GPIO %hhu is not valid!", configuredOutputGpio); - } - } - - if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - bool value = false; - if (settings.cascadeControl.output.onFault && vars.slave.fault.active) { - value = true; - - } else if (settings.cascadeControl.output.onLossConnection && !vars.slave.connected) { - value = true; - - } else if (settings.cascadeControl.output.onEnabledHeating && settings.heating.enabled && vars.cascadeControl.input) { - value = true; - } - - if (value != vars.cascadeControl.output) { - if (value != outputTempValue) { - outputTempValue = value; - outputChangedTs = millis(); - - } else if (millis() - outputChangedTs >= settings.cascadeControl.output.thresholdTime * 1000u) { - vars.cascadeControl.output = value; - - digitalWrite( - configuredOutputGpio, - vars.cascadeControl.output ^ settings.cascadeControl.output.invertState - ? HIGH - : LOW - ); - - Log.sinfoln( - L_CASCADE_OUTPUT, - "State changed to %s", - value ? "TRUE" : "FALSE" - ); - } - - } else if (value != outputTempValue) { - outputTempValue = value; - } - } - } - - if (!settings.cascadeControl.output.enabled || configuredOutputGpio == GPIO_IS_NOT_CONFIGURED) { - if (vars.cascadeControl.output) { - vars.cascadeControl.output = false; - - if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite( - configuredOutputGpio, - vars.cascadeControl.output ^ settings.cascadeControl.output.invertState - ? HIGH - : LOW - ); - } - - Log.sinfoln( - L_CASCADE_OUTPUT, - "Disabled, state changed to %s", - vars.cascadeControl.output ? "TRUE" : "FALSE" - ); - } - } - } - - void externalPump() { - static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; - - if (settings.externalPump.gpio != configuredGpio) { - if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(configuredGpio, LOW); - } - - if (GPIO_IS_VALID(settings.externalPump.gpio)) { - configuredGpio = settings.externalPump.gpio; - pinMode(configuredGpio, OUTPUT); - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { - configuredGpio = GPIO_IS_NOT_CONFIGURED; - } - } - - if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { - if (vars.externalPump.state) { - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(L_EXTPUMP, "Disabled: use = off"); - } - - return; - } - - if (!vars.master.heating.enabled && this->heatingEnabled) { - this->heatingEnabled = false; - this->heatingDisabledTime = millis(); - - } else if (vars.master.heating.enabled && !this->heatingEnabled) { - this->heatingEnabled = true; - } - - if (!settings.externalPump.use) { - if (vars.externalPump.state) { - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(L_EXTPUMP, "Disabled: use = off"); - } - - return; - } - - if (vars.externalPump.state && !this->heatingEnabled) { - if (this->extPumpStartReason == MainTask::PumpStartReason::HEATING && millis() - this->heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) { - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(L_EXTPUMP, "Disabled: expired post circulation time"); - - } else if (this->extPumpStartReason == MainTask::PumpStartReason::ANTISTUCK && millis() - this->externalPumpStartTime >= (settings.externalPump.antiStuckTime * 1000u)) { - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? HIGH - : LOW - ); - - vars.externalPump.state = false; - vars.externalPump.lastEnabledTime = millis(); - - Log.sinfoln(L_EXTPUMP, "Disabled: expired anti stuck time"); - } - - } else if (vars.externalPump.state && this->heatingEnabled && this->extPumpStartReason == MainTask::PumpStartReason::ANTISTUCK) { - this->extPumpStartReason = MainTask::PumpStartReason::HEATING; - - } else if (!vars.externalPump.state && this->heatingEnabled) { - vars.externalPump.state = true; - this->externalPumpStartTime = millis(); - this->extPumpStartReason = MainTask::PumpStartReason::HEATING; - - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? LOW - : HIGH - ); - - Log.sinfoln(L_EXTPUMP, "Enabled: heating on"); - - } else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || millis() - vars.externalPump.lastEnabledTime >= (settings.externalPump.antiStuckInterval * 1000lu))) { - vars.externalPump.state = true; - this->externalPumpStartTime = millis(); - this->extPumpStartReason = MainTask::PumpStartReason::ANTISTUCK; - - digitalWrite( - configuredGpio, - settings.externalPump.invertState - ? LOW - : HIGH - ); - - Log.sinfoln(L_EXTPUMP, "Enabled: anti stuck"); - } - } -}; diff --git a/src/MqttTask.h b/src/MqttTask.h deleted file mode 100644 index 47ff63d..0000000 --- a/src/MqttTask.h +++ /dev/null @@ -1,634 +0,0 @@ -#include -#include -#include -#include -#include "HaHelper.h" - -extern FileData fsSettings; - -class MqttTask : public Task { -public: - explicit MqttTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) { - this->wifiClient = new WiFiClient(); - this->client = new MqttClient(this->wifiClient); - this->writer = new MqttWriter(this->client, 256); - this->haHelper = new HaHelper(); - } - - ~MqttTask() { - delete this->haHelper; - - if (this->client != nullptr) { - if (this->client->connected()) { - this->client->stop(); - - if (this->connected) { - this->onDisconnect(); - this->connected = false; - } - } - - delete this->client; - } - - delete this->writer; - delete this->wifiClient; - } - - void disable() { - this->client->stop(); - - if (this->connected) { - this->onDisconnect(); - this->connected = false; - } - - Task::disable(); - - Log.sinfoln(L_MQTT, "Disabled"); - } - - void enable() { - Task::enable(); - - Log.sinfoln(L_MQTT, "Enabled"); - } - - inline bool isConnected() { - return this->connected; - } - - inline void resetPublishedSettingsTime() { - this->prevPubSettingsTime = 0; - } - - inline void resetPublishedSensorTime(uint8_t sensorId) { - this->prevPubSensorTime[sensorId] = 0; - } - - inline void resetPublishedVarsTime() { - this->prevPubVarsTime = 0; - } - - inline void reconfigureSensor(uint8_t sensorId, Sensors::Settings& prevSettings) { - this->queueReconfigureSensors[sensorId] = prevSettings; - } - -protected: - WiFiClient* wifiClient = nullptr; - MqttClient* client = nullptr; - HaHelper* haHelper = nullptr; - MqttWriter* writer = nullptr; - char configUrl[64] = {}; - UnitSystem currentUnitSystem = UnitSystem::METRIC; - bool currentHomeAssistantDiscovery = false; - std::unordered_map queueReconfigureSensors; - unsigned short readyForSendTime = 30000; - unsigned long lastReconnectTime = 0; - unsigned long connectedTime = 0; - unsigned long disconnectedTime = 0; - unsigned long prevPubVarsTime = 0; - unsigned long prevPubSettingsTime = 0; - std::unordered_map prevPubSensorTime; - bool connected = false; - bool newConnection = false; - - const char* getTaskName() override { - return "Mqtt"; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 2; - } - - inline bool isReadyForSend() { - return millis() - this->connectedTime > this->readyForSendTime; - } - - void setup() { - Log.sinfoln(L_MQTT, "Started"); - - // client settings - this->client->setTxPayloadSize(256); - this->client->setConnectionTimeout(3000); - - this->client->onMessage([this] (void*, size_t length) { - const String& topic = this->client->messageTopic(); - if (!length || length > 2048 || !topic.length()) { - return; - } - - uint8_t payload[length]; - for (size_t i = 0; i < length && this->client->available(); i++) { - payload[i] = this->client->read(); - } - - this->onMessage(topic, payload, length); - }); - - // writer settings - this->writer->setYieldCallback([this] { - this->delay(10); - }); - - this->writer->setPublishEventCallback([this] (const char* topic, size_t written, size_t length, bool result) { - Log.straceln(L_MQTT, "%s publish %u of %u bytes to topic: %s", result ? "Successfully" : "Failed", written, length, topic); - - //this->client->poll(); - this->delay(250); - }); - - // ha helper settings - this->haHelper->setDevicePrefix(settings.mqtt.prefix); - this->haHelper->setDeviceVersion(BUILD_VERSION); - this->haHelper->setDeviceModel(PROJECT_NAME); - this->haHelper->setDeviceName(PROJECT_NAME); - this->haHelper->setWriter(this->writer); - - snprintf(this->configUrl, sizeof(this->configUrl), CONFIG_URL, WiFi.localIP().toString().c_str()); - this->haHelper->setDeviceConfigUrl(this->configUrl); - } - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - if (this->connected && !this->client->connected()) { - this->connected = false; - this->onDisconnect(); - - } else if (!this->connected && millis() - this->lastReconnectTime >= MQTT_RECONNECT_INTERVAL) { - Log.sinfoln(L_MQTT, "Connecting to %s:%u...", settings.mqtt.server, settings.mqtt.port); - - this->haHelper->setDevicePrefix(settings.mqtt.prefix); - this->haHelper->updateCachedTopics(); - - this->client->stop(); - this->client->setKeepAliveInterval(settings.mqtt.interval * 10000); - this->client->setId(networkSettings.hostname); - this->client->setUsernamePassword(settings.mqtt.user, settings.mqtt.password); - this->client->beginWill(this->haHelper->getDeviceTopic("status").c_str(), 7, true, 1); - this->client->print("offline"); - this->client->endWill(); - this->client->connect(settings.mqtt.server, settings.mqtt.port); - this->lastReconnectTime = millis(); - this->yield(); - - } else if (!this->connected && this->client->connected()) { - this->connected = true; - this->onConnect(); - } - - if (!this->connected) { - return; - } - - this->client->poll(); - - // delay for publish data - if (!this->isReadyForSend()) { - return; - } - - // publish variables and status - if (this->newConnection || millis() - this->prevPubVarsTime > (settings.mqtt.interval * 1000u)) { - this->writer->publish(this->haHelper->getDeviceTopic("status").c_str(), "online", false); - this->publishVariables(this->haHelper->getDeviceTopic("state").c_str()); - this->prevPubVarsTime = millis(); - } - - // publish settings - if (this->newConnection || millis() - this->prevPubSettingsTime > (settings.mqtt.interval * 10000u)) { - this->publishSettings(this->haHelper->getDeviceTopic("settings").c_str()); - this->prevPubSettingsTime = millis(); - } - - // publish sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - auto& rSensor = Sensors::results[sensorId]; - bool needUpdate = false; - if (millis() - this->prevPubSensorTime[sensorId] > ((this->haHelper->getExpireAfter() - 10) * 1000u)) { - needUpdate = true; - - } else if (rSensor.activityTime >= this->prevPubSensorTime[sensorId]) { - auto estimated = rSensor.activityTime - this->prevPubSensorTime[sensorId]; - needUpdate = estimated > 1000u; - } - - if (this->newConnection || needUpdate) { - this->publishSensor(sensorId); - this->prevPubSensorTime[sensorId] = millis(); - } - } - - // publish ha entities if not published - if (settings.mqtt.homeAssistantDiscovery) { - if (this->newConnection || !this->currentHomeAssistantDiscovery || this->currentUnitSystem != settings.system.unitSystem) { - this->publishHaEntities(); - this->publishNonStaticHaEntities(true); - this->currentHomeAssistantDiscovery = true; - this->currentUnitSystem = settings.system.unitSystem; - - } else { - // publish non static ha entities - this->publishNonStaticHaEntities(); - } - - // rebuilding ha configs - for (auto& [sensorId, prevSettings] : this->queueReconfigureSensors) { - Log.sinfoln(L_MQTT_HA, "Rebuilding config for sensor #%hhu '%s'", sensorId, prevSettings.name); - - // delete old config - if (strlen(prevSettings.name) && prevSettings.enabled) { - switch (prevSettings.type) { - case Sensors::Type::BLUETOOTH: - this->haHelper->deleteConnectionDynamicSensor(prevSettings); - this->haHelper->deleteSignalQualityDynamicSensor(prevSettings); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::TEMPERATURE); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::HUMIDITY); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::BATTERY); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::RSSI); - break; - - case Sensors::Type::DHT11: - case Sensors::Type::DHT22: - this->haHelper->deleteConnectionDynamicSensor(prevSettings); - this->haHelper->deleteSignalQualityDynamicSensor(prevSettings); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::TEMPERATURE); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::HUMIDITY); - break; - - case Sensors::Type::DALLAS_TEMP: - this->haHelper->deleteConnectionDynamicSensor(prevSettings); - this->haHelper->deleteSignalQualityDynamicSensor(prevSettings); - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::TEMPERATURE); - break; - - default: - this->haHelper->deleteDynamicSensor(prevSettings, Sensors::ValueType::PRIMARY); - } - } - - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - // make new config - auto& sSettings = Sensors::settings[sensorId]; - switch (sSettings.type) { - case Sensors::Type::BLUETOOTH: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::HUMIDITY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::BATTERY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::RSSI, settings.system.unitSystem, false); - break; - - case Sensors::Type::DHT11: - case Sensors::Type::DHT22: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::HUMIDITY, settings.system.unitSystem); - break; - - case Sensors::Type::DALLAS_TEMP: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - break; - - default: - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::PRIMARY, settings.system.unitSystem); - } - } - - } else if (this->currentHomeAssistantDiscovery) { - this->currentHomeAssistantDiscovery = false; - } - - // reconfigure manual sensors - for (auto& [sensorId, prevSettings] : this->queueReconfigureSensors) { - // unsubscribe from old topic - if (strlen(prevSettings.name) && prevSettings.enabled) { - if (prevSettings.type == Sensors::Type::MANUAL) { - this->client->unsubscribe( - this->haHelper->getDeviceTopic( - "sensors", - Sensors::makeObjectId(prevSettings.name).c_str(), - "set" - ).c_str() - ); - } - } - - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - // subscribe to new topic - auto& sSettings = Sensors::settings[sensorId]; - if (sSettings.type == Sensors::Type::MANUAL) { - this->client->subscribe( - this->haHelper->getDeviceTopic( - "sensors", - Sensors::makeObjectId(sSettings.name).c_str(), - "set" - ).c_str() - ); - } - } - - // clear queue - this->queueReconfigureSensors.clear(); - - if (this->newConnection) { - this->newConnection = false; - } - } - - void onConnect() { - this->connectedTime = millis(); - this->newConnection = true; - unsigned long downtime = (millis() - this->disconnectedTime) / 1000; - Log.sinfoln(L_MQTT, "Connected (downtime: %u s.)", downtime); - - this->client->subscribe(this->haHelper->getDeviceTopic("settings/set").c_str()); - this->client->subscribe(this->haHelper->getDeviceTopic("state/set").c_str()); - - // subscribe to manual sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - auto& sSettings = Sensors::settings[sensorId]; - if (sSettings.type != Sensors::Type::MANUAL) { - continue; - } - - this->client->subscribe( - this->haHelper->getDeviceTopic( - "sensors", - Sensors::makeObjectId(sSettings.name).c_str(), - "set" - ).c_str() - ); - } - } - - void onDisconnect() { - this->disconnectedTime = millis(); - - unsigned long uptime = (millis() - this->connectedTime) / 1000; - Log.swarningln(L_MQTT, "Disconnected (reason: %d uptime: %lu s.)", this->client->connectError(), uptime); - } - - void onMessage(const String& topic, uint8_t* payload, size_t length) { - if (!length) { - return; - } - - if (settings.system.logLevel >= TinyLoggerLevel::TRACE) { - Log.strace(L_MQTT_MSG, "Topic: %s\r\n> ", topic.c_str()); - if (Log.lock()) { - for (size_t i = 0; i < length; i++) { - if (payload[i] == 0) { - break; - } else if (payload[i] == 13) { - continue; - } else if (payload[i] == 10) { - Log.print("\r\n> "); - } else { - Log.print(static_cast(payload[i])); - } - } - Log.print("\r\n\n"); - Log.flush(); - Log.unlock(); - } - } - - JsonDocument doc; - DeserializationError dErr = deserializeJson(doc, payload, length); - if (dErr != DeserializationError::Ok) { - Log.swarningln(L_MQTT_MSG, "Error on deserialization: %s", dErr.c_str()); - return; - - } else if (doc.isNull() || !doc.size()) { - Log.swarningln(L_MQTT_MSG, "Not valid json"); - return; - } - doc.shrinkToFit(); - - // delete topic - this->writer->publish(topic.c_str(), nullptr, 0, true); - - if (this->haHelper->getDeviceTopic("state/set").equals(topic)) { - if (jsonToVars(doc, vars)) { - this->resetPublishedVarsTime(); - } - - } else if (this->haHelper->getDeviceTopic("settings/set").equals(topic)) { - if (safeJsonToSettings(doc, settings)) { - this->resetPublishedSettingsTime(); - fsSettings.update(); - } - - } else { - const String& sensorsTopic = this->haHelper->getDeviceTopic("sensors/"); - auto stLength = sensorsTopic.length(); - - if (topic.startsWith(sensorsTopic) && topic.endsWith("/set")) { - if (topic.length() > stLength + 4) { - const String& name = topic.substring(stLength, topic.indexOf('/', stLength)); - int16_t id = Sensors::getIdByObjectId(name.c_str()); - - if (id == -1) { - return; - } - - if (jsonToSensorResult(id, doc)) { - this->resetPublishedSensorTime(id); - } - } - } - } - } - - void publishHaEntities() { - // heating - this->haHelper->publishSwitchHeatingTurbo(false); - this->haHelper->publishSwitchHeatingHysteresis(); - this->haHelper->publishInputHeatingHysteresis(settings.system.unitSystem); - this->haHelper->publishInputHeatingTurboFactor(false); - this->haHelper->publishInputHeatingMinTemp(settings.system.unitSystem); - this->haHelper->publishInputHeatingMaxTemp(settings.system.unitSystem); - - // pid - this->haHelper->publishSwitchPid(); - this->haHelper->publishInputPidFactorP(false); - this->haHelper->publishInputPidFactorI(false); - this->haHelper->publishInputPidFactorD(false); - this->haHelper->publishInputPidDt(false); - this->haHelper->publishInputPidMinTemp(settings.system.unitSystem, false); - this->haHelper->publishInputPidMaxTemp(settings.system.unitSystem, false); - - // equitherm - this->haHelper->publishSwitchEquitherm(); - this->haHelper->publishInputEquithermSlope(false); - this->haHelper->publishInputEquithermExponent(false); - this->haHelper->publishInputEquithermShift(false); - this->haHelper->publishInputEquithermTargetDiffFactor(false); - - // states - this->haHelper->publishStatusState(); - this->haHelper->publishEmergencyState(); - this->haHelper->publishOpenthermConnectedState(); - this->haHelper->publishHeatingState(); - this->haHelper->publishFlameState(); - this->haHelper->publishFaultState(); - this->haHelper->publishDiagState(); - this->haHelper->publishExternalPumpState(false); - - // sensors - this->haHelper->publishFaultCode(); - this->haHelper->publishDiagCode(); - this->haHelper->publishNetworkRssi(false); - this->haHelper->publishUptime(false); - - // buttons - this->haHelper->publishRestartButton(false); - this->haHelper->publishResetFaultButton(); - this->haHelper->publishResetDiagButton(); - - // dynamic sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (!Sensors::hasEnabledAndValid(sensorId)) { - continue; - } - - auto& sSettings = Sensors::settings[sensorId]; - switch (sSettings.type) { - case Sensors::Type::BLUETOOTH: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::HUMIDITY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::BATTERY, settings.system.unitSystem); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::RSSI, settings.system.unitSystem, false); - break; - - case Sensors::Type::DALLAS_TEMP: - this->haHelper->publishConnectionDynamicSensor(sSettings); - this->haHelper->publishSignalQualityDynamicSensor(sSettings, false); - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::TEMPERATURE, settings.system.unitSystem); - break; - - default: - this->haHelper->publishDynamicSensor(sSettings, Sensors::ValueType::PRIMARY, settings.system.unitSystem); - } - } - } - - bool publishNonStaticHaEntities(bool force = false) { - static uint8_t _heatingMinTemp, _heatingMaxTemp, _dhwMinTemp, _dhwMaxTemp = 0; - static bool _indoorTempControl, _dhwSupport = false; - - bool published = false; - if (force || _dhwSupport != settings.opentherm.options.dhwSupport) { - _dhwSupport = settings.opentherm.options.dhwSupport; - - if (_dhwSupport) { - this->haHelper->publishInputDhwMinTemp(settings.system.unitSystem); - this->haHelper->publishInputDhwMaxTemp(settings.system.unitSystem); - this->haHelper->publishDhwState(); - - } else { - this->haHelper->deleteSwitchDhw(); - this->haHelper->deleteInputDhwMinTemp(); - this->haHelper->deleteInputDhwMaxTemp(); - this->haHelper->deleteDhwState(); - this->haHelper->deleteInputDhwTarget(); - this->haHelper->deleteClimateDhw(); - } - - published = true; - } - - if (force || _indoorTempControl != vars.master.heating.indoorTempControl || _heatingMinTemp != vars.master.heating.minTemp || _heatingMaxTemp != vars.master.heating.maxTemp) { - _heatingMinTemp = vars.master.heating.minTemp; - _heatingMaxTemp = vars.master.heating.maxTemp; - _indoorTempControl = vars.master.heating.indoorTempControl; - - this->haHelper->publishClimateHeating( - settings.system.unitSystem, - vars.master.heating.minTemp, - vars.master.heating.maxTemp - ); - - published = true; - } - - if (_dhwSupport && (force || _dhwMinTemp != settings.dhw.minTemp || _dhwMaxTemp != settings.dhw.maxTemp)) { - _dhwMinTemp = settings.dhw.minTemp; - _dhwMaxTemp = settings.dhw.maxTemp; - - this->haHelper->publishClimateDhw(settings.system.unitSystem, settings.dhw.minTemp, settings.dhw.maxTemp); - - published = true; - } - - return published; - } - - bool publishSettings(const char* topic) { - JsonDocument doc; - safeSettingsToJson(settings, doc); - doc.shrinkToFit(); - - return this->writer->publish(topic, doc, true); - } - - bool publishSensor(uint8_t sensorId) { - auto& sSettings = Sensors::settings[sensorId]; - - if (!Sensors::isValidSensorId(sensorId)) { - return false; - - } else if (!strlen(sSettings.name)) { - return false; - } - - JsonDocument doc; - sensorResultToJson(sensorId, doc); - doc.shrinkToFit(); - - return this->writer->publish( - this->haHelper->getDeviceTopic( - "sensors", - Sensors::makeObjectId(sSettings.name).c_str() - ).c_str(), - doc, - true - ); - } - - bool publishVariables(const char* topic) { - JsonDocument doc; - varsToJson(vars, doc); - doc.shrinkToFit(); - - return this->writer->publish(topic, doc, true); - } -}; diff --git a/src/OpenThermTask.h b/src/OpenThermTask.h deleted file mode 100644 index 32e0efb..0000000 --- a/src/OpenThermTask.h +++ /dev/null @@ -1,2673 +0,0 @@ -#include -extern FileData fsSettings; - -class OpenThermTask : public Task { -public: - explicit OpenThermTask(bool _enabled = false, unsigned long _interval = 0) : Task(_enabled, _interval) {} - - ~OpenThermTask() { - delete this->instance; - } - -protected: - const unsigned short readyTime = 60000u; - const unsigned int resetBusInterval = 120000u; - const unsigned short heatingSetTempInterval = 60000u; - const unsigned short dhwSetTempInterval = 60000u; - const unsigned short ch2SetTempInterval = 60000u; - const unsigned int initializingInterval = 3600000u; - - CustomOpenTherm* instance = nullptr; - unsigned long instanceCreatedTime = 0; - uint8_t instanceInGpio = 0; - uint8_t instanceOutGpio = 0; - bool initialized = false; - unsigned long connectedTime = 0; - unsigned long disconnectedTime = 0; - unsigned long resetBusTime = 0; - unsigned long initializedTime = 0; - unsigned long lastSuccessResponse = 0; - unsigned long prevUpdateNonEssentialVars = 0; - unsigned long heatingSetTempTime = 0; - unsigned long dhwSetTempTime = 0; - unsigned long ch2SetTempTime = 0; - unsigned long roomSetTempTime = 0; - unsigned long roomSetTempCh2Time = 0; - uint8_t configuredRxLedGpio = GPIO_IS_NOT_CONFIGURED; - - const char* getTaskName() override { - return "OpenTherm"; - } - - uint32_t getTaskStackSize() override { - return 7500; - } - - BaseType_t getTaskCore() override { - return 0; - } - - int getTaskPriority() override { - return 5; - } - - void setup() { - // Convert defaults at start - if (settings.system.unitSystem != UnitSystem::METRIC) { - vars.slave.heating.minTemp = convertTemp(vars.slave.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem); - vars.slave.heating.maxTemp = convertTemp(vars.slave.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); - vars.slave.dhw.minTemp = convertTemp(vars.slave.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem); - vars.slave.dhw.maxTemp = convertTemp(vars.slave.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); - } - - // delete instance - if (this->instance != nullptr) { - delete this->instance; - this->instance = nullptr; - Log.sinfoln(L_OT, "Stopped"); - } - - if (!GPIO_IS_VALID(settings.opentherm.inGpio) || !GPIO_IS_VALID(settings.opentherm.outGpio)) { - Log.swarningln( - L_OT, - "Not started. GPIO IN: %hhu or GPIO OUT: %hhu is not valid", - settings.opentherm.inGpio, - settings.opentherm.outGpio - ); - return; - } - - #ifdef OT_BYPASS_RELAY_GPIO - pinMode(OT_BYPASS_RELAY_GPIO, OUTPUT); - digitalWrite(OT_BYPASS_RELAY_GPIO, true); - #endif - - // create instance - this->instance = new CustomOpenTherm(settings.opentherm.inGpio, settings.opentherm.outGpio); - - // flags - this->instanceCreatedTime = millis(); - this->instanceInGpio = settings.opentherm.inGpio; - this->instanceOutGpio = settings.opentherm.outGpio; - this->resetBusTime = millis(); - this->initialized = false; - this->heatingSetTempTime = 0; - this->dhwSetTempTime = 0; - this->ch2SetTempTime = 0; - this->roomSetTempTime = 0; - this->roomSetTempCh2Time = 0; - - Log.sinfoln(L_OT, "Started. GPIO IN: %hhu, GPIO OUT: %hhu", settings.opentherm.inGpio, settings.opentherm.outGpio); - - this->instance->setAfterSendRequestCallback([this](unsigned long request, unsigned long response, OpenThermResponseStatus status, uint8_t attempt) { - Log.sverboseln( - L_OT, - "ID: %4d Request: %8lx Response: %8lx Msg type: %s Attempt: %2d Status: %s", - CustomOpenTherm::getDataID(request), - request, - response, - CustomOpenTherm::getResponseMessageTypeString(response), - attempt, - CustomOpenTherm::statusToString(status) - ); - - if (status == OpenThermResponseStatus::SUCCESS) { - this->lastSuccessResponse = millis(); - - if (this->configuredRxLedGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(this->configuredRxLedGpio, HIGH); - delayMicroseconds(2000); - digitalWrite(this->configuredRxLedGpio, LOW); - } - } - }); - - this->instance->setDelayCallback([this](unsigned int time) { - this->delay(time); - }); - } - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - if (this->instanceInGpio != settings.opentherm.inGpio || this->instanceOutGpio != settings.opentherm.outGpio) { - this->setup(); - - } else if (vars.master.memberId != settings.opentherm.memberId || vars.master.flags != settings.opentherm.flags) { - this->initialized = false; - vars.master.memberId = settings.opentherm.memberId; - vars.master.flags = settings.opentherm.flags; - vars.master.protocolVersion = 2.2f; - vars.master.appVersion = 0x3F; - vars.master.type = 0x01; - - } else if (millis() - this->initializedTime > this->initializingInterval) { - this->initialized = false; - } - - if (this->instance == nullptr) { - this->delay(5000); - return; - - } else if (this->instance->status == OpenThermStatus::NOT_INITIALIZED) { - if (!this->instance->begin()) { - Log.swarningln(L_OT, "Failed begin"); - - this->delay(5000); - return; - } - } - - // RX LED GPIO setup - if (settings.opentherm.rxLedGpio != this->configuredRxLedGpio) { - if (this->configuredRxLedGpio != GPIO_IS_NOT_CONFIGURED) { - digitalWrite(this->configuredRxLedGpio, LOW); - } - - if (GPIO_IS_VALID(settings.opentherm.rxLedGpio)) { - this->configuredRxLedGpio = settings.opentherm.rxLedGpio; - pinMode(this->configuredRxLedGpio, OUTPUT); - digitalWrite(this->configuredRxLedGpio, LOW); - - } else if (this->configuredRxLedGpio != GPIO_IS_NOT_CONFIGURED) { - this->configuredRxLedGpio = GPIO_IS_NOT_CONFIGURED; - } - } - - // Heating settings - vars.master.heating.enabled = this->isReady() - && settings.heating.enabled - && (vars.master.heating.freezing || (vars.cascadeControl.input && !vars.master.heating.blocking)) - && !vars.master.heating.overheat; - - // DHW settings - vars.master.dhw.enabled = this->isReady() - && settings.opentherm.options.dhwSupport - && settings.dhw.enabled - && !vars.master.dhw.overheat; - vars.master.dhw.targetTemp = settings.dhw.target; - - // CH2 settings - vars.master.ch2.enabled = settings.opentherm.options.ch2AlwaysEnabled - || (settings.opentherm.options.heatingToCh2 && vars.master.heating.enabled) - || (settings.opentherm.options.dhwToCh2 && vars.master.dhw.enabled); - - if (settings.opentherm.options.heatingToCh2) { - vars.master.ch2.targetTemp = !settings.opentherm.options.nativeOTC - ? vars.master.heating.setpointTemp - : vars.master.heating.targetTemp; - - } else if (settings.opentherm.options.dhwToCh2) { - vars.master.ch2.targetTemp = vars.master.dhw.targetTemp; - } - - // Set boiler status LB - // Some boilers require this, although this is against protocol - uint8_t statusLb = 0; - - // Immergas fix - // https://arduino.ru/forum/programmirovanie/termostat-opentherm-na-esp8266?page=15#comment-649392 - if (settings.opentherm.options.immergasFix) { - statusLb = 0xCA; - } - - // Mode flags follow the channel request, before applying its disabling action. - // Summer/winter mode - bool summerWinterMode = settings.opentherm.options.summerWinterMode; - if (settings.opentherm.options.heatingStateToSummerWinterMode) { - summerWinterMode = vars.master.heating.enabled == summerWinterMode; - } - - // DHW blocking - bool dhwBlocking = settings.opentherm.options.dhwBlocking; - if (settings.opentherm.options.dhwStateAsDhwBlocking) { - dhwBlocking = vars.master.dhw.enabled == dhwBlocking; - } - - unsigned long response = this->instance->setBoilerStatus( - this->getSlaveChannelEnabled(vars.master.heating.enabled, settings.opentherm.heatingDisablingAction), - settings.opentherm.options.dhwSupport && this->getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction), - settings.opentherm.options.coolingSupport, - settings.opentherm.options.nativeOTC, - this->getSlaveChannelEnabled(vars.master.ch2.enabled, settings.opentherm.ch2DisablingAction), - summerWinterMode, - dhwBlocking, - statusLb - ); - - if (!CustomOpenTherm::isValidResponse(response) || !CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Status)) { - Log.swarningln( - L_OT, - "Failed receive boiler status: %s", - CustomOpenTherm::statusToString(this->instance->getLastResponseStatus()) - ); - - } else { - vars.slave.heating.active = CustomOpenTherm::isCentralHeatingActive(response); - vars.slave.dhw.active = settings.opentherm.options.dhwSupport ? CustomOpenTherm::isHotWaterActive(response) : false; - vars.slave.flame = CustomOpenTherm::isFlameOn(response); - vars.slave.cooling.active = CustomOpenTherm::isCoolingActive(response); - vars.slave.ch2.active = CustomOpenTherm::isCh2Active(response); - vars.slave.fault.active = CustomOpenTherm::isFault(response); - - if (!settings.opentherm.options.ignoreDiagState) { - vars.slave.diag.active = CustomOpenTherm::isDiagnostic(response); - - } else if (vars.slave.diag.active) { - vars.slave.diag.active = false; - } - - Log.snoticeln( - L_OT, "Received boiler status. Heating: %hhu; DHW: %hhu; flame: %hhu; cooling: %hhu; channel 2: %hhu; fault: %hhu; diag: %hhu", - vars.slave.heating.active, vars.slave.dhw.active, - vars.slave.flame, vars.slave.cooling.active, vars.slave.ch2.active, vars.slave.fault.active, vars.slave.diag.active - ); - } - - // 5 request retries - // 1000ms maximum response waiting time - // 100ms delay between requests - // +15% - // 5 * (1000 + 100) * 1.15 = 6325 ms - if (!vars.slave.connected && millis() - this->lastSuccessResponse < 6325) { - Log.sinfoln( - L_OT, - "Connected, downtime: %lu s.", - (millis() - this->disconnectedTime) / 1000 - ); - - this->connectedTime = millis(); - vars.slave.connected = true; - - } else if (vars.slave.connected && millis() - this->lastSuccessResponse > 6325) { - Log.swarningln( - L_OT, - "Disconnected, uptime: %lu s.", - (millis() - this->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); - - this->initialized = false; - this->disconnectedTime = millis(); - vars.slave.connected = false; - } - - // 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() - this->disconnectedTime > this->resetBusInterval) { - if (millis() - this->resetBusTime > this->resetBusInterval) { - Log.sinfoln(L_OT, "Reset bus..."); - - this->instance->end(); - this->instance->status = OpenThermStatus::NOT_INITIALIZED; - - digitalWrite(this->instanceOutGpio, LOW); - this->resetBusTime = millis(); - this->delay(5000); - } - } - - return; - } - - if (!this->initialized) { - Log.sinfoln(L_OT, "Initializing..."); - this->initialized = true; - this->initializedTime = millis(); - this->initialize(); - } - - if (vars.master.heating.enabled != vars.slave.heating.enabled) { - this->prevUpdateNonEssentialVars = 0; - vars.slave.heating.enabled = vars.master.heating.enabled; - Log.sinfoln(L_OT_HEATING, vars.master.heating.enabled ? "Enabled" : "Disabled"); - } - - if (vars.master.dhw.enabled != vars.slave.dhw.enabled) { - this->prevUpdateNonEssentialVars = 0; - vars.slave.dhw.enabled = vars.master.dhw.enabled; - Log.sinfoln(L_OT_DHW, vars.master.dhw.enabled ? "Enabled" : "Disabled"); - } - - // These parameters will be updated every minute - if (millis() - this->prevUpdateNonEssentialVars > 60000) { - // Set date & time - if (settings.opentherm.options.setDateAndTime) { - struct tm ti; - - if (getLocalTime(&ti)) { - if (this->setYear(&ti)) { - Log.sinfoln(L_OT, "Year of date set successfully"); - - } else { - Log.sinfoln(L_OT, "Failed set year of date"); - } - - if (this->setDayAndMonth(&ti)) { - Log.sinfoln(L_OT, "Day and month of date set successfully"); - - } else { - Log.sinfoln(L_OT, "Failed set day and month of date"); - } - - if (this->setTime(&ti)) { - Log.sinfoln(L_OT, "Time set successfully"); - - } else { - Log.sinfoln(L_OT, "Failed set time"); - } - } - } - - // Get min modulation level & max power - if (this->updateMinModulationLevel()) { - Log.snoticeln( - L_OT, "Received min modulation: %hhu%%, max power: %.2f kW", - vars.slave.modulation.min, vars.slave.power.max - ); - - if (settings.heating.maxModulation < vars.slave.modulation.min) { - settings.heating.maxModulation = vars.slave.modulation.min; - fsSettings.update(); - - Log.swarningln( - L_SETTINGS_HEATING, "Updated min modulation: %hhu%%", - settings.heating.maxModulation - ); - } - - if (settings.dhw.maxModulation < vars.slave.modulation.min) { - settings.dhw.maxModulation = vars.slave.modulation.min; - fsSettings.update(); - - Log.swarningln( - L_SETTINGS_DHW, "Updated min modulation: %hhu%%", - settings.dhw.maxModulation - ); - } - - if (fabsf(settings.opentherm.maxPower) < 0.1f && vars.slave.power.max > 0.1f) { - settings.opentherm.maxPower = vars.slave.power.max; - settings.opentherm.minPower = vars.slave.power.min; - - fsSettings.update(); - Log.swarningln( - L_SETTINGS_OT, "Updated power, min: %.2f kW, max: %.2f kW", - settings.opentherm.minPower, settings.opentherm.maxPower - ); - } - - } else { - Log.swarningln(L_OT, "Failed receive min modulation and max power"); - } - - - // Get DHW min/max temp (if necessary) - if (settings.opentherm.options.dhwSupport && settings.opentherm.options.getMinMaxTemp) { - if (this->updateMinMaxDhwTemp()) { - uint8_t convertedMinTemp = convertTemp( - vars.slave.dhw.minTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - uint8_t convertedMaxTemp = convertTemp( - vars.slave.dhw.maxTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_DHW, "Received min temp: %hhu (converted: %hhu), max temp: %hhu (converted: %hhu)", - vars.slave.dhw.minTemp, convertedMinTemp, vars.slave.dhw.maxTemp, convertedMaxTemp - ); - - if (settings.dhw.minTemp < convertedMinTemp) { - settings.dhw.minTemp = convertedMinTemp; - fsSettings.update(); - - Log.swarningln(L_SETTINGS_DHW, "Updated min temp: %hhu", settings.dhw.minTemp); - } - - if (settings.dhw.maxTemp > convertedMaxTemp) { - settings.dhw.maxTemp = convertedMaxTemp; - fsSettings.update(); - - Log.swarningln(L_SETTINGS_DHW, "Updated max temp: %hhu", settings.dhw.maxTemp); - } - - } else { - Log.swarningln(L_OT_DHW, "Failed receive min/max temp"); - } - } - - if (settings.dhw.minTemp >= settings.dhw.maxTemp) { - settings.dhw.minTemp = convertTemp(DEFAULT_DHW_MIN_TEMP, UnitSystem::METRIC, settings.system.unitSystem); - settings.dhw.maxTemp = convertTemp(DEFAULT_DHW_MAX_TEMP, UnitSystem::METRIC, settings.system.unitSystem); - fsSettings.update(); - } - - - // Get heating min/max temp - if (settings.opentherm.options.getMinMaxTemp) { - if (this->updateMinMaxHeatingTemp()) { - uint8_t convertedMinTemp = convertTemp( - vars.slave.heating.minTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - uint8_t convertedMaxTemp = convertTemp( - vars.slave.heating.maxTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_HEATING, "Received min temp: %hhu (converted: %hhu), max temp: %hhu (converted: %hhu)", - vars.slave.heating.minTemp, convertedMinTemp, vars.slave.heating.maxTemp, convertedMaxTemp - ); - - if (settings.heating.minTemp < convertedMinTemp) { - settings.heating.minTemp = convertedMinTemp; - fsSettings.update(); - - Log.swarningln(L_SETTINGS_HEATING, "Updated min temp: %hhu", settings.heating.minTemp); - } - - if (settings.heating.maxTemp > convertedMaxTemp) { - settings.heating.maxTemp = convertedMaxTemp; - fsSettings.update(); - - Log.swarningln(L_SETTINGS_HEATING, "Updated max temp: %hhu", settings.heating.maxTemp); - } - - } else { - Log.swarningln(L_OT_HEATING, "Failed receive min/max temp"); - } - } - - if (settings.heating.minTemp >= settings.heating.maxTemp) { - settings.heating.minTemp = convertTemp(DEFAULT_HEATING_MIN_TEMP, UnitSystem::METRIC, settings.system.unitSystem);; - settings.heating.maxTemp = convertTemp(DEFAULT_HEATING_MAX_TEMP, UnitSystem::METRIC, settings.system.unitSystem);; - fsSettings.update(); - } - - // Get fault code (if necessary) - if (vars.slave.fault.active) { - if (this->updateFaultCode()) { - Log.snoticeln( - L_OT, "Received fault code: %hhu (0x%02X)", - vars.slave.fault.code, vars.slave.fault.code - ); - - } else { - Log.swarningln(L_OT, "Failed receive fault code"); - } - - } else if (vars.slave.fault.code != 0) { - vars.slave.fault.code = 0; - } - - // Get diagnostic code (if necessary) - if (vars.slave.fault.active || vars.slave.diag.active) { - if (this->updateDiagCode()) { - Log.snoticeln( - L_OT, "Received diag code: %hu (0x%02X)", - vars.slave.diag.code, vars.slave.diag.code - ); - - } else { - Log.swarningln(L_OT, "Failed receive diag code"); - } - - } else if (vars.slave.diag.code != 0) { - vars.slave.diag.code = 0; - } - - // Update burner starts - if (Sensors::getAmountByType(Sensors::Type::OT_BURNER_STARTS, true)) { - if (this->updateBurnerStarts()) { - Log.snoticeln(L_OT, "Received burner starts: %hu", vars.slave.stats.burnerStarts); - - Sensors::setValueByType( - Sensors::Type::OT_BURNER_STARTS, vars.slave.stats.burnerStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive burner starts"); - } - } - - // Update DHW burner starts - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_STARTS, true)) { - if (this->updateDhwBurnerStarts()) { - Log.snoticeln(L_OT, "Received DHW burner starts: %hu", vars.slave.stats.dhwBurnerStarts); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_BURNER_STARTS, vars.slave.stats.dhwBurnerStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive DHW burner starts"); - } - } - - // Update heating pump starts - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_STARTS, true)) { - if (this->updateHeatingPumpStarts()) { - Log.snoticeln(L_OT, "Received heating pump starts: %hu", vars.slave.stats.heatingPumpStarts); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_PUMP_STARTS, vars.slave.stats.heatingPumpStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive heating pump starts"); - } - } - - // Update DHW pump starts - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_STARTS, true)) { - if (this->updateDhwPumpStarts()) { - Log.snoticeln(L_OT, "Received DHW pump starts: %hu", vars.slave.stats.dhwPumpStarts); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_PUMP_STARTS, vars.slave.stats.dhwPumpStarts, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive DHW pump starts"); - } - } - - // Update burner hours - if (Sensors::getAmountByType(Sensors::Type::OT_BURNER_HOURS, true)) { - if (this->updateBurnerHours()) { - Log.snoticeln(L_OT, "Received burner hours: %hu", vars.slave.stats.burnerHours); - - Sensors::setValueByType( - Sensors::Type::OT_BURNER_HOURS, vars.slave.stats.burnerHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive burner hours"); - } - } - - // Update DHW burner hours - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_HOURS, true)) { - if (this->updateDhwBurnerHours()) { - Log.snoticeln(L_OT, "Received DHW burner hours: %hu", vars.slave.stats.dhwBurnerHours); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_BURNER_HOURS, vars.slave.stats.dhwBurnerHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive DHW burner hours"); - } - } - - // Update heating pump hours - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_HOURS, true)) { - if (this->updateHeatingPumpHours()) { - Log.snoticeln(L_OT, "Received heating pump hours: %hu", vars.slave.stats.heatingPumpHours); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_PUMP_HOURS, vars.slave.stats.heatingPumpHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive heating pump hours"); - } - } - - // Update DHW pump hours - if (Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_HOURS, true)) { - if (this->updateDhwPumpHours()) { - Log.snoticeln(L_OT, "Received DHW pump hours: %hu", vars.slave.stats.dhwPumpHours); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_PUMP_HOURS, vars.slave.stats.dhwPumpHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive DHW pump hours"); - } - } - - // Update cooling hours - if (Sensors::getAmountByType(Sensors::Type::OT_COOLING_HOURS, true)) { - if (this->updateCoolingHours()) { - Log.snoticeln(L_OT, "Received cooling hours: %hu", vars.slave.stats.coolingHours); - - Sensors::setValueByType( - Sensors::Type::OT_COOLING_HOURS, vars.slave.stats.coolingHours, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive cooling hours"); - } - } - - // Auto fault reset - if (settings.opentherm.options.autoFaultReset && vars.slave.fault.active && !vars.actions.resetFault) { - vars.actions.resetFault = true; - } - - // Auto diag reset - if (settings.opentherm.options.autoDiagReset && vars.slave.diag.active && !vars.actions.resetDiagnostic) { - vars.actions.resetDiagnostic = true; - } - - this->prevUpdateNonEssentialVars = millis(); - } - - // Set cooling setpoint = heating max modulation - if (settings.opentherm.options.coolingSupport) { - if (this->setCoolingSetpoint(settings.heating.maxModulation)) { - Log.snoticeln( - L_OT, "Set cooling setpoint: %hhu%% (response: %hhu%%)", - settings.heating.maxModulation, vars.slave.cooling.setpoint - ); - - } else { - Log.swarningln( - L_OT, "Failed set cooling setpoint: %hhu%% (response: %hhu%%)", - settings.heating.maxModulation, vars.slave.cooling.setpoint - ); - } - } - - // Set max modulation level - uint8_t targetMaxModulation = vars.slave.modulation.max; - if (vars.slave.heating.active) { - targetMaxModulation = settings.heating.maxModulation; - - } else if (vars.slave.dhw.active) { - targetMaxModulation = settings.dhw.maxModulation; - - } else { - // This fixes the inability to enable channels if - // the maximum modulation level has become zero for some reason. - - if (vars.master.heating.enabled && targetMaxModulation < settings.heating.maxModulation) { - targetMaxModulation = settings.heating.maxModulation; - } - - if (vars.master.dhw.enabled && targetMaxModulation < settings.dhw.maxModulation) { - targetMaxModulation = settings.dhw.maxModulation; - } - } - - if (this->setMaxModulationLevel(targetMaxModulation)) { - Log.snoticeln( - L_OT, "Set max modulation: %hhu%% (response: %hhu%%)", - targetMaxModulation, vars.slave.modulation.max - ); - - } else { - Log.swarningln( - L_OT, "Failed set max modulation: %hhu%% (response: %hhu%%)", - targetMaxModulation, vars.slave.modulation.max - ); - } - - // Update modulation level - if ( - Sensors::getAmountByType(Sensors::Type::OT_MODULATION_LEVEL, true) || - Sensors::getAmountByType(Sensors::Type::OT_CURRENT_POWER, true) - ) { - if (vars.slave.flame) { - if (this->updateModulationLevel()) { - float power = 0.0f; - if (settings.opentherm.maxPower > 0.1f) { - power += settings.opentherm.minPower; - - if (vars.slave.modulation.current > 0) { - power += ( - settings.opentherm.maxPower - settings.opentherm.minPower - ) / 100.0f * vars.slave.modulation.current; - } - } - vars.slave.power.current = power; - - Log.snoticeln( - L_OT, "Received modulation level: %hhu%%, power: %.2f of %.2f kW (min: %.2f kW)", - vars.slave.modulation.current, vars.slave.power.current, - settings.opentherm.maxPower, settings.opentherm.minPower - ); - - // Modulation level sensors - Sensors::setValueByType( - Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, - Sensors::ValueType::PRIMARY, true, true - ); - - // Power sensors - Sensors::setValueByType( - Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive modulation level"); - } - - } else { - vars.slave.modulation.current = 0; - vars.slave.power.current = 0.0f; - - // Modulation level sensors - Sensors::setValueByType( - Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, - Sensors::ValueType::PRIMARY, true, true - ); - - // Power sensors - Sensors::setValueByType( - Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, - Sensors::ValueType::PRIMARY, true, true - ); - } - } - - // Update DHW temp - if (settings.opentherm.options.dhwSupport && Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP, true)) { - bool result = this->updateDhwTemp(); - - if (result) { - const float convertedDhwTemp = convertTemp( - vars.slave.dhw.currentTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_DHW, "Received temp: %.2f (converted: %.2f)", - vars.slave.dhw.currentTemp, convertedDhwTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_TEMP, convertedDhwTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT_DHW, "Failed receive temp"); - } - } - - // Update DHW temp 2 - if (settings.opentherm.options.dhwSupport && Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP2, true)) { - if (this->updateDhwTemp2()) { - const float convertedDhwTemp2 = convertTemp( - vars.slave.dhw.currentTemp2, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_DHW, "Received temp 2: %.2f (converted: %.2f)", - vars.slave.dhw.currentTemp2, convertedDhwTemp2 - ); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_TEMP2, convertedDhwTemp2, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT_DHW, "Failed receive temp 2"); - } - } - - // Update DHW flow rate - if (settings.opentherm.options.dhwSupport && Sensors::getAmountByType(Sensors::Type::OT_DHW_FLOW_RATE, true)) { - if (this->updateDhwFlowRate()) { - const float convertedDhwFlowRate = convertVolume( - vars.slave.dhw.flowRate, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_DHW, "Received flow rate: %.2f (converted: %.2f)", - vars.slave.dhw.flowRate, convertedDhwFlowRate - ); - - Sensors::setValueByType( - Sensors::Type::OT_DHW_FLOW_RATE, convertedDhwFlowRate, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT_DHW, "Failed receive flow rate"); - } - } - - // Update heating temp - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_TEMP, true)) { - if (this->updateHeatingTemp()) { - const float convertedHeatingTemp = convertTemp( - vars.slave.heating.currentTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_HEATING, "Received temp: %.2f", - vars.slave.heating.currentTemp, convertedHeatingTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_TEMP, convertedHeatingTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed receive temp"); - } - } - - // Update heating return temp - if (Sensors::getAmountByType(Sensors::Type::OT_HEATING_RETURN_TEMP, true)) { - if (this->updateHeatingReturnTemp()) { - const float convertedHeatingReturnTemp = convertTemp( - vars.slave.heating.returnTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_HEATING, "Received return temp: %.2f (converted: %.2f)", - vars.slave.heating.returnTemp, convertedHeatingReturnTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_HEATING_RETURN_TEMP, convertedHeatingReturnTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed receive return temp"); - } - } - - // Update CH2 temp - if (Sensors::getAmountByType(Sensors::Type::OT_CH2_TEMP, true)) { - if (vars.master.ch2.enabled && !settings.opentherm.options.nativeOTC) { - if (this->updateCh2Temp()) { - const float convertedCh2Temp = convertTemp( - vars.slave.ch2.currentTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT_CH2, "Received temp: %.2f (converted: %.2f)", - vars.slave.ch2.currentTemp, convertedCh2Temp - ); - - Sensors::setValueByType( - Sensors::Type::OT_CH2_TEMP, convertedCh2Temp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT_CH2, "Failed receive temp"); - } - } - } - - // Update exhaust temp - if (Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_TEMP, true)) { - if (this->updateExhaustTemp()) { - const float convertedExhaustTemp = convertTemp( - vars.slave.exhaust.temp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT, "Received exhaust temp: %.2f (converted: %.2f)", - vars.slave.exhaust.temp, convertedExhaustTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_EXHAUST_TEMP, convertedExhaustTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive exhaust temp"); - } - } - - // Update heat exchanger temp - if (Sensors::getAmountByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, true)) { - if (this->updateHeatExchangerTemp()) { - const float convertedHeatExchTemp = convertTemp( - vars.slave.heatExchangerTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT, "Received heat exchanger temp: %.2f (converted: %.2f)", - vars.slave.heatExchangerTemp, convertedHeatExchTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_HEAT_EXCHANGER_TEMP, convertedHeatExchTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive heat exchanger temp"); - } - } - - // Update outdoor temp - if (Sensors::getAmountByType(Sensors::Type::OT_OUTDOOR_TEMP, true)) { - if (this->updateOutdoorTemp()) { - const float convertedOutdoorTemp = convertTemp( - vars.slave.heating.outdoorTemp, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT, "Received outdoor temp: %.2f (converted: %.2f)", - vars.slave.heating.outdoorTemp, convertedOutdoorTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_OUTDOOR_TEMP, convertedOutdoorTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive outdoor temp"); - } - } - - // Update solar storage temp - if (Sensors::getAmountByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, true)) { - if (this->updateSolarStorageTemp()) { - const float convertedSolarStorageTemp = convertTemp( - vars.slave.solar.storage, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT, "Received solar storage temp: %.2f (converted: %.2f)", - vars.slave.solar.storage, convertedSolarStorageTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_SOLAR_STORAGE_TEMP, convertedSolarStorageTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive solar storage temp"); - } - } - - // Update solar collector temp - if (Sensors::getAmountByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, true)) { - if (this->updateSolarCollectorTemp()) { - const float convertedSolarCollectorTemp = convertTemp( - vars.slave.solar.collector, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT, "Received solar collector temp: %.2f (converted: %.2f)", - vars.slave.solar.collector, convertedSolarCollectorTemp - ); - - Sensors::setValueByType( - Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, convertedSolarCollectorTemp, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive solar collector temp"); - } - } - - // Update fan speed - if ( - Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, true) || - Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_CURRENT, true) - ) { - if (this->updateFanSpeed()) { - Log.snoticeln( - L_OT, "Received fan speed, setpoint: %hhu%%, current: %hhu%%", - vars.slave.fanSpeed.setpoint, vars.slave.fanSpeed.current - ); - - Sensors::setValueByType( - Sensors::Type::OT_FAN_SPEED_SETPOINT, vars.slave.fanSpeed.setpoint, - Sensors::ValueType::PRIMARY, true, true - ); - Sensors::setValueByType( - Sensors::Type::OT_FAN_SPEED_CURRENT, vars.slave.fanSpeed.current, - Sensors::ValueType::PRIMARY, true, true - ); - } - } - - // Update pressure - if (Sensors::getAmountByType(Sensors::Type::OT_PRESSURE, true)) { - if (this->updatePressure()) { - const float convertedPressure = convertPressure( - vars.slave.pressure, - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - Log.snoticeln( - L_OT, "Received pressure: %.2f (converted: %.2f)", - vars.slave.pressure, convertedPressure - ); - - Sensors::setValueByType( - Sensors::Type::OT_PRESSURE, convertedPressure, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive pressure"); - } - } - - // Update exhaust CO2 - if (Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_CO2, true)) { - if (this->updateExhaustCo2()) { - Log.snoticeln( - L_OT, "Received exhaust CO2: %hu ppm", - vars.slave.exhaust.co2 - ); - - Sensors::setValueByType( - Sensors::Type::OT_EXHAUST_CO2, vars.slave.exhaust.co2, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive exhaust CO2"); - } - } - - // Update exhaust fan speed - if (Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, true)) { - if (this->updateExhaustFanSpeed()) { - Log.snoticeln( - L_OT, "Received exhaust fan speed: %hu rpm", - vars.slave.exhaust.fanSpeed - ); - - Sensors::setValueByType( - Sensors::Type::OT_EXHAUST_FAN_SPEED, vars.slave.exhaust.fanSpeed, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive exhaust fan speed"); - } - } - - // Update supply fan speed - if (Sensors::getAmountByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, true)) { - if (this->updateSupplyFanSpeed()) { - Log.snoticeln( - L_OT, "Received supply fan speed: %hu rpm", - vars.slave.fanSpeed.supply - ); - - Sensors::setValueByType( - Sensors::Type::OT_SUPPLY_FAN_SPEED, vars.slave.fanSpeed.supply, - Sensors::ValueType::PRIMARY, true, true - ); - - } else { - Log.swarningln(L_OT, "Failed receive supply fan speed"); - } - } - - // Fault reset action - if (vars.actions.resetFault) { - if (vars.slave.fault.active) { - if (this->instance->sendBoilerReset()) { - Log.sinfoln(L_OT, "Boiler fault reset successfully"); - - } else { - Log.serrorln(L_OT, "Boiler fault reset failed"); - } - } - - vars.actions.resetFault = false; - } - - // Diag reset action - if (vars.actions.resetDiagnostic) { - if (vars.slave.diag.active) { - if (this->instance->sendServiceReset()) { - Log.sinfoln(L_OT, "Boiler diagnostic reset successfully"); - - } else { - Log.serrorln(L_OT, "Boiler diagnostic reset failed"); - } - } - - vars.actions.resetDiagnostic = false; - } - - - // Update DHW temp - if (settings.opentherm.options.dhwSupport) { - // Target dhw temp - const float targetTemp = this->getSlaveChannelSetpoint( - vars.master.dhw.enabled, vars.master.dhw.targetTemp, settings.opentherm.dhwDisablingAction - ); - - // Converted target dhw temp - const float convertedTemp = this->convertSetpointTemp(targetTemp); - - // Set DHW temp - if (this->needSetDhwTemp(convertedTemp)) { - if (this->setDhwTemp(convertedTemp)) { - this->dhwSetTempTime = millis(); - - Log.sinfoln( - L_OT_DHW, "Set temp: %.2f (converted: %.2f, response: %.2f)", - targetTemp, convertedTemp, vars.slave.dhw.targetTemp - ); - - } else { - Log.swarningln(L_OT_DHW, "Failed set temp"); - } - } - } - - // Send indoor temp if AlwaysSendIndoorTemp option is enabled. - if (settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp) { - // Current indoor temp - const float& indoorTemp = vars.master.heating.indoorTemp; - - // Converted current indoor temp - const float convertedTemp = convertTemp(indoorTemp, settings.system.unitSystem, settings.opentherm.unitSystem); - - // Set current indoor temp - if (this->setRoomTemp(convertedTemp)) { - Log.sinfoln( - L_OT_HEATING, "Set current indoor temp: %.2f (converted: %.2f, response: %.2f)", - indoorTemp, convertedTemp, vars.slave.heating.indoorTemp - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed set current indoor temp"); - } - - // Set current CH2 indoor temp - if (settings.opentherm.options.heatingToCh2) { - if (this->setRoomTempCh2(convertedTemp)) { - Log.sinfoln( - L_OT_HEATING, "Set current CH2 indoor temp: %.2f (converted: %.2f, response: %.2f)", - indoorTemp, convertedTemp, vars.slave.ch2.indoorTemp - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed set current CH2 indoor temp"); - } - } - } - - // NativeOTC - if (settings.opentherm.options.nativeOTC) { - // Target indoor temp - const float& targetTemp = vars.master.heating.targetTemp; - - // Converted target indoor temp - const float convertedTemp = convertTemp( - targetTemp, - settings.system.unitSystem, - settings.opentherm.unitSystem - ); - - // Set target indoor temp - if (this->needSetRoomSetpoint(convertedTemp)) { - if (this->setRoomSetpoint(convertedTemp)) { - this->roomSetTempTime = millis(); - - Log.sinfoln( - L_OT_HEATING, "Set target indoor temp: %.2f (converted: %.2f, response: %.2f)", - targetTemp, convertedTemp, vars.slave.heating.roomTargetTemp - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed set target indoor temp"); - } - } - - // Set target CH2 temp - if (settings.opentherm.options.heatingToCh2 && this->needSetRoomSetpointCh2(convertedTemp)) { - if (this->setRoomSetpointCh2(convertedTemp)) { - this->roomSetTempCh2Time = millis(); - - Log.sinfoln( - L_OT_HEATING, "Set target CH2 indoor temp: %.2f (converted: %.2f, response: %.2f)", - targetTemp, convertedTemp, vars.slave.ch2.roomTargetTemp - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed set target CH2 indoor temp"); - } - } - } - - // Set heating temp - { - // Target heating temp - const float targetTemp = this->getSlaveChannelSetpoint( - vars.master.heating.enabled, - settings.opentherm.options.nativeOTC - ? vars.master.heating.targetTemp - : vars.master.heating.setpointTemp, - settings.opentherm.heatingDisablingAction - ); - - // Converted target heating temp - const float convertedTemp = this->convertSetpointTemp(targetTemp); - - if (this->needSetHeatingTemp(convertedTemp)) { - // Set max heating temp - if (settings.opentherm.options.maxTempSyncWithTargetTemp) { - if (this->setMaxHeatingTemp(convertedTemp)) { - Log.sinfoln( - L_OT_HEATING, "Set max heating temp: %.2f (converted: %.2f)", - targetTemp, convertedTemp - ); - - } else { - Log.swarningln( - L_OT_HEATING, "Failed set max heating temp: %.2f (converted: %.2f)", - targetTemp, convertedTemp - ); - } - } - - // Set target heating temp - if (this->setHeatingTemp(convertedTemp)) { - this->heatingSetTempTime = millis(); - - Log.sinfoln( - L_OT_HEATING, "Set target temp: %.2f (converted: %.2f, response: %.2f)", - targetTemp, convertedTemp, vars.slave.heating.targetTemp - ); - - } else { - Log.swarningln(L_OT_HEATING, "Failed set target temp"); - } - } - } - - // Set CH2 temp - if (settings.opentherm.options.heatingToCh2 || settings.opentherm.options.dhwToCh2 - || (!vars.master.ch2.enabled && settings.opentherm.ch2DisablingAction != ChannelDisablingAction::OFF)) { - // Target CH2 heating temp - const float targetTemp = this->getSlaveChannelSetpoint( - vars.master.ch2.enabled, vars.master.ch2.targetTemp, settings.opentherm.ch2DisablingAction - ); - - // Converted target CH2 temp - const float convertedTemp = this->convertSetpointTemp(targetTemp); - - if (this->needSetCh2Temp(convertedTemp)) { - if (this->setCh2Temp(convertedTemp)) { - this->ch2SetTempTime = millis(); - - Log.sinfoln( - L_OT_CH2, "Set temp: %.2f (converted: %.2f, response: %.2f)", - targetTemp, convertedTemp, vars.slave.ch2.targetTemp - ); - - } else { - Log.swarningln(L_OT_CH2, "Failed set temp"); - } - } - } - - - // Heating overheat control - if (settings.heating.overheatProtection.highTemp > 0 && settings.heating.overheatProtection.lowTemp > 0) { - const float highTemp = convertTemp( - max({ - vars.slave.heating.currentTemp, - vars.slave.heating.returnTemp, - vars.slave.heatExchangerTemp - }), - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - if (vars.master.heating.overheat) { - if (static_cast(settings.heating.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) { - vars.master.heating.overheat = false; - - Log.sinfoln( - L_OT_HEATING, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu", - highTemp, settings.heating.overheatProtection.lowTemp - ); - } - - } else if (vars.slave.heating.active) { - if (highTemp - static_cast(settings.heating.overheatProtection.highTemp) + 0.0001f >= 0.0f) { - vars.master.heating.overheat = true; - - Log.swarningln( - L_OT_HEATING, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu", - highTemp, settings.heating.overheatProtection.highTemp - ); - } - } - - } else if (vars.master.heating.overheat) { - vars.master.heating.overheat = false; - } - - // DHW overheat control - if (settings.dhw.overheatProtection.highTemp > 0 && settings.dhw.overheatProtection.lowTemp > 0) { - const float highTemp = convertTemp( - max({ - vars.slave.heating.currentTemp, - vars.slave.heating.returnTemp, - vars.slave.heatExchangerTemp, - vars.slave.dhw.currentTemp, - vars.slave.dhw.currentTemp2, - vars.slave.dhw.returnTemp - }), - settings.opentherm.unitSystem, - settings.system.unitSystem - ); - - if (vars.master.dhw.overheat) { - if (static_cast(settings.dhw.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) { - vars.master.dhw.overheat = false; - - Log.sinfoln( - L_OT_DHW, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu", - highTemp, settings.dhw.overheatProtection.lowTemp - ); - } - - } else if (vars.slave.dhw.active) { - if (highTemp - static_cast(settings.dhw.overheatProtection.highTemp) + 0.0001f >= 0.0f) { - vars.master.dhw.overheat = true; - - Log.swarningln( - L_OT_DHW, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu", - highTemp, settings.dhw.overheatProtection.highTemp - ); - } - } - - } else if (vars.master.dhw.overheat) { - vars.master.dhw.overheat = false; - } - } - - void initialize() { - // Not all boilers support these, only try once when the boiler becomes connected - if (this->updateSlaveVersion()) { - Log.snoticeln( - L_OT, "Received slave app version: %u, type: %u", - vars.slave.appVersion, vars.slave.type - ); - - } else { - Log.swarningln(L_OT, "Failed receive slave version"); - } - - if (this->setMasterVersion(vars.master.appVersion, vars.master.type)) { - Log.snoticeln( - L_OT, "Set master version: %u, type: %u", - vars.master.appVersion, vars.master.type - ); - - } else { - Log.swarningln(L_OT, "Failed set master version"); - } - - if (this->updateSlaveOtVersion()) { - Log.snoticeln(L_OT, "Received slave OT version: %f", vars.slave.protocolVersion); - - } else { - Log.swarningln(L_OT, "Failed receive slave OT version"); - } - - if (this->setMasterOtVersion(vars.master.protocolVersion)) { - Log.snoticeln(L_OT, "Set master OT version: %f", vars.master.protocolVersion); - - } else { - Log.swarningln(L_OT, "Failed set master OT version"); - } - - if (this->updateSlaveConfig()) { - Log.snoticeln( - L_OT, "Received slave member id: %u, flags: %u", - vars.slave.memberId, vars.slave.flags - ); - - } else { - Log.swarningln(L_OT, "Failed receive slave config"); - } - - if (this->setMasterConfig(vars.master.memberId, vars.master.flags)) { - Log.snoticeln( - L_OT, "Set master member id: %u, flags: %u", - vars.master.memberId, vars.master.flags - ); - - } else { - Log.swarningln(L_OT, "Failed set master config"); - } - - /*char buf[100]; - if (this->instance->getStr(OpenThermMessageID::Brand, buf, sizeof(buf) - 1)) { - Log.snoticeln(L_OT, "Slave brand: %s", buf); - } - - if (this->instance->getStr(OpenThermMessageID::BrandVersion, buf, sizeof(buf) - 1)) { - Log.snoticeln(L_OT, "Slave brand version: %s", buf); - } - - if (this->instance->getStr(OpenThermMessageID::BrandSerialNumber, buf, sizeof(buf) - 1)) { - Log.snoticeln(L_OT, "Slave brand s/n: %s", buf); - }*/ - } - - bool isReady() { - return millis() - this->instanceCreatedTime > this->readyTime; - } - - bool getSlaveChannelEnabled(const bool enabled, const ChannelDisablingAction action) { - return enabled || action == ChannelDisablingAction::ZERO_SETPOINT; - } - - float getSlaveChannelSetpoint(const bool enabled, const float temperature, const ChannelDisablingAction action) { - if (!enabled && action != ChannelDisablingAction::OFF) { - return 0.0f; - } - - return temperature; - } - - float convertSetpointTemp(const float temperature) { - // Preserve the no-demand zero for TSet/TsetCH2 when converting units. - if (temperature == 0.0f) { - return 0.0f; - } - - return convertTemp(temperature, settings.system.unitSystem, settings.opentherm.unitSystem); - } - - bool needSetRoomSetpoint(const float target) { - return !this->roomSetTempTime - || millis() - this->roomSetTempTime > this->heatingSetTempInterval - || fabsf(target - vars.slave.heating.roomTargetTemp) > 0.05f; - } - - bool needSetRoomSetpointCh2(const float target) { - return !this->roomSetTempCh2Time - || millis() - this->roomSetTempCh2Time > this->ch2SetTempInterval - || fabsf(target - vars.slave.ch2.roomTargetTemp) > 0.05f; - } - - bool needSetDhwTemp(const float target) { - return !this->dhwSetTempTime - || millis() - this->dhwSetTempTime > this->dhwSetTempInterval - || fabsf(target - vars.slave.dhw.targetTemp) > 0.05f; - } - - bool needSetHeatingTemp(const float target) { - return !this->heatingSetTempTime - || millis() - this->heatingSetTempTime > this->heatingSetTempInterval - || fabsf(target - vars.slave.heating.targetTemp) > 0.05f; - } - - bool needSetCh2Temp(const float target) { - return !this->ch2SetTempTime - || millis() - this->ch2SetTempTime > this->ch2SetTempInterval - || fabsf(target - vars.slave.ch2.targetTemp) > 0.05f; - } - - bool updateSlaveConfig() { - unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::SConfigSMemberIDcode, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::SConfigSMemberIDcode)) { - return false; - } - - vars.slave.memberId = response & 0xFF; - vars.slave.flags = (response & 0xFFFF) >> 8; - - /*uint8_t flags = (response & 0xFFFF) >> 8; - Log.straceln( - "OT", - "MasterMemberIdCode:\r\n DHW present: %u\r\n Control type: %u\r\n Cooling configuration: %u\r\n DHW configuration: %u\r\n Pump control: %u\r\n CH2 present: %u\r\n Remote water filling function: %u\r\n Heat/cool mode control: %u\r\n Slave MemberID Code: %u\r\n Raw: %u", - (bool) (flags & 0x01), - (bool) (flags & 0x02), - (bool) (flags & 0x04), - (bool) (flags & 0x08), - (bool) (flags & 0x10), - (bool) (flags & 0x20), - (bool) (flags & 0x40), - (bool) (flags & 0x80), - response & 0xFF, - response - );*/ - - return true; - } - - bool setYear(const struct tm *ptm) { - const unsigned int request = (ptm->tm_year + 1900) & 0xFFFF; - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::Year, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Year)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setDayAndMonth(const struct tm *ptm) { - const uint8_t month = (ptm->tm_mon + 1) & 0xFF; - const unsigned int request = (month << 8) | (ptm->tm_mday & 0xFF); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::Date, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Date)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setTime(const struct tm *ptm) { - const uint8_t dayOfWeek = ptm->tm_wday == 0 ? 7 : ptm->tm_wday; - const unsigned int request = ((dayOfWeek & 0x07) << 13) - | ((ptm->tm_hour & 0x1F) << 8) - | (ptm->tm_min & 0x3F); - - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::DayTime, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DayTime)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setCoolingSetpoint(const uint8_t value) { - const unsigned int request = CustomOpenTherm::toFloat(value); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::CoolingControl, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CoolingControl)) { - return false; - } - - vars.slave.cooling.setpoint = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setMaxModulationLevel(const uint8_t value) { - const unsigned int request = CustomOpenTherm::toFloat(value); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::MaxRelModLevelSetting, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxRelModLevelSetting)) { - return false; - } - - vars.slave.modulation.max = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setDhwTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TdhwSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TdhwSet)) { - return false; - } - - vars.slave.dhw.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - - bool setRoomTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::Tr, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tr)) { - return false; - } - - vars.slave.heating.indoorTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setRoomTempCh2(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TrCH2, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TrCH2)) { - return false; - } - - vars.slave.ch2.indoorTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setRoomSetpoint(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TrSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TrSet)) { - return false; - } - - vars.slave.heating.roomTargetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setRoomSetpointCh2(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TrSetCH2, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TrSetCH2)) { - return false; - } - - vars.slave.ch2.roomTargetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setMaxHeatingTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::MaxTSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxTSet)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setHeatingTemp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TSet, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TSet)) { - return false; - } - - vars.slave.heating.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setCh2Temp(const float temperature) { - const unsigned int request = CustomOpenTherm::temperatureToData(temperature); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::WRITE_DATA, - OpenThermMessageID::TsetCH2, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TsetCH2)) { - return false; - } - - vars.slave.ch2.targetTemp = CustomOpenTherm::getFloat(response); - - return CustomOpenTherm::getUInt(response) == request; - } - - bool setMasterVersion(const uint8_t version, const uint8_t type) { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::MasterVersion, - (unsigned int) version | (unsigned int) type << 8 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MasterVersion)) { - return false; - } - - uint8_t rVersion = response & 0xFF; - uint8_t rType = (response & 0xFFFF) >> 8; - - return rVersion == version && rType == type; - } - - bool setMasterOtVersion(const float version) { - const unsigned int request = CustomOpenTherm::toFloat(version); - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::OpenThermVersionMaster, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::OpenThermVersionMaster)) { - return false; - } - - return CustomOpenTherm::getUInt(response) == request; - } - - /** - * @brief Set the Master Config - * From slave member id code: - * id: slave.memberIdCode & 0xFF, - * flags: (slave.memberIdCode & 0xFFFF) >> 8 - * @param id - * @param flags - * @param force - * @return true - * @return false - */ - bool setMasterConfig(const uint8_t id, const uint8_t flags, const bool force = false) { - const uint8_t rMemberId = (force || id > 0) ? id : vars.slave.memberId; - const uint8_t rFlags = (force || flags > 0) ? flags : vars.slave.flags; - const unsigned int request = (unsigned int) rMemberId | (unsigned int) rFlags << 8; - - // if empty request - if (!request) { - return true; - } - - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::WRITE_DATA, - OpenThermMessageID::MConfigMMemberIDcode, - request - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MConfigMMemberIDcode)) { - return false; - } - - //uint8_t rMemberId = response & 0xFF; - //uint8_t rFlags = (response & 0xFFFF) >> 8; - - return CustomOpenTherm::getUInt(response) == request; - } - - bool updateSlaveOtVersion() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::OpenThermVersionSlave, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::OpenThermVersionSlave)) { - return false; - } - - vars.slave.protocolVersion = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateSlaveVersion() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::SlaveVersion, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::SlaveVersion)) { - return false; - } - - vars.slave.appVersion = response & 0xFF; - vars.slave.type = (response & 0xFFFF) >> 8; - - return true; - } - - bool updateMinModulationLevel() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::MaxCapacityMinModLevel, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxCapacityMinModLevel)) { - return false; - } - - vars.slave.modulation.min = response & 0xFF; - vars.slave.power.max = (response & 0xFFFF) >> 8; - vars.slave.power.min = vars.slave.modulation.min > 0 && vars.slave.power.max > 0.1f - ? (vars.slave.modulation.min * 0.01f) * vars.slave.power.max - : 0.0f; - - return true; - } - - bool updateMinMaxDhwTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::TdhwSetUBTdhwSetLB, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TdhwSetUBTdhwSetLB)) { - return false; - } - - uint8_t minTemp = response & 0xFF; - uint8_t maxTemp = (response & 0xFFFF) >> 8; - - if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { - vars.slave.dhw.minTemp = minTemp; - vars.slave.dhw.maxTemp = maxTemp; - - return true; - } - - return false; - } - - bool updateMinMaxHeatingTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::MaxTSetUBMaxTSetLB, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::MaxTSetUBMaxTSetLB)) { - return false; - } - - uint8_t minTemp = response & 0xFF; - uint8_t maxTemp = (response & 0xFFFF) >> 8; - - if (minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { - vars.slave.heating.minTemp = minTemp; - vars.slave.heating.maxTemp = maxTemp; - - return true; - } - - return false; - } - - bool updateFaultCode() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::ASFflags, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::ASFflags)) { - return false; - } - - vars.slave.fault.code = response & 0xFF; - - return true; - } - - bool updateDiagCode() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::OEMDiagnosticCode, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::OEMDiagnosticCode)) { - return false; - } - - vars.slave.diag.code = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateBurnerStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::SuccessfulBurnerStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::SuccessfulBurnerStarts)) { - return false; - } - - vars.slave.stats.burnerStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwBurnerStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWBurnerStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWBurnerStarts)) { - return false; - } - - vars.slave.stats.dhwBurnerStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateHeatingPumpStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CHPumpStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CHPumpStarts)) { - return false; - } - - vars.slave.stats.heatingPumpStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwPumpStarts() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWPumpValveStarts, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWPumpValveStarts)) { - return false; - } - - vars.slave.stats.dhwPumpStarts = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateBurnerHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::BurnerOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::BurnerOperationHours)) { - return false; - } - - vars.slave.stats.burnerHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwBurnerHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWBurnerOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWBurnerOperationHours)) { - return false; - } - - vars.slave.stats.dhwBurnerHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateHeatingPumpHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CHPumpOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CHPumpOperationHours)) { - return false; - } - - vars.slave.stats.heatingPumpHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateDhwPumpHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::DHWPumpValveOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWPumpValveOperationHours)) { - return false; - } - - vars.slave.stats.dhwPumpHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateCoolingHours() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CoolingOperationHours, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CoolingOperationHours)) { - return false; - } - - vars.slave.stats.coolingHours = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateModulationLevel() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::RelModLevel, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::RelModLevel)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value < 0) { - return false; - } - - vars.slave.modulation.current = value; - - return true; - } - - bool updateDhwTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tdhw, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tdhw)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.dhw.currentTemp = value; - - return true; - } - - bool updateDhwTemp2() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tdhw2, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tdhw2)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.dhw.currentTemp2 = value; - - return true; - } - - bool updateDhwFlowRate() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::DHWFlowRate, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::DHWFlowRate)) { - return false; - } - - float value = CustomOpenTherm::getFloat(response); - if (value < 0) { - return false; - } - - // no minuscule values - // some boilers send a response of 0.06 when there is no flow - if (value < 0.1f) { - value = 0.0f; - } - - vars.slave.dhw.flowRate = value; - - return true; - } - - bool updateHeatingTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tboiler, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tboiler)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.heating.currentTemp = value; - - return true; - } - - bool updateHeatingReturnTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tret, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tret)) { - return false; - } - - vars.slave.heating.returnTemp = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateCh2Temp() { - unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::TflowCH2, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TflowCH2)) { - return false; - } - - vars.slave.ch2.currentTemp = CustomOpenTherm::getFloat(response); - - return true; - } - - - - bool updateExhaustTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::Texhaust, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Texhaust)) { - return false; - } - - const float value = CustomOpenTherm::getInt(response); - if (!isValidTemp(value, settings.opentherm.unitSystem, -40, 500)) { - return false; - } - - vars.slave.exhaust.temp = value; - - return true; - } - - bool updateHeatExchangerTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::TboilerHeatExchanger, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::TboilerHeatExchanger)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value <= 0) { - return false; - } - - vars.slave.heatExchangerTemp = value; - - return true; - } - - bool updateOutdoorTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::Toutside, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Toutside)) { - return false; - } - - vars.slave.heating.outdoorTemp = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateSolarStorageTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tstorage, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tstorage)) { - return false; - } - - vars.slave.solar.storage = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateSolarCollectorTemp() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermMessageType::READ_DATA, - OpenThermMessageID::Tcollector, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::Tcollector)) { - return false; - } - - vars.slave.solar.collector = CustomOpenTherm::getFloat(response); - - return true; - } - - bool updateFanSpeed() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::BoilerFanSpeedSetpointAndActual, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::BoilerFanSpeedSetpointAndActual)) { - return false; - } - - vars.slave.fanSpeed.setpoint = (response & 0xFFFF) >> 8; - vars.slave.fanSpeed.current = response & 0xFF; - - return true; - } - - bool updatePressure() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CHPressure, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CHPressure)) { - return false; - } - - const float value = CustomOpenTherm::getFloat(response); - if (value < 0) { - return false; - } - - vars.slave.pressure = value; - - return true; - } - - bool updateExhaustCo2() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::CO2exhaust, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::CO2exhaust)) { - return false; - } - - vars.slave.exhaust.co2 = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateExhaustFanSpeed() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::RPMexhaust, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::RPMexhaust)) { - return false; - } - - vars.slave.exhaust.fanSpeed = CustomOpenTherm::getUInt(response); - - return true; - } - - bool updateSupplyFanSpeed() { - const unsigned long response = this->instance->sendRequest(CustomOpenTherm::buildRequest( - OpenThermRequestType::READ_DATA, - OpenThermMessageID::RPMsupply, - 0 - )); - - if (!CustomOpenTherm::isValidResponse(response)) { - return false; - - } else if (!CustomOpenTherm::isValidResponseId(response, OpenThermMessageID::RPMsupply)) { - return false; - } - - vars.slave.fanSpeed.supply = CustomOpenTherm::getUInt(response); - - return true; - } -}; diff --git a/src/PortalTask.h b/src/PortalTask.h deleted file mode 100644 index d5da17a..0000000 --- a/src/PortalTask.h +++ /dev/null @@ -1,829 +0,0 @@ -//#define PORTAL_CACHE "max-age=86400" -#define PORTAL_CACHE nullptr -#include -#include -#include -#include -#include -#include -#include - -using namespace NetworkUtils; - -extern NetworkMgr* network; -extern FileData fsNetworkSettings, fsSettings, fsSensorsSettings; -extern MqttTask* tMqtt; -extern WebSerial* webSerial; - - -class PortalTask : public LeanTask { -public: - explicit PortalTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) { - this->webServer = new AsyncWebServer(80); - this->dnsServer = new DNSServer(); - } - - ~PortalTask() { - if (this->webServer != nullptr) { - this->stopWebServer(); - delete this->webServer; - } - - if (this->dnsServer != nullptr) { - this->stopDnsServer(); - delete this->dnsServer; - } - } - -protected: - const unsigned int changeStateInterval = 5000; - - AsyncWebServer* webServer = nullptr; - DNSServer* dnsServer = nullptr; - - bool webServerEnabled = false; - bool dnsServerEnabled = false; - unsigned long webServerChangeState = 0; - bool mDnsState = false; - - const char* getTaskName() override { - return "Portal"; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 1; - } - - void setup() { - this->dnsServer->setTTL(0); - this->dnsServer->setErrorReplyCode(DNSReplyCode::NoError); - - // auth middleware - static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { - if (!isAuthenticationRequired()) { - return next(); - } - - if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { - return next(); - } - - return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); - }); - - // web serial - if (webSerial != nullptr) { - webSerial->begin(this->webServer, nullptr, "/webserial"); - - // Refresh credentials before each handshake to use the current portal settings. - this->webServer->addMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { - if (request->url().equals("/webserial")) { - if (isAuthenticationRequired()) { - webSerial->setAuthentication(settings.portal.login, settings.portal.password); - } else { - webSerial->setAuthentication("", ""); - } - } - - return next(); - }); - } - - // index page - this->webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) { - request->redirect("/index.html"); - }); - this->webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE); - - // dashboard page - this->webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE) - .addMiddleware(&authMiddleware); - - // restart - this->webServer->on("/restart.html", HTTP_GET, [](AsyncWebServerRequest *request) { - vars.actions.restart = true; - request->redirect("/"); - }).addMiddleware(&authMiddleware); - - // network settings page - this->webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE) - .addMiddleware(&authMiddleware); - - // settings page - this->webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE) - .addMiddleware(&authMiddleware); - - // sensors page - this->webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE) - .addMiddleware(&authMiddleware); - - // upgrade page - this->webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE) - .addMiddleware(&authMiddleware); - - // logs page - this->webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE) - .addMiddleware(&authMiddleware); - - // OTA - auto upgradeHandler = (new UpgradeHandler("/api/upgrade")) - ->setBeforeUpgradeCallback([](AsyncWebServerRequest *request, UpgradeHandler::UpgradeType type) -> bool { - if (vars.states.restarting) { - return false; - } - - vars.states.upgrading = true; - return true; - - })->setAfterUpgradeCallback([](AsyncWebServerRequest *request, const UpgradeHandler::UpgradeResult& fwResult, const UpgradeHandler::UpgradeResult& fsResult) { - unsigned short status = 406; - if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) { - status = 202; - vars.actions.restart = true; - } - vars.states.upgrading = false; - - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - - auto fwDoc = doc["firmware"].to(); - fwDoc["status"] = static_cast(fwResult.status); - fwDoc["error"] = fwResult.error; - - auto fsDoc = doc["filesystem"].to(); - fsDoc["status"] = static_cast(fsResult.status); - fsDoc["error"] = fsResult.error; - - // send response - response->setLength(); - response->setCode(status); - request->send(response); - }); - this->webServer->addHandler(upgradeHandler); - - - // backup - this->webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - - // add network settings - auto networkDoc = doc[S_NETWORK].to(); - networkSettingsToJson(networkSettings, networkDoc); - - // add main settings - auto settingsDoc = doc[S_SETTINGS].to(); - settingsToJson(settings, settingsDoc); - - // add sensors settings - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to(); - sensorSettingsToJson(sensorId, Sensors::settings[sensorId], sensorsettingsDoc); - } - - char filename[64]; - getFilename(filename, sizeof(filename), "backup"); - - char contentDispositionValue[128]; - snprintf( - contentDispositionValue, - sizeof(contentDispositionValue), - "attachment; filename=\"%s\"", - filename - ); - - // send response - response->addHeader("Content-Disposition", contentDispositionValue); - response->setLength(); - request->send(response); - }).addMiddleware(&authMiddleware); - - // backup restore - auto& brHandler = this->webServer->on("/api/backup/restore", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { - if (vars.states.restarting) { - return request->send(503); - } - - if (requestDoc.isNull() || !requestDoc.size()) { - return request->send(400); - } - - // prepare request - bool changed = false; - - // restore network settings - if (!requestDoc[S_NETWORK].isNull() && jsonToNetworkSettings(requestDoc[S_NETWORK], networkSettings)) { - fsNetworkSettings.update(); - network->setHostname(networkSettings.hostname) - ->setStaCredentials(networkSettings.sta.ssid, networkSettings.sta.password, networkSettings.sta.channel) - ->setApCredentials(networkSettings.ap.ssid, networkSettings.ap.password, networkSettings.ap.channel) - ->setUseDhcp(networkSettings.useDhcp) - ->setStaticConfig( - networkSettings.staticConfig.ip, - networkSettings.staticConfig.gateway, - networkSettings.staticConfig.subnet, - networkSettings.staticConfig.dns - ); - changed = true; - } - - // restore main settings - if (!requestDoc[S_SETTINGS].isNull() && jsonToSettings(requestDoc[S_SETTINGS], settings)) { - fsSettings.update(); - changed = true; - } - - // restore sensors settings - if (!requestDoc[S_SENSORS].isNull()) { - for (auto sensor : requestDoc[S_SENSORS].as()) { - uint8_t sensorId; - if (!Sensors::parseId(sensor.key().c_str(), sensorId)) { - continue; - } - - if (jsonToSensorSettings(sensorId, sensor.value(), Sensors::settings[sensorId])) { - fsSensorsSettings.update(); - changed = true; - } - } - } - requestDoc.clear(); - - // send response - request->send(changed ? 201 : 200); - - if (changed) { - vars.actions.restart = true; - } - }); - brHandler.setMaxContentLength(3072); - brHandler.addMiddleware(&authMiddleware); - - // network - this->webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - networkSettingsToJson(networkSettings, doc); - - // send response - response->setLength(); - request->send(response); - }).addMiddleware(&authMiddleware); - - auto& nsHandler = this->webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { - if (vars.states.restarting) { - return request->send(503); - } - - if (requestDoc.isNull() || !requestDoc.size()) { - return request->send(400); - } - - // prepare request - bool changed = jsonToNetworkSettings(requestDoc, networkSettings); - requestDoc.clear(); - - // make response - auto *response = new AsyncJsonResponse(); - auto& responseDoc = response->getRoot(); - networkSettingsToJson(networkSettings, responseDoc); - - // send response - response->setLength(); - response->setCode(changed ? 201 : 200); - request->send(response); - - if (changed) { - fsNetworkSettings.update(); - network->setHostname(networkSettings.hostname) - ->setStaCredentials(networkSettings.sta.ssid, networkSettings.sta.password, networkSettings.sta.channel) - ->setApCredentials(networkSettings.ap.ssid, networkSettings.ap.password, networkSettings.ap.channel) - ->setUseDhcp(networkSettings.useDhcp) - ->setStaticConfig( - networkSettings.staticConfig.ip, - networkSettings.staticConfig.gateway, - networkSettings.staticConfig.subnet, - networkSettings.staticConfig.dns - ) - ->reconnect(); - } - }); - nsHandler.setMaxContentLength(512); - nsHandler.addMiddleware(&authMiddleware); - - this->webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) { - auto apCount = WiFi.scanComplete(); - - switch (apCount) { - case WIFI_SCAN_FAILED: - WiFi.scanNetworks(true, true, false); - request->send(404); - break; - - case WIFI_SCAN_RUNNING: - request->send(202); - break; - - default: - // make respponse - auto *response = new AsyncJsonResponse(true); - auto& doc = response->getRoot(); - for (short int i = 0; i < apCount; i++) { - doc[i][S_SSID] = WiFi.SSID(i); - doc[i][S_BSSID] = WiFi.BSSIDstr(i); - doc[i][S_SIGNAL_QUALITY] = NetworkMgr::rssiToSignalQuality(WiFi.RSSI(i)); - doc[i][S_CHANNEL] = WiFi.channel(i); - doc[i][S_HIDDEN] = !WiFi.SSID(i).length(); - doc[i][S_AUTH] = WiFi.encryptionType(i); - } - - // send response - response->setLength(); - request->send(response); - - // clear - WiFi.scanDelete(); - } - }).addMiddleware(&authMiddleware); - - - // settings - this->webServer->on("/api/settings", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - settingsToJson(settings, doc); - - // send response - response->setLength(); - request->send(response); - }).addMiddleware(&authMiddleware); - - auto& sHandler = this->webServer->on("/api/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { - if (vars.states.restarting) { - return request->send(503); - } - - if (requestDoc.isNull() || !requestDoc.size()) { - return request->send(400); - } - - // prepare request - bool changed = jsonToSettings(requestDoc, settings); - requestDoc.clear(); - - // make response - auto *response = new AsyncJsonResponse(); - auto& responseDoc = response->getRoot(); - settingsToJson(settings, responseDoc); - - // send response - response->setLength(); - response->setCode(changed ? 201 : 200); - request->send(response); - - if (changed) { - fsSettings.update(); - tMqtt->resetPublishedSettingsTime(); - } - }); - sHandler.setMaxContentLength(3072); - sHandler.addMiddleware(&authMiddleware); - - - // sensors list - this->webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - bool detailed = request->hasParam("detailed"); - auto *response = new AsyncJsonResponse(true); - auto& responseDoc = response->getRoot(); - - // add sensors - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - if (detailed) { - auto& sSensor = Sensors::settings[sensorId]; - responseDoc[sensorId][S_ENABLED] = sSensor.enabled; - responseDoc[sensorId][S_NAME] = sSensor.name; - responseDoc[sensorId][S_PURPOSE] = static_cast(sSensor.purpose); - sensorResultToJson(sensorId, responseDoc[sensorId]); - - } else { - responseDoc[sensorId] = Sensors::settings[sensorId].name; - } - } - - // send response - response->setLength(); - request->send(response); - }).addMiddleware(&authMiddleware); - - // sensor settings - this->webServer->on("/api/sensor", HTTP_GET, [](AsyncWebServerRequest *request) { - if (!request->hasParam("id")) { - return request->send(400); - } - - const auto& id = request->getParam("id")->value(); - uint8_t sensorId; - if (!Sensors::parseId(id.c_str(), sensorId)) { - return request->send(404); - } - - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - sensorSettingsToJson(sensorId, Sensors::settings[sensorId], doc); - - response->setLength(); - request->send(response); - }).addMiddleware(&authMiddleware); - - auto& ssHandler = this->webServer->on("/api/sensor", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { - if (vars.states.restarting) { - return request->send(503); - } - - if (requestDoc.isNull() || !requestDoc.size()) { - return request->send(400); - } - - if (!request->hasParam("id")) { - return request->send(400); - } - - auto& id = request->getParam("id")->value(); - uint8_t sensorId; - if (!Sensors::parseId(id.c_str(), sensorId)) { - return request->send(404); - } - - // prepare request - auto prevSettings = Sensors::settings[sensorId]; - bool changed = jsonToSensorSettings(sensorId, requestDoc, Sensors::settings[sensorId]); - requestDoc.clear(); - - // make response - auto *response = new AsyncJsonResponse(); - auto& responseDoc = response->getRoot(); - - auto& sSettings = Sensors::settings[sensorId]; - sensorSettingsToJson(sensorId, sSettings, responseDoc); - - // send response - response->setLength(); - response->setCode(changed ? 201 : 200); - request->send(response); - - if (changed) { - tMqtt->reconfigureSensor(sensorId, prevSettings); - fsSensorsSettings.update(); - } - }); - ssHandler.setMaxContentLength(1024); - ssHandler.addMiddleware(&authMiddleware); - - - // vars - this->webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - varsToJson(vars, doc); - - // send response - response->setLength(); - request->send(response); - }); - - auto& vHandler = this->webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { - if (vars.states.restarting) { - return request->send(503); - } - - if (requestDoc.isNull() || !requestDoc.size()) { - return request->send(400); - } - - // prepare request - bool changed = jsonToVars(requestDoc, vars); - requestDoc.clear(); - - // make response - auto *response = new AsyncJsonResponse(); - auto& responseDoc = response->getRoot(); - varsToJson(vars, responseDoc); - - // send response - response->setLength(); - response->setCode(changed ? 201 : 200); - request->send(response); - - if (changed) { - tMqtt->resetPublishedVarsTime(); - } - }); - vHandler.setMaxContentLength(1536); - vHandler.addMiddleware(&authMiddleware); - - this->webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - - auto docSystem = doc[S_SYSTEM].to(); - docSystem[S_RESET_REASON] = getResetReason(); - docSystem[S_UPTIME] = millis() / 1000; - - bool isConnected = network->isConnected(); - auto docNetwork = doc[S_NETWORK].to(); - docNetwork[S_HOSTNAME] = networkSettings.hostname; - docNetwork[S_MAC] = network->getStaMac(); - docNetwork[S_CONNECTED] = isConnected; - docNetwork[S_SSID] = network->getStaSsid(); - docNetwork[S_SIGNAL_QUALITY] = isConnected ? NetworkMgr::rssiToSignalQuality(network->getRssi()) : 0; - docNetwork[S_CHANNEL] = isConnected ? network->getStaChannel() : 0; - docNetwork[S_IP] = isConnected ? network->getStaIp().toString() : ""; - docNetwork[S_SUBNET] = isConnected ? network->getStaSubnet().toString() : ""; - docNetwork[S_GATEWAY] = isConnected ? network->getStaGateway().toString() : ""; - docNetwork[S_DNS] = isConnected ? network->getStaDns().toString() : ""; - - auto docBuild = doc[S_BUILD].to(); - docBuild[S_VERSION] = BUILD_VERSION; - docBuild[S_COMMIT] = BUILD_COMMIT; - docBuild[S_DATE] = __DATE__ " " __TIME__; - docBuild[S_ENV] = BUILD_ENV; - docBuild[S_CORE] = ESP.getCoreVersion(); - docBuild[S_SDK] = ESP.getSdkVersion(); - - auto docHeap = doc[S_HEAP].to(); - docHeap[S_TOTAL] = getTotalHeap(); - docHeap[S_FREE] = getFreeHeap(); - docHeap[S_MIN_FREE] = getFreeHeap(true); - docHeap[S_MAX_FREE_BLOCK] = getMaxFreeBlockHeap(); - docHeap[S_MIN_MAX_FREE_BLOCK] = getMaxFreeBlockHeap(true); - - auto docPsram = doc[S_PSRAM].to(); - docPsram[S_TOTAL] = ESP.getPsramSize(); - docPsram[S_FREE] = ESP.getFreePsram(); - docPsram[S_MIN_FREE] = ESP.getMinFreePsram(); - docPsram[S_MAX_FREE_BLOCK] = ESP.getMaxAllocPsram(); - - auto docChip = doc[S_CHIP].to(); - docChip[S_MODEL] = ESP.getChipModel(); - docChip[S_REV] = ESP.getChipRevision(); - docChip[S_CORES] = ESP.getChipCores(); - docChip[S_FREQ] = ESP.getCpuFreqMHz(); - - auto docFlash = doc[S_FLASH].to(); - docFlash[S_SIZE] = ESP.getFlashChipSize(); - docFlash[S_REAL_SIZE] = docFlash[S_SIZE]; - - // send response - response->setLength(); - request->send(response); - }); - - this->webServer->on("/api/debug", HTTP_GET, [](AsyncWebServerRequest *request) { - // make response - auto *response = new AsyncJsonResponse(); - auto& doc = response->getRoot(); - - auto docBuild = doc[S_BUILD].to(); - docBuild[S_VERSION] = BUILD_VERSION; - docBuild[S_COMMIT] = BUILD_COMMIT; - docBuild[S_DATE] = __DATE__ " " __TIME__; - docBuild[S_ENV] = BUILD_ENV; - docBuild[S_CORE] = ESP.getCoreVersion(); - docBuild[S_SDK] = ESP.getSdkVersion(); - - auto docHeap = doc[S_HEAP].to(); - docHeap[S_TOTAL] = getTotalHeap(); - docHeap[S_FREE] = getFreeHeap(); - docHeap[S_MIN_FREE] = getFreeHeap(true); - docHeap[S_MAX_FREE_BLOCK] = getMaxFreeBlockHeap(); - docHeap[S_MIN_MAX_FREE_BLOCK] = getMaxFreeBlockHeap(true); - - auto docChip = doc[S_CHIP].to(); - docChip[S_MODEL] = ESP.getChipModel(); - docChip[S_REV] = ESP.getChipRevision(); - docChip[S_CORES] = ESP.getChipCores(); - docChip[S_FREQ] = ESP.getCpuFreqMHz(); - - auto docFlash = doc[S_FLASH].to(); - docFlash[S_SIZE] = ESP.getFlashChipSize(); - docFlash[S_REAL_SIZE] = docFlash[S_SIZE]; - - auto reason = esp_reset_reason(); - if (reason != ESP_RST_UNKNOWN && reason != ESP_RST_POWERON && reason != ESP_RST_SW) { - auto docCrash = doc[S_CRASH].to(); - docCrash[S_REASON] = getResetReason(); - docCrash[S_CORE] = CrashRecorder::ext.core; - docCrash[S_HEAP] = CrashRecorder::ext.heap; - docCrash[S_UPTIME] = CrashRecorder::ext.uptime; - - if (CrashRecorder::backtrace.length > 0 && CrashRecorder::backtrace.length <= CrashRecorder::backtraceMaxLength) { - String backtraceStr; - arr2str(backtraceStr, CrashRecorder::backtrace.data, CrashRecorder::backtrace.length); - docCrash[S_BACKTRACE][S_DATA] = backtraceStr; - docCrash[S_BACKTRACE][S_CONTINUES] = CrashRecorder::backtrace.continues; - } - - if (CrashRecorder::epc.length > 0 && CrashRecorder::epc.length <= CrashRecorder::epcMaxLength) { - String epcStr; - arr2str(epcStr, CrashRecorder::epc.data, CrashRecorder::epc.length); - docCrash[S_EPC] = epcStr; - } - } - char filename[64]; - getFilename(filename, sizeof(filename), "debug"); - - char contentDispositionValue[128]; - snprintf( - contentDispositionValue, - sizeof(contentDispositionValue), - "attachment; filename=\"%s\"", - filename - ); - - // send response - response->addHeader("Content-Disposition", contentDispositionValue); - response->setLength(); - request->send(response); - }).addMiddleware(&authMiddleware); - - - // not found - this->webServer->onNotFound([this](AsyncWebServerRequest *request) { - const auto& url = request->url(); - Log.straceln(L_PORTAL_WEBSERVER, "Page not found, uri: %s", url.c_str()); - - if (url.equals("/")) { - request->send(200, "text/plain", "The file system is not flashed!"); - - } else if (network->isApEnabled()) { - this->onCaptivePortal(request); - - } else { - request->send(404, "text/plain", "Page not found"); - } - }); - - this->webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE); - this->webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE); - this->webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE); - } - - void loop() { - // web server - if (!this->stateWebServer() && (network->isApEnabled() || network->isConnected()) && millis() - this->webServerChangeState >= this->changeStateInterval) { - this->startWebServer(); - Log.straceln(L_PORTAL_WEBSERVER, "Started: AP up or STA connected"); - - // Enabling mDNS - if (!this->mDnsState && settings.portal.mdns) { - if (MDNS.begin(networkSettings.hostname)) { - MDNS.addService("http", "tcp", 80); - this->mDnsState = true; - - Log.straceln(L_PORTAL_WEBSERVER, "mDNS enabled and service added"); - } - } - - } else if (this->stateWebServer() && !network->isApEnabled() && !network->isStaEnabled()) { - this->stopWebServer(); - Log.straceln(L_PORTAL_WEBSERVER, "Stopped: AP and STA down"); - - // Disabling mDNS - if (this->mDnsState) { - MDNS.end(); - this->mDnsState = false; - - Log.straceln(L_PORTAL_WEBSERVER, "mDNS disabled"); - } - } - - // Disabling mDNS if disabled in settings - if (this->mDnsState && !settings.portal.mdns) { - MDNS.end(); - this->mDnsState = false; - - Log.straceln(L_PORTAL_WEBSERVER, "mDNS disabled"); - } - - // dns server - if (!this->stateDnsServer() && !network->isConnected() && network->isApEnabled() && this->stateWebServer()) { - this->startDnsServer(); - Log.straceln(L_PORTAL_DNSSERVER, "Started: AP up"); - - } else if (this->stateDnsServer() && (network->isConnected() || !network->isApEnabled() || !this->stateWebServer())) { - this->stopDnsServer(); - Log.straceln(L_PORTAL_DNSSERVER, "Stopped: AP down/STA connected"); - } - - if (this->stateDnsServer()) { - this->dnsServer->processNextRequest(); - } - - if (!this->stateDnsServer()) { - this->delay(250); - } - } - - void onCaptivePortal(AsyncWebServerRequest *request) { - const auto& url = request->url(); - - if (url.equals("/connecttest.txt")) { - request->redirect("http://logout.net", 302); - - Log.straceln(L_PORTAL_CAPTIVE, "Redirect to http://logout.net with 302 code"); - - } else if (url.equals("/wpad.dat")) { - request->send(404); - - Log.straceln(L_PORTAL_CAPTIVE, "Send empty page with 404 code"); - - } else if (url.equals("/success.txt")) { - request->send(200); - - Log.straceln(L_PORTAL_CAPTIVE, "Send empty page with 200 code"); - - } else { - String portalUrl = "http://"; - portalUrl += network->getApIp().toString().c_str(); - portalUrl += '/'; - - request->redirect(portalUrl, 302); - - Log.straceln(L_PORTAL_CAPTIVE, "Redirect to portal page with 302 code"); - } - } - - bool stateWebServer() { - return this->webServerEnabled; - } - - void startWebServer() { - if (this->stateWebServer()) { - return; - } - - this->webServer->begin(); - this->webServerEnabled = true; - this->webServerChangeState = millis(); - } - - void stopWebServer() { - if (!this->stateWebServer()) { - return; - } - - this->webServer->end(); - this->webServerEnabled = false; - this->webServerChangeState = millis(); - } - - bool stateDnsServer() { - return this->dnsServerEnabled; - } - - void startDnsServer() { - if (this->stateDnsServer()) { - return; - } - - this->dnsServer->start(53, "*", network->getApIp()); - this->dnsServerEnabled = true; - } - - void stopDnsServer() { - if (!this->stateDnsServer()) { - return; - } - - //this->dnsServer->processNextRequest(); - this->dnsServer->stop(); - this->dnsServerEnabled = false; - } - - static bool isAuthenticationRequired() { - return !network->isApEnabled() && settings.portal.auth && strlen(settings.portal.password); - } - - static void getFilename(char* filename, size_t maxSizeFilename, const char* type) { - const time_t now = time(nullptr); - - tm localNow {}; - localtime_r(&now, &localNow); - - char localNowValue[20]; - strftime(localNowValue, sizeof(localNowValue), "%Y-%m-%d-%H-%M-%S", &localNow); - - snprintf(filename, maxSizeFilename, "%s_%s_%s.json", networkSettings.hostname, localNowValue, type); - } -}; diff --git a/src/RegulatorTask.h b/src/RegulatorTask.h deleted file mode 100644 index 7e47dca..0000000 --- a/src/RegulatorTask.h +++ /dev/null @@ -1,255 +0,0 @@ -#include - -GyverPID pidRegulator(0, 0, 0); - - -class RegulatorTask : public LeanTask { -public: - explicit RegulatorTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) {} - -protected: - float prevHeatingTarget = 0.0f; - float prevEtResult = 0.0f; - float prevPidResult = 0.0f; - - bool indoorSensorsConnected = false; - //bool outdoorSensorsConnected = false; - - const char* getTaskName() override { - return "Regulator"; - } - - uint32_t getTaskStackSize() override { - return 5000; - } - - /*BaseType_t getTaskCore() override { - return 1; - }*/ - - int getTaskPriority() override { - return 4; - } - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - this->indoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP); - //this->outdoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP); - - if (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC) { - vars.master.heating.indoorTempControl = true; - vars.master.heating.minTemp = THERMOSTAT_INDOOR_MIN_TEMP; - vars.master.heating.maxTemp = THERMOSTAT_INDOOR_MAX_TEMP; - - } else { - vars.master.heating.indoorTempControl = false; - vars.master.heating.minTemp = settings.heating.minTemp; - vars.master.heating.maxTemp = settings.heating.maxTemp; - } - - if (!settings.pid.enabled && fabsf(pidRegulator.integral) > 0.01f) { - pidRegulator.integral = 0.0f; - - Log.sinfoln(L_REGULATOR_PID, "Integral sum has been reset"); - } - - this->turbo(); - this->hysteresis(); - - vars.master.heating.targetTemp = settings.heating.target; - vars.master.heating.setpointTemp = roundf(constrain( - this->getHeatingSetpointTemp(), - this->getHeatingMinSetpointTemp(), - this->getHeatingMaxSetpointTemp() - ), 0); - - Sensors::setValueByType( - Sensors::Type::HEATING_SETPOINT_TEMP, vars.master.heating.setpointTemp, - Sensors::ValueType::PRIMARY, true, true - ); - } - - void turbo() { - if (settings.heating.turbo) { - if (!settings.heating.enabled || vars.emergency.state || !this->indoorSensorsConnected) { - settings.heating.turbo = false; - - } else if (!settings.pid.enabled && !settings.equitherm.enabled) { - settings.heating.turbo = false; - - } else if (fabsf(settings.heating.target - vars.master.heating.indoorTemp) <= 1.0f) { - settings.heating.turbo = false; - } - - if (!settings.heating.turbo) { - Log.sinfoln(L_REGULATOR, "Turbo mode auto disabled"); - } - } - } - - void hysteresis() { - bool useHyst = false; - if (settings.heating.hysteresis.enabled && this->indoorSensorsConnected) { - useHyst = settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC; - } - - if (useHyst) { - if (!vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target + 0.0001f >= settings.heating.hysteresis.value) { - vars.master.heating.blocking = true; - - } else if (vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target - 0.0001f <= -(settings.heating.hysteresis.value)) { - vars.master.heating.blocking = false; - } - - } else if (vars.master.heating.blocking) { - vars.master.heating.blocking = false; - } - } - - inline float getHeatingMinSetpointTemp() { - return settings.opentherm.options.nativeOTC - ? vars.master.heating.minTemp - : settings.heating.minTemp; - } - - inline float getHeatingMaxSetpointTemp() { - return settings.opentherm.options.nativeOTC - ? vars.master.heating.maxTemp - : settings.heating.maxTemp; - } - - float getHeatingSetpointTemp() { - float newTemp = 0; - - if (fabsf(prevHeatingTarget - settings.heating.target) > 0.0001f) { - prevHeatingTarget = settings.heating.target; - Log.sinfoln(L_REGULATOR, "New target: %.2f", settings.heating.target); - - /*if (settings.pid.enabled) { - pidRegulator.integral = 0.0f; - Log.sinfoln(L_REGULATOR_PID, "Integral sum has been reset"); - }*/ - } - - if (vars.emergency.state) { - return settings.emergency.target; - - } else if (settings.opentherm.options.nativeOTC) { - return settings.heating.target; - - } else if (!settings.equitherm.enabled && !settings.pid.enabled) { - return settings.heating.target; - } - - // if use equitherm - if (settings.equitherm.enabled) { - float tempDelta = settings.heating.target - vars.master.heating.outdoorTemp; - float maxPoint = settings.heating.target - ( - settings.heating.maxTemp - settings.heating.target - ) / settings.equitherm.slope; - - float sf = (settings.heating.maxTemp - settings.heating.target) / pow( - settings.heating.target - maxPoint, - 1.0f / settings.equitherm.exponent - ); - float etResult = settings.heating.target + settings.equitherm.shift + sf * ( - tempDelta >= 0 - ? pow(tempDelta, 1.0f / settings.equitherm.exponent) - : -(pow(-(tempDelta), 1.0f / settings.equitherm.exponent)) - ); - - // add diff - if (this->indoorSensorsConnected && !settings.pid.enabled && !settings.heating.turbo) { - etResult += constrain( - settings.heating.target - vars.master.heating.indoorTemp, - -3.0f, - 3.0f - ) * settings.equitherm.targetDiffFactor; - } - - // limit - etResult = constrain(etResult, settings.heating.minTemp, settings.heating.maxTemp); - - if (fabsf(prevEtResult - etResult) > 0.09f) { - prevEtResult = etResult; - newTemp += etResult; - - Log.sinfoln(L_REGULATOR_EQUITHERM, "New result: %.2f", etResult); - - } else { - newTemp += prevEtResult; - } - } - - // if use pid - if (settings.pid.enabled) { - //if (vars.parameters.heatingEnabled) { - if (settings.heating.enabled && this->indoorSensorsConnected) { - pidRegulator.Kp = settings.heating.turbo ? 0.0f : settings.pid.p_factor; - pidRegulator.Ki = settings.pid.i_factor; - pidRegulator.Kd = settings.pid.d_factor; - - pidRegulator.setLimits(settings.pid.minTemp, settings.pid.maxTemp); - pidRegulator.setDt(settings.pid.dt * 1000u); - pidRegulator.input = vars.master.heating.indoorTemp; - pidRegulator.setpoint = settings.heating.target; - - /*if (fabsf(pidRegulator.Ki - settings.pid.i_factor) >= 0.0001f) { - pidRegulator.Ki = settings.pid.i_factor; - pidRegulator.integral = 0.0f; - pidRegulator.getResultNow(); - - Log.sinfoln(L_REGULATOR_PID, "Integral sum has been reset"); - }*/ - - float error = pidRegulator.setpoint - pidRegulator.input; - bool hasDeadband = settings.pid.deadband.enabled - && (error > -(settings.pid.deadband.thresholdHigh)) - && (error < settings.pid.deadband.thresholdLow); - - if (hasDeadband) { - pidRegulator.Kp *= settings.pid.deadband.p_multiplier; - pidRegulator.Ki *= settings.pid.deadband.i_multiplier; - pidRegulator.Kd *= settings.pid.deadband.d_multiplier; - } - - float pidResult = pidRegulator.getResultTimer(); - if (fabsf(prevPidResult - pidResult) > 0.09f) { - prevPidResult = pidResult; - newTemp += pidResult; - - Log.sinfoln(L_REGULATOR_PID, "New result: %.2f", pidResult); - Log.straceln(L_REGULATOR_PID, "Integral: %.2f", pidRegulator.integral); - - } else { - newTemp += prevPidResult; - } - - } else { - newTemp += prevPidResult; - } - } - - // Turbo mode - if (settings.heating.turbo && (settings.equitherm.enabled || settings.pid.enabled)) { - newTemp += constrain( - settings.heating.target - vars.master.heating.indoorTemp, - -3.0f, - 3.0f - ) * settings.heating.turboFactor; - } - - // If freezing, set temperature to no lower than low temp provided by freeze protection - if (vars.master.heating.freezing) { - newTemp = fmaxf( - newTemp, - static_cast(settings.heating.freezeProtection.lowTemp) - ); - } - - return newTemp; - } -}; diff --git a/src/Sensors.h b/src/Sensors.h deleted file mode 100644 index f67a8aa..0000000 --- a/src/Sensors.h +++ /dev/null @@ -1,540 +0,0 @@ -#pragma once -#include -#include - -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]; - 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 activityTime = 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; - - - static Settings* settings; - static Result* results; - - static inline void setMaxSensors(uint8_t value) { - maxSensors = value; - } - - static inline uint8_t getMaxSensors() { - return maxSensors; - } - - static uint8_t getMaxSensorId() { - uint8_t maxSensors = getMaxSensors(); - return maxSensors > 1 ? (maxSensors - 1) : 0; - } - - template - static bool isValidSensorId(const T id) { - return id >= 0 && id <= getMaxSensorId(); - } - - static bool parseId(const char* value, uint8_t& sensorId) { - if (!isDigit(value)) { - return false; - } - - errno = 0; - const unsigned long parsed = strtoul(value, nullptr, 10); - if (errno == ERANGE || !isValidSensorId(parsed)) { - return false; - } - - sensorId = static_cast(parsed); - return true; - } - - static inline bool isValidValueId(const uint8_t id) { - return id >= (uint8_t) ValueType::TEMPERATURE && id <= (uint8_t) ValueType::RSSI; - } - - static bool hasEnabledAndValid(const uint8_t id) { - if (!isValidSensorId(id) || !settings[id].enabled) { - return false; - } - - if (settings[id].type == Type::NOT_CONFIGURED || settings[id].purpose == Purpose::NOT_CONFIGURED) { - return false; - } - - return true; - } - - static uint8_t getAmountByType(Type type, bool onlyEnabled = false) { - 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 int16_t getIdByName(const char* name) { - if (settings == nullptr) { - return -1; - } - - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - if (strcmp(settings[id].name, name) == 0) { - return id; - } - } - - return -1; - } - - static int16_t getIdByObjectId(const char* objectId) { - if (settings == nullptr) { - return -1; - } - - String refObjectId; - for (uint8_t id = 0; id <= getMaxSensorId(); id++) { - Sensors::makeObjectId(refObjectId, settings[id].name); - if (refObjectId.equals(objectId)) { - return id; - } - } - - return -1; - } - - static bool setValueById(const uint8_t sensorId, float value, const ValueType valueType, const bool updateActivityTime = false, const bool markConnected = false) { - if (settings == nullptr || results == nullptr) { - return false; - } - - uint8_t valueId = (uint8_t) valueType; - if (!isValidSensorId(sensorId) || !isValidValueId(valueId)) { - return false; - } - - auto& sSensor = settings[sensorId]; - auto& rSensor = results[sensorId]; - - float compensatedValue = value; - if (sSensor.type == Type::HEATING_SETPOINT_TEMP || sSensor.type == Type::MANUAL) { - rSensor.values[valueId] = compensatedValue; - - } else { - if (valueType == ValueType::PRIMARY) { - if (fabsf(sSensor.factor) > 0.001f) { - compensatedValue *= sSensor.factor; - } - - if (fabsf(sSensor.offset) > 0.001f) { - compensatedValue += sSensor.offset; - } - - } else if (valueType == ValueType::RSSI) { - if (sSensor.type == Type::BLUETOOTH) { - rSensor.signalQuality = Sensors::bluetoothRssiToQuality(value); - } - } - - if (sSensor.filtering && fabsf(rSensor.values[valueId]) >= 0.1f) { - rSensor.values[valueId] += (compensatedValue - rSensor.values[valueId]) * sSensor.filteringFactor; - - } else { - rSensor.values[valueId] = compensatedValue; - } - } - - if (updateActivityTime) { - rSensor.activityTime = millis(); - } - - if (markConnected && !rSensor.connected) { - rSensor.connected = true; - - Log.snoticeln( - L_SENSORS, "#%hhu '%s' new status: CONNECTED", - sensorId, sSensor.name - ); - } - - Log.snoticeln( - L_SENSORS, "#%hhu '%s' new value %hhu: %.2f, compensated: %.2f, raw: %.2f", - sensorId, sSensor.name, valueId, rSensor.values[valueId], compensatedValue, value - ); - - return true; - } - - static uint8_t setValueByType(Type type, float value, const ValueType valueType, const bool updateActivityTime = false, const bool markConnected = false) { - if (settings == nullptr) { - return 0; - } - - uint8_t updated = 0; - - // read sensors data for current instance - for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) { - auto& sSensor = settings[sensorId]; - - // only target & valid sensors - if (!sSensor.enabled || sSensor.type != type) { - continue; - } - - if (setValueById(sensorId, value, valueType, updateActivityTime, markConnected)) { - updated++; - } - } - - return updated; - } - - static bool getConnectionStatusById(const uint8_t sensorId) { - if (settings == nullptr || results == nullptr) { - return false; - } - - if (!isValidSensorId(sensorId)) { - return false; - } - - return results[sensorId].connected; - } - - static bool setConnectionStatusById(const uint8_t sensorId, const bool status, const bool updateActivityTime = true) { - if (settings == nullptr || results == nullptr) { - return false; - } - - if (!isValidSensorId(sensorId)) { - return false; - } - - auto& sSensor = settings[sensorId]; - auto& rSensor = results[sensorId]; - - if (rSensor.connected != status) { - Log.snoticeln( - L_SENSORS, "#%hhu '%s' new status: %s", - sensorId, sSensor.name, status ? "CONNECTED" : "DISCONNECTED" - ); - - rSensor.connected = status; - } - - if (updateActivityTime) { - rSensor.activityTime = millis(); - } - - return true; - } - - static uint8_t setConnectionStatusByType(Type type, const bool status, const bool updateActivityTime = true) { - if (settings == nullptr) { - return 0; - } - - uint8_t updated = 0; - - // read sensors data for current instance - for (uint8_t sensorId = 0; sensorId <= getMaxSensorId(); sensorId++) { - auto& sSensor = settings[sensorId]; - - // only target & valid sensors - if (!sSensor.enabled || sSensor.type != type) { - continue; - } - - if (setConnectionStatusById(sensorId, status, updateActivityTime)) { - updated++; - } - } - - return updated; - } - - static float getMeanValueByPurpose(Purpose purpose, const ValueType valueType, const AverageType avgType = AverageType::MEAN, const bool onlyConnected = true, const float defaultValue = NAN) { - 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) { - 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 String& cleanName(String& value, char space = ' ') { - // only valid symbols - for (size_t pos = 0; pos < value.length(); pos++) { - char symbol = value.charAt(pos); - - // 0..9 - if (symbol >= 48 && symbol <= 57) { - continue; - } - - // A..Z - if (symbol >= 65 && symbol <= 90) { - continue; - } - - // a..z - if (symbol >= 97 && symbol <= 122) { - continue; - } - - // _- - if (symbol == 95 || symbol == 45 || symbol == space) { - continue; - } - - value.setCharAt(pos, space); - } - - value.trim(); - - return value; - } - - template - static String cleanName(T value, char space = ' ') { - String res = value; - return cleanName(res, space); - } - - template - static String& makeObjectId(String& res, T value, char separator = '_') { - res = value; - cleanName(res); - res.toLowerCase(); - res.replace(' ', separator); - - return res; - } - - template - static String makeObjectId(T value, char separator = '_') { - String res; - makeObjectId(res, value, separator); - - return res; - } - - template - static String& makeObjectIdWithSuffix(String& res, TV value, TS suffix, char separator = '_') { - res.clear(); - makeObjectId(res, value, separator); - res += separator; - res += suffix; - - return res; - } - - template - static String makeObjectIdWithSuffix(TV value, TS suffix, char separator = '_') { - String res; - makeObjectIdWithSuffix(res, value, suffix, separator); - return res; - } - - template - static String& makeObjectIdWithPrefix(String& res, TV value, TP prefix, char separator = '_') { - res = prefix; - res += separator; - res += makeObjectId(value, separator).c_str(); - - return res; - } - - template - static String makeObjectIdWithPrefix(TV value, TP prefix, char separator = '_') { - String res; - return makeObjectIdWithPrefix(res, value, prefix, separator); - } - - static uint8_t bluetoothRssiToQuality(int rssi) { - return constrain(map(rssi, -110, -50, 0, 100), 0, 100);; - } - -private: - 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; - } -}; - -uint8_t Sensors::maxSensors = 0; -Sensors::Settings* Sensors::settings = nullptr; -Sensors::Result* Sensors::results = nullptr; diff --git a/src/SensorsTask.h b/src/SensorsTask.h deleted file mode 100644 index 120acb0..0000000 --- a/src/SensorsTask.h +++ /dev/null @@ -1,971 +0,0 @@ -#include -#include -#include -#include - -#if USE_BLE - #include -#endif - -extern FileData fsSensorsSettings; - -#if USE_BLE -class BluetoothScanCallbacks : public NimBLEScanCallbacks { -public: - void onDiscovered(const NimBLEAdvertisedDevice* device) override { - auto& deviceAddress = device->getAddress(); - - bool found = false; - uint8_t sensorId; - for (sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - if (!sSensor.enabled || sSensor.type != Sensors::Type::BLUETOOTH || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - const auto sensorAddress = NimBLEAddress(sSensor.address, deviceAddress.getType()); - if (sensorAddress.isNull() || sensorAddress != deviceAddress) { - continue; - } - - found = true; - break; - } - - if (!found) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - auto deviceName = device->getName(); - auto deviceRssi = device->getRSSI(); - - Log.sinfoln( - L_SENSORS_BLE, "Sensor #%hhu '%s': discovered device %s, name: %s, RSSI: %hhd", - sensorId, sSensor.name, - deviceAddress.toString().c_str(), deviceName.c_str(), deviceRssi - ); - - if (!device->haveServiceData()) { - Log.swarningln( - L_SENSORS_BLE, "Sensor #%hhu '%s': not found service data!", - sensorId, sSensor.name - ); - return; - } - - auto serviceDataCount = device->getServiceDataCount(); - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu '%s': found %hhu service data", - sensorId, sSensor.name, serviceDataCount - ); - - if (parseAtcData(device, sensorId) || parsePvvxData(device, sensorId) || parseBTHomeData(device, sensorId)) { - // update rssi - Sensors::setValueById(sensorId, deviceRssi, Sensors::ValueType::RSSI, false, false); - - } else { - Log.swarningln( - L_SENSORS_BLE, "Sensor #%hhu '%s': unsupported data format!", - sensorId, sSensor.name - ); - } - } - - static bool parseAtcData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { - NimBLEUUID serviceUuid(static_cast(0x181A)); - - auto serviceData = device->getServiceData(serviceUuid); - if (!serviceData.size()) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: not found ATC1441 data", - sensorId, serviceUuid.toString().c_str() - ); - return false; - - } else if (serviceData.size() != 13) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: not in ATC1441 format", - sensorId, serviceUuid.toString().c_str() - ); - return false; - } - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: found ATC1441 format", - sensorId, serviceUuid.toString().c_str() - ); - - // Temperature (2 bytes, big-endian) - float temperature = ( - (static_cast(serviceData[6]) << 8) | static_cast(serviceData[7]) - ) * 0.1f; - Sensors::setValueById(sensorId, temperature, Sensors::ValueType::TEMPERATURE, true, true); - - // Humidity (1 byte) - float humidity = static_cast(serviceData[8]); - Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); - - // Battery level (1 byte) - uint8_t batteryLevel = static_cast(serviceData[9]); - Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); - - // Battery mV (2 bytes, big-endian) - uint16_t batteryMv = (static_cast(serviceData[10]) << 8) | static_cast(serviceData[11]); - - // Log - Log.snoticeln( - L_SENSORS_BLE, - "Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu", - sensorId, temperature, humidity, batteryMv, batteryLevel - ); - - return true; - } - - static bool parsePvvxData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { - NimBLEUUID serviceUuid(static_cast(0x181A)); - - auto serviceData = device->getServiceData(serviceUuid); - if (!serviceData.size()) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: not found PVVX data", - sensorId, serviceUuid.toString().c_str() - ); - return false; - - } else if (serviceData.size() != 15) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: not in PVVX format", - sensorId, serviceUuid.toString().c_str() - ); - return false; - } - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: found PVVX format", - sensorId, serviceUuid.toString().c_str() - ); - - // Temperature (2 bytes, little-endian) - float temperature = ( - (static_cast(serviceData[7]) << 8) | static_cast(serviceData[6]) - ) * 0.01f; - Sensors::setValueById(sensorId, temperature, Sensors::ValueType::TEMPERATURE, true, true); - - // Humidity (2 bytes, little-endian) - float humidity = ( - (static_cast(serviceData[9]) << 8) | static_cast(serviceData[8]) - ) * 0.01f; - Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); - - // Battery level (1 byte) - uint8_t batteryLevel = static_cast(serviceData[12]); - Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); - - // Battery mV (2 bytes, little-endian) - uint16_t batteryMv = (static_cast(serviceData[11]) << 8) | static_cast(serviceData[10]); - - // Log - Log.snoticeln( - L_SENSORS_BLE, - "Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu", - sensorId, temperature, humidity, batteryMv, batteryLevel - ); - - return true; - } - - static bool parseBTHomeData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { - NimBLEUUID serviceUuid(static_cast(0xFCD2)); - - auto serviceData = device->getServiceData(serviceUuid); - if (!serviceData.size()) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: not found BTHome data", - sensorId, serviceUuid.toString().c_str() - ); - return false; - - } else if ((serviceData[0] & 0xE0) != 0x40) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome version", - sensorId, serviceUuid.toString().c_str() - ); - return false; - - } else if ((serviceData[0] & 0x01) != 0) { - Log.straceln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome encrypted data", - sensorId, serviceUuid.toString().c_str() - ); - return false; - } - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, service %s: found BTHome format", - sensorId, serviceUuid.toString().c_str() - ); - - bool foundData = false; - size_t serviceDataPos = 0; - while (serviceDataPos < serviceData.size()) { - uint8_t objectId = serviceData[serviceDataPos++]; - - switch (objectId) { - // Packet ID (1 byte) - case 0x00: - serviceDataPos += 1; - break; - - // Battery (1 byte) - case 0x01: { - if (serviceDataPos + 1 > serviceData.size()) { - break; - } - - uint8_t batteryLevel = static_cast(serviceData[serviceDataPos]); - Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); - serviceDataPos += 1; - foundData = true; - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, received battery level: %hhu", - sensorId, batteryLevel - ); - break; - } - - // Temperature (2 bytes, little-endian) - case 0x02: { - if (serviceDataPos + 2 > serviceData.size()) { - break; - } - - int16_t rawTemp = (static_cast(serviceData[serviceDataPos + 1]) << 8) - | static_cast(serviceData[serviceDataPos]); - float temperature = static_cast(rawTemp) * 0.01f; - Sensors::setValueById(sensorId, temperature, Sensors::ValueType::TEMPERATURE, true, true); - serviceDataPos += 2; - foundData = true; - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, received temp: %.2f", - sensorId, temperature - ); - break; - } - - // Humidity (2 bytes, little-endian) - case 0x03: { - if (serviceDataPos + 2 > serviceData.size()) { - break; - } - - uint16_t rawHumidity = (static_cast(serviceData[serviceDataPos + 1]) << 8) - | static_cast(serviceData[serviceDataPos]); - float humidity = static_cast(rawHumidity) * 0.01f; - Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); - serviceDataPos += 2; - foundData = true; - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, received humidity: %.2f", - sensorId, humidity - ); - break; - } - - // Voltage (2 bytes, little-endian) - case 0x0C: { - if (serviceDataPos + 2 > serviceData.size()) { - break; - } - - uint16_t batteryMv = (static_cast(serviceData[serviceDataPos + 1]) << 8) - | static_cast(serviceData[serviceDataPos]); - serviceDataPos += 2; - foundData = true; - - Log.snoticeln( - L_SENSORS_BLE, "Sensor #%hhu, received battery voltage: %hu", - sensorId, batteryMv - ); - break; - } - } - } - - return foundData; - } -}; -#endif - -class SensorsTask : public LeanTask { -public: - explicit SensorsTask(bool _enabled = false, unsigned long _interval = 0) : LeanTask(_enabled, _interval) { - this->gpioLastPollingTime.reserve(2); - - // OneWire - this->owInstances.reserve(2); - this->dallasInstances.reserve(2); - this->dallasSearchTime.reserve(2); - this->dallasPolling.reserve(2); - - #if USE_BLE - this->pBLEScanCallbacks = new BluetoothScanCallbacks(); - #endif - } - - ~SensorsTask() { - this->gpioLastPollingTime.clear(); - - // OneWire - this->dallasInstances.clear(); - this->owInstances.clear(); - this->dallasSearchTime.clear(); - this->dallasPolling.clear(); - - #if USE_BLE - delete this->pBLEScanCallbacks; - #endif - } - -protected: - const unsigned int wiredDisconnectTimeout = 180000u; - const unsigned int wirelessDisconnectTimeout = 600000u; - const unsigned short dallasSearchInterval = 60000u; - const unsigned short dallasPollingInterval = 10000u; - const unsigned short dhtPollingInterval = 15000; - const unsigned short globalPollingInterval = 15000u; - - std::unordered_map gpioLastPollingTime; - - // OneWire - std::unordered_map owInstances; - std::unordered_map dallasInstances; - std::unordered_map dallasSearchTime; - std::unordered_map dallasPolling; - - // DHT - DHT dhtInstance; - bool dhtIsPolling = false; - - #if USE_BLE - NimBLEScan* pBLEScan = nullptr; - BluetoothScanCallbacks* pBLEScanCallbacks = nullptr; - bool activeScanBle = false; - #endif - unsigned long globalLastPollingTime = 0; - - const char* getTaskName() override { - return "Sensors"; - } - - uint32_t getTaskStackSize() override { - return 7500; - } - - BaseType_t getTaskCore() override { - // https://github.com/h2zero/NimBLE-Arduino/issues/676 - #if USE_BLE && defined(CONFIG_BT_NIMBLE_PINNED_TO_CORE) - return CONFIG_BT_NIMBLE_PINNED_TO_CORE; - #else - return tskNO_AFFINITY; - #endif - } - - int getTaskPriority() override { - return 4; - } - - void loop() { - if (vars.states.restarting || vars.states.upgrading) { - return; - } - - if (isPollingDallasSensors()) { - pollingDallasSensors(false); - this->yield(); - } - - pollingDhtSensors(); - this->yield(); - - if (millis() - this->globalLastPollingTime > this->globalPollingInterval) { - cleanDallasInstances(); - makeDallasInstances(); - this->yield(); - - searchDallasSensors(); - fillingAddressesDallasSensors(); - this->yield(); - - pollingDallasSensors(); - this->yield(); - - pollingNtcSensors(); - this->yield(); - - #if USE_BLE - scanBleSensors(); - this->yield(); - #endif - - this->globalLastPollingTime = millis(); - } - - updateConnectionStatus(); - updateMasterValues(); - } - - void updateMasterValues() { - vars.master.heating.indoorTemp = Sensors::getMeanValueByPurpose( - Sensors::Purpose::INDOOR_TEMP, - Sensors::ValueType::PRIMARY, - settings.heating.indoorTempAvgType, - true, - 0.0f - ); - vars.master.heating.outdoorTemp = Sensors::getMeanValueByPurpose( - Sensors::Purpose::OUTDOOR_TEMP, - Sensors::ValueType::PRIMARY, - settings.heating.outdoorTempAvgType, - true, - 0.0f - ); - - vars.master.heating.currentTemp = Sensors::getMeanValueByPurpose( - Sensors::Purpose::HEATING_TEMP, - Sensors::ValueType::PRIMARY, - Sensors::AverageType::MEAN, - true, - 0.0f - ); - vars.master.heating.returnTemp = Sensors::getMeanValueByPurpose( - Sensors::Purpose::HEATING_RETURN_TEMP, - Sensors::ValueType::PRIMARY, - Sensors::AverageType::MEAN, - true, - 0.0f - ); - - vars.master.dhw.currentTemp = Sensors::getMeanValueByPurpose( - Sensors::Purpose::DHW_TEMP, - Sensors::ValueType::PRIMARY, - Sensors::AverageType::MEAN, - true, - 0.0f - ); - vars.master.dhw.returnTemp = Sensors::getMeanValueByPurpose( - Sensors::Purpose::DHW_RETURN_TEMP, - Sensors::ValueType::PRIMARY, - Sensors::AverageType::MEAN, - true, - 0.0f - ); - } - - void makeDallasInstances() { - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - - } else if (this->dallasInstances.count(sSensor.gpio)) { - // no need to make instances - continue; - } - - auto& owInstance = this->owInstances[sSensor.gpio]; - owInstance.begin(sSensor.gpio); - owInstance.reset(); - - this->dallasSearchTime[sSensor.gpio] = 0; - this->dallasPolling[sSensor.gpio] = false; - this->gpioLastPollingTime[sSensor.gpio] = 0; - - auto& instance = this->dallasInstances[sSensor.gpio]; - instance.setOneWire(&owInstance); - instance.setWaitForConversion(false); - - Log.sinfoln(L_SENSORS_DALLAS, "Started on GPIO %hhu", sSensor.gpio); - } - } - - void cleanDallasInstances() { - // for (auto& [gpio, instance] : this->dallasInstances) { - auto it = this->dallasInstances.begin(); - while (it != this->dallasInstances.end()) { - auto gpio = it->first; - bool instanceUsed = false; - - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - if (Sensors::settings[sensorId].gpio == gpio) { - instanceUsed = true; - break; - } - } - - if (!instanceUsed) { - it = this->dallasInstances.erase(it); - this->owInstances.erase(gpio); - this->dallasSearchTime.erase(gpio); - this->dallasPolling.erase(gpio); - this->gpioLastPollingTime.erase(gpio); - - Log.sinfoln(L_SENSORS_DALLAS, "Stopped on GPIO %hhu", gpio); - continue; - } - - it++; - } - } - - void searchDallasSensors() { - // search sensors on bus - for (auto& [gpio, instance] : this->dallasInstances) { - // do not search if polling! - if (this->dallasPolling[gpio]) { - continue; - } - - if (millis() - this->dallasSearchTime[gpio] < this->dallasSearchInterval) { - continue; - } - - this->dallasSearchTime[gpio] = millis(); - this->owInstances[gpio].reset(); - instance.begin(); - - Log.straceln( - L_SENSORS_DALLAS, - "GPIO %hhu, devices on bus: %hhu, DS18* devices: %hhu", - gpio, instance.getDeviceCount(), instance.getDS18Count() - ); - } - } - - void fillingAddressesDallasSensors() { - // check & filling sensors address - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - - } else if (!this->dallasInstances.count(sSensor.gpio)) { - continue; - } - - // do nothing if address not empty - if (!isEmptyAddress(sSensor.address)) { - continue; - } - - // do nothing if polling - if (this->dallasPolling[sSensor.gpio]) { - continue; - } - - auto& instance = this->dallasInstances[sSensor.gpio]; - DeviceAddress devAddr; - for (uint8_t devId = 0; devId < instance.getDeviceCount(); devId++) { - if (!instance.getAddress(devAddr, devId)) { - continue; - } - - bool freeAddress = true; - - // checking address usage - for (uint8_t checkingSensorId = 0; checkingSensorId <= Sensors::getMaxSensorId(); checkingSensorId++) { - auto& sCheckingSensor = Sensors::settings[checkingSensorId]; - if (sCheckingSensor.type != Sensors::Type::DALLAS_TEMP || checkingSensorId == sensorId) { - continue; - } - - if (sCheckingSensor.gpio != sSensor.gpio || isEmptyAddress(sCheckingSensor.address)) { - continue; - } - - if (isEqualAddress(sCheckingSensor.address, devAddr)) { - freeAddress = false; - break; - } - } - - // address already in use - if (!freeAddress) { - continue; - } - - // set address - for (uint8_t i = 0; i < 8; i++) { - sSensor.address[i] = devAddr[i]; - } - - fsSensorsSettings.update(); - Log.straceln( - L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', set address: %hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX", - sSensor.gpio, sensorId, sSensor.name, - sSensor.address[0], sSensor.address[1], sSensor.address[2], sSensor.address[3], - sSensor.address[4], sSensor.address[5], sSensor.address[6], sSensor.address[7] - ); - - break; - } - } - } - - bool isPollingDallasSensors() { - for (auto& [gpio, instance] : this->dallasInstances) { - if (this->dallasPolling.count(gpio) && this->dallasPolling[gpio]) { - return true; - } - } - - return false; - } - - void pollingDallasSensors(bool newPolling = true) { - for (auto& [gpio, instance] : this->dallasInstances) { - unsigned long ts = millis(); - - if (this->dallasPolling[gpio]) { - unsigned long minPollingTime = instance.millisToWaitForConversion(12) * 2; - unsigned long estimatePollingTime = ts - this->gpioLastPollingTime[gpio]; - - // check conversion time - // isConversionComplete does not work with chinese clones! - if (estimatePollingTime < minPollingTime) { - continue; - } - - // read sensors data for current instance - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - // only target & valid sensors - if (!sSensor.enabled || sSensor.type != Sensors::Type::DALLAS_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - - } else if (sSensor.gpio != gpio || isEmptyAddress(sSensor.address)) { - continue; - } - - auto& rSensor = Sensors::results[sensorId]; - float value = instance.getTempC(sSensor.address); - if (value == DEVICE_DISCONNECTED_C) { - Log.swarningln( - L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s': failed receiving data", - sSensor.gpio, sensorId, sSensor.name - ); - - if (rSensor.signalQuality > 0) { - rSensor.signalQuality--; - } - - continue; - } - - Log.straceln( - L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', received data: %.2f", - sSensor.gpio, sensorId, sSensor.name, value - ); - - if (rSensor.signalQuality < 100) { - rSensor.signalQuality++; - } - - // set sensor value - Sensors::setValueById(sensorId, value, Sensors::ValueType::TEMPERATURE, true, true); - } - - // reset polling flag - this->dallasPolling[gpio] = false; - - } else if (newPolling) { - auto estimateLastPollingTime = ts - this->gpioLastPollingTime[gpio]; - - // check last polling time - if (estimateLastPollingTime < this->dallasPollingInterval) { - continue; - } - - // start polling - instance.setResolution(12); - instance.requestTemperatures(); - this->dallasPolling[gpio] = true; - this->gpioLastPollingTime[gpio] = ts; - - Log.straceln(L_SENSORS_DALLAS, "GPIO %hhu, polling...", gpio); - } - } - } - - void pollingDhtSensors() { - if (this->dhtIsPolling) { - // busy - return; - } - - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - if (sSensor.type != Sensors::Type::DHT11 && sSensor.type != Sensors::Type::DHT22) { - continue; - } - - if (this->gpioLastPollingTime.count(sSensor.gpio) && millis() - this->gpioLastPollingTime[sSensor.gpio] < this->dhtPollingInterval) { - continue; - } - - const auto sensorGpio = static_cast(sSensor.gpio); - if (this->dhtInstance.getGpio() != sensorGpio) { - this->dhtInstance.reset(); - this->dhtInstance.onData([this, sensorId](float humidity, float temperature) { - auto& sSensor = Sensors::settings[sensorId]; - - Log.straceln( - L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s', temp: %.2f, humidity: %.2f%%", - sSensor.gpio, sensorId, sSensor.name, temperature, humidity - ); - - // set temperature - Sensors::setValueById(sensorId, temperature, Sensors::ValueType::TEMPERATURE, true, true); - - // set humidity - Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); - - auto& rSensor = Sensors::results[sensorId]; - if (rSensor.signalQuality < 100) { - rSensor.signalQuality++; - } - - this->gpioLastPollingTime[sSensor.gpio] = millis(); - this->dhtIsPolling = false; - }); - - this->dhtInstance.onError([this, sensorId](DHT::Status status) { - auto& sSensor = Sensors::settings[sensorId]; - - Log.swarningln( - L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s': failed receiving data (err: %s)", - sSensor.gpio, sensorId, sSensor.name, DHT::statusToString(this->dhtInstance.getStatus()) - ); - - auto& rSensor = Sensors::results[sensorId]; - if (rSensor.signalQuality > 0) { - rSensor.signalQuality--; - } - - this->gpioLastPollingTime[sSensor.gpio] = millis(); - this->dhtIsPolling = false; - }); - - DHT::Type sType = DHT::Type::DHT22; - if (sSensor.type == Sensors::Type::DHT11) { - sType = DHT::Type::DHT11; - - } else if (sSensor.type == Sensors::Type::DHT22) { - sType = DHT::Type::DHT22; - } - - if (this->dhtInstance.setup(sensorGpio, sType)) { - Log.sinfoln(L_SENSORS_DHT, "Started on GPIO %hhu", sSensor.gpio); - - } else { - Log.swarningln( - L_SENSORS_DHT, "Failed to start on GPIO %hhu (err: %s)", - sSensor.gpio, DHT::statusToString(this->dhtInstance.getStatus()) - ); - } - } - - this->dhtIsPolling = this->dhtInstance.poll(); - - break; - } - } - - void pollingNtcSensors() { - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - - if (!sSensor.enabled || sSensor.type != Sensors::Type::NTC_10K_TEMP || sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - continue; - } - - const auto value = analogReadMilliVolts(sSensor.gpio); - - if (value < DEFAULT_NTC_VLOW_TRESHOLD || value > DEFAULT_NTC_VHIGH_TRESHOLD) { - if (Sensors::getConnectionStatusById(sensorId)) { - Sensors::setConnectionStatusById(sensorId, false, false); - } - - Log.swarningln( - L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', voltage is out of threshold: %.3f", - sSensor.gpio, sensorId, sSensor.name, (value / 1000.0f) - ); - - continue; - } - - const float sensorResistance = value > 1 - ? DEFAULT_NTC_REF_RESISTANCE / (DEFAULT_NTC_VREF / static_cast(value) - 1.0f) - : 0.0f; - const float rawTemp = 1.0f / ( - 1.0f / (DEFAULT_NTC_NOMINAL_TEMP + 273.15f) + - log(sensorResistance / DEFAULT_NTC_NOMINAL_RESISTANCE) / DEFAULT_NTC_BETA_FACTOR - ) - 273.15f; - - Log.straceln( - L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', raw temp: %.2f, raw voltage: %.3f, raw resistance: %.2f", - sSensor.gpio, sensorId, sSensor.name, rawTemp, (value / 1000.0f), sensorResistance - ); - - // set temp - Sensors::setValueById(sensorId, rawTemp, Sensors::ValueType::TEMPERATURE, true, true); - } - } - - #if USE_BLE - void scanBleSensors() { - if (!Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)) { - if (NimBLEDevice::isInitialized()) { - if (this->pBLEScan != nullptr) { - if (this->pBLEScan->isScanning()) { - this->pBLEScan->stop(); - - } else { - this->pBLEScan = nullptr; - } - } - - if (this->pBLEScan == nullptr) { - if (NimBLEDevice::deinit(true)) { - Log.sinfoln(L_SENSORS_BLE, "Deinitialized"); - - } else { - Log.swarningln(L_SENSORS_BLE, "Unable to deinitialize!"); - } - } - } - - return; - } - - if (!NimBLEDevice::isInitialized() && millis() > 5000) { - if (NimBLEDevice::init(PROJECT_NAME)) { - Log.sinfoln(L_SENSORS_BLE, "Initialized"); - - #ifdef ESP_PWR_LVL_P20 - NimBLEDevice::setPower(ESP_PWR_LVL_P20); - #elifdef ESP_PWR_LVL_P9 - NimBLEDevice::setPower(ESP_PWR_LVL_P9); - #endif - - } else { - Log.swarningln(L_SENSORS_BLE, "Unable to initialize!"); - return; - } - } - - if (this->pBLEScan == nullptr) { - this->pBLEScan = NimBLEDevice::getScan(); - this->pBLEScan->setScanCallbacks(this->pBLEScanCallbacks); - #if MYNEWT_VAL(BLE_EXT_ADV) - this->pBLEScan->setPhy(NimBLEScan::Phy::SCAN_ALL); - #endif - this->pBLEScan->setDuplicateFilter(false); - this->pBLEScan->setMaxResults(0); - this->pBLEScan->setInterval(10000); - this->pBLEScan->setWindow(10000); - - Log.sinfoln(L_SENSORS_BLE, "Scanning initialized"); - } - - if (!this->pBLEScan->isScanning()) { - this->activeScanBle = !this->activeScanBle; - this->pBLEScan->setActiveScan(this->activeScanBle); - - if (this->pBLEScan->start(30000, false, false)) { - Log.sinfoln( - L_SENSORS_BLE, - "%s scanning started", - this->activeScanBle ? "Active" : "Passive" - ); - - } else { - Log.sinfoln(L_SENSORS_BLE, "Unable to start scanning"); - } - } - } - #endif - - void updateConnectionStatus() { - for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - - if (rSensor.connected && !sSensor.enabled) { - Sensors::setConnectionStatusById(sensorId, false, false); - - } else if (rSensor.connected && sSensor.type == Sensors::Type::NOT_CONFIGURED) { - Sensors::setConnectionStatusById(sensorId, false, false); - - } else if (rSensor.connected && sSensor.purpose == Sensors::Purpose::NOT_CONFIGURED) { - Sensors::setConnectionStatusById(sensorId, false, false); - - } else if (rSensor.connected) { - if (sSensor.type == Sensors::Type::MANUAL || sSensor.type == Sensors::Type::BLUETOOTH) { - if ((millis() - rSensor.activityTime) > this->wirelessDisconnectTimeout) { - Sensors::setConnectionStatusById(sensorId, false, false); - } - - } else if ((millis() - rSensor.activityTime) > this->wiredDisconnectTimeout) { - Sensors::setConnectionStatusById(sensorId, false, false); - } - } - } - } - - 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; - - for (uint8_t i = 0; i < length; i++) { - if (addr[i] != 0) { - result = false; - break; - } - } - - return result; - } -}; diff --git a/src/Settings.h b/src/Settings.h deleted file mode 100644 index 68be7a6..0000000 --- a/src/Settings.h +++ /dev/null @@ -1,448 +0,0 @@ -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; -} networkSettings; - -struct Settings { - struct { - uint8_t logLevel = 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; - } system; - - struct { - bool auth = false; - char login[13] = DEFAULT_PORTAL_LOGIN; - char password[33] = DEFAULT_PORTAL_PASSWORD; - bool mdns = true; - } portal; - - struct { - UnitSystem unitSystem = UnitSystem::METRIC; - 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; - } opentherm; - - struct { - 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; - } mqtt; - - struct { - float target = DEFAULT_HEATING_TARGET_TEMP; - unsigned short tresholdTime = 120; - } emergency; - - struct { - 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; - } heating; - - struct { - 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; - } dhw; - - struct { - 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; - } pid; - - struct { - bool enabled = false; - float slope = 0.7f; - float exponent = 1.3f; - float shift = 0.0f; - float targetDiffFactor = 2.0f; - } equitherm; - - struct { - 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; - } externalPump; - - struct { - 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; - } cascadeControl; - - char validationValue[8] = SETTINGS_VALID_VALUE; -} settings; - -Sensors::Settings sensorsSettings[SENSORS_AMOUNT] = { - { - false, - "Outdoor temp", - Sensors::Purpose::OUTDOOR_TEMP, - Sensors::Type::OT_OUTDOOR_TEMP, - DEFAULT_SENSOR_OUTDOOR_GPIO - }, - { - false, - "Indoor temp", - Sensors::Purpose::INDOOR_TEMP, - Sensors::Type::DALLAS_TEMP, - DEFAULT_SENSOR_INDOOR_GPIO - }, - { - true, - "Heating temp", - Sensors::Purpose::HEATING_TEMP, - Sensors::Type::OT_HEATING_TEMP, - }, - { - true, - "Heating return temp", - Sensors::Purpose::HEATING_RETURN_TEMP, - Sensors::Type::OT_HEATING_RETURN_TEMP, - }, - { - true, - "Heating setpoint temp", - Sensors::Purpose::TEMPERATURE, - Sensors::Type::HEATING_SETPOINT_TEMP, - }, - { - true, - "DHW temp", - Sensors::Purpose::DHW_TEMP, - Sensors::Type::OT_DHW_TEMP, - }, - { - true, - "DHW flow rate", - Sensors::Purpose::DHW_FLOW_RATE, - Sensors::Type::OT_DHW_FLOW_RATE, - }, - { - true, - "Exhaust temp", - Sensors::Purpose::EXHAUST_TEMP, - Sensors::Type::OT_EXHAUST_TEMP, - }, - { - true, - "Pressure", - Sensors::Purpose::PRESSURE, - Sensors::Type::OT_PRESSURE, - }, - { - true, - "Modulation level", - Sensors::Purpose::MODULATION_LEVEL, - Sensors::Type::OT_MODULATION_LEVEL, - }, - { - true, - "Power", - Sensors::Purpose::POWER, - Sensors::Type::OT_CURRENT_POWER, - } -}; - -struct Variables { - struct { - bool connected = false; - int8_t rssi = 0; - } network; - - struct { - bool connected = false; - } mqtt; - - 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 = 0; - uint8_t appVersion = 0; - float protocolVersion = 0.0f; - - 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 restart = false; - bool resetFault = false; - bool resetDiagnostic = false; - } actions; - - struct { - bool restarting = false; - bool upgrading = false; - } states; -} vars; diff --git a/src/config.cpp b/src/config.cpp new file mode 100644 index 0000000..ff32696 --- /dev/null +++ b/src/config.cpp @@ -0,0 +1,3513 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include +#include +#include +#include + +NetworkSettings networkSettings; +Settings settings; +Sensors::Settings sensorsSettings[SENSORS_AMOUNT] = { + { + false, + "Outdoor temp", + "outdoor_temp", + Sensors::Purpose::OUTDOOR_TEMP, + Sensors::Type::OT_OUTDOOR_TEMP, + DEFAULT_SENSOR_OUTDOOR_GPIO + }, + { + false, + "Indoor temp", + "indoor_temp", + Sensors::Purpose::INDOOR_TEMP, + Sensors::Type::DALLAS_TEMP, + DEFAULT_SENSOR_INDOOR_GPIO + }, + { + true, + "Heating temp", + "heating_temp", + Sensors::Purpose::HEATING_TEMP, + Sensors::Type::OT_HEATING_TEMP, + }, + { + true, + "Heating return temp", + "heating_return_temp", + Sensors::Purpose::HEATING_RETURN_TEMP, + Sensors::Type::OT_HEATING_RETURN_TEMP, + }, + { + true, + "Heating setpoint temp", + "heating_setpoint_temp", + Sensors::Purpose::TEMPERATURE, + Sensors::Type::HEATING_SETPOINT_TEMP, + }, + { + true, + "DHW temp", + "dhw_temp", + Sensors::Purpose::DHW_TEMP, + Sensors::Type::OT_DHW_TEMP, + }, + { + true, + "DHW flow rate", + "dhw_flow_rate", + Sensors::Purpose::DHW_FLOW_RATE, + Sensors::Type::OT_DHW_FLOW_RATE, + }, + { + true, + "Exhaust temp", + "exhaust_temp", + Sensors::Purpose::EXHAUST_TEMP, + Sensors::Type::OT_EXHAUST_TEMP, + }, + { + true, + "Pressure", + "pressure", + Sensors::Purpose::PRESSURE, + Sensors::Type::OT_PRESSURE, + }, + { + true, + "Modulation level", + "modulation_level", + Sensors::Purpose::MODULATION_LEVEL, + Sensors::Type::OT_MODULATION_LEVEL, + }, + { + true, + "Power", + "power", + Sensors::Purpose::POWER, + Sensors::Type::OT_CURRENT_POWER, + } +}; + +static FileData fsNetworkSettings(&LittleFS, "/network.conf", 'n', &networkSettings, sizeof(networkSettings), 1000); +static FileData fsSettings(&LittleFS, "/settings.conf", 's', &settings, sizeof(settings), 60000); +static FileData fsSensorsSettings(&LittleFS, "/sensors.conf", 'e', &sensorsSettings, sizeof(sensorsSettings), 60000); + +// FileData requests can arrive while the save task is running. +static std::mutex settingsSaveMutex; + +void requestSaveNetworkSettings() { + std::lock_guard lock(settingsSaveMutex); + fsNetworkSettings.update(); +} + +void requestSaveSettings() { + std::lock_guard lock(settingsSaveMutex); + fsSettings.update(); +} + +void requestSaveSensorsSettings() { + std::lock_guard lock(Sensors::mutex); + fsSensorsSettings.update(); +} + +static Task settingsSaveTask("Settings save", [](void*) { + FDstat_t status; + { + std::lock_guard lock(settingsSaveMutex); + status = fsNetworkSettings.tick(); + } + if (status == FD_WRITE) { + ESP_LOGI(L_NETWORK_SETTINGS, "Updated"); + } + + { + std::lock_guard lock(settingsSaveMutex); + status = fsSettings.tick(); + } + if (status == FD_WRITE) { + ESP_LOGI(L_SETTINGS, "Updated"); + } + + { + std::lock_guard lock(Sensors::mutex); + status = fsSensorsSettings.tick(); + } + if (status == FD_WRITE) { + ESP_LOGI(L_SENSORS_SETTINGS, "Updated"); + } +}); + +void saveSettingsNow() { + { + std::lock_guard lock(settingsSaveMutex); + fsSettings.updateNow(); + } + + { + std::lock_guard lock(Sensors::mutex); + fsSensorsSettings.updateNow(); + } + + // Always preserve the network configuration + { + std::lock_guard lock(settingsSaveMutex); + if (fsNetworkSettings.updateNow() == FD_FILE_ERR && LittleFS.begin()) { + fsNetworkSettings.write(); + } + } +} + +// Initialization +static bool loadNetworkSettings() { + bool loaded = false; + + switch (fsNetworkSettings.read()) { + case FD_FS_ERR: + ESP_LOGW(L_NETWORK_SETTINGS, "Filesystem error, load default"); + break; + + case FD_FILE_ERR: + ESP_LOGW(L_NETWORK_SETTINGS, "Bad data, load default"); + break; + + case FD_WRITE: + ESP_LOGI(L_NETWORK_SETTINGS, "Not found, load default"); + break; + + case FD_ADD: + case FD_READ: + ESP_LOGI(L_NETWORK_SETTINGS, "Loaded"); + loaded = true; + break; + + default: + break; + } + + if (!networkSettings.hostname[0]) { + strcpy(networkSettings.hostname, getChipId("otgateway-").c_str()); + requestSaveNetworkSettings(); + } + + return loaded; +} + +static bool loadSettings() { + bool loaded = false; + + switch (fsSettings.read()) { + case FD_FS_ERR: + ESP_LOGW(L_SETTINGS, "Filesystem error, load default"); + break; + + case FD_FILE_ERR: + ESP_LOGW(L_SETTINGS, "Bad data, load default"); + break; + + case FD_WRITE: + ESP_LOGI(L_SETTINGS, "Not found, load default"); + break; + + case FD_ADD: + case FD_READ: + if (memcmp(settings.validationValue, SETTINGS_VALID_VALUE, sizeof(settings.validationValue)) == 0) { + ESP_LOGI(L_SETTINGS, "Loaded"); + loaded = true; + + } else { + ESP_LOGW(L_SETTINGS, "Loaded, but not valid, reset to default"); + settings = Settings{}; + fsSettings.reset(); + } + break; + + default: + break; + } + + if (settings.system.logLevel < ESP_LOG_NONE || settings.system.logLevel > ESP_LOG_VERBOSE) { + settings.system.logLevel = static_cast(DEFAULT_LOG_LEVEL); + requestSaveSettings(); + } + + // generate mqtt prefix if it is empty + if (!strlen(settings.mqtt.prefix)) { + strcpy(settings.mqtt.prefix, getChipId("otgateway_").c_str()); + requestSaveSettings(); + } + + return loaded; +} + +static bool loadSensorsSettings() { + bool loaded = false; + + switch (fsSensorsSettings.read()) { + case FD_FS_ERR: + ESP_LOGW(L_SENSORS, "Filesystem error, load default"); + break; + + case FD_FILE_ERR: + ESP_LOGW(L_SENSORS, "Bad data, load default"); + break; + + case FD_WRITE: + ESP_LOGI(L_SENSORS, "Not found, load default"); + break; + + case FD_ADD: + case FD_READ: + ESP_LOGI(L_SENSORS, "Loaded"); + loaded = true; + break; + + default: + break; + } + + return loaded; +} + +void initConfig() { + loadNetworkSettings(); + loadSettings(); + loadSensorsSettings(); + configureLoggingTask.forceRun(); + + settingsSaveTask.setInterval(100); + coreTaskManager.addTask(settingsSaveTask); +} + +// JSON API + +// Shared validation + +static bool isSettingInteger(float value, float minValue, float maxValue) { + return std::isfinite(value) && value >= minValue && value <= maxValue && std::trunc(value) == value; +} + +// Network settings + +static bool isHostnameValid(const char* value) { + if (value == nullptr) { + return false; + } + + size_t len = strlen(value); + if (len == 0 || len > 24 || value[0] == '-' || value[len - 1] == '-') { + return false; + } + + for (size_t i = 0; i < len; i++) { + const char symbol = value[i]; + + // Lowercase ASCII letters. + if (symbol >= 'a' && symbol <= 'z') { + continue; + } + + // Uppercase ASCII letters. + if (symbol >= 'A' && symbol <= 'Z') { + continue; + } + + // Decimal digits. + if (symbol >= '0' && symbol <= '9') { + continue; + } + + // Hyphens are allowed inside the hostname. + if (symbol == '-') { + continue; + } + + // All other characters are invalid. + return false; + } + + return true; +} + +JsonVariant toJson(const NetworkSettings& src, JsonVariant dst) { + dst[S_HOSTNAME] = src.hostname; + + dst[S_USE_DHCP] = src.useDhcp; + dst[S_STATIC_CONFIG][S_IP] = src.staticConfig.ip; + dst[S_STATIC_CONFIG][S_GATEWAY] = src.staticConfig.gateway; + dst[S_STATIC_CONFIG][S_SUBNET] = src.staticConfig.subnet; + dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns; + + dst[S_AP][S_SSID] = src.ap.ssid; + dst[S_AP][S_PASSWORD] = src.ap.password; + dst[S_AP][S_CHANNEL] = src.ap.channel; + + dst[S_STA][S_SSID] = src.sta.ssid; + dst[S_STA][S_PASSWORD] = src.sta.password; + dst[S_STA][S_CHANNEL] = src.sta.channel; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) { + SettingResult result; + + // hostname + if (src[S_HOSTNAME].is()) { + const JsonString value = src[S_HOSTNAME].as(); + + 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; + } + } + } + + // use dhcp + if (src[S_USE_DHCP].is()) { + const auto value = src[S_USE_DHCP].as(); + result.accepted = true; + + if (value != dst.useDhcp) { + dst.useDhcp = value; + result.changed = true; + } + } + + + // static config + if (src[S_STATIC_CONFIG][S_IP].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_IP].as(); + + 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 (src[S_STATIC_CONFIG][S_GATEWAY].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_GATEWAY].as(); + + 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 (src[S_STATIC_CONFIG][S_SUBNET].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_SUBNET].as(); + + 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 (src[S_STATIC_CONFIG][S_DNS].is()) { + const JsonString value = src[S_STATIC_CONFIG][S_DNS].as(); + + 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; + } + } + } + + + // ap + if (src[S_AP][S_SSID].is()) { + const JsonString value = src[S_AP][S_SSID].as(); + + if (value.size() && value.size() < sizeof(dst.ap.ssid)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.ap.ssid) != 0) { + strcpy(dst.ap.ssid, value.c_str()); + result.changed = true; + } + } + } + + if (src[S_AP][S_PASSWORD].is()) { + const JsonString value = src[S_AP][S_PASSWORD].as(); + + if (value.size() && value.size() < sizeof(dst.ap.password)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.ap.password) != 0) { + strcpy(dst.ap.password, value.c_str()); + result.changed = true; + } + } + } + + if (src[S_AP][S_CHANNEL].is()) { + const auto value = src[S_AP][S_CHANNEL].as(); + + if (value < 12) { + result.accepted = true; + + if (value != dst.ap.channel) { + dst.ap.channel = value; + result.changed = true; + } + } + } + + + // sta + if (src[S_STA][S_SSID].is()) { + const JsonString value = src[S_STA][S_SSID].as(); + + if (value.size() && value.size() < sizeof(dst.sta.ssid)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.sta.ssid) != 0) { + strcpy(dst.sta.ssid, value.c_str()); + result.changed = true; + } + } + } + + if (src[S_STA][S_PASSWORD].is()) { + const JsonString value = src[S_STA][S_PASSWORD].as(); + + if (value.size() < sizeof(dst.sta.password)) { + result.accepted = true; + if (strcmp(value.c_str(), dst.sta.password) != 0) { + strcpy(dst.sta.password, value.c_str()); + result.changed = true; + } + } + } + + if (src[S_STA][S_CHANNEL].is()) { + const auto value = src[S_STA][S_CHANNEL].as(); + + if (value < 12) { + result.accepted = true; + + if (value != dst.sta.channel) { + dst.sta.channel = value; + result.changed = true; + } + } + } + + return result; +} + +// System settings + +JsonVariant toJson(const SystemSettings& src, JsonVariant dst) { + auto system = dst.to(); + system[S_LOG_LEVEL] = static_cast(src.logLevel); + + auto serial = system[S_SERIAL].to(); + serial[S_ENABLED] = src.serial.enabled; + serial[S_BAUDRATE] = src.serial.baudrate; + + auto webSerial = system[S_WEBSERIAL].to(); + webSerial[S_ENABLED] = src.webSerial.enabled; + + auto ntp = system[S_NTP].to(); + ntp[S_SERVER] = src.ntp.server; + ntp[S_TIMEZONE] = src.ntp.timezone; + + system[S_UNIT_SYSTEM] = static_cast(src.unitSystem); + system[S_STATUS_LED_GPIO] = src.statusLedGpio; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, SystemSettings& dst) { + SettingResult result; + + if (src[S_LOG_LEVEL].is()) { + const auto value = src[S_LOG_LEVEL].as(); + + if (value >= ESP_LOG_NONE && value <= ESP_LOG_VERBOSE) { + result.accepted = true; + if (value != dst.logLevel) { + dst.logLevel = static_cast(value); + result.changed = true; + } + } + } + + if (src[S_SERIAL][S_ENABLED].is()) { + const auto value = src[S_SERIAL][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.serial.enabled) { + dst.serial.enabled = value; + result.changed = true; + } + } + + if (src[S_SERIAL][S_BAUDRATE].is()) { + const auto value = src[S_SERIAL][S_BAUDRATE].as(); + + if (value == 9600 || value == 19200 || value == 38400 || value == 57600 || value == 74880 || value == 115200) { + result.accepted = true; + if (value != dst.serial.baudrate) { + dst.serial.baudrate = value; + result.changed = true; + } + } + } + + if (src[S_WEBSERIAL][S_ENABLED].is()) { + const auto value = src[S_WEBSERIAL][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.webSerial.enabled) { + dst.webSerial.enabled = value; + result.changed = true; + } + } + + if (src[S_NTP][S_SERVER].is()) { + const JsonString value = src[S_NTP][S_SERVER].as(); + + 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 (src[S_NTP][S_TIMEZONE].is()) { + const JsonString value = src[S_NTP][S_TIMEZONE].as(); + + 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 (src[S_UNIT_SYSTEM].is()) { + const auto value = src[S_UNIT_SYSTEM].as(); + + switch (value) { + case static_cast(UnitSystem::METRIC): + result.accepted = true; + if (dst.unitSystem != UnitSystem::METRIC) { + dst.unitSystem = UnitSystem::METRIC; + result.changed = true; + } + break; + + case static_cast(UnitSystem::IMPERIAL): + result.accepted = true; + if (dst.unitSystem != UnitSystem::IMPERIAL) { + dst.unitSystem = UnitSystem::IMPERIAL; + result.changed = true; + } + break; + + default: + break; + } + + } + + if (!src[S_STATUS_LED_GPIO].isNull()) { + if (src[S_STATUS_LED_GPIO].is() && src[S_STATUS_LED_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.statusLedGpio != GPIO_IS_NOT_CONFIGURED) { + dst.statusLedGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_STATUS_LED_GPIO].is()) { + const auto value = src[S_STATUS_LED_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.statusLedGpio) { + dst.statusLedGpio = value; + result.changed = true; + } + } + } + } + + return result; +} + +// Portal settings + +JsonVariant toJson(const PortalSettings& src, JsonVariant dst) { + auto portal = dst.to(); + portal[S_AUTH] = src.auth; + portal[S_LOGIN] = src.login; + portal[S_PASSWORD] = src.password; + portal[S_MDNS] = src.mdns; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) { + SettingResult result; + + if (src[S_AUTH].is()) { + const auto value = src[S_AUTH].as(); + + result.accepted = true; + if (value != dst.auth) { + dst.auth = value; + result.changed = true; + } + } + + if (src[S_LOGIN].is()) { + const JsonString value = src[S_LOGIN].as(); + + 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 (src[S_PASSWORD].is()) { + const JsonString value = src[S_PASSWORD].as(); + + 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 (dst.auth && (!strlen(dst.login) || !strlen(dst.password))) { + dst.auth = false; + result.changed = true; + } + + if (src[S_MDNS].is()) { + const auto value = src[S_MDNS].as(); + + result.accepted = true; + if (value != dst.mdns) { + dst.mdns = value; + result.changed = true; + } + } + + return result; +} + +// OpenTherm settings + +static SettingResult jsonToChannelDisablingAction(const JsonVariantConst src, ChannelDisablingAction& dst) { + if (!src.is()) { + return {}; + } + + const uint8_t value = src.as(); + switch (value) { + case static_cast(ChannelDisablingAction::OFF): + case static_cast(ChannelDisablingAction::ZERO_SETPOINT): + case static_cast(ChannelDisablingAction::OFF_AND_ZERO_SETPOINT): + if (static_cast(dst) != value) { + dst = static_cast(value); + return {.changed = true, .accepted = true}; + } + return {.accepted = true}; + + default: + break; + } + + return {}; +} + +JsonVariant toJson(const OpenThermSettings& src, JsonVariant dst) { + auto opentherm = dst.to(); + opentherm[S_IN_GPIO] = src.inGpio; + opentherm[S_OUT_GPIO] = src.outGpio; + opentherm[S_RX_LED_GPIO] = src.rxLedGpio; + opentherm[S_MEMBER_ID] = src.memberId; + opentherm[S_FLAGS] = src.flags; + opentherm[S_HEATING_DISABLING_ACTION] = static_cast(src.heatingDisablingAction); + opentherm[S_DHW_DISABLING_ACTION] = static_cast(src.dhwDisablingAction); + opentherm[S_CH2_DISABLING_ACTION] = static_cast(src.ch2DisablingAction); + opentherm[S_MIN_POWER] = roundf(src.minPower, 2); + opentherm[S_MAX_POWER] = roundf(src.maxPower, 2); + + auto otOptions = opentherm[S_OPTIONS].to(); + otOptions[S_DHW_SUPPORT] = src.options.dhwSupport; + otOptions[S_COOLING_SUPPORT] = src.options.coolingSupport; + otOptions[S_SUMMER_WINTER_MODE] = src.options.summerWinterMode; + otOptions[S_HEATING_STATE_TO_SUMMER_WINTER_MODE] = src.options.heatingStateToSummerWinterMode; + otOptions[S_CH2_ALWAYS_ENABLED] = src.options.ch2AlwaysEnabled; + otOptions[S_HEATING_TO_CH2] = src.options.heatingToCh2; + otOptions[S_DHW_TO_CH2] = src.options.dhwToCh2; + otOptions[S_DHW_BLOCKING] = src.options.dhwBlocking; + otOptions[S_DHW_STATE_AS_DHW_BLOCKING] = src.options.dhwStateAsDhwBlocking; + otOptions[S_MAX_TEMP_SYNC_WITH_TARGET_TEMP] = src.options.maxTempSyncWithTargetTemp; + otOptions[S_GET_MIN_MAX_TEMP] = src.options.getMinMaxTemp; + otOptions[S_IGNORE_DIAG_STATE] = src.options.ignoreDiagState; + otOptions[S_AUTO_FAULT_RESET] = src.options.autoFaultReset; + otOptions[S_AUTO_DIAG_RESET] = src.options.autoDiagReset; + otOptions[S_SET_DATE_AND_TIME] = src.options.setDateAndTime; + otOptions[S_ALWAYS_SEND_INDOOR_TEMP] = src.options.alwaysSendIndoorTemp; + otOptions[S_NATIVE_OTC] = src.options.nativeOTC; + otOptions[S_IMMERGAS_FIX] = src.options.immergasFix; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, OpenThermSettings& dst) { + SettingResult result; + + if (!src[S_IN_GPIO].isNull()) { + if (src[S_IN_GPIO].is() && src[S_IN_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.inGpio != GPIO_IS_NOT_CONFIGURED) { + dst.inGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_IN_GPIO].is()) { + const auto value = src[S_IN_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_INPUT(value)) { + result.accepted = true; + if (value != dst.inGpio) { + dst.inGpio = value; + result.changed = true; + } + } + } + } + + if (!src[S_OUT_GPIO].isNull()) { + if (src[S_OUT_GPIO].is() && src[S_OUT_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.outGpio != GPIO_IS_NOT_CONFIGURED) { + dst.outGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_OUT_GPIO].is()) { + const auto value = src[S_OUT_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.outGpio) { + dst.outGpio = value; + result.changed = true; + } + } + } + } + + if (!src[S_RX_LED_GPIO].isNull()) { + if (src[S_RX_LED_GPIO].is() && src[S_RX_LED_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.rxLedGpio != GPIO_IS_NOT_CONFIGURED) { + dst.rxLedGpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_RX_LED_GPIO].is()) { + const auto value = src[S_RX_LED_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.rxLedGpio) { + dst.rxLedGpio = value; + result.changed = true; + } + } + } + } + + if (src[S_MEMBER_ID].is()) { + const auto value = src[S_MEMBER_ID].as(); + + result.accepted = true; + if (value != dst.memberId) { + dst.memberId = value; + result.changed = true; + } + } + + if (src[S_FLAGS].is()) { + const auto value = src[S_FLAGS].as(); + + result.accepted = true; + if (value != dst.flags) { + dst.flags = value; + result.changed = true; + } + } + + const auto heatingDisablingActionResult = jsonToChannelDisablingAction(src[S_HEATING_DISABLING_ACTION], dst.heatingDisablingAction); + result.changed = heatingDisablingActionResult.changed || result.changed; + result.accepted = heatingDisablingActionResult.accepted || result.accepted; + + const auto dhwDisablingActionResult = jsonToChannelDisablingAction(src[S_DHW_DISABLING_ACTION], dst.dhwDisablingAction); + result.changed = dhwDisablingActionResult.changed || result.changed; + result.accepted = dhwDisablingActionResult.accepted || result.accepted; + + const auto ch2DisablingActionResult = jsonToChannelDisablingAction(src[S_CH2_DISABLING_ACTION], dst.ch2DisablingAction); + result.changed = ch2DisablingActionResult.changed || result.changed; + result.accepted = ch2DisablingActionResult.accepted || result.accepted; + + if (src[S_MIN_POWER].is()) { + const auto value = src[S_MIN_POWER].as(); + + if (value >= 0 && value <= 1000) { + result.accepted = true; + if (isFloatDifferent(value, dst.minPower, 0.0001f)) { + dst.minPower = roundf(value, 2); + result.changed = true; + } + } + } + + if (src[S_MAX_POWER].is()) { + const auto value = src[S_MAX_POWER].as(); + + if (value >= 0 && value <= 1000) { + result.accepted = true; + if (isFloatDifferent(value, dst.maxPower, 0.0001f)) { + dst.maxPower = roundf(value, 2); + result.changed = true; + } + } + } + + if (src[S_OPTIONS][S_DHW_SUPPORT].is()) { + const auto value = src[S_OPTIONS][S_DHW_SUPPORT].as(); + + result.accepted = true; + if (value != dst.options.dhwSupport) { + dst.options.dhwSupport = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_COOLING_SUPPORT].is()) { + const auto value = src[S_OPTIONS][S_COOLING_SUPPORT].as(); + + result.accepted = true; + if (value != dst.options.coolingSupport) { + dst.options.coolingSupport = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_SUMMER_WINTER_MODE].is()) { + const auto value = src[S_OPTIONS][S_SUMMER_WINTER_MODE].as(); + + result.accepted = true; + if (value != dst.options.summerWinterMode) { + dst.options.summerWinterMode = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_HEATING_STATE_TO_SUMMER_WINTER_MODE].is()) { + const auto value = src[S_OPTIONS][S_HEATING_STATE_TO_SUMMER_WINTER_MODE].as(); + + result.accepted = true; + if (value != dst.options.heatingStateToSummerWinterMode) { + dst.options.heatingStateToSummerWinterMode = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_CH2_ALWAYS_ENABLED].is()) { + const auto value = src[S_OPTIONS][S_CH2_ALWAYS_ENABLED].as(); + + result.accepted = true; + if (value != dst.options.ch2AlwaysEnabled) { + dst.options.ch2AlwaysEnabled = value; + + if (dst.options.ch2AlwaysEnabled) { + dst.options.heatingToCh2 = false; + dst.options.dhwToCh2 = false; + } + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_HEATING_TO_CH2].is()) { + const auto value = src[S_OPTIONS][S_HEATING_TO_CH2].as(); + + result.accepted = true; + if (value != dst.options.heatingToCh2) { + dst.options.heatingToCh2 = value; + + if (dst.options.heatingToCh2) { + dst.options.ch2AlwaysEnabled = false; + dst.options.dhwToCh2 = false; + } + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_DHW_TO_CH2].is()) { + const auto value = src[S_OPTIONS][S_DHW_TO_CH2].as(); + + result.accepted = true; + if (value != dst.options.dhwToCh2) { + dst.options.dhwToCh2 = value; + + if (dst.options.dhwToCh2) { + dst.options.ch2AlwaysEnabled = false; + dst.options.heatingToCh2 = false; + } + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_DHW_BLOCKING].is()) { + const auto value = src[S_OPTIONS][S_DHW_BLOCKING].as(); + + result.accepted = true; + if (value != dst.options.dhwBlocking) { + dst.options.dhwBlocking = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_DHW_STATE_AS_DHW_BLOCKING].is()) { + const auto value = src[S_OPTIONS][S_DHW_STATE_AS_DHW_BLOCKING].as(); + + result.accepted = true; + if (value != dst.options.dhwStateAsDhwBlocking) { + dst.options.dhwStateAsDhwBlocking = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_MAX_TEMP_SYNC_WITH_TARGET_TEMP].is()) { + const auto value = src[S_OPTIONS][S_MAX_TEMP_SYNC_WITH_TARGET_TEMP].as(); + + result.accepted = true; + if (value != dst.options.maxTempSyncWithTargetTemp) { + dst.options.maxTempSyncWithTargetTemp = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_GET_MIN_MAX_TEMP].is()) { + const auto value = src[S_OPTIONS][S_GET_MIN_MAX_TEMP].as(); + + result.accepted = true; + if (value != dst.options.getMinMaxTemp) { + dst.options.getMinMaxTemp = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_IGNORE_DIAG_STATE].is()) { + const auto value = src[S_OPTIONS][S_IGNORE_DIAG_STATE].as(); + + result.accepted = true; + if (value != dst.options.ignoreDiagState) { + dst.options.ignoreDiagState = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_AUTO_FAULT_RESET].is()) { + const auto value = src[S_OPTIONS][S_AUTO_FAULT_RESET].as(); + + result.accepted = true; + if (value != dst.options.autoFaultReset) { + dst.options.autoFaultReset = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_AUTO_DIAG_RESET].is()) { + const auto value = src[S_OPTIONS][S_AUTO_DIAG_RESET].as(); + + result.accepted = true; + if (value != dst.options.autoDiagReset) { + dst.options.autoDiagReset = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_SET_DATE_AND_TIME].is()) { + const auto value = src[S_OPTIONS][S_SET_DATE_AND_TIME].as(); + + result.accepted = true; + if (value != dst.options.setDateAndTime) { + dst.options.setDateAndTime = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_ALWAYS_SEND_INDOOR_TEMP].is()) { + const auto value = src[S_OPTIONS][S_ALWAYS_SEND_INDOOR_TEMP].as(); + + result.accepted = true; + if (value != dst.options.alwaysSendIndoorTemp) { + dst.options.alwaysSendIndoorTemp = value; + result.changed = true; + } + } + + if (src[S_OPTIONS][S_NATIVE_OTC].is()) { + const auto value = src[S_OPTIONS][S_NATIVE_OTC].as(); + + result.accepted = true; + if (value != dst.options.nativeOTC) { + dst.options.nativeOTC = value; + + result.changed = true; + } + } + + if (src[S_OPTIONS][S_IMMERGAS_FIX].is()) { + const auto value = src[S_OPTIONS][S_IMMERGAS_FIX].as(); + + result.accepted = true; + if (value != dst.options.immergasFix) { + dst.options.immergasFix = value; + result.changed = true; + } + } + + return result; +} + +// MQTT settings + +JsonVariant toJson(const MqttSettings& src, JsonVariant dst) { + auto mqtt = dst.to(); + mqtt[S_ENABLED] = src.enabled; + mqtt[S_SERVER] = src.server; + mqtt[S_PORT] = src.port; + mqtt[S_USER] = src.user; + mqtt[S_PASSWORD] = src.password; + mqtt[S_PREFIX] = src.prefix; + mqtt[S_INTERVAL] = src.interval; + mqtt[S_HOME_ASSISTANT_DISCOVERY] = src.homeAssistantDiscovery; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, MqttSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + + result.accepted = true; + if (value != dst.enabled) { + dst.enabled = value; + result.changed = true; + } + } + + if (src[S_SERVER].is()) { + const JsonString value = src[S_SERVER].as(); + + 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 (src[S_PORT].is()) { + const auto value = src[S_PORT].as(); + + if (value > 0 && value <= 65535) { + result.accepted = true; + if (value != dst.port) { + dst.port = value; + result.changed = true; + } + } + } + + if (src[S_USER].is()) { + const JsonString value = src[S_USER].as(); + + 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 (src[S_PASSWORD].is()) { + const JsonString value = src[S_PASSWORD].as(); + + 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 (src[S_PREFIX].is()) { + const JsonString value = src[S_PREFIX].as(); + + 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 (src[S_INTERVAL].is()) { + const auto value = src[S_INTERVAL].as(); + + if (value >= 3 && value <= 60) { + result.accepted = true; + if (value != dst.interval) { + dst.interval = value; + result.changed = true; + } + } + } + + if (src[S_HOME_ASSISTANT_DISCOVERY].is()) { + const auto value = src[S_HOME_ASSISTANT_DISCOVERY].as(); + + result.accepted = true; + if (value != dst.homeAssistantDiscovery) { + dst.homeAssistantDiscovery = value; + result.changed = true; + } + } + + return result; +} + +// Emergency settings + +static SettingResult setEmergencyTarget(EmergencySettings& dst, float value) { + bool changed = false; + + bool noRegulators = !settings.opentherm.options.nativeOTC; + float minTemp = noRegulators + ? settings.heating.minTemp + : THERMOSTAT_INDOOR_MIN_TEMP; + float maxTemp = noRegulators + ? settings.heating.maxTemp + : THERMOSTAT_INDOOR_MAX_TEMP; + + bool valid = isValidTemp( + value, + UnitSystem::METRIC, + minTemp, + maxTemp, + UnitSystem::METRIC + ); + + if (!valid) { + value = noRegulators ? DEFAULT_HEATING_TARGET_TEMP : THERMOSTAT_INDOOR_DEFAULT_TEMP; + } + + value = constrain(value, minTemp, maxTemp); + + if (isFloatDifferent(dst.target, value, 0.0001f)) { + dst.target = roundf(value, 2); + changed = true; + } + + return {.changed = changed, .accepted = valid}; +} + +static SettingResult applySetting(EmergencySettings& dst, std::string_view path, float input) { + if (path == S_TARGET) { + return setEmergencyTarget(dst, input); + } + + return {}; +} + +JsonVariant toJson(const EmergencySettings& src, JsonVariant dst) { + auto emergency = dst.to(); + emergency[S_TARGET] = roundf(convertTemp(src.target, UnitSystem::METRIC, settings.system.unitSystem), 2); + emergency[S_TRESHOLD_TIME] = src.tresholdTime; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, EmergencySettings& dst) { + SettingResult result; + + if (src[S_TRESHOLD_TIME].is()) { + const auto value = src[S_TRESHOLD_TIME].as(); + + if (value >= 60 && value <= 1800) { + result.accepted = true; + if (value != dst.tresholdTime) { + dst.tresholdTime = value; + result.changed = true; + } + } + } + + float value = src[S_TARGET].is() + ? convertTemp(src[S_TARGET].as(), settings.system.unitSystem, UnitSystem::METRIC) + : dst.target; + const auto fieldResult = applySetting(dst, S_TARGET, value); + result.changed = fieldResult.changed || result.changed; + if (src[S_TARGET].is()) { + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// Heating settings + +static bool normalizeHeatingBounds(HeatingSettings& dst) { + bool changed = false; + + if (dst.maxTemp < dst.minTemp) { + dst.maxTemp = dst.minTemp; + changed = true; + } + + return changed; +} + +static bool normalizeHeatingOverheatBounds(HeatingSettings& dst) { + bool changed = false; + + if (dst.overheatProtection.highTemp < dst.overheatProtection.lowTemp) { + dst.overheatProtection.highTemp = dst.overheatProtection.lowTemp; + changed = true; + } + + return changed; +} + +static bool normalizeHeatingFreezeBounds(HeatingSettings& dst) { + bool changed = false; + + if (dst.freezeProtection.highTemp < dst.freezeProtection.lowTemp) { + dst.freezeProtection.highTemp = dst.freezeProtection.lowTemp; + changed = true; + } + + return changed; +} + +static SettingResult setHeatingTarget(HeatingSettings& dst, float value) { + bool changed = false; + + bool indoorTempControl = settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC; + float minTemp = indoorTempControl + ? THERMOSTAT_INDOOR_MIN_TEMP + : dst.minTemp; + float maxTemp = indoorTempControl + ? THERMOSTAT_INDOOR_MAX_TEMP + : dst.maxTemp; + + bool valid = isValidTemp( + value, + UnitSystem::METRIC, + minTemp, + maxTemp, + UnitSystem::METRIC + ); + + if (!valid) { + value = indoorTempControl ? THERMOSTAT_INDOOR_DEFAULT_TEMP : DEFAULT_HEATING_TARGET_TEMP; + } + + value = constrain(value, minTemp, maxTemp); + + if (isFloatDifferent(dst.target, value, 0.0001f)) { + dst.target = roundf(value, 2); + changed = true; + } + + return {.changed = changed, .accepted = valid}; +} + +static SettingResult applySetting(HeatingSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TURBO) { + if (value && (settings.opentherm.options.nativeOTC || (!settings.equitherm.enabled && !settings.pid.enabled))) { + return {}; + } + + if (value != dst.turbo) { + dst.turbo = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "hysteresis/enabled") { + if (value != dst.hysteresis.enabled) { + dst.hysteresis.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +static SettingResult applySetting(HeatingSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == "hysteresis/value") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0.0f || value > 15.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.hysteresis.value, 0.0001f)) { + dst.hysteresis.value = roundf(value, 2); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TURBO_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 1.5f || value > 10.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.turboFactor, 0.0001f)) { + dst.turboFactor = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MIN_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value < vars.slave.heating.minTemp + || value >= vars.slave.heating.maxTemp + || value == dst.maxTemp) { + return {}; + } + + if (value != dst.minTemp) { + dst.minTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= vars.slave.heating.minTemp + || value > vars.slave.heating.maxTemp + || value == dst.minTemp) { + return {}; + } + + if (value != dst.maxTemp) { + dst.maxTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_MODULATION) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= 0 || value > 100) { + return {}; + } + + if (value != dst.maxModulation) { + dst.maxModulation = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_INDOOR_TEMP_AVG_TYPE) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + uint8_t value = static_cast(input); + + switch (value) { + case static_cast(Sensors::AverageType::MEAN): + case static_cast(Sensors::AverageType::MINIMUM): + case static_cast(Sensors::AverageType::MAXIMUM): + if (static_cast(dst.indoorTempAvgType) != value) { + dst.indoorTempAvgType = static_cast(value); + changed = true; + } + break; + + default: + return {}; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_OUTDOOR_TEMP_AVG_TYPE) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + uint8_t value = static_cast(input); + + switch (value) { + case static_cast(Sensors::AverageType::MEAN): + case static_cast(Sensors::AverageType::MINIMUM): + case static_cast(Sensors::AverageType::MAXIMUM): + if (static_cast(dst.outdoorTempAvgType) != value) { + dst.outdoorTempAvgType = static_cast(value); + changed = true; + } + break; + + default: + return {}; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/high_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 100.0f)) { + return {}; + } + + if (value != dst.overheatProtection.highTemp) { + dst.overheatProtection.highTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/low_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 99.0f)) { + return {}; + } + + if (value != dst.overheatProtection.lowTemp) { + dst.overheatProtection.lowTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "freeze_protection/high_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 65535)) { + return {}; + } + + unsigned short value = static_cast(input); + + if (!isValidTemp(value, UnitSystem::METRIC, 1, 50)) { + return {}; + } + + if (value != dst.freezeProtection.highTemp) { + dst.freezeProtection.highTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "freeze_protection/low_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 65535)) { + return {}; + } + + unsigned short value = static_cast(input); + + if (!isValidTemp(value, UnitSystem::METRIC, 1, 30)) { + return {}; + } + + if (value != dst.freezeProtection.lowTemp) { + dst.freezeProtection.lowTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TARGET) { + return setHeatingTarget(dst, input); + } + + return {}; +} + +JsonVariant toJson(const HeatingSettings& src, JsonVariant dst) { + auto heating = dst.to(); + heating[S_ENABLED] = src.enabled; + heating[S_TURBO] = src.turbo; + heating[S_TARGET] = roundf(convertTemp(src.target, UnitSystem::METRIC, settings.system.unitSystem), 2); + heating[S_HYSTERESIS][S_ENABLED] = src.hysteresis.enabled; + heating[S_HYSTERESIS][S_VALUE] = roundf(src.hysteresis.value, 3); + heating[S_TURBO_FACTOR] = roundf(src.turboFactor, 3); + heating[S_MIN_TEMP] = convertTemp(src.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + heating[S_MAX_TEMP] = convertTemp(src.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + heating[S_MAX_MODULATION] = src.maxModulation; + heating[S_INDOOR_TEMP_AVG_TYPE] = static_cast(src.indoorTempAvgType); + heating[S_OUTDOOR_TEMP_AVG_TYPE] = static_cast(src.outdoorTempAvgType); + + auto heatingOverheatProtection = heating[S_OVERHEAT_PROTECTION].to(); + heatingOverheatProtection[S_HIGH_TEMP] = src.overheatProtection.highTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem); + heatingOverheatProtection[S_LOW_TEMP] = src.overheatProtection.lowTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto freezeProtection = heating[S_FREEZE_PROTECTION].to(); + freezeProtection[S_HIGH_TEMP] = convertTemp(src.freezeProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem); + freezeProtection[S_LOW_TEMP] = convertTemp(src.freezeProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, HeatingSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_TURBO].is()) { + const auto value = src[S_TURBO].as(); + const auto fieldResult = applySetting(dst, S_TURBO, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_HYSTERESIS][S_ENABLED].is()) { + const auto value = src[S_HYSTERESIS][S_ENABLED].as(); + const auto fieldResult = applySetting(dst, "hysteresis/enabled", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_HYSTERESIS][S_VALUE].is()) { + const auto value = src[S_HYSTERESIS][S_VALUE].as(); + const auto fieldResult = applySetting(dst, "hysteresis/value", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_TURBO_FACTOR].is()) { + const auto value = src[S_TURBO_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_TURBO_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MIN_TEMP].is()) { + float value = convertTemp(src[S_MIN_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MIN_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MAX_TEMP].is()) { + float value = convertTemp(src[S_MAX_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MAX_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeHeatingBounds(dst) || result.changed; + + + if (src[S_MAX_MODULATION].is()) { + const auto value = src[S_MAX_MODULATION].as(); + const auto fieldResult = applySetting(dst, S_MAX_MODULATION, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_INDOOR_TEMP_AVG_TYPE].is()) { + const auto value = src[S_INDOOR_TEMP_AVG_TYPE].as(); + const auto fieldResult = applySetting(dst, S_INDOOR_TEMP_AVG_TYPE, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OUTDOOR_TEMP_AVG_TYPE].is()) { + const auto value = src[S_OUTDOOR_TEMP_AVG_TYPE].as(); + const auto fieldResult = applySetting(dst, S_OUTDOOR_TEMP_AVG_TYPE, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/high_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/low_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeHeatingOverheatBounds(dst) || result.changed; + + if (src[S_FREEZE_PROTECTION][S_HIGH_TEMP].is()) { + float value = convertTemp(src[S_FREEZE_PROTECTION][S_HIGH_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, "freeze_protection/high_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_FREEZE_PROTECTION][S_LOW_TEMP].is()) { + float value = convertTemp(src[S_FREEZE_PROTECTION][S_LOW_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, "freeze_protection/low_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeHeatingFreezeBounds(dst) || result.changed; + + float value = src[S_TARGET].is() + ? convertTemp(src[S_TARGET].as(), settings.system.unitSystem, UnitSystem::METRIC) + : dst.target; + const auto fieldResult = applySetting(dst, S_TARGET, value); + result.changed = fieldResult.changed || result.changed; + if (src[S_TARGET].is()) { + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// DHW settings + +static bool normalizeDhwBounds(DhwSettings& dst) { + bool changed = false; + + if (dst.maxTemp < dst.minTemp) { + dst.maxTemp = dst.minTemp; + changed = true; + } + + return changed; +} + +static bool normalizeDhwOverheatBounds(DhwSettings& dst) { + bool changed = false; + + if (dst.overheatProtection.highTemp < dst.overheatProtection.lowTemp) { + dst.overheatProtection.highTemp = dst.overheatProtection.lowTemp; + changed = true; + } + + return changed; +} + +static SettingResult setDhwTarget(DhwSettings& dst, float value) { + bool changed = false; + + bool valid = isValidTemp( + value, + UnitSystem::METRIC, + dst.minTemp, + dst.maxTemp, + UnitSystem::METRIC + ); + + if (!valid) { + value = DEFAULT_DHW_TARGET_TEMP; + } + + value = constrain(value, dst.minTemp, dst.maxTemp); + + if (isFloatDifferent(dst.target, value, 0.0001f)) { + dst.target = value; + changed = true; + } + + return {.changed = changed, .accepted = valid}; +} + +static SettingResult applySetting(DhwSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +static SettingResult applySetting(DhwSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == S_MIN_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value < vars.slave.dhw.minTemp + || value >= vars.slave.dhw.maxTemp) { + return {}; + } + + if (value != dst.minTemp) { + dst.minTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_TEMP) { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= vars.slave.dhw.minTemp + || value > vars.slave.dhw.maxTemp) { + return {}; + } + + if (value != dst.maxTemp) { + dst.maxTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_MODULATION) { + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value <= 0 || value > 100) { + return {}; + } + + if (value != dst.maxModulation) { + dst.maxModulation = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/high_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 100.0f)) { + return {}; + } + + if (value != dst.overheatProtection.highTemp) { + dst.overheatProtection.highTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "overheat_protection/low_temp") { + input = std::round(input); + + if (!isSettingInteger(input, 0, 255)) { + return {}; + } + + unsigned char value = static_cast(input); + + if (value != 0 && !isValidTemp(value, UnitSystem::METRIC, 0.0f, 99.0f)) { + return {}; + } + + if (value != dst.overheatProtection.lowTemp) { + dst.overheatProtection.lowTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TARGET) { + return setDhwTarget(dst, input); + } + + return {}; +} + +JsonVariant toJson(const DhwSettings& src, JsonVariant dst) { + auto dhw = dst.to(); + dhw[S_ENABLED] = src.enabled; + dhw[S_TARGET] = roundf(convertTemp(src.target, UnitSystem::METRIC, settings.system.unitSystem), 1); + dhw[S_MIN_TEMP] = convertTemp(src.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + dhw[S_MAX_TEMP] = convertTemp(src.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + dhw[S_MAX_MODULATION] = src.maxModulation; + + auto dhwOverheatProtection = dhw[S_OVERHEAT_PROTECTION].to(); + dhwOverheatProtection[S_HIGH_TEMP] = src.overheatProtection.highTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem); + dhwOverheatProtection[S_LOW_TEMP] = src.overheatProtection.lowTemp == 0 + ? 0 + : convertTemp(src.overheatProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, DhwSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MIN_TEMP].is()) { + float value = convertTemp(src[S_MIN_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MIN_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MAX_TEMP].is()) { + float value = convertTemp(src[S_MAX_TEMP].as(), settings.system.unitSystem, UnitSystem::METRIC); + const auto fieldResult = applySetting(dst, S_MAX_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeDhwBounds(dst) || result.changed; + + if (src[S_MAX_MODULATION].is()) { + const auto value = src[S_MAX_MODULATION].as(); + const auto fieldResult = applySetting(dst, S_MAX_MODULATION, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_HIGH_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/high_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].is()) { + float value = src[S_OVERHEAT_PROTECTION][S_LOW_TEMP].as(); + if (value != 0) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, "overheat_protection/low_temp", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizeDhwOverheatBounds(dst) || result.changed; + + float value = src[S_TARGET].is() + ? convertTemp(src[S_TARGET].as(), settings.system.unitSystem, UnitSystem::METRIC) + : dst.target; + const auto fieldResult = applySetting(dst, S_TARGET, value); + result.changed = fieldResult.changed || result.changed; + if (src[S_TARGET].is()) { + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// PID settings + +static bool normalizePidBounds(PidSettings& dst) { + bool changed = false; + + if (dst.maxTemp < dst.minTemp) { + dst.maxTemp = dst.minTemp; + changed = true; + } + + return changed; +} + +static SettingResult applySetting(PidSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (!settings.opentherm.options.nativeOTC) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + } else if (dst.enabled) { + dst.enabled = false; + changed = true; + } + + return {.changed = changed, .accepted = !value || !settings.opentherm.options.nativeOTC}; + } + + if (path == "deadband/enabled") { + if (value != dst.deadband.enabled) { + dst.deadband.enabled = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +static SettingResult applySetting(PidSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == S_P_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value <= 0 || value > 1000) { + return {}; + } + + if (isFloatDifferent(value, dst.p_factor, 0.0001f)) { + dst.p_factor = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_I_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0 || value > 100) { + return {}; + } + + if (isFloatDifferent(value, dst.i_factor, 0.0001f)) { + dst.i_factor = roundf(value, 4); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_D_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0 || value > 100000) { + return {}; + } + + if (isFloatDifferent(value, dst.d_factor, 0.0001f)) { + dst.d_factor = roundf(value, 1); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_DT) { + if (!isSettingInteger(input, 0, 65535)) { + return {}; + } + + unsigned short value = static_cast(input); + + if (value < 30 || value > 1800) { + return {}; + } + + if (value != dst.dt) { + dst.dt = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MIN_TEMP) { + if (!settings.equitherm.enabled) { + input = std::round(input); + } + + if (!isSettingInteger(input, -32768, 32767)) { + return {}; + } + + short value = static_cast(input); + + if (settings.equitherm.enabled) { + if (value < -99.9f || value > 99.9f) { + return {}; + } + + } else if (!isValidTemp(value, UnitSystem::METRIC, 0.0f)) { + return {}; + } + + if (value != dst.minTemp) { + dst.minTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_MAX_TEMP) { + if (!settings.equitherm.enabled) { + input = std::round(input); + } + + if (!isSettingInteger(input, -32768, 32767)) { + return {}; + } + + short value = static_cast(input); + + if (settings.equitherm.enabled) { + if (value < 0.1f || value > 99.9f) { + return {}; + } + + } else if (!isValidTemp(value, UnitSystem::METRIC)) { + return {}; + } + + if (value != dst.maxTemp) { + dst.maxTemp = value; + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/p_multiplier") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0 || value > 1) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.p_multiplier, 0.0001f)) { + dst.deadband.p_multiplier = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/i_multiplier") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0 || value > 1) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.i_multiplier, 0.0001f)) { + dst.deadband.i_multiplier = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/d_multiplier") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0 || value > 1) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.d_multiplier, 0.0001f)) { + dst.deadband.d_multiplier = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/threshold_high") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0.0f || value > 5.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.thresholdHigh, 0.0001f)) { + dst.deadband.thresholdHigh = roundf(value, 2); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == "deadband/threshold_low") { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0.0f || value > 5.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.deadband.thresholdLow, 0.0001f)) { + dst.deadband.thresholdLow = roundf(value, 2); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +JsonVariant toJson(const PidSettings& src, JsonVariant dst) { + auto pid = dst.to(); + pid[S_ENABLED] = src.enabled; + pid[S_P_FACTOR] = roundf(src.p_factor, 3); + pid[S_I_FACTOR] = roundf(src.i_factor, 4); + pid[S_D_FACTOR] = roundf(src.d_factor, 1); + pid[S_DT] = src.dt; + pid[S_MIN_TEMP] = settings.equitherm.enabled + ? src.minTemp + : convertTemp(src.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + pid[S_MAX_TEMP] = settings.equitherm.enabled + ? src.maxTemp + : convertTemp(src.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto pidDeadband = pid[S_DEADBAND].to(); + pidDeadband[S_ENABLED] = src.deadband.enabled; + pidDeadband[S_P_MULTIPLIER] = src.deadband.p_multiplier; + pidDeadband[S_I_MULTIPLIER] = src.deadband.i_multiplier; + pidDeadband[S_D_MULTIPLIER] = src.deadband.d_multiplier; + pidDeadband[S_THRESHOLD_HIGH] = src.deadband.thresholdHigh; + pidDeadband[S_THRESHOLD_LOW] = src.deadband.thresholdLow; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, PidSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_P_FACTOR].is()) { + const auto value = src[S_P_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_P_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_I_FACTOR].is()) { + const auto value = src[S_I_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_I_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_D_FACTOR].is()) { + const auto value = src[S_D_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_D_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DT].is()) { + const auto value = src[S_DT].as(); + const auto fieldResult = applySetting(dst, S_DT, static_cast(value)); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MIN_TEMP].is()) { + float value = src[S_MIN_TEMP].as(); + if (!settings.equitherm.enabled) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, S_MIN_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_MAX_TEMP].is()) { + float value = src[S_MAX_TEMP].as(); + if (!settings.equitherm.enabled) { + value = convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + const auto fieldResult = applySetting(dst, S_MAX_TEMP, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + result.changed = normalizePidBounds(dst) || result.changed; + + if (src[S_DEADBAND][S_ENABLED].is()) { + const auto value = src[S_DEADBAND][S_ENABLED].as(); + const auto fieldResult = applySetting(dst, "deadband/enabled", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_P_MULTIPLIER].is()) { + const auto value = src[S_DEADBAND][S_P_MULTIPLIER].as(); + const auto fieldResult = applySetting(dst, "deadband/p_multiplier", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_I_MULTIPLIER].is()) { + const auto value = src[S_DEADBAND][S_I_MULTIPLIER].as(); + const auto fieldResult = applySetting(dst, "deadband/i_multiplier", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_D_MULTIPLIER].is()) { + const auto value = src[S_DEADBAND][S_D_MULTIPLIER].as(); + const auto fieldResult = applySetting(dst, "deadband/d_multiplier", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_THRESHOLD_HIGH].is()) { + const auto value = src[S_DEADBAND][S_THRESHOLD_HIGH].as(); + const auto fieldResult = applySetting(dst, "deadband/threshold_high", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_DEADBAND][S_THRESHOLD_LOW].is()) { + const auto value = src[S_DEADBAND][S_THRESHOLD_LOW].as(); + const auto fieldResult = applySetting(dst, "deadband/threshold_low", value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// Equitherm settings + +static SettingResult applySetting(EquithermSettings& dst, std::string_view path, bool value) { + bool changed = false; + + if (path == S_ENABLED) { + if (!settings.opentherm.options.nativeOTC) { + if (value != dst.enabled) { + dst.enabled = value; + changed = true; + } + + } else if (dst.enabled) { + dst.enabled = false; + changed = true; + } + + return {.changed = changed, .accepted = !value || !settings.opentherm.options.nativeOTC}; + } + + return {}; +} + +static SettingResult applySetting(EquithermSettings& dst, std::string_view path, float input) { + bool changed = false; + + if (path == S_SLOPE) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0.001f || value > 10.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.slope, 0.0001f)) { + dst.slope = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_EXPONENT) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value <= 0.01f || value > 2.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.exponent, 0.0001f)) { + dst.exponent = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_SHIFT) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < -15.0f || value > 15.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.shift, 0.0001f)) { + dst.shift = roundf(value, 2); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + if (path == S_TARGET_DIFF_FACTOR) { + float value = input; + + if (!std::isfinite(value)) { + return {}; + } + + if (value < 0.0f || value > 10.0f) { + return {}; + } + + if (isFloatDifferent(value, dst.targetDiffFactor, 0.0001f)) { + dst.targetDiffFactor = roundf(value, 3); + changed = true; + } + + return {.changed = changed, .accepted = true}; + } + + return {}; +} + +JsonVariant toJson(const EquithermSettings& src, JsonVariant dst) { + auto equitherm = dst.to(); + equitherm[S_ENABLED] = src.enabled; + equitherm[S_SLOPE] = roundf(src.slope, 3); + equitherm[S_EXPONENT] = roundf(src.exponent, 3); + equitherm[S_SHIFT] = roundf(src.shift, 2); + equitherm[S_TARGET_DIFF_FACTOR] = roundf(src.targetDiffFactor, 3); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, EquithermSettings& dst) { + SettingResult result; + + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + const auto fieldResult = applySetting(dst, S_ENABLED, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_SLOPE].is()) { + const auto value = src[S_SLOPE].as(); + const auto fieldResult = applySetting(dst, S_SLOPE, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_EXPONENT].is()) { + const auto value = src[S_EXPONENT].as(); + const auto fieldResult = applySetting(dst, S_EXPONENT, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_SHIFT].is()) { + const auto value = src[S_SHIFT].as(); + const auto fieldResult = applySetting(dst, S_SHIFT, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + if (src[S_TARGET_DIFF_FACTOR].is()) { + const auto value = src[S_TARGET_DIFF_FACTOR].as(); + const auto fieldResult = applySetting(dst, S_TARGET_DIFF_FACTOR, value); + result.changed = fieldResult.changed || result.changed; + result.accepted = fieldResult.accepted || result.accepted; + } + + return result; +} + +// External pump settings + +JsonVariant toJson(const ExternalPumpSettings& src, JsonVariant dst) { + auto externalPump = dst.to(); + externalPump[S_USE] = src.use; + externalPump[S_GPIO] = src.gpio; + externalPump[S_INVERT_STATE] = src.invertState; + externalPump[S_POST_CIRCULATION_TIME] = roundf(src.postCirculationTime / 60, 0); + externalPump[S_ANTI_STUCK_INTERVAL] = roundf(src.antiStuckInterval / 86400, 0); + externalPump[S_ANTI_STUCK_TIME] = roundf(src.antiStuckTime / 60, 0); + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, ExternalPumpSettings& dst) { + SettingResult result; + + if (src[S_USE].is()) { + const auto value = src[S_USE].as(); + + result.accepted = true; + if (value != dst.use) { + dst.use = value; + result.changed = true; + } + } + + if (!src[S_GPIO].isNull()) { + if (src[S_GPIO].is() && src[S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_GPIO].is()) { + const auto value = src[S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.gpio) { + dst.gpio = value; + result.changed = true; + } + } + } + } + + if (src[S_INVERT_STATE].is()) { + const auto value = src[S_INVERT_STATE].as(); + + result.accepted = true; + if (value != dst.invertState) { + dst.invertState = value; + result.changed = true; + } + } + + if (src[S_POST_CIRCULATION_TIME].is()) { + unsigned short value = src[S_POST_CIRCULATION_TIME].as(); + + if (value <= 120) { + value = value * 60; + + result.accepted = true; + if (value != dst.postCirculationTime) { + dst.postCirculationTime = value; + result.changed = true; + } + } + } + + if (src[S_ANTI_STUCK_INTERVAL].is()) { + unsigned int value = src[S_ANTI_STUCK_INTERVAL].as(); + + if (value <= 366) { + value = value * 86400; + + result.accepted = true; + if (value != dst.antiStuckInterval) { + dst.antiStuckInterval = value; + result.changed = true; + } + } + } + + if (src[S_ANTI_STUCK_TIME].is()) { + unsigned short value = src[S_ANTI_STUCK_TIME].as(); + + if (value <= 20) { + value = value * 60; + + result.accepted = true; + if (value != dst.antiStuckTime) { + dst.antiStuckTime = value; + result.changed = true; + } + } + } + + return result; +} + +// Cascade control settings + +JsonVariant toJson(const CascadeControlSettings& src, JsonVariant dst) { + auto cascadeControl = dst.to(); + auto cascadeControlInput = cascadeControl[S_INPUT].to(); + cascadeControlInput[S_ENABLED] = src.input.enabled; + cascadeControlInput[S_GPIO] = src.input.gpio; + cascadeControlInput[S_INVERT_STATE] = src.input.invertState; + cascadeControlInput[S_THRESHOLD_TIME] = src.input.thresholdTime; + + auto cascadeControlOutput = cascadeControl[S_OUTPUT].to(); + cascadeControlOutput[S_ENABLED] = src.output.enabled; + cascadeControlOutput[S_GPIO] = src.output.gpio; + cascadeControlOutput[S_INVERT_STATE] = src.output.invertState; + cascadeControlOutput[S_THRESHOLD_TIME] = src.output.thresholdTime; + cascadeControlOutput[S_ON_FAULT] = src.output.onFault; + cascadeControlOutput[S_ON_LOSS_CONNECTION] = src.output.onLossConnection; + cascadeControlOutput[S_ON_ENABLED_HEATING] = src.output.onEnabledHeating; + + return dst; +} + +SettingResult fromJson(JsonVariantConst src, CascadeControlSettings& dst) { + SettingResult result; + + if (src[S_INPUT][S_ENABLED].is()) { + const auto value = src[S_INPUT][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.input.enabled) { + dst.input.enabled = value; + result.changed = true; + } + } + + if (!src[S_INPUT][S_GPIO].isNull()) { + if (src[S_INPUT][S_GPIO].is() && src[S_INPUT][S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.input.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.input.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_INPUT][S_GPIO].is()) { + const auto value = src[S_INPUT][S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_INPUT(value)) { + result.accepted = true; + if (value != dst.input.gpio) { + dst.input.gpio = value; + result.changed = true; + } + } + } + } + + if (src[S_INPUT][S_INVERT_STATE].is()) { + const auto value = src[S_INPUT][S_INVERT_STATE].as(); + + result.accepted = true; + if (value != dst.input.invertState) { + dst.input.invertState = value; + result.changed = true; + } + } + + if (src[S_INPUT][S_THRESHOLD_TIME].is()) { + const auto value = src[S_INPUT][S_THRESHOLD_TIME].as(); + + if (value >= 5 && value <= 600) { + result.accepted = true; + if (value != dst.input.thresholdTime) { + dst.input.thresholdTime = value; + result.changed = true; + } + } + } + + if (src[S_OUTPUT][S_ENABLED].is()) { + const auto value = src[S_OUTPUT][S_ENABLED].as(); + + result.accepted = true; + if (value != dst.output.enabled) { + dst.output.enabled = value; + result.changed = true; + } + } + + if (!src[S_OUTPUT][S_GPIO].isNull()) { + if (src[S_OUTPUT][S_GPIO].is() && src[S_OUTPUT][S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.output.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.output.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_OUTPUT][S_GPIO].is()) { + const auto value = src[S_OUTPUT][S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED || GPIO_IS_VALID_OUTPUT(value)) { + result.accepted = true; + if (value != dst.output.gpio) { + dst.output.gpio = value; + result.changed = true; + } + } + } + } + + if (src[S_OUTPUT][S_INVERT_STATE].is()) { + const auto value = src[S_OUTPUT][S_INVERT_STATE].as(); + + result.accepted = true; + if (value != dst.output.invertState) { + dst.output.invertState = value; + result.changed = true; + } + } + + if (src[S_OUTPUT][S_THRESHOLD_TIME].is()) { + const auto value = src[S_OUTPUT][S_THRESHOLD_TIME].as(); + + if (value >= 5 && value <= 600) { + result.accepted = true; + if (value != dst.output.thresholdTime) { + dst.output.thresholdTime = value; + result.changed = true; + } + } + } + + if (src[S_OUTPUT][S_ON_FAULT].is()) { + const auto value = src[S_OUTPUT][S_ON_FAULT].as(); + + result.accepted = true; + if (value != dst.output.onFault) { + dst.output.onFault = value; + result.changed = true; + } + } + + if (src[S_OUTPUT][S_ON_LOSS_CONNECTION].is()) { + const auto value = src[S_OUTPUT][S_ON_LOSS_CONNECTION].as(); + + result.accepted = true; + if (value != dst.output.onLossConnection) { + dst.output.onLossConnection = value; + result.changed = true; + } + } + + if (src[S_OUTPUT][S_ON_ENABLED_HEATING].is()) { + const auto value = src[S_OUTPUT][S_ON_ENABLED_HEATING].as(); + + result.accepted = true; + if (value != dst.output.onEnabledHeating) { + dst.output.onEnabledHeating = value; + result.changed = true; + } + } + + return result; +} + +// MQTT paths and cross-section normalization + +SettingResult applySetting(Settings& dst, std::string_view path, bool value) { + const auto separator = path.find('/'); + if (separator == std::string_view::npos) { + return {}; + } + + const auto section = path.substr(0, separator); + path.remove_prefix(separator + 1); + + if (section == S_EQUITHERM) { + return applySetting(dst.equitherm, path, value); + } + + if (section == S_PID) { + return applySetting(dst.pid, path, value); + } + + if (section == S_HEATING) { + return applySetting(dst.heating, path, value); + } + + if (section == S_DHW) { + return applySetting(dst.dhw, path, value); + } + + return {}; +} + +SettingResult applySetting(Settings& dst, std::string_view path, float input) { + const auto separator = path.find('/'); + if (separator == std::string_view::npos) { + return {}; + } + + const auto section = path.substr(0, separator); + path.remove_prefix(separator + 1); + + if (section == S_EQUITHERM) { + return applySetting(dst.equitherm, path, input); + } + + if (section == S_PID) { + return applySetting(dst.pid, path, input); + } + + if (section == S_HEATING) { + return applySetting(dst.heating, path, input); + } + + if (section == S_DHW) { + return applySetting(dst.dhw, path, input); + } + + if (section == S_EMERGENCY) { + return applySetting(dst.emergency, path, input); + } + + return {}; +} + +static bool normalizeRegulatorModes(Settings& dst) { + bool changed = false; + + if (dst.opentherm.options.nativeOTC) { + if (dst.equitherm.enabled) { + dst.equitherm.enabled = false; + changed = true; + } + if (dst.pid.enabled) { + dst.pid.enabled = false; + changed = true; + } + } + + return changed; +} + +bool normalizeSettings(Settings& dst) { + bool changed = false; + + changed = normalizeRegulatorModes(dst) || changed; + + changed = normalizePidBounds(dst.pid) || changed; + changed = normalizeHeatingBounds(dst.heating) || changed; + changed = normalizeHeatingOverheatBounds(dst.heating) || changed; + changed = normalizeHeatingFreezeBounds(dst.heating) || changed; + changed = normalizeDhwBounds(dst.dhw) || changed; + changed = normalizeDhwOverheatBounds(dst.dhw) || changed; + + changed = setEmergencyTarget(dst.emergency, dst.emergency.target).changed || changed; + changed = setHeatingTarget(dst.heating, dst.heating.target).changed || changed; + changed = setDhwTarget(dst.dhw, dst.dhw.target).changed || changed; + + return changed; +} + +// Sensor settings + +JsonVariant toJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst) { + dst[S_ID] = sensorId; + dst[S_ENABLED] = src.enabled; + // Snapshot storage is temporary; the pointer adapter copies the name. + dst[S_NAME] = static_cast(src.name); + dst[S_SLUG] = static_cast(src.slug); + dst[S_PURPOSE] = static_cast(src.purpose); + dst[S_TYPE] = static_cast(src.type); + dst[S_GPIO] = src.gpio; + + if (src.type == Sensors::Type::DALLAS_TEMP) { + char addr[24]; + sprintf( + addr, + "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", + src.address[0], src.address[1], src.address[2], src.address[3], + src.address[4], src.address[5], src.address[6], src.address[7] + ); + dst[S_ADDRESS] = addr; + + } else if (src.type == Sensors::Type::BLUETOOTH) { + char addr[18]; + sprintf( + addr, + "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", + src.address[0], src.address[1], src.address[2], + src.address[3], src.address[4], src.address[5] + ); + dst[S_ADDRESS] = addr; + + } else { + dst[S_ADDRESS] = ""; + } + + dst[S_OFFSET] = roundf(src.offset, 3); + dst[S_FACTOR] = roundf(src.factor, 3); + dst[S_FILTERING] = src.filtering; + dst[S_FILTERING_FACTOR] = roundf(src.filteringFactor, 3); + return dst; +} + +SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) { + SettingResult result; + + // enabled + if (src[S_ENABLED].is()) { + const auto value = src[S_ENABLED].as(); + result.accepted = true; + + if (value != dst.enabled) { + dst.enabled = value; + result.changed = true; + } + } + + // name + if (src[S_NAME].is()) { + const auto raw = src[S_NAME].as(); + 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) { + 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; + } + } + + if (dst.enabled && !dst.slug[0]) { + dst.enabled = false; + result.changed = true; + } + + // purpose + if (src[S_PURPOSE].is()) { + const auto value = src[S_PURPOSE].as(); + + switch (value) { + case static_cast(Sensors::Purpose::OUTDOOR_TEMP): + case static_cast(Sensors::Purpose::INDOOR_TEMP): + case static_cast(Sensors::Purpose::HEATING_TEMP): + case static_cast(Sensors::Purpose::HEATING_RETURN_TEMP): + case static_cast(Sensors::Purpose::DHW_TEMP): + case static_cast(Sensors::Purpose::DHW_RETURN_TEMP): + case static_cast(Sensors::Purpose::DHW_FLOW_RATE): + case static_cast(Sensors::Purpose::EXHAUST_TEMP): + case static_cast(Sensors::Purpose::MODULATION_LEVEL): + + case static_cast(Sensors::Purpose::NUMBER): + case static_cast(Sensors::Purpose::POWER_FACTOR): + case static_cast(Sensors::Purpose::POWER): + case static_cast(Sensors::Purpose::FAN_SPEED): + case static_cast(Sensors::Purpose::CO2): + case static_cast(Sensors::Purpose::PRESSURE): + case static_cast(Sensors::Purpose::HUMIDITY): + case static_cast(Sensors::Purpose::TEMPERATURE): + case static_cast(Sensors::Purpose::NOT_CONFIGURED): + result.accepted = true; + if (static_cast(dst.purpose) != value) { + dst.purpose = static_cast(value); + result.changed = true; + } + break; + + default: + break; + } + } + + // type + if (src[S_TYPE].is()) { + const auto value = src[S_TYPE].as(); + + switch (value) { + case static_cast(Sensors::Type::OT_OUTDOOR_TEMP): + case static_cast(Sensors::Type::OT_HEATING_TEMP): + case static_cast(Sensors::Type::OT_HEATING_RETURN_TEMP): + case static_cast(Sensors::Type::OT_DHW_TEMP): + case static_cast(Sensors::Type::OT_DHW_TEMP2): + case static_cast(Sensors::Type::OT_DHW_FLOW_RATE): + case static_cast(Sensors::Type::OT_CH2_TEMP): + case static_cast(Sensors::Type::OT_EXHAUST_TEMP): + case static_cast(Sensors::Type::OT_HEAT_EXCHANGER_TEMP): + case static_cast(Sensors::Type::OT_PRESSURE): + case static_cast(Sensors::Type::OT_MODULATION_LEVEL): + case static_cast(Sensors::Type::OT_CURRENT_POWER): + case static_cast(Sensors::Type::OT_EXHAUST_CO2): + case static_cast(Sensors::Type::OT_EXHAUST_FAN_SPEED): + case static_cast(Sensors::Type::OT_SUPPLY_FAN_SPEED): + case static_cast(Sensors::Type::OT_SOLAR_STORAGE_TEMP): + case static_cast(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP): + case static_cast(Sensors::Type::OT_FAN_SPEED_SETPOINT): + case static_cast(Sensors::Type::OT_FAN_SPEED_CURRENT): + + case static_cast(Sensors::Type::OT_BURNER_STARTS): + case static_cast(Sensors::Type::OT_DHW_BURNER_STARTS): + case static_cast(Sensors::Type::OT_HEATING_PUMP_STARTS): + case static_cast(Sensors::Type::OT_DHW_PUMP_STARTS): + case static_cast(Sensors::Type::OT_BURNER_HOURS): + case static_cast(Sensors::Type::OT_DHW_BURNER_HOURS): + case static_cast(Sensors::Type::OT_HEATING_PUMP_HOURS): + case static_cast(Sensors::Type::OT_DHW_PUMP_HOURS): + case static_cast(Sensors::Type::OT_COOLING_HOURS): + + case static_cast(Sensors::Type::NTC_10K_TEMP): + case static_cast(Sensors::Type::DALLAS_TEMP): + case static_cast(Sensors::Type::BLUETOOTH): + case static_cast(Sensors::Type::DHT11): + case static_cast(Sensors::Type::DHT22): + case static_cast(Sensors::Type::HEATING_SETPOINT_TEMP): + case static_cast(Sensors::Type::MANUAL): + case static_cast(Sensors::Type::NOT_CONFIGURED): + result.accepted = true; + if (static_cast(dst.type) != value) { + dst.type = static_cast(value); + result.changed = true; + } + break; + + default: + break; + } + } + + // gpio + if (!src[S_GPIO].isNull()) { + if (dst.type != Sensors::Type::DALLAS_TEMP && dst.type != Sensors::Type::NTC_10K_TEMP && + dst.type != Sensors::Type::DHT11 && dst.type != Sensors::Type::DHT22) { + if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_GPIO].is() && src[S_GPIO].as().size() == 0) { + result.accepted = true; + if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { + dst.gpio = GPIO_IS_NOT_CONFIGURED; + result.changed = true; + } + + } else if (src[S_GPIO].is()) { + const auto value = src[S_GPIO].as(); + + if (value == GPIO_IS_NOT_CONFIGURED + || (GPIO_IS_VALID_INPUT(value) + && (dst.type == Sensors::Type::NTC_10K_TEMP || GPIO_IS_VALID_OUTPUT(value)))) { + result.accepted = true; + if (value != dst.gpio) { + dst.gpio = value; + result.changed = true; + } + } + } + } + + // address + if (src[S_ADDRESS].is()) { + const JsonString value = src[S_ADDRESS].as(); + + 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; + } + } + + } 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; + } + } + } + + // offset + if (src[S_OFFSET].is()) { + const auto value = src[S_OFFSET].as(); + + if (value >= -20.0f && value <= 20.0f) { + result.accepted = true; + if (isFloatDifferent(value, dst.offset, 0.0001f)) { + dst.offset = roundf(value, 2); + result.changed = true; + } + } + } + + // factor + if (src[S_FACTOR].is()) { + const auto value = src[S_FACTOR].as(); + + if (value > 0.09f && value <= 100.0f) { + result.accepted = true; + if (isFloatDifferent(value, dst.factor, 0.0001f)) { + dst.factor = roundf(value, 3); + result.changed = true; + } + } + } + + // filtering + if (src[S_FILTERING].is()) { + const auto value = src[S_FILTERING].as(); + result.accepted = true; + + if (value != dst.filtering) { + dst.filtering = value; + result.changed = true; + } + } + + // filtering factor + if (src[S_FILTERING_FACTOR].is()) { + const auto value = src[S_FILTERING_FACTOR].as(); + + if (value >= 0.001f && value <= 1.0f) { + result.accepted = true; + if (isFloatDifferent(value, dst.filteringFactor, 0.0001f)) { + dst.filteringFactor = roundf(value, 3); + result.changed = true; + } + } + } + + return result; +} + +// Sensor measurements + +JsonVariant toJson(const Sensors::Settings& sSensor, const Sensors::Result& rSensor, JsonVariant dst) { + dst[S_CONNECTED] = rSensor.connected; + dst[S_SIGNAL_QUALITY] = rSensor.signalQuality; + + if (sSensor.type == Sensors::Type::BLUETOOTH) { + dst[S_TEMPERATURE] = roundf(convertTemp(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], UnitSystem::METRIC, settings.system.unitSystem), 3); + dst[S_HUMIDITY] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); + dst[S_BATTERY] = roundf(rSensor.values[static_cast(Sensors::ValueType::BATTERY)], 1); + dst[S_RSSI] = roundf(rSensor.values[static_cast(Sensors::ValueType::RSSI)], 0); + + } else if (sSensor.type == Sensors::Type::DHT11 || sSensor.type == Sensors::Type::DHT22) { + dst[S_TEMPERATURE] = roundf(convertTemp(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], UnitSystem::METRIC, settings.system.unitSystem), 3); + dst[S_HUMIDITY] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); + + } else { + dst[S_VALUE] = roundf(Sensors::convertValue(sSensor, Sensors::ValueType::PRIMARY, rSensor.values[static_cast(Sensors::ValueType::PRIMARY)], UnitSystem::METRIC, settings.system.unitSystem), 3); + } + return dst; +} + +JsonVariant toJson(const uint8_t sensorId, JsonVariant dst) { + if (const auto snapshot = Sensors::getSnapshot(sensorId)) { + return toJson(snapshot->settings, snapshot->result, dst); + } + return dst; +} + +// Runtime variables and actions + +JsonVariant toJson(const Variables& src, JsonVariant dst) { + auto slave = dst[S_SLAVE].to(); + slave[S_MEMBER_ID] = src.slave.memberId; + slave[S_FLAGS] = src.slave.flags; + slave[S_TYPE] = src.slave.type; + slave[S_APP_VERSION] = src.slave.appVersion; + slave[S_PROTOCOL_VERSION] = src.slave.protocolVersion; + slave[S_CONNECTED] = src.slave.connected; + slave[S_FLAME] = src.slave.flame; + + auto sCooling = slave[S_COOLING].to(); + sCooling[S_ACTIVE] = src.slave.cooling.active; + sCooling[S_SETPOINT] = src.slave.cooling.setpoint; + + auto sModulation = slave[S_MODULATION].to(); + sModulation[S_MIN] = src.slave.modulation.min; + sModulation[S_MAX] = src.slave.modulation.max; + + auto sPower = slave[S_POWER].to(); + sPower[S_MIN] = roundf(src.slave.power.min, 2); + sPower[S_MAX] = roundf(src.slave.power.max, 2); + + auto sHeating = slave[S_HEATING].to(); + sHeating[S_ACTIVE] = src.slave.heating.active; + sHeating[S_MIN_TEMP] = convertTemp(src.slave.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + sHeating[S_MAX_TEMP] = convertTemp(src.slave.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto sDhw = slave[S_DHW].to(); + sDhw[S_ACTIVE] = src.slave.dhw.active; + sDhw[S_MIN_TEMP] = convertTemp(src.slave.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + sDhw[S_MAX_TEMP] = convertTemp(src.slave.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + auto sFault = slave[S_FAULT].to(); + sFault[S_ACTIVE] = src.slave.fault.active; + sFault[S_CODE] = src.slave.fault.code; + + auto sDiag = slave[S_DIAG].to(); + sDiag[S_ACTIVE] = src.slave.diag.active; + sDiag[S_CODE] = src.slave.diag.code; + + + auto master = dst[S_MASTER].to(); + auto mHeating = master[S_HEATING].to(); + mHeating[S_ENABLED] = src.master.heating.enabled; + mHeating[S_BLOCKING] = src.master.heating.blocking; + mHeating[S_INDOOR_TEMP_CONTROL] = src.master.heating.indoorTempControl; + mHeating[S_OVERHEAT] = src.master.heating.overheat; + mHeating[S_FREEZING] = src.master.heating.freezing; + mHeating[S_SETPOINT_TEMP] = roundf((src.master.heating.setpointTemp == 0 ? 0 : convertTemp(src.master.heating.setpointTemp, UnitSystem::METRIC, settings.system.unitSystem)), 2); + mHeating[S_TARGET_TEMP] = roundf((src.master.heating.targetTemp == 0 ? 0 : convertTemp(src.master.heating.targetTemp, UnitSystem::METRIC, settings.system.unitSystem)), 2); + mHeating[S_CURRENT_TEMP] = roundf(convertTemp(src.master.heating.currentTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_RETURN_TEMP] = roundf(convertTemp(src.master.heating.returnTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_INDOOR_TEMP] = roundf(convertTemp(src.master.heating.indoorTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_OUTDOOR_TEMP] = roundf(convertTemp(src.master.heating.outdoorTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_MIN_TEMP] = roundf(convertTemp(src.master.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mHeating[S_MAX_TEMP] = roundf(convertTemp(src.master.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + + auto mDhw = master[S_DHW].to(); + mDhw[S_ENABLED] = src.master.dhw.enabled; + mDhw[S_OVERHEAT] = src.master.dhw.overheat; + mDhw[S_TARGET_TEMP] = roundf((src.master.dhw.targetTemp == 0 ? 0 : convertTemp(src.master.dhw.targetTemp, UnitSystem::METRIC, settings.system.unitSystem)), 2); + mDhw[S_CURRENT_TEMP] = roundf(convertTemp(src.master.dhw.currentTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mDhw[S_RETURN_TEMP] = roundf(convertTemp(src.master.dhw.returnTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + mDhw[S_MIN_TEMP] = convertTemp(settings.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem); + mDhw[S_MAX_TEMP] = convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem); + + master[S_NETWORK][S_CONNECTED] = isNetworkConnected(); + master[S_NETWORK][S_RSSI] = src.network.rssi; + master[S_MQTT][S_CONNECTED] = isMqttConnected(); + master[S_EMERGENCY][S_STATE] = src.emergency.state; + master[S_EXTERNAL_PUMP][S_STATE] = src.externalPump.state; + + auto mCascadeControl = master[S_CASCADE_CONTROL].to(); + mCascadeControl[S_INPUT] = src.cascadeControl.input; + mCascadeControl[S_OUTPUT] = src.cascadeControl.output; + + master[S_UPTIME] = millis() / 1000; + return dst; +} + +static SettingResult applyAction(Variables& dst, std::string_view action, bool value) { + SettingResult result; + if (action == "restart") { + if (value) { + restartTask.resume(15000); + result.changed = true; + } + + result.accepted = true; + return result; + } + + if (action == "reset_fault") { + if (value && !dst.actions.resetFault) { + dst.actions.resetFault = true; + result.changed = true; + } + + result.accepted = true; + return result; + } + + if (action == "reset_diagnostic") { + if (value && !dst.actions.resetDiagnostic) { + dst.actions.resetDiagnostic = true; + result.changed = true; + } + + result.accepted = true; + return result; + } + + return result; +} + +bool applyAction(std::string_view action, bool value) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return false; + } + + return applyAction(vars, action, value).accepted; +} + +SettingResult fromJson(const JsonVariantConst src, Variables& dst) { + SettingResult result; + + // Admit the whole request before one of its actions schedules a restart. + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return result; + } + + if (src[S_ACTIONS][S_RESTART].is()) { + const auto actionResult = applyAction(dst, "restart", src[S_ACTIONS][S_RESTART].as()); + result.changed = actionResult.changed || result.changed; + result.accepted = actionResult.accepted || result.accepted; + } + + if (src[S_ACTIONS][S_RESET_FAULT].is()) { + const auto actionResult = applyAction(dst, "reset_fault", src[S_ACTIONS][S_RESET_FAULT].as()); + result.changed = actionResult.changed || result.changed; + result.accepted = actionResult.accepted || result.accepted; + } + + if (src[S_ACTIONS][S_RESET_DIAGNOSTIC].is()) { + const auto actionResult = applyAction(dst, "reset_diagnostic", src[S_ACTIONS][S_RESET_DIAGNOSTIC].as()); + result.changed = actionResult.changed || result.changed; + result.accepted = actionResult.accepted || result.accepted; + } + + return result; +} diff --git a/src/control.cpp b/src/control.cpp new file mode 100644 index 0000000..7132d26 --- /dev/null +++ b/src/control.cpp @@ -0,0 +1,455 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include + +Variables vars; + +enum class PumpStartReason {NONE, HEATING, ANTISTUCK}; + +static bool heatingEnabled = false; +static unsigned long heatingDisabledTime = 0; +static PumpStartReason extPumpStartReason = PumpStartReason::NONE; +static unsigned long externalPumpStartTime = 0; +static bool emergencyDetected = false; +static unsigned long emergencyFlipTime = 0; + +static Task freezeProtectionTask("Freeze protection", [](void*) { + float lowTemp = 255.0f; + uint8_t availableSensors = 0; + + if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { + auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::INDOOR_TEMP, Sensors::ValueType::PRIMARY, settings.heating.indoorTempAvgType); + if (value < lowTemp) { + lowTemp = value; + } + + availableSensors++; + } + + if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_TEMP)) { + auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_TEMP, Sensors::ValueType::PRIMARY); + if (value < lowTemp) { + lowTemp = value; + } + + availableSensors++; + } + + if (Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP)) { + auto value = Sensors::getMeanValueByPurpose(Sensors::Purpose::HEATING_RETURN_TEMP, Sensors::ValueType::PRIMARY); + if (value < lowTemp) { + lowTemp = value; + } + + availableSensors++; + } + + if (availableSensors) { + if (vars.master.heating.freezing) { + if (lowTemp - static_cast(settings.heating.freezeProtection.highTemp) + 0.0001f >= 0.0f) { + vars.master.heating.freezing = false; + + ESP_LOGI( + L_MAIN, + "No freezing detected. Current low temp: %.2f, threshold (high): %hhu", + lowTemp, settings.heating.freezeProtection.highTemp + ); + } + + } else { + if (static_cast(settings.heating.freezeProtection.lowTemp) - lowTemp + 0.0001f >= 0.0f) { + vars.master.heating.freezing = true; + + if (!settings.heating.enabled) { + settings.heating.enabled = true; + requestSaveSettings(); + } + + ESP_LOGI( + L_MAIN, + "Freezing detected! Current low temp: %.2f, threshold (low): %hhu", + lowTemp, settings.heating.freezeProtection.lowTemp + ); + } + } + + } else if (vars.master.heating.freezing) { + vars.master.heating.freezing = false; + + ESP_LOGI(L_MAIN, "No sensors available, freeze protection unavailable!"); + } +}); + +static Task emergencyTask("Emergency mode", [](void*) { + // flags + uint8_t emergencyFlags = 0b00000000; + + // set outdoor sensor flag + if (settings.equitherm.enabled) { + if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::OUTDOOR_TEMP)) { + emergencyFlags |= 0b00000001; + } + } + + // set indoor sensor flags + if (!Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP)) { + if (!settings.equitherm.enabled && settings.pid.enabled) { + emergencyFlags |= 0b00000010; + } + + if (settings.opentherm.options.nativeOTC) { + emergencyFlags |= 0b00000100; + } + } + + // if any flags is true + if ((emergencyFlags & 0b00001111) != 0) { + if (!emergencyDetected) { + // flip flag + emergencyDetected = true; + emergencyFlipTime = millis(); + + } else if (emergencyDetected && !vars.emergency.state) { + // enable emergency + if (millis() - emergencyFlipTime > (settings.emergency.tresholdTime * 1000)) { + vars.emergency.state = true; + ESP_LOGI(L_MAIN, "Emergency mode enabled (%hhu)", emergencyFlags); + } + } + + } else { + if (emergencyDetected) { + // flip flag + emergencyDetected = false; + emergencyFlipTime = millis(); + + } else if (!emergencyDetected && vars.emergency.state) { + // disable emergency + if (millis() - emergencyFlipTime > (settings.emergency.tresholdTime * 1000)) { + vars.emergency.state = false; + ESP_LOGI(L_MAIN, "Emergency mode disabled"); + } + } + } +}); + +static Task overheatProtectionTask("Overheat protection", [](void*) { + // Heating overheat control + if (settings.heating.overheatProtection.highTemp > 0 && settings.heating.overheatProtection.lowTemp > 0) { + const float highTemp = std::max({ + vars.slave.heating.currentTemp, + vars.slave.heating.returnTemp, + vars.slave.heatExchangerTemp + }); + + if (vars.master.heating.overheat) { + if (static_cast(settings.heating.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) { + vars.master.heating.overheat = false; + + ESP_LOGI( + L_OT_HEATING, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu", + highTemp, settings.heating.overheatProtection.lowTemp + ); + } + + } else if (vars.slave.heating.active) { + if (highTemp - static_cast(settings.heating.overheatProtection.highTemp) + 0.0001f >= 0.0f) { + vars.master.heating.overheat = true; + + ESP_LOGW( + L_OT_HEATING, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu", + highTemp, settings.heating.overheatProtection.highTemp + ); + } + } + + } else if (vars.master.heating.overheat) { + vars.master.heating.overheat = false; + } + + // DHW overheat control + if (settings.dhw.overheatProtection.highTemp > 0 && settings.dhw.overheatProtection.lowTemp > 0) { + const float highTemp = std::max({ + vars.slave.heating.currentTemp, + vars.slave.heating.returnTemp, + vars.slave.heatExchangerTemp, + vars.slave.dhw.currentTemp, + vars.slave.dhw.currentTemp2, + vars.slave.dhw.returnTemp + }); + + if (vars.master.dhw.overheat) { + if (static_cast(settings.dhw.overheatProtection.lowTemp) - highTemp + 0.0001f >= 0.0f) { + vars.master.dhw.overheat = false; + + ESP_LOGI( + L_OT_DHW, "Overheating not detected. Current high temp: %.2f, threshold (low): %hhu", + highTemp, settings.dhw.overheatProtection.lowTemp + ); + } + + } else if (vars.slave.dhw.active) { + if (highTemp - static_cast(settings.dhw.overheatProtection.highTemp) + 0.0001f >= 0.0f) { + vars.master.dhw.overheat = true; + + ESP_LOGW( + L_OT_DHW, "Overheating detected! Current high temp: %.2f, threshold (high): %hhu", + highTemp, settings.dhw.overheatProtection.highTemp + ); + } + } + + } else if (vars.master.dhw.overheat) { + vars.master.dhw.overheat = false; + } +}); + +static Task cascadeTask("Cascade", [](void*) { + static uint8_t configuredInputGpio = GPIO_IS_NOT_CONFIGURED; + static uint8_t configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; + static bool pendingInputState = false; + static unsigned long inputChangedTime = 0; + static bool pendingOutputState = false; + static unsigned long outputChangedTime = 0; + + // input + if (settings.cascadeControl.input.enabled) { + if (settings.cascadeControl.input.gpio != configuredInputGpio) { + if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { + // Keep the old input high-impedance, including input-only GPIOs. + pinMode(configuredInputGpio, INPUT); + + ESP_LOGI(L_CASCADE_INPUT, "Deinitialized on GPIO %hhu", configuredInputGpio); + } + + if (GPIO_IS_VALID_INPUT(settings.cascadeControl.input.gpio)) { + configuredInputGpio = settings.cascadeControl.input.gpio; + pinMode(configuredInputGpio, INPUT); + + ESP_LOGI(L_CASCADE_INPUT, "Initialized on GPIO %hhu", configuredInputGpio); + + } else if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { + configuredInputGpio = GPIO_IS_NOT_CONFIGURED; + + ESP_LOGW(L_CASCADE_INPUT, "Failed initialize: GPIO %hhu is not valid!", configuredInputGpio); + } + } + + if (configuredInputGpio != GPIO_IS_NOT_CONFIGURED) { + bool value = (digitalRead(configuredInputGpio) == HIGH) ^ settings.cascadeControl.input.invertState; + + if (value != vars.cascadeControl.input) { + if (value != pendingInputState) { + pendingInputState = value; + inputChangedTime = millis(); + + } else if (millis() - inputChangedTime >= settings.cascadeControl.input.thresholdTime * 1000u) { + vars.cascadeControl.input = value; + + ESP_LOGI( + L_CASCADE_INPUT, + "State changed to %s", + value ? "TRUE" : "FALSE" + ); + } + + } else if (value != pendingInputState) { + pendingInputState = value; + } + } + } + + if (!settings.cascadeControl.input.enabled || configuredInputGpio == GPIO_IS_NOT_CONFIGURED) { + if (!vars.cascadeControl.input) { + vars.cascadeControl.input = true; + + ESP_LOGI( + L_CASCADE_INPUT, + "Disabled, state changed to %s", + vars.cascadeControl.input ? "TRUE" : "FALSE" + ); + } + } + + + // output + if (settings.cascadeControl.output.gpio != configuredOutputGpio) { + if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(configuredOutputGpio, LOW); + pinMode(configuredOutputGpio, DISABLED); + + ESP_LOGI(L_CASCADE_OUTPUT, "Deinitialized on GPIO %hhu", configuredOutputGpio); + } + + if (GPIO_IS_VALID_OUTPUT(settings.cascadeControl.output.gpio)) { + configuredOutputGpio = settings.cascadeControl.output.gpio; + pinMode(configuredOutputGpio, OUTPUT); + + ESP_LOGI(L_CASCADE_OUTPUT, "Initialized on GPIO %hhu", configuredOutputGpio); + + } else if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + configuredOutputGpio = GPIO_IS_NOT_CONFIGURED; + + ESP_LOGW(L_CASCADE_OUTPUT, "Failed initialize: GPIO %hhu is not valid!", configuredOutputGpio); + } + } + + if (settings.cascadeControl.output.enabled) { + if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + bool value = false; + if (settings.cascadeControl.output.onFault && vars.slave.fault.active) { + value = true; + + } else if (settings.cascadeControl.output.onLossConnection && !vars.slave.connected) { + value = true; + + } else if (settings.cascadeControl.output.onEnabledHeating && settings.heating.enabled && vars.cascadeControl.input) { + value = true; + } + + if (value != vars.cascadeControl.output) { + if (value != pendingOutputState) { + pendingOutputState = value; + outputChangedTime = millis(); + + } else if (millis() - outputChangedTime >= settings.cascadeControl.output.thresholdTime * 1000u) { + vars.cascadeControl.output = value; + + ESP_LOGI( + L_CASCADE_OUTPUT, + "State changed to %s", + value ? "TRUE" : "FALSE" + ); + } + + } else if (value != pendingOutputState) { + pendingOutputState = value; + } + } + } + + if (!settings.cascadeControl.output.enabled || configuredOutputGpio == GPIO_IS_NOT_CONFIGURED) { + if (vars.cascadeControl.output) { + vars.cascadeControl.output = false; + + ESP_LOGI( + L_CASCADE_OUTPUT, + "Disabled, state changed to %s", + vars.cascadeControl.output ? "TRUE" : "FALSE" + ); + } + } + + if (configuredOutputGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite( + configuredOutputGpio, + (vars.cascadeControl.output ^ settings.cascadeControl.output.invertState) ? HIGH : LOW + ); + } +}); + +static Task externalPumpTask("External pump", [](void*) { + static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; + + if (settings.externalPump.gpio != configuredGpio) { + if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(configuredGpio, LOW); + pinMode(configuredGpio, DISABLED); + } + + if (GPIO_IS_VALID_OUTPUT(settings.externalPump.gpio)) { + configuredGpio = settings.externalPump.gpio; + pinMode(configuredGpio, OUTPUT); + + } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + configuredGpio = GPIO_IS_NOT_CONFIGURED; + } + } + + if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { + if (vars.externalPump.state) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = millis(); + + ESP_LOGI(L_EXTPUMP, "Disabled: use = off"); + } + + return; + } + + if (!vars.master.heating.enabled && heatingEnabled) { + heatingEnabled = false; + heatingDisabledTime = millis(); + + } else if (vars.master.heating.enabled && !heatingEnabled) { + heatingEnabled = true; + } + + if (!settings.externalPump.use) { + if (vars.externalPump.state) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = millis(); + + ESP_LOGI(L_EXTPUMP, "Disabled: use = off"); + } + + } else if (vars.externalPump.state && !heatingEnabled) { + if (extPumpStartReason == PumpStartReason::HEATING && millis() - heatingDisabledTime > (settings.externalPump.postCirculationTime * 1000u)) { + vars.externalPump.state = false; + vars.externalPump.lastEnabledTime = millis(); + + 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(); + + ESP_LOGI(L_EXTPUMP, "Disabled: expired anti stuck time"); + } + + } else if (vars.externalPump.state && heatingEnabled && extPumpStartReason == PumpStartReason::ANTISTUCK) { + extPumpStartReason = PumpStartReason::HEATING; + + } else if (!vars.externalPump.state && heatingEnabled) { + vars.externalPump.state = true; + externalPumpStartTime = millis(); + extPumpStartReason = PumpStartReason::HEATING; + + ESP_LOGI(L_EXTPUMP, "Enabled: heating on"); + + } else if (!vars.externalPump.state && (vars.externalPump.lastEnabledTime == 0 || millis() - vars.externalPump.lastEnabledTime >= (settings.externalPump.antiStuckInterval * 1000lu))) { + vars.externalPump.state = true; + externalPumpStartTime = millis(); + extPumpStartReason = PumpStartReason::ANTISTUCK; + + ESP_LOGI(L_EXTPUMP, "Enabled: anti stuck"); + } + + digitalWrite( + configuredGpio, + (vars.externalPump.state ^ settings.externalPump.invertState) ? HIGH : LOW + ); +}); + +void initControl() { + freezeProtectionTask.setInterval(1000); + coreTaskManager.addTask(freezeProtectionTask); + + emergencyTask.setInterval(1000); + coreTaskManager.addTask(emergencyTask); + + // The OpenTherm loop previously skipped overheat control while disconnected. + overheatProtectionTask.setEnabledWhen([] { + return vars.slave.connected; + }); + overheatProtectionTask.setInterval(1000); + coreTaskManager.addTask(overheatProtectionTask); + + cascadeTask.setInterval(1000); + coreTaskManager.addTask(cascadeTask); + + externalPumpTask.setInterval(1000); + coreTaskManager.addTask(externalPumpTask); +} diff --git a/src/ha_discovery.cpp b/src/ha_discovery.cpp new file mode 100644 index 0000000..4d25a52 --- /dev/null +++ b/src/ha_discovery.cpp @@ -0,0 +1,1181 @@ +#include + +#include + +HA::Discovery haDiscovery; + +void publishHaEntity(HaEntity entityId, bool remove) { + std::unique_ptr entity; + const UnitSystem unit = settings.system.unitSystem; + const uint32_t stateExpiration = std::max(60u, 2u * settings.mqtt.interval); + + switch (entityId) { + case HA_ENTITY_HEATING_TURBO: { + auto toggle = std::make_unique("heating_turbo", "Turbo heating"); + if (!remove) { + toggle->stateTopic = "~/settings/heating/turbo"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:rocket-launch-outline"; + toggle->enabledByDefault = false; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_HEATING_HYSTERESIS_ENABLED: { + auto toggle = std::make_unique("heating_hysteresis", "Use heating hysteresis"); + if (!remove) { + toggle->stateTopic = "~/settings/heating/hysteresis/enabled"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:altimeter"; + toggle->enabledByDefault = true; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_HEATING_HYSTERESIS_VALUE: { + auto number = std::make_unique("heating_hysteresis", "Heating hysteresis"); + if (!remove) { + number->stateTopic = "~/settings/heating/hysteresis/value"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 15; + number->step = 0.01f; + number->icon = "mdi:altimeter"; + number->enabledByDefault = true; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_HEATING_TURBO_FACTOR: { + auto number = std::make_unique("heating_turbo_factor", "Heating turbo factor"); + if (!remove) { + number->stateTopic = "~/settings/heating/turbo_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 1.5f; + number->max = 10; + number->step = 0.01f; + number->icon = "mdi:multiplication-box"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_HEATING_MIN_TEMP: { + auto number = std::make_unique("heating_min_temp", "Heating min temp"); + if (!remove) { + number->stateTopic = "~/settings/heating/min_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.heating.minTemp, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.heating.maxTemp - 1.0f, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-down"; + number->deviceClass = S_TEMPERATURE; + number->enabledByDefault = true; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_HEATING_MAX_TEMP: { + auto number = std::make_unique("heating_max_temp", "Heating max temp"); + if (!remove) { + number->stateTopic = "~/settings/heating/max_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.heating.minTemp + 1.0f, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.heating.maxTemp, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-up"; + number->deviceClass = S_TEMPERATURE; + number->enabledByDefault = true; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_ENABLED: { + auto toggle = std::make_unique("pid", "PID"); + if (!remove) { + toggle->stateTopic = "~/settings/pid/enabled"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:chart-bar-stacked"; + toggle->enabledByDefault = true; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_PID_P_FACTOR: { + auto number = std::make_unique("pid_p_factor", "PID factor P"); + if (!remove) { + number->stateTopic = "~/settings/pid/p_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0.001f; + number->max = 1000; + number->step = 0.001f; + number->icon = "mdi:alpha-p-circle-outline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_I_FACTOR: { + auto number = std::make_unique("pid_i_factor", "PID factor I"); + if (!remove) { + number->stateTopic = "~/settings/pid/i_factor"; + number->commandTopic = number->stateTopic + "/set"; + // Home Assistant requires a Number step of at least 0.001. + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 100; + number->step = 0.001f; + number->icon = "mdi:alpha-i-circle-outline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_D_FACTOR: { + auto number = std::make_unique("pid_d_factor", "PID factor D"); + if (!remove) { + number->stateTopic = "~/settings/pid/d_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 100000; + number->step = 0.1f; + number->icon = "mdi:alpha-d-circle-outline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_DT: { + auto number = std::make_unique("pid_dt", "PID DT"); + if (!remove) { + number->stateTopic = "~/settings/pid/dt"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 30; + number->max = 1800; + number->step = 1; + number->icon = "mdi:timer-cog-outline"; + number->enabledByDefault = false; + number->deviceClass = "duration"; + number->unit = "s"; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_MIN_TEMP: { + auto number = std::make_unique("pid_min_temp", "PID min temp"); + if (!remove) { + number->stateTopic = "~/settings/pid/min_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = settings.equitherm.enabled + ? -99.0f + : convertTemp(0, UnitSystem::METRIC, unit); + number->max = settings.equitherm.enabled + ? 99.0f + : convertTemp(99, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = settings.equitherm.enabled ? 1.0f : 0.1f; + } + number->icon = "mdi:thermometer-chevron-down"; + number->enabledByDefault = false; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_PID_MAX_TEMP: { + auto number = std::make_unique("pid_max_temp", "PID max temp"); + if (!remove) { + number->stateTopic = "~/settings/pid/max_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = settings.equitherm.enabled + ? 1.0f + : convertTemp(1, UnitSystem::METRIC, unit); + number->max = settings.equitherm.enabled + ? 99.0f + : convertTemp(99, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = settings.equitherm.enabled ? 1.0f : 0.1f; + } + number->icon = "mdi:thermometer-chevron-up"; + number->enabledByDefault = false; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_ENABLED: { + auto toggle = std::make_unique("equitherm", "Equitherm"); + if (!remove) { + toggle->stateTopic = "~/settings/equitherm/enabled"; + toggle->commandTopic = toggle->stateTopic + "/set"; + toggle->category = HA::Category::CONFIG; + toggle->payloadOn = S_TRUE; + toggle->payloadOff = S_FALSE; + toggle->icon = "mdi:sun-snowflake-variant"; + toggle->enabledByDefault = true; + } + entity = std::move(toggle); + break; + } + + case HA_ENTITY_EQUITHERM_SLOPE: { + auto number = std::make_unique("equitherm_slope", "Equitherm slope"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/slope"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0.001f; + number->max = 10; + number->step = 0.001f; + number->icon = "mdi:slope-uphill"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_EXPONENT: { + auto number = std::make_unique("equitherm_exponent", "Equitherm exponent"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/exponent"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0.011f; + number->max = 2; + number->step = 0.001f; + number->icon = "mdi:exponent"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_SHIFT: { + auto number = std::make_unique("equitherm_shift", "Equitherm shift"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/shift"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = -15; + number->max = 15; + number->step = 0.01f; + number->icon = "mdi:chart-areaspline"; + number->enabledByDefault = false; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_EQUITHERM_TARGET_DIFF_FACTOR: { + auto number = std::make_unique("equitherm_target_diff_factor", "Equitherm target diff factor"); + if (!remove) { + number->stateTopic = "~/settings/equitherm/target_diff_factor"; + number->commandTopic = number->stateTopic + "/set"; + number->availabilityTopic = "~/settings/pid/enabled"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = 0; + number->max = 10; + number->step = 0.001f; + number->icon = "mdi:chart-timeline-variant-shimmer"; + number->enabledByDefault = false; + number->payloadAvailable = S_FALSE; + number->payloadNotAvailable = S_TRUE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_STATUS: { + auto state = std::make_unique("status", "Status"); + if (!remove) { + state->stateTopic = "~/status"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = "ON"; + state->payloadOff = "OFF"; + state->deviceClass = "problem"; + state->icon = "mdi:list-status"; + state->useDeviceAvailability = false; + state->valueTemplate = "{{ iif(value == 'online', 'OFF', 'ON') }}"; + state->expireAfter = stateExpiration; + state->enabledByDefault = true; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_EMERGENCY: { + auto state = std::make_unique("emergency", "Emergency"); + if (!remove) { + state->stateTopic = "~/state/master/emergency/state"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:alert-rhombus-outline"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_OPENTHERM_STATUS: { + auto state = std::make_unique("ot_status", "Opentherm status"); + if (!remove) { + state->stateTopic = "~/state/slave/connected"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "connectivity"; + state->icon = "mdi:list-status"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_HEATING: { + auto state = std::make_unique("heating", "Heating"); + if (!remove) { + state->stateTopic = "~/state/slave/heating/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:radiator"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_FLAME: { + auto state = std::make_unique("flame", "Flame"); + if (!remove) { + state->stateTopic = "~/state/slave/flame"; + state->availabilityTopic = "~/state/slave/connected"; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:gas-burner"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_FAULT: { + auto state = std::make_unique("fault", "Fault"); + if (!remove) { + state->stateTopic = "~/state/slave/fault/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:alert-remove-outline"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_DIAGNOSTIC: { + auto state = std::make_unique("diagnostic", "Diagnostic"); + if (!remove) { + state->stateTopic = "~/state/slave/diag/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:account-wrench"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_EXTERNAL_PUMP: { + auto state = std::make_unique("ext_pump", "External pump"); + if (!remove) { + state->stateTopic = "~/state/master/ext_pump/state"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:pump"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_FAULT_CODE: { + auto value = std::make_unique("fault_code", "Fault code"); + if (!remove) { + value->stateTopic = "~/state/slave/fault/code"; + value->availabilityTopic = "~/state/slave/fault/available"; + value->category = HA::Category::DIAGNOSTIC; + value->icon = "mdi:cog-box"; + value->valueTemplate = "{{ '%02d (0x%02X)' | format(value | int, value | int) }}"; + value->enabledByDefault = true; + value->expireAfter = stateExpiration; + value->payloadAvailable = S_TRUE; + value->payloadNotAvailable = S_FALSE; + } + entity = std::move(value); + break; + } + + case HA_ENTITY_DIAGNOSTIC_CODE: { + auto value = std::make_unique("diagnostic_code", "Diagnostic code"); + if (!remove) { + value->stateTopic = "~/state/slave/diag/code"; + value->availabilityTopic = "~/state/slave/diag/available"; + value->category = HA::Category::DIAGNOSTIC; + value->icon = "mdi:information-box"; + value->valueTemplate = "{{ '%02d (0x%02X)' | format(value | int, value | int) }}"; + value->enabledByDefault = true; + value->expireAfter = stateExpiration; + value->payloadAvailable = S_TRUE; + value->payloadNotAvailable = S_FALSE; + } + entity = std::move(value); + break; + } + + case HA_ENTITY_RSSI: { + auto gauge = std::make_unique("rssi", "RSSI"); + if (!remove) { + gauge->stateTopic = "~/state/master/network/rssi"; + gauge->category = HA::Category::DIAGNOSTIC; + gauge->deviceClass = "signal_strength"; + gauge->icon = "mdi:signal"; + gauge->unit = "dBm"; + gauge->enabledByDefault = false; + gauge->expireAfter = stateExpiration; + } + entity = std::move(gauge); + break; + } + + case HA_ENTITY_UPTIME: { + auto counter = std::make_unique("uptime", "Uptime"); + if (!remove) { + counter->stateTopic = "~/state/master/uptime"; + counter->category = HA::Category::DIAGNOSTIC; + counter->deviceClass = "duration"; + counter->icon = "mdi:clock-start"; + counter->unit = "s"; + counter->enabledByDefault = false; + counter->expireAfter = stateExpiration; + } + entity = std::move(counter); + break; + } + + case HA_ENTITY_RESTART: { + auto button = std::make_unique("restart", "Restart"); + if (!remove) { + button->commandTopic = "~/actions/restart/set"; + button->category = HA::Category::CONFIG; + button->deviceClass = "restart"; + button->payloadPress = S_TRUE; + button->enabledByDefault = false; + } + entity = std::move(button); + break; + } + + case HA_ENTITY_RESET_FAULT: { + auto button = std::make_unique("reset_fault", "Reset fault"); + if (!remove) { + button->commandTopic = "~/actions/reset_fault/set"; + button->availabilityTopic = "~/state/slave/fault/active"; + button->category = HA::Category::CONFIG; + button->deviceClass = "restart"; + button->payloadPress = S_TRUE; + button->enabledByDefault = true; + button->payloadAvailable = S_TRUE; + button->payloadNotAvailable = S_FALSE; + } + entity = std::move(button); + break; + } + + case HA_ENTITY_RESET_DIAGNOSTIC: { + auto button = std::make_unique("reset_diagnostic", "Reset diagnostic"); + if (!remove) { + button->commandTopic = "~/actions/reset_diagnostic/set"; + button->availabilityTopic = "~/state/slave/diag/active"; + button->category = HA::Category::CONFIG; + button->deviceClass = "restart"; + button->payloadPress = S_TRUE; + button->enabledByDefault = true; + button->payloadAvailable = S_TRUE; + button->payloadNotAvailable = S_FALSE; + } + entity = std::move(button); + break; + } + + case HA_ENTITY_HEATING_CLIMATE: { + auto climate = std::make_unique("heating", "Heating"); + if (!remove) { + climate->icon = "mdi:radiator"; + climate->enabledByDefault = true; + climate->currentTemperatureTopic = vars.master.heating.indoorTempControl + ? "~/state/master/heating/indoor_temp" + : "~/state/master/heating/current_temp"; + climate->temperatureCommandTopic = "~/settings/heating/target/set"; + climate->temperatureStateTopic = "~/settings/heating/target"; + climate->modeCommandTopic = "~/settings/heating/enabled/set"; + climate->modeCommandTemplate = "{% if value == 'heat' %}true{% elif value == 'off' %}false{% endif %}"; + climate->modeStateTopic = "~/settings/heating/enabled"; + climate->modeStateTemplate = "{{ 'heat' if value == 'true' else 'off' }}"; + climate->modes = {"off", "heat"}; + climate->actionTopic = "~/state/slave/heating/active"; + climate->actionTemplate = "{{ 'heating' if value == 'true' else 'idle' }}"; + climate->presetModeCommandTopic = "~/settings/heating/turbo/set"; + climate->presetModeCommandTemplate = "{% if value == 'boost' %}true{% elif value == 'none' %}false{% endif %}"; + climate->presetModeStateTopic = "~/settings/heating/turbo"; + climate->presetModeValueTemplate = "{{ 'boost' if value == 'true' else 'none' }}"; + // Home Assistant adds the reserved reset preset "none" itself. + climate->presetModes = {"boost"}; + if (unit == UnitSystem::METRIC) { + climate->temperatureUnit = "C"; + + } else if (unit == UnitSystem::IMPERIAL) { + climate->temperatureUnit = "F"; + } + climate->minTemp = convertTemp(vars.master.heating.minTemp, UnitSystem::METRIC, unit); + climate->maxTemp = convertTemp(vars.master.heating.maxTemp, UnitSystem::METRIC, unit); + climate->tempStep = 0.1f; + } + entity = std::move(climate); + break; + } + + case HA_ENTITY_DHW_MIN_TEMP: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto number = std::make_unique("dhw_min_temp", "DHW min temp"); + if (!remove) { + number->stateTopic = "~/settings/dhw/min_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.dhw.minTemp, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.dhw.maxTemp - 1.0f, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-down"; + number->enabledByDefault = true; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_DHW_MAX_TEMP: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto number = std::make_unique("dhw_max_temp", "DHW max temp"); + if (!remove) { + number->stateTopic = "~/settings/dhw/max_temp"; + number->commandTopic = number->stateTopic + "/set"; + number->category = HA::Category::CONFIG; + number->mode = HA::NumberMode::BOX; + number->min = convertTemp(vars.slave.dhw.minTemp + 1.0f, UnitSystem::METRIC, unit); + number->max = convertTemp(vars.slave.dhw.maxTemp, UnitSystem::METRIC, unit); + if (unit == UnitSystem::METRIC) { + number->unit = "°C"; + number->step = 1.0f; + + } else if (unit == UnitSystem::IMPERIAL) { + number->unit = "°F"; + number->step = 0.1f; + } + number->icon = "mdi:thermometer-chevron-up"; + number->enabledByDefault = true; + number->deviceClass = S_TEMPERATURE; + } + entity = std::move(number); + break; + } + + case HA_ENTITY_DHW: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto state = std::make_unique("dhw", "DHW"); + if (!remove) { + state->stateTopic = "~/state/slave/dhw/active"; + state->availabilityTopic = "~/state/slave/connected"; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "running"; + state->icon = "mdi:faucet"; + state->enabledByDefault = true; + state->expireAfter = stateExpiration; + state->payloadAvailable = S_TRUE; + state->payloadNotAvailable = S_FALSE; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_DHW_CLIMATE: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto climate = std::make_unique("dhw", "DHW"); + if (!remove) { + climate->icon = "mdi:faucet"; + climate->enabledByDefault = true; + climate->currentTemperatureTopic = "~/state/master/dhw/current_temp"; + climate->temperatureCommandTopic = "~/settings/dhw/target/set"; + climate->temperatureStateTopic = "~/settings/dhw/target"; + climate->modeCommandTopic = "~/settings/dhw/enabled/set"; + climate->modeCommandTemplate = "{% if value == 'heat' %}true{% elif value == 'off' %}false{% endif %}"; + climate->modeStateTopic = "~/settings/dhw/enabled"; + climate->modeStateTemplate = "{{ 'heat' if value == 'true' else 'off' }}"; + climate->modes = {"off", "heat"}; + climate->actionTopic = "~/state/slave/dhw/active"; + climate->actionTemplate = "{{ 'heating' if value == 'true' else 'idle' }}"; + if (unit == UnitSystem::METRIC) { + climate->temperatureUnit = "C"; + + } else if (unit == UnitSystem::IMPERIAL) { + climate->temperatureUnit = "F"; + } + climate->minTemp = convertTemp(settings.dhw.minTemp, UnitSystem::METRIC, unit); + climate->maxTemp = convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, unit); + climate->tempStep = 0.1f; + } + entity = std::move(climate); + break; + } + + case HA_ENTITY_HEATING_BLOCKING: { + auto state = std::make_unique("heating_blocking", "Heating blocking"); + if (!remove) { + state->stateTopic = "~/state/master/heating/blocking"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:radiator-off"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_HEATING_OVERHEAT: { + auto state = std::make_unique("heating_overheat", "Heating overheat"); + if (!remove) { + state->stateTopic = "~/state/master/heating/overheat"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:thermometer-alert"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_HEATING_FREEZING: { + auto state = std::make_unique("heating_freezing", "Heating freezing"); + if (!remove) { + state->stateTopic = "~/state/master/heating/freezing"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:snowflake"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_DHW_OVERHEAT: { + remove = remove || !settings.opentherm.options.dhwSupport; + auto state = std::make_unique("dhw_overheat", "DHW overheat"); + if (!remove) { + state->stateTopic = "~/state/master/dhw/overheat"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->deviceClass = "problem"; + state->icon = "mdi:thermometer-alert"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_CASCADE_CONTROL_INPUT: { + auto state = std::make_unique("cascade_control_input", "Cascade control input"); + if (!remove) { + state->stateTopic = "~/state/master/cascade_control/input"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:import"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + case HA_ENTITY_CASCADE_CONTROL_OUTPUT: { + auto state = std::make_unique("cascade_control_output", "Cascade control output"); + if (!remove) { + state->stateTopic = "~/state/master/cascade_control/output"; + state->category = HA::Category::DIAGNOSTIC; + state->payloadOn = S_TRUE; + state->payloadOff = S_FALSE; + state->icon = "mdi:export"; + state->enabledByDefault = false; + state->expireAfter = stateExpiration; + } + entity = std::move(state); + break; + } + + default: { + return; + } + } + + if (remove) { + haDiscovery.unpublish(std::move(entity)); + + } else { + haDiscovery.publish(std::move(entity)); + } +} + +static std::string makeDynamicSensorId(const Sensors::Settings& sensor, Sensors::ValueType valueType) { + std::string id = sensor.slug; + if (id.empty()) { + return {}; + } + const bool multiple = sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22; + if (!multiple) { + return valueType == Sensors::ValueType::PRIMARY ? id : std::string(); + } + + switch (valueType) { + case Sensors::ValueType::TEMPERATURE: + return id + "_temp"; + case Sensors::ValueType::HUMIDITY: + return id + "_humidity"; + case Sensors::ValueType::BATTERY: + return id + "_battery"; + case Sensors::ValueType::RSSI: + return id + "_rssi"; + default: + return {}; + } +} + +static const char* getDynamicSensorIcon(Sensors::Purpose purpose) { + switch (purpose) { + case Sensors::Purpose::OUTDOOR_TEMP: + return "mdi:home-thermometer-outline"; + case Sensors::Purpose::INDOOR_TEMP: + return "mdi:home-thermometer"; + case Sensors::Purpose::HEATING_TEMP: + return "mdi:radiator"; + case Sensors::Purpose::HEATING_RETURN_TEMP: + case Sensors::Purpose::DHW_RETURN_TEMP: + return "mdi:heating-coil"; + case Sensors::Purpose::DHW_TEMP: + case Sensors::Purpose::DHW_FLOW_RATE: + return "mdi:faucet"; + case Sensors::Purpose::EXHAUST_TEMP: + return "mdi:smoke"; + case Sensors::Purpose::TEMPERATURE: + return "mdi:thermometer-lines"; + case Sensors::Purpose::MODULATION_LEVEL: + return "mdi:fire-circle"; + case Sensors::Purpose::POWER_FACTOR: + case Sensors::Purpose::POWER: + return "mdi:chart-bar"; + case Sensors::Purpose::FAN_SPEED: + return "mdi:fan"; + case Sensors::Purpose::PRESSURE: + return "mdi:gauge"; + case Sensors::Purpose::HUMIDITY: + return "mdi:water-percent"; + default: + return nullptr; + } +} + +void publishDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType, bool enabledByDefault) { + auto id = makeDynamicSensorId(sensor, valueType); + if (id.empty()) { + return; + } + + const UnitSystem unit = settings.system.unitSystem; + auto entity = std::make_unique(std::move(id), sensor.name); + entity->icon = getDynamicSensorIcon(sensor.purpose); + entity->availabilityTopic = mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED); + entity->payloadAvailable = S_TRUE; + entity->payloadNotAvailable = S_FALSE; + entity->expireAfter = 2u * MQTT_SENSOR_REPUBLISH_INTERVAL / 1000u; + entity->enabledByDefault = enabledByDefault; + + switch (sensor.purpose) { + case Sensors::Purpose::OUTDOOR_TEMP: + case Sensors::Purpose::INDOOR_TEMP: + case Sensors::Purpose::HEATING_TEMP: + case Sensors::Purpose::HEATING_RETURN_TEMP: + case Sensors::Purpose::DHW_TEMP: + case Sensors::Purpose::DHW_RETURN_TEMP: + case Sensors::Purpose::EXHAUST_TEMP: + case Sensors::Purpose::TEMPERATURE: + entity->deviceClass = S_TEMPERATURE; + if (unit == UnitSystem::METRIC) { + entity->unit = "°C"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "°F"; + } + break; + + case Sensors::Purpose::DHW_FLOW_RATE: + entity->deviceClass = "volume_flow_rate"; + if (unit == UnitSystem::METRIC) { + entity->unit = "L/min"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "gal/min"; + } + break; + + case Sensors::Purpose::MODULATION_LEVEL: + case Sensors::Purpose::POWER_FACTOR: + entity->deviceClass = "power_factor"; + entity->unit = "%"; + break; + + case Sensors::Purpose::POWER: + entity->deviceClass = "power"; + entity->unit = "kW"; + break; + + case Sensors::Purpose::FAN_SPEED: + entity->unit = "RPM"; + break; + + case Sensors::Purpose::CO2: + entity->deviceClass = "carbon_dioxide"; + entity->unit = "ppm"; + break; + + case Sensors::Purpose::PRESSURE: + entity->deviceClass = "pressure"; + if (unit == UnitSystem::METRIC) { + entity->unit = "bar"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "psi"; + } + break; + + case Sensors::Purpose::HUMIDITY: + entity->deviceClass = S_HUMIDITY; + entity->unit = "%"; + break; + + default: + break; + } + + if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { + switch (valueType) { + case Sensors::ValueType::TEMPERATURE: + entity->name += " "; + entity->name += S_TEMPERATURE; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE); + entity->deviceClass = S_TEMPERATURE; + if (unit == UnitSystem::METRIC) { + entity->unit = "°C"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "°F"; + } + break; + + case Sensors::ValueType::HUMIDITY: + entity->name += " "; + entity->name += S_HUMIDITY; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY); + entity->deviceClass = S_HUMIDITY; + entity->unit = "%"; + break; + + case Sensors::ValueType::BATTERY: + entity->name += " "; + entity->name += S_BATTERY; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_BATTERY); + entity->deviceClass = S_BATTERY; + entity->unit = "%"; + entity->category = HA::Category::DIAGNOSTIC; + break; + + case Sensors::ValueType::RSSI: + entity->name += " "; + entity->name += S_RSSI; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_RSSI); + entity->deviceClass = "signal_strength"; + entity->unit = "dBm"; + entity->category = HA::Category::DIAGNOSTIC; + break; + + default: + return; + } + + } else { + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_VALUE); + } + + haDiscovery.publish(std::move(entity)); +} + +void publishDynamicManualSensor(const Sensors::Settings& sensor, bool enabledByDefault) { + auto id = makeDynamicSensorId(sensor, Sensors::ValueType::PRIMARY); + if (id.empty()) { + return; + } + + const UnitSystem unit = settings.system.unitSystem; + auto entity = std::make_unique(std::move(id), sensor.name); + entity->icon = getDynamicSensorIcon(sensor.purpose); + entity->category = HA::Category::CONFIG; + entity->enabledByDefault = enabledByDefault; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_VALUE); + entity->commandTopic = entity->stateTopic + "/set"; + entity->mode = HA::NumberMode::BOX; + entity->step = 0.01f; + entity->min.reset(); + entity->max.reset(); + + switch (sensor.purpose) { + case Sensors::Purpose::OUTDOOR_TEMP: + case Sensors::Purpose::INDOOR_TEMP: + case Sensors::Purpose::HEATING_TEMP: + case Sensors::Purpose::HEATING_RETURN_TEMP: + case Sensors::Purpose::DHW_TEMP: + case Sensors::Purpose::DHW_RETURN_TEMP: + case Sensors::Purpose::EXHAUST_TEMP: + case Sensors::Purpose::TEMPERATURE: + entity->deviceClass = S_TEMPERATURE; + if (unit == UnitSystem::METRIC) { + entity->unit = "°C"; + entity->min = -99; + entity->max = 99; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "°F"; + entity->min = -147; + entity->max = 211; + } + break; + + case Sensors::Purpose::DHW_FLOW_RATE: + entity->deviceClass = "volume_flow_rate"; + if (unit == UnitSystem::METRIC) { + entity->unit = "L/min"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "gal/min"; + } + break; + + case Sensors::Purpose::MODULATION_LEVEL: + case Sensors::Purpose::POWER_FACTOR: + entity->deviceClass = "power_factor"; + entity->unit = "%"; + break; + + case Sensors::Purpose::POWER: + entity->deviceClass = "power"; + entity->unit = "kW"; + break; + + case Sensors::Purpose::FAN_SPEED: + entity->unit = "RPM"; + break; + + case Sensors::Purpose::CO2: + entity->deviceClass = "carbon_dioxide"; + entity->unit = "ppm"; + break; + + case Sensors::Purpose::PRESSURE: + entity->deviceClass = "pressure"; + if (unit == UnitSystem::METRIC) { + entity->unit = "bar"; + + } else if (unit == UnitSystem::IMPERIAL) { + entity->unit = "psi"; + } + break; + + case Sensors::Purpose::HUMIDITY: + entity->deviceClass = S_HUMIDITY; + entity->unit = "%"; + break; + + default: + break; + } + + haDiscovery.publish(std::move(entity)); +} + +void deleteDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType) { + auto id = makeDynamicSensorId(sensor, valueType); + if (id.empty()) { + return; + } + + if (sensor.type == Sensors::Type::MANUAL) { + haDiscovery.unpublish(std::move(id), ""); + return; + } + + haDiscovery.unpublish(std::move(id), ""); +} + +void publishConnectionDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault) { + auto entity = std::make_unique( + std::string(sensor.slug) + "_connected", std::string(sensor.name) + " connected" + ); + entity->category = HA::Category::DIAGNOSTIC; + entity->deviceClass = "connectivity"; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED); + entity->payloadOn = S_TRUE; + entity->payloadOff = S_FALSE; + entity->enabledByDefault = enabledByDefault; + entity->expireAfter = 2u * MQTT_SENSOR_REPUBLISH_INTERVAL / 1000u; + haDiscovery.publish(std::move(entity)); +} + +void deleteConnectionDynamicSensor(const Sensors::Settings& sensor) { + haDiscovery.unpublish(std::string(sensor.slug) + "_connected", ""); +} + +void publishSignalQualityDynamicSensor(const Sensors::Settings& sensor, bool enabledByDefault) { + auto entity = std::make_unique( + std::string(sensor.slug) + "_signal_quality", std::string(sensor.name) + " signal quality" + ); + entity->category = HA::Category::DIAGNOSTIC; + entity->stateTopic = mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY); + entity->unit = "%"; + entity->icon = "mdi:signal"; + entity->enabledByDefault = enabledByDefault; + entity->expireAfter = 2u * MQTT_SENSOR_REPUBLISH_INTERVAL / 1000u; + haDiscovery.publish(std::move(entity)); +} + +void deleteSignalQualityDynamicSensor(const Sensors::Settings& sensor) { + haDiscovery.unpublish(std::string(sensor.slug) + "_signal_quality", ""); +} diff --git a/src/leds.cpp b/src/leds.cpp new file mode 100644 index 0000000..af6a2c0 --- /dev/null +++ b/src/leds.cpp @@ -0,0 +1,91 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include + +static Blinker blinker; + +static Task ledStatusTask("LED status", [](void*) { + uint8_t errors[4]; + uint8_t errCount = 0; + static uint8_t errPos = 0; + static unsigned long endBlinkTime = 0; + static bool ledOn = false; + static uint8_t configuredGpio = GPIO_IS_NOT_CONFIGURED; + + if (settings.system.statusLedGpio != configuredGpio) { + if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(configuredGpio, LOW); + pinMode(configuredGpio, DISABLED); + } + + if (GPIO_IS_VALID_OUTPUT(settings.system.statusLedGpio)) { + configuredGpio = settings.system.statusLedGpio; + pinMode(configuredGpio, OUTPUT); + digitalWrite(configuredGpio, LOW); + blinker.init(configuredGpio); + + } else if (configuredGpio != GPIO_IS_NOT_CONFIGURED) { + configuredGpio = GPIO_IS_NOT_CONFIGURED; + } + } + + if (configuredGpio == GPIO_IS_NOT_CONFIGURED) { + return; + } + + if (!isNetworkConnected()) { + errors[errCount++] = 2; + } + + if (!vars.slave.connected) { + errors[errCount++] = 3; + } + + if (vars.slave.fault.active) { + errors[errCount++] = 4; + } + + if (vars.emergency.state) { + errors[errCount++] = 5; + } + + + if (blinker.ready()) { + endBlinkTime = millis(); + } + + if (!blinker.running() && millis() - endBlinkTime >= 5000) { + if (errCount == 0) { + if (!ledOn) { + digitalWrite(configuredGpio, HIGH); + ledOn = true; + } + + return; + + } else if (ledOn) { + digitalWrite(configuredGpio, LOW); + ledOn = false; + endBlinkTime = millis(); + return; + } + + if (errPos >= errCount) { + errPos = 0; + + // end of error list + blinker.blink(10, 50, 50); + + } else { + blinker.blink(errors[errPos++], 300, 300); + } + } + + blinker.tick(); +}); + +void initLeds() { + ledStatusTask.setInterval(100); + coreTaskManager.addTask(ledStatusTask); +} diff --git a/src/logging.cpp b/src/logging.cpp new file mode 100644 index 0000000..58f5c65 --- /dev/null +++ b/src/logging.cpp @@ -0,0 +1,239 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static_assert(CONFIG_LOG_VERSION == 2, "OTGateway requires an SDK built with Log v2"); +static_assert(CONFIG_LOG_DYNAMIC_LEVEL_CONTROL, "Runtime log levels require dynamic level control"); + +static std::atomic loggingQueue{nullptr}; +static std::atomic activeSerial{false}; +static std::atomic activeWebSerial{false}; +static thread_local bool writingOutputs = false; + +// Return the full byte count, like snprintf, so only long records need a second pass. +static size_t formatLogRecord(esp_log_msg_t& message, char* buffer, size_t capacity) { + const auto& options = message.config.opts; + size_t prefixLength = 0; + const char* suffix = ""; + + if (options.require_formatting) { + const auto level = options.log_level; + if (level >= ESP_LOG_MAX) { + return 0; + } + + const char* color = ""; + #if ESP_LOG_SUPPORT_COLOR && !ESP_LOG_COLOR_DISABLED + static const char* const colors[ESP_LOG_MAX] = { + "", LOG_COLOR_E, LOG_COLOR_W, LOG_COLOR_I, LOG_COLOR(LOG_COLOR_CYAN), LOG_COLOR(LOG_COLOR_MAGENTA) + }; + if (!options.dis_color) { + color = colors[level]; + } + #endif + + char timestamp[32] = {}; + if (!options.dis_timestamp) { + esp_log_timestamp_str(false, message.timestamp, timestamp); + } + + int written = snprintf( + buffer, capacity, "%s%s%s%s[%c]%s%s%s ", + options.dis_timestamp ? "" : "[", + timestamp, + options.dis_timestamp ? "" : "]", + color, + "\0EWIDV"[level], + message.tag ? "[" : "", + message.tag ? message.tag : "", + message.tag ? "]" : "" + ); + if (written < 0) { + return 0; + } + + prefixLength = written; + suffix = *color ? LOG_RESET_COLOR "\n" : "\n"; + } + + size_t offset = std::min(prefixLength, capacity - 1); + va_list args; + va_copy(args, message.args); + int bodyLength = vsnprintf(buffer + offset, capacity - offset, message.format, args); + va_end(args); + if (bodyLength < 0) { + return 0; + } + + size_t suffixOffset = prefixLength + bodyLength; + size_t length = suffixOffset + strlen(suffix); + if (length < capacity) { + memcpy(buffer + suffixOffset, suffix, length - suffixOffset + 1); + } + return length; +} + +static void __attribute__((noinline)) enqueueLogRecord(RingbufHandle_t queue, esp_log_msg_t& message) { + char local[128]; + size_t length = formatLogRecord(message, local, sizeof(local)); + if (length == 0 || length >= xRingbufferGetMaxItemSize(queue)) { + return; + } + + if (length < sizeof(local)) { + xRingbufferSend(queue, local, length + 1, 0); + return; + } + + char* buffer = static_cast(malloc(length + 1)); + if (buffer != nullptr) { + if (formatLogRecord(message, buffer, length + 1) == length) { + xRingbufferSend(queue, buffer, length + 1, 0); + } + + free(buffer); + } +} + +extern "C" { + void __real_esp_log_format(esp_log_msg_t* message); + + void IRAM_ATTR __wrap_esp_log_format(esp_log_msg_t* message) { + RingbufHandle_t queue = loggingQueue.load(std::memory_order_acquire); + if (message->config.opts.constrained_env || writingOutputs || queue == nullptr) { + __real_esp_log_format(message); + return; + } + + const bool hasOutput = activeSerial.load(std::memory_order_relaxed) || + activeWebSerial.load(std::memory_order_relaxed); + + if (hasOutput) { + enqueueLogRecord(queue, *message); + } + } +} + +static void writeOutput(Print& output, const uint8_t* buffer, size_t size) { + while (size > 0) { + size_t written = output.write(buffer, size); + if (written == 0 || written > size) { + return; + } + + buffer += written; + size -= written; + } +} + +static void setLoggingLevel(esp_log_level_t level) { + esp_log_level_set("*", level); + + // prevents loop with WebSerial in case we reach some error logs in esp_async_ws like WS message queue overflow + esp_log_level_set("async_tcp", ESP_LOG_NONE); + esp_log_level_set("async_ws", ESP_LOG_NONE); +} + +void drainLoggingSerial() { + if (activeSerial.load(std::memory_order_relaxed)) { + // Drain only the current RX backlog; continuous input must not starve tasks. + int available = Serial.available(); + while (available-- > 0) { + Serial.read(); + } + } +} + +static Task sendLogsTask("Send logs", [](void*) { + // Bound each pass so continuous logging cannot starve System tasks. + size_t remaining = LOGGING_QUEUE_SIZE; + const unsigned long started = millis(); + RingbufHandle_t queue = loggingQueue.load(std::memory_order_acquire); + + while (remaining > 0 && millis() - started < 10) { + size_t size = 0; + auto* buffer = static_cast(xRingbufferReceive(queue, &size, 0)); + + if (buffer == nullptr) { + break; + } + + // A transport may itself log during a write on this task. + writingOutputs = true; + if (activeSerial.load(std::memory_order_relaxed)) { + writeOutput(Serial, buffer, size - 1); + } + + if (activeWebSerial.load(std::memory_order_relaxed) && webSerial != nullptr) { + if (webSerial->getConnectionCount() > 0) { + writeOutput(*webSerial, buffer, size - 1); + } + } + writingOutputs = false; + + vRingbufferReturnItem(queue, buffer); + remaining = size >= remaining ? 0 : remaining - size; + } +}); + +Task configureLoggingTask("Configure logging", Task::Type::ONCE, [](void*) { + static unsigned int currentSerialBaudrate = 0; + unsigned int newSerialBaudrate = settings.system.serial.enabled ? settings.system.serial.baudrate : 0; + if (currentSerialBaudrate != newSerialBaudrate) { + if (newSerialBaudrate == 0) { + Serial.end(); + } + + if (newSerialBaudrate != 0) { + #if ARDUINO_USB_CDC_ON_BOOT && ARDUINO_USB_MODE + Serial.setTxBufferSize(512); + Serial.setTxTimeoutMs(0); + #endif + + Serial.begin(newSerialBaudrate); + } + + currentSerialBaudrate = newSerialBaudrate; + } + + activeSerial.store(currentSerialBaudrate != 0, std::memory_order_relaxed); + activeWebSerial.store(settings.system.webSerial.enabled && webSerial != nullptr, std::memory_order_relaxed); + + setLoggingLevel(settings.system.logLevel); +}); + +bool initLogging() { + if (loggingQueue.load(std::memory_order_relaxed) != nullptr) { + return false; + } + + RingbufHandle_t queue = xRingbufferCreate(LOGGING_QUEUE_SIZE, RINGBUF_TYPE_NOSPLIT); + if (queue == nullptr) { + return false; + } + + #if !CONFIG_LOG_API_CONSTRAINED_ENV_SAFE + // The native formatter uses the vprintf hook even in an ISR on these SDK builds. + esp_log_set_vprintf(esp_rom_vprintf); + #endif + + configureLoggingTask.forceRun(); + loggingQueue.store(queue, std::memory_order_release); + systemTaskManager.addTask(configureLoggingTask); + + sendLogsTask.setInterval(10); + systemTaskManager.addTask(sendLogsTask); + + return true; +} diff --git a/src/main.cpp b/src/main.cpp index ac0a024..b4b84d3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,226 +1,97 @@ -#include +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE -#if !defined(ARDUINO_ARCH_ESP32) +#include +#include +#include +#include + +#if ARDUINO_USB_CDC_ON_BOOT && !ARDUINO_USB_MODE + #include +#endif + +#ifndef ARDUINO_ARCH_ESP32 #error Only ESP32 boards are supported #endif -#include -#include #include -#include - -#include "defines.h" -#include "strings.h" - -#include -#include -#include "CrashRecorder.h" -#include "Sensors.h" -#include "Settings.h" -#include "utils.h" - -#include - -#include -#include -#include "MqttTask.h" -#include "OpenThermTask.h" -#include "SensorsTask.h" -#include "RegulatorTask.h" -#include "PortalTask.h" -#include "MainTask.h" - -using namespace NetworkUtils; // Vars -WebSerial* webSerial = nullptr; -NetworkMgr* network = nullptr; Sensors::Result sensorsResults[SENSORS_AMOUNT]; -FileData fsNetworkSettings(&LittleFS, "/network.conf", 'n', &networkSettings, sizeof(networkSettings), 1000); -FileData fsSettings(&LittleFS, "/settings.conf", 's', &settings, sizeof(settings), 60000); -FileData fsSensorsSettings(&LittleFS, "/sensors.conf", 'e', &sensorsSettings, sizeof(sensorsSettings), 60000); - -// Tasks -MqttTask* tMqtt; -OpenThermTask* tOt; -SensorsTask* tSensors; -RegulatorTask* tRegulator; -PortalTask* tPortal; -MainTask* tMain; +TaskManager coreTaskManager("Core"); +TaskManager systemTaskManager("System"); +TaskManager openthermTaskManager("OpenTherm"); +TaskManager sensorsTaskManager("Sensors"); -void setup() { - CrashRecorder::init(); +extern "C" void app_main() { + // https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/main.cpp + #if defined(F_XTAL_MHZ) && !CONFIG_IDF_TARGET_ESP32S2 + rtc_clk_xtal_freq_update((rtc_xtal_freq_t)F_XTAL_MHZ); + rtc_clk_cpu_freq_set_xtal(); + #endif + + #ifdef F_CPU + setCpuFrequencyMhz(F_CPU / 1000000); + #endif + + #if ARDUINO_USB_DFU_ON_BOOT && !ARDUINO_USB_MODE + USB.enableDFU(); + #endif + + #if ARDUINO_USB_ON_BOOT && !ARDUINO_USB_MODE + USB.begin(); + #endif + + initArduino(); + + initCoreDumpMetrics(); Sensors::setMaxSensors(SENSORS_AMOUNT); Sensors::settings = sensorsSettings; Sensors::results = sensorsResults; LittleFS.begin(); - Log.setLevel(TinyLoggerLevel::VERBOSE); - Log.setServiceTemplate("\033[1m[%s]\033[22m"); - Log.setLevelTemplate("\033[1m[%s]\033[22m"); - Log.setMsgPrefix("\033[m "); - Log.setDateTemplate("\033[1m[%H:%M:%S]\033[22m"); - Log.setDateCallback([] { - unsigned int time = millis() / 1000; - int sec = time % 60; - int min = time % 3600 / 60; - int hour = time / 3600; + if (!initLogging()) { + std::abort(); + } - return tm{sec, min, hour}; - }); + initConfig(); + initNetwork(); + initSensors(); + initControl(); + initRegulator(); + initLeds(); + initMqtt(); + initPortal(); + initSystem(); + initOpenTherm(); - Serial.begin(115200); - #if ARDUINO_USB_MODE - Serial.setTxBufferSize(512); + // RMT has its own worker; this manager schedules synchronous boiler operations. + if (!openthermTaskManager.asyncStart(4096, 5, 0, 10, false)) { + esp_system_abort("Failed to start OpenTherm task manager"); + } + ESP_LOGI(L_MAIN, "Started %s task manager", openthermTaskManager.name()); + + // Core runs control and MQTT tasks; poll their intervals every 100 ms. + if (!coreTaskManager.asyncStart(4608, 4, tskNO_AFFINITY, 100, false)) { + esp_system_abort("Failed to start Core task manager"); + } + ESP_LOGI(L_MAIN, "Started %s task manager", coreTaskManager.name()); + + // System keeps maintenance, networking and restart handling active during Core pauses. + if (!systemTaskManager.asyncStart(5120, 3, tskNO_AFFINITY, 100, false)) { + esp_system_abort("Failed to start System task manager"); + } + ESP_LOGI(L_MAIN, "Started %s task manager", systemTaskManager.name()); + + BaseType_t sensorsCore = tskNO_AFFINITY; + #if USE_BLE && defined(CONFIG_BT_NIMBLE_PINNED_TO_CORE) + sensorsCore = CONFIG_BT_NIMBLE_PINNED_TO_CORE; #endif - Log.addHandler(&Serial); - Log.print("\n\n\r"); - // - // Network settings - switch (fsNetworkSettings.read()) { - case FD_FS_ERR: - Log.swarningln(L_NETWORK_SETTINGS, "Filesystem error, load default"); - break; - case FD_FILE_ERR: - Log.swarningln(L_NETWORK_SETTINGS, "Bad data, load default"); - break; - case FD_WRITE: - Log.sinfoln(L_NETWORK_SETTINGS, "Not found, load default"); - break; - case FD_ADD: - case FD_READ: - Log.sinfoln(L_NETWORK_SETTINGS, "Loaded"); - break; - default: - break; + // Keep physical sensor I/O and result processing outside the Core worker. + if (!sensorsTaskManager.asyncStart(4096, 4, sensorsCore, 1000, false)) { + esp_system_abort("Failed to start Sensors task manager"); } - - // generate hostname if it is empty - if (!strlen(networkSettings.hostname)) { - strcpy(networkSettings.hostname, getChipId("otgateway-").c_str()); - fsNetworkSettings.update(); - } - - network = (new NetworkMgr) - ->setHostname(networkSettings.hostname) - ->setStaCredentials( - strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr, - strlen(networkSettings.sta.password) ? networkSettings.sta.password : nullptr, - networkSettings.sta.channel - )->setApCredentials( - strlen(networkSettings.ap.ssid) ? networkSettings.ap.ssid : nullptr, - strlen(networkSettings.ap.password) ? networkSettings.ap.password : nullptr, - networkSettings.ap.channel - ) - ->setUseDhcp(networkSettings.useDhcp) - ->setStaticConfig( - networkSettings.staticConfig.ip, - networkSettings.staticConfig.gateway, - networkSettings.staticConfig.subnet, - networkSettings.staticConfig.dns - ); - - // - // Settings - switch (fsSettings.read()) { - case FD_FS_ERR: - Log.swarningln(L_SETTINGS, "Filesystem error, load default"); - break; - case FD_FILE_ERR: - Log.swarningln(L_SETTINGS, "Bad data, load default"); - break; - case FD_WRITE: - Log.sinfoln(L_SETTINGS, "Not found, load default"); - break; - case FD_ADD: - case FD_READ: - Log.sinfoln(L_SETTINGS, "Loaded"); - - if (strcmp(SETTINGS_VALID_VALUE, settings.validationValue) != 0) { - Log.swarningln(L_SETTINGS, "Not valid, set default and restart..."); - fsSettings.reset(); - ::delay(5000); - ESP.restart(); - } - break; - default: - break; - } - - // generate mqtt prefix if it is empty - if (!strlen(settings.mqtt.prefix)) { - strcpy(settings.mqtt.prefix, getChipId("otgateway_").c_str()); - fsSettings.update(); - } - - // Logs settings - if (!settings.system.serial.enabled) { - Serial.end(); - Log.clearHandlers(); - - } else if (settings.system.serial.baudrate != 115200) { - Serial.end(); - Log.clearHandlers(); - - Serial.begin(settings.system.serial.baudrate); - Log.addHandler(&Serial); - } - - if (settings.system.webSerial.enabled) { - webSerial = new WebSerial(); - webSerial->setBuffer(100); - Log.addHandler(webSerial); - } - - if (settings.system.logLevel >= TinyLoggerLevel::SILENT && settings.system.logLevel <= TinyLoggerLevel::VERBOSE) { - Log.setLevel(static_cast(settings.system.logLevel)); - } - - // - // Sensors settings - switch (fsSensorsSettings.read()) { - case FD_FS_ERR: - Log.swarningln(L_SENSORS, "Filesystem error, load default"); - break; - case FD_FILE_ERR: - Log.swarningln(L_SENSORS, "Bad data, load default"); - break; - case FD_WRITE: - Log.sinfoln(L_SENSORS, "Not found, load default"); - break; - case FD_ADD: - case FD_READ: - Log.sinfoln(L_SENSORS, "Loaded"); - default: - break; - } - - // - // Make tasks - tMqtt = new MqttTask(false, 500); - Scheduler.start(tMqtt); - - tOt = new OpenThermTask(true, 750); - Scheduler.start(tOt); - - tSensors = new SensorsTask(true, 1000); - Scheduler.start(tSensors); - - tRegulator = new RegulatorTask(true, 10000); - Scheduler.start(tRegulator); - - tPortal = new PortalTask(true, 10); - Scheduler.start(tPortal); - - tMain = new MainTask(true, 100); - Scheduler.start(tMain); - - Scheduler.begin(); -} - -void loop() { - vTaskDelete(NULL); + ESP_LOGI(L_MAIN, "Started %s task manager", sensorsTaskManager.name()); } diff --git a/src/mqtt.cpp b/src/mqtt.cpp new file mode 100644 index 0000000..63ebced --- /dev/null +++ b/src/mqtt.cpp @@ -0,0 +1,1104 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +std::mutex mqttMutex; + +static MQTT* mqttClient = nullptr; +static std::string mqttPrefix; +static std::atomic mqttConnectedAt{0}; +static unsigned long mqttPublishedSensorAt[SENSORS_AMOUNT] = {}; + +static std::atomic mqttHaRefreshRequested{false}; +// Discovery and its synchronous publisher run only on Core. +static std::bitset mqttHaPendingEntities; +static std::bitset mqttHaPendingSensors; + +Task* mqttPublishSettingsTask = nullptr; +Task* mqttPublishStateTask = nullptr; +Task* mqttPublishSensorsTask = nullptr; +static Task* mqttReconfigureSensorsTask = nullptr; +static Task* mqttPublishHaTask = nullptr; + +// Protect the MQTT change queue and publication timestamps across HTTP/native callbacks. +static std::mutex mqttSensorsMutex; + +struct MqttSensorChange { + uint8_t sensorId; + std::optional previousSettings; +}; +static std::list mqttSensorChanges; + +// The caller holds mqttSensorsMutex. +static bool isSensorReconfigurationPending(uint8_t sensorId) { + return std::any_of(mqttSensorChanges.begin(), mqttSensorChanges.end(), [sensorId](const auto& change) { + return change.sensorId == sensorId; + }); +} + +static bool isMqttBlocked() { + return vars.states.upgrading || restartTask.scheduled() || restartTask.active(); +} + +static bool isMqttReady() { + return settings.mqtt.enabled && isNetworkConnected() && !isMqttBlocked() + && !mqttConfigureTask.scheduled() && isMqttConnected(); +} + +static bool isMqttReadyForPublish() { + const unsigned long connectedAt = mqttConnectedAt.load(); + return isMqttReady() && connectedAt && millis() - connectedAt > 30000u; +} + +std::string mqttTopic(std::initializer_list parts) { + size_t length = mqttPrefix.size(); + for (const auto part : parts) { + length += 1 + part.size(); + } + + std::string topic; + topic.reserve(length); + topic.append(mqttPrefix); + for (const auto part : parts) { + topic += '/'; + topic.append(part); + } + return topic; +} + +static void publishValue(const std::string& topic, std::string_view value) { + mqttClient->publish(topic.c_str(), value, true); +} + +static void publishValue(const std::string& topic, const char* value) { + publishValue(topic, std::string_view(value)); +} + +static void publishValue(const std::string& topic, bool value) { + publishValue(topic, value ? S_TRUE : S_FALSE); +} + +static void 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; + } + + char payload[64]; + const int length = snprintf(payload, sizeof(payload), "%.*f", decimals, value); + if (length < 0 || static_cast(length) >= sizeof(payload)) { + return; + } + + if (decimals) { + char* end = payload + length - 1; + while (*end == '0') { + *end-- = '\0'; + } + if (*end == '.') { + *end = '\0'; + } + } + publishValue(topic, payload); +} + +static void publishHeatingSettings() { + publishValue(mqttTopic("settings/heating/enabled"), settings.heating.enabled); + publishValue(mqttTopic("settings/heating/turbo"), settings.heating.turbo); + publishValue(mqttTopic("settings/heating/target"), convertTemp(settings.heating.target, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("settings/heating/hysteresis/enabled"), settings.heating.hysteresis.enabled); + publishValue(mqttTopic("settings/heating/hysteresis/value"), settings.heating.hysteresis.value, 3); + publishValue(mqttTopic("settings/heating/turbo_factor"), settings.heating.turboFactor, 3); + publishValue(mqttTopic("settings/heating/min_temp"), convertTemp(settings.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("settings/heating/max_temp"), convertTemp(settings.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("settings/heating/max_modulation"), std::to_string(settings.heating.maxModulation)); + publishValue(mqttTopic("settings/heating/indoor_temp_avg_type"), std::to_string(static_cast(settings.heating.indoorTempAvgType))); + publishValue(mqttTopic("settings/heating/outdoor_temp_avg_type"), std::to_string(static_cast(settings.heating.outdoorTempAvgType))); + publishValue( + mqttTopic("settings/heating/overheat_protection/high_temp"), + settings.heating.overheatProtection.highTemp == 0 + ? 0 + : convertTemp(settings.heating.overheatProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue( + mqttTopic("settings/heating/overheat_protection/low_temp"), + settings.heating.overheatProtection.lowTemp == 0 + ? 0 + : convertTemp(settings.heating.overheatProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue(mqttTopic("settings/heating/freeze_protection/high_temp"), convertTemp(settings.heating.freezeProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("settings/heating/freeze_protection/low_temp"), convertTemp(settings.heating.freezeProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); +} + +static void publishDhwSettings() { + publishValue(mqttTopic("settings/dhw/enabled"), settings.dhw.enabled); + publishValue(mqttTopic("settings/dhw/target"), convertTemp(settings.dhw.target, UnitSystem::METRIC, settings.system.unitSystem), 1); + publishValue(mqttTopic("settings/dhw/min_temp"), convertTemp(settings.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("settings/dhw/max_temp"), convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("settings/dhw/max_modulation"), std::to_string(settings.dhw.maxModulation)); + publishValue( + mqttTopic("settings/dhw/overheat_protection/high_temp"), + settings.dhw.overheatProtection.highTemp == 0 + ? 0 + : convertTemp(settings.dhw.overheatProtection.highTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue( + mqttTopic("settings/dhw/overheat_protection/low_temp"), + settings.dhw.overheatProtection.lowTemp == 0 + ? 0 + : convertTemp(settings.dhw.overheatProtection.lowTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); +} + +static void publishPidSettings() { + publishValue(mqttTopic("settings/pid/enabled"), settings.pid.enabled); + publishValue(mqttTopic("settings/pid/p_factor"), settings.pid.p_factor, 3); + publishValue(mqttTopic("settings/pid/i_factor"), settings.pid.i_factor, 4); + publishValue(mqttTopic("settings/pid/d_factor"), settings.pid.d_factor, 1); + publishValue(mqttTopic("settings/pid/dt"), std::to_string(settings.pid.dt)); + publishValue( + mqttTopic("settings/pid/min_temp"), + settings.equitherm.enabled + ? settings.pid.minTemp + : convertTemp(settings.pid.minTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue( + mqttTopic("settings/pid/max_temp"), + settings.equitherm.enabled + ? settings.pid.maxTemp + : convertTemp(settings.pid.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue(mqttTopic("settings/pid/deadband/enabled"), settings.pid.deadband.enabled); + publishValue(mqttTopic("settings/pid/deadband/p_multiplier"), settings.pid.deadband.p_multiplier, 3); + publishValue(mqttTopic("settings/pid/deadband/i_multiplier"), settings.pid.deadband.i_multiplier, 3); + publishValue(mqttTopic("settings/pid/deadband/d_multiplier"), settings.pid.deadband.d_multiplier, 3); + publishValue(mqttTopic("settings/pid/deadband/threshold_high"), settings.pid.deadband.thresholdHigh); + publishValue(mqttTopic("settings/pid/deadband/threshold_low"), settings.pid.deadband.thresholdLow); +} + +static void publishEquithermSettings() { + publishValue(mqttTopic("settings/equitherm/enabled"), settings.equitherm.enabled); + publishValue(mqttTopic("settings/equitherm/slope"), settings.equitherm.slope, 3); + publishValue(mqttTopic("settings/equitherm/exponent"), settings.equitherm.exponent, 3); + publishValue(mqttTopic("settings/equitherm/shift"), settings.equitherm.shift, 2); + publishValue(mqttTopic("settings/equitherm/target_diff_factor"), settings.equitherm.targetDiffFactor, 3); +} + +static void publishSettings() { + publishValue(mqttTopic("settings/emergency/target"), convertTemp(settings.emergency.target, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishHeatingSettings(); + publishDhwSettings(); + publishPidSettings(); + publishEquithermSettings(); +} + +static void publishSlaveState() { + publishValue(mqttTopic("state/slave/member_id"), std::to_string(vars.slave.memberId)); + publishValue(mqttTopic("state/slave/flags"), std::to_string(vars.slave.flags)); + publishValue(mqttTopic("state/slave/type"), std::to_string(vars.slave.type)); + publishValue(mqttTopic("state/slave/app_version"), std::to_string(vars.slave.appVersion)); + publishValue(mqttTopic("state/slave/protocol_version"), vars.slave.protocolVersion); + publishValue(mqttTopic("state/slave/connected"), vars.slave.connected); + publishValue(mqttTopic("state/slave/flame"), vars.slave.flame); + publishValue(mqttTopic("state/slave/cooling/active"), vars.slave.cooling.active); + publishValue(mqttTopic("state/slave/cooling/setpoint"), std::to_string(vars.slave.cooling.setpoint)); + publishValue(mqttTopic("state/slave/modulation/min"), std::to_string(vars.slave.modulation.min)); + publishValue(mqttTopic("state/slave/modulation/max"), std::to_string(vars.slave.modulation.max)); + publishValue(mqttTopic("state/slave/power/min"), vars.slave.power.min, 2); + publishValue(mqttTopic("state/slave/power/max"), vars.slave.power.max, 2); + publishValue(mqttTopic("state/slave/heating/active"), vars.slave.heating.active); + publishValue(mqttTopic("state/slave/heating/min_temp"), convertTemp(vars.slave.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/slave/heating/max_temp"), convertTemp(vars.slave.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/slave/dhw/active"), vars.slave.dhw.active); + publishValue(mqttTopic("state/slave/dhw/min_temp"), convertTemp(vars.slave.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/slave/dhw/max_temp"), convertTemp(vars.slave.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/slave/fault/active"), vars.slave.fault.active); + publishValue(mqttTopic("state/slave/fault/code"), std::to_string(vars.slave.fault.code)); + publishValue(mqttTopic("state/slave/fault/available"), vars.slave.connected && vars.slave.fault.active); + publishValue(mqttTopic("state/slave/diag/active"), vars.slave.diag.active); + publishValue(mqttTopic("state/slave/diag/code"), std::to_string(vars.slave.diag.code)); + // Preserve the diagnostic-code availability condition from async. + publishValue(mqttTopic("state/slave/diag/available"), (vars.slave.connected && vars.slave.fault.active) || vars.slave.diag.active); +} + +static void publishMasterState() { + publishValue(mqttTopic("state/master/heating/enabled"), vars.master.heating.enabled); + publishValue(mqttTopic("state/master/heating/blocking"), vars.master.heating.blocking); + publishValue(mqttTopic("state/master/heating/overheat"), vars.master.heating.overheat); + publishValue(mqttTopic("state/master/heating/freezing"), vars.master.heating.freezing); + publishValue( + mqttTopic("state/master/heating/setpoint_temp"), + vars.master.heating.setpointTemp == 0 + ? 0 + : convertTemp(vars.master.heating.setpointTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue( + mqttTopic("state/master/heating/target_temp"), + vars.master.heating.targetTemp == 0 + ? 0 + : convertTemp(vars.master.heating.targetTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue(mqttTopic("state/master/heating/current_temp"), convertTemp(vars.master.heating.currentTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/heating/return_temp"), convertTemp(vars.master.heating.returnTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/heating/indoor_temp"), convertTemp(vars.master.heating.indoorTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/heating/outdoor_temp"), convertTemp(vars.master.heating.outdoorTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/heating/min_temp"), convertTemp(vars.master.heating.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/heating/max_temp"), convertTemp(vars.master.heating.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/dhw/enabled"), vars.master.dhw.enabled); + publishValue(mqttTopic("state/master/dhw/overheat"), vars.master.dhw.overheat); + publishValue( + mqttTopic("state/master/dhw/target_temp"), + vars.master.dhw.targetTemp == 0 + ? 0 + : convertTemp(vars.master.dhw.targetTemp, UnitSystem::METRIC, settings.system.unitSystem), + 2 + ); + publishValue(mqttTopic("state/master/dhw/current_temp"), convertTemp(vars.master.dhw.currentTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/dhw/return_temp"), convertTemp(vars.master.dhw.returnTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/dhw/min_temp"), convertTemp(settings.dhw.minTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/dhw/max_temp"), convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2); + publishValue(mqttTopic("state/master/network/connected"), isNetworkConnected()); + publishValue(mqttTopic("state/master/network/rssi"), std::to_string(vars.network.rssi)); + publishValue(mqttTopic("state/master/mqtt/connected"), isMqttConnected()); + publishValue(mqttTopic("state/master/emergency/state"), vars.emergency.state); + publishValue(mqttTopic("state/master/ext_pump/state"), vars.externalPump.state); + publishValue(mqttTopic("state/master/cascade_control/input"), vars.cascadeControl.input); + publishValue(mqttTopic("state/master/cascade_control/output"), vars.cascadeControl.output); + publishValue(mqttTopic("state/master/uptime"), std::to_string(millis() / 1000u)); +} + +static void publishState() { + publishValue(mqttTopic("status"), "online"); + publishSlaveState(); + publishMasterState(); +} + +static std::string_view trimPayload(std::string_view payload) { + const auto first = payload.find_first_not_of(" \t\r\n"); + if (first == std::string_view::npos) { + return {}; + } + return payload.substr(first, payload.find_last_not_of(" \t\r\n") - first + 1); +} + +static std::optional parseNumber(std::string_view payload, uint8_t bufferSize = 17) { + if (payload.empty() || bufferSize < 2) { + return std::nullopt; + } + + // Long input is intentionally truncated to leave room for the terminating NUL. + payload = payload.substr(0, bufferSize - 1); + + // strtof also accepts leading whitespace, '+' and hexadecimal numbers. + const char first = payload.front(); + if ((first < '0' || first > '9') && first != '-' && first != '.') { + return std::nullopt; + } + + if (payload.find_first_of("xX") != std::string_view::npos) { + return std::nullopt; + } + + char buffer[bufferSize]; + memcpy(buffer, payload.data(), payload.size()); + buffer[payload.size()] = '\0'; + + char* end; + errno = 0; + const float parsed = std::strtof(buffer, &end); + if (end != buffer + payload.size() || !std::isfinite(parsed) || (errno == ERANGE && parsed == 0.0f)) { + return std::nullopt; + } + + return parsed; +} + +static bool isCommandValid(const std::string& topic, std::string_view payload) { + if (payload.empty()) { + return false; + } + + // These bounds keep commands within RX 512: MycilaMQTT does not expose fragment metadata. + if (topic.size() > 128 || payload.size() > 64 || topic.find('\0') != std::string::npos) { + ESP_LOGW(L_MQTT_MSG, "Invalid scalar command size or topic"); + return false; + } + + return true; +} + +static void publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) { + if (!sensor.slug[0]) { + return; + } + + 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 (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { + publishValue( + mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE), + convertTemp( + result.values[static_cast(Sensors::ValueType::TEMPERATURE)], + UnitSystem::METRIC, settings.system.unitSystem + ), + 3 + ); + publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); + + if (sensor.type == Sensors::Type::BLUETOOTH) { + publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast(Sensors::ValueType::BATTERY)], 1); + publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast(Sensors::ValueType::RSSI)], 0); + } + + } else { + publishValue( + mqttTopic(S_SENSORS, sensor.slug, S_VALUE), + Sensors::convertValue( + sensor, Sensors::ValueType::PRIMARY, + result.values[static_cast(Sensors::ValueType::PRIMARY)], + UnitSystem::METRIC, settings.system.unitSystem + ), + 3 + ); + } +} + +static bool purgeSensor(const char* slug) { + if (slug == nullptr || !slug[0]) { + return true; + } + + const char* fields[] = {S_CONNECTED, S_SIGNAL_QUALITY, S_VALUE, S_TEMPERATURE, S_HUMIDITY, S_BATTERY, S_RSSI}; + for (const auto field : fields) { + const std::string topic = mqttTopic(S_SENSORS, slug, field); + + if (!mqttClient->publish(topic.c_str(), {}, true)) { + return false; + } + } + + return true; +} + +void requestReconfigureMqttSensor(uint8_t sensorId, std::optional previousSettings) { + if (!Sensors::isValidSensorId(sensorId)) { + return; + } + + { + std::lock_guard lock(mqttSensorsMutex); + const auto pending = std::find_if(mqttSensorChanges.begin(), mqttSensorChanges.end(), [sensorId](const auto& change) { + return change.sensorId == sensorId; + }); + + if (pending == mqttSensorChanges.end()) { + mqttSensorChanges.push_back({sensorId, std::move(previousSettings)}); + + } else if (!pending->previousSettings && previousSettings) { + // Keep the first settings whose old MQTT identity may need cleanup. + pending->previousSettings = std::move(previousSettings); + } + } + + // If SDK stop holds the lock, pending changes stay queued for a periodic run. + std::unique_lock taskLock(mqttMutex, std::try_to_lock); + if (taskLock.owns_lock() && mqttReconfigureSensorsTask) { + mqttReconfigureSensorsTask->requestEarlyRun(); + } +} + +void requestPublishMqttSensor(uint8_t sensorId) { + if (!Sensors::isValidSensorId(sensorId)) { + return; + } + + { + std::lock_guard lock(mqttSensorsMutex); + mqttPublishedSensorAt[sensorId] = 0; + } + + // stopMqtt holds this lock while waiting for the MQTT callback to finish. + // If busy, the cleared timestamp still triggers the next periodic publication. + std::unique_lock taskLock(mqttMutex, std::try_to_lock); + if (taskLock.owns_lock() && mqttPublishSensorsTask) { + mqttPublishSensorsTask->requestEarlyRun(); + } +} + +void requestReconfigureMqtt() { + mqttConfigureTask.setInterval(0).resume(); +} + +bool isMqttConnected() { + // Do not wait for SDK stop or access a client being destroyed. + std::unique_lock lock(mqttMutex, std::try_to_lock); + return lock.owns_lock() && mqttClient && mqttClient->isConnected(); +} + +void stopMqtt(bool destroy = false) { + std::lock_guard lock(mqttMutex); + if (mqttClient) { + mqttClient->end(); + } + mqttConnectedAt.store(0); + haDiscovery.end(); + mqttHaPendingEntities.reset(); + mqttHaPendingSensors.reset(); + + if (!destroy) { + return; + } + + if (mqttPublishSettingsTask) { + coreTaskManager.removeTask(*mqttPublishSettingsTask); + delete mqttPublishSettingsTask; + mqttPublishSettingsTask = nullptr; + } + + if (mqttPublishStateTask) { + coreTaskManager.removeTask(*mqttPublishStateTask); + delete mqttPublishStateTask; + mqttPublishStateTask = nullptr; + } + + if (mqttPublishSensorsTask) { + coreTaskManager.removeTask(*mqttPublishSensorsTask); + delete mqttPublishSensorsTask; + mqttPublishSensorsTask = nullptr; + } + + if (mqttReconfigureSensorsTask) { + coreTaskManager.removeTask(*mqttReconfigureSensorsTask); + delete mqttReconfigureSensorsTask; + mqttReconfigureSensorsTask = nullptr; + } + + if (mqttPublishHaTask) { + coreTaskManager.removeTask(*mqttPublishHaTask); + delete mqttPublishHaTask; + mqttPublishHaTask = nullptr; + } + + delete mqttClient; + mqttClient = nullptr; + + std::string().swap(mqttPrefix); +} + +static float mqttValueToMetric(std::string_view path, float value) { + if (settings.equitherm.enabled && path.starts_with("pid/")) { + return value; + } + + if (value == 0 && path.find(S_OVERHEAT_PROTECTION) != std::string_view::npos) { + return value; + } + + const auto name = path.substr(path.find_last_of('/') + 1); + if (name == S_TARGET || name == S_MIN_TEMP || name == S_MAX_TEMP + || name == S_HIGH_TEMP || name == S_LOW_TEMP) { + return convertTemp(value, settings.system.unitSystem, UnitSystem::METRIC); + } + + return value; +} + +static void subscribe() { + mqttClient->subscribe("homeassistant/status", [](const std::string&, const std::string_view& message) { + if (message == "online") { + mqttHaRefreshRequested.store(true); + } + }); + + const auto onSettingCommand = [](const std::string& topic, const std::string_view& message) { + if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { + return; + } + + auto path = std::string_view(topic).substr(mqttPrefix.size()); + if (!path.starts_with("/settings/")) { + return; + } + + path.remove_prefix(sizeof("/settings/") - 1); + if (!path.ends_with("/set")) { + return; + } + + path.remove_suffix(sizeof("/set") - 1); + if (!isCommandValid(topic, message)) { + return; + } + + mqttClient->publish(topic.c_str(), {}, true); + const auto payload = trimPayload(message); + + SettingResult result; + if (payload == S_TRUE || payload == S_FALSE) { + result = applySetting(settings, path, payload == S_TRUE); + + } else { + const auto parsed = parseNumber(payload); + if (parsed) { + result = applySetting(settings, path, mqttValueToMetric(path, *parsed)); + } + } + + if (!result.accepted) { + ESP_LOGW(L_MQTT_MSG, "Unsupported or invalid setting command"); + if (!result.changed) { + return; + } + } + + result.changed = normalizeSettings(settings) || result.changed; + if (result.changed) { + requestSaveSettings(); + } + + mqttPublishSettingsTask->requestEarlyRun(); + }; + + mqttClient->subscribe(mqttTopic(S_SETTINGS, "+/+/set"), onSettingCommand); + mqttClient->subscribe(mqttTopic(S_SETTINGS, "+/+/+/set"), onSettingCommand); + + mqttClient->subscribe(mqttTopic(S_ACTIONS, "+", "set"), [](const std::string& topic, const std::string_view& message) { + if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { + return; + } + + if (!isCommandValid(topic, message)) { + return; + } + + mqttClient->publish(topic.c_str(), {}, true); + + const auto payload = trimPayload(message); + if (payload != S_TRUE && payload != S_FALSE) { + ESP_LOGW(L_MQTT_MSG, "Invalid action value"); + return; + } + + auto action = std::string_view(topic).substr(mqttPrefix.size() + sizeof("/actions/") - 1); + action.remove_suffix(sizeof("/set") - 1); + + + if (!applyAction(action, payload == S_TRUE)) { + ESP_LOGW(L_MQTT_MSG, "Unsupported or blocked action"); + } + }); + + mqttClient->subscribe(mqttTopic(S_SENSORS, "+", S_VALUE, "set"), [](const std::string& topic, const std::string_view& message) { + if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { + return; + } + + if (!isCommandValid(topic, message)) { + return; + } + + mqttClient->publish(topic.c_str(), {}, true); + + const auto parsed = parseNumber(trimPayload(message)); + if (!parsed) { + ESP_LOGW(L_MQTT_MSG, "Invalid manual sensor value"); + return; + } + + const auto slugStart = mqttPrefix.size() + strlen(S_SENSORS) + 2; + const std::string slug = topic.substr(slugStart, topic.find('/', slugStart) - slugStart); + if (slug.empty()) { + return; + } + + const auto sensorId = Sensors::setManualValueBySlug(slug, *parsed, settings.system.unitSystem); + if (!sensorId) { + ESP_LOGW(L_MQTT_MSG, "Unknown or disabled manual sensor"); + return; + } + + requestPublishMqttSensor(*sensorId); + }); +} + +static void connect() { + if (!mqttClient) { + std::lock_guard lock(mqttMutex); + + mqttClient = new MQTT(); + mqttClient->setAsync(true); + mqttClient->setConfigHook([](esp_mqtt_client_config_t& config) { + config.session.last_will.qos = 1; + config.session.disable_clean_session = false; + config.network.timeout_ms = 3000; + config.network.reconnect_timeout_ms = MQTT_RECONNECT_INTERVAL; + config.buffer.size = 512; + config.buffer.out_size = 512; + config.outbox.limit = 8192; + config.task.stack_size = 4096; + config.task.priority = 2; + }); + + mqttClient->onConnect([] { + mqttConnectedAt.store(millis()); + mqttHaRefreshRequested.store(true); + { + std::lock_guard lock(mqttSensorsMutex); + memset(mqttPublishedSensorAt, 0, sizeof(mqttPublishedSensorAt)); + } + mqttPublishSettingsTask->requestEarlyRun(); + mqttPublishStateTask->requestEarlyRun(); + mqttPublishSensorsTask->requestEarlyRun(); + mqttReconfigureSensorsTask->requestEarlyRun(); + ESP_LOGI(L_MQTT, "Connected"); + }); + + mqttPrefix = settings.mqtt.prefix; + subscribe(); + + } else if (mqttPrefix != settings.mqtt.prefix) { + for (const auto& topic : mqttClient->getSubscribedTopics()) { + mqttClient->unsubscribe(topic.c_str()); + } + + mqttPrefix = settings.mqtt.prefix; + subscribe(); + } + + haDiscovery.setWillTopic("~/status"); + haDiscovery.begin( + { + .id = mqttPrefix, + .name = PROJECT_NAME, + .version = BUILD_VERSION, + .model = PROJECT_NAME, + .manufacturer = PROJECT_REPO, + .url = std::string("http://") + WiFi.localIP().toString().c_str() + "/", + }, + mqttPrefix, + [](const char* topic, const std::string& payload) { + mqttClient->publish(topic, payload, true); + } + ); + mqttClient->begin({ + .server = settings.mqtt.server, + .port = settings.mqtt.port, + .keepAlive = static_cast(settings.mqtt.interval * 10u), + .username = settings.mqtt.user, + .password = settings.mqtt.password, + .clientId = networkSettings.hostname, + .willTopic = mqttTopic("status"), + }); +} + +Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) { + if (!settings.mqtt.enabled) { + stopMqtt(true); + return; + } + + // Publish complete settings while MQTT is enabled. + if (!mqttPublishSettingsTask) { + auto* task = new Task("Publish MQTT settings", [](void*) { + publishSettings(); + }); + + task->setEnabledWhen(isMqttReadyForPublish); + coreTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishSettingsTask = task; + } + + // Publish the current application and slave state. + if (!mqttPublishStateTask) { + auto* task = new Task("Publish MQTT state", [](void*) { + publishState(); + }); + + task->setEnabledWhen(isMqttReadyForPublish); + coreTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishStateTask = task; + } + + // Publish one discovery config per tick, without retaining Component objects. + if (!mqttPublishHaTask) { + auto* task = new Task("Publish HA discovery", [](void*) { + static bool discoveryEnabled = settings.mqtt.homeAssistantDiscovery; + static UnitSystem unitSystem = settings.system.unitSystem; + static bool equithermEnabled = settings.equitherm.enabled; + static unsigned short interval = settings.mqtt.interval; + static uint8_t heatingMinTemp = vars.slave.heating.minTemp; + static uint8_t heatingMaxTemp = vars.slave.heating.maxTemp; + static bool dhwSupport = settings.opentherm.options.dhwSupport; + static bool indoorTempControl = vars.master.heating.indoorTempControl; + static float heatingMinSetpointTemp = vars.master.heating.minTemp; + static float heatingMaxSetpointTemp = vars.master.heating.maxTemp; + static uint8_t dhwMinTemp = settings.dhw.minTemp; + static uint8_t dhwMaxTemp = settings.dhw.maxTemp; + static uint8_t dhwBoilerMinTemp = vars.slave.dhw.minTemp; + static uint8_t dhwBoilerMaxTemp = vars.slave.dhw.maxTemp; + + // Observe metadata dependencies regardless of the settings entry point. + if (discoveryEnabled != settings.mqtt.homeAssistantDiscovery) { + discoveryEnabled = settings.mqtt.homeAssistantDiscovery; + mqttHaRefreshRequested.store(true); + } + + if (unitSystem != settings.system.unitSystem) { + unitSystem = settings.system.unitSystem; + mqttHaPendingEntities + .set(HA_ENTITY_HEATING_MIN_TEMP) + .set(HA_ENTITY_HEATING_MAX_TEMP) + .set(HA_ENTITY_PID_MIN_TEMP) + .set(HA_ENTITY_PID_MAX_TEMP) + .set(HA_ENTITY_HEATING_CLIMATE) + .set(HA_ENTITY_DHW_MIN_TEMP) + .set(HA_ENTITY_DHW_MAX_TEMP) + .set(HA_ENTITY_DHW_CLIMATE); + mqttHaPendingSensors.set(); + } + + if (equithermEnabled != settings.equitherm.enabled) { + equithermEnabled = settings.equitherm.enabled; + mqttHaPendingEntities.set(HA_ENTITY_PID_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_PID_MAX_TEMP); + } + + if (interval != settings.mqtt.interval) { + const uint32_t previousExpiration = std::max(60u, 2u * interval); + interval = settings.mqtt.interval; + const uint32_t expiration = std::max(60u, 2u * interval); + if (previousExpiration != expiration) { + mqttHaPendingEntities.set(); + } + } + + if (heatingMinTemp != vars.slave.heating.minTemp) { + heatingMinTemp = vars.slave.heating.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MAX_TEMP); + } + + if (heatingMaxTemp != vars.slave.heating.maxTemp) { + heatingMaxTemp = vars.slave.heating.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_HEATING_MAX_TEMP); + } + + if (dhwSupport != settings.opentherm.options.dhwSupport) { + dhwSupport = settings.opentherm.options.dhwSupport; + mqttHaPendingEntities + .set(HA_ENTITY_DHW_MIN_TEMP) + .set(HA_ENTITY_DHW_MAX_TEMP) + .set(HA_ENTITY_DHW) + .set(HA_ENTITY_DHW_CLIMATE) + .set(HA_ENTITY_DHW_OVERHEAT); + } + + if (indoorTempControl != vars.master.heating.indoorTempControl) { + indoorTempControl = vars.master.heating.indoorTempControl; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_CLIMATE); + } + + if (heatingMinSetpointTemp != vars.master.heating.minTemp) { + heatingMinSetpointTemp = vars.master.heating.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_CLIMATE); + } + + if (heatingMaxSetpointTemp != vars.master.heating.maxTemp) { + heatingMaxSetpointTemp = vars.master.heating.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_HEATING_CLIMATE); + } + + if (dhwMinTemp != settings.dhw.minTemp) { + dhwMinTemp = settings.dhw.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_CLIMATE); + } + + if (dhwMaxTemp != settings.dhw.maxTemp) { + dhwMaxTemp = settings.dhw.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_CLIMATE); + } + + if (dhwBoilerMinTemp != vars.slave.dhw.minTemp) { + dhwBoilerMinTemp = vars.slave.dhw.minTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_DHW_MAX_TEMP); + } + + if (dhwBoilerMaxTemp != vars.slave.dhw.maxTemp) { + dhwBoilerMaxTemp = vars.slave.dhw.maxTemp; + mqttHaPendingEntities.set(HA_ENTITY_DHW_MIN_TEMP); + mqttHaPendingEntities.set(HA_ENTITY_DHW_MAX_TEMP); + } + + if (mqttHaRefreshRequested.exchange(false)) { + mqttHaPendingEntities.set(); + mqttHaPendingSensors.set(); + } + + for (size_t index = 0; index < mqttHaPendingEntities.size(); index++) { + if (!mqttHaPendingEntities.test(index)) { + continue; + } + + mqttHaPendingEntities.reset(index); + publishHaEntity(static_cast(index), !settings.mqtt.homeAssistantDiscovery); + return; + } + + for (uint8_t sensorId = 0; sensorId < SENSORS_AMOUNT; sensorId++) { + if (!mqttHaPendingSensors.test(sensorId)) { + continue; + } + + mqttHaPendingSensors.reset(sensorId); + if (settings.mqtt.homeAssistantDiscovery) { + requestReconfigureMqttSensor(sensorId); + + } else { + auto sensor = Sensors::getSettings(sensorId); + if (sensor) { + requestReconfigureMqttSensor(sensorId, std::move(sensor)); + } + } + break; + } + }); + + task->setInterval(250).setEnabledWhen(isMqttReadyForPublish); + coreTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishHaTask = task; + } + + // Rebuild sensor discovery and clear old readings in the same queue handler. + if (!mqttReconfigureSensorsTask) { + auto* task = new Task("Reconfigure MQTT sensors", [](void*) { + std::unique_lock lock(mqttSensorsMutex, std::try_to_lock); + if (!lock.owns_lock() || mqttSensorChanges.empty()) { + return; + } + + MqttSensorChange change = mqttSensorChanges.front(); + const auto sensor = Sensors::getSettings(change.sensorId); + mqttSensorChanges.pop_front(); + mqttPublishedSensorAt[change.sensorId] = 0; + lock.unlock(); + + const auto& [sensorId, prevSettings] = change; + const bool metadataChanged = prevSettings && ( + !sensor + || prevSettings->enabled != sensor->enabled + || strcmp(prevSettings->name, sensor->name) != 0 + || strcmp(prevSettings->slug, sensor->slug) != 0 + || prevSettings->purpose != sensor->purpose + || prevSettings->type != sensor->type + ); + + // Metadata changes replace entities; disabling discovery removes them. + if (prevSettings && Sensors::hasEnabledAndValid(*prevSettings) + && (metadataChanged || !settings.mqtt.homeAssistantDiscovery)) { + deleteConnectionDynamicSensor(*prevSettings); + deleteSignalQualityDynamicSensor(*prevSettings); + + switch (prevSettings->type) { + case Sensors::Type::BLUETOOTH: + deleteDynamicSensor(*prevSettings, Sensors::ValueType::TEMPERATURE); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::HUMIDITY); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::BATTERY); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::RSSI); + break; + + case Sensors::Type::DHT11: + case Sensors::Type::DHT22: + deleteDynamicSensor(*prevSettings, Sensors::ValueType::TEMPERATURE); + deleteDynamicSensor(*prevSettings, Sensors::ValueType::HUMIDITY); + break; + + default: + deleteDynamicSensor(*prevSettings); + break; + } + } + + // Hardware, calibration and discovery-only refreshes keep retained readings. + if (prevSettings && prevSettings->slug[0] && metadataChanged) { + purgeSensor(prevSettings->slug); + } + + if (settings.mqtt.homeAssistantDiscovery && sensor && Sensors::hasEnabledAndValid(*sensor)) { + if (sensor->type == Sensors::Type::BLUETOOTH || sensor->type == Sensors::Type::DALLAS_TEMP || + sensor->type == Sensors::Type::DHT11 || sensor->type == Sensors::Type::DHT22) { + publishConnectionDynamicSensor(*sensor); + publishSignalQualityDynamicSensor(*sensor); + + } else if (sensor->type == Sensors::Type::NTC_10K_TEMP) { + publishConnectionDynamicSensor(*sensor); + } + + switch (sensor->type) { + case Sensors::Type::BLUETOOTH: + publishDynamicSensor(*sensor, Sensors::ValueType::TEMPERATURE); + publishDynamicSensor(*sensor, Sensors::ValueType::HUMIDITY); + publishDynamicSensor(*sensor, Sensors::ValueType::BATTERY); + publishDynamicSensor(*sensor, Sensors::ValueType::RSSI, false); + break; + + case Sensors::Type::DHT11: + case Sensors::Type::DHT22: + publishDynamicSensor(*sensor, Sensors::ValueType::TEMPERATURE); + publishDynamicSensor(*sensor, Sensors::ValueType::HUMIDITY); + break; + + case Sensors::Type::MANUAL: + publishDynamicManualSensor(*sensor); + break; + + default: + publishDynamicSensor(*sensor); + break; + } + } + + mqttPublishSensorsTask->requestEarlyRun(); + }); + + task->setInterval(500).setEnabledWhen(isMqttReady); + coreTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttReconfigureSensorsTask = task; + } + + // Publish sensor readings after startup and pending subscription changes. + if (!mqttPublishSensorsTask) { + auto* task = new Task("Publish MQTT sensors", [](void*) { + static UnitSystem publishedUnitSystem = UnitSystem::METRIC; + if (publishedUnitSystem != settings.system.unitSystem) { + std::lock_guard lock(mqttSensorsMutex); + memset(mqttPublishedSensorAt, 0, sizeof(mqttPublishedSensorAt)); + publishedUnitSystem = settings.system.unitSystem; + } + + const unsigned long changeDelay = mqttPublishSensorsTask->earlyRunRequested() ? 0u : 1000u; + for (uint8_t sensorId = 0; sensorId < SENSORS_AMOUNT; sensorId++) { + std::optional snapshot; + { + std::lock_guard lock(mqttSensorsMutex); + if (isSensorReconfigurationPending(sensorId)) { + continue; + } + + // Keep physical updates after this cutoff pending for the next publication. + const unsigned long snapshotAt = millis(); + snapshot = Sensors::getSnapshot(sensorId); + if (!snapshot || !Sensors::hasEnabledAndValid(snapshot->settings)) { + continue; + } + + const unsigned long publishedAt = mqttPublishedSensorAt[sensorId]; + if (publishedAt) { + const auto now = millis(); + const auto elapsed = now - publishedAt; + const bool changed = now - snapshot->result.updatedAt <= elapsed; + + if (elapsed <= MQTT_SENSOR_REPUBLISH_INTERVAL && (!changed || elapsed < changeDelay)) { + continue; + } + } + + // A newer manual value can reset this timestamp while the snapshot is publishing. + mqttPublishedSensorAt[sensorId] = snapshotAt; + } + + publishSensor(snapshot->settings, snapshot->result); + } + }); + + task->setInterval(500).setEnabledWhen([] { + if (!isMqttReadyForPublish()) { + return false; + } + + std::lock_guard lock(mqttSensorsMutex); + return mqttSensorChanges.empty(); + }); + coreTaskManager.addTask(*task); + + std::lock_guard lock(mqttMutex); + mqttPublishSensorsTask = task; + } + + mqttPublishSettingsTask->setInterval(settings.mqtt.interval * 10000u); + mqttPublishStateTask->setInterval(settings.mqtt.interval * 1000u); + + // Call end() to reset the connection + stopMqtt(false); + + if (!isNetworkConnected()) { + return; + } + + // Call begin() to reconnect + connect(); + + if (!mqttClient->isEnabled()) { + stopMqtt(false); + + // Preserve a newer reconfiguration request instead of replacing it with backoff. + if (!mqttConfigureTask.scheduled()) { + mqttConfigureTask.resume(MQTT_RECONNECT_INTERVAL); + } + + ESP_LOGE(L_MQTT, "Failed to start MQTT client"); + return; + } +}); + +void initMqtt() { + // Keep only the configuration dispatcher when MQTT publications are disabled. + mqttConfigureTask.pause().setEnabledWhen([] { + return !vars.states.upgrading && !restartTask.scheduled() && !restartTask.active(); + }); + + coreTaskManager.addTask(mqttConfigureTask); + onNetworkEvent([](NetworkEvent event) { + if (event == NetworkEvent::CONNECTED || event == NetworkEvent::DISCONNECTED || event == NetworkEvent::EVENTS_OVERFLOW) { + requestReconfigureMqtt(); + } + }); +} diff --git a/src/network.cpp b/src/network.cpp new file mode 100644 index 0000000..a368aba --- /dev/null +++ b/src/network.cpp @@ -0,0 +1,849 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Requests and state shared with other workers. +static std::atomic reconnectRequested{false}; +static std::atomic staStarted{false}; +static std::atomic apStarted{false}; +static std::atomic staState{NetworkState::NETWORK_DISABLED}; +static std::atomic apState{NetworkState::NETWORK_DISABLED}; + +// Subscriptions are fixed before the worker starts. +static std::vector networkCallbacks; +static std::vector stateCallbacks; + +// Framework callbacks only copy events. Driver and service operations stay in this worker. +struct PendingNetworkEvent { + uint32_t value; // IPv4 address for STA_GOT_IP and AP_STARTED. + NetworkEvent event; + uint8_t reason; // STA disconnect reason. +}; + +static constexpr size_t NETWORK_EVENT_QUEUE_LENGTH = 32; +static StaticQueue_t networkEventQueueStorage; +static uint8_t networkEventBuffer[NETWORK_EVENT_QUEUE_LENGTH * sizeof(PendingNetworkEvent)]; +static QueueHandle_t networkEventQueue = nullptr; +static std::atomic networkEventsOverflowed{false}; +static std::atomic networkRecoveryRequested{false}; + +// Station state and timers; only the system worker accesses these values. +static unsigned long lastConnectionAttempt = 0; +static unsigned long connectedTime = 0; +static unsigned long disconnectedTime = 0; +static unsigned long lastRssiUpdate = 0; +static uint32_t connectedIp = 0; +static uint8_t disconnectReason = 0; +static bool staAssociated = false; +static bool connectionPending = false; +static bool ntpStarted = false; + +// Fallback access point +static unsigned long lastApAttempt = 0; +static uint32_t apIp = 0; +static uint8_t apClients = 0; + +// Full driver recovery +static unsigned long lastNetworkRecoveryAttempt = 0; +static bool recoveryPending = false; + +// DNS is asynchronous in the current framework; it needs no polling task. +static bool webServerReady = false; +static DNSServer dnsServer; +static bool dnsStarted = false; +static bool mdnsStarted = false; +static unsigned long lastDnsAttempt = 0; +static unsigned long lastMdnsAttempt = 0; +static char mdnsHostname[sizeof(networkSettings.hostname)] = {}; + +// Event subscriptions +void onNetworkEvent(NetworkEventCallback callback) { + if (!callback) { + return; + } + + for (auto registered : networkCallbacks) { + if (registered == callback) { + return; + } + } + + networkCallbacks.push_back(callback); +} + +void onNetworkStateChange(NetworkStateCallback callback) { + if (callback) { + stateCallbacks.push_back(std::move(callback)); + } +} + +// Published interface state +NetworkState getNetworkState(NetworkMode mode) { + if (mode == NetworkMode::STA) { + return staState.load(); + } + + if (mode == NetworkMode::AP) { + return apState.load(); + } + + // Ethernet initialization and routing will be implemented separately. + return NetworkState::NETWORK_DISABLED; +} + +bool isNetworkConnected() { + return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED; +} + +NetworkMode getNetworkMode() { + if (isNetworkConnected()) { + return NetworkMode::STA; + } + + return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE; +} + +bool isNetworkInterfaceStarted(NetworkMode mode) { + if (mode == NetworkMode::STA) { + return staStarted.load(); + } + + return mode == NetworkMode::AP && apStarted.load(); +} + +// Requests from other tasks; driver operations run in the system worker. +void reconnectNetwork() { + reconnectRequested.store(true); +} + +// State transitions and notifications +static void notifyNetworkEvent(NetworkEvent event) { + for (auto callback : networkCallbacks) { + callback(event); + } +} + +static void setNetworkState(NetworkMode mode, NetworkState next) { + auto& state = mode == NetworkMode::STA ? staState : apState; + const NetworkState previous = state.load(); + + if (previous == next) { + return; + } + + if (mode == NetworkMode::STA) { + if (previous == NetworkState::NETWORK_CONNECTED) { + disconnectedTime = millis(); + connectedIp = 0; + vars.network.rssi = 0; + ntpStarted = false; + Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false); + } + + if (next == NetworkState::NETWORK_CONNECTED) { + connectedTime = millis(); + } + } + + // Publish before callbacks so getters and JSON already reflect the new state. + state.store(next); + for (auto& callback : stateCallbacks) { + callback(mode, previous, next); + } + + if (mode == NetworkMode::STA) { + if (next == NetworkState::NETWORK_CONNECTED) { + notifyNetworkEvent(NetworkEvent::CONNECTED); + + } else if (previous == NetworkState::NETWORK_CONNECTED) { + notifyNetworkEvent(NetworkEvent::DISCONNECTED); + } + } +} + +// Framework events +static void queueNetworkEvent(NetworkEvent event, uint32_t value = 0, uint8_t reason = 0) { + const PendingNetworkEvent pending{value, event, reason}; + + // Never wait here: this worker can be waiting for the framework inside STA/AP.begin(). + if (xQueueSend(networkEventQueue, &pending, 0) != pdTRUE) { + networkEventsOverflowed.store(true); + } +} + +static void handleWifiEvent(arduino_event_id_t event, arduino_event_info_t info) { + // This callback runs in the Arduino event task; only copy the event data here. + switch (event) { + // Station + case ARDUINO_EVENT_WIFI_STA_START: + queueNetworkEvent(NetworkEvent::STA_STARTED); + break; + case ARDUINO_EVENT_WIFI_STA_STOP: + queueNetworkEvent(NetworkEvent::STA_STOPPED); + break; + case ARDUINO_EVENT_WIFI_STA_CONNECTED: + queueNetworkEvent(NetworkEvent::STA_CONNECTED); + break; + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: + queueNetworkEvent(NetworkEvent::STA_DISCONNECTED, 0, info.wifi_sta_disconnected.reason); + break; + case ARDUINO_EVENT_WIFI_STA_GOT_IP: + queueNetworkEvent(NetworkEvent::STA_GOT_IP, info.got_ip.ip_info.ip.addr); + break; + case ARDUINO_EVENT_WIFI_STA_LOST_IP: + queueNetworkEvent(NetworkEvent::STA_LOST_IP); + break; + case ARDUINO_EVENT_WIFI_STA_GOT_IP6: + queueNetworkEvent(NetworkEvent::STA_GOT_IP6); + break; + + // Access point + case ARDUINO_EVENT_WIFI_AP_START: + queueNetworkEvent(NetworkEvent::AP_STARTED, static_cast(WiFi.AP.localIP())); + break; + case ARDUINO_EVENT_WIFI_AP_STOP: + queueNetworkEvent(NetworkEvent::AP_STOPPED); + break; + case ARDUINO_EVENT_WIFI_AP_STACONNECTED: + queueNetworkEvent(NetworkEvent::AP_CLIENT_CONNECTED); + break; + case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: + queueNetworkEvent(NetworkEvent::AP_CLIENT_DISCONNECTED); + break; + case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: + queueNetworkEvent(NetworkEvent::AP_CLIENT_GOT_IP); + break; + case ARDUINO_EVENT_WIFI_AP_GOT_IP6: + queueNetworkEvent(NetworkEvent::AP_GOT_IP6); + break; + + default: + break; + } +} + +static void postInterfaceStopped(arduino_event_id_t type) { + // onDisable() can remove the native STOP handler. Keep our notification ordered + // after already queued framework START/GOT_IP events and before the next start. + arduino_event_t event{}; + event.event_id = type; + if (!Network.postEvent(&event)) { + ESP_LOGE(L_NETWORK, "Failed post interface stop, reset WiFi requested"); + networkRecoveryRequested.store(true); + } +} + +// WiFi interfaces +static void configureWifiRadio() { + // Apply the existing channel policy after the WiFi driver has started. + const wifi_country_t country = { + "JP", + 1, + 14, + CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER, + WIFI_COUNTRY_POLICY_MANUAL + }; + + esp_wifi_set_country(&country); + //WiFi.setSleep(USE_BLE ? WIFI_PS_MIN_MODEM : WIFI_PS_NONE); + WiFi.setSleep(WIFI_PS_NONE); +} + +static void stopAccessPoint() { + if (!WiFi.AP.end()) { + ESP_LOGE(L_NETWORK, "Failed stop AP, reset WiFi requested"); + networkRecoveryRequested.store(true); + return; + } + + postInterfaceStopped(ARDUINO_EVENT_WIFI_AP_STOP); +} + +static void startAccessPoint() { + lastApAttempt = millis(); + setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING); + + // Keep STA available for scans and retries while the fallback AP is running. + WiFi.STA.begin(); + if (!WiFi.AP.begin()) { + // begin() can enable AP but time out before its STARTED event arrives. + stopAccessPoint(); + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + ESP_LOGE(L_NETWORK, "Failed start AP"); + return; + } + + configureWifiRadio(); + WiFi.AP.setHostname(networkSettings.hostname); + if (!WiFi.AP.create( + networkSettings.ap.ssid, + networkSettings.ap.password[0] ? networkSettings.ap.password : nullptr, + networkSettings.ap.channel + )) { + stopAccessPoint(); + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + ESP_LOGE(L_NETWORK, "Failed configure AP"); + } +} + +static bool resetWifi() { + const bool restoreAp = WiFi.AP.started(); + connectionPending = false; + + // A failed driver reset must also respect the retry cooldown. + lastConnectionAttempt = millis(); + if (!WiFi.mode(WIFI_OFF)) { + ESP_LOGE(L_NETWORK, "Failed reset WiFi"); + return false; + } + + postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP); + if (restoreAp) { + postInterfaceStopped(ARDUINO_EVENT_WIFI_AP_STOP); + } + + lastConnectionAttempt = 0; + if (restoreAp) { + startAccessPoint(); + } + + return true; +} + +static bool startNetworkConnection() { + // Ordinary retries preserve AP. Escalate only if STA cannot be stopped. + const bool wasStarted = WiFi.STA.started(); + + if (!WiFi.STA.end()) { + ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi..."); + if (!resetWifi()) { + return false; + } + + } else if (wasStarted) { + postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP); + } + + if (!WiFi.STA.begin()) { + return false; + } + + configureWifiRadio(); + WiFi.STA.setAutoReconnect(false); + WiFi.STA.setScanMethod(WIFI_ALL_CHANNEL_SCAN); + WiFi.STA.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); + + if (!WiFi.STA.setHostname(networkSettings.hostname)) { + ESP_LOGE(L_NETWORK, "Set hostname '%s': fail", networkSettings.hostname); + } + + if (networkSettings.useDhcp) { + if (!WiFi.STA.config()) { + return false; + } + + } else { + IPAddress ip, gateway, subnet, dns; + ip.fromString(networkSettings.staticConfig.ip); + gateway.fromString(networkSettings.staticConfig.gateway); + subnet.fromString(networkSettings.staticConfig.subnet); + dns.fromString(networkSettings.staticConfig.dns); + + if (!WiFi.STA.config(ip, gateway, subnet, dns)) { + return false; + } + } + + setNetworkState( + NetworkMode::STA, + connectedTime ? NetworkState::NETWORK_RECONNECTING : NetworkState::NETWORK_CONNECTING + ); + + return WiFi.STA.connect( + networkSettings.sta.ssid, + networkSettings.sta.password[0] ? networkSettings.sta.password : nullptr, + networkSettings.sta.channel + ); +} + +// Station connection and recovery timeouts +static void updateConnection() { + if (!networkSettings.sta.ssid[0]) { + return; + } + + if (connectionPending) { + if (millis() - lastConnectionAttempt < 10000) { + return; + } + + connectionPending = false; + lastConnectionAttempt = millis(); + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_TIMEOUT); + + ESP_LOGD( + L_NETWORK, + "Connection attempt timed out. Status: %d", + WiFi.STA.status() + ); + } + + // Associated without IP: allow DHCP to recover before resetting the whole driver. + if (staAssociated) { + if (millis() - lastConnectionAttempt > 90000) { + ESP_LOGW(L_NETWORK, "Connection timeout, reset WiFi..."); + resetWifi(); + } + + return; + } + + if (!lastConnectionAttempt || millis() - lastConnectionAttempt > 15000) { + ESP_LOGI(L_NETWORK, "Try connect..."); + + connectionPending = startNetworkConnection(); + lastConnectionAttempt = millis(); + + if (!connectionPending) { + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_TIMEOUT); + ESP_LOGW(L_NETWORK, "Failed start connection"); + } + } +} + +// Fallback access point +static void updateAccessPoint() { + if (isNetworkConnected()) { + if (apStarted.load() && millis() - connectedTime > 15000 && !apClients) { + ESP_LOGI(L_NETWORK, "Stop AP because STA connected"); + stopAccessPoint(); + } + + return; + } + + if (!apStarted.load() && (!networkSettings.sta.ssid[0] || millis() - disconnectedTime > 185000)) { + if (!lastApAttempt || millis() - lastApAttempt > 15000) { + ESP_LOGI(L_NETWORK, "Start fallback AP"); + startAccessPoint(); + } + } +} + +// Captive DNS and mDNS +static void stopCaptiveDns(bool complete = false) { + if (!dnsStarted) { + return; + } + + dnsServer.stop(); + dnsStarted = false; + lastDnsAttempt = 0; + + if (complete) { + setNetworkState(NetworkMode::AP, NetworkState::PORTAL_COMPLETE); + } + + setNetworkState( + NetworkMode::AP, + apStarted.load() ? NetworkState::AP_STARTED : NetworkState::NETWORK_DISABLED + ); + notifyNetworkEvent(NetworkEvent::PORTAL_STOPPED); + ESP_LOGD(L_PORTAL_DNSSERVER, "Stopped"); +} + +static void stopMdns() { + if (mdnsStarted) { + MDNS.end(); + mdnsStarted = false; + lastMdnsAttempt = 0; + notifyNetworkEvent(NetworkEvent::MDNS_STOPPED); + ESP_LOGD(L_PORTAL_WEBSERVER, "mDNS disabled"); + } +} + +static void updateNetworkServices() { + const bool ready = webServerReady; + + // Serve captive DNS only while HTTP is ready and no upstream connection exists. + const bool captive = ready + && apStarted.load() + && apIp + && !isNetworkConnected(); + + if (!captive) { + stopCaptiveDns(isNetworkConnected()); + + } else if (!dnsStarted && (!lastDnsAttempt || millis() - lastDnsAttempt >= 5000)) { + lastDnsAttempt = millis(); + setNetworkState(NetworkMode::AP, NetworkState::PORTAL_STARTING); + + if (dnsServer.start(53, "*", IPAddress(apIp))) { + dnsStarted = true; + setNetworkState(NetworkMode::AP, NetworkState::PORTAL_STARTED); + notifyNetworkEvent(NetworkEvent::PORTAL_STARTED); + ESP_LOGD(L_PORTAL_DNSSERVER, "Started: AP up"); + + } else { + dnsServer.stop(); + setNetworkState(NetworkMode::AP, NetworkState::AP_STARTED); + ESP_LOGE(L_PORTAL_DNSSERVER, "Failed start DNS"); + } + } + + // Advertise HTTP on either interface, including while the fallback AP is active. + const bool enableMdns = ready + && settings.portal.mdns + && (apStarted.load() || isNetworkConnected()); + + if (!enableMdns) { + stopMdns(); + + } else { + if (mdnsStarted && strcmp(mdnsHostname, networkSettings.hostname) != 0) { + stopMdns(); + lastMdnsAttempt = 0; + } + + if (!mdnsStarted && (!lastMdnsAttempt || millis() - lastMdnsAttempt >= 5000)) { + lastMdnsAttempt = millis(); + bool started = MDNS.begin(networkSettings.hostname); + + if (started) { + started = MDNS.addService("http", "tcp", 80); + } + + if (started) { + strcpy(mdnsHostname, networkSettings.hostname); + mdnsStarted = true; + notifyNetworkEvent(NetworkEvent::MDNS_STARTED); + ESP_LOGD(L_PORTAL_WEBSERVER, "mDNS enabled and service added"); + + } else { + MDNS.end(); + ESP_LOGE(L_PORTAL_WEBSERVER, "Failed start mDNS"); + } + } + } +} + +// Event processing and recovery +static void processNetworkEvent(const PendingNetworkEvent& pending) { + switch (pending.event) { + // Station + case NetworkEvent::STA_STARTED: + // Repeated START must not invalidate an active connection. + if (staStarted.exchange(true)) { + break; + } + + if (connectionPending) { + setNetworkState( + NetworkMode::STA, + connectedTime ? NetworkState::NETWORK_RECONNECTING : NetworkState::NETWORK_CONNECTING + ); + + } else { + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_ENABLED); + } + break; + case NetworkEvent::STA_STOPPED: { + const bool started = staStarted.exchange(false); + staAssociated = false; + disconnectReason = 0; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED); + if (!started) { + return; + } + break; + } + + case NetworkEvent::STA_CONNECTED: + // Association alone does not confirm a usable IP address. + staAssociated = true; + break; + case NetworkEvent::STA_GOT_IP: + if (!pending.value) { + return; + } + + // GOT_IP confirms both DHCP and configured static IPv4 after association. + // IP changes invalidate the previous client session, including A -> B -> A. + if (isNetworkConnected() && connectedIp != pending.value) { + disconnectReason = 0; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); + } + + staAssociated = true; + connectedIp = pending.value; + if (!isNetworkConnected()) { + vars.network.rssi = WiFi.STA.RSSI(); + lastRssiUpdate = millis(); + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_CONNECTED); + } + break; + case NetworkEvent::STA_DISCONNECTED: + staAssociated = false; + disconnectReason = pending.reason; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); + break; + case NetworkEvent::STA_LOST_IP: + // Keep association so the DHCP recovery timeout remains active. + disconnectReason = 0; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); + break; + + // Access point + case NetworkEvent::AP_STARTED: + // Preserve clients and captive portal state on a repeated START. + if (apStarted.exchange(true)) { + break; + } + + apIp = pending.value; + apClients = 0; + setNetworkState(NetworkMode::AP, NetworkState::AP_STARTED); + break; + case NetworkEvent::AP_STOPPED: { + stopCaptiveDns(); + const bool started = apStarted.exchange(false); + apIp = 0; + apClients = 0; + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + if (!isNetworkConnected()) { + stopMdns(); + } + if (!started) { + return; + } + break; + } + + case NetworkEvent::AP_CLIENT_CONNECTED: + if (apClients < UINT8_MAX) { + ++apClients; + } + break; + + case NetworkEvent::AP_CLIENT_DISCONNECTED: + if (apClients) { + --apClients; + } + break; + default: + break; + } + + notifyNetworkEvent(pending.event); +} + +static void processNetworkEvents() { + const bool overflowed = networkEventsOverflowed.exchange(false); + const bool recoveryRequested = networkRecoveryRequested.exchange(false); + + if (overflowed || recoveryRequested) { + // Lost events invalidate published state immediately, even during the reset cooldown. + xQueueReset(networkEventQueue); + stopCaptiveDns(); + stopMdns(); + staStarted.store(false); + apStarted.store(false); + staAssociated = false; + setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED); + setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); + + if (overflowed) { + ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi requested"); + notifyNetworkEvent(NetworkEvent::EVENTS_OVERFLOW); + } + + recoveryPending = true; + } + + if (recoveryPending) { + // Limit driver resets, but keep the published state offline while waiting. + if (lastNetworkRecoveryAttempt && millis() - lastNetworkRecoveryAttempt < 15000) { + return; + } + + lastNetworkRecoveryAttempt = millis(); + // Keep callbacks nonblocking; recover through the existing full-reset path. + ESP_LOGW(L_NETWORK, "Reset WiFi after network event failure..."); + if (!resetWifi()) { + return; + } + + recoveryPending = false; + } + + // Bound each pass so event bursts leave time for the rest of the worker. + PendingNetworkEvent pending; + for (size_t count = 0; count < NETWORK_EVENT_QUEUE_LENGTH; ++count) { + if (xQueueReceive(networkEventQueue, &pending, 0) != pdTRUE) { + break; + } + + processNetworkEvent(pending); + } +} + +// Connection services +static void updateRssi() { + if (isNetworkConnected() && millis() - lastRssiUpdate >= 1000) { + vars.network.rssi = WiFi.STA.RSSI(); + lastRssiUpdate = millis(); + } +} + +static void updateNtp() { + if (!ntpStarted && settings.system.ntp.server[0]) { + configTime(0, 0, settings.system.ntp.server); + setenv("TZ", settings.system.ntp.timezone, 1); + tzset(); + ntpStarted = true; + } +} + +static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) { + if (mode != NetworkMode::STA) { + return; + } + + if (state == NetworkState::NETWORK_CONNECTED) { + ESP_LOGI( + L_NETWORK, + "Connected, downtime: %lu s., IP: %s, RSSI: %hhd", + (millis() - disconnectedTime) / 1000, + IPAddress(connectedIp).toString().c_str(), + vars.network.rssi + ); + + } else if (previous == NetworkState::NETWORK_CONNECTED) { + ESP_LOGI( + L_NETWORK, + "Disconnected, reason: %hhu, uptime: %lu s.", + disconnectReason, + (millis() - connectedTime) / 1000 + ); + } +} + +// Tasks +static Task networkStartTask("Start network services", Task::Type::ONCE, [](void*) { + if (webServerReady || (!isNetworkInterfaceStarted(NetworkMode::AP) && !isNetworkConnected())) { + return; + } + + webServer->begin(); + webServerReady = true; + configureLoggingTask.resume(); + ESP_LOGD(L_PORTAL_WEBSERVER, "Started: AP up or STA connected"); +}); + +static Task reconnectTask("Reconnect network", Task::Type::ONCE, [](void*) { + ESP_LOGI(L_NETWORK, "Reconnecting..."); + + const bool wasStarted = WiFi.STA.started(); + if (!WiFi.STA.end()) { + ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi..."); + resetWifi(); + return; + } + + if (wasStarted) { + postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP); + } + + lastConnectionAttempt = 0; + connectionPending = false; +}); + +static Task networkTask("Network", [](void*) { + // Delay explicit reconnects so the HTTP handler can finish its response. + if (reconnectRequested.exchange(false)) { + reconnectTask.resume(5000); + } + + // Apply queued transitions before using the interfaces and services. + processNetworkEvents(); + if (!isNetworkConnected()) { + Sensors::setConnectionStatusByType(Sensors::Type::MANUAL, false, false); + } + + if (recoveryPending + || networkRecoveryRequested.load() + || networkEventsOverflowed.load() + ) { + return; + } + + updateRssi(); + updateNetworkServices(); + + // Continue processing events and services during the reconnect delay. + if (!reconnectTask.paused()) { + return; + } + + if (isNetworkConnected()) { + if (connectionPending) { + connectionPending = false; + lastConnectionAttempt = millis(); + } + + updateNtp(); + updateAccessPoint(); + + } else { + updateAccessPoint(); + updateConnection(); + } +}); + +// Initialization +void initNetwork() { + // The queue must exist before registering framework callbacks or starting WiFi. + networkEventQueue = xQueueCreateStatic( + NETWORK_EVENT_QUEUE_LENGTH, + sizeof(PendingNetworkEvent), + networkEventBuffer, + &networkEventQueueStorage + ); + + if (!networkEventQueue) { + ESP_LOGE(L_NETWORK, "Failed create network event queue"); + std::abort(); + } + + dnsServer.setTTL(0); + dnsServer.setErrorReplyCode(DNSReplyCode::NoError); + + onNetworkEvent([](NetworkEvent event) { + if (!webServerReady && (event == NetworkEvent::AP_STARTED || event == NetworkEvent::CONNECTED)) { + networkStartTask.resume(); + } + }); + + Network.begin(); + Network.onEvent(handleWifiEvent); + onNetworkStateChange(logNetworkState); + WiFi.persistent(false); + WiFi.STA.setAutoReconnect(false); + Network.setHostname(networkSettings.hostname); + + networkTask.setInterval(100); + systemTaskManager.addTask(reconnectTask); + systemTaskManager.addTask(networkTask); + systemTaskManager.addTask(networkStartTask); +} diff --git a/src/opentherm.cpp b/src/opentherm.cpp new file mode 100644 index 0000000..ee94e3a --- /dev/null +++ b/src/opentherm.cpp @@ -0,0 +1,2306 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include + +// Application state and ID polling belong to this manager; the library owns RMT. + +static const unsigned short masterReadyTime = 60000u; +static const unsigned int resetBusInterval = 120000u; +static const unsigned short heatingSetpointWriteInterval = 60000u; +static const unsigned short roomSetpointWriteInterval = 60000u; +static const unsigned short dhwSetpointWriteInterval = 60000u; +static const unsigned short ch2SetpointWriteInterval = 60000u; +static const unsigned int initializingInterval = 1800000u; +static const char responseMismatchMessage[] = "Response mismatch: expected %04x, received %04x"; +static const char unrepresentableTemperatureLimitsMessage[] = "Received temperature limits cannot be represented in system units"; + +static ESP32OT::ESP32OT slave; +static unsigned long busConfiguredTime = 0; +static unsigned long connectedTime = 0; +static unsigned long disconnectedTime = 0; +static unsigned long resetBusTime = 0; +static unsigned long initializedTime = 0; +static unsigned long lastSuccessStatusResponse = 0; +static unsigned long heatingSetpointWriteTime = 0; +static unsigned long dhwSetpointWriteTime = 0; +static unsigned long ch2SetpointWriteTime = 0; +static unsigned long roomSetpointWriteTime = 0; +static unsigned long ch2RoomSetpointWriteTime = 0; +static std::atomic configuredRxLedGpio{GPIO_IS_NOT_CONFIGURED}; + + +static bool canUseBus() { + return !restartTask.scheduled() + && slave.isInitialized() + && slave.getConfig().rxGpio == settings.opentherm.inGpio + && slave.getConfig().txGpio == settings.opentherm.outGpio; +} + +static bool isMasterReady() { + return millis() - busConfiguredTime > masterReadyTime; +} + +static bool getSlaveChannelEnabled(const bool enabled, const ChannelDisablingAction action); +static float getSlaveChannelSetpoint(const bool enabled, const float temperature, const ChannelDisablingAction action); +static bool needWriteRoomSetpoint(const float target); +static bool needWriteRoomSetpointCh2(const float target); +static bool needWriteDhwSetpoint(const float target); +static bool needWriteHeatingSetpoint(const float target); +static bool needWriteCh2Setpoint(const float target); + +static bool getSlaveChannelEnabled(const bool enabled, const ChannelDisablingAction action) { + return enabled || action == ChannelDisablingAction::ZERO_SETPOINT; +} + +static float getSlaveChannelSetpoint(const bool enabled, const float temperature, const ChannelDisablingAction action) { + if (!enabled && action != ChannelDisablingAction::OFF) { + return 0.0f; + } + + return temperature; +} + +static float getHeatingChannelSetpoint() { + return getSlaveChannelSetpoint( + vars.master.heating.enabled, + settings.opentherm.options.nativeOTC + ? vars.master.heating.targetTemp + : vars.master.heating.setpointTemp, + settings.opentherm.heatingDisablingAction + ); +} + +static float getDhwChannelSetpoint() { + return getSlaveChannelSetpoint( + vars.master.dhw.enabled, vars.master.dhw.targetTemp, settings.opentherm.dhwDisablingAction + ); +} + +static float getCh2ChannelSetpoint() { + return getSlaveChannelSetpoint( + vars.master.ch2.enabled, vars.master.ch2.targetTemp, settings.opentherm.ch2DisablingAction + ); +} + +static bool needWriteRoomSetpoint(const float target) { + return !roomSetpointWriteTime + || millis() - roomSetpointWriteTime > roomSetpointWriteInterval + || isFloatDifferent(target, vars.slave.heating.roomTargetTemp, 0.05f); +} + +static bool needWriteRoomSetpointCh2(const float target) { + return !ch2RoomSetpointWriteTime + || millis() - ch2RoomSetpointWriteTime > roomSetpointWriteInterval + || isFloatDifferent(target, vars.slave.ch2.roomTargetTemp, 0.05f); +} + +static bool needWriteDhwSetpoint(const float target) { + return !dhwSetpointWriteTime + || millis() - dhwSetpointWriteTime > dhwSetpointWriteInterval + || isFloatDifferent(target, vars.slave.dhw.targetTemp, 0.05f); +} + +static bool needWriteHeatingSetpoint(const float target) { + return !heatingSetpointWriteTime + || millis() - heatingSetpointWriteTime > heatingSetpointWriteInterval + || isFloatDifferent(target, vars.slave.heating.targetTemp, 0.05f); +} + +static bool needWriteCh2Setpoint(const float target) { + return !ch2SetpointWriteTime + || millis() - ch2SetpointWriteTime > ch2SetpointWriteInterval + || isFloatDifferent(target, vars.slave.ch2.targetTemp, 0.05f); +} + +// ONCE identification steps keep their own callbacks and completion handling. +static Task readSlaveVersionTask("Read slave version", Task::Type::ONCE, [](void*) { + const auto response = slave.sendRequest( + ESP32OT::Messages::ProductVersion(ESP32OT::MessageID::SlaveVersion) + ); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive slave version"); + return; + } + + vars.slave.appVersion = response.getVersion(); + vars.slave.type = response.getProductType(); + + ESP_LOGI( + L_OT, "Received slave app version: %u, type: %u", + vars.slave.appVersion, vars.slave.type + ); +}); + +static Task writeMasterVersionTask("Write master version", Task::Type::ONCE, [](void*) { + const ESP32OT::Messages::ProductVersion request( + ESP32OT::MessageID::MasterVersion, + vars.master.type, + vars.master.appVersion + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || + response.getVersion() != request.getVersion() || + response.getProductType() != request.getProductType()) { + ESP_LOGW(L_OT, "Failed set master version"); + return; + } + + ESP_LOGI( + L_OT, "Set master version: %u, type: %u", + vars.master.appVersion, vars.master.type + ); +}); + +static Task readSlaveProtocolTask("Read slave protocol", Task::Type::ONCE, [](void*) { + const auto response = slave.sendRequest( + ESP32OT::Messages::Float(ESP32OT::MessageID::OpenThermVersionSlave) + ); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive slave OT version"); + return; + } + + vars.slave.protocolVersion = response.get(); + + ESP_LOGI(L_OT, "Received slave OT version: %f", vars.slave.protocolVersion); +}); + +static Task writeMasterProtocolTask("Write master protocol", Task::Type::ONCE, [](void*) { + const ESP32OT::Messages::Float request( + ESP32OT::MessageID::OpenThermVersionMaster, + vars.master.protocolVersion + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGW(L_OT, "Failed set master OT version"); + return; + } + + ESP_LOGI(L_OT, "Set master OT version: %f", vars.master.protocolVersion); +}); + +static Task readSlaveConfigTask("Read slave config", Task::Type::ONCE, [](void*) { + const auto response = slave.sendRequest(ESP32OT::Messages::SlaveConfig()); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive slave config"); + return; + } + + vars.slave.memberId = response.getMemberId(); + vars.slave.flags = response.getHighByte(); + + ESP_LOGI( + L_OT, "Received slave member id: %u, flags: %u", + vars.slave.memberId, vars.slave.flags + ); +}); + +static Task writeMasterConfigTask("Write master config", Task::Type::ONCE, [](void*) { + const uint8_t id = vars.master.memberId; + const uint8_t flags = vars.master.flags; + const uint8_t memberId = id > 0 ? id : vars.slave.memberId; + const uint8_t configFlags = flags > 0 ? flags : vars.slave.flags; + const ESP32OT::Messages::MasterConfig request(configFlags, memberId); + if (request.getData()) { + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGW(L_OT, "Failed set master config"); + return; + } + } + + ESP_LOGI( + L_OT, "Set master member id: %u, flags: %u", + vars.master.memberId, vars.master.flags + ); +}); + +// Keep initialization scheduled until completion; ONCE pauses before its callback. +static Task initializeSlaveTask("Initialize slave", [](void*) { + ESP_LOGI(L_OT, "Initializing..."); + + readSlaveVersionTask.resume().tryRun(); + writeMasterVersionTask.resume().tryRun(); + readSlaveProtocolTask.resume().tryRun(); + writeMasterProtocolTask.resume().tryRun(); + readSlaveConfigTask.resume().tryRun(); + writeMasterConfigTask.resume().tryRun(); + + if (!canUseBus() || !vars.slave.connected) { + return; + } + + initializeSlaveTask.pause(); + initializedTime = millis(); +}); + +static bool isSlaveReady() { + return canUseBus() && vars.slave.connected && !initializeSlaveTask.scheduled(); +} + +static bool isInitializingSlave() { + return canUseBus() && vars.slave.connected && initializeSlaveTask.running(); +} + + +static void updateMasterState() { + // Heating settings + vars.master.heating.enabled = isMasterReady() + && settings.heating.enabled + && (vars.master.heating.freezing || (vars.cascadeControl.input && !vars.master.heating.blocking)) + && !vars.master.heating.overheat; + + // DHW settings + vars.master.dhw.enabled = isMasterReady() + && settings.opentherm.options.dhwSupport + && settings.dhw.enabled + && !vars.master.dhw.overheat; + vars.master.dhw.targetTemp = settings.dhw.target; + + // CH2 settings + vars.master.ch2.enabled = settings.opentherm.options.ch2AlwaysEnabled + || (settings.opentherm.options.heatingToCh2 && vars.master.heating.enabled) + || (settings.opentherm.options.dhwToCh2 && vars.master.dhw.enabled); + + if (settings.opentherm.options.heatingToCh2) { + vars.master.ch2.targetTemp = !settings.opentherm.options.nativeOTC + ? vars.master.heating.setpointTemp + : vars.master.heating.targetTemp; + + } else if (settings.opentherm.options.dhwToCh2) { + vars.master.ch2.targetTemp = vars.master.dhw.targetTemp; + } + + if (isSlaveReady()) { + if (vars.master.heating.enabled != vars.slave.heating.enabled) { + vars.slave.heating.enabled = vars.master.heating.enabled; + ESP_LOGI(L_OT_HEATING, vars.master.heating.enabled ? "Enabled" : "Disabled"); + } + + if (vars.master.dhw.enabled != vars.slave.dhw.enabled) { + vars.slave.dhw.enabled = vars.master.dhw.enabled; + ESP_LOGI(L_OT_DHW, vars.master.dhw.enabled ? "Enabled" : "Disabled"); + } + } +} + +static Task configureDriverTask("Configure OpenTherm driver", Task::Type::ONCE, [](void*) { + // Stop the current bus before changing GPIO. + if (!slave.end()) { + ESP_LOGW(L_OT, "Failed stop"); + return; + } + + if (!GPIO_IS_VALID_INPUT(settings.opentherm.inGpio) || !GPIO_IS_VALID_OUTPUT(settings.opentherm.outGpio)) { + ESP_LOGW( + L_OT, + "Not started. GPIO IN: %hhu or GPIO OUT: %hhu is not valid", + settings.opentherm.inGpio, + settings.opentherm.outGpio + ); + return; + } + + #ifdef OT_BYPASS_RELAY_GPIO + pinMode(OT_BYPASS_RELAY_GPIO, OUTPUT); + digitalWrite(OT_BYPASS_RELAY_GPIO, true); + #endif + + // Configure the existing driver. + ESP32OT::ESP32OT::Config config; + config.rxGpio = static_cast(settings.opentherm.inGpio); + config.txGpio = static_cast(settings.opentherm.outGpio); + + // Log formatting stays on the RMT worker; transport output runs on System. + config.stackSize = 4096; + if (!slave.setConfig(config)) { + ESP_LOGW(L_OT, "Failed configure"); + return; + } + + // flags + busConfiguredTime = millis(); + resetBusTime = millis(); + initializeSlaveTask.resume(); + heatingSetpointWriteTime = 0; + dhwSetpointWriteTime = 0; + ch2SetpointWriteTime = 0; + roomSetpointWriteTime = 0; + ch2RoomSetpointWriteTime = 0; + + ESP_LOGI(L_OT, "Started. GPIO IN: %hhu, GPIO OUT: %hhu", settings.opentherm.inGpio, settings.opentherm.outGpio); + + slave.onStatusChange([](const ESP32OT::ESP32OT::StatusEvent& event) { + const auto& response = event.message; + if (!response.isComplete()) { + return; + } + + ESP_LOGD( + L_OT, + "ID: %3d; Request: %8lx; Response: %8lx; Msg type: %s; Attempt: %2d; Status: %s", + static_cast(ESP32OT::Protocol::Frame::getId(response.getRequest())), + static_cast(response.getRequest()), + static_cast(response.hasFrame() ? response.getRaw() : 0), + response.hasFrame() ? ESP32OT::Protocol::Frame::typeToString(response.getType()) : "NONE", + response.getAttempt(), + ESP32OT::Protocol::Frame::statusToString(response.getStatus()) + ); + + if (response.isSuccess()) { + // The manager may reconfigure the LED after sendRequest() returns. + const uint8_t rxLedGpio = configuredRxLedGpio.load(); + if (rxLedGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(rxLedGpio, HIGH); + delayMicroseconds(2000); + digitalWrite(rxLedGpio, LOW); + } + } + }); +}); + +static Task maintainOpenThermTask("Maintain OpenTherm", [](void*) { + if (slave.getConfig().rxGpio != settings.opentherm.inGpio || + slave.getConfig().txGpio != settings.opentherm.outGpio) { + // Apply changed GPIO before any bus exchange in this manager pass. + configureDriverTask.resume().tryRun(); + + } else if (vars.master.memberId != settings.opentherm.memberId || vars.master.flags != settings.opentherm.flags) { + initializeSlaveTask.resume(); + vars.master.memberId = settings.opentherm.memberId; + vars.master.flags = settings.opentherm.flags; + + } else if (millis() - initializedTime > initializingInterval) { + initializeSlaveTask.resume(); + } + + if (slave.getConfig().rxGpio != settings.opentherm.inGpio || + slave.getConfig().txGpio != settings.opentherm.outGpio) { + maintainOpenThermTask.setInterval(5000); + return; + + } else if (!slave.isInitialized()) { + // A fatal error can leave the RMT worker alive until end() succeeds. + if (!slave.end() || !slave.begin()) { + ESP_LOGW(L_OT, "Failed begin"); + + maintainOpenThermTask.setInterval(5000); + return; + } + } + + // Retry failures after 5 seconds; otherwise check settings on each pass. + maintainOpenThermTask.setInterval(0); + + // RX LED GPIO setup + const uint8_t rxLedGpio = configuredRxLedGpio.load(); + if (settings.opentherm.rxLedGpio != rxLedGpio) { + configuredRxLedGpio.store(GPIO_IS_NOT_CONFIGURED); + if (rxLedGpio != GPIO_IS_NOT_CONFIGURED) { + digitalWrite(rxLedGpio, LOW); + } + + if (GPIO_IS_VALID_OUTPUT(settings.opentherm.rxLedGpio)) { + pinMode(settings.opentherm.rxLedGpio, OUTPUT); + digitalWrite(settings.opentherm.rxLedGpio, LOW); + configuredRxLedGpio.store(settings.opentherm.rxLedGpio); + } + } + + updateMasterState(); +}); + +static Task readStatusTask("Read boiler status", [](void*) { + updateMasterState(); + + // Set boiler status LB + // Some boilers require this, although this is against protocol + uint8_t statusLb = 0; + + // Immergas fix + // https://arduino.ru/forum/programmirovanie/termostat-opentherm-na-esp8266?page=15#comment-649392 + if (settings.opentherm.options.immergasFix) { + statusLb = 0xCA; + } + + // Mode flags follow the channel request, before applying its disabling action. + + // Summer/winter mode + bool summerWinterMode = settings.opentherm.options.summerWinterMode; + if (settings.opentherm.options.heatingStateToSummerWinterMode) { + summerWinterMode = vars.master.heating.enabled == summerWinterMode; + } + + // DHW blocking + bool dhwBlocking = settings.opentherm.options.dhwBlocking; + if (settings.opentherm.options.dhwStateAsDhwBlocking) { + dhwBlocking = vars.master.dhw.enabled == dhwBlocking; + } + + ESP32OT::Messages::Status request(0, statusLb); + request + .setCentralHeatingEnabled(getSlaveChannelEnabled( + vars.master.heating.enabled, settings.opentherm.heatingDisablingAction + )) + .setHotWaterEnabled( + settings.opentherm.options.dhwSupport && + getSlaveChannelEnabled(vars.master.dhw.enabled, settings.opentherm.dhwDisablingAction) + ) + .setCoolingEnabled(settings.opentherm.options.coolingSupport) + .setOutsideTemperatureCompensationEnabled(settings.opentherm.options.nativeOTC) + .setCh2Enabled(getSlaveChannelEnabled( + vars.master.ch2.enabled, settings.opentherm.ch2DisablingAction + )) + .setSummerWinterMode(summerWinterMode) + .setDhwBlocking(dhwBlocking); + + const auto response = slave.sendRequest(request); + const bool validStatus = response.isSuccess(); + if (!validStatus) { + ESP_LOGW( + L_OT, + "Failed receive boiler status: %s", + ESP32OT::Protocol::Frame::statusToString(response.getStatus()) + ); + + } else { + lastSuccessStatusResponse = millis(); + vars.slave.heating.active = response.isCentralHeatingActive(); + vars.slave.dhw.active = settings.opentherm.options.dhwSupport ? response.isHotWaterActive() : false; + vars.slave.flame = response.isFlameOn(); + vars.slave.cooling.active = response.isCoolingActive(); + vars.slave.ch2.active = response.isCh2Active(); + vars.slave.fault.active = response.isFault(); + + if (!settings.opentherm.options.ignoreDiagState) { + vars.slave.diag.active = response.isDiagnostic(); + + } else if (vars.slave.diag.active) { + vars.slave.diag.active = false; + } + + if (!vars.slave.fault.active && vars.slave.fault.code != 0) { + vars.slave.fault.code = 0; + } + + if (!vars.slave.diag.active && vars.slave.diag.code != 0) { + vars.slave.diag.code = 0; + } + + ESP_LOGI( + L_OT, "Received boiler status. Heating: %hhu; DHW: %hhu; flame: %hhu; cooling: %hhu; channel 2: %hhu; fault: %hhu; diag: %hhu", + vars.slave.heating.active, vars.slave.dhw.active, + vars.slave.flame, vars.slave.cooling.active, vars.slave.ch2.active, vars.slave.fault.active, vars.slave.diag.active + ); + } + + // 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, + "Connected, downtime: %lu s.", + (millis() - disconnectedTime) / 1000 + ); + + 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; + } + + // 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) { + ESP_LOGI(L_OT, "Reset bus..."); + + if (!slave.end()) { + ESP_LOGW(L_OT, "Failed stop"); + } + + resetBusTime = millis(); + ::delay(5000); + } + } + + } else { + std::unique_lock mqttLock(mqttMutex, std::try_to_lock); + if (mqttLock.owns_lock() && mqttPublishStateTask) { + mqttPublishStateTask->requestEarlyRun(); + } + } +}); + +static Task writeHeatingSetpointTask("Write heating setpoint", [](void*) { + // Target heating temp + const float targetTemp = getHeatingChannelSetpoint(); + + // Set max heating temp + if (settings.opentherm.options.maxTempSyncWithTargetTemp) { + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::MaxTSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (response.isSuccess() && response.getData() == request.getData()) { + ESP_LOGI( + L_OT_HEATING, "Set max heating temp: %.2f", + targetTemp + ); + + } else { + ESP_LOGW( + L_OT_HEATING, "Failed set max heating temp: %.2f", + targetTemp + ); + } + } + + // Set target heating temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set target temp"); + return; + } + + vars.slave.heating.targetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + heatingSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_HEATING, "Set target temp: %.2f (response: %.2f)", + targetTemp, vars.slave.heating.targetTemp + ); +}); + +static Task writeDhwSetpointTask("Write DHW setpoint", [](void*) { + // Target dhw temp + const float targetTemp = getDhwChannelSetpoint(); + + // Set DHW temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TdhwSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_DHW, "Failed set temp"); + return; + } + + vars.slave.dhw.targetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_DHW, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + dhwSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_DHW, "Set temp: %.2f (response: %.2f)", + targetTemp, vars.slave.dhw.targetTemp + ); +}); + +static Task writeCh2SetpointTask("Write CH2 setpoint", [](void*) { + // Target CH2 heating temp + const float targetTemp = getCh2ChannelSetpoint(); + + // Set CH2 temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TsetCH2, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_CH2, "Failed set temp"); + return; + } + + vars.slave.ch2.targetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_CH2, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ch2SetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_CH2, "Set temp: %.2f (response: %.2f)", + targetTemp, vars.slave.ch2.targetTemp + ); +}); + +static Task writeRoomSetpointTask("Write room setpoint", [](void*) { + // Target indoor temp + const float& targetTemp = vars.master.heating.targetTemp; + + // Set target indoor temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TrSet, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set target indoor temp"); + return; + } + + vars.slave.heating.roomTargetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + roomSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_HEATING, "Set target indoor temp: %.2f (response: %.2f)", + targetTemp, vars.slave.heating.roomTargetTemp + ); +}); + +static Task writeRoomSetpointCh2Task("Write CH2 room setpoint", [](void*) { + // Target indoor temp + const float& targetTemp = vars.master.heating.targetTemp; + + // Set target CH2 temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TrSetCH2, + targetTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set target CH2 indoor temp"); + return; + } + + vars.slave.ch2.roomTargetTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ch2RoomSetpointWriteTime = millis(); + + ESP_LOGI( + L_OT_HEATING, "Set target CH2 indoor temp: %.2f (response: %.2f)", + targetTemp, vars.slave.ch2.roomTargetTemp + ); +}); + +static Task writeMaxModulationTask("Write maximum modulation", [](void*) { + // Set max modulation level + uint8_t maxModulation = vars.slave.modulation.max; + if (vars.slave.heating.active) { + maxModulation = settings.heating.maxModulation; + + } else if (vars.slave.dhw.active) { + maxModulation = settings.dhw.maxModulation; + + } else { + // This fixes the inability to enable channels if + // the maximum modulation level has become zero for some reason. + + if (vars.master.heating.enabled && maxModulation < settings.heating.maxModulation) { + maxModulation = settings.heating.maxModulation; + } + + if (vars.master.dhw.enabled && maxModulation < settings.dhw.maxModulation) { + maxModulation = settings.dhw.maxModulation; + } + } + + const ESP32OT::Messages::Float request(ESP32OT::MessageID::MaxRelModLevelSetting, maxModulation); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW( + L_OT, "Failed set max modulation: %hhu%% (response: %hhu%%)", + maxModulation, vars.slave.modulation.max + ); + return; + } + + vars.slave.modulation.max = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ESP_LOGI( + L_OT, "Set max modulation: %hhu%% (response: %hhu%%)", + maxModulation, vars.slave.modulation.max + ); +}); + +static Task writeCoolingSetpointTask("Write cooling setpoint", [](void*) { + // Set cooling setpoint = heating max modulation + const ESP32OT::Messages::Float request( + ESP32OT::MessageID::CoolingControl, + settings.heating.maxModulation + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW( + L_OT, "Failed set cooling setpoint: %hhu%% (response: %hhu%%)", + settings.heating.maxModulation, vars.slave.cooling.setpoint + ); + return; + } + + vars.slave.cooling.setpoint = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ESP_LOGI( + L_OT, "Set cooling setpoint: %hhu%% (response: %hhu%%)", + settings.heating.maxModulation, vars.slave.cooling.setpoint + ); +}); + +// Fault reset action +static Task writeFaultResetTask("Write fault reset", [](void*) { + const auto response = slave.sendRequest(ESP32OT::Messages::RemoteRequest(1)); + if (!response.isSuccess() || response.getRequestCode() != 1 || response.getResponseCode() < 128) { + ESP_LOGE(L_OT, "Boiler fault reset failed"); + return; + } + + slave.sendRequest(ESP32OT::Messages::RemoteRequest(0)); + ESP_LOGI(L_OT, "Boiler fault reset successfully"); +}); + +// Diag reset action +static Task writeDiagnosticResetTask("Write diagnostic reset", [](void*) { + const auto response = slave.sendRequest(ESP32OT::Messages::RemoteRequest(10)); + if (!response.isSuccess() || + response.getRequestCode() != 10 || + response.getResponseCode() < 128) { + ESP_LOGE(L_OT, "Boiler diagnostic reset failed"); + return; + } + + slave.sendRequest(ESP32OT::Messages::RemoteRequest(0)); + ESP_LOGI(L_OT, "Boiler diagnostic reset successfully"); +}); + +Task writeRoomTemperatureTask("Write room temperature", [](void*) { + // Current indoor temp + const float& indoorTemp = vars.master.heating.indoorTemp; + + // Set current indoor temp + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::Tr, + indoorTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set current indoor temp"); + return; + } + + vars.slave.heating.indoorTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ESP_LOGI( + L_OT_HEATING, "Set current indoor temp: %.2f (response: %.2f)", + indoorTemp, vars.slave.heating.indoorTemp + ); +}); + +Task writeRoomTemperatureCh2Task("Write CH2 room temperature", [](void*) { + // Current indoor temp + const float& indoorTemp = vars.master.heating.indoorTemp; + + const auto request = ESP32OT::Messages::Float::writeTemperature( + ESP32OT::MessageID::TrCH2, + indoorTemp + ); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed set current CH2 indoor temp"); + return; + } + + vars.slave.ch2.indoorTemp = response.get(); + + if (response.getData() != request.getData()) { + ESP_LOGW( + L_OT_HEATING, responseMismatchMessage, + request.getData(), response.getData() + ); + return; + } + + ESP_LOGI( + L_OT_HEATING, "Set current CH2 indoor temp: %.2f (response: %.2f)", + indoorTemp, vars.slave.ch2.indoorTemp + ); +}); + +static Task readModulationTask("Read modulation", [](void*) { + // Update modulation level + if (vars.slave.flame) { + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::RelModLevel)); + const float value = response.get(); + + if (!response.isSuccess() || value < 0) { + ESP_LOGW(L_OT, "Failed receive modulation level"); + return; + } + + vars.slave.modulation.current = value; + + float power = 0.0f; + if (settings.opentherm.maxPower > 0.1f) { + power += settings.opentherm.minPower; + + if (vars.slave.modulation.current > 0) { + power += ( + settings.opentherm.maxPower - settings.opentherm.minPower + ) / 100.0f * vars.slave.modulation.current; + } + } + vars.slave.power.current = power; + + ESP_LOGI( + L_OT, "Received modulation level: %hhu%%, power: %.2f of %.2f kW (min: %.2f kW)", + vars.slave.modulation.current, vars.slave.power.current, + settings.opentherm.maxPower, settings.opentherm.minPower + ); + + // Modulation level sensors + Sensors::setValueByType( + Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, + Sensors::ValueType::PRIMARY, true, true + ); + + // Power sensors + Sensors::setValueByType( + Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, + Sensors::ValueType::PRIMARY, true, true + ); + + } else { + vars.slave.modulation.current = 0; + vars.slave.power.current = 0.0f; + + // Modulation level sensors + Sensors::setValueByType( + Sensors::Type::OT_MODULATION_LEVEL, vars.slave.modulation.current, + Sensors::ValueType::PRIMARY, true, true + ); + + // Power sensors + Sensors::setValueByType( + Sensors::Type::OT_CURRENT_POWER, vars.slave.power.current, + Sensors::ValueType::PRIMARY, true, true + ); + } +}); + +static Task readDhwTemperatureTask("Read DHW temperature", [](void*) { + // Update DHW temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tdhw)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT_DHW, "Failed receive temp"); + return; + } + + vars.slave.dhw.currentTemp = value; + + ESP_LOGI( + L_OT_DHW, "Received temp: %.2f", + vars.slave.dhw.currentTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_TEMP, vars.slave.dhw.currentTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwTemperature2Task("Read DHW temperature 2", [](void*) { + // Update DHW temp 2 + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tdhw2)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT_DHW, "Failed receive temp 2"); + return; + } + + vars.slave.dhw.currentTemp2 = value; + + ESP_LOGI( + L_OT_DHW, "Received temp 2: %.2f", + vars.slave.dhw.currentTemp2 + ); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_TEMP2, vars.slave.dhw.currentTemp2, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwFlowTask("Read DHW flow", [](void*) { + // Update DHW flow rate + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::DHWFlowRate)); + float value = response.get(); + + if (!response.isSuccess() || value < 0) { + ESP_LOGW(L_OT_DHW, "Failed receive flow rate"); + return; + } + + // no minuscule values + // some boilers send a response of 0.06 when there is no flow + if (value < 0.1f) { + value = 0.0f; + } + + vars.slave.dhw.flowRate = value; + + ESP_LOGI( + L_OT_DHW, "Received flow rate: %.2f", + vars.slave.dhw.flowRate + ); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_FLOW_RATE, vars.slave.dhw.flowRate, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingTemperatureTask("Read heating temperature", [](void*) { + // Update heating temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tboiler)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT_HEATING, "Failed receive temp"); + return; + } + + vars.slave.heating.currentTemp = value; + + ESP_LOGI( + L_OT_HEATING, "Received temp: %.2f", + vars.slave.heating.currentTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_TEMP, vars.slave.heating.currentTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingReturnTemperatureTask("Read return temperature", [](void*) { + // Update heating return temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tret)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_HEATING, "Failed receive return temp"); + return; + } + + vars.slave.heating.returnTemp = response.get(); + + ESP_LOGI( + L_OT_HEATING, "Received return temp: %.2f", + vars.slave.heating.returnTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_RETURN_TEMP, vars.slave.heating.returnTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readCh2TemperatureTask("Read CH2 temperature", [](void*) { + // Update CH2 temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::TflowCH2)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT_CH2, "Failed receive temp"); + return; + } + + vars.slave.ch2.currentTemp = response.get(); + + ESP_LOGI( + L_OT_CH2, "Received temp: %.2f", + vars.slave.ch2.currentTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_CH2_TEMP, vars.slave.ch2.currentTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readExhaustTemperatureTask("Read exhaust temperature", [](void*) { + // Update exhaust temp + const auto response = slave.sendRequest(ESP32OT::Messages::Int16(ESP32OT::MessageID::Texhaust)); + const float value = response.getInt(); + + if (!response.isSuccess() || !isValidTemp(value, UnitSystem::METRIC, -40, 500)) { + ESP_LOGW(L_OT, "Failed receive exhaust temp"); + return; + } + + vars.slave.exhaust.temp = value; + + ESP_LOGI( + L_OT, "Received exhaust temp: %.2f", + vars.slave.exhaust.temp + ); + + Sensors::setValueByType( + Sensors::Type::OT_EXHAUST_TEMP, vars.slave.exhaust.temp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatExchangerTemperatureTask("Read heat exchanger temperature", [](void*) { + // Update heat exchanger temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::TboilerHeatExchanger)); + const float value = response.get(); + + if (!response.isSuccess() || value <= 0) { + ESP_LOGW(L_OT, "Failed receive heat exchanger temp"); + return; + } + + vars.slave.heatExchangerTemp = value; + + ESP_LOGI( + L_OT, "Received heat exchanger temp: %.2f", + vars.slave.heatExchangerTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_HEAT_EXCHANGER_TEMP, vars.slave.heatExchangerTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readOutdoorTemperatureTask("Read outdoor temperature", [](void*) { + // Update outdoor temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Toutside)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive outdoor temp"); + return; + } + + vars.slave.heating.outdoorTemp = response.get(); + + ESP_LOGI( + L_OT, "Received outdoor temp: %.2f", + vars.slave.heating.outdoorTemp + ); + + Sensors::setValueByType( + Sensors::Type::OT_OUTDOOR_TEMP, vars.slave.heating.outdoorTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readSolarStorageTemperatureTask("Read solar storage temperature", [](void*) { + // Update solar storage temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tstorage)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive solar storage temp"); + return; + } + + vars.slave.solar.storage = response.get(); + + ESP_LOGI( + L_OT, "Received solar storage temp: %.2f", + vars.slave.solar.storage + ); + + Sensors::setValueByType( + Sensors::Type::OT_SOLAR_STORAGE_TEMP, vars.slave.solar.storage, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readSolarCollectorTemperatureTask("Read solar collector temperature", [](void*) { + // Update solar collector temp + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::Tcollector)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive solar collector temp"); + return; + } + + vars.slave.solar.collector = response.get(); + + ESP_LOGI( + L_OT, "Received solar collector temp: %.2f", + vars.slave.solar.collector + ); + + Sensors::setValueByType( + Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, vars.slave.solar.collector, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readFanSpeedTask("Read fan speed", [](void*) { + // Update fan speed + const auto response = slave.sendRequest(ESP32OT::Messages::FanSpeed()); + + if (!response.isSuccess()) { + return; + } + + vars.slave.fanSpeed.setpoint = response.getSetpointHz(); + vars.slave.fanSpeed.current = response.getActualHz(); + + ESP_LOGI( + L_OT, "Received fan speed, setpoint: %hhu%%, current: %hhu%%", + vars.slave.fanSpeed.setpoint, vars.slave.fanSpeed.current + ); + + Sensors::setValueByType( + Sensors::Type::OT_FAN_SPEED_SETPOINT, vars.slave.fanSpeed.setpoint, + Sensors::ValueType::PRIMARY, true, true + ); + Sensors::setValueByType( + Sensors::Type::OT_FAN_SPEED_CURRENT, vars.slave.fanSpeed.current, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readPressureTask("Read pressure", [](void*) { + // Update pressure + const auto response = slave.sendRequest(ESP32OT::Messages::Float(ESP32OT::MessageID::CHPressure)); + const float value = response.get(); + + if (!response.isSuccess() || value < 0) { + ESP_LOGW(L_OT, "Failed receive pressure"); + return; + } + + vars.slave.pressure = value; + + ESP_LOGI( + L_OT, "Received pressure: %.2f", + vars.slave.pressure + ); + + Sensors::setValueByType( + Sensors::Type::OT_PRESSURE, vars.slave.pressure, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readExhaustCo2Task("Read exhaust CO2", [](void*) { + // Update exhaust CO2 + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CO2exhaust)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive exhaust CO2"); + return; + } + + vars.slave.exhaust.co2 = response.getUInt(); + + ESP_LOGI( + L_OT, "Received exhaust CO2: %hu ppm", + vars.slave.exhaust.co2 + ); + + Sensors::setValueByType( + Sensors::Type::OT_EXHAUST_CO2, vars.slave.exhaust.co2, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readExhaustFanSpeedTask("Read exhaust fan speed", [](void*) { + // Update exhaust fan speed + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::RPMexhaust)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive exhaust fan speed"); + return; + } + + vars.slave.exhaust.fanSpeed = response.getUInt(); + + ESP_LOGI( + L_OT, "Received exhaust fan speed: %hu rpm", + vars.slave.exhaust.fanSpeed + ); + + Sensors::setValueByType( + Sensors::Type::OT_EXHAUST_FAN_SPEED, vars.slave.exhaust.fanSpeed, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readSupplyFanSpeedTask("Read supply fan speed", [](void*) { + // Update supply fan speed + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::RPMsupply)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive supply fan speed"); + return; + } + + vars.slave.fanSpeed.supply = response.getUInt(); + + ESP_LOGI( + L_OT, "Received supply fan speed: %hu rpm", + vars.slave.fanSpeed.supply + ); + + Sensors::setValueByType( + Sensors::Type::OT_SUPPLY_FAN_SPEED, vars.slave.fanSpeed.supply, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task writeYearTask("Write year", [](void*) { + struct tm boilerTime; + if (getLocalTime(&boilerTime, 0)) { + const ESP32OT::Messages::UInt16 request(ESP32OT::MessageID::Year, (boilerTime.tm_year + 1900) & 0xFFFF); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGI(L_OT, "Failed set year of date"); + return; + } + + ESP_LOGI(L_OT, "Year of date set successfully"); + } +}); + +static Task writeDayAndMonthTask("Write date", [](void*) { + // Other operations can run between clock writes; use the current date. + struct tm boilerTime; + if (getLocalTime(&boilerTime, 0)) { + const uint8_t month = (boilerTime.tm_mon + 1) & 0xFF; + const ESP32OT::Messages::Date request(month, boilerTime.tm_mday & 0xFF); + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGI(L_OT, "Failed set day and month of date"); + return; + } + + ESP_LOGI(L_OT, "Day and month of date set successfully"); + } +}); + +static Task writeTimeTask("Write time", [](void*) { + struct tm boilerTime; + if (getLocalTime(&boilerTime, 0)) { + const uint8_t dayOfWeek = boilerTime.tm_wday == 0 ? 7 : boilerTime.tm_wday; + const ESP32OT::Messages::DayTime request(dayOfWeek, boilerTime.tm_hour, boilerTime.tm_min & 0x3F); + + const auto response = slave.sendRequest(request); + + if (!response.isSuccess() || response.getData() != request.getData()) { + ESP_LOGI(L_OT, "Failed set time"); + return; + } + + ESP_LOGI(L_OT, "Time set successfully"); + } +}); + +static Task readPowerLimitsTask("Read power limits", [](void*) { + // Get min modulation level & max power + const auto response = slave.sendRequest(ESP32OT::Messages::Capacity()); + + if (!response.isSuccess() || response.getMinModulation() > 100) { + ESP_LOGW(L_OT, "Failed receive min modulation and max power"); + return; + } + + vars.slave.modulation.min = response.getMinModulation(); + vars.slave.power.max = response.getMaxCapacity(); + vars.slave.power.min = vars.slave.modulation.min > 0 && vars.slave.power.max > 0.1f + ? (vars.slave.modulation.min * 0.01f) * vars.slave.power.max + : 0.0f; + + ESP_LOGI( + L_OT, "Received min modulation: %hhu%%, max power: %.2f kW", + vars.slave.modulation.min, vars.slave.power.max + ); + + if (settings.heating.maxModulation < vars.slave.modulation.min) { + settings.heating.maxModulation = vars.slave.modulation.min; + requestSaveSettings(); + + ESP_LOGW( + L_SETTINGS_HEATING, "Updated min modulation: %hhu%%", + settings.heating.maxModulation + ); + } + + if (settings.dhw.maxModulation < vars.slave.modulation.min) { + settings.dhw.maxModulation = vars.slave.modulation.min; + requestSaveSettings(); + + ESP_LOGW( + L_SETTINGS_DHW, "Updated min modulation: %hhu%%", + settings.dhw.maxModulation + ); + } + + if (fabsf(settings.opentherm.maxPower) < 0.1f && vars.slave.power.max > 0.1f) { + settings.opentherm.maxPower = vars.slave.power.max; + settings.opentherm.minPower = vars.slave.power.min; + + requestSaveSettings(); + ESP_LOGW( + L_SETTINGS_OT, "Updated power, min: %.2f kW, max: %.2f kW", + settings.opentherm.minPower, settings.opentherm.maxPower + ); + } +}); + +static Task readDhwLimitsTask("Read DHW limits", [](void*) { + // Get DHW min/max temp (if necessary) + if (settings.opentherm.options.dhwSupport && settings.opentherm.options.getMinMaxTemp) { + const auto response = slave.sendRequest( + ESP32OT::Messages::TemperatureBounds(ESP32OT::MessageID::TdhwSetUBTdhwSetLB) + ); + int8_t minTemp = response.getLower(); + int8_t maxTemp = response.getUpper(); + + if (response.isSuccess() && minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { + vars.slave.dhw.minTemp = minTemp; + vars.slave.dhw.maxTemp = maxTemp; + + float convertedMinTemp = ceilf(vars.slave.dhw.minTemp); + float convertedMaxTemp = floorf(vars.slave.dhw.maxTemp); + + convertedMinTemp = constrain(convertedMinTemp, 0.0f, 255.0f); + convertedMaxTemp = constrain(convertedMaxTemp, 0.0f, 255.0f); + + // Integer settings need two distinct limits within their storage range. + if (convertedMinTemp >= convertedMaxTemp) { + ESP_LOGW(L_OT_DHW, unrepresentableTemperatureLimitsMessage); + return; + } + + ESP_LOGI( + L_OT_DHW, "Received min temp: %hhu (converted: %.0f), max temp: %hhu (converted: %.0f)", + vars.slave.dhw.minTemp, convertedMinTemp, vars.slave.dhw.maxTemp, convertedMaxTemp + ); + + if (settings.dhw.minTemp < convertedMinTemp) { + settings.dhw.minTemp = static_cast(convertedMinTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_DHW, "Updated min temp: %hhu", settings.dhw.minTemp); + } + + if (settings.dhw.maxTemp > convertedMaxTemp) { + settings.dhw.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_DHW, "Updated max temp: %hhu", settings.dhw.maxTemp); + } + + if (settings.dhw.minTemp >= settings.dhw.maxTemp) { + settings.dhw.minTemp = static_cast(convertedMinTemp); + settings.dhw.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_DHW, "Updated min temp: %hhu, max temp: %hhu", settings.dhw.minTemp, settings.dhw.maxTemp); + } + + } else { + ESP_LOGW(L_OT_DHW, "Failed receive min/max temp"); + } + } + + if (settings.dhw.minTemp >= settings.dhw.maxTemp) { + settings.dhw.minTemp = DEFAULT_DHW_MIN_TEMP; + settings.dhw.maxTemp = DEFAULT_DHW_MAX_TEMP; + requestSaveSettings(); + } +}); + +static Task readHeatingLimitsTask("Read heating limits", [](void*) { + // Get heating min/max temp + if (settings.opentherm.options.getMinMaxTemp) { + const auto response = slave.sendRequest( + ESP32OT::Messages::TemperatureBounds(ESP32OT::MessageID::MaxTSetUBMaxTSetLB) + ); + int8_t minTemp = response.getLower(); + int8_t maxTemp = response.getUpper(); + + if (response.isSuccess() && minTemp >= 0 && maxTemp > 0 && maxTemp > minTemp) { + vars.slave.heating.minTemp = minTemp; + vars.slave.heating.maxTemp = maxTemp; + + float convertedMinTemp = ceilf(vars.slave.heating.minTemp); + float convertedMaxTemp = floorf(vars.slave.heating.maxTemp); + + convertedMinTemp = constrain(convertedMinTemp, 0.0f, 255.0f); + convertedMaxTemp = constrain(convertedMaxTemp, 0.0f, 255.0f); + + // Integer settings need two distinct limits within their storage range. + if (convertedMinTemp >= convertedMaxTemp) { + ESP_LOGW(L_OT_HEATING, unrepresentableTemperatureLimitsMessage); + return; + } + + ESP_LOGI( + L_OT_HEATING, "Received min temp: %hhu (converted: %.0f), max temp: %hhu (converted: %.0f)", + vars.slave.heating.minTemp, convertedMinTemp, vars.slave.heating.maxTemp, convertedMaxTemp + ); + + if (settings.heating.minTemp < convertedMinTemp) { + settings.heating.minTemp = static_cast(convertedMinTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_HEATING, "Updated min temp: %hhu", settings.heating.minTemp); + } + + if (settings.heating.maxTemp > convertedMaxTemp) { + settings.heating.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_HEATING, "Updated max temp: %hhu", settings.heating.maxTemp); + } + + if (settings.heating.minTemp >= settings.heating.maxTemp) { + settings.heating.minTemp = static_cast(convertedMinTemp); + settings.heating.maxTemp = static_cast(convertedMaxTemp); + requestSaveSettings(); + + ESP_LOGW(L_SETTINGS_HEATING, "Updated min temp: %hhu, max temp: %hhu", settings.heating.minTemp, settings.heating.maxTemp); + } + + } else { + ESP_LOGW(L_OT_HEATING, "Failed receive min/max temp"); + } + } + + if (settings.heating.minTemp >= settings.heating.maxTemp) { + settings.heating.minTemp = DEFAULT_HEATING_MIN_TEMP; + settings.heating.maxTemp = DEFAULT_HEATING_MAX_TEMP; + requestSaveSettings(); + } +}); + +static Task readFaultTask("Read fault code", [](void*) { + // Get fault code + const auto response = slave.sendRequest(ESP32OT::Messages::Fault()); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive fault code"); + return; + } + + vars.slave.fault.code = response.getOemFaultCode(); + + ESP_LOGI( + L_OT, "Received fault code: %hhu (0x%02X)", + vars.slave.fault.code, vars.slave.fault.code + ); +}); + +static Task readDiagnosticTask("Read diagnostic code", [](void*) { + // Get diagnostic code + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::OEMDiagnosticCode)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive diag code"); + return; + } + + vars.slave.diag.code = response.getUInt(); + + ESP_LOGI( + L_OT, "Received diag code: %hu (0x%02X)", + vars.slave.diag.code, vars.slave.diag.code + ); +}); + +static Task readBurnerStartsTask("Read burner starts", [](void*) { + // Update burner starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::SuccessfulBurnerStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive burner starts"); + return; + } + + vars.slave.stats.burnerStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received burner starts: %hu", vars.slave.stats.burnerStarts); + + Sensors::setValueByType( + Sensors::Type::OT_BURNER_STARTS, vars.slave.stats.burnerStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwBurnerStartsTask("Read DHW burner starts", [](void*) { + // Update DHW burner starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWBurnerStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW burner starts"); + return; + } + + vars.slave.stats.dhwBurnerStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW burner starts: %hu", vars.slave.stats.dhwBurnerStarts); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_BURNER_STARTS, vars.slave.stats.dhwBurnerStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingPumpStartsTask("Read heating pump starts", [](void*) { + // Update heating pump starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CHPumpStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive heating pump starts"); + return; + } + + vars.slave.stats.heatingPumpStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received heating pump starts: %hu", vars.slave.stats.heatingPumpStarts); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_PUMP_STARTS, vars.slave.stats.heatingPumpStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwPumpStartsTask("Read DHW pump starts", [](void*) { + // Update DHW pump starts + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWPumpValveStarts)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW pump starts"); + return; + } + + vars.slave.stats.dhwPumpStarts = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW pump starts: %hu", vars.slave.stats.dhwPumpStarts); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_PUMP_STARTS, vars.slave.stats.dhwPumpStarts, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readBurnerHoursTask("Read burner hours", [](void*) { + // Update burner hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::BurnerOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive burner hours"); + return; + } + + vars.slave.stats.burnerHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received burner hours: %hu", vars.slave.stats.burnerHours); + + Sensors::setValueByType( + Sensors::Type::OT_BURNER_HOURS, vars.slave.stats.burnerHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwBurnerHoursTask("Read DHW burner hours", [](void*) { + // Update DHW burner hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWBurnerOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW burner hours"); + return; + } + + vars.slave.stats.dhwBurnerHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW burner hours: %hu", vars.slave.stats.dhwBurnerHours); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_BURNER_HOURS, vars.slave.stats.dhwBurnerHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readHeatingPumpHoursTask("Read heating pump hours", [](void*) { + // Update heating pump hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CHPumpOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive heating pump hours"); + return; + } + + vars.slave.stats.heatingPumpHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received heating pump hours: %hu", vars.slave.stats.heatingPumpHours); + + Sensors::setValueByType( + Sensors::Type::OT_HEATING_PUMP_HOURS, vars.slave.stats.heatingPumpHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readDhwPumpHoursTask("Read DHW pump hours", [](void*) { + // Update DHW pump hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::DHWPumpValveOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive DHW pump hours"); + return; + } + + vars.slave.stats.dhwPumpHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received DHW pump hours: %hu", vars.slave.stats.dhwPumpHours); + + Sensors::setValueByType( + Sensors::Type::OT_DHW_PUMP_HOURS, vars.slave.stats.dhwPumpHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +static Task readCoolingHoursTask("Read cooling hours", [](void*) { + // Update cooling hours + const auto response = slave.sendRequest(ESP32OT::Messages::UInt16(ESP32OT::MessageID::CoolingOperationHours)); + + if (!response.isSuccess()) { + ESP_LOGW(L_OT, "Failed receive cooling hours"); + return; + } + + vars.slave.stats.coolingHours = response.getUInt(); + + ESP_LOGI(L_OT, "Received cooling hours: %hu", vars.slave.stats.coolingHours); + + Sensors::setValueByType( + Sensors::Type::OT_COOLING_HOURS, vars.slave.stats.coolingHours, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +// Status may force this task while running its own onDone. +static void onOperationDone(const Task&, uint32_t) { + if (readStatusTask.idle()) { + readStatusTask.tryRun(); + } + + if (esp_log_level_get(L_OT) >= ESP_LOG_VERBOSE) { + static uint32_t lastManagerStack = UINT32_MAX; + static uint32_t lastWorkerStack = UINT32_MAX; + const uint32_t managerStack = uxTaskGetStackHighWaterMark(nullptr); + const uint32_t workerStack = slave.getWorkerStackHighWaterMark(); + if (workerStack > 0 && (managerStack < lastManagerStack || workerStack < lastWorkerStack)) { + ESP_LOGV( + L_OT, "Stack free: manager %lu, RMT worker %lu bytes", + static_cast(managerStack), static_cast(workerStack) + ); + lastManagerStack = managerStack; + lastWorkerStack = workerStack; + } + } +} + +void initOpenTherm() { + // Configure OpenTherm before polling the boiler. + configureDriverTask.setEnabledWhen([] { + return !restartTask.scheduled(); + }).resume(); + openthermTaskManager.addTask(configureDriverTask); + + // Reconfigure GPIO and track initialization requirements. + maintainOpenThermTask.setEnabledWhen([] { + return !restartTask.scheduled(); + }); + openthermTaskManager.addTask(maintainOpenThermTask); + + // Exchange boiler status and monitor the connection. + readStatusTask.setInterval(750) + .setEnabledWhen(canUseBus) + .onDone([](const Task&, uint32_t) { + // Both tasks can reach each other's onDone; never re-enter an active task. + if (vars.slave.flame || vars.slave.modulation.current > 0) { + if (readModulationTask.idle() && readModulationTask.enabled()) { + readModulationTask.forceRun(); + } + } + }); + openthermTaskManager.addTask(readStatusTask); + + // Identify the slave before enabling ordinary operations. + initializeSlaveTask.setEnabledWhen([] { + return canUseBus() && vars.slave.connected; + }); + openthermTaskManager.addTask(initializeSlaveTask); + + // Read the boiler application version. + readSlaveVersionTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSlaveVersionTask); + + // Write the master application version. + writeMasterVersionTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMasterVersionTask); + + // Read the boiler OpenTherm version. + readSlaveProtocolTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSlaveProtocolTask); + + // Write the master OpenTherm version. + writeMasterProtocolTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMasterProtocolTask); + + // Read the boiler configuration. + readSlaveConfigTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSlaveConfigTask); + + // Write the master configuration. + writeMasterConfigTask.setEnabledWhen(isInitializingSlave) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMasterConfigTask); + + // Write the heating water setpoint and optional maximum temperature. + writeHeatingSetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && needWriteHeatingSetpoint(getHeatingChannelSetpoint()); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeHeatingSetpointTask); + + // Write the DHW temperature setpoint. + writeDhwSetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() + && settings.opentherm.options.dhwSupport + && needWriteDhwSetpoint(getDhwChannelSetpoint()); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeDhwSetpointTask); + + // Write the CH2 water temperature setpoint. + writeCh2SetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() + && (settings.opentherm.options.heatingToCh2 || settings.opentherm.options.dhwToCh2 + || (!vars.master.ch2.enabled && settings.opentherm.ch2DisablingAction != ChannelDisablingAction::OFF)) + && needWriteCh2Setpoint(getCh2ChannelSetpoint()); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeCh2SetpointTask); + + // Write the heating room setpoint for native OTC. + writeRoomSetpointTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() + && settings.opentherm.options.nativeOTC + && needWriteRoomSetpoint(vars.master.heating.targetTemp); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeRoomSetpointTask); + + // Write the mirrored CH2 room setpoint for native OTC. + writeRoomSetpointCh2Task.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() + && settings.opentherm.options.nativeOTC && settings.opentherm.options.heatingToCh2 + && needWriteRoomSetpointCh2(vars.master.heating.targetTemp); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeRoomSetpointCh2Task); + + // Write the maximum relative modulation level. + writeMaxModulationTask.setInterval(5000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeMaxModulationTask); + + // Write the cooling control signal. + writeCoolingSetpointTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.coolingSupport; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeCoolingSetpointTask); + + // Execute pending boiler fault reset requests. + writeFaultResetTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && vars.slave.fault.active && ( + vars.actions.resetFault || settings.opentherm.options.autoFaultReset + ); + }) + .onDone([](const Task& task, uint32_t elapsed) { + vars.actions.resetFault = false; + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeFaultResetTask); + + // Execute pending service reset requests. + writeDiagnosticResetTask.setInterval(750) + .setEnabledWhen([] { + return isSlaveReady() && vars.slave.diag.active && ( + vars.actions.resetDiagnostic || settings.opentherm.options.autoDiagReset + ); + }) + .onDone([](const Task& task, uint32_t elapsed) { + vars.actions.resetDiagnostic = false; + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeDiagnosticResetTask); + + // Send the current indoor temperature. + writeRoomTemperatureTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && ( + settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp + ); + }) + .onDone([](const Task& task, uint32_t elapsed) { + writeRoomTemperatureTask.setInterval(60000); + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeRoomTemperatureTask); + + // Send the current indoor temperature to CH2. + writeRoomTemperatureCh2Task.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && ( + settings.opentherm.options.nativeOTC || settings.opentherm.options.alwaysSendIndoorTemp + ) && settings.opentherm.options.heatingToCh2; + }) + .onDone([](const Task& task, uint32_t elapsed) { + writeRoomTemperatureCh2Task.setInterval(60000); + onOperationDone(task, elapsed); + }); + openthermTaskManager.addTask(writeRoomTemperatureCh2Task); + + // Read relative modulation and calculate current power. + readModulationTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && ( + Sensors::getAmountByType(Sensors::Type::OT_MODULATION_LEVEL, true) || + Sensors::getAmountByType(Sensors::Type::OT_CURRENT_POWER, true) + ); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readModulationTask); + + // Read the primary DHW temperature. + readDhwTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() + && settings.opentherm.options.dhwSupport + && Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwTemperatureTask); + + // Read the second DHW temperature. + readDhwTemperature2Task.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() + && settings.opentherm.options.dhwSupport + && Sensors::getAmountByType(Sensors::Type::OT_DHW_TEMP2, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwTemperature2Task); + + // Read the DHW flow rate. + readDhwFlowTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() + && settings.opentherm.options.dhwSupport + && Sensors::getAmountByType(Sensors::Type::OT_DHW_FLOW_RATE, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwFlowTask); + + // Read the heating supply temperature. + readHeatingTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingTemperatureTask); + + // Read the heating return temperature. + readHeatingReturnTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_RETURN_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingReturnTemperatureTask); + + // Read the CH2 water temperature. + readCh2TemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() + && Sensors::getAmountByType(Sensors::Type::OT_CH2_TEMP, true) + && vars.master.ch2.enabled && !settings.opentherm.options.nativeOTC; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readCh2TemperatureTask); + + // Read the exhaust temperature. + readExhaustTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readExhaustTemperatureTask); + + // Read the boiler heat exchanger temperature. + readHeatExchangerTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEAT_EXCHANGER_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatExchangerTemperatureTask); + + // Read the outdoor temperature. + readOutdoorTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_OUTDOOR_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readOutdoorTemperatureTask); + + // Read the solar storage temperature. + readSolarStorageTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_SOLAR_STORAGE_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSolarStorageTemperatureTask); + + // Read the solar collector temperature. + readSolarCollectorTemperatureTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSolarCollectorTemperatureTask); + + // Read the requested and actual relative fan speeds. + readFanSpeedTask.setInterval(5000) + .setEnabledWhen([] { + return isSlaveReady() && ( + Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_SETPOINT, true) || + Sensors::getAmountByType(Sensors::Type::OT_FAN_SPEED_CURRENT, true) + ); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readFanSpeedTask); + + // Read the heating circuit pressure. + readPressureTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_PRESSURE, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readPressureTask); + + // Read the exhaust CO2 concentration. + readExhaustCo2Task.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_CO2, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readExhaustCo2Task); + + // Read the exhaust fan speed. + readExhaustFanSpeedTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_EXHAUST_FAN_SPEED, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readExhaustFanSpeedTask); + + // Read the supply fan speed. + readSupplyFanSpeedTask.setInterval(15000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_SUPPLY_FAN_SPEED, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readSupplyFanSpeedTask); + + // Write the current year. + writeYearTask.setInterval(600000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.setDateAndTime; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeYearTask); + + // Write the current day and month. + writeDayAndMonthTask.setInterval(600000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.setDateAndTime; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeDayAndMonthTask); + + // Write the current weekday and time. + writeTimeTask.setInterval(600000) + .setEnabledWhen([] { + return isSlaveReady() && settings.opentherm.options.setDateAndTime; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(writeTimeTask); + + // Read minimum modulation and boiler power limits. + readPowerLimitsTask.setInterval(60000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(readPowerLimitsTask); + + // Read and apply DHW temperature limits. + readDhwLimitsTask.setInterval(60000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwLimitsTask); + + // Read and apply heating temperature limits. + readHeatingLimitsTask.setInterval(60000) + .setEnabledWhen(isSlaveReady) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingLimitsTask); + + // Read or clear the boiler fault code. + readFaultTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && vars.slave.fault.active; + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readFaultTask); + + // Read or clear the diagnostic code. + readDiagnosticTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && ( + vars.slave.diag.active || vars.slave.fault.active + ); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDiagnosticTask); + + // Read the burner start counter. + readBurnerStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_BURNER_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readBurnerStartsTask); + + // Read the DHW burner start counter. + readDhwBurnerStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwBurnerStartsTask); + + // Read the heating pump start counter. + readHeatingPumpStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingPumpStartsTask); + + // Read the DHW pump start counter. + readDhwPumpStartsTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_STARTS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwPumpStartsTask); + + // Read accumulated burner operating hours. + readBurnerHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_BURNER_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readBurnerHoursTask); + + // Read accumulated DHW burner operating hours. + readDhwBurnerHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_BURNER_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwBurnerHoursTask); + + // Read accumulated heating pump operating hours. + readHeatingPumpHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_HEATING_PUMP_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readHeatingPumpHoursTask); + + // Read accumulated DHW pump operating hours. + readDhwPumpHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_DHW_PUMP_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readDhwPumpHoursTask); + + // Read accumulated cooling operating hours. + readCoolingHoursTask.setInterval(60000) + .setEnabledWhen([] { + return isSlaveReady() && Sensors::getAmountByType(Sensors::Type::OT_COOLING_HOURS, true); + }) + .onDone(onOperationDone); + openthermTaskManager.addTask(readCoolingHoursTask); +} diff --git a/src/portal.cpp b/src/portal.cpp new file mode 100644 index 0000000..7bfa838 --- /dev/null +++ b/src/portal.cpp @@ -0,0 +1,985 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include +//#define PORTAL_CACHE "max-age=86400" +#define PORTAL_CACHE nullptr + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +WebSerial* webSerial = nullptr; + +AsyncWebServer* webServer = nullptr; + +enum class RequestInterface : uint8_t { + UNKNOWN, + AP, + STA, + ETH +}; + +static RequestInterface getRequestInterface(AsyncWebServerRequest* request) { + if (request == nullptr || request->client() == nullptr) { + return RequestInterface::UNKNOWN; + } + + // Classify the connection by its destination address. + const IPAddress localIP = request->client()->localIP(); + if (localIP == IPAddress(0, 0, 0, 0)) { + return RequestInterface::UNKNOWN; + } + + const IPAddress apIP = WiFi.AP.localIP(); + const IPAddress staIP = WiFi.STA.localIP(); + if (localIP == apIP && localIP == staIP) { + // Matching AP/STA addresses cannot identify the interface. + return RequestInterface::UNKNOWN; + } + + if (localIP == apIP) { + return RequestInterface::AP; + } + + if (localIP == staIP) { + return RequestInterface::STA; + } + + return RequestInterface::UNKNOWN; +} + +static void onCaptivePortal(AsyncWebServerRequest *request) { + const auto& url = request->url(); + + if (url.equals("/connecttest.txt")) { + request->redirect("http://logout.net", 302); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Redirect to http://logout.net with 302 code"); + + } else if (url.equals("/wpad.dat")) { + request->send(404); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Send empty page with 404 code"); + + } else if (url.equals("/success.txt")) { + request->send(200); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Send empty page with 200 code"); + + } else { + std::string portalUrl; + portalUrl.reserve(7 + 15 + 1); + portalUrl = "http://"; + portalUrl += WiFi.AP.localIP().toString().c_str(); + portalUrl += '/'; + + request->redirect(portalUrl.c_str(), 302); + + ESP_LOGD(L_PORTAL_CAPTIVE, "Redirect to portal page with 302 code"); + } +} + +static bool isAuthenticationRequired(AsyncWebServerRequest* request) { + if (isNetworkInterfaceStarted(NetworkMode::AP) && getRequestInterface(request) == RequestInterface::AP) { + return false; + } + + return settings.portal.auth && strlen(settings.portal.password); +} + +static void setDownloadFilename(AsyncWebServerResponse* response, const char* type, const char* extension) { + const time_t now = time(nullptr); + + tm localNow {}; + localtime_r(&now, &localNow); + + char localNowValue[20]; + strftime(localNowValue, sizeof(localNowValue), "%Y-%m-%d-%H-%M-%S", &localNow); + + char contentDisposition[96]; + snprintf( + contentDisposition, sizeof(contentDisposition), + "attachment; filename=\"%s_%s_%s.%s\"", + networkSettings.hostname, localNowValue, type, extension + ); + response->addHeader("Content-Disposition", contentDisposition); +} + +// auth middleware +static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + if (!isAuthenticationRequired(request)) { + return next(); + } + + if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return next(); + } + + return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); +}); + +static void initWebSerial() { + // Register before System starts. Unbuffered WebSerial preserves newlines inside each record. + webSerial = new WebSerial(); + webSerial->begin(webServer, nullptr, "/webserial"); + + webServer->addMiddleware([](AsyncWebServerRequest* request, ArMiddlewareNext next) { + if (request->url().equals("/webserial")) { + if (!settings.system.webSerial.enabled) { + request->send(404); + return; + } + + // Refresh credentials before each handshake, including after re-enabling. + if (isAuthenticationRequired(request)) { + webSerial->setAuthentication(settings.portal.login, settings.portal.password); + } else { + webSerial->setAuthentication("", ""); + } + } + next(); + }); +} + +static void routes() { + // index page + webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->redirect("/index.html"); + }); + webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE); + + // dashboard page + webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // network settings page + webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // settings page + webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // sensors page + webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // upgrade page + webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // logs page + webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE) + .addMiddleware(&authMiddleware); + + // not found + webServer->onNotFound([](AsyncWebServerRequest *request) { + const auto& url = request->url(); + ESP_LOGD(L_PORTAL_WEBSERVER, "Page not found, uri: %s", url.c_str()); + + if (url.equals("/index.html")) { + request->send(200, "text/plain", "The file system is not flashed!"); + + } else if (getNetworkState(NetworkMode::AP) == NetworkState::PORTAL_STARTED && getRequestInterface(request) == RequestInterface::AP) { + onCaptivePortal(request); + + } else { + request->send(404, "text/plain", "Page not found"); + } + }); + + webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE); + webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE); + webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE); +} + +static void restApi() { + // OTA + auto upgradeHandler = (new UpgradeHandler("/api/upgrade")) + ->setBeforeUpgradeCallback([](AsyncWebServerRequest *request, UpgradeHandler::UpgradeType type) -> bool { + // Upload callbacks run before middleware; reject before pausing tasks or writing. + if (isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return false; + } + + if (restartTask.scheduled() || restartTask.active()) { + return false; + } + // UpgradeHandler invokes this callback for every upload chunk. + if (vars.states.upgrading) { + return true; + } + + vars.states.upgrading = true; + coreTaskManager.pause(); + // Core owns MQTT; finish its current callback before stopping the client. + if (!coreTaskManager.waitForPaused(5000)) { + vars.states.upgrading = false; + if (!restartTask.scheduled() && !restartTask.active()) { + coreTaskManager.resume(); + } + ESP_LOGW(L_PORTAL_OTA, "Core task manager pause not confirmed, upgrade cancelled"); + return false; + } + + stopMqtt(false); + + // An MQTT command already in flight may have scheduled a restart before end(). + if (restartTask.scheduled() || restartTask.active()) { + vars.states.upgrading = false; + return false; + } + + sensorsTaskManager.pause(); + if (!sensorsTaskManager.waitForPaused(5000)) { + requestReconfigureMqtt(); + vars.states.upgrading = false; + if (!restartTask.scheduled() && !restartTask.active()) { + coreTaskManager.resume(); + sensorsTaskManager.resume(); + } + ESP_LOGW(L_PORTAL_OTA, "Sensors task manager pause not confirmed, upgrade cancelled"); + return false; + } + + openthermTaskManager.pause(); + if (!openthermTaskManager.waitForPaused(5000)) { + requestReconfigureMqtt(); + vars.states.upgrading = false; + if (!restartTask.scheduled() && !restartTask.active()) { + coreTaskManager.resume(); + sensorsTaskManager.resume(); + openthermTaskManager.resume(); + } + ESP_LOGW(L_PORTAL_OTA, "OpenTherm task manager pause not confirmed, upgrade cancelled"); + return false; + } + + return true; + })->setAfterUpgradeCallback([](AsyncWebServerRequest *request, const UpgradeHandler::UpgradeResult& fwResult, const UpgradeHandler::UpgradeResult& fsResult) { + if (request && isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); + } + + unsigned short status = 406; + if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) { + status = 202; + if (!restartTask.scheduled() && !restartTask.active()) { + restartTask.resume(15000); + } + + } else { + requestReconfigureMqtt(); + } + + vars.states.upgrading = false; + if (status != 202 && !restartTask.scheduled() && !restartTask.active()) { + coreTaskManager.resume(); + sensorsTaskManager.resume(); + openthermTaskManager.resume(); + } + + if (!request) { + return; + } + + // make response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + auto fwDoc = doc["firmware"].to(); + fwDoc["status"] = static_cast(fwResult.status); + fwDoc["error"] = fwResult.error; + + auto fsDoc = doc["filesystem"].to(); + fsDoc["status"] = static_cast(fsResult.status); + fsDoc["error"] = fsResult.error; + + // send response + response->setLength(); + response->setCode(status); + request->send(response); + }); + upgradeHandler->addMiddleware(&authMiddleware); + webServer->addHandler(upgradeHandler); + + + // backup + webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) { + // make response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + // add network settings + auto networkDoc = doc[S_NETWORK].to(); + toJson(networkSettings, networkDoc); + + // add main settings + auto settingsDoc = doc[S_SETTINGS].to(); + toJson(settings.system, settingsDoc[S_SYSTEM].to()); + toJson(settings.portal, settingsDoc[S_PORTAL].to()); + toJson(settings.opentherm, settingsDoc[S_OPENTHERM].to()); + toJson(settings.mqtt, settingsDoc[S_MQTT].to()); + toJson(settings.emergency, settingsDoc[S_EMERGENCY].to()); + toJson(settings.heating, settingsDoc[S_HEATING].to()); + toJson(settings.dhw, settingsDoc[S_DHW].to()); + toJson(settings.equitherm, settingsDoc[S_EQUITHERM].to()); + toJson(settings.pid, settingsDoc[S_PID].to()); + toJson(settings.externalPump, settingsDoc[S_EXTERNAL_PUMP].to()); + toJson(settings.cascadeControl, settingsDoc[S_CASCADE_CONTROL].to()); + + // add sensors settings + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + if (const auto sensor = Sensors::getSettings(sensorId)) { + auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to(); + toJson(sensorId, *sensor, sensorsettingsDoc); + } + } + + // send response + setDownloadFilename(response, "backup", "json"); + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + // restart + webServer->on("/api/restart", HTTP_POST, [](AsyncWebServerRequest *request) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + restartTask.resume(15000); + request->send(202); + }).addMiddleware(&authMiddleware); + + // network + webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) { + // make response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(networkSettings, doc); + + // send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + auto& nsHandler = webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + if (requestDoc.isNull() || !requestDoc.size()) { + return request->send(400); + } + + // prepare request + const auto result = fromJson(requestDoc, networkSettings); + if (result.changed) { + requestSaveNetworkSettings(); + } + requestDoc.clear(); + + if (request->hasParam("noresponse")) { + request->send(result.changed ? 201 : 200); + + } else { + // make response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(networkSettings, responseDoc); + + // send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + } + + if (result.changed && !request->hasParam("noreconnect")) { + // Queue the response before a network reset can disconnect this request. + reconnectNetwork(); + } + }); + nsHandler.setMaxContentLength(512); + nsHandler.addMiddleware(&authMiddleware); + + webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) { + auto apCount = WiFi.scanComplete(); + + switch (apCount) { + case WIFI_SCAN_FAILED: + WiFi.scanNetworks(true, true, true); + request->send(404); + break; + + case WIFI_SCAN_RUNNING: + request->send(202); + break; + + default: + // make respponse + auto *response = new AsyncJsonResponse(true); + auto& doc = response->getRoot(); + for (short int i = 0; i < apCount; i++) { + doc[i][S_SSID] = WiFi.SSID(i); + doc[i][S_BSSID] = WiFi.BSSIDstr(i); + doc[i][S_SIGNAL_QUALITY] = rssiToSignalQuality(WiFi.RSSI(i)); + doc[i][S_CHANNEL] = WiFi.channel(i); + doc[i][S_HIDDEN] = !WiFi.SSID(i).length(); + doc[i][S_AUTH] = WiFi.encryptionType(i); + } + + // send response + response->setLength(); + request->send(response); + + // clear + WiFi.scanDelete(); + } + }).addMiddleware(&authMiddleware); + + + // settings + webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_GET, [](AsyncWebServerRequest *request) { + const auto& url = request->url(); + const auto section = std::string_view(url.c_str(), url.length()) + .substr(sizeof("/api/settings/") - 1); + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + if (section == S_SYSTEM) { + toJson(settings.system, doc); + + } else if (section == S_PORTAL) { + toJson(settings.portal, doc); + + } else if (section == S_OPENTHERM) { + toJson(settings.opentherm, doc); + + } else if (section == S_MQTT) { + toJson(settings.mqtt, doc); + + } else if (section == S_EMERGENCY) { + toJson(settings.emergency, doc); + + } else if (section == S_HEATING) { + toJson(settings.heating, doc); + + } else if (section == S_DHW) { + toJson(settings.dhw, doc); + + } else if (section == S_PID) { + toJson(settings.pid, doc); + + } else if (section == S_EQUITHERM) { + toJson(settings.equitherm, doc); + + } else if (section == S_EXTERNAL_PUMP) { + toJson(settings.externalPump, doc); + + } else if (section == S_CASCADE_CONTROL) { + toJson(settings.cascadeControl, doc); + + } else { + delete response; + return request->send(404); + } + + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + auto& settingsHandler = webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + request->send(503); + return; + } + + if (!requestDoc.is() || !requestDoc.size()) { + request->send(400); + return; + } + + const auto& url = request->url(); + const auto section = std::string_view(url.c_str(), url.length()) + .substr(sizeof("/api/settings/") - 1); + SettingResult result; + bool mqttChanged = false; + + if (section == S_SYSTEM) { + result = fromJson(requestDoc, settings.system); + + } else if (section == S_PORTAL) { + result = fromJson(requestDoc, settings.portal); + + } else if (section == S_OPENTHERM) { + result = fromJson(requestDoc, settings.opentherm); + + } else if (section == S_MQTT) { + const auto previousMqtt = settings.mqtt; + result = fromJson(requestDoc, settings.mqtt); + mqttChanged = previousMqtt.enabled != settings.mqtt.enabled + || previousMqtt.port != settings.mqtt.port + || previousMqtt.interval != settings.mqtt.interval + || strcmp(previousMqtt.server, settings.mqtt.server) != 0 + || strcmp(previousMqtt.user, settings.mqtt.user) != 0 + || strcmp(previousMqtt.password, settings.mqtt.password) != 0 + || strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0; + + } else if (section == S_EMERGENCY) { + result = fromJson(requestDoc, settings.emergency); + + } else if (section == S_HEATING) { + result = fromJson(requestDoc, settings.heating); + + } else if (section == S_DHW) { + result = fromJson(requestDoc, settings.dhw); + + } else if (section == S_PID) { + result = fromJson(requestDoc, settings.pid); + + } else if (section == S_EQUITHERM) { + result = fromJson(requestDoc, settings.equitherm); + + } else if (section == S_EXTERNAL_PUMP) { + result = fromJson(requestDoc, settings.externalPump); + + } else if (section == S_CASCADE_CONTROL) { + result = fromJson(requestDoc, settings.cascadeControl); + + } else { + return request->send(404); + } + + result.changed = normalizeSettings(settings) || result.changed; + if (result.changed) { + requestSaveSettings(); + configureLoggingTask.resume(); + if (mqttChanged) { + requestReconfigureMqtt(); + } + + // If busy, the periodic task will publish the current settings. + std::unique_lock lock(mqttMutex, std::try_to_lock); + if (lock.owns_lock() && mqttPublishSettingsTask) { + mqttPublishSettingsTask->requestEarlyRun(); + } + } + requestDoc.clear(); + + if (request->hasParam("noresponse")) { + return request->send(result.changed ? 201 : 200); + } + + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + + if (section == S_SYSTEM) { + toJson(settings.system, responseDoc); + + } else if (section == S_PORTAL) { + toJson(settings.portal, responseDoc); + + } else if (section == S_OPENTHERM) { + toJson(settings.opentherm, responseDoc); + + } else if (section == S_MQTT) { + toJson(settings.mqtt, responseDoc); + + } else if (section == S_EMERGENCY) { + toJson(settings.emergency, responseDoc); + + } else if (section == S_HEATING) { + toJson(settings.heating, responseDoc); + + } else if (section == S_DHW) { + toJson(settings.dhw, responseDoc); + + } else if (section == S_PID) { + toJson(settings.pid, responseDoc); + + } else if (section == S_EQUITHERM) { + toJson(settings.equitherm, responseDoc); + + } else if (section == S_EXTERNAL_PUMP) { + toJson(settings.externalPump, responseDoc); + + } else if (section == S_CASCADE_CONTROL) { + toJson(settings.cascadeControl, responseDoc); + } + + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + }); + settingsHandler.setMaxContentLength(3072); + settingsHandler.addMiddleware(&authMiddleware); + + + // sensors list + webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) { + // make response + bool detailed = request->hasParam("detailed"); + auto *response = new AsyncJsonResponse(true); + auto& responseDoc = response->getRoot(); + + // add sensors + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + if (detailed) { + if (const auto snapshot = Sensors::getSnapshot(sensorId)) { + responseDoc[sensorId][S_ENABLED] = snapshot->settings.enabled; + responseDoc[sensorId][S_NAME] = static_cast(snapshot->settings.name); + responseDoc[sensorId][S_SLUG] = static_cast(snapshot->settings.slug); + responseDoc[sensorId][S_PURPOSE] = static_cast(snapshot->settings.purpose); + toJson(snapshot->settings, snapshot->result, responseDoc[sensorId]); + } + + } else if (const auto sensor = Sensors::getSettings(sensorId)) { + responseDoc[sensorId] = static_cast(sensor->name); + } + } + + // send response + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + // sensor settings + webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_GET, [](AsyncWebServerRequest *request) { + if (!request->hasParam("id")) { + return request->send(400); + } + + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + const auto sensor = Sensors::getSettings(*sensorId); + if (!sensor) { + return request->send(404); + } + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(*sensorId, *sensor, doc); + + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + auto& ssHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + if (requestDoc.isNull() || !requestDoc.size()) { + return request->send(400); + } + + if (!request->hasParam("id")) { + return request->send(400); + } + + auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + const auto previousSettings = Sensors::getSettings(*sensorId); + if (!previousSettings) { + return request->send(404); + } + + bool isDifferent = false; + SettingResult result; + { + std::lock_guard lock(Sensors::mutex); + auto& sensor = Sensors::settings[*sensorId]; + + 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; + } + } + + if (result.changed) { + if (isDifferent) { + requestReconfigureMqttSensor(*sensorId, *previousSettings); + } + + requestSaveSensorsSettings(); + } + requestDoc.clear(); + + if (request->hasParam("noresponse")) { + return request->send(result.changed ? 201 : 200); + } + + // make response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + + if (const auto sensor = Sensors::getSettings(*sensorId)) { + toJson(*sensorId, *sensor, responseDoc); + } + + // send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + }); + ssHandler.setMaxContentLength(1024); + ssHandler.addMiddleware(&authMiddleware); + + + // sensor measurements + webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_GET, [](AsyncWebServerRequest *request) { + if (!request->hasParam("id")) { + return request->send(400); + } + + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + const auto sensor = Sensors::getSnapshot(*sensorId); + if (!sensor) { + return request->send(404); + } + + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(sensor->settings, sensor->result, doc); + response->setLength(); + request->send(response); + }).addMiddleware(&authMiddleware); + + auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + } + + if (!request->hasParam("id")) { + return request->send(400); + } + + const auto& id = request->getParam("id")->value(); + const auto sensorId = Sensors::parseId(id.c_str()); + if (!sensorId) { + return request->send(404); + } + + if (!requestDoc[S_VALUE].is()) { + return request->send(400); + } + + const auto value = requestDoc[S_VALUE].as(); + requestDoc.clear(); + if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) { + return request->send(400); + } + + requestPublishMqttSensor(*sensorId); + + if (request->hasParam("noresponse")) { + return request->send(201); + } + + const auto sensor = Sensors::getSnapshot(*sensorId); + if (!sensor) { + return request->send(404); + } + + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(sensor->settings, sensor->result, responseDoc); + response->setLength(); + response->setCode(201); + request->send(response); + }); + sensorValueHandler.setMaxContentLength(1024); + sensorValueHandler.addMiddleware(&authMiddleware); + + + // vars + webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) { + // make response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + toJson(vars, doc); + + // send response + response->setLength(); + request->send(response); + }); + + auto& vHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { + if (vars.states.upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + if (requestDoc.isNull() || !requestDoc.size()) { + return request->send(400); + } + + // prepare request + const auto result = fromJson(requestDoc, vars); + requestDoc.clear(); + + // make response + auto *response = new AsyncJsonResponse(); + auto& responseDoc = response->getRoot(); + toJson(vars, responseDoc); + + // send response + response->setLength(); + response->setCode(result.changed ? 201 : 200); + request->send(response); + + if (result.changed) { + // If busy, the periodic task will publish the current state. + std::unique_lock lock(mqttMutex, std::try_to_lock); + if (lock.owns_lock() && mqttPublishStateTask) { + mqttPublishStateTask->requestEarlyRun(); + } + } + }); + vHandler.setMaxContentLength(1536); + vHandler.addMiddleware(&authMiddleware); + + webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) { + // make response + auto *response = new AsyncJsonResponse(); + auto& doc = response->getRoot(); + + auto docSystem = doc[S_SYSTEM].to(); + docSystem[S_RESET_REASON] = getResetReason(); + docSystem[S_UPTIME] = millis() / 1000; + + bool isConnected = isNetworkConnected(); + auto docNetwork = doc[S_NETWORK].to(); + docNetwork[S_HOSTNAME] = networkSettings.hostname; + docNetwork[S_MAC] = WiFi.STA.macAddress(); + docNetwork[S_CONNECTED] = isConnected; + docNetwork[S_SSID] = strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr; + docNetwork[S_SIGNAL_QUALITY] = isConnected ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0; + docNetwork[S_CHANNEL] = isConnected ? networkSettings.sta.channel : 0; + docNetwork[S_IP] = isConnected ? WiFi.STA.localIP().toString() : ""; + docNetwork[S_SUBNET] = isConnected ? WiFi.STA.subnetMask().toString() : ""; + docNetwork[S_GATEWAY] = isConnected ? WiFi.STA.gatewayIP().toString() : ""; + docNetwork[S_DNS] = isConnected ? WiFi.STA.dnsIP().toString() : ""; + + auto docBuild = doc[S_BUILD].to(); + docBuild[S_VERSION] = BUILD_VERSION; + docBuild[S_COMMIT] = BUILD_COMMIT; + docBuild[S_DATE] = __DATE__ " " __TIME__; + docBuild[S_ENV] = BUILD_ENV; + docBuild[S_CORE] = ESP.getCoreVersion(); + docBuild[S_SDK] = ESP.getSdkVersion(); + + const auto memory = getMemoryMetrics(); + auto docHeap = doc[S_HEAP].to(); + docHeap[S_TOTAL] = memory.heap.total; + docHeap[S_FREE] = memory.heap.total_free_bytes; + docHeap[S_MIN_FREE] = memory.heap.minimum_free_bytes; + docHeap[S_MAX_FREE_BLOCK] = memory.heap.largest_free_block; + docHeap[S_MIN_MAX_FREE_BLOCK] = memory.heap.minLargestBlock; + + auto docPsram = doc[S_PSRAM].to(); + docPsram[S_TOTAL] = memory.psram.total; + docPsram[S_FREE] = memory.psram.total_free_bytes; + docPsram[S_MIN_FREE] = memory.psram.minimum_free_bytes; + docPsram[S_MAX_FREE_BLOCK] = memory.psram.largest_free_block; + + auto docChip = doc[S_CHIP].to(); + docChip[S_MODEL] = ESP.getChipModel(); + docChip[S_REV] = ESP.getChipRevision(); + docChip[S_CORES] = ESP.getChipCores(); + docChip[S_FREQ] = ESP.getCpuFreqMHz(); + + auto docFlash = doc[S_FLASH].to(); + docFlash[S_SIZE] = ESP.getFlashChipSize(); + + // send response + response->setLength(); + request->send(response); + }); + + webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) { + size_t address = 0; + size_t size = 0; + + const esp_err_t image = esp_core_dump_image_get(&address, &size); + if (image != ESP_OK) { + request->send(image == ESP_ERR_NOT_FOUND ? 404 : 500); + return; + } + + if (esp_core_dump_image_check() != ESP_OK) { + request->send(500); + return; + } + + const esp_partition_t* partition = esp_partition_find_first( + ESP_PARTITION_TYPE_DATA, + ESP_PARTITION_SUBTYPE_DATA_COREDUMP, + nullptr + ); + if (partition == nullptr || partition->address != address || size > partition->size) { + request->send(500); + return; + } + + auto* response = request->beginResponse("application/octet-stream", size, + [partition, size](uint8_t* buffer, size_t maximum, size_t index) -> size_t { + if (index >= size) { + return 0; + } + + const size_t remaining = size - index; + const size_t count = remaining < maximum ? remaining : maximum; + if (esp_partition_read(partition, index, buffer, count) != ESP_OK) { + return 0; + } + + return count; + }); + setDownloadFilename(response, "coredump", "bin"); + request->send(response); + }).addMiddleware(&authMiddleware); +} + +// Initialization +void initPortal() { + webServer = new AsyncWebServer(80); + initWebSerial(); + routes(); + restApi(); +} diff --git a/src/regulator.cpp b/src/regulator.cpp new file mode 100644 index 0000000..7c792cb --- /dev/null +++ b/src/regulator.cpp @@ -0,0 +1,242 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include + +#include +#include + +static GyverPID pidRegulator(0, 0, 0); + +static float prevHeatingTarget = 0.0f; +static float equithermResult = 0.0f; +static float pidResult = 0.0f; +static bool indoorSensorsConnected = false; + +static Task equithermTask("Equitherm", Task::Type::ONCE, [](void*) { + float etResult = settings.heating.target + settings.equitherm.shift; + + if (settings.heating.maxTemp > settings.heating.target) { + float tempDelta = settings.heating.target - vars.master.heating.outdoorTemp; + float maxPoint = settings.heating.target - ( + settings.heating.maxTemp - settings.heating.target + ) / settings.equitherm.slope; + + float sf = (settings.heating.maxTemp - settings.heating.target) / pow( + settings.heating.target - maxPoint, + 1.0f / settings.equitherm.exponent + ); + etResult = settings.heating.target + settings.equitherm.shift + sf * ( + tempDelta >= 0 + ? pow(tempDelta, 1.0f / settings.equitherm.exponent) + : -(pow(-(tempDelta), 1.0f / settings.equitherm.exponent)) + ); + } + + if (indoorSensorsConnected && !settings.pid.enabled && !settings.heating.turbo) { + etResult += constrain( + settings.heating.target - vars.master.heating.indoorTemp, + -3.0f, + 3.0f + ) * settings.equitherm.targetDiffFactor; + } + + if (!std::isfinite(etResult)) { + etResult = settings.heating.target + settings.equitherm.shift; + } + + etResult = constrain(etResult, settings.heating.minTemp, settings.heating.maxTemp); + + if (isFloatDifferent(equithermResult, etResult, 0.09f)) { + equithermResult = etResult; + ESP_LOGI(L_REGULATOR_EQUITHERM, "New result: %.2f", etResult); + } +}); + +static Task pidTask("PID", Task::Type::FOREVER, [](void*) { + pidRegulator.Kp = settings.heating.turbo ? 0.0f : settings.pid.p_factor; + pidRegulator.Ki = settings.pid.i_factor; + pidRegulator.Kd = settings.pid.d_factor; + + pidRegulator.setLimits(settings.pid.minTemp, settings.pid.maxTemp); + // Use the same period for scheduling and the integral/derivative terms. + pidRegulator.setDt(pidTask.interval()); + pidRegulator.input = vars.master.heating.indoorTemp; + pidRegulator.setpoint = settings.heating.target; + + float error = pidRegulator.setpoint - pidRegulator.input; + bool hasDeadband = settings.pid.deadband.enabled + && (error > -(settings.pid.deadband.thresholdHigh)) + && (error < settings.pid.deadband.thresholdLow); + + if (hasDeadband) { + pidRegulator.Kp *= settings.pid.deadband.p_multiplier; + pidRegulator.Ki *= settings.pid.deadband.i_multiplier; + pidRegulator.Kd *= settings.pid.deadband.d_multiplier; + } + + float result = pidRegulator.getResult(); + if (isFloatDifferent(pidResult, result, 0.09f)) { + pidResult = result; + ESP_LOGI(L_REGULATOR_PID, "New result: %.2f", result); + ESP_LOGD(L_REGULATOR_PID, "Integral: %.2f", pidRegulator.integral); + } +}); + +static void turbo() { + if (settings.heating.turbo) { + if (!settings.heating.enabled || vars.emergency.state || !indoorSensorsConnected) { + settings.heating.turbo = false; + + } else if (!settings.pid.enabled && !settings.equitherm.enabled) { + settings.heating.turbo = false; + + } else if (fabsf(settings.heating.target - vars.master.heating.indoorTemp) <= 1.0f) { + settings.heating.turbo = false; + } + + if (!settings.heating.turbo) { + ESP_LOGI(L_REGULATOR, "Turbo mode auto disabled"); + } + } +} + +static void hysteresis() { + // Hysteresis also clears blocking when it is no longer applicable. + const bool useHysteresis = settings.heating.hysteresis.enabled && indoorSensorsConnected + && (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC); + + if (useHysteresis) { + if (!vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target + 0.0001f >= settings.heating.hysteresis.value) { + vars.master.heating.blocking = true; + + } else if (vars.master.heating.blocking && vars.master.heating.indoorTemp - settings.heating.target - 0.0001f <= -(settings.heating.hysteresis.value)) { + vars.master.heating.blocking = false; + } + + } else if (vars.master.heating.blocking) { + vars.master.heating.blocking = false; + } +} + +static inline float getHeatingMinSetpointTemp() { + return settings.opentherm.options.nativeOTC + ? vars.master.heating.minTemp + : settings.heating.minTemp; +} + +static inline float getHeatingMaxSetpointTemp() { + return settings.opentherm.options.nativeOTC + ? vars.master.heating.maxTemp + : settings.heating.maxTemp; +} + +static float getHeatingSetpointTemp() { + if (isFloatDifferent(prevHeatingTarget, settings.heating.target, 0.0001f)) { + prevHeatingTarget = settings.heating.target; + ESP_LOGI(L_REGULATOR, "New target: %.2f", settings.heating.target); + } + + if (vars.emergency.state) { + return settings.emergency.target; + + } else if (settings.opentherm.options.nativeOTC) { + return settings.heating.target; + } + + float setpoint = settings.heating.target; + if (settings.equitherm.enabled || settings.pid.enabled) { + setpoint = 0.0f; + + if (settings.equitherm.enabled) { + equithermTask.forceRun(); + setpoint += equithermResult; + } + + // Keep the last PID result when heating or the indoor sensor is unavailable. + if (settings.pid.enabled) { + setpoint += pidResult; + } + + if (settings.heating.turbo) { + setpoint += constrain( + settings.heating.target - vars.master.heating.indoorTemp, + -3.0f, + 3.0f + ) * settings.heating.turboFactor; + } + } + + if (vars.master.heating.freezing) { + setpoint = fmaxf( + setpoint, + static_cast(settings.heating.freezeProtection.lowTemp) + ); + } + + return setpoint; +} + +static Task regulatorTask("Regulator", [](void*) { + indoorSensorsConnected = Sensors::existsConnectedSensorsByPurpose(Sensors::Purpose::INDOOR_TEMP); + + if (pidTask.enabled()) { + const uint32_t pidInterval = settings.pid.dt * 1000u; + + if (pidTask.interval() != pidInterval) { + pidTask.setInterval(pidInterval); + } + } + + if (settings.equitherm.enabled || settings.pid.enabled || settings.opentherm.options.nativeOTC) { + vars.master.heating.indoorTempControl = true; + vars.master.heating.minTemp = THERMOSTAT_INDOOR_MIN_TEMP; + vars.master.heating.maxTemp = THERMOSTAT_INDOOR_MAX_TEMP; + + } else { + vars.master.heating.indoorTempControl = false; + vars.master.heating.minTemp = settings.heating.minTemp; + vars.master.heating.maxTemp = settings.heating.maxTemp; + } + + // This must still run when the PID calculation task is disabled. + if (!settings.pid.enabled && fabsf(pidRegulator.integral) > 0.01f) { + pidRegulator.integral = 0.0f; + ESP_LOGI(L_REGULATOR_PID, "Integral sum has been reset"); + } + + turbo(); + hysteresis(); + + vars.master.heating.targetTemp = settings.heating.target; + + const float setpointTemp = getHeatingSetpointTemp(); + vars.master.heating.setpointTemp = roundf(constrain( + setpointTemp, + getHeatingMinSetpointTemp(), + getHeatingMaxSetpointTemp() + ), 0); + + Sensors::setValueByType( + Sensors::Type::HEATING_SETPOINT_TEMP, vars.master.heating.setpointTemp, + Sensors::ValueType::PRIMARY, true, true + ); +}); + +void initRegulator() { + regulatorTask.setInterval(10000); + + // Sensor availability is refreshed by the regulator before checking PID eligibility. + pidTask.setEnabledWhen([] { + return settings.pid.enabled && settings.heating.enabled + && !vars.emergency.state && !settings.opentherm.options.nativeOTC + && indoorSensorsConnected; + }); + pidTask.setInterval(10000); + pidTask.resume(pidTask.interval()); + + // Apply mode changes and turbo auto-disable before a PID calculation due on the same pass. + coreTaskManager.addTask(regulatorTask); + coreTaskManager.addTask(pidTask); + coreTaskManager.addTask(equithermTask); + equithermTask.pause(); +} diff --git a/src/sensors.cpp b/src/sensors.cpp new file mode 100644 index 0000000..bbd52cd --- /dev/null +++ b/src/sensors.cpp @@ -0,0 +1,990 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if USE_BLE + #include +#endif + +#if USE_BLE +class BluetoothScanCallbacks : public NimBLEScanCallbacks { +public: + void onDiscovered(const NimBLEAdvertisedDevice* device) override { + auto& deviceAddress = device->getAddress(); + + bool found = false; + uint8_t sensorId; + std::optional sSensor; + for (sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + if (!sSensor->enabled || sSensor->type != Sensors::Type::BLUETOOTH || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + const auto sensorAddress = NimBLEAddress(sSensor->address, deviceAddress.getType()); + if (sensorAddress.isNull() || sensorAddress != deviceAddress) { + continue; + } + + found = true; + break; + } + + if (!found) { + return; + } + + auto deviceName = device->getName(); + auto deviceRssi = device->getRSSI(); + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu '%s': discovered device %s, name: %s, RSSI: %hhd", + sensorId, sSensor->name, + deviceAddress.toString().c_str(), deviceName.c_str(), deviceRssi + ); + + if (!device->haveServiceData()) { + ESP_LOGW( + L_SENSORS_BLE, "Sensor #%hhu '%s': not found service data!", + sensorId, sSensor->name + ); + return; + } + + auto serviceDataCount = device->getServiceDataCount(); + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu '%s': found %hhu service data", + sensorId, sSensor->name, serviceDataCount + ); + + if (parseAtcData(device, sensorId) || parsePvvxData(device, sensorId) || parseBTHomeData(device, sensorId)) { + // update rssi + Sensors::setValueById(sensorId, deviceRssi, Sensors::ValueType::RSSI, false, false); + + } else { + ESP_LOGW( + L_SENSORS_BLE, "Sensor #%hhu '%s': unsupported data format!", + sensorId, sSensor->name + ); + } + } + + static bool parseAtcData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { + NimBLEUUID serviceUuid(static_cast(0x181A)); + + auto serviceData = device->getServiceData(serviceUuid); + if (!serviceData.size()) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not found ATC1441 data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if (serviceData.size() != 13) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not in ATC1441 format", + sensorId, serviceUuid.toString().c_str() + ); + return false; + } + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, service %s: found ATC1441 format", + sensorId, serviceUuid.toString().c_str() + ); + + // Temperature (2 bytes, signed, big-endian) + float temperature = static_cast( + (static_cast(serviceData[6]) << 8) | + static_cast(serviceData[7]) + ) * 0.1f; + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + + // Humidity (1 byte) + float humidity = static_cast(serviceData[8]); + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + + // Battery level (1 byte) + uint8_t batteryLevel = static_cast(serviceData[9]); + Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); + + // Battery mV (2 bytes, big-endian) + uint16_t batteryMv = (static_cast(serviceData[10]) << 8) | static_cast(serviceData[11]); + + // Log + ESP_LOGI( + L_SENSORS_BLE, + "Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu", + sensorId, temperature, humidity, batteryMv, batteryLevel + ); + + return true; + } + + static bool parsePvvxData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { + NimBLEUUID serviceUuid(static_cast(0x181A)); + + auto serviceData = device->getServiceData(serviceUuid); + if (!serviceData.size()) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not found PVVX data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if (serviceData.size() != 14 && serviceData.size() != 15) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not in PVVX format", + sensorId, serviceUuid.toString().c_str() + ); + return false; + } + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, service %s: found PVVX format", + sensorId, serviceUuid.toString().c_str() + ); + + // Temperature (2 bytes, signed, little-endian) + float temperature = static_cast( + (static_cast(serviceData[7]) << 8) | + static_cast(serviceData[6]) + ) * 0.01f; + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + + // Humidity (2 bytes, little-endian) + float humidity = ( + (static_cast(serviceData[9]) << 8) | static_cast(serviceData[8]) + ) * 0.01f; + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + + // Battery level (1 byte) + uint8_t batteryLevel = static_cast(serviceData[12]); + Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); + + // Battery mV (2 bytes, little-endian) + uint16_t batteryMv = (static_cast(serviceData[11]) << 8) | static_cast(serviceData[10]); + + // Log + ESP_LOGI( + L_SENSORS_BLE, + "Sensor #%hhu, received temp: %.2f; humidity: %.2f, battery voltage: %hu, battery level: %hhu", + sensorId, temperature, humidity, batteryMv, batteryLevel + ); + + return true; + } + + static bool parseBTHomeData(const NimBLEAdvertisedDevice* device, uint8_t sensorId) { + NimBLEUUID serviceUuid(static_cast(0xFCD2)); + + auto serviceData = device->getServiceData(serviceUuid); + if (!serviceData.size()) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: not found BTHome data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if ((serviceData[0] & 0xE0) != 0x40) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome version", + sensorId, serviceUuid.toString().c_str() + ); + return false; + + } else if ((serviceData[0] & 0x01) != 0) { + ESP_LOGD( + L_SENSORS_BLE, "Sensor #%hhu, service %s: unsupported BTHome encrypted data", + sensorId, serviceUuid.toString().c_str() + ); + return false; + } + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, service %s: found BTHome format", + sensorId, serviceUuid.toString().c_str() + ); + + bool foundData = false; + size_t serviceDataPos = 1; + while (serviceDataPos < serviceData.size()) { + uint8_t objectId = serviceData[serviceDataPos++]; + + switch (objectId) { + // Packet ID (1 byte) + case 0x00: + if (serviceDataPos + 1 > serviceData.size()) { + return foundData; + } + + serviceDataPos += 1; + break; + + // Battery (1 byte) + case 0x01: { + if (serviceDataPos + 1 > serviceData.size()) { + return foundData; + } + + uint8_t batteryLevel = static_cast(serviceData[serviceDataPos]); + Sensors::setValueById(sensorId, batteryLevel, Sensors::ValueType::BATTERY, true, true); + serviceDataPos += 1; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received battery level: %hhu", + sensorId, batteryLevel + ); + break; + } + + // Temperature (2 bytes, signed, little-endian) + case 0x02: { + if (serviceDataPos + 2 > serviceData.size()) { + return foundData; + } + + int16_t rawTemperature = (static_cast(serviceData[serviceDataPos + 1]) << 8) + | static_cast(serviceData[serviceDataPos]); + float temperature = static_cast(rawTemperature) * 0.01f; + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + serviceDataPos += 2; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received temp: %.2f", + sensorId, temperature + ); + break; + } + + // Humidity (2 bytes, little-endian) + case 0x03: { + if (serviceDataPos + 2 > serviceData.size()) { + return foundData; + } + + uint16_t rawHumidity = (static_cast(serviceData[serviceDataPos + 1]) << 8) + | static_cast(serviceData[serviceDataPos]); + float humidity = static_cast(rawHumidity) * 0.01f; + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + serviceDataPos += 2; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received humidity: %.2f", + sensorId, humidity + ); + break; + } + + // Voltage (2 bytes, little-endian) + case 0x0C: { + if (serviceDataPos + 2 > serviceData.size()) { + return foundData; + } + + uint16_t batteryMv = (static_cast(serviceData[serviceDataPos + 1]) << 8) + | static_cast(serviceData[serviceDataPos]); + serviceDataPos += 2; + foundData = true; + + ESP_LOGI( + L_SENSORS_BLE, "Sensor #%hhu, received battery voltage: %hu", + sensorId, batteryMv + ); + break; + } + + default: + return foundData; + } + } + + return foundData; + } +}; + +static BluetoothScanCallbacks bluetoothScanCallbacks; +#endif + +static const unsigned int wiredDisconnectTimeout = 180000u; +static const unsigned int wirelessDisconnectTimeout = 600000u; +static const unsigned short dallasSearchInterval = 60000u; +static const unsigned short dallasPollingInterval = 10000u; +static const unsigned short dhtPollingInterval = 15000; + +// OneWire +static std::unordered_map owInstances; +static std::unordered_map dallasInstances; +static std::unordered_map dallasSearchTime; +static std::unordered_map dallasLastPollingTime; +static std::unordered_map dallasPolling; + +#if USE_BLE +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; + + for (uint8_t i = 0; i < length; i++) { + if (addr[i] != 0) { + result = false; + break; + } + } + + return result; +} + +static void updateMasterValues() { + const float previousIndoorTemp = vars.master.heating.indoorTemp; + vars.master.heating.indoorTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::INDOOR_TEMP, + Sensors::ValueType::PRIMARY, + settings.heating.indoorTempAvgType, + true, + 0.0f + ); + + if (previousIndoorTemp != vars.master.heating.indoorTemp) { + writeRoomTemperatureTask.requestEarlyRun(); + writeRoomTemperatureCh2Task.requestEarlyRun(); + } + + vars.master.heating.outdoorTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::OUTDOOR_TEMP, + Sensors::ValueType::PRIMARY, + settings.heating.outdoorTempAvgType, + true, + 0.0f + ); + + vars.master.heating.currentTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::HEATING_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); + vars.master.heating.returnTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::HEATING_RETURN_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); + + vars.master.dhw.currentTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::DHW_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); + vars.master.dhw.returnTemp = Sensors::getMeanValueByPurpose( + Sensors::Purpose::DHW_RETURN_TEMP, + Sensors::ValueType::PRIMARY, + Sensors::AverageType::MEAN, + true, + 0.0f + ); +} + +static void makeDallasInstances() { + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + + } else if (dallasInstances.count(sSensor->gpio)) { + // no need to make instances + continue; + } + + auto& owInstance = owInstances[sSensor->gpio]; + owInstance.begin(sSensor->gpio); + owInstance.reset(); + + dallasSearchTime[sSensor->gpio] = 0; + dallasPolling[sSensor->gpio] = false; + dallasLastPollingTime[sSensor->gpio] = 0; + + auto& instance = dallasInstances[sSensor->gpio]; + instance.setOneWire(&owInstance); + instance.setWaitForConversion(false); + + ESP_LOGI(L_SENSORS_DALLAS, "Started on GPIO %hhu", sSensor->gpio); + } +} + +static void cleanDallasInstances() { + // for (auto& [gpio, instance] : dallasInstances) { + auto it = dallasInstances.begin(); + while (it != dallasInstances.end()) { + auto gpio = it->first; + bool instanceUsed = false; + + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + if (sSensor->gpio == gpio) { + instanceUsed = true; + break; + } + } + + if (!instanceUsed) { + it = dallasInstances.erase(it); + owInstances.erase(gpio); + dallasSearchTime.erase(gpio); + dallasPolling.erase(gpio); + dallasLastPollingTime.erase(gpio); + + ESP_LOGI(L_SENSORS_DALLAS, "Stopped on GPIO %hhu", gpio); + continue; + } + + it++; + } +} + +static void searchDallasSensors() { + // search sensors on bus + for (auto& [gpio, instance] : dallasInstances) { + // do not search if polling! + if (dallasPolling[gpio]) { + continue; + } + + if (millis() - dallasSearchTime[gpio] < dallasSearchInterval) { + continue; + } + + dallasSearchTime[gpio] = millis(); + owInstances[gpio].reset(); + instance.begin(); + + ESP_LOGD( + L_SENSORS_DALLAS, + "GPIO %hhu, devices on bus: %hhu, DS18* devices: %hhu", + gpio, instance.getDeviceCount(), instance.getDS18Count() + ); + } +} + +static void fillingAddressesDallasSensors() { + // check & filling sensors address + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + + } else if (!dallasInstances.count(sSensor->gpio)) { + continue; + } + + // do nothing if address not empty + if (!isEmptyAddress(sSensor->address)) { + continue; + } + + // do nothing if polling + if (dallasPolling[sSensor->gpio]) { + continue; + } + + auto& instance = dallasInstances[sSensor->gpio]; + DeviceAddress devAddr; + for (uint8_t devId = 0; devId < instance.getDeviceCount(); devId++) { + if (!instance.getAddress(devAddr, devId)) { + continue; + } + + bool freeAddress = true; + + // checking address usage + for (uint8_t checkingSensorId = 0; checkingSensorId <= Sensors::getMaxSensorId(); checkingSensorId++) { + const auto sCheckingSensor = Sensors::getSettings(checkingSensorId); + if (!sCheckingSensor) { + continue; + } + if (sCheckingSensor->type != Sensors::Type::DALLAS_TEMP || checkingSensorId == sensorId) { + continue; + } + + if (sCheckingSensor->gpio != sSensor->gpio || isEmptyAddress(sCheckingSensor->address)) { + continue; + } + + if (isEqualAddress(sCheckingSensor->address, devAddr)) { + freeAddress = false; + break; + } + } + + // address already in use + if (!freeAddress) { + continue; + } + + const bool addressSet = Sensors::setAddressById(sensorId, devAddr, [sensorId] { + requestReconfigureMqttSensor(sensorId); + requestSaveSensorsSettings(); + }); + if (!addressSet) { + break; + } + ESP_LOGD( + L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', set address: %hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX:%hhX", + sSensor->gpio, sensorId, sSensor->name, + devAddr[0], devAddr[1], devAddr[2], devAddr[3], + devAddr[4], devAddr[5], devAddr[6], devAddr[7] + ); + + break; + } + } +} + +static bool isPollingDallasSensors() { + for (auto& [gpio, instance] : dallasInstances) { + if (dallasPolling.count(gpio) && dallasPolling[gpio]) { + return true; + } + } + + return false; +} + +static void pollingDallasSensors(bool newPolling = true) { + for (auto& [gpio, instance] : dallasInstances) { + unsigned long ts = millis(); + + if (dallasPolling[gpio]) { + unsigned long minPollingTime = instance.millisToWaitForConversion(12) * 2; + unsigned long estimatePollingTime = ts - dallasLastPollingTime[gpio]; + + // check conversion time + // isConversionComplete does not work with chinese clones! + if (estimatePollingTime < minPollingTime) { + continue; + } + + // read sensors data for current instance + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + // only target & valid sensors + if (!sSensor->enabled || sSensor->type != Sensors::Type::DALLAS_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + + } else if (sSensor->gpio != gpio || isEmptyAddress(sSensor->address)) { + continue; + } + + float value = instance.getTempC(sSensor->address); + if (value == DEVICE_DISCONNECTED_C) { + ESP_LOGW( + L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s': failed receiving data", + sSensor->gpio, sensorId, sSensor->name + ); + + Sensors::adjustSignalQuality(sensorId, -1); + + continue; + } + + ESP_LOGD( + L_SENSORS_DALLAS, "GPIO %hhu, sensor #%hhu '%s', received data: %.2f", + sSensor->gpio, sensorId, sSensor->name, value + ); + + Sensors::adjustSignalQuality(sensorId, 1); + + // set sensor value + Sensors::setValueById( + sensorId, value, + Sensors::ValueType::TEMPERATURE, true, true + ); + } + + // reset polling flag + dallasPolling[gpio] = false; + + } else if (newPolling) { + auto estimateLastPollingTime = ts - dallasLastPollingTime[gpio]; + + // check last polling time + if (estimateLastPollingTime < dallasPollingInterval) { + continue; + } + + // start polling + instance.setResolution(12); + instance.requestTemperatures(); + dallasPolling[gpio] = true; + dallasLastPollingTime[gpio] = ts; + + ESP_LOGD(L_SENSORS_DALLAS, "GPIO %hhu, polling...", gpio); + } + } +} + +#if USE_BLE +static void scanBleSensors() { + if (!Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true)) { + if (NimBLEDevice::isInitialized()) { + if (pBLEScan != nullptr) { + if (pBLEScan->isScanning()) { + pBLEScan->stop(); + + } else { + pBLEScan = nullptr; + } + } + + if (pBLEScan == nullptr) { + if (NimBLEDevice::deinit(true)) { + ESP_LOGI(L_SENSORS_BLE, "Deinitialized"); + + } else { + ESP_LOGW(L_SENSORS_BLE, "Unable to deinitialize!"); + } + } + } + + return; + } + + if (!NimBLEDevice::isInitialized() && millis() > 5000) { + if (NimBLEDevice::init(PROJECT_NAME)) { + ESP_LOGI(L_SENSORS_BLE, "Initialized"); + + #ifdef ESP_PWR_LVL_P20 + NimBLEDevice::setPower(ESP_PWR_LVL_P20); + #elifdef ESP_PWR_LVL_P9 + NimBLEDevice::setPower(ESP_PWR_LVL_P9); + #endif + + } else { + ESP_LOGW(L_SENSORS_BLE, "Unable to initialize!"); + return; + } + } + + if (pBLEScan == nullptr) { + pBLEScan = NimBLEDevice::getScan(); + pBLEScan->setCallbacks(bluetoothScanCallbacks); + #if MYNEWT_VAL(BLE_EXT_ADV) + pBLEScan->setPhy(NimBLEScan::Phy::SCAN_ALL); + #endif + pBLEScan->setDuplicateFilter(false); + pBLEScan->setMaxResults(0); + pBLEScan->setInterval(10000); + pBLEScan->setWindow(10000); + + ESP_LOGI(L_SENSORS_BLE, "Scanning initialized"); + } + + if (!pBLEScan->isScanning()) { + activeScanBle = !activeScanBle; + pBLEScan->setActiveScan(activeScanBle); + + if (pBLEScan->start(30000, false, false)) { + ESP_LOGI( + L_SENSORS_BLE, + "%s scanning started", + activeScanBle ? "Active" : "Passive" + ); + + } else { + ESP_LOGI(L_SENSORS_BLE, "Unable to start scanning"); + } + } +} +#endif + +static void updateConnectionStatus() { + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + Sensors::updateConnectionStatusById(sensorId, wiredDisconnectTimeout, wirelessDisconnectTimeout); + } +} + +static bool canRunSensors() { + return !vars.states.upgrading && !restartTask.scheduled() && !restartTask.active(); +} + +static Task readDallasSensorsTask("Read Dallas sensors", [](void*) { + pollingDallasSensors(false); +}); + +static Task pollDhtSensorsTask("Poll DHT sensors", [](void*) { + static DHT instance; + static uint8_t lastPollingSensorId{0}; + static std::unordered_map lastPollingTime(2); + + if (instance.isPolling()) { + return; + } + + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + if (sSensor->type != Sensors::Type::DHT11 && sSensor->type != Sensors::Type::DHT22) { + continue; + } + + if (lastPollingTime.count(sSensor->gpio) && millis() - lastPollingTime[sSensor->gpio] < dhtPollingInterval) { + continue; + } + + const auto sensorGpio = static_cast(sSensor->gpio); + DHT::Type sensorType = DHT::Type::DHT22; + if (sSensor->type == Sensors::Type::DHT11) { + sensorType = DHT::Type::DHT11; + + } else if (sSensor->type == Sensors::Type::DHT22) { + sensorType = DHT::Type::DHT22; + } + + if (lastPollingSensorId != sensorId || instance.getGpio() != sensorGpio || instance.getType() != sensorType) { + instance.reset(); + instance.onData([sensorId, gpio = sSensor->gpio](float humidity, float temperature) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + lastPollingTime[gpio] = millis(); + return; + } + + ESP_LOGD( + L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s', temp: %.2f, humidity: %.2f%%", + sSensor->gpio, sensorId, sSensor->name, temperature, humidity + ); + + // set temperature + Sensors::setValueById( + sensorId, temperature, + Sensors::ValueType::TEMPERATURE, true, true + ); + + // set humidity + Sensors::setValueById(sensorId, humidity, Sensors::ValueType::HUMIDITY, true, true); + + Sensors::adjustSignalQuality(sensorId, 1); + lastPollingTime[gpio] = millis(); + }); + + instance.onError([sensorId, gpio = sSensor->gpio](DHT::Status status) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + lastPollingTime[gpio] = millis(); + return; + } + + ESP_LOGW( + L_SENSORS_DHT, "GPIO %hhu, sensor #%hhu '%s': failed receiving data (err: %s)", + sSensor->gpio, sensorId, sSensor->name, DHT::statusToString(instance.getStatus()) + ); + + Sensors::adjustSignalQuality(sensorId, -1); + lastPollingTime[gpio] = millis(); + }); + + if (instance.setup(sensorGpio, sensorType)) { + ESP_LOGI(L_SENSORS_DHT, "Started on GPIO %hhu", sSensor->gpio); + + } else { + ESP_LOGW( + L_SENSORS_DHT, "Failed to start on GPIO %hhu (err: %s)", + sSensor->gpio, DHT::statusToString(instance.getStatus()) + ); + } + } + + lastPollingSensorId = sensorId; + if (!instance.poll()) { + lastPollingTime[sSensor->gpio] = millis(); + } + + break; + } +}); + +static Task maintainDallasSensorsTask("Maintain Dallas sensors", [](void*) { + cleanDallasInstances(); + makeDallasInstances(); + searchDallasSensors(); + fillingAddressesDallasSensors(); + pollingDallasSensors(); +}); + +static Task readNtcSensorsTask("Read NTC sensors", [](void*) { + for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) { + const auto sSensor = Sensors::getSettings(sensorId); + if (!sSensor) { + continue; + } + + if (!sSensor->enabled || sSensor->type != Sensors::Type::NTC_10K_TEMP || sSensor->purpose == Sensors::Purpose::NOT_CONFIGURED) { + continue; + } + + const auto value = analogReadMilliVolts(sSensor->gpio); + if (value < DEFAULT_NTC_VLOW_TRESHOLD || value > DEFAULT_NTC_VHIGH_TRESHOLD) { + Sensors::setConnectionStatusById(sensorId, false, false); + + ESP_LOGW( + L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', voltage is out of threshold: %.3f", + sSensor->gpio, sensorId, sSensor->name, (value / 1000.0f) + ); + + continue; + } + + const float sensorResistance = value > 1 + ? DEFAULT_NTC_REF_RESISTANCE / (DEFAULT_NTC_VREF / static_cast(value) - 1.0f) + : 0.0f; + const float rawTemp = 1.0f / ( + 1.0f / (DEFAULT_NTC_NOMINAL_TEMP + 273.15f) + + log(sensorResistance / DEFAULT_NTC_NOMINAL_RESISTANCE) / DEFAULT_NTC_BETA_FACTOR + ) - 273.15f; + + ESP_LOGD( + L_SENSORS_NTC, "GPIO %hhu, sensor #%hhu '%s', raw temp: %.2f, raw voltage: %.3f, raw resistance: %.2f", + sSensor->gpio, sensorId, sSensor->name, rawTemp, (value / 1000.0f), sensorResistance + ); + + // set temp + Sensors::setValueById( + sensorId, rawTemp, + Sensors::ValueType::TEMPERATURE, true, true + ); + } +}); + +#if USE_BLE +static Task scanBleSensorsTask("Scan BLE sensors", [](void*) { + scanBleSensors(); +}); +#endif + +static Task updateSensorsTask("Update sensor states", [](void*) { + updateConnectionStatus(); + updateMasterValues(); +}); + +void initSensors() { + dallasLastPollingTime.reserve(2); + owInstances.reserve(2); + dallasInstances.reserve(2); + dallasSearchTime.reserve(2); + dallasPolling.reserve(2); + + readDallasSensorsTask.setInterval(1000) + .setEnabledWhen([] { + return canRunSensors() && isPollingDallasSensors(); + }); + sensorsTaskManager.addTask(readDallasSensorsTask); + + pollDhtSensorsTask.setInterval(1000) + .setEnabledWhen([] { + return canRunSensors() && ( + Sensors::getAmountByType(Sensors::Type::DHT11, true) || + Sensors::getAmountByType(Sensors::Type::DHT22, true) + ); + }); + sensorsTaskManager.addTask(pollDhtSensorsTask); + + maintainDallasSensorsTask.setEnabledWhen([] { + return canRunSensors() && ( + !dallasInstances.empty() || + Sensors::getAmountByType(Sensors::Type::DALLAS_TEMP, true) + ); + }) + .resume(15000); + sensorsTaskManager.addTask(maintainDallasSensorsTask); + + readNtcSensorsTask.setEnabledWhen([] { + return canRunSensors() && Sensors::getAmountByType(Sensors::Type::NTC_10K_TEMP, true); + }) + .resume(15000); + sensorsTaskManager.addTask(readNtcSensorsTask); + + #if USE_BLE + scanBleSensorsTask.setEnabledWhen([] { + return canRunSensors() && ( + NimBLEDevice::isInitialized() || + Sensors::getAmountByType(Sensors::Type::BLUETOOTH, true) + ); + }) + .resume(15000); + sensorsTaskManager.addTask(scanBleSensorsTask); + #endif + + updateSensorsTask.setInterval(1000) + .setEnabledWhen(canRunSensors); + sensorsTaskManager.addTask(updateSensorsTask); +} diff --git a/src/strings.h b/src/strings.h deleted file mode 100644 index b7f2eb8..0000000 --- a/src/strings.h +++ /dev/null @@ -1,226 +0,0 @@ -#pragma once - -const char L_SETTINGS[] = "SETTINGS"; -const char L_SETTINGS_OT[] = "SETTINGS.OT"; -const char L_SETTINGS_DHW[] = "SETTINGS.DHW"; -const char L_SETTINGS_HEATING[] = "SETTINGS.HEATING"; -const char L_NETWORK[] = "NETWORK"; -const char L_NETWORK_SETTINGS[] = "NETWORK.SETTINGS"; -const char L_PORTAL_WEBSERVER[] = "PORTAL.WEBSERVER"; -const char L_PORTAL_DNSSERVER[] = "PORTAL.DNSSERVER"; -const char L_PORTAL_CAPTIVE[] = "PORTAL.CAPTIVE"; -const char L_PORTAL_OTA[] = "PORTAL.OTA"; -const char L_MAIN[] = "MAIN"; -const char L_MQTT[] = "MQTT"; -const char L_MQTT_HA[] = "MQTT.HA"; -const char L_MQTT_MSG[] = "MQTT.MSG"; -const char L_OT[] = "OT"; -const char L_OT_DHW[] = "OT.DHW"; -const char L_OT_HEATING[] = "OT.HEATING"; -const char L_OT_CH2[] = "OT.CH2"; -const char L_SENSORS[] = "SENSORS"; -const char L_SENSORS_SETTINGS[] = "SENSORS.SETTINGS"; -const char L_SENSORS_DALLAS[] = "SENSORS.DALLAS"; -const char L_SENSORS_DHT[] = "SENSORS.DHT"; -const char L_SENSORS_NTC[] = "SENSORS.NTC"; -const char L_SENSORS_BLE[] = "SENSORS.BLE"; -const char L_REGULATOR[] = "REGULATOR"; -const char L_REGULATOR_PID[] = "REGULATOR.PID"; -const char L_REGULATOR_EQUITHERM[] = "REGULATOR.EQUITHERM"; -const char L_CASCADE_INPUT[] = "CASCADE.INPUT"; -const char L_CASCADE_OUTPUT[] = "CASCADE.OUTPUT"; -const char L_EXTPUMP[] = "EXTPUMP"; - - -const char S_ACTIONS[] = "actions"; -const char S_ACTIVE[] = "active"; -const char S_ADDRESS[] = "address"; -const char S_ANTI_STUCK_INTERVAL[] = "antiStuckInterval"; -const char S_ANTI_STUCK_TIME[] = "antiStuckTime"; -const char S_AP[] = "ap"; -const char S_APP_VERSION[] = "appVersion"; -const char S_AUTH[] = "auth"; -const char S_AUTO_DIAG_RESET[] = "autoDiagReset"; -const char S_AUTO_FAULT_RESET[] = "autoFaultReset"; -const char S_BACKTRACE[] = "backtrace"; -const char S_BATTERY[] = "battery"; -const char S_BAUDRATE[] = "baudrate"; -const char S_BLOCKING[] = "blocking"; -const char S_BSSID[] = "bssid"; -const char S_BUILD[] = "build"; -const char S_CASCADE_CONTROL[] = "cascadeControl"; -const char S_CHANNEL[] = "channel"; -const char S_CH2_ALWAYS_ENABLED[] = "ch2AlwaysEnabled"; -const char S_CH2_DISABLING_ACTION[] = "ch2DisablingAction"; -const char S_CHIP[] = "chip"; -const char S_CODE[] = "code"; -const char S_COMMIT[] = "commit"; -const char S_CONNECTED[] = "connected"; -const char S_CONTINUES[] = "continues"; -const char S_COOLING[] = "cooling"; -const char S_COOLING_SUPPORT[] = "coolingSupport"; -const char S_CORE[] = "core"; -const char S_CORES[] = "cores"; -const char S_CRASH[] = "crash"; -const char S_CURRENT_TEMP[] = "currentTemp"; -const char S_DATA[] = "data"; -const char S_DATE[] = "date"; -const char S_DEADBAND[] = "deadband"; -const char S_DHW[] = "dhw"; -const char S_DHW_BLOCKING[] = "dhwBlocking"; -const char S_DHW_DISABLING_ACTION[] = "dhwDisablingAction"; -const char S_DHW_STATE_AS_DHW_BLOCKING[] = "dhwStateAsDhwBlocking"; -const char S_DHW_SUPPORT[] = "dhwSupport"; -const char S_DHW_TO_CH2[] = "dhwToCh2"; -const char S_DIAG[] = "diag"; -const char S_DNS[] = "dns"; -const char S_DT[] = "dt"; -const char S_D_FACTOR[] = "d_factor"; -const char S_D_MULTIPLIER[] = "d_multiplier"; -const char S_EMERGENCY[] = "emergency"; -const char S_ENABLED[] = "enabled"; -const char S_ENV[] = "env"; -const char S_EPC[] = "epc"; -const char S_EQUITHERM[] = "equitherm"; -const char S_EXPONENT[] = "exponent"; -const char S_EXTERNAL_PUMP[] = "externalPump"; -const char S_FACTOR[] = "factor"; -const char S_FAULT[] = "fault"; -const char S_FREEZE_PROTECTION[] = "freezeProtection"; -const char S_FREEZING[] = "freezing"; -const char S_FILTERING[] = "filtering"; -const char S_FILTERING_FACTOR[] = "filteringFactor"; -const char S_FLAGS[] = "flags"; -const char S_FLAME[] = "flame"; -const char S_FLASH[] = "flash"; -const char S_FREE[] = "free"; -const char S_FREQ[] = "freq"; -const char S_GATEWAY[] = "gateway"; -const char S_GET_MIN_MAX_TEMP[] = "getMinMaxTemp"; -const char S_GPIO[] = "gpio"; -const char S_HEAP[] = "heap"; -const char S_HEATING[] = "heating"; -const char S_HEATING_DISABLING_ACTION[] = "heatingDisablingAction"; -const char S_HEATING_TO_CH2[] = "heatingToCh2"; -const char S_HEATING_STATE_TO_SUMMER_WINTER_MODE[] = "heatingStateToSummerWinterMode"; -const char S_HIDDEN[] = "hidden"; -const char S_HIGH_TEMP[] = "highTemp"; -const char S_HOME_ASSISTANT_DISCOVERY[] = "homeAssistantDiscovery"; -const char S_HOSTNAME[] = "hostname"; -const char S_HUMIDITY[] = "humidity"; -const char S_HYSTERESIS[] = "hysteresis"; -const char S_ID[] = "id"; -const char S_IGNORE_DIAG_STATE[] = "ignoreDiagState"; -const char S_IMMERGAS_FIX[] = "immergasFix"; -const char S_ALWAYS_SEND_INDOOR_TEMP[] = "alwaysSendIndoorTemp"; -const char S_INDOOR_TEMP[] = "indoorTemp"; -const char S_INDOOR_TEMP_AVG_TYPE[] = "indoorTempAvgType"; -const char S_INDOOR_TEMP_CONTROL[] = "indoorTempControl"; -const char S_IN_GPIO[] = "inGpio"; -const char S_INPUT[] = "input"; -const char S_INTERVAL[] = "interval"; -const char S_INVERT_STATE[] = "invertState"; -const char S_IP[] = "ip"; -const char S_I_FACTOR[] = "i_factor"; -const char S_I_MULTIPLIER[] = "i_multiplier"; -const char S_LOGIN[] = "login"; -const char S_LOG_LEVEL[] = "logLevel"; -const char S_LOW_TEMP[] = "lowTemp"; -const char S_MAC[] = "mac"; -const char S_MASTER[] = "master"; -const char S_MAX[] = "max"; -const char S_MAX_FREE_BLOCK[] = "maxFreeBlock"; -const char S_MAX_MODULATION[] = "maxModulation"; -const char S_MAX_POWER[] = "maxPower"; -const char S_MAX_TEMP[] = "maxTemp"; -const char S_MAX_TEMP_SYNC_WITH_TARGET_TEMP[] = "maxTempSyncWithTargetTemp"; -const char S_MDNS[] = "mdns"; -const char S_MEMBER_ID[] = "memberId"; -const char S_MIN[] = "min"; -const char S_MIN_FREE[] = "minFree"; -const char S_MIN_MAX_FREE_BLOCK[] = "minMaxFreeBlock"; -const char S_MIN_POWER[] = "minPower"; -const char S_MIN_TEMP[] = "minTemp"; -const char S_MODEL[] = "model"; -const char S_MODULATION[] = "modulation"; -const char S_MQTT[] = "mqtt"; -const char S_NAME[] = "name"; -const char S_NATIVE_OTC[] = "nativeOTC"; -const char S_NETWORK[] = "network"; -const char S_NTP[] = "ntp"; -const char S_OFFSET[] = "offset"; -const char S_ON_ENABLED_HEATING[] = "onEnabledHeating"; -const char S_ON_FAULT[] = "onFault"; -const char S_ON_LOSS_CONNECTION[] = "onLossConnection"; -const char S_OPENTHERM[] = "opentherm"; -const char S_OPTIONS[] = "options"; -const char S_OUTDOOR_TEMP[] = "outdoorTemp"; -const char S_OUTDOOR_TEMP_AVG_TYPE[] = "outdoorTempAvgType"; -const char S_OUT_GPIO[] = "outGpio"; -const char S_OUTPUT[] = "output"; -const char S_OVERHEAT[] = "overheat"; -const char S_OVERHEAT_PROTECTION[] = "overheatProtection"; -const char S_PASSWORD[] = "password"; -const char S_PID[] = "pid"; -const char S_PORT[] = "port"; -const char S_PORTAL[] = "portal"; -const char S_POST_CIRCULATION_TIME[] = "postCirculationTime"; -const char S_POWER[] = "power"; -const char S_PREFIX[] = "prefix"; -const char S_PROTOCOL_VERSION[] = "protocolVersion"; -const char S_PURPOSE[] = "purpose"; -const char S_PSRAM[] = "psram"; -const char S_P_FACTOR[] = "p_factor"; -const char S_P_MULTIPLIER[] = "p_multiplier"; -const char S_REAL_SIZE[] = "realSize"; -const char S_REASON[] = "reason"; -const char S_RESET_DIAGNOSTIC[] = "resetDiagnostic"; -const char S_RESET_FAULT[] = "resetFault"; -const char S_RESET_REASON[] = "resetReason"; -const char S_RESTART[] = "restart"; -const char S_RETURN_TEMP[] = "returnTemp"; -const char S_REV[] = "rev"; -const char S_RSSI[] = "rssi"; -const char S_RX_LED_GPIO[] = "rxLedGpio"; -const char S_SDK[] = "sdk"; -const char S_SENSORS[] = "sensors"; -const char S_SERIAL[] = "serial"; -const char S_SERVER[] = "server"; -const char S_SETTINGS[] = "settings"; -const char S_SET_DATE_AND_TIME[] = "setDateAndTime"; -const char S_SHIFT[] = "shift"; -const char S_SIGNAL_QUALITY[] = "signalQuality"; -const char S_SIZE[] = "size"; -const char S_SLAVE[] = "slave"; -const char S_SLOPE[] = "slope"; -const char S_SSID[] = "ssid"; -const char S_STA[] = "sta"; -const char S_STATE[] = "state"; -const char S_STATIC_CONFIG[] = "staticConfig"; -const char S_STATUS_LED_GPIO[] = "statusLedGpio"; -const char S_SETPOINT[] = "setpoint"; -const char S_SETPOINT_TEMP[] = "setpointTemp"; -const char S_SUBNET[] = "subnet"; -const char S_SUMMER_WINTER_MODE[] = "summerWinterMode"; -const char S_SYSTEM[] = "system"; -const char S_TARGET[] = "target"; -const char S_TARGET_DIFF_FACTOR[] = "targetDiffFactor"; -const char S_TARGET_TEMP[] = "targetTemp"; -const char S_TEMPERATURE[] = "temperature"; -const char S_THRESHOLD_HIGH[] = "thresholdHigh"; -const char S_THRESHOLD_LOW[] = "thresholdLow"; -const char S_THRESHOLD_TIME[] = "thresholdTime"; -const char S_TIMEZONE[] = "timezone"; -const char S_TOTAL[] = "total"; -const char S_TRESHOLD_TIME[] = "tresholdTime"; -const char S_TURBO[] = "turbo"; -const char S_TURBO_FACTOR[] = "turboFactor"; -const char S_TYPE[] = "type"; -const char S_UNIT_SYSTEM[] = "unitSystem"; -const char S_UPTIME[] = "uptime"; -const char S_USE[] = "use"; -const char S_USE_DHCP[] = "useDhcp"; -const char S_USER[] = "user"; -const char S_VALUE[] = "value"; -const char S_VERSION[] = "version"; -const char S_WEBSERIAL[] = "webSerial"; diff --git a/src/system.cpp b/src/system.cpp new file mode 100644 index 0000000..9b6c7db --- /dev/null +++ b/src/system.cpp @@ -0,0 +1,140 @@ +#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE + +#include +#include +#include + + +std::string getResetReason() { + std::string value; + + switch (esp_reset_reason()) { + case ESP_RST_POWERON: + value = "Reset due to power-on event"; + break; + + case ESP_RST_EXT: + value = "Reset by external pin"; + break; + + case ESP_RST_SW: + value = "Software reset via esp_restart"; + break; + + case ESP_RST_PANIC: + value = "Software reset due to exception/panic"; + break; + + case ESP_RST_INT_WDT: + value = "Reset (software or hardware) due to interrupt watchdog"; + break; + + case ESP_RST_TASK_WDT: + value = "Reset due to task watchdog"; + break; + + case ESP_RST_WDT: + value = "Reset due to other watchdogs"; + break; + + case ESP_RST_DEEPSLEEP: + value = "Reset after exiting deep sleep mode"; + break; + + case ESP_RST_BROWNOUT: + value = "Brownout reset (software or hardware)"; + break; + + case ESP_RST_SDIO: + value = "Reset over SDIO"; + break; + + case ESP_RST_UNKNOWN: + default: + value = "unknown"; + break; + + } + + return value; +} + +static unsigned long lastHeapInfo = 0; +static unsigned int minFreeHeap = 0; +static unsigned int minLargestFreeBlock = 0; + +Task restartTask("Restart", Task::Type::ONCE, [](void*) { + ESP_LOGI(L_MAIN, "Restart preparation started"); + coreTaskManager.pause(); + sensorsTaskManager.pause(); + openthermTaskManager.pause(); + + // Finish application callbacks and onDone before saving, including with critical heap. + coreTaskManager.waitForPaused(); + sensorsTaskManager.waitForPaused(); + openthermTaskManager.waitForPaused(); + saveSettingsNow(); + + // Yield to FreeRTOS/IDF tasks before resetting the device. + ::delay(250); + ESP.restart(); +}); + +// Maintenance +static Task maintenanceTask("System maintenance", [](void*) { + getMemoryMetrics(); + + drainLoggingSerial(); +}); + +// Heap monitoring remains active while the core manager is paused. +static Task heapTask("Heap monitoring", [](void*) { + const auto memory = getMemoryMetrics(); + unsigned int freeHeap = memory.heap.total_free_bytes; + unsigned int maxFreeBlockHeap = memory.heap.largest_free_block; + + /*if (freeHeap < 2048 || maxFreeBlockHeap < 2048) { + if (!vars.states.upgrading) { + esp_system_abort("OTGateway: low internal heap"); + } + }*/ + + if (esp_log_level_get(L_MAIN) < ESP_LOG_VERBOSE) { + return; + } + + size_t currentMinFreeHeap = memory.heap.minimum_free_bytes; + size_t minFreeHeapDiff = 0; + if (currentMinFreeHeap < minFreeHeap || minFreeHeap == 0) { + minFreeHeapDiff = minFreeHeap ? minFreeHeap - currentMinFreeHeap : 0; + minFreeHeap = currentMinFreeHeap; + } + + size_t currentMinLargestFreeBlock = memory.heap.minLargestBlock; + size_t minLargestFreeBlockDiff = 0; + if (currentMinLargestFreeBlock < minLargestFreeBlock || minLargestFreeBlock == 0) { + minLargestFreeBlockDiff = minLargestFreeBlock ? minLargestFreeBlock - currentMinLargestFreeBlock : 0; + minLargestFreeBlock = currentMinLargestFreeBlock; + } + + if (millis() - lastHeapInfo > 20000 || minFreeHeapDiff > 0 || minLargestFreeBlockDiff > 0) { + ESP_LOGV( + L_MAIN, + "Free heap size: %u of %u bytes (min: %u, diff: %u), max free block: %u (min: %u, diff: %u, frag: %hhu%%)", + freeHeap, memory.heap.total, minFreeHeap, minFreeHeapDiff, + maxFreeBlockHeap, minLargestFreeBlock, minLargestFreeBlockDiff, memory.heap.fragmentation + ); + lastHeapInfo = millis(); + } +}); + +// Initialization +void initSystem() { + systemTaskManager.addTask(restartTask); + + maintenanceTask.setInterval(100); + systemTaskManager.addTask(maintenanceTask); + + heapTask.setInterval(100); + systemTaskManager.addTask(heapTask); +} diff --git a/src/utils.h b/src/utils.h deleted file mode 100644 index 60fab59..0000000 --- a/src/utils.h +++ /dev/null @@ -1,2240 +0,0 @@ -#include - -String getChipId(const char* prefix = nullptr, const char* suffix = nullptr) { - String chipId; - chipId.reserve( - 6 - + (prefix != nullptr ? strlen(prefix) : 0) - + (suffix != nullptr ? strlen(suffix) : 0) - ); - - if (prefix != nullptr) { - chipId.concat(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; - } - - chipId += String(cid, HEX); - - if (suffix != nullptr) { - chipId.concat(suffix); - } - - chipId.trim(); - return chipId; -} - -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 -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 / 4.546091879f; -} - -inline float gallon2liter(float value) { - return value * 4.546091879f; -} - -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; -} - -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); -} - -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); -} - -float roundf(float value, uint8_t decimals = 2) { - if (decimals == 0) { - return static_cast(value + 0.5f); - - } else if (abs(value) < 0.00000001f) { - return 0.0f; - } - - float multiplier = pow10(decimals); - value += 0.5f / multiplier * (value < 0.0f ? -1.0f : 1.0f); - return static_cast(value * multiplier) / multiplier; -} - -inline size_t getTotalHeap() { - return ESP.getHeapSize(); -} - -size_t getFreeHeap(bool getMinValue = false) { - return getMinValue ? ESP.getMinFreeHeap() : ESP.getFreeHeap(); -} - -size_t getMaxFreeBlockHeap(bool getMinValue = false) { - static size_t minValue = 0; - size_t value = ESP.getMaxAllocHeap(); - - size_t minHeapValue = getFreeHeap(true); - if (minHeapValue < minValue || minValue == 0) { - minValue = minHeapValue; - } - - if (value < minValue || minValue == 0) { - minValue = value; - } - - return getMinValue ? minValue : value; -} - -inline uint8_t getHeapFrag() { - return 100 - getMaxFreeBlockHeap() * 100.0 / getFreeHeap(); -} - -String getResetReason() { - String value; - - switch (esp_reset_reason()) { - case ESP_RST_POWERON: - value = "Reset due to power-on event"; - break; - - case ESP_RST_EXT: - value = "Reset by external pin"; - break; - - case ESP_RST_SW: - value = "Software reset via esp_restart"; - break; - - case ESP_RST_PANIC: - value = "Software reset due to exception/panic"; - break; - - case ESP_RST_INT_WDT: - value = "Reset (software or hardware) due to interrupt watchdog"; - break; - - case ESP_RST_TASK_WDT: - value = "Reset due to task watchdog"; - break; - - case ESP_RST_WDT: - value = "Reset due to other watchdogs"; - break; - - case ESP_RST_DEEPSLEEP: - value = "Reset after exiting deep sleep mode"; - break; - - case ESP_RST_BROWNOUT: - value = "Brownout reset (software or hardware)"; - break; - - case ESP_RST_SDIO: - value = "Reset over SDIO"; - break; - - case ESP_RST_UNKNOWN: - default: - value = "unknown"; - break; - - } - - return value; -} - -template -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(); -} - -void networkSettingsToJson(const NetworkSettings& src, JsonVariant dst) { - dst[S_HOSTNAME] = src.hostname; - - dst[S_USE_DHCP] = src.useDhcp; - dst[S_STATIC_CONFIG][S_IP] = src.staticConfig.ip; - dst[S_STATIC_CONFIG][S_GATEWAY] = src.staticConfig.gateway; - dst[S_STATIC_CONFIG][S_SUBNET] = src.staticConfig.subnet; - dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns; - - dst[S_AP][S_SSID] = src.ap.ssid; - dst[S_AP][S_PASSWORD] = src.ap.password; - dst[S_AP][S_CHANNEL] = src.ap.channel; - - dst[S_STA][S_SSID] = src.sta.ssid; - dst[S_STA][S_PASSWORD] = src.sta.password; - dst[S_STA][S_CHANNEL] = src.sta.channel; -} - -bool jsonToNetworkSettings(const JsonVariantConst src, NetworkSettings& dst) { - bool changed = false; - - // hostname - if (src[S_HOSTNAME].is()) { - const JsonString value = src[S_HOSTNAME].as(); - - if (value.size() < sizeof(dst.hostname) && NetworkUtils::NetworkMgr::isHostnameValid(value.c_str())) { - if (strcmp(value.c_str(), dst.hostname) != 0) { - strcpy(dst.hostname, value.c_str()); - changed = true; - } - } - } - - // use dhcp - if (src[S_USE_DHCP].is()) { - dst.useDhcp = src[S_USE_DHCP].as(); - changed = true; - } - - - // static config - if (!src[S_STATIC_CONFIG][S_IP].isNull()) { - String value = src[S_STATIC_CONFIG][S_IP].as(); - - if (value.length() < sizeof(dst.staticConfig.ip) && !value.equals(dst.staticConfig.ip)) { - strcpy(dst.staticConfig.ip, value.c_str()); - changed = true; - } - } - - if (!src[S_STATIC_CONFIG][S_GATEWAY].isNull()) { - String value = src[S_STATIC_CONFIG][S_GATEWAY].as(); - - if (value.length() < sizeof(dst.staticConfig.gateway) && !value.equals(dst.staticConfig.gateway)) { - strcpy(dst.staticConfig.gateway, value.c_str()); - changed = true; - } - } - - if (!src[S_STATIC_CONFIG][S_SUBNET].isNull()) { - String value = src[S_STATIC_CONFIG][S_SUBNET].as(); - - if (value.length() < sizeof(dst.staticConfig.subnet) && !value.equals(dst.staticConfig.subnet)) { - strcpy(dst.staticConfig.subnet, value.c_str()); - changed = true; - } - } - - if (!src[S_STATIC_CONFIG][S_DNS].isNull()) { - String value = src[S_STATIC_CONFIG][S_DNS].as(); - - if (value.length() < sizeof(dst.staticConfig.dns) && !value.equals(dst.staticConfig.dns)) { - strcpy(dst.staticConfig.dns, value.c_str()); - changed = true; - } - } - - - // ap - if (!src[S_AP][S_SSID].isNull()) { - String value = src[S_AP][S_SSID].as(); - - if (value.length() < sizeof(dst.ap.ssid) && !value.equals(dst.ap.ssid)) { - strcpy(dst.ap.ssid, value.c_str()); - changed = true; - } - } - - if (!src[S_AP][S_PASSWORD].isNull()) { - String value = src[S_AP][S_PASSWORD].as(); - - if (value.length() < sizeof(dst.ap.password) && !value.equals(dst.ap.password)) { - strcpy(dst.ap.password, value.c_str()); - changed = true; - } - } - - if (!src[S_AP][S_CHANNEL].isNull()) { - unsigned char value = src[S_AP][S_CHANNEL].as(); - - if (value >= 0 && value < 12) { - dst.ap.channel = value; - changed = true; - } - } - - - // sta - if (!src[S_STA][S_SSID].isNull()) { - String value = src[S_STA][S_SSID].as(); - - if (value.length() < sizeof(dst.sta.ssid) && !value.equals(dst.sta.ssid)) { - strcpy(dst.sta.ssid, value.c_str()); - changed = true; - } - } - - if (!src[S_STA][S_PASSWORD].isNull()) { - String value = src[S_STA][S_PASSWORD].as(); - - if (value.length() < sizeof(dst.sta.password) && !value.equals(dst.sta.password)) { - strcpy(dst.sta.password, value.c_str()); - changed = true; - } - } - - if (!src[S_STA][S_CHANNEL].isNull()) { - unsigned char value = src[S_STA][S_CHANNEL].as(); - - if (value >= 0 && value < 12) { - dst.sta.channel = value; - changed = true; - } - } - - return changed; -} - -void settingsToJson(const Settings& src, JsonVariant dst, bool safe = false) { - if (!safe) { - auto system = dst[S_SYSTEM].to(); - system[S_LOG_LEVEL] = static_cast(src.system.logLevel); - - auto serial = system[S_SERIAL].to(); - serial[S_ENABLED] = src.system.serial.enabled; - serial[S_BAUDRATE] = src.system.serial.baudrate; - - auto webSerial = system[S_WEBSERIAL].to(); - webSerial[S_ENABLED] = src.system.webSerial.enabled; - - auto ntp = system[S_NTP].to(); - ntp[S_SERVER] = src.system.ntp.server; - ntp[S_TIMEZONE] = src.system.ntp.timezone; - - system[S_UNIT_SYSTEM] = static_cast(src.system.unitSystem); - system[S_STATUS_LED_GPIO] = src.system.statusLedGpio; - - auto portal = dst[S_PORTAL].to(); - portal[S_AUTH] = src.portal.auth; - portal[S_LOGIN] = src.portal.login; - portal[S_PASSWORD] = src.portal.password; - portal[S_MDNS] = src.portal.mdns; - - auto opentherm = dst[S_OPENTHERM].to(); - opentherm[S_UNIT_SYSTEM] = static_cast(src.opentherm.unitSystem); - opentherm[S_IN_GPIO] = src.opentherm.inGpio; - opentherm[S_OUT_GPIO] = src.opentherm.outGpio; - opentherm[S_RX_LED_GPIO] = src.opentherm.rxLedGpio; - opentherm[S_MEMBER_ID] = src.opentherm.memberId; - opentherm[S_FLAGS] = src.opentherm.flags; - opentherm[S_HEATING_DISABLING_ACTION] = static_cast(src.opentherm.heatingDisablingAction); - opentherm[S_DHW_DISABLING_ACTION] = static_cast(src.opentherm.dhwDisablingAction); - opentherm[S_CH2_DISABLING_ACTION] = static_cast(src.opentherm.ch2DisablingAction); - opentherm[S_MIN_POWER] = roundf(src.opentherm.minPower, 2); - opentherm[S_MAX_POWER] = roundf(src.opentherm.maxPower, 2); - - auto otOptions = opentherm[S_OPTIONS].to(); - otOptions[S_DHW_SUPPORT] = src.opentherm.options.dhwSupport; - otOptions[S_COOLING_SUPPORT] = src.opentherm.options.coolingSupport; - otOptions[S_SUMMER_WINTER_MODE] = src.opentherm.options.summerWinterMode; - otOptions[S_HEATING_STATE_TO_SUMMER_WINTER_MODE] = src.opentherm.options.heatingStateToSummerWinterMode; - otOptions[S_CH2_ALWAYS_ENABLED] = src.opentherm.options.ch2AlwaysEnabled; - otOptions[S_HEATING_TO_CH2] = src.opentherm.options.heatingToCh2; - otOptions[S_DHW_TO_CH2] = src.opentherm.options.dhwToCh2; - otOptions[S_DHW_BLOCKING] = src.opentherm.options.dhwBlocking; - otOptions[S_DHW_STATE_AS_DHW_BLOCKING] = src.opentherm.options.dhwStateAsDhwBlocking; - otOptions[S_MAX_TEMP_SYNC_WITH_TARGET_TEMP] = src.opentherm.options.maxTempSyncWithTargetTemp; - otOptions[S_GET_MIN_MAX_TEMP] = src.opentherm.options.getMinMaxTemp; - otOptions[S_IGNORE_DIAG_STATE] = src.opentherm.options.ignoreDiagState; - otOptions[S_AUTO_FAULT_RESET] = src.opentherm.options.autoFaultReset; - otOptions[S_AUTO_DIAG_RESET] = src.opentherm.options.autoDiagReset; - otOptions[S_SET_DATE_AND_TIME] = src.opentherm.options.setDateAndTime; - otOptions[S_ALWAYS_SEND_INDOOR_TEMP] = src.opentherm.options.alwaysSendIndoorTemp; - otOptions[S_NATIVE_OTC] = src.opentherm.options.nativeOTC; - otOptions[S_IMMERGAS_FIX] = src.opentherm.options.immergasFix; - - - auto mqtt = dst[S_MQTT].to(); - mqtt[S_ENABLED] = src.mqtt.enabled; - mqtt[S_SERVER] = src.mqtt.server; - mqtt[S_PORT] = src.mqtt.port; - mqtt[S_USER] = src.mqtt.user; - mqtt[S_PASSWORD] = src.mqtt.password; - mqtt[S_PREFIX] = src.mqtt.prefix; - mqtt[S_INTERVAL] = src.mqtt.interval; - mqtt[S_HOME_ASSISTANT_DISCOVERY] = src.mqtt.homeAssistantDiscovery; - - auto emergency = dst[S_EMERGENCY].to(); - emergency[S_TARGET] = roundf(src.emergency.target, 2); - emergency[S_TRESHOLD_TIME] = src.emergency.tresholdTime; - } - - auto heating = dst[S_HEATING].to(); - heating[S_ENABLED] = src.heating.enabled; - heating[S_TURBO] = src.heating.turbo; - heating[S_TARGET] = roundf(src.heating.target, 2); - heating[S_HYSTERESIS][S_ENABLED] = src.heating.hysteresis.enabled; - heating[S_HYSTERESIS][S_VALUE] = roundf(src.heating.hysteresis.value, 3); - heating[S_TURBO_FACTOR] = roundf(src.heating.turboFactor, 3); - heating[S_MIN_TEMP] = src.heating.minTemp; - heating[S_MAX_TEMP] = src.heating.maxTemp; - heating[S_MAX_MODULATION] = src.heating.maxModulation; - heating[S_INDOOR_TEMP_AVG_TYPE] = static_cast(src.heating.indoorTempAvgType); - heating[S_OUTDOOR_TEMP_AVG_TYPE] = static_cast(src.heating.outdoorTempAvgType); - - auto heatingOverheatProtection = heating[S_OVERHEAT_PROTECTION].to(); - heatingOverheatProtection[S_HIGH_TEMP] = src.heating.overheatProtection.highTemp; - heatingOverheatProtection[S_LOW_TEMP] = src.heating.overheatProtection.lowTemp; - - auto freezeProtection = heating[S_FREEZE_PROTECTION].to(); - freezeProtection[S_HIGH_TEMP] = src.heating.freezeProtection.highTemp; - freezeProtection[S_LOW_TEMP] = src.heating.freezeProtection.lowTemp; - - auto dhw = dst[S_DHW].to(); - dhw[S_ENABLED] = src.dhw.enabled; - dhw[S_TARGET] = roundf(src.dhw.target, 1); - dhw[S_MIN_TEMP] = src.dhw.minTemp; - dhw[S_MAX_TEMP] = src.dhw.maxTemp; - dhw[S_MAX_MODULATION] = src.dhw.maxModulation; - - auto dhwOverheatProtection = dhw[S_OVERHEAT_PROTECTION].to(); - dhwOverheatProtection[S_HIGH_TEMP] = src.dhw.overheatProtection.highTemp; - dhwOverheatProtection[S_LOW_TEMP] = src.dhw.overheatProtection.lowTemp; - - auto equitherm = dst[S_EQUITHERM].to(); - equitherm[S_ENABLED] = src.equitherm.enabled; - equitherm[S_SLOPE] = roundf(src.equitherm.slope, 3); - equitherm[S_EXPONENT] = roundf(src.equitherm.exponent, 3); - equitherm[S_SHIFT] = roundf(src.equitherm.shift, 2); - equitherm[S_TARGET_DIFF_FACTOR] = roundf(src.equitherm.targetDiffFactor, 3); - - auto pid = dst[S_PID].to(); - pid[S_ENABLED] = src.pid.enabled; - pid[S_P_FACTOR] = roundf(src.pid.p_factor, 3); - pid[S_I_FACTOR] = roundf(src.pid.i_factor, 4); - pid[S_D_FACTOR] = roundf(src.pid.d_factor, 1); - pid[S_DT] = src.pid.dt; - pid[S_MIN_TEMP] = src.pid.minTemp; - pid[S_MAX_TEMP] = src.pid.maxTemp; - - auto pidDeadband = pid[S_DEADBAND].to(); - pidDeadband[S_ENABLED] = src.pid.deadband.enabled; - pidDeadband[S_P_MULTIPLIER] = src.pid.deadband.p_multiplier; - pidDeadband[S_I_MULTIPLIER] = src.pid.deadband.i_multiplier; - pidDeadband[S_D_MULTIPLIER] = src.pid.deadband.d_multiplier; - pidDeadband[S_THRESHOLD_HIGH] = src.pid.deadband.thresholdHigh; - pidDeadband[S_THRESHOLD_LOW] = src.pid.deadband.thresholdLow; - - if (!safe) { - auto externalPump = dst[S_EXTERNAL_PUMP].to(); - externalPump[S_USE] = src.externalPump.use; - externalPump[S_GPIO] = src.externalPump.gpio; - externalPump[S_INVERT_STATE] = src.externalPump.invertState; - externalPump[S_POST_CIRCULATION_TIME] = roundf(src.externalPump.postCirculationTime / 60, 0); - externalPump[S_ANTI_STUCK_INTERVAL] = roundf(src.externalPump.antiStuckInterval / 86400, 0); - externalPump[S_ANTI_STUCK_TIME] = roundf(src.externalPump.antiStuckTime / 60, 0); - - auto cascadeControlInput = dst[S_CASCADE_CONTROL][S_INPUT].to(); - cascadeControlInput[S_ENABLED] = src.cascadeControl.input.enabled; - cascadeControlInput[S_GPIO] = src.cascadeControl.input.gpio; - cascadeControlInput[S_INVERT_STATE] = src.cascadeControl.input.invertState; - cascadeControlInput[S_THRESHOLD_TIME] = src.cascadeControl.input.thresholdTime; - - auto cascadeControlOutput = dst[S_CASCADE_CONTROL][S_OUTPUT].to(); - cascadeControlOutput[S_ENABLED] = src.cascadeControl.output.enabled; - cascadeControlOutput[S_GPIO] = src.cascadeControl.output.gpio; - cascadeControlOutput[S_INVERT_STATE] = src.cascadeControl.output.invertState; - cascadeControlOutput[S_THRESHOLD_TIME] = src.cascadeControl.output.thresholdTime; - cascadeControlOutput[S_ON_FAULT] = src.cascadeControl.output.onFault; - cascadeControlOutput[S_ON_LOSS_CONNECTION] = src.cascadeControl.output.onLossConnection; - cascadeControlOutput[S_ON_ENABLED_HEATING] = src.cascadeControl.output.onEnabledHeating; - } -} - -inline void safeSettingsToJson(const Settings& src, JsonVariant dst) { - settingsToJson(src, dst, true); -} - -bool jsonToChannelDisablingAction(const JsonVariantConst src, ChannelDisablingAction& dst) { - if (!src.is()) { - return false; - } - - const uint8_t value = src.as(); - switch (value) { - case static_cast(ChannelDisablingAction::OFF): - case static_cast(ChannelDisablingAction::ZERO_SETPOINT): - case static_cast(ChannelDisablingAction::OFF_AND_ZERO_SETPOINT): - if (static_cast(dst) != value) { - dst = static_cast(value); - return true; - } - break; - - default: - break; - } - - return false; -} - -bool jsonToSettings(const JsonVariantConst src, Settings& dst, bool safe = false) { - bool changed = false; - - if (!safe) { - // system - if (!src[S_SYSTEM][S_LOG_LEVEL].isNull()) { - uint8_t value = src[S_SYSTEM][S_LOG_LEVEL].as(); - - if (value != dst.system.logLevel && value >= TinyLoggerLevel::SILENT && value <= TinyLoggerLevel::VERBOSE) { - dst.system.logLevel = value; - changed = true; - } - } - - if (src[S_SYSTEM][S_SERIAL][S_ENABLED].is()) { - bool value = src[S_SYSTEM][S_SERIAL][S_ENABLED].as(); - - if (value != dst.system.serial.enabled) { - dst.system.serial.enabled = value; - changed = true; - } - } - - if (!src[S_SYSTEM][S_SERIAL][S_BAUDRATE].isNull()) { - unsigned int value = src[S_SYSTEM][S_SERIAL][S_BAUDRATE].as(); - - if (value == 9600 || value == 19200 || value == 38400 || value == 57600 || value == 74880 || value == 115200) { - if (value != dst.system.serial.baudrate) { - dst.system.serial.baudrate = value; - changed = true; - } - } - } - - if (src[S_SYSTEM][S_WEBSERIAL][S_ENABLED].is()) { - bool value = src[S_SYSTEM][S_WEBSERIAL][S_ENABLED].as(); - - if (value != dst.system.webSerial.enabled) { - dst.system.webSerial.enabled = value; - changed = true; - } - } - - if (!src[S_SYSTEM][S_NTP][S_SERVER].isNull()) { - String value = src[S_SYSTEM][S_NTP][S_SERVER].as(); - - if (value.length() < sizeof(dst.system.ntp.server) && !value.equals(dst.system.ntp.server)) { - strcpy(dst.system.ntp.server, value.c_str()); - changed = true; - } - } - - if (!src[S_SYSTEM][S_NTP][S_TIMEZONE].isNull()) { - String value = src[S_SYSTEM][S_NTP][S_TIMEZONE].as(); - - if (value.length() < sizeof(dst.system.ntp.timezone) && !value.equals(dst.system.ntp.timezone)) { - strcpy(dst.system.ntp.timezone, value.c_str()); - changed = true; - } - } - - if (!src[S_SYSTEM][S_UNIT_SYSTEM].isNull()) { - uint8_t value = src[S_SYSTEM][S_UNIT_SYSTEM].as(); - UnitSystem prevUnitSystem = dst.system.unitSystem; - - switch (value) { - case static_cast(UnitSystem::METRIC): - if (dst.system.unitSystem != UnitSystem::METRIC) { - dst.system.unitSystem = UnitSystem::METRIC; - changed = true; - } - break; - - case static_cast(UnitSystem::IMPERIAL): - if (dst.system.unitSystem != UnitSystem::IMPERIAL) { - dst.system.unitSystem = UnitSystem::IMPERIAL; - changed = true; - } - break; - - default: - break; - } - - // convert temps - if (dst.system.unitSystem != prevUnitSystem) { - dst.emergency.target = convertTemp(dst.emergency.target, prevUnitSystem, dst.system.unitSystem); - dst.heating.target = convertTemp(dst.heating.target, prevUnitSystem, dst.system.unitSystem); - dst.heating.minTemp = convertTemp(dst.heating.minTemp, prevUnitSystem, dst.system.unitSystem); - dst.heating.maxTemp = convertTemp(dst.heating.maxTemp, prevUnitSystem, dst.system.unitSystem); - dst.dhw.target = convertTemp(dst.dhw.target, prevUnitSystem, dst.system.unitSystem); - dst.dhw.minTemp = convertTemp(dst.dhw.minTemp, prevUnitSystem, dst.system.unitSystem); - dst.dhw.maxTemp = convertTemp(dst.dhw.maxTemp, prevUnitSystem, dst.system.unitSystem); - dst.pid.minTemp = convertTemp(dst.pid.minTemp, prevUnitSystem, dst.system.unitSystem); - dst.pid.maxTemp = convertTemp(dst.pid.maxTemp, prevUnitSystem, dst.system.unitSystem); - } - } - - if (!src[S_SYSTEM][S_STATUS_LED_GPIO].isNull()) { - if (src[S_SYSTEM][S_STATUS_LED_GPIO].is() && src[S_SYSTEM][S_STATUS_LED_GPIO].as().size() == 0) { - if (dst.system.statusLedGpio != GPIO_IS_NOT_CONFIGURED) { - dst.system.statusLedGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_SYSTEM][S_STATUS_LED_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.system.statusLedGpio) { - dst.system.statusLedGpio = value; - changed = true; - } - } - } - - - // portal - if (src[S_PORTAL][S_AUTH].is()) { - bool value = src[S_PORTAL][S_AUTH].as(); - - if (value != dst.portal.auth) { - dst.portal.auth = value; - changed = true; - } - } - - if (!src[S_PORTAL][S_LOGIN].isNull()) { - String value = src[S_PORTAL][S_LOGIN].as(); - - if (value.length() < sizeof(dst.portal.login) && !value.equals(dst.portal.login)) { - strcpy(dst.portal.login, value.c_str()); - changed = true; - } - } - - if (!src[S_PORTAL][S_PASSWORD].isNull()) { - String value = src[S_PORTAL][S_PASSWORD].as(); - - if (value.length() < sizeof(dst.portal.password) && !value.equals(dst.portal.password)) { - strcpy(dst.portal.password, value.c_str()); - changed = true; - } - } - - if (dst.portal.auth && (!strlen(dst.portal.login) || !strlen(dst.portal.password))) { - dst.portal.auth = false; - changed = true; - } - - if (src[S_PORTAL][S_MDNS].is()) { - bool value = src[S_PORTAL][S_MDNS].as(); - - if (value != dst.portal.mdns) { - dst.portal.mdns = value; - changed = true; - } - } - - - // opentherm - if (!src[S_OPENTHERM][S_UNIT_SYSTEM].isNull()) { - uint8_t value = src[S_OPENTHERM][S_UNIT_SYSTEM].as(); - - switch (value) { - case static_cast(UnitSystem::METRIC): - if (dst.opentherm.unitSystem != UnitSystem::METRIC) { - dst.opentherm.unitSystem = UnitSystem::METRIC; - changed = true; - } - break; - - case static_cast(UnitSystem::IMPERIAL): - if (dst.opentherm.unitSystem != UnitSystem::IMPERIAL) { - dst.opentherm.unitSystem = UnitSystem::IMPERIAL; - changed = true; - } - break; - - default: - break; - } - } - - if (!src[S_OPENTHERM][S_IN_GPIO].isNull()) { - if (src[S_OPENTHERM][S_IN_GPIO].is() && src[S_OPENTHERM][S_IN_GPIO].as().size() == 0) { - if (dst.opentherm.inGpio != GPIO_IS_NOT_CONFIGURED) { - dst.opentherm.inGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_OPENTHERM][S_IN_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.opentherm.inGpio) { - dst.opentherm.inGpio = value; - changed = true; - } - } - } - - if (!src[S_OPENTHERM][S_OUT_GPIO].isNull()) { - if (src[S_OPENTHERM][S_OUT_GPIO].is() && src[S_OPENTHERM][S_OUT_GPIO].as().size() == 0) { - if (dst.opentherm.outGpio != GPIO_IS_NOT_CONFIGURED) { - dst.opentherm.outGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_OPENTHERM][S_OUT_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.opentherm.outGpio) { - dst.opentherm.outGpio = value; - changed = true; - } - } - } - - if (!src[S_OPENTHERM][S_RX_LED_GPIO].isNull()) { - if (src[S_OPENTHERM][S_RX_LED_GPIO].is() && src[S_OPENTHERM][S_RX_LED_GPIO].as().size() == 0) { - if (dst.opentherm.rxLedGpio != GPIO_IS_NOT_CONFIGURED) { - dst.opentherm.rxLedGpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_OPENTHERM][S_RX_LED_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.opentherm.rxLedGpio) { - dst.opentherm.rxLedGpio = value; - changed = true; - } - } - } - - if (!src[S_OPENTHERM][S_MEMBER_ID].isNull()) { - auto value = src[S_OPENTHERM][S_MEMBER_ID].as(); - - if (value != dst.opentherm.memberId) { - dst.opentherm.memberId = value; - changed = true; - } - } - - if (!src[S_OPENTHERM][S_FLAGS].isNull()) { - auto value = src[S_OPENTHERM][S_FLAGS].as(); - - if (value != dst.opentherm.flags) { - dst.opentherm.flags = value; - changed = true; - } - } - - if (jsonToChannelDisablingAction(src[S_OPENTHERM][S_HEATING_DISABLING_ACTION], dst.opentherm.heatingDisablingAction)) { - changed = true; - } - - if (jsonToChannelDisablingAction(src[S_OPENTHERM][S_DHW_DISABLING_ACTION], dst.opentherm.dhwDisablingAction)) { - changed = true; - } - - if (jsonToChannelDisablingAction(src[S_OPENTHERM][S_CH2_DISABLING_ACTION], dst.opentherm.ch2DisablingAction)) { - changed = true; - } - - if (!src[S_OPENTHERM][S_MIN_POWER].isNull()) { - float value = src[S_OPENTHERM][S_MIN_POWER].as(); - - if (value >= 0 && value <= 1000 && fabsf(value - dst.opentherm.minPower) > 0.0001f) { - dst.opentherm.minPower = roundf(value, 2); - changed = true; - } - } - - if (!src[S_OPENTHERM][S_MAX_POWER].isNull()) { - float value = src[S_OPENTHERM][S_MAX_POWER].as(); - - if (value >= 0 && value <= 1000 && fabsf(value - dst.opentherm.maxPower) > 0.0001f) { - dst.opentherm.maxPower = roundf(value, 2); - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_DHW_SUPPORT].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_DHW_SUPPORT].as(); - - if (value != dst.opentherm.options.dhwSupport) { - dst.opentherm.options.dhwSupport = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_COOLING_SUPPORT].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_COOLING_SUPPORT].as(); - - if (value != dst.opentherm.options.coolingSupport) { - dst.opentherm.options.coolingSupport = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_SUMMER_WINTER_MODE].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_SUMMER_WINTER_MODE].as(); - - if (value != dst.opentherm.options.summerWinterMode) { - dst.opentherm.options.summerWinterMode = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_HEATING_STATE_TO_SUMMER_WINTER_MODE].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_HEATING_STATE_TO_SUMMER_WINTER_MODE].as(); - - if (value != dst.opentherm.options.heatingStateToSummerWinterMode) { - dst.opentherm.options.heatingStateToSummerWinterMode = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_CH2_ALWAYS_ENABLED].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_CH2_ALWAYS_ENABLED].as(); - - if (value != dst.opentherm.options.ch2AlwaysEnabled) { - dst.opentherm.options.ch2AlwaysEnabled = value; - - if (dst.opentherm.options.ch2AlwaysEnabled) { - dst.opentherm.options.heatingToCh2 = false; - dst.opentherm.options.dhwToCh2 = false; - } - - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_HEATING_TO_CH2].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_HEATING_TO_CH2].as(); - - if (value != dst.opentherm.options.heatingToCh2) { - dst.opentherm.options.heatingToCh2 = value; - - if (dst.opentherm.options.heatingToCh2) { - dst.opentherm.options.ch2AlwaysEnabled = false; - dst.opentherm.options.dhwToCh2 = false; - } - - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_DHW_TO_CH2].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_DHW_TO_CH2].as(); - - if (value != dst.opentherm.options.dhwToCh2) { - dst.opentherm.options.dhwToCh2 = value; - - if (dst.opentherm.options.dhwToCh2) { - dst.opentherm.options.ch2AlwaysEnabled = false; - dst.opentherm.options.heatingToCh2 = false; - } - - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_DHW_BLOCKING].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_DHW_BLOCKING].as(); - - if (value != dst.opentherm.options.dhwBlocking) { - dst.opentherm.options.dhwBlocking = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_DHW_STATE_AS_DHW_BLOCKING].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_DHW_STATE_AS_DHW_BLOCKING].as(); - - if (value != dst.opentherm.options.dhwStateAsDhwBlocking) { - dst.opentherm.options.dhwStateAsDhwBlocking = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_MAX_TEMP_SYNC_WITH_TARGET_TEMP].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_MAX_TEMP_SYNC_WITH_TARGET_TEMP].as(); - - if (value != dst.opentherm.options.maxTempSyncWithTargetTemp) { - dst.opentherm.options.maxTempSyncWithTargetTemp = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_GET_MIN_MAX_TEMP].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_GET_MIN_MAX_TEMP].as(); - - if (value != dst.opentherm.options.getMinMaxTemp) { - dst.opentherm.options.getMinMaxTemp = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_IGNORE_DIAG_STATE].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_IGNORE_DIAG_STATE].as(); - - if (value != dst.opentherm.options.ignoreDiagState) { - dst.opentherm.options.ignoreDiagState = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_AUTO_FAULT_RESET].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_AUTO_FAULT_RESET].as(); - - if (value != dst.opentherm.options.autoFaultReset) { - dst.opentherm.options.autoFaultReset = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_AUTO_DIAG_RESET].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_AUTO_DIAG_RESET].as(); - - if (value != dst.opentherm.options.autoDiagReset) { - dst.opentherm.options.autoDiagReset = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_SET_DATE_AND_TIME].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_SET_DATE_AND_TIME].as(); - - if (value != dst.opentherm.options.setDateAndTime) { - dst.opentherm.options.setDateAndTime = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_ALWAYS_SEND_INDOOR_TEMP].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_ALWAYS_SEND_INDOOR_TEMP].as(); - - if (value != dst.opentherm.options.alwaysSendIndoorTemp) { - dst.opentherm.options.alwaysSendIndoorTemp = value; - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_NATIVE_OTC].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_NATIVE_OTC].as(); - - if (value != dst.opentherm.options.nativeOTC) { - dst.opentherm.options.nativeOTC = value; - - if (value) { - dst.equitherm.enabled = false; - dst.pid.enabled = false; - } - - changed = true; - } - } - - if (src[S_OPENTHERM][S_OPTIONS][S_IMMERGAS_FIX].is()) { - bool value = src[S_OPENTHERM][S_OPTIONS][S_IMMERGAS_FIX].as(); - - if (value != dst.opentherm.options.immergasFix) { - dst.opentherm.options.immergasFix = value; - changed = true; - } - } - - // mqtt - if (src[S_MQTT][S_ENABLED].is()) { - bool value = src[S_MQTT][S_ENABLED].as(); - - if (value != dst.mqtt.enabled) { - dst.mqtt.enabled = value; - changed = true; - } - } - - if (!src[S_MQTT][S_SERVER].isNull()) { - String value = src[S_MQTT][S_SERVER].as(); - - if (value.length() < sizeof(dst.mqtt.server) && !value.equals(dst.mqtt.server)) { - strcpy(dst.mqtt.server, value.c_str()); - changed = true; - } - } - - if (!src[S_MQTT][S_PORT].isNull()) { - unsigned short value = src[S_MQTT][S_PORT].as(); - - if (value > 0 && value <= 65535 && value != dst.mqtt.port) { - dst.mqtt.port = value; - changed = true; - } - } - - if (!src[S_MQTT][S_USER].isNull()) { - String value = src[S_MQTT][S_USER].as(); - - if (value.length() < sizeof(dst.mqtt.user) && !value.equals(dst.mqtt.user)) { - strcpy(dst.mqtt.user, value.c_str()); - changed = true; - } - } - - if (!src[S_MQTT][S_PASSWORD].isNull()) { - String value = src[S_MQTT][S_PASSWORD].as(); - - if (value.length() < sizeof(dst.mqtt.password) && !value.equals(dst.mqtt.password)) { - strcpy(dst.mqtt.password, value.c_str()); - changed = true; - } - } - - if (!src[S_MQTT][S_PREFIX].isNull()) { - String value = src[S_MQTT][S_PREFIX].as(); - - if (value.length() < sizeof(dst.mqtt.prefix) && !value.equals(dst.mqtt.prefix)) { - strcpy(dst.mqtt.prefix, value.c_str()); - changed = true; - } - } - - if (!src[S_MQTT][S_INTERVAL].isNull()) { - unsigned short value = src[S_MQTT][S_INTERVAL].as(); - - if (value >= 3 && value <= 60 && value != dst.mqtt.interval) { - dst.mqtt.interval = value; - changed = true; - } - } - - if (src[S_MQTT][S_HOME_ASSISTANT_DISCOVERY].is()) { - bool value = src[S_MQTT][S_HOME_ASSISTANT_DISCOVERY].as(); - - if (value != dst.mqtt.homeAssistantDiscovery) { - dst.mqtt.homeAssistantDiscovery = value; - changed = true; - } - } - - - // emergency - if (!src[S_EMERGENCY][S_TRESHOLD_TIME].isNull()) { - unsigned short value = src[S_EMERGENCY][S_TRESHOLD_TIME].as(); - - if (value >= 60 && value <= 1800 && value != dst.emergency.tresholdTime) { - dst.emergency.tresholdTime = value; - changed = true; - } - } - } - - - // equitherm - if (src[S_EQUITHERM][S_ENABLED].is()) { - bool value = src[S_EQUITHERM][S_ENABLED].as(); - - if (!dst.opentherm.options.nativeOTC) { - if (value != dst.equitherm.enabled) { - dst.equitherm.enabled = value; - changed = true; - } - - } else if (dst.equitherm.enabled) { - dst.equitherm.enabled = false; - changed = true; - } - } - - if (!src[S_EQUITHERM][S_SLOPE].isNull()) { - float value = src[S_EQUITHERM][S_SLOPE].as(); - - if (value > 0.0f && value <= 10.0f && fabsf(value - dst.equitherm.slope) > 0.0001f) { - dst.equitherm.slope = roundf(value, 3); - changed = true; - } - } - - if (!src[S_EQUITHERM][S_EXPONENT].isNull()) { - float value = src[S_EQUITHERM][S_EXPONENT].as(); - - if (value > 0.0f && value <= 2.0f && fabsf(value - dst.equitherm.exponent) > 0.0001f) { - dst.equitherm.exponent = roundf(value, 3); - changed = true; - } - } - - if (!src[S_EQUITHERM][S_SHIFT].isNull()) { - float value = src[S_EQUITHERM][S_SHIFT].as(); - - if (value >= -15.0f && value <= 15.0f && fabsf(value - dst.equitherm.shift) > 0.0001f) { - dst.equitherm.shift = roundf(value, 2); - changed = true; - } - } - - if (!src[S_EQUITHERM][S_TARGET_DIFF_FACTOR].isNull()) { - float value = src[S_EQUITHERM][S_TARGET_DIFF_FACTOR].as(); - - if (value >= 0.0f && value <= 10.0f && fabsf(value - dst.equitherm.targetDiffFactor) > 0.0001f) { - dst.equitherm.targetDiffFactor = roundf(value, 3); - changed = true; - } - } - - - // pid - if (src[S_PID][S_ENABLED].is()) { - bool value = src[S_PID][S_ENABLED].as(); - - if (!dst.opentherm.options.nativeOTC) { - if (value != dst.pid.enabled) { - dst.pid.enabled = value; - changed = true; - } - - } else if (dst.pid.enabled) { - dst.pid.enabled = false; - changed = true; - } - } - - if (!src[S_PID][S_P_FACTOR].isNull()) { - float value = src[S_PID][S_P_FACTOR].as(); - - if (value > 0 && value <= 1000 && fabsf(value - dst.pid.p_factor) > 0.0001f) { - dst.pid.p_factor = roundf(value, 3); - changed = true; - } - } - - if (!src[S_PID][S_I_FACTOR].isNull()) { - float value = src[S_PID][S_I_FACTOR].as(); - - if (value >= 0 && value <= 100 && fabsf(value - dst.pid.i_factor) > 0.0001f) { - dst.pid.i_factor = roundf(value, 4); - changed = true; - } - } - - if (!src[S_PID][S_D_FACTOR].isNull()) { - float value = src[S_PID][S_D_FACTOR].as(); - - if (value >= 0 && value <= 100000 && fabsf(value - dst.pid.d_factor) > 0.0001f) { - dst.pid.d_factor = roundf(value, 1); - changed = true; - } - } - - if (!src[S_PID][S_DT].isNull()) { - unsigned short value = src[S_PID][S_DT].as(); - - if (value >= 30 && value <= 1800 && value != dst.pid.dt) { - dst.pid.dt = value; - changed = true; - } - } - - if (!src[S_PID][S_MIN_TEMP].isNull()) { - short value = src[S_PID][S_MIN_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, dst.equitherm.enabled ? -99.9f : 0.0f) && value != dst.pid.minTemp) { - dst.pid.minTemp = value; - changed = true; - } - } - - if (!src[S_PID][S_MAX_TEMP].isNull()) { - short value = src[S_PID][S_MAX_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem) && value != dst.pid.maxTemp) { - dst.pid.maxTemp = value; - changed = true; - } - } - - if (dst.pid.maxTemp < dst.pid.minTemp) { - dst.pid.maxTemp = dst.pid.minTemp; - changed = true; - } - - if (src[S_PID][S_DEADBAND][S_ENABLED].is()) { - bool value = src[S_PID][S_DEADBAND][S_ENABLED].as(); - - if (value != dst.pid.deadband.enabled) { - dst.pid.deadband.enabled = value; - changed = true; - } - } - - if (!src[S_PID][S_DEADBAND][S_P_MULTIPLIER].isNull()) { - float value = src[S_PID][S_DEADBAND][S_P_MULTIPLIER].as(); - - if (value >= 0 && value <= 1 && fabsf(value - dst.pid.deadband.p_multiplier) > 0.0001f) { - dst.pid.deadband.p_multiplier = roundf(value, 3); - changed = true; - } - } - - if (!src[S_PID][S_DEADBAND][S_I_MULTIPLIER].isNull()) { - float value = src[S_PID][S_DEADBAND][S_I_MULTIPLIER].as(); - - if (value >= 0 && value <= 1 && fabsf(value - dst.pid.deadband.i_multiplier) > 0.0001f) { - dst.pid.deadband.i_multiplier = roundf(value, 3); - changed = true; - } - } - - if (!src[S_PID][S_DEADBAND][S_D_MULTIPLIER].isNull()) { - float value = src[S_PID][S_DEADBAND][S_D_MULTIPLIER].as(); - - if (value >= 0 && value <= 1 && fabsf(value - dst.pid.deadband.d_multiplier) > 0.0001f) { - dst.pid.deadband.d_multiplier = roundf(value, 3); - changed = true; - } - } - - if (!src[S_PID][S_DEADBAND][S_THRESHOLD_HIGH].isNull()) { - float value = src[S_PID][S_DEADBAND][S_THRESHOLD_HIGH].as(); - - if (value >= 0.0f && value <= 5.0f && fabsf(value - dst.pid.deadband.thresholdHigh) > 0.0001f) { - dst.pid.deadband.thresholdHigh = roundf(value, 2); - changed = true; - } - } - - if (!src[S_PID][S_DEADBAND][S_THRESHOLD_LOW].isNull()) { - float value = src[S_PID][S_DEADBAND][S_THRESHOLD_LOW].as(); - - if (value >= 0.0f && value <= 5.0f && fabsf(value - dst.pid.deadband.thresholdLow) > 0.0001f) { - dst.pid.deadband.thresholdLow = roundf(value, 2); - changed = true; - } - } - - - // heating - if (src[S_HEATING][S_ENABLED].is()) { - bool value = src[S_HEATING][S_ENABLED].as(); - - if (value != dst.heating.enabled) { - dst.heating.enabled = value; - changed = true; - } - } - - if (src[S_HEATING][S_TURBO].is()) { - bool value = src[S_HEATING][S_TURBO].as(); - - if (value != dst.heating.turbo) { - dst.heating.turbo = value; - changed = true; - } - } - - if (src[S_HEATING][S_HYSTERESIS][S_ENABLED].is()) { - bool value = src[S_HEATING][S_HYSTERESIS][S_ENABLED].as(); - - if (value != dst.heating.hysteresis.enabled) { - dst.heating.hysteresis.enabled = value; - changed = true; - } - } - - if (!src[S_HEATING][S_HYSTERESIS][S_VALUE].isNull()) { - float value = src[S_HEATING][S_HYSTERESIS][S_VALUE].as(); - - if (value >= 0.0f && value <= 15.0f && fabsf(value - dst.heating.hysteresis.value) > 0.0001f) { - dst.heating.hysteresis.value = roundf(value, 2); - changed = true; - } - } - - if (!src[S_HEATING][S_TURBO_FACTOR].isNull()) { - float value = src[S_HEATING][S_TURBO_FACTOR].as(); - - if (value >= 1.5f && value <= 10.0f && fabsf(value - dst.heating.turboFactor) > 0.0001f) { - dst.heating.turboFactor = roundf(value, 3); - changed = true; - } - } - - if (!src[S_HEATING][S_MIN_TEMP].isNull()) { - unsigned char value = src[S_HEATING][S_MIN_TEMP].as(); - - if (value != dst.heating.minTemp && value >= vars.slave.heating.minTemp && value < vars.slave.heating.maxTemp && value != dst.heating.maxTemp) { - dst.heating.minTemp = value; - changed = true; - } - } - - if (!src[S_HEATING][S_MAX_TEMP].isNull()) { - unsigned char value = src[S_HEATING][S_MAX_TEMP].as(); - - if (value != dst.heating.maxTemp && value > vars.slave.heating.minTemp && value <= vars.slave.heating.maxTemp && value != dst.heating.minTemp) { - dst.heating.maxTemp = value; - changed = true; - } - } - - if (dst.heating.maxTemp < dst.heating.minTemp) { - dst.heating.maxTemp = dst.heating.minTemp; - changed = true; - } - - - if (!src[S_HEATING][S_MAX_MODULATION].isNull()) { - unsigned char value = src[S_HEATING][S_MAX_MODULATION].as(); - - if (value > 0 && value <= 100 && value != dst.heating.maxModulation) { - dst.heating.maxModulation = value; - changed = true; - } - } - - if (!src[S_HEATING][S_INDOOR_TEMP_AVG_TYPE].isNull()) { - uint8_t value = src[S_HEATING][S_INDOOR_TEMP_AVG_TYPE].as(); - - switch (value) { - case static_cast(Sensors::AverageType::MEAN): - case static_cast(Sensors::AverageType::MINIMUM): - case static_cast(Sensors::AverageType::MAXIMUM): - if (static_cast(dst.heating.indoorTempAvgType) != value) { - dst.heating.indoorTempAvgType = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - if (!src[S_HEATING][S_OUTDOOR_TEMP_AVG_TYPE].isNull()) { - uint8_t value = src[S_HEATING][S_OUTDOOR_TEMP_AVG_TYPE].as(); - - switch (value) { - case static_cast(Sensors::AverageType::MEAN): - case static_cast(Sensors::AverageType::MINIMUM): - case static_cast(Sensors::AverageType::MAXIMUM): - if (static_cast(dst.heating.outdoorTempAvgType) != value) { - dst.heating.outdoorTempAvgType = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - if (!src[S_HEATING][S_OVERHEAT_PROTECTION][S_HIGH_TEMP].isNull()) { - unsigned char value = src[S_HEATING][S_OVERHEAT_PROTECTION][S_HIGH_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 100.0f) && value != dst.heating.overheatProtection.highTemp) { - dst.heating.overheatProtection.highTemp = value; - changed = true; - } - } - - if (!src[S_HEATING][S_OVERHEAT_PROTECTION][S_LOW_TEMP].isNull()) { - unsigned char value = src[S_HEATING][S_OVERHEAT_PROTECTION][S_LOW_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 99.0f) && value != dst.heating.overheatProtection.lowTemp) { - dst.heating.overheatProtection.lowTemp = value; - changed = true; - } - } - - if (dst.heating.overheatProtection.highTemp < dst.heating.overheatProtection.lowTemp) { - dst.heating.overheatProtection.highTemp = dst.heating.overheatProtection.lowTemp; - changed = true; - } - - if (!src[S_HEATING][S_FREEZE_PROTECTION][S_HIGH_TEMP].isNull()) { - unsigned short value = src[S_HEATING][S_FREEZE_PROTECTION][S_HIGH_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, 1, 50) && value != dst.heating.freezeProtection.highTemp) { - dst.heating.freezeProtection.highTemp = value; - changed = true; - } - } - - if (!src[S_HEATING][S_FREEZE_PROTECTION][S_LOW_TEMP].isNull()) { - unsigned short value = src[S_HEATING][S_FREEZE_PROTECTION][S_LOW_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, 1, 30) && value != dst.heating.freezeProtection.lowTemp) { - dst.heating.freezeProtection.lowTemp = value; - changed = true; - } - } - - if (dst.heating.freezeProtection.highTemp < dst.heating.freezeProtection.lowTemp) { - dst.heating.freezeProtection.highTemp = dst.heating.freezeProtection.lowTemp; - changed = true; - } - - - // dhw - if (src[S_DHW][S_ENABLED].is()) { - bool value = src[S_DHW][S_ENABLED].as(); - - if (value != dst.dhw.enabled) { - dst.dhw.enabled = value; - changed = true; - } - } - - if (!src[S_DHW][S_MIN_TEMP].isNull()) { - unsigned char value = src[S_DHW][S_MIN_TEMP].as(); - - if (value >= vars.slave.dhw.minTemp && value < vars.slave.dhw.maxTemp && value != dst.dhw.minTemp) { - dst.dhw.minTemp = value; - changed = true; - } - } - - if (!src[S_DHW][S_MAX_TEMP].isNull()) { - unsigned char value = src[S_DHW][S_MAX_TEMP].as(); - - if (value > vars.slave.dhw.minTemp && value <= vars.slave.dhw.maxTemp && value != dst.dhw.maxTemp) { - dst.dhw.maxTemp = value; - changed = true; - } - } - - if (dst.dhw.maxTemp < dst.dhw.minTemp) { - dst.dhw.maxTemp = dst.dhw.minTemp; - changed = true; - } - - if (!src[S_DHW][S_MAX_MODULATION].isNull()) { - unsigned char value = src[S_DHW][S_MAX_MODULATION].as(); - - if (value > 0 && value <= 100 && value != dst.dhw.maxModulation) { - dst.dhw.maxModulation = value; - changed = true; - } - } - - if (!src[S_DHW][S_OVERHEAT_PROTECTION][S_HIGH_TEMP].isNull()) { - unsigned char value = src[S_DHW][S_OVERHEAT_PROTECTION][S_HIGH_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 100.0f) && value != dst.dhw.overheatProtection.highTemp) { - dst.dhw.overheatProtection.highTemp = value; - changed = true; - } - } - - if (!src[S_DHW][S_OVERHEAT_PROTECTION][S_LOW_TEMP].isNull()) { - unsigned char value = src[S_DHW][S_OVERHEAT_PROTECTION][S_LOW_TEMP].as(); - - if (isValidTemp(value, dst.system.unitSystem, 0.0f, 99.0f) && value != dst.dhw.overheatProtection.lowTemp) { - dst.dhw.overheatProtection.lowTemp = value; - changed = true; - } - } - - if (dst.dhw.overheatProtection.highTemp < dst.dhw.overheatProtection.lowTemp) { - dst.dhw.overheatProtection.highTemp = dst.dhw.overheatProtection.lowTemp; - changed = true; - } - - - if (!safe) { - // external pump - if (src[S_EXTERNAL_PUMP][S_USE].is()) { - bool value = src[S_EXTERNAL_PUMP][S_USE].as(); - - if (value != dst.externalPump.use) { - dst.externalPump.use = value; - changed = true; - } - } - - if (!src[S_EXTERNAL_PUMP][S_GPIO].isNull()) { - if (src[S_EXTERNAL_PUMP][S_GPIO].is() && src[S_EXTERNAL_PUMP][S_GPIO].as().size() == 0) { - if (dst.externalPump.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.externalPump.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_EXTERNAL_PUMP][S_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.externalPump.gpio) { - dst.externalPump.gpio = value; - changed = true; - } - } - } - - if (src[S_EXTERNAL_PUMP][S_INVERT_STATE].is()) { - bool value = src[S_EXTERNAL_PUMP][S_INVERT_STATE].as(); - - if (value != dst.externalPump.invertState) { - dst.externalPump.invertState = value; - changed = true; - } - } - - if (!src[S_EXTERNAL_PUMP][S_POST_CIRCULATION_TIME].isNull()) { - unsigned short value = src[S_EXTERNAL_PUMP][S_POST_CIRCULATION_TIME].as(); - - if (value >= 0 && value <= 120) { - value = value * 60; - - if (value != dst.externalPump.postCirculationTime) { - dst.externalPump.postCirculationTime = value; - changed = true; - } - } - } - - if (!src[S_EXTERNAL_PUMP][S_ANTI_STUCK_INTERVAL].isNull()) { - unsigned int value = src[S_EXTERNAL_PUMP][S_ANTI_STUCK_INTERVAL].as(); - - if (value >= 0 && value <= 366) { - value = value * 86400; - - if (value != dst.externalPump.antiStuckInterval) { - dst.externalPump.antiStuckInterval = value; - changed = true; - } - } - } - - if (!src[S_EXTERNAL_PUMP][S_ANTI_STUCK_TIME].isNull()) { - unsigned short value = src[S_EXTERNAL_PUMP][S_ANTI_STUCK_TIME].as(); - - if (value >= 0 && value <= 20) { - value = value * 60; - - if (value != dst.externalPump.antiStuckTime) { - dst.externalPump.antiStuckTime = value; - changed = true; - } - } - } - - - // cascade control - if (src[S_CASCADE_CONTROL][S_INPUT][S_ENABLED].is()) { - bool value = src[S_CASCADE_CONTROL][S_INPUT][S_ENABLED].as(); - - if (value != dst.cascadeControl.input.enabled) { - dst.cascadeControl.input.enabled = value; - changed = true; - } - } - - if (!src[S_CASCADE_CONTROL][S_INPUT][S_GPIO].isNull()) { - if (src[S_CASCADE_CONTROL][S_INPUT][S_GPIO].is() && src[S_CASCADE_CONTROL][S_INPUT][S_GPIO].as().size() == 0) { - if (dst.cascadeControl.input.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.cascadeControl.input.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_CASCADE_CONTROL][S_INPUT][S_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.cascadeControl.input.gpio) { - dst.cascadeControl.input.gpio = value; - changed = true; - } - } - } - - if (src[S_CASCADE_CONTROL][S_INPUT][S_INVERT_STATE].is()) { - bool value = src[S_CASCADE_CONTROL][S_INPUT][S_INVERT_STATE].as(); - - if (value != dst.cascadeControl.input.invertState) { - dst.cascadeControl.input.invertState = value; - changed = true; - } - } - - if (!src[S_CASCADE_CONTROL][S_INPUT][S_THRESHOLD_TIME].isNull()) { - unsigned short value = src[S_CASCADE_CONTROL][S_INPUT][S_THRESHOLD_TIME].as(); - - if (value >= 5 && value <= 600) { - if (value != dst.cascadeControl.input.thresholdTime) { - dst.cascadeControl.input.thresholdTime = value; - changed = true; - } - } - } - - if (src[S_CASCADE_CONTROL][S_OUTPUT][S_ENABLED].is()) { - bool value = src[S_CASCADE_CONTROL][S_OUTPUT][S_ENABLED].as(); - - if (value != dst.cascadeControl.output.enabled) { - dst.cascadeControl.output.enabled = value; - changed = true; - } - } - - if (!src[S_CASCADE_CONTROL][S_OUTPUT][S_GPIO].isNull()) { - if (src[S_CASCADE_CONTROL][S_OUTPUT][S_GPIO].is() && src[S_CASCADE_CONTROL][S_OUTPUT][S_GPIO].as().size() == 0) { - if (dst.cascadeControl.output.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.cascadeControl.output.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_CASCADE_CONTROL][S_OUTPUT][S_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.cascadeControl.output.gpio) { - dst.cascadeControl.output.gpio = value; - changed = true; - } - } - } - - if (src[S_CASCADE_CONTROL][S_OUTPUT][S_INVERT_STATE].is()) { - bool value = src[S_CASCADE_CONTROL][S_OUTPUT][S_INVERT_STATE].as(); - - if (value != dst.cascadeControl.output.invertState) { - dst.cascadeControl.output.invertState = value; - changed = true; - } - } - - if (!src[S_CASCADE_CONTROL][S_OUTPUT][S_THRESHOLD_TIME].isNull()) { - unsigned short value = src[S_CASCADE_CONTROL][S_OUTPUT][S_THRESHOLD_TIME].as(); - - if (value >= 5 && value <= 600) { - if (value != dst.cascadeControl.output.thresholdTime) { - dst.cascadeControl.output.thresholdTime = value; - changed = true; - } - } - } - - if (src[S_CASCADE_CONTROL][S_OUTPUT][S_ON_FAULT].is()) { - bool value = src[S_CASCADE_CONTROL][S_OUTPUT][S_ON_FAULT].as(); - - if (value != dst.cascadeControl.output.onFault) { - dst.cascadeControl.output.onFault = value; - changed = true; - } - } - - if (src[S_CASCADE_CONTROL][S_OUTPUT][S_ON_LOSS_CONNECTION].is()) { - bool value = src[S_CASCADE_CONTROL][S_OUTPUT][S_ON_LOSS_CONNECTION].as(); - - if (value != dst.cascadeControl.output.onLossConnection) { - dst.cascadeControl.output.onLossConnection = value; - changed = true; - } - } - - if (src[S_CASCADE_CONTROL][S_OUTPUT][S_ON_ENABLED_HEATING].is()) { - bool value = src[S_CASCADE_CONTROL][S_OUTPUT][S_ON_ENABLED_HEATING].as(); - - if (value != dst.cascadeControl.output.onEnabledHeating) { - dst.cascadeControl.output.onEnabledHeating = value; - changed = true; - } - } - } - - // force check emergency target - { - float value = !src[S_EMERGENCY][S_TARGET].isNull() ? src[S_EMERGENCY][S_TARGET].as() : dst.emergency.target; - bool noRegulators = !dst.opentherm.options.nativeOTC; - bool valid = isValidTemp( - value, - dst.system.unitSystem, - noRegulators ? dst.heating.minTemp : THERMOSTAT_INDOOR_MIN_TEMP, - noRegulators ? dst.heating.maxTemp : THERMOSTAT_INDOOR_MAX_TEMP, - noRegulators ? dst.system.unitSystem : UnitSystem::METRIC - ); - - if (!valid) { - value = convertTemp( - noRegulators ? DEFAULT_HEATING_TARGET_TEMP : THERMOSTAT_INDOOR_DEFAULT_TEMP, - UnitSystem::METRIC, - dst.system.unitSystem - ); - } - - if (fabsf(dst.emergency.target - value) > 0.0001f) { - dst.emergency.target = roundf(value, 2); - changed = true; - } - } - - // force check heating target - { - bool indoorTempControl = dst.equitherm.enabled || dst.pid.enabled || dst.opentherm.options.nativeOTC; - float minTemp = indoorTempControl ? THERMOSTAT_INDOOR_MIN_TEMP : dst.heating.minTemp; - float maxTemp = indoorTempControl ? THERMOSTAT_INDOOR_MAX_TEMP : dst.heating.maxTemp; - - float value = !src[S_HEATING][S_TARGET].isNull() - ? src[S_HEATING][S_TARGET].as() - : dst.heating.target; - bool valid = isValidTemp( - value, - dst.system.unitSystem, - minTemp, - maxTemp, - dst.system.unitSystem - ); - - if (!valid) { - value = convertTemp( - indoorTempControl ? THERMOSTAT_INDOOR_DEFAULT_TEMP : DEFAULT_HEATING_TARGET_TEMP, - UnitSystem::METRIC, - dst.system.unitSystem - ); - } - - if (fabsf(dst.heating.target - value) > 0.0001f) { - dst.heating.target = roundf(value, 2); - changed = true; - } - } - - // force check dhw target - { - float value = !src[S_DHW][S_TARGET].isNull() - ? src[S_DHW][S_TARGET].as() - : dst.dhw.target; - bool valid = isValidTemp( - value, - dst.system.unitSystem, - dst.dhw.minTemp, - dst.dhw.maxTemp, - dst.system.unitSystem - ); - - if (!valid) { - value = convertTemp(DEFAULT_DHW_TARGET_TEMP, UnitSystem::METRIC, dst.system.unitSystem); - } - - if (fabsf(dst.dhw.target - value) > 0.0001f) { - dst.dhw.target = value; - changed = true; - } - } - - return changed; -} - -inline bool safeJsonToSettings(const JsonVariantConst src, Settings& dst) { - return jsonToSettings(src, dst, true); -} - -void sensorSettingsToJson(const uint8_t sensorId, const Sensors::Settings& src, JsonVariant dst) { - dst[S_ID] = sensorId; - dst[S_ENABLED] = src.enabled; - dst[S_NAME] = src.name; - dst[S_PURPOSE] = static_cast(src.purpose); - dst[S_TYPE] = static_cast(src.type); - dst[S_GPIO] = src.gpio; - - if (src.type == Sensors::Type::DALLAS_TEMP) { - char addr[24]; - sprintf( - addr, - "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", - src.address[0], src.address[1], src.address[2], src.address[3], - src.address[4], src.address[5], src.address[6], src.address[7] - ); - dst[S_ADDRESS] = String(addr); - - } else if (src.type == Sensors::Type::BLUETOOTH) { - char addr[18]; - sprintf( - addr, - "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx", - src.address[0], src.address[1], src.address[2], - src.address[3], src.address[4], src.address[5] - ); - dst[S_ADDRESS] = String(addr); - - } else { - dst[S_ADDRESS] = ""; - } - - dst[S_OFFSET] = roundf(src.offset, 3); - dst[S_FACTOR] = roundf(src.factor, 3); - dst[S_FILTERING] = src.filtering; - dst[S_FILTERING_FACTOR] = roundf(src.filteringFactor, 3); -} - -bool jsonToSensorSettings(const uint8_t sensorId, const JsonVariantConst src, Sensors::Settings& dst) { - if (sensorId > Sensors::getMaxSensorId()) { - return false; - } - - bool changed = false; - - // enabled - if (src[S_ENABLED].is()) { - auto value = src[S_ENABLED].as(); - - if (value != dst.enabled) { - dst.enabled = value; - changed = true; - } - } - - // name - if (src[S_NAME].is() && src[S_NAME].as().size() < sizeof(dst.name)) { - auto value = src[S_NAME].as(); - Sensors::cleanName(value); - - if (value.length() < sizeof(dst.name) && !value.equals(dst.name)) { - strcpy(dst.name, value.c_str()); - changed = true; - } - } - - // purpose - if (!src[S_PURPOSE].isNull()) { - uint8_t value = src[S_PURPOSE].as(); - - switch (value) { - case static_cast(Sensors::Purpose::OUTDOOR_TEMP): - case static_cast(Sensors::Purpose::INDOOR_TEMP): - case static_cast(Sensors::Purpose::HEATING_TEMP): - case static_cast(Sensors::Purpose::HEATING_RETURN_TEMP): - case static_cast(Sensors::Purpose::DHW_TEMP): - case static_cast(Sensors::Purpose::DHW_RETURN_TEMP): - case static_cast(Sensors::Purpose::DHW_FLOW_RATE): - case static_cast(Sensors::Purpose::EXHAUST_TEMP): - case static_cast(Sensors::Purpose::MODULATION_LEVEL): - - case static_cast(Sensors::Purpose::NUMBER): - case static_cast(Sensors::Purpose::POWER_FACTOR): - case static_cast(Sensors::Purpose::POWER): - case static_cast(Sensors::Purpose::FAN_SPEED): - case static_cast(Sensors::Purpose::CO2): - case static_cast(Sensors::Purpose::PRESSURE): - case static_cast(Sensors::Purpose::HUMIDITY): - case static_cast(Sensors::Purpose::TEMPERATURE): - case static_cast(Sensors::Purpose::NOT_CONFIGURED): - if (static_cast(dst.purpose) != value) { - dst.purpose = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - // type - if (!src[S_TYPE].isNull()) { - uint8_t value = src[S_TYPE].as(); - - switch (value) { - case static_cast(Sensors::Type::OT_OUTDOOR_TEMP): - case static_cast(Sensors::Type::OT_HEATING_TEMP): - case static_cast(Sensors::Type::OT_HEATING_RETURN_TEMP): - case static_cast(Sensors::Type::OT_DHW_TEMP): - case static_cast(Sensors::Type::OT_DHW_TEMP2): - case static_cast(Sensors::Type::OT_DHW_FLOW_RATE): - case static_cast(Sensors::Type::OT_CH2_TEMP): - case static_cast(Sensors::Type::OT_EXHAUST_TEMP): - case static_cast(Sensors::Type::OT_HEAT_EXCHANGER_TEMP): - case static_cast(Sensors::Type::OT_PRESSURE): - case static_cast(Sensors::Type::OT_MODULATION_LEVEL): - case static_cast(Sensors::Type::OT_CURRENT_POWER): - case static_cast(Sensors::Type::OT_EXHAUST_CO2): - case static_cast(Sensors::Type::OT_EXHAUST_FAN_SPEED): - case static_cast(Sensors::Type::OT_SUPPLY_FAN_SPEED): - case static_cast(Sensors::Type::OT_SOLAR_STORAGE_TEMP): - case static_cast(Sensors::Type::OT_SOLAR_COLLECTOR_TEMP): - case static_cast(Sensors::Type::OT_FAN_SPEED_SETPOINT): - case static_cast(Sensors::Type::OT_FAN_SPEED_CURRENT): - - case static_cast(Sensors::Type::OT_BURNER_STARTS): - case static_cast(Sensors::Type::OT_DHW_BURNER_STARTS): - case static_cast(Sensors::Type::OT_HEATING_PUMP_STARTS): - case static_cast(Sensors::Type::OT_DHW_PUMP_STARTS): - case static_cast(Sensors::Type::OT_BURNER_HOURS): - case static_cast(Sensors::Type::OT_DHW_BURNER_HOURS): - case static_cast(Sensors::Type::OT_HEATING_PUMP_HOURS): - case static_cast(Sensors::Type::OT_DHW_PUMP_HOURS): - case static_cast(Sensors::Type::OT_COOLING_HOURS): - - case static_cast(Sensors::Type::NTC_10K_TEMP): - case static_cast(Sensors::Type::DALLAS_TEMP): - case static_cast(Sensors::Type::BLUETOOTH): - case static_cast(Sensors::Type::DHT11): - case static_cast(Sensors::Type::DHT22): - case static_cast(Sensors::Type::HEATING_SETPOINT_TEMP): - case static_cast(Sensors::Type::MANUAL): - case static_cast(Sensors::Type::NOT_CONFIGURED): - if (static_cast(dst.type) != value) { - dst.type = static_cast(value); - changed = true; - } - break; - - default: - break; - } - } - - // gpio - if (!src[S_GPIO].isNull()) { - if (dst.type != Sensors::Type::DALLAS_TEMP && dst.type != Sensors::Type::NTC_10K_TEMP && - dst.type != Sensors::Type::DHT11 && dst.type != Sensors::Type::DHT22) { - if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else if (src[S_GPIO].is() && src[S_GPIO].as().size() == 0) { - if (dst.gpio != GPIO_IS_NOT_CONFIGURED) { - dst.gpio = GPIO_IS_NOT_CONFIGURED; - changed = true; - } - - } else { - unsigned char value = src[S_GPIO].as(); - - if (GPIO_IS_VALID(value) && value != dst.gpio) { - dst.gpio = value; - changed = true; - } - } - } - - // address - if (!src[S_ADDRESS].isNull()) { - String value = src[S_ADDRESS].as(); - - 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) { - for (uint8_t i = 0; i < parsed; i++) { - if (dst.address[i] != tmp[i]) { - dst.address[i] = tmp[i]; - changed = true; - } - } - - } else { - // reset - for (uint8_t i = 0; i < sizeof(dst.address); i++) { - dst.address[i] = 0x00; - } - - 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) { - for (uint8_t i = 0; i < parsed; i++) { - if (dst.address[i] != tmp[i]) { - dst.address[i] = tmp[i]; - changed = true; - } - } - - } else { - // reset - for (uint8_t i = 0; i < sizeof(dst.address); i++) { - dst.address[i] = 0x00; - } - - changed = true; - } - } - } - - // offset - if (!src[S_OFFSET].isNull()) { - float value = src[S_OFFSET].as(); - - if (value >= -20.0f && value <= 20.0f && fabsf(value - dst.offset) > 0.0001f) { - dst.offset = roundf(value, 2); - changed = true; - } - } - - // factor - if (!src[S_FACTOR].isNull()) { - float value = src[S_FACTOR].as(); - - if (value > 0.09f && value <= 100.0f && fabsf(value - dst.factor) > 0.0001f) { - dst.factor = roundf(value, 3); - changed = true; - } - } - - // filtering - if (src[S_FILTERING].is()) { - auto value = src[S_FILTERING].as(); - - if (value != dst.filtering) { - dst.filtering = value; - changed = true; - } - } - - // filtering factor - if (!src[S_FILTERING_FACTOR].isNull()) { - float value = src[S_FILTERING_FACTOR].as(); - - if (value > 0 && value <= 1 && fabsf(value - dst.filteringFactor) > 0.0001f) { - dst.filteringFactor = roundf(value, 3); - changed = true; - } - } - - return changed; -} - -void sensorResultToJson(const uint8_t sensorId, JsonVariant dst) { - if (!Sensors::isValidSensorId(sensorId)) { - return; - } - - auto& sSensor = Sensors::settings[sensorId]; - auto& rSensor = Sensors::results[sensorId]; - - //dst[S_ID] = sensorId; - dst[S_CONNECTED] = rSensor.connected; - dst[S_SIGNAL_QUALITY] = rSensor.signalQuality; - - if (sSensor.type == Sensors::Type::BLUETOOTH) { - dst[S_TEMPERATURE] = roundf(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], 3); - dst[S_HUMIDITY] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); - dst[S_BATTERY] = roundf(rSensor.values[static_cast(Sensors::ValueType::BATTERY)], 1); - dst[S_RSSI] = roundf(rSensor.values[static_cast(Sensors::ValueType::RSSI)], 0); - - } else if (sSensor.type == Sensors::Type::DHT11 || sSensor.type == Sensors::Type::DHT22) { - dst[S_TEMPERATURE] = roundf(rSensor.values[static_cast(Sensors::ValueType::TEMPERATURE)], 3); - dst[S_HUMIDITY] = roundf(rSensor.values[static_cast(Sensors::ValueType::HUMIDITY)], 3); - - } else { - dst[S_VALUE] = roundf(rSensor.values[static_cast(Sensors::ValueType::PRIMARY)], 3); - } -} - -bool jsonToSensorResult(const uint8_t sensorId, const JsonVariantConst src) { - if (!Sensors::isValidSensorId(sensorId)) { - return false; - } - - auto& sSensor = Sensors::settings[sensorId]; - if (!sSensor.enabled || sSensor.type != Sensors::Type::MANUAL) { - return false; - } - - // value - if (!src[S_VALUE].isNull()) { - return Sensors::setValueById( - sensorId, - src[S_VALUE].as(), - Sensors::ValueType::PRIMARY, - true, - true - ); - } - - return false; -} - -void varsToJson(const Variables& src, JsonVariant dst) { - auto slave = dst[S_SLAVE].to(); - slave[S_MEMBER_ID] = src.slave.memberId; - slave[S_FLAGS] = src.slave.flags; - slave[S_TYPE] = src.slave.type; - slave[S_APP_VERSION] = src.slave.appVersion; - slave[S_PROTOCOL_VERSION] = src.slave.protocolVersion; - slave[S_CONNECTED] = src.slave.connected; - slave[S_FLAME] = src.slave.flame; - - auto sCooling = slave[S_COOLING].to(); - sCooling[S_ACTIVE] = src.slave.cooling.active; - sCooling[S_SETPOINT] = src.slave.cooling.setpoint; - - auto sModulation = slave[S_MODULATION].to(); - sModulation[S_MIN] = src.slave.modulation.min; - sModulation[S_MAX] = src.slave.modulation.max; - - auto sPower = slave[S_POWER].to(); - sPower[S_MIN] = roundf(src.slave.power.min, 2); - sPower[S_MAX] = roundf(src.slave.power.max, 2); - - auto sHeating = slave[S_HEATING].to(); - sHeating[S_ACTIVE] = src.slave.heating.active; - sHeating[S_MIN_TEMP] = src.slave.heating.minTemp; - sHeating[S_MAX_TEMP] = src.slave.heating.maxTemp; - - auto sDhw = slave[S_DHW].to(); - sDhw[S_ACTIVE] = src.slave.dhw.active; - sDhw[S_MIN_TEMP] = src.slave.dhw.minTemp; - sDhw[S_MAX_TEMP] = src.slave.dhw.maxTemp; - - auto sFault = slave[S_FAULT].to(); - sFault[S_ACTIVE] = src.slave.fault.active; - sFault[S_CODE] = src.slave.fault.code; - - auto sDiag = slave[S_DIAG].to(); - sDiag[S_ACTIVE] = src.slave.diag.active; - sDiag[S_CODE] = src.slave.diag.code; - - - auto master = dst[S_MASTER].to(); - auto mHeating = master[S_HEATING].to(); - mHeating[S_ENABLED] = src.master.heating.enabled; - mHeating[S_BLOCKING] = src.master.heating.blocking; - mHeating[S_INDOOR_TEMP_CONTROL] = src.master.heating.indoorTempControl; - mHeating[S_OVERHEAT] = src.master.heating.overheat; - mHeating[S_FREEZING] = src.master.heating.freezing; - mHeating[S_SETPOINT_TEMP] = roundf(src.master.heating.setpointTemp, 2); - mHeating[S_TARGET_TEMP] = roundf(src.master.heating.targetTemp, 2); - mHeating[S_CURRENT_TEMP] = roundf(src.master.heating.currentTemp, 2); - mHeating[S_RETURN_TEMP] = roundf(src.master.heating.returnTemp, 2); - mHeating[S_INDOOR_TEMP] = roundf(src.master.heating.indoorTemp, 2); - mHeating[S_OUTDOOR_TEMP] = roundf(src.master.heating.outdoorTemp, 2); - mHeating[S_MIN_TEMP] = roundf(src.master.heating.minTemp, 2); - mHeating[S_MAX_TEMP] = roundf(src.master.heating.maxTemp, 2); - - auto mDhw = master[S_DHW].to(); - mDhw[S_ENABLED] = src.master.dhw.enabled; - mDhw[S_OVERHEAT] = src.master.dhw.overheat; - mDhw[S_TARGET_TEMP] = roundf(src.master.dhw.targetTemp, 2); - mDhw[S_CURRENT_TEMP] = roundf(src.master.dhw.currentTemp, 2); - mDhw[S_RETURN_TEMP] = roundf(src.master.dhw.returnTemp, 2); - mDhw[S_MIN_TEMP] = settings.dhw.minTemp; - mDhw[S_MAX_TEMP] = settings.dhw.maxTemp; - - master[S_NETWORK][S_CONNECTED] = src.network.connected; - master[S_NETWORK][S_RSSI] = src.network.rssi; - master[S_MQTT][S_CONNECTED] = src.mqtt.connected; - master[S_EMERGENCY][S_STATE] = src.emergency.state; - master[S_EXTERNAL_PUMP][S_STATE] = src.externalPump.state; - - auto mCascadeControl = master[S_CASCADE_CONTROL].to(); - mCascadeControl[S_INPUT] = src.cascadeControl.input; - mCascadeControl[S_OUTPUT] = src.cascadeControl.output; - - master[S_UPTIME] = millis() / 1000; -} - -bool jsonToVars(const JsonVariantConst src, Variables& dst) { - bool changed = false; - - // actions - if (src[S_ACTIONS][S_RESTART].is() && src[S_ACTIONS][S_RESTART].as()) { - dst.actions.restart = true; - } - - if (src[S_ACTIONS][S_RESET_FAULT].is() && src[S_ACTIONS][S_RESET_FAULT].as()) { - dst.actions.resetFault = true; - } - - if (src[S_ACTIONS][S_RESET_DIAGNOSTIC].is() && src[S_ACTIONS][S_RESET_DIAGNOSTIC].as()) { - dst.actions.resetDiagnostic = true; - } - - return changed; -} diff --git a/tools/after_build_sdk.py b/tools/after_build_sdk.py new file mode 100644 index 0000000..db6e79c --- /dev/null +++ b/tools/after_build_sdk.py @@ -0,0 +1,51 @@ +"""Apply environment flags after SDK compile environments are prepared.""" + +from pathlib import Path +import re + +Import("env") + +build_frameworks = env.BuildFrameworks + + +def no_exception_link_flags(sdk_directory): + cmake = (Path(sdk_directory) / "components/cxx/CMakeLists.txt").read_text() + wrappers = re.findall(r"set\(WRAP_FUNCTIONS\s+([^)]*)\)", cmake, re.S) + forced = re.findall( + r'if\(NOT CONFIG_COMPILER_CXX_EXCEPTIONS\)\s+' + r'target_link_libraries\(\$\{COMPONENT_LIB\} INTERFACE "(-u [A-Za-z_][A-Za-z0-9_]*)"\)\s+endif\(\)', + cmake + ) + if len(wrappers) != 1 or len(forced) != 1: + raise RuntimeError("ESP-IDF C++ linker metadata changed; review tools/after_build_sdk.py") + + symbols = wrappers[0].split() + if (not symbols or len(symbols) != len(set(symbols)) + or not all(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", symbol) for symbol in symbols)): + raise RuntimeError("Unsupported ESP-IDF C++ wrapper list") + + return ["-Wl,--wrap=" + symbol for symbol in symbols] + forced[0].split() + + +def configure_after_build_sdk_flags(build_env, frameworks): + result = build_frameworks(frameworks) + + # SDK environments are already cloned; project libraries are configured later. + flags = build_env.GetProjectOption("custom_app_flags", "") + build_env.ProcessFlags(flags) + link_flags = build_env.GetProjectOption("custom_link_flags", "").split() + + sdkconfig = build_env.GetProjectOption("custom_sdkconfig", "") + if any(line.strip().strip("'\"") == "# CONFIG_COMPILER_CXX_EXCEPTIONS is not set" + for line in sdkconfig.splitlines()): + # HybridCompile does not transfer this component's interface linker flags. + sdk_directory = build_env.PioPlatform().get_package_dir("framework-espidf") + if not sdk_directory: + raise RuntimeError("ESP-IDF package is required for the C++ linker bridge") + link_flags += no_exception_link_flags(sdk_directory) + + build_env.Append(LINKFLAGS=link_flags) + return result + + +env.AddMethod(configure_after_build_sdk_flags, "BuildFrameworks") diff --git a/tools/build.py b/tools/build.py index dede5f9..baf6de0 100644 --- a/tools/build.py +++ b/tools/build.py @@ -6,17 +6,19 @@ Import("env") def post_build(source, target, env): copy_to_build_dir({ - source[0].get_abspath(): "firmware_%s_%s.bin" % (env["PIOENV"], env.GetProjectOption("version")), - env.subst("$BUILD_DIR/${PROGNAME}.factory.bin"): "firmware_%s_%s.factory.bin" % (env["PIOENV"], env.GetProjectOption("version")), - env.subst("$BUILD_DIR/${PROGNAME}.elf"): "firmware_%s_%s.elf" % (env["PIOENV"], env.GetProjectOption("version")) + source[0].get_abspath(): "firmware_%s_%s.bin" % (env["PIOENV"], env.GetProjectOption("custom_version")), + env.subst("$BUILD_DIR/${PROGNAME}.factory.bin"): "firmware_%s_%s.factory.bin" % (env["PIOENV"], env.GetProjectOption("custom_version")), + env.subst("$BUILD_DIR/${PROGNAME}.elf"): "firmware_%s_%s.elf" % (env["PIOENV"], env.GetProjectOption("custom_version")) }, os.path.join(env["PROJECT_DIR"], "build")); - env.Execute("pio run --target buildfs --environment %s" % env["PIOENV"]); + return env.Execute('"$PYTHONEXE" -m platformio run --target buildfs --environment "$PIOENV"') def before_buildfs(source, target, env): - env.Execute("npm install --silent") - env.Execute("npx gulp build_all --no-deprecation") + result = env.Execute("npm install --silent") + if result: + return result + return env.Execute("npx gulp build_all --no-deprecation") """ src = os.path.join(env["PROJECT_DIR"], "src_data") dst = os.path.join(env["PROJECT_DIR"], "data") @@ -40,7 +42,7 @@ def before_buildfs(source, target, env): def after_buildfs(source, target, env): copy_to_build_dir({ - source[0].get_abspath(): "filesystem_%s_%s.bin" % (env["PIOENV"], env.GetProjectOption("version")), + source[0].get_abspath(): "filesystem_%s_%s.bin" % (env["PIOENV"], env.GetProjectOption("custom_version")), }, os.path.join(env["PROJECT_DIR"], "build")); @@ -59,4 +61,4 @@ def copy_to_build_dir(files, build_dir): env.AddPostAction("buildprog", post_build) env.AddPreAction("$BUILD_DIR/spiffs.bin", before_buildfs) env.AddPreAction("$BUILD_DIR/littlefs.bin", before_buildfs) -env.AddPostAction("buildfs", after_buildfs) \ No newline at end of file +env.AddPostAction("buildfs", after_buildfs) diff --git a/tools/tinyusb_s2.py b/tools/tinyusb_s2.py new file mode 100644 index 0000000..242f671 --- /dev/null +++ b/tools/tinyusb_s2.py @@ -0,0 +1,64 @@ +"""Provide Arduino TinyUSB for the ESP32-S2 HybridCompile SDK.""" + +from pathlib import Path +import shutil +import subprocess + +Import("env") + + +def checkout(repository, revision, directory): + if not (directory / ".git").is_dir(): + subprocess.run(["git", "clone", "--filter=blob:none", "--no-checkout", + repository, str(directory)], check=True) + current = subprocess.run(["git", "-C", str(directory), "rev-parse", "HEAD"], + check=True, capture_output=True, text=True).stdout.strip() + if not current.startswith(revision): + subprocess.run(["git", "-C", str(directory), "checkout", "--detach", revision], check=True) + + +platform = env.PioPlatform() +project = Path(env.subst("$PROJECT_DIR")) +framework = Path(platform.get_package_dir("framework-arduinoespressif32")) +dummy = project / ".dummy" +sdk = Path(platform.get_package_dir("framework-arduinoespressif32-libs")) +versions = {} +for line in (sdk / "versions.txt").read_text(encoding="utf-8").splitlines(): + if ": " in line: + name, value = line.split(": ", 1) + versions[name] = value.split()[-1] + +builder_revision = versions["lib-builder"] +tinyusb_revision = versions["tinyusb"] +cache = project / ".pio/tinyusb-s2" +cache.mkdir(parents=True, exist_ok=True) +builder = cache / ("lib-builder-" + builder_revision) +tinyusb = cache / ("tinyusb-" + tinyusb_revision) +checkout("https://github.com/espressif/esp32-arduino-lib-builder.git", builder_revision, builder) +checkout("https://github.com/hathach/tinyusb.git", tinyusb_revision, tinyusb) + +original = builder / "components/arduino_tinyusb" +component = cache / ("component-" + builder_revision + "-" + tinyusb_revision) / "arduino_tinyusb" +cmake_file = component / "CMakeLists.txt" +if not cmake_file.is_file(): + component.mkdir(parents=True, exist_ok=True) + shutil.copytree(original / "include", component / "include", dirs_exist_ok=True) + shutil.copytree(tinyusb / "src", component / "tinyusb/src", dirs_exist_ok=True) + shutil.copytree(tinyusb / "hw/bsp", component / "tinyusb/hw/bsp", dirs_exist_ok=True) + shutil.copyfile(original / "Kconfig.projbuild", component / "Kconfig.projbuild") + +# Adapt only the generated build description to HybridCompile component names. +cmake = (original / "CMakeLists.txt").read_text(encoding="utf-8") +requires = "set(priv_requires arduino main)" +if requires not in cmake: + raise RuntimeError("Unsupported Arduino TinyUSB component dependencies") +cmake = cmake.replace(requires, f"set(priv_requires {framework.name} {dummy.name})") +if not cmake_file.is_file() or cmake_file.read_text(encoding="utf-8") != cmake: + cmake_file.write_text(cmake, encoding="utf-8") + +# Keep HybridCompile's two default components when extending the CMake list. +dummy.mkdir(exist_ok=True) +directories = [dummy, framework, component] +arguments = env.BoardConfig().get("build.cmake_extra_args", "") or "" +arguments += ' "-DEXTRA_COMPONENT_DIRS:PATH=' + ";".join(path.as_posix() for path in directories) + '"' +env.BoardConfig().update("build.cmake_extra_args", arguments.strip())