69 lines
2.3 KiB
C++
69 lines
2.3 KiB
C++
#pragma once
|
|
|
|
#include <Arduino.h>
|
|
#include <BatteryMonitor.h>
|
|
#include <InputManager.h>
|
|
#include <Logging.h>
|
|
#include <Wire.h>
|
|
#include <freertos/semphr.h>
|
|
|
|
#include <atomic>
|
|
#include <cassert>
|
|
|
|
#include "HalGPIO.h"
|
|
|
|
class HalPowerManager;
|
|
extern HalPowerManager powerManager; // Singleton
|
|
|
|
class HalPowerManager {
|
|
int normalFreq = 0; // MHz
|
|
bool isLowPower = false;
|
|
|
|
// I2C fuel gauge configuration for X3 battery monitoring
|
|
bool _batteryUseI2C = false; // True if using I2C fuel gauge (X3), false for ADC (X4)
|
|
mutable int _batteryCachedPercent = 0; // Last read battery percentage — X3: 0-100, X4: 0-1000 (scaled)
|
|
mutable bool _batterySeeded = false; // True once the smoothing filter has a first real sample (X4)
|
|
mutable unsigned long _batteryLastPollMs = 0; // Timestamp of last battery read in milliseconds
|
|
|
|
enum LockMode { None, NormalSpeed };
|
|
std::atomic<LockMode> currentLockMode{None};
|
|
SemaphoreHandle_t modeMutex = nullptr; // Protect Lock acquire/release ordering
|
|
|
|
public:
|
|
static constexpr int LOW_POWER_FREQ = 10; // MHz
|
|
static constexpr unsigned long IDLE_POWER_SAVING_MS = 3000; // ms
|
|
static constexpr unsigned long BATTERY_POLL_MS = 1500; // ms
|
|
|
|
void begin();
|
|
|
|
// Control CPU frequency for power saving
|
|
void setPowerSaving(bool enabled);
|
|
|
|
// Setup wake up GPIO and enter deep sleep.
|
|
// When keepClockAlive is true, GPIO13 stays HIGH so the LP timer keeps
|
|
// running during sleep (~3-4 mA extra). This allows HalClock to compute
|
|
// elapsed sleep time and restore the wall clock accurately on wake.
|
|
void startDeepSleep(HalGPIO& gpio, bool keepClockAlive = false) const;
|
|
|
|
// Get battery percentage (range 0-100)
|
|
uint16_t getBatteryPercentage() const;
|
|
|
|
// RAII helper class to manage power saving locks
|
|
// Usage: create an instance of Lock in a scope to disable power saving, for example when running a task that needs
|
|
// full performance. When the Lock instance is destroyed (goes out of scope), power saving will be re-enabled.
|
|
class Lock {
|
|
friend class HalPowerManager;
|
|
bool valid = false;
|
|
|
|
public:
|
|
explicit Lock();
|
|
~Lock();
|
|
|
|
// Non-copyable and non-movable
|
|
Lock(const Lock&) = delete;
|
|
Lock& operator=(const Lock&) = delete;
|
|
Lock(Lock&&) = delete;
|
|
Lock& operator=(Lock&&) = delete;
|
|
};
|
|
};
|