ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
deep_sleep_component.cpp
Go to the documentation of this file.
3#include "esphome/core/log.h"
4
5namespace esphome::deep_sleep {
6
7static const char *const TAG = "deep_sleep";
8// 5 seconds for deep sleep to ensure clean disconnect from Home Assistant
9static const uint32_t TEARDOWN_TIMEOUT_DEEP_SLEEP_MS = 5000;
10
11bool global_has_deep_sleep = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
12
17
19 this->next_enter_deep_sleep_ = false;
20 const optional<uint32_t> run_duration = get_run_duration_();
21 if (run_duration.has_value()) {
22 ESP_LOGI(TAG, "Scheduling in %" PRIu32 " ms", *run_duration);
23 this->set_timeout(*run_duration, [this]() { this->begin_sleep(); });
24 } else {
25 ESP_LOGD(TAG, "Not scheduling; no run duration configured");
26 }
27}
28
30 ESP_LOGCONFIG(TAG, "Deep sleep:");
31 if (this->sleep_duration_.has_value()) {
32 uint32_t duration = *this->sleep_duration_ / 1000;
33 ESP_LOGCONFIG(TAG, " Sleep Duration: %" PRIu32 " ms", duration);
34 }
35 if (this->run_duration_.has_value()) {
36 ESP_LOGCONFIG(TAG, " Run Duration: %" PRIu32 " ms", *this->run_duration_);
37 }
39}
40
42 if (this->next_enter_deep_sleep_)
43 this->begin_sleep();
44}
45
47 if (this->prevent_ && !manual) {
48 this->next_enter_deep_sleep_ = true;
49 return;
50 }
51
52 if (!this->prepare_to_sleep_()) {
53 return;
54 }
55
56 ESP_LOGI(TAG, "Beginning sleep");
57 if (this->sleep_duration_.has_value()) {
58 ESP_LOGI(TAG, "Sleeping for %" PRId64 "us", *this->sleep_duration_);
59 }
60
61 if (this->should_teardown_()) {
63 // It's critical to teardown components cleanly for deep sleep to ensure
64 // Home Assistant sees a clean disconnect instead of marking the device unavailable
65 App.teardown_components(TEARDOWN_TIMEOUT_DEEP_SLEEP_MS);
67 }
68
69 this->deep_sleep_();
70 this->schedule_sleep_();
71}
72
74
75} // namespace esphome::deep_sleep
void teardown_components(uint32_t timeout_ms)
Teardown all components with a timeout.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
optional< uint32_t > get_run_duration_() const
void begin_sleep(bool manual=false)
Helper to enter deep sleep mode.
uint8_t duration
Definition msa3xx.h:0
constexpr float LATE
For components that should be initialized at the very end of the setup process.
Definition component.h:59
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t