ESPHome  2024.7.2
deep_sleep_component.cpp
Go to the documentation of this file.
1 #include "deep_sleep_component.h"
3 #include "esphome/core/log.h"
4 
5 namespace esphome {
6 namespace deep_sleep {
7 
8 static const char *const TAG = "deep_sleep";
9 
10 bool global_has_deep_sleep = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
11 
13  ESP_LOGCONFIG(TAG, "Setting up Deep Sleep...");
14  global_has_deep_sleep = true;
15 
16  const optional<uint32_t> run_duration = get_run_duration_();
17  if (run_duration.has_value()) {
18  ESP_LOGI(TAG, "Scheduling Deep Sleep to start in %" PRIu32 " ms", *run_duration);
19  this->set_timeout(*run_duration, [this]() { this->begin_sleep(); });
20  } else {
21  ESP_LOGD(TAG, "Not scheduling Deep Sleep, as no run duration is configured.");
22  }
23 }
24 
26  ESP_LOGCONFIG(TAG, "Setting up Deep Sleep...");
27  if (this->sleep_duration_.has_value()) {
28  uint32_t duration = *this->sleep_duration_ / 1000;
29  ESP_LOGCONFIG(TAG, " Sleep Duration: %" PRIu32 " ms", duration);
30  }
31  if (this->run_duration_.has_value()) {
32  ESP_LOGCONFIG(TAG, " Run Duration: %" PRIu32 " ms", *this->run_duration_);
33  }
34  this->dump_config_platform_();
35 }
36 
38  if (this->next_enter_deep_sleep_)
39  this->begin_sleep();
40 }
41 
43  return -100.0f; // run after everything else is ready
44 }
45 
46 void DeepSleepComponent::set_sleep_duration(uint32_t time_ms) { this->sleep_duration_ = uint64_t(time_ms) * 1000; }
47 
48 void DeepSleepComponent::set_run_duration(uint32_t time_ms) { this->run_duration_ = time_ms; }
49 
51  if (this->prevent_ && !manual) {
52  this->next_enter_deep_sleep_ = true;
53  return;
54  }
55 
56  if (!this->prepare_to_sleep_()) {
57  return;
58  }
59 
60  ESP_LOGI(TAG, "Beginning Deep Sleep");
61  if (this->sleep_duration_.has_value()) {
62  ESP_LOGI(TAG, "Sleeping for %" PRId64 "us", *this->sleep_duration_);
63  }
65 
66  this->deep_sleep_();
67 }
68 
70 
72 
74 
75 } // namespace deep_sleep
76 } // namespace esphome
optional< uint32_t > get_run_duration_() const
void set_sleep_duration(uint32_t time_ms)
Set the duration in ms the component should sleep once it&#39;s in deep sleep mode.
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:69
const float LATE
For components that should be initialized at the very end of the setup process.
Definition: component.cpp:28
bool has_value() const
Definition: optional.h:87
void set_run_duration(WakeupCauseToRunDuration wakeup_cause_to_run_duration)
void begin_sleep(bool manual=false)
Helper to enter deep sleep mode.
Application App
Global storage of Application pointer - only one Application can exist.
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7