#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE #include #include "StructSnapshot.h" #include "StructTimestampMap.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static std::unique_ptr mqttClient; // Keep the applied prefix separate from settings until MQTT is reconfigured. static std::string mqttPrefix; // NOLINT(runtime/string) static std::atomic mqttConnectedAt{0}; static unsigned long mqttPublishedSensorAt[SENSORS_AMOUNT] = {}; // Only App accesses snapshots and the sorted publication timestamps. static StructSnapshot settingsSnapshot(settings); static StructSnapshot varsSnapshot(vars); static StructTimestampMap<96> mqttPublishTimes; static std::atomic mqttRefreshRequested{false}; static std::atomic mqttHaRefreshRequested{false}; // Discovery and its synchronous publisher run only on App. 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 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 bool publishValue(const std::string& topic, std::string_view value) { const bool published = mqttClient->publish(topic.c_str(), value, true); ESP_LOGD( L_MQTT, "%s publish topic: %s, value: %.*s", published ? "Successfully" : "Failed", topic.c_str(), static_cast(value.size()), value.empty() ? "" : value.data() ); return published; } static bool publishValue(const std::string& topic, const char* value) { return publishValue(topic, std::string_view(value)); } static bool publishValue(const std::string& topic, bool value) { return publishValue(topic, value ? S_TRUE : S_FALSE); } static bool publishValue(const std::string& topic, float value, uint8_t decimals = 2) { if (!std::isfinite(value)) { // Remove an obsolete retained reading instead of publishing nan/inf. return publishValue(topic, ""); } char payload[64]; const int length = snprintf(payload, sizeof(payload), "%.*f", decimals, value); if (length < 0 || static_cast(length) >= sizeof(payload)) { return false; } if (decimals) { char* end = payload + length - 1; while (*end == '0') { *end-- = '\0'; } if (*end == '.') { *end = '\0'; } } return publishValue(topic, payload); } static void collectMqttChanges() { if (mqttRefreshRequested.exchange(false)) { mqttPublishTimes.resetAll(); } if (!settingsSnapshot.equals(&settings.system.unitSystem)) { mqttPublishTimes.reset({ &settings.heating.target, &settings.heating.minTemp, &settings.heating.maxTemp, &settings.heating.overheatProtection.highTemp, &settings.heating.overheatProtection.lowTemp, &settings.heating.freezeProtection.highTemp, &settings.heating.freezeProtection.lowTemp, &settings.dhw.target, &settings.dhw.minTemp, &settings.dhw.maxTemp, &settings.dhw.overheatProtection.highTemp, &settings.dhw.overheatProtection.lowTemp, &settings.pid.minTemp, &settings.pid.maxTemp, &settings.emergency.target }); mqttPublishTimes.reset({ &vars.slave.heating.minTemp, &vars.slave.heating.maxTemp, &vars.slave.dhw.minTemp, &vars.slave.dhw.maxTemp, &vars.master.heating.setpointTemp, &vars.master.heating.targetTemp, &vars.master.heating.currentTemp, &vars.master.heating.returnTemp, &vars.master.heating.indoorTemp, &vars.master.heating.outdoorTemp, &vars.master.heating.minTemp, &vars.master.heating.maxTemp, &vars.master.dhw.targetTemp, &vars.master.dhw.currentTemp, &vars.master.dhw.returnTemp, &vars.master.dhw.minTemp, &vars.master.dhw.maxTemp }); settingsSnapshot.set(&settings.system.unitSystem); } if (!settingsSnapshot.equals(&settings.equitherm.enabled)) { mqttPublishTimes.reset({&settings.pid.minTemp, &settings.pid.maxTemp}); } } template static bool publishField( StructSnapshot& snapshot, const Field* field, unsigned long intervalMs, Publish publish, float tolerance = 0.0001f ) { const unsigned long now = millis(); unsigned long& lastPublishAt = mqttPublishTimes.get(field); if (lastPublishAt != 0 && now - lastPublishAt < intervalMs && snapshot.equals(field, tolerance)) { return false; } const Field value = *field; if (publish(value)) { lastPublishAt = now; snapshot.set(field, &value); } // A failed send still consumes this pass; unchanged state allows a retry. return true; } template static bool publishField( StructSnapshot& snapshot, const Field* field, unsigned long intervalMs, const char* topicSuffix ) { return publishField(snapshot, field, intervalMs, [topicSuffix](const Field& value) { const auto topic = mqttTopic(topicSuffix); if constexpr (std::is_enum_v) { return publishValue(topic, std::to_string(static_cast>(value))); } else if constexpr (std::is_integral_v && !std::is_same_v) { return publishValue(topic, std::to_string(value)); } else { return publishValue(topic, value); } }); } static bool publishHeatingSettings(unsigned long intervalMs) { bool published = publishField(settingsSnapshot, &settings.heating.enabled, intervalMs, "settings/heating/enabled"); if (published) { return true; } published = publishField(settingsSnapshot, &settings.heating.turbo, intervalMs, "settings/heating/turbo"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.target, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/target"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.heating.hysteresis.enabled, intervalMs, "settings/heating/hysteresis/enabled"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.hysteresis.value, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/hysteresis/value"), value, 3 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.turboFactor, intervalMs, [](float value) { return publishValue(mqttTopic("settings/heating/turbo_factor"), value, 3); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/min_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/max_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.heating.maxModulation, intervalMs, "settings/heating/max_modulation"); if (published) { return true; } published = publishField(settingsSnapshot, &settings.heating.indoorTempAvgType, intervalMs, "settings/heating/indoor_temp_avg_type"); if (published) { return true; } published = publishField(settingsSnapshot, &settings.heating.outdoorTempAvgType, intervalMs, "settings/heating/outdoor_temp_avg_type"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.overheatProtection.highTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/overheat_protection/high_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.overheatProtection.lowTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/overheat_protection/low_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.freezeProtection.highTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/freeze_protection/high_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.heating.freezeProtection.lowTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/heating/freeze_protection/low_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } return false; } static bool publishDhwSettings(unsigned long intervalMs) { bool published = publishField(settingsSnapshot, &settings.dhw.enabled, intervalMs, "settings/dhw/enabled"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.dhw.target, intervalMs, [](float value) { return publishValue( mqttTopic("settings/dhw/target"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 1 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.dhw.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/dhw/min_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.dhw.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/dhw/max_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.dhw.maxModulation, intervalMs, "settings/dhw/max_modulation"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.dhw.overheatProtection.highTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/dhw/overheat_protection/high_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.dhw.overheatProtection.lowTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/dhw/overheat_protection/low_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } return false; } static bool publishPidSettings(unsigned long intervalMs) { bool published = publishField(settingsSnapshot, &settings.pid.enabled, intervalMs, "settings/pid/enabled"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.p_factor, intervalMs, [](float value) { return publishValue(mqttTopic("settings/pid/p_factor"), value, 3); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.i_factor, intervalMs, [](float value) { return publishValue(mqttTopic("settings/pid/i_factor"), value, 4); }, 0.00005f ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.d_factor, intervalMs, [](float value) { return publishValue(mqttTopic("settings/pid/d_factor"), value, 1); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.pid.dt, intervalMs, "settings/pid/dt"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/pid/min_temp"), settings.equitherm.enabled ? value : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("settings/pid/max_temp"), settings.equitherm.enabled ? value : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.pid.deadband.enabled, intervalMs, "settings/pid/deadband/enabled"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.deadband.p_multiplier, intervalMs, [](float value) { return publishValue( mqttTopic("settings/pid/deadband/p_multiplier"), value, 3 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.deadband.i_multiplier, intervalMs, [](float value) { return publishValue( mqttTopic("settings/pid/deadband/i_multiplier"), value, 3 ); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.pid.deadband.d_multiplier, intervalMs, [](float value) { return publishValue( mqttTopic("settings/pid/deadband/d_multiplier"), value, 3 ); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.pid.deadband.thresholdHigh, intervalMs, "settings/pid/deadband/threshold_high"); if (published) { return true; } published = publishField(settingsSnapshot, &settings.pid.deadband.thresholdLow, intervalMs, "settings/pid/deadband/threshold_low"); if (published) { return true; } return false; } static bool publishEquithermSettings(unsigned long intervalMs) { bool published = publishField(settingsSnapshot, &settings.equitherm.enabled, intervalMs, "settings/equitherm/enabled"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.equitherm.slope, intervalMs, [](float value) { return publishValue(mqttTopic("settings/equitherm/slope"), value, 3); } ); if (published) { return true; } published = publishField( settingsSnapshot, &settings.equitherm.exponent, intervalMs, [](float value) { return publishValue(mqttTopic("settings/equitherm/exponent"), value, 3); } ); if (published) { return true; } published = publishField(settingsSnapshot, &settings.equitherm.shift, intervalMs, "settings/equitherm/shift"); if (published) { return true; } published = publishField( settingsSnapshot, &settings.equitherm.targetDiffFactor, intervalMs, [](float value) { return publishValue( mqttTopic("settings/equitherm/target_diff_factor"), value, 3 ); } ); if (published) { return true; } return false; } static bool publishEmergencySettings(unsigned long intervalMs) { bool published = publishField(settingsSnapshot, &settings.emergency.target, intervalMs, [](float value) { return publishValue( mqttTopic("settings/emergency/target"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); }); return published; } static bool publishSlaveState(unsigned long intervalMs) { bool published = publishField(varsSnapshot, &vars.slave.memberId, intervalMs, "state/slave/member_id"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.flags, intervalMs, "state/slave/flags"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.type, intervalMs, "state/slave/type"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.appVersion, intervalMs, "state/slave/app_version"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.protocolVersion, intervalMs, "state/slave/protocol_version"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.connected, intervalMs, "state/slave/connected"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.flame, intervalMs, "state/slave/flame"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.cooling.active, intervalMs, "state/slave/cooling/active"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.cooling.setpoint, intervalMs, "state/slave/cooling/setpoint"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.modulation.min, intervalMs, "state/slave/modulation/min"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.modulation.max, intervalMs, "state/slave/modulation/max"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.power.min, intervalMs, "state/slave/power/min"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.power.max, intervalMs, "state/slave/power/max"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.heating.active, intervalMs, "state/slave/heating/active"); if (published) { return true; } published = publishField( varsSnapshot, &vars.slave.heating.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/slave/heating/min_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.slave.heating.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/slave/heating/max_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.dhw.active, intervalMs, "state/slave/dhw/active"); if (published) { return true; } published = publishField( varsSnapshot, &vars.slave.dhw.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/slave/dhw/min_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.slave.dhw.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/slave/dhw/max_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.fault.active, intervalMs, "state/slave/fault/active"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.fault.code, intervalMs, "state/slave/fault/code"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.diag.active, intervalMs, "state/slave/diag/active"); if (published) { return true; } published = publishField(varsSnapshot, &vars.slave.diag.code, intervalMs, "state/slave/diag/code"); if (published) { return true; } return false; } static bool publishMasterState(unsigned long intervalMs) { const unsigned long now = millis(); { static unsigned long lastPublishAt = 0; if (now - lastPublishAt >= intervalMs) { publishValue(mqttTopic("state/master/uptime"), std::to_string(now / 1000u)); lastPublishAt = now; // force return true; } } bool published = publishField(varsSnapshot, &vars.master.heating.enabled, intervalMs, "state/master/heating/enabled"); if (published) { return true; } published = publishField(varsSnapshot, &vars.master.heating.blocking, intervalMs, "state/master/heating/blocking"); if (published) { return true; } published = publishField(varsSnapshot, &vars.master.heating.smartControl, intervalMs, "state/master/heating/smart_control"); if (published) { return true; } published = publishField(varsSnapshot, &vars.master.heating.overheat, intervalMs, "state/master/heating/overheat"); if (published) { return true; } published = publishField(varsSnapshot, &vars.master.heating.freezing, intervalMs, "state/master/heating/freezing"); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.setpointTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/setpoint_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.targetTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/target_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.currentTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/current_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.returnTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/return_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.indoorTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/indoor_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.outdoorTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/outdoor_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/min_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.heating.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/heating/max_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(varsSnapshot, &vars.master.dhw.enabled, intervalMs, "state/master/dhw/enabled"); if (published) { return true; } published = publishField(varsSnapshot, &vars.master.dhw.overheat, intervalMs, "state/master/dhw/overheat"); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.dhw.targetTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/dhw/target_temp"), value == 0 ? 0 : convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.dhw.currentTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/dhw/current_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.dhw.returnTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/dhw/return_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.dhw.minTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/dhw/min_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField( varsSnapshot, &vars.master.dhw.maxTemp, intervalMs, [](float value) { return publishValue( mqttTopic("state/master/dhw/max_temp"), convertTemp(value, UnitSystem::METRIC, settings.system.unitSystem), 2 ); } ); if (published) { return true; } published = publishField(varsSnapshot, &vars.network.rssi, intervalMs, "state/master/network/rssi"); if (published) { return true; } published = publishField(varsSnapshot, &vars.emergency.state, intervalMs, "state/master/emergency/state"); if (published) { return true; } published = publishField(varsSnapshot, &vars.externalPump.state, intervalMs, "state/master/ext_pump/state"); if (published) { return true; } published = publishField(varsSnapshot, &vars.cascadeControl.input, intervalMs, "state/master/cascade_control/input"); if (published) { return true; } published = publishField(varsSnapshot, &vars.cascadeControl.output, intervalMs, "state/master/cascade_control/output"); if (published) { return true; } return false; } static void publishState(unsigned long intervalMs) { const unsigned long now = millis(); { static unsigned long lastPublishAt = 0; if (now - lastPublishAt >= 5000UL) { publishValue(mqttTopic("status"), "online"); lastPublishAt = now; // force return; } } publishSlaveState(intervalMs); publishMasterState(intervalMs); } 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 bool publishSensor(const Sensors::Settings& sensor, const Sensors::Result& result) { if (!sensor.slug[0]) { return false; } if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_CONNECTED), result.connected)) { return false; } if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DALLAS_TEMP || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_SIGNAL_QUALITY), std::to_string(result.signalQuality))) { return false; } } if (sensor.type == Sensors::Type::BLUETOOTH || sensor.type == Sensors::Type::DHT11 || sensor.type == Sensors::Type::DHT22) { const bool published = publishValue( mqttTopic(S_SENSORS, sensor.slug, S_TEMPERATURE), convertTemp( result.values[static_cast(Sensors::ValueType::TEMPERATURE)], UnitSystem::METRIC, settings.system.unitSystem ), 3 ); if (!published) { return false; } if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_HUMIDITY), result.values[static_cast(Sensors::ValueType::HUMIDITY)], 3)) { return false; } if (sensor.type == Sensors::Type::BLUETOOTH) { if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_BATTERY), result.values[static_cast(Sensors::ValueType::BATTERY)], 1)) { return false; } if (!publishValue(mqttTopic(S_SENSORS, sensor.slug, S_RSSI), result.values[static_cast(Sensors::ValueType::RSSI)], 0)) { return false; } } } else { const bool published = 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 ); if (!published) { return false; } } return true; } 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); mqttHaPendingEntities.reset(); mqttHaPendingSensors.reset(); if (!destroy) { return; } if (mqttPublishSettingsTask) { appTaskManager.removeTask(*mqttPublishSettingsTask); delete mqttPublishSettingsTask; mqttPublishSettingsTask = nullptr; } if (mqttPublishStateTask) { appTaskManager.removeTask(*mqttPublishStateTask); delete mqttPublishStateTask; mqttPublishStateTask = nullptr; } if (mqttPublishSensorsTask) { appTaskManager.removeTask(*mqttPublishSensorsTask); delete mqttPublishSensorsTask; mqttPublishSensorsTask = nullptr; } if (mqttReconfigureSensorsTask) { appTaskManager.removeTask(*mqttReconfigureSensorsTask); delete mqttReconfigureSensorsTask; mqttReconfigureSensorsTask = nullptr; } if (mqttPublishHaTask) { appTaskManager.removeTask(*mqttPublishHaTask); delete mqttPublishHaTask; mqttPublishHaTask = nullptr; } haDiscovery.reset(); mqttClient.reset(); 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() { 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); if (payload.size() >= 32) { ESP_LOGW( L_MQTT_MSG, "Unsupported or invalid setting command: '%.*s'", static_cast(payload.size()), payload.data() ); return; } 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: '%.*s'", static_cast(payload.size()), payload.empty() ? "" : payload.data() ); 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 payload = trimPayload(message); if (payload.size() >= 32) { ESP_LOGW( L_MQTT_MSG, "Invalid manual sensor value: '%.*s'", static_cast(payload.size()), payload.data() ); return; } const auto parsed = parseNumber(payload); if (!parsed) { ESP_LOGW( L_MQTT_MSG, "Invalid manual sensor value: '%.*s'", static_cast(payload.size()), payload.empty() ? "" : payload.data() ); 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 = std::make_unique(); 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()); mqttRefreshRequested.store(true); 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"); }); } // Update the local subscriptions; MQTT applies them when connected. if (mqttPrefix != settings.mqtt.prefix || !haDiscovery) { for (const auto& topic : mqttClient->getSubscribedTopics()) { mqttClient->unsubscribe(topic.c_str()); } mqttPrefix = settings.mqtt.prefix; subscribe(); } // Apply the current device metadata and MQTT prefix. HA::Device haDevice{ .id = mqttPrefix, .name = PROJECT_NAME, .version = BUILD_VERSION, .model = PROJECT_NAME, .manufacturer = PROJECT_REPO, .url = std::string("http://") + getNetworkIp().toString().c_str() + "/", }; // Create or update existing discovery if (!haDiscovery) { haDiscovery = std::make_unique( std::move(haDevice), mqttPrefix, [](const char* topic, const std::string& payload) { return mqttClient->publish(topic, payload, true) ? HA::Error::SUCCESS : HA::Error::ERR_MQTT_PUBLISHER; } ); haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); haDiscovery->setWillTopic("~/status"); } else { haDiscovery->setDevice(std::move(haDevice)); haDiscovery->setBaseTopic(mqttPrefix); } // Start the connection after configuring discovery and subscriptions. 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 = settings.mqtt.prefix, .willTopic = mqttTopic("status"), }); } Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) { if (!settings.mqtt.enabled) { stopMqtt(true); return; } if (!mqttPublishSettingsTask) { auto* task = new Task("Publish MQTT settings", [](void*) { const unsigned long intervalMs = settings.mqtt.interval * 1000UL; collectMqttChanges(); if (publishEmergencySettings(intervalMs)) { return; } if (publishHeatingSettings(intervalMs)) { return; } if (publishDhwSettings(intervalMs)) { return; } if (publishEquithermSettings(intervalMs)) { return; } if (publishPidSettings(intervalMs)) { return; } }); task->setInterval(50).setEnabledWhen(isMqttReadyForPublish); appTaskManager.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*) { const unsigned long intervalMs = settings.mqtt.interval * 1000UL; collectMqttChanges(); publishState(intervalMs); }); task->setInterval(50).setEnabledWhen(isMqttReadyForPublish); appTaskManager.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 smartControl = vars.master.heating.smartControl; 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); } // Apply the new discovery prefix and request a full HA refresh. if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) { const auto statusTopic = haDiscovery->getDiscoveryTopic() + "/status"; mqttClient->unsubscribe(statusTopic.c_str()); haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); 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) { interval = settings.mqtt.interval; 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 (smartControl != vars.master.heating.smartControl) { smartControl = vars.master.heating.smartControl; 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)) { const auto statusTopic = haDiscovery->getDiscoveryTopic() + "/status"; const auto topics = mqttClient->getSubscribedTopics(); const bool subscribed = std::find(topics.begin(), topics.end(), statusTopic) != topics.end(); if (settings.mqtt.homeAssistantDiscovery && !subscribed) { mqttClient->subscribe(statusTopic, [](const std::string&, const std::string_view& message) { if (message == "online") { mqttHaRefreshRequested.store(true); } }); } else if (!settings.mqtt.homeAssistantDiscovery && subscribed) { mqttClient->unsubscribe(statusTopic.c_str()); } mqttHaPendingEntities.set(); mqttHaPendingSensors.set(); } for (size_t index = 0; index < mqttHaPendingEntities.size(); index++) { if (!mqttHaPendingEntities.test(index)) { continue; } const bool published = publishHaEntity(static_cast(index), !settings.mqtt.homeAssistantDiscovery); if (published) { mqttHaPendingEntities.reset(index); } else { ESP_LOGD(L_MQTT, "HA publication deferred"); } break; } 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); appTaskManager.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*) { if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) { return; } 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); appTaskManager.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; } if (!publishSensor(snapshot->settings, snapshot->result)) { { std::lock_guard lock(mqttSensorsMutex); mqttPublishedSensorAt[sensorId] = 0; } ESP_LOGD(L_MQTT, "Sensor publication deferred"); } } }); task->setInterval(500).setEnabledWhen([] { if (!isMqttReadyForPublish()) { return false; } std::lock_guard lock(mqttSensorsMutex); return mqttSensorChanges.empty(); }); appTaskManager.addTask(*task); std::lock_guard lock(mqttMutex); mqttPublishSensorsTask = task; } // 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() { onNetworkEvent([](NetworkEvent event) { if (event == NetworkEvent::CONNECTED || event == NetworkEvent::DISCONNECTED || event == NetworkEvent::EVENTS_OVERFLOW) { requestReconfigureMqtt(); } }); // Keep only the configuration dispatcher when MQTT publications are disabled. mqttConfigureTask.pause().setEnabledWhen([] { return !upgrading && !restartTask.scheduled() && !restartTask.active(); }); appTaskManager.addTask(mqttConfigureTask); }