[safe_mode] Conditionally compile callback when on_safe_mode is configured

This commit is contained in:
J. Nick Koston
2026-01-10 20:34:05 -10:00
parent a1395af763
commit a30d12fb89
5 changed files with 17 additions and 3 deletions

View File

@@ -59,9 +59,11 @@ async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
for conf in config.get(CONF_ON_SAFE_MODE, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
if on_safe_mode_config := config.get(CONF_ON_SAFE_MODE):
cg.add_define("USE_SAFE_MODE_CALLBACK")
for conf in on_safe_mode_config:
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
condition = var.should_enter_safe_mode(
config[CONF_NUM_ATTEMPTS],

View File

@@ -1,4 +1,7 @@
#pragma once
#include "esphome/core/defines.h"
#ifdef USE_SAFE_MODE_CALLBACK
#include "safe_mode.h"
#include "esphome/core/automation.h"
@@ -15,3 +18,5 @@ class SafeModeTrigger : public Trigger<> {
} // namespace safe_mode
} // namespace esphome
#endif // USE_SAFE_MODE_CALLBACK

View File

@@ -126,7 +126,9 @@ bool SafeModeComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t en
ESP_LOGW(TAG, "SAFE MODE IS ACTIVE");
#ifdef USE_SAFE_MODE_CALLBACK
this->safe_mode_callback_.call();
#endif
return true;
}

View File

@@ -25,9 +25,11 @@ class SafeModeComponent : public Component {
void on_safe_shutdown() override;
#ifdef USE_SAFE_MODE_CALLBACK
void add_on_safe_mode_callback(std::function<void()> &&callback) {
this->safe_mode_callback_.add(std::move(callback));
}
#endif
protected:
void write_rtc_(uint32_t val);
@@ -43,7 +45,9 @@ class SafeModeComponent : public Component {
uint8_t safe_mode_num_attempts_{0};
// Larger objects at the end
ESPPreferenceObject rtc_;
#ifdef USE_SAFE_MODE_CALLBACK
CallbackManager<void()> safe_mode_callback_{};
#endif
static const uint32_t ENTER_SAFE_MODE_MAGIC =
0x5afe5afe; ///< a magic number to indicate that safe mode should be entered on next boot

View File

@@ -100,6 +100,7 @@
#define USE_OUTPUT
#define USE_POWER_SUPPLY
#define USE_QR_CODE
#define USE_SAFE_MODE_CALLBACK
#define USE_SELECT
#define USE_SENSOR
#define USE_STATUS_LED