ESPHome 2026.2.4
Loading...
Searching...
No Matches
safe_mode.cpp
Go to the documentation of this file.
1#include "safe_mode.h"
2
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6#include "esphome/core/util.h"
7
8#include <cerrno>
9#include <cinttypes>
10#include <cstdio>
11
12#if defined(USE_ESP32) && defined(USE_OTA_ROLLBACK)
13#include <esp_ota_ops.h>
14#include <esp_system.h>
15#endif
16
17namespace esphome::safe_mode {
18
19static const char *const TAG = "safe_mode";
20
22 ESP_LOGCONFIG(TAG,
23 "Safe Mode:\n"
24 " Successful after: %" PRIu32 "s\n"
25 " Invoke after: %u attempts\n"
26 " Duration: %" PRIu32 "s",
27 this->safe_mode_boot_is_good_after_ / 1000, // because milliseconds
29 this->safe_mode_enable_time_ / 1000); // because milliseconds
30#if defined(USE_ESP32) && defined(USE_OTA_ROLLBACK)
31 const char *state_str;
32 if (this->ota_state_ == ESP_OTA_IMG_NEW) {
33 state_str = "not supported";
34 } else if (this->ota_state_ == ESP_OTA_IMG_PENDING_VERIFY) {
35 state_str = "supported";
36 } else {
37 state_str = "support unknown";
38 }
39 ESP_LOGCONFIG(TAG, " Bootloader rollback: %s", state_str);
40#endif
41
43 auto remaining_restarts = this->safe_mode_num_attempts_ - this->safe_mode_rtc_value_;
44 if (remaining_restarts) {
45 ESP_LOGW(TAG, "Last reset too quick; invoke in %" PRIu32 " restarts", remaining_restarts);
46 } else {
47 ESP_LOGW(TAG, "SAFE MODE IS ACTIVE");
48 }
49 }
50
51#if defined(USE_ESP32) && defined(USE_OTA_ROLLBACK)
52 const esp_partition_t *last_invalid = esp_ota_get_last_invalid_partition();
53 if (last_invalid != nullptr) {
54 ESP_LOGW(TAG,
55 "OTA rollback detected! Rolled back from partition '%s'\n"
56 "The device reset before the boot was marked successful",
57 last_invalid->label);
58 if (esp_reset_reason() == ESP_RST_BROWNOUT) {
59 ESP_LOGW(TAG, "Last reset was due to brownout - check your power supply!\n"
60 "See https://esphome.io/guides/faq.html#brownout-detector-was-triggered");
61 }
62 }
63#endif
64}
65
67
70 // successful boot, reset counter
71 ESP_LOGI(TAG, "Boot seems successful; resetting boot loop counter");
72 this->clean_rtc();
73 this->boot_successful_ = true;
74#if defined(USE_ESP32) && defined(USE_OTA_ROLLBACK)
75 // Mark OTA partition as valid to prevent rollback
76 esp_ota_mark_app_valid_cancel_rollback();
77#endif
78 // Disable loop since we no longer need to check
79 this->disable_loop();
80 }
81}
82
84 uint32_t current_rtc = this->read_rtc_();
85
86 if (pending && current_rtc != SafeModeComponent::ENTER_SAFE_MODE_MAGIC) {
87 ESP_LOGI(TAG, "Device will enter on next boot");
89 }
90
91 if (!pending && current_rtc == SafeModeComponent::ENTER_SAFE_MODE_MAGIC) {
92 ESP_LOGI(TAG, "Safe mode pending has been cleared");
93 this->clean_rtc();
94 }
95}
96
100
101bool SafeModeComponent::should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time,
102 uint32_t boot_is_good_after) {
104 this->safe_mode_enable_time_ = enable_time;
105 this->safe_mode_boot_is_good_after_ = boot_is_good_after;
106 this->safe_mode_num_attempts_ = num_attempts;
107 this->rtc_ = global_preferences->make_preference<uint32_t>(233825507UL, false);
108
109#if defined(USE_ESP32) && defined(USE_OTA_ROLLBACK)
110 // Check partition state to detect if bootloader supports rollback
111 const esp_partition_t *running = esp_ota_get_running_partition();
112 esp_ota_get_state_partition(running, &this->ota_state_);
113#endif
114
115 uint32_t rtc_val = this->read_rtc_();
116 this->safe_mode_rtc_value_ = rtc_val;
117
118 bool is_manual = rtc_val == SafeModeComponent::ENTER_SAFE_MODE_MAGIC;
119
120 if (is_manual) {
121 ESP_LOGI(TAG, "Manual mode");
122 } else {
123 ESP_LOGCONFIG(TAG, "Unsuccessful boot attempts: %" PRIu32, rtc_val);
124 }
125
126 if (rtc_val < num_attempts && !is_manual) {
127 // increment counter
128 this->write_rtc_(rtc_val + 1);
129 return false;
130 }
131
132 this->clean_rtc();
133
134 if (!is_manual) {
135 ESP_LOGE(TAG, "Boot loop detected");
136 }
137
138 this->status_set_error();
139 this->set_timeout(enable_time, []() {
140 ESP_LOGW(TAG, "Timeout, restarting");
141 App.reboot();
142 });
143
144 // Delay here to allow power to stabilize before Wi-Fi/Ethernet is initialised
145 delay(300); // NOLINT
146 App.setup();
147
148 ESP_LOGW(TAG, "SAFE MODE IS ACTIVE");
149
150#ifdef USE_SAFE_MODE_CALLBACK
151 this->safe_mode_callback_.call();
152#endif
153
154 return true;
155}
156
158 this->rtc_.save(&val);
160}
161
163 uint32_t val;
164 if (!this->rtc_.load(&val))
165 return 0;
166 return val;
167}
168
170 // Save without sync - preferences will be written at shutdown or by IntervalSyncer.
171 // This avoids blocking the loop for 50+ ms on flash write. If the device crashes
172 // before sync, the boot wasn't really successful anyway and the counter should
173 // remain incremented.
174 uint32_t val = 0;
175 this->rtc_.save(&val);
176}
177
182
183} // namespace esphome::safe_mode
void setup()
Set up all the registered components. Call this at the end of your setup() function.
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:429
void disable_loop()
Disable this component's loop.
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
bool should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time, uint32_t boot_is_good_after)
uint32_t safe_mode_enable_time_
The time safe mode should remain active for.
Definition safe_mode.h:43
bool boot_successful_
set to true after boot is considered successful
Definition safe_mode.h:47
uint32_t safe_mode_start_time_
stores when safe mode was enabled
Definition safe_mode.h:45
uint32_t safe_mode_boot_is_good_after_
The amount of time after which the boot is considered successful.
Definition safe_mode.h:42
float get_setup_priority() const override
Definition safe_mode.cpp:66
esp_ota_img_states_t ota_state_
Definition safe_mode.h:50
void set_safe_mode_pending(const bool &pending)
Set to true if the next startup will enter safe mode.
Definition safe_mode.cpp:83
static const uint32_t ENTER_SAFE_MODE_MAGIC
a magic number to indicate that safe mode should be entered on next boot
Definition safe_mode.h:58
CallbackManager< void()> safe_mode_callback_
Definition safe_mode.h:55
mopeka_std_values val[4]
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.cpp:91
ESPPreferences * global_preferences
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.