power_controller.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #pragma once
  2. #include <mutex>
  3. #include <functional>
  4. #include <driver/gpio.h>
  5. #include <driver/rtc_io.h>
  6. #include <esp_log.h>
  7. #include "config.h"
  8. enum class PowerState {
  9. ACTIVE,
  10. LIGHT_SLEEP,
  11. DEEP_SLEEP,
  12. SHUTDOWN
  13. };
  14. class PowerController {
  15. public:
  16. static PowerController& Instance() {
  17. static PowerController instance;
  18. return instance;
  19. }
  20. void SetState(PowerState newState) {
  21. std::lock_guard<std::mutex> lock(mutex_);
  22. if (currentState_ != newState) {
  23. ESP_LOGI("PowerCtrl", "State change: %d -> %d",
  24. static_cast<int>(currentState_),
  25. static_cast<int>(newState));
  26. currentState_ = newState;
  27. if (stateChangeCallback_) {
  28. stateChangeCallback_(newState);
  29. }
  30. }
  31. }
  32. PowerState GetState() const {
  33. std::lock_guard<std::mutex> lock(mutex_);
  34. return currentState_;
  35. }
  36. void OnStateChange(std::function<void(PowerState)> callback) {
  37. stateChangeCallback_ = callback;
  38. }
  39. private:
  40. PowerController(){
  41. rtc_gpio_init(PWR_EN_GPIO);
  42. rtc_gpio_set_direction(PWR_EN_GPIO, RTC_GPIO_MODE_OUTPUT_ONLY);
  43. rtc_gpio_set_level(PWR_EN_GPIO, 1);
  44. }
  45. ~PowerController() = default;
  46. PowerState currentState_ = PowerState::ACTIVE;
  47. std::function<void(PowerState)> stateChangeCallback_;
  48. mutable std::mutex mutex_;
  49. };