ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
deep_sleep_zephyr.cpp
Go to the documentation of this file.
2#ifdef USE_ZEPHYR
3#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
5#include "esphome/core/wake.h"
6#include <zephyr/sys/poweroff.h>
7#include <algorithm>
8
9namespace esphome::deep_sleep {
10
11ESPHOME_LOG_TAG(TAG, "deep_sleep");
12
13// The Zephyr watchdog has a short window (2s, or 10s with Zigbee) and
14// WDT_OPT_PAUSE_IN_SLEEP only pauses it during true hardware sleep — not while a
15// radio thread (e.g. the Zigbee stack) keeps the CPU busy in k_sem_take(). Feed
16// it at least this often while waiting so it does not reset the device.
17static const uint32_t WDT_FEED_INTERVAL_MS = 1000;
18
19static bool wakeable_delay_feed_wdt(uint32_t ms) {
20 while (ms > 0) {
21 const uint32_t step = std::min(ms, WDT_FEED_INTERVAL_MS);
24 if (esphome::wake_request_take()) {
25 return true;
26 }
27 if (ms != UINT32_MAX) {
28 ms -= step;
29 }
30 }
31 return false;
32}
33
34// A wake from System OFF is not told apart from a reset yet.
36
37optional<uint32_t> DeepSleepComponent::get_run_duration_() const { return this->run_duration_; }
38
40
41bool DeepSleepComponent::prepare_to_sleep_() { return true; }
42
44 bool woke = false;
45 if (this->sleep_duration_.has_value()) {
46 woke = wakeable_delay_feed_wdt(static_cast<uint32_t>(*this->sleep_duration_ / 1000));
47 } else {
48#ifndef USE_ZIGBEE
49 // the device can be woken up through one of the following signals:
50 // - The DETECT signal, optionally generated by the GPIO peripheral.
51 // - The ANADETECT signal, optionally generated by the LPCOMP module.
52 // - The SENSE signal, optionally generated by the NFC module to wake-on-field.
53 // - Detecting a valid USB voltage on the VBUS pin (VBUS,DETECT).
54 // - A reset.
55 //
56 // The system is reset when it wakes up from System OFF mode.
57 sys_poweroff();
58#else
59 woke = wakeable_delay_feed_wdt(UINT32_MAX);
60#endif
61 }
62 if (woke) {
63 ESP_LOGD(TAG, "Woken up by another thread");
64 } else {
65 ESP_LOGD(TAG, "Timeout expired (normal sleep)");
66 }
67}
68
70 if (this->sleep_duration_.has_value()) {
71 return false;
72 }
73#ifdef USE_ZIGBEE
74 return false;
75#else
76 return true;
77#endif
78}
79
80} // namespace esphome::deep_sleep
81
82#endif
optional< uint32_t > get_run_duration_() const
ESPHOME_LOG_TAG(TAG, "deep_sleep")
WakeupCause get_wakeup_cause()
Return why the device woke from deep sleep. Implemented per platform.
WakeupCause
Why the device woke from deep sleep. Passed to on_wake automations.
@ WAKEUP_CAUSE_NONE
The device did not wake from deep sleep (for example a cold boot, reset or OTA restart).
void ESPHOME_ALWAYS_INLINE wakeable_delay(uint32_t ms)
Host wakeable_delay uses select() over the registered fds — defined in wake_host.cpp.
void arch_feed_wdt()
Definition hal.cpp:115
static void uint32_t
Platform-specific main loop wake primitives.