You've already forked MicroPythonOS
mirror of
https://github.com/m5stack/MicroPythonOS.git
synced 2026-05-20 11:51:27 -07:00
Add new BatteryManager framework
This commit is contained in:
@@ -49,7 +49,7 @@ battery power:
|
||||
import lvgl as lv
|
||||
import time
|
||||
|
||||
from mpos import battery_voltage, Activity
|
||||
from mpos import BatteryManager, Activity
|
||||
|
||||
class Hello(Activity):
|
||||
|
||||
@@ -70,9 +70,9 @@ class Hello(Activity):
|
||||
|
||||
def update_bat(timer):
|
||||
#global l
|
||||
r = battery_voltage.read_raw_adc()
|
||||
v = battery_voltage.read_battery_voltage()
|
||||
percent = battery_voltage.get_battery_percentage()
|
||||
r = BatteryManager.read_raw_adc()
|
||||
v = BatteryManager.read_battery_voltage()
|
||||
percent = BatteryManager.get_battery_percentage()
|
||||
text = f"{time.localtime()}\n{r}\n{v}V\n{percent}%"
|
||||
#text = f"{time.localtime()}: {r}"
|
||||
print(text)
|
||||
|
||||
@@ -17,6 +17,9 @@ from .time_zone import TimeZone
|
||||
from .device_info import DeviceInfo
|
||||
from .build_info import BuildInfo
|
||||
|
||||
# Battery manager (imported early for UI dependencies)
|
||||
from .battery_manager import BatteryManager
|
||||
|
||||
# Common activities
|
||||
from .app.activities.chooser import ChooserActivity
|
||||
from .app.activities.view import ViewActivity
|
||||
@@ -56,7 +59,6 @@ from . import time
|
||||
from . import sensor_manager
|
||||
from . import camera_manager
|
||||
from . import sdcard
|
||||
from . import battery_voltage
|
||||
from . import audio
|
||||
from . import hardware
|
||||
|
||||
@@ -66,7 +68,7 @@ __all__ = [
|
||||
"Activity",
|
||||
"SharedPreferences",
|
||||
"ConnectivityManager", "DownloadManager", "WifiService", "AudioFlinger", "Intent",
|
||||
"ActivityNavigator", "AppManager", "TaskManager", "CameraManager",
|
||||
"ActivityNavigator", "AppManager", "TaskManager", "CameraManager", "BatteryManager",
|
||||
# Device and build info
|
||||
"DeviceInfo", "BuildInfo",
|
||||
# Common activities
|
||||
@@ -93,7 +95,7 @@ __all__ = [
|
||||
"get_all_widgets_with_text",
|
||||
# Submodules
|
||||
"ui", "config", "net", "content", "time", "sensor_manager",
|
||||
"camera_manager", "sdcard", "battery_voltage", "audio", "hardware", "bootloader",
|
||||
"camera_manager", "sdcard", "audio", "hardware", "bootloader",
|
||||
# Timezone utilities
|
||||
"TimeZone"
|
||||
]
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"""
|
||||
BatteryManager - Android-inspired battery and power information API.
|
||||
|
||||
Provides direct query access to battery voltage, charge percentage, and raw ADC values.
|
||||
Handles ADC1/ADC2 pin differences on ESP32-S3 with adaptive caching to minimize WiFi interference.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
MIN_VOLTAGE = 3.15
|
||||
MAX_VOLTAGE = 4.15
|
||||
|
||||
# Internal state
|
||||
_adc = None
|
||||
_conversion_func = None
|
||||
_adc_pin = None
|
||||
|
||||
# Cache to reduce WiFi interruptions (ADC2 requires WiFi to be disabled)
|
||||
_cached_raw_adc = None
|
||||
_last_read_time = 0
|
||||
CACHE_DURATION_ADC1_MS = 30000 # 30 seconds (cheaper: no WiFi interference)
|
||||
CACHE_DURATION_ADC2_MS = 600000 # 600 seconds (expensive: requires WiFi disable)
|
||||
|
||||
|
||||
def _is_adc2_pin(pin):
|
||||
"""Check if pin is on ADC2 (ESP32-S3: GPIO11-20)."""
|
||||
return 11 <= pin <= 20
|
||||
|
||||
|
||||
class BatteryManager:
|
||||
"""
|
||||
Android-inspired BatteryManager for querying battery and power information.
|
||||
|
||||
Provides static methods for battery voltage, percentage, and raw ADC readings.
|
||||
Automatically handles ADC1/ADC2 differences and WiFi coordination on ESP32-S3.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def init_adc(pinnr, adc_to_voltage_func):
|
||||
"""
|
||||
Initialize ADC for battery voltage monitoring.
|
||||
|
||||
IMPORTANT for ESP32-S3: ADC2 (GPIO11-20) doesn't work when WiFi is active!
|
||||
Use ADC1 pins (GPIO1-10) for battery monitoring if possible.
|
||||
If using ADC2, WiFi will be temporarily disabled during readings.
|
||||
|
||||
Args:
|
||||
pinnr: GPIO pin number
|
||||
adc_to_voltage_func: Conversion function that takes raw ADC value (0-4095)
|
||||
and returns battery voltage in volts
|
||||
"""
|
||||
global _adc, _conversion_func, _adc_pin
|
||||
|
||||
_conversion_func = adc_to_voltage_func
|
||||
_adc_pin = pinnr
|
||||
|
||||
try:
|
||||
print(f"Initializing ADC pin {pinnr} with conversion function")
|
||||
if _is_adc2_pin(pinnr):
|
||||
print(f" WARNING: GPIO{pinnr} is on ADC2 - WiFi will be disabled during readings")
|
||||
from machine import ADC, Pin
|
||||
_adc = ADC(Pin(pinnr))
|
||||
_adc.atten(ADC.ATTN_11DB) # 0-3.3V range
|
||||
except Exception as e:
|
||||
print(f"Info: this platform has no ADC for measuring battery voltage: {e}")
|
||||
|
||||
initial_adc_value = BatteryManager.read_raw_adc()
|
||||
print(f"Reading ADC at init to fill cache: {initial_adc_value} => {BatteryManager.read_battery_voltage(raw_adc_value=initial_adc_value)}V => {BatteryManager.get_battery_percentage(raw_adc_value=initial_adc_value)}%")
|
||||
|
||||
@staticmethod
|
||||
def read_raw_adc(force_refresh=False):
|
||||
"""
|
||||
Read raw ADC value (0-4095) with adaptive caching.
|
||||
|
||||
On ESP32-S3 with ADC2, WiFi is temporarily disabled during reading.
|
||||
Raises RuntimeError if WifiService is busy (connecting/scanning) when using ADC2.
|
||||
|
||||
Args:
|
||||
force_refresh: Bypass cache and force fresh reading
|
||||
|
||||
Returns:
|
||||
float: Raw ADC value (0-4095)
|
||||
|
||||
Raises:
|
||||
RuntimeError: If WifiService is busy (only when using ADC2)
|
||||
"""
|
||||
global _cached_raw_adc, _last_read_time
|
||||
|
||||
# Desktop mode - return random value in typical ADC range
|
||||
if not _adc:
|
||||
import random
|
||||
return random.randint(1900, 2600)
|
||||
|
||||
# Check if this is an ADC2 pin (requires WiFi disable)
|
||||
needs_wifi_disable = _adc_pin is not None and _is_adc2_pin(_adc_pin)
|
||||
|
||||
# Use different cache durations based on cost
|
||||
cache_duration = CACHE_DURATION_ADC2_MS if needs_wifi_disable else CACHE_DURATION_ADC1_MS
|
||||
|
||||
# Check cache
|
||||
current_time = time.ticks_ms()
|
||||
if not force_refresh and _cached_raw_adc is not None:
|
||||
age = time.ticks_diff(current_time, _last_read_time)
|
||||
if age < cache_duration:
|
||||
return _cached_raw_adc
|
||||
|
||||
# Import WifiService only if needed
|
||||
WifiService = None
|
||||
if needs_wifi_disable:
|
||||
try:
|
||||
# Needs actual path, not "from mpos" shorthand because it's mocked by test_battery_voltage.py
|
||||
from mpos.net.wifi_service import WifiService
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Temporarily disable WiFi for ADC2 reading
|
||||
was_connected = False
|
||||
if needs_wifi_disable and WifiService:
|
||||
# This will raise RuntimeError if WiFi is already busy
|
||||
was_connected = WifiService.temporarily_disable()
|
||||
time.sleep(0.05) # Brief delay for WiFi to fully disable
|
||||
|
||||
try:
|
||||
# Read ADC (average of 10 samples)
|
||||
total = sum(_adc.read() for _ in range(10))
|
||||
raw_value = total / 10.0
|
||||
|
||||
# Update cache
|
||||
_cached_raw_adc = raw_value
|
||||
_last_read_time = current_time
|
||||
|
||||
return raw_value
|
||||
|
||||
finally:
|
||||
# Re-enable WiFi (only if we disabled it)
|
||||
if needs_wifi_disable and WifiService:
|
||||
WifiService.temporarily_enable(was_connected)
|
||||
|
||||
@staticmethod
|
||||
def read_battery_voltage(force_refresh=False, raw_adc_value=None):
|
||||
"""
|
||||
Read battery voltage in volts.
|
||||
|
||||
Args:
|
||||
force_refresh: Bypass cache and force fresh reading
|
||||
raw_adc_value: Optional pre-computed raw ADC value (for testing)
|
||||
|
||||
Returns:
|
||||
float: Battery voltage in volts (clamped to 0-MAX_VOLTAGE)
|
||||
"""
|
||||
raw = raw_adc_value if raw_adc_value else BatteryManager.read_raw_adc(force_refresh)
|
||||
voltage = _conversion_func(raw) if _conversion_func else 0.0
|
||||
return voltage
|
||||
|
||||
@staticmethod
|
||||
def get_battery_percentage(raw_adc_value=None):
|
||||
"""
|
||||
Get battery charge percentage.
|
||||
|
||||
Args:
|
||||
raw_adc_value: Optional pre-computed raw ADC value (for testing)
|
||||
|
||||
Returns:
|
||||
float: Battery percentage (0-100)
|
||||
"""
|
||||
voltage = BatteryManager.read_battery_voltage(raw_adc_value=raw_adc_value)
|
||||
percentage = (voltage - MIN_VOLTAGE) * 100.0 / (MAX_VOLTAGE - MIN_VOLTAGE)
|
||||
return max(0, min(100.0, percentage)) # limit to 100.0% and make sure it's positive
|
||||
|
||||
@staticmethod
|
||||
def clear_cache():
|
||||
"""Clear the battery voltage cache to force fresh reading on next call."""
|
||||
global _cached_raw_adc, _last_read_time
|
||||
_cached_raw_adc = None
|
||||
_last_read_time = 0
|
||||
@@ -1,157 +0,0 @@
|
||||
import time
|
||||
|
||||
MIN_VOLTAGE = 3.15
|
||||
MAX_VOLTAGE = 4.15
|
||||
|
||||
adc = None
|
||||
conversion_func = None # Conversion function: ADC value -> voltage
|
||||
adc_pin = None
|
||||
|
||||
# Cache to reduce WiFi interruptions (ADC2 requires WiFi to be disabled)
|
||||
_cached_raw_adc = None
|
||||
_last_read_time = 0
|
||||
CACHE_DURATION_ADC1_MS = 30000 # 30 seconds (cheaper: no WiFi interference)
|
||||
CACHE_DURATION_ADC2_MS = 600000 # 600 seconds (expensive: requires WiFi disable)
|
||||
#CACHE_DURATION_ADC2_MS = CACHE_DURATION_ADC1_MS # trigger frequent disconnections for debugging OSUpdate resume
|
||||
# Or at runtime, do:
|
||||
# import mpos.battery_voltage ; mpos.battery_voltage.CACHE_DURATION_ADC2_MS = 30000
|
||||
|
||||
|
||||
def _is_adc2_pin(pin):
|
||||
"""Check if pin is on ADC2 (ESP32-S3: GPIO11-20)."""
|
||||
return 11 <= pin <= 20
|
||||
|
||||
|
||||
def init_adc(pinnr, adc_to_voltage_func):
|
||||
"""
|
||||
Initialize ADC for battery voltage monitoring.
|
||||
|
||||
IMPORTANT for ESP32-S3: ADC2 (GPIO11-20) doesn't work when WiFi is active!
|
||||
Use ADC1 pins (GPIO1-10) for battery monitoring if possible.
|
||||
If using ADC2, WiFi will be temporarily disabled during readings.
|
||||
|
||||
Args:
|
||||
pinnr: GPIO pin number
|
||||
adc_to_voltage_func: Conversion function that takes raw ADC value (0-4095)
|
||||
and returns battery voltage in volts
|
||||
"""
|
||||
global adc, conversion_func, adc_pin
|
||||
|
||||
conversion_func = adc_to_voltage_func
|
||||
adc_pin = pinnr
|
||||
|
||||
try:
|
||||
print(f"Initializing ADC pin {pinnr} with conversion function")
|
||||
if _is_adc2_pin(pinnr):
|
||||
print(f" WARNING: GPIO{pinnr} is on ADC2 - WiFi will be disabled during readings")
|
||||
from machine import ADC, Pin
|
||||
adc = ADC(Pin(pinnr))
|
||||
adc.atten(ADC.ATTN_11DB) # 0-3.3V range
|
||||
except Exception as e:
|
||||
print(f"Info: this platform has no ADC for measuring battery voltage: {e}")
|
||||
|
||||
initial_adc_value = read_raw_adc()
|
||||
print(f"Reading ADC at init to fill cache: {initial_adc_value} => {read_battery_voltage(raw_adc_value=initial_adc_value)}V => {get_battery_percentage(raw_adc_value=initial_adc_value)}%")
|
||||
|
||||
|
||||
def read_raw_adc(force_refresh=False):
|
||||
"""
|
||||
Read raw ADC value (0-4095) with adaptive caching.
|
||||
|
||||
On ESP32-S3 with ADC2, WiFi is temporarily disabled during reading.
|
||||
Raises RuntimeError if WifiService is busy (connecting/scanning) when using ADC2.
|
||||
|
||||
Args:
|
||||
force_refresh: Bypass cache and force fresh reading
|
||||
|
||||
Returns:
|
||||
float: Raw ADC value (0-4095)
|
||||
|
||||
Raises:
|
||||
RuntimeError: If WifiService is busy (only when using ADC2)
|
||||
"""
|
||||
global _cached_raw_adc, _last_read_time
|
||||
|
||||
# Desktop mode - return random value in typical ADC range
|
||||
if not adc:
|
||||
import random
|
||||
return random.randint(1900, 2600)
|
||||
|
||||
# Check if this is an ADC2 pin (requires WiFi disable)
|
||||
needs_wifi_disable = adc_pin is not None and _is_adc2_pin(adc_pin)
|
||||
|
||||
# Use different cache durations based on cost
|
||||
cache_duration = CACHE_DURATION_ADC2_MS if needs_wifi_disable else CACHE_DURATION_ADC1_MS
|
||||
|
||||
# Check cache
|
||||
current_time = time.ticks_ms()
|
||||
if not force_refresh and _cached_raw_adc is not None:
|
||||
age = time.ticks_diff(current_time, _last_read_time)
|
||||
if age < cache_duration:
|
||||
return _cached_raw_adc
|
||||
|
||||
# Import WifiService only if needed
|
||||
WifiService = None
|
||||
if needs_wifi_disable:
|
||||
try:
|
||||
# Needs actual path, not "from mpos" shorthand because it's mocked by test_battery_voltage.py
|
||||
from mpos.net.wifi_service import WifiService
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Temporarily disable WiFi for ADC2 reading
|
||||
was_connected = False
|
||||
if needs_wifi_disable and WifiService:
|
||||
# This will raise RuntimeError if WiFi is already busy
|
||||
was_connected = WifiService.temporarily_disable()
|
||||
time.sleep(0.05) # Brief delay for WiFi to fully disable
|
||||
|
||||
try:
|
||||
# Read ADC (average of 10 samples)
|
||||
total = sum(adc.read() for _ in range(10))
|
||||
raw_value = total / 10.0
|
||||
|
||||
# Update cache
|
||||
_cached_raw_adc = raw_value
|
||||
_last_read_time = current_time
|
||||
|
||||
return raw_value
|
||||
|
||||
finally:
|
||||
# Re-enable WiFi (only if we disabled it)
|
||||
if needs_wifi_disable and WifiService:
|
||||
WifiService.temporarily_enable(was_connected)
|
||||
|
||||
|
||||
def read_battery_voltage(force_refresh=False, raw_adc_value=None):
|
||||
"""
|
||||
Read battery voltage in volts.
|
||||
|
||||
Args:
|
||||
force_refresh: Bypass cache and force fresh reading
|
||||
|
||||
Returns:
|
||||
float: Battery voltage in volts (clamped to 0-MAX_VOLTAGE)
|
||||
"""
|
||||
raw = raw_adc_value if raw_adc_value else read_raw_adc(force_refresh)
|
||||
voltage = conversion_func(raw) if conversion_func else 0.0
|
||||
return voltage
|
||||
|
||||
|
||||
def get_battery_percentage(raw_adc_value=None):
|
||||
"""
|
||||
Get battery charge percentage.
|
||||
|
||||
Returns:
|
||||
float: Battery percentage (0-100)
|
||||
"""
|
||||
voltage = read_battery_voltage(raw_adc_value=raw_adc_value)
|
||||
percentage = (voltage - MIN_VOLTAGE) * 100.0 / (MAX_VOLTAGE - MIN_VOLTAGE)
|
||||
return max(0,min(100.0, percentage)) # limit to 100.0% and make sure it's positive
|
||||
|
||||
|
||||
def clear_cache():
|
||||
"""Clear the battery voltage cache to force fresh reading on next call."""
|
||||
global _cached_raw_adc, _last_read_time
|
||||
_cached_raw_adc = None
|
||||
_last_read_time = 0
|
||||
@@ -264,8 +264,8 @@ InputManager.register_indev(indev)
|
||||
|
||||
# Battery voltage ADC measuring
|
||||
# NOTE: GPIO13 is on ADC2, which requires WiFi to be disabled during reading on ESP32-S3.
|
||||
# battery_voltage.py handles this automatically: disables WiFi, reads ADC, reconnects WiFi.
|
||||
import mpos.battery_voltage
|
||||
# BatteryManager handles this automatically: disables WiFi, reads ADC, reconnects WiFi.
|
||||
from mpos import BatteryManager
|
||||
"""
|
||||
best fit on battery power:
|
||||
2482 is 4.180
|
||||
@@ -289,7 +289,7 @@ def adc_to_voltage(adc_value):
|
||||
"""
|
||||
return (0.001651* adc_value + 0.08709)
|
||||
|
||||
mpos.battery_voltage.init_adc(13, adc_to_voltage)
|
||||
BatteryManager.init_adc(13, adc_to_voltage)
|
||||
|
||||
import mpos.sdcard
|
||||
mpos.sdcard.init(spi_bus, cs_pin=14)
|
||||
|
||||
@@ -185,7 +185,7 @@ indev.enable(True) # NOQA
|
||||
InputManager.register_indev(indev)
|
||||
|
||||
# Battery voltage ADC measuring: sits on PC0 of CH32X035GxUx
|
||||
import mpos.battery_voltage
|
||||
from mpos import BatteryManager
|
||||
def adc_to_voltage(adc_value):
|
||||
"""
|
||||
Convert raw ADC value to battery voltage using calibrated linear function.
|
||||
@@ -193,7 +193,7 @@ def adc_to_voltage(adc_value):
|
||||
This is ~10x more accurate than simple scaling (error ~0.01V vs ~0.1V).
|
||||
"""
|
||||
return (0.001651* adc_value + 0.08709)
|
||||
#mpos.battery_voltage.init_adc(13, adc_to_voltage) # TODO
|
||||
#BatteryManager.init_adc(13, adc_to_voltage) # TODO
|
||||
|
||||
import mpos.sdcard
|
||||
mpos.sdcard.init(spi_bus, cs_pin=14)
|
||||
|
||||
@@ -89,13 +89,13 @@ except Exception as e:
|
||||
|
||||
|
||||
# Simulated battery voltage ADC measuring
|
||||
import mpos.battery_voltage
|
||||
from mpos import BatteryManager
|
||||
|
||||
def adc_to_voltage(adc_value):
|
||||
"""Convert simulated ADC value to voltage."""
|
||||
return adc_value * (3.3 / 4095) * 2
|
||||
|
||||
mpos.battery_voltage.init_adc(999, adc_to_voltage)
|
||||
BatteryManager.init_adc(999, adc_to_voltage)
|
||||
|
||||
# === AUDIO HARDWARE ===
|
||||
from mpos import AudioFlinger
|
||||
|
||||
@@ -82,7 +82,7 @@ lv.init()
|
||||
mpos.ui.main_display.set_rotation(lv.DISPLAY_ROTATION._90) # must be done after initializing display and creating the touch drivers, to ensure proper handling
|
||||
|
||||
# Battery voltage ADC measuring
|
||||
import mpos.battery_voltage
|
||||
from mpos import BatteryManager
|
||||
|
||||
def adc_to_voltage(adc_value):
|
||||
"""
|
||||
@@ -95,7 +95,7 @@ def adc_to_voltage(adc_value):
|
||||
"""
|
||||
return adc_value * 0.00262
|
||||
|
||||
mpos.battery_voltage.init_adc(5, adc_to_voltage)
|
||||
BatteryManager.init_adc(5, adc_to_voltage)
|
||||
|
||||
# On the Waveshare ESP32-S3-Touch-LCD-2, the camera is hard-wired to power on,
|
||||
# so it needs a software power off to prevent it from staying hot all the time and quickly draining the battery.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import lvgl as lv
|
||||
|
||||
import mpos.time
|
||||
import mpos.battery_voltage
|
||||
from ..battery_manager import BatteryManager
|
||||
from .display_metrics import DisplayMetrics
|
||||
from .appearance_manager import AppearanceManager
|
||||
from .util import (get_foreground_app)
|
||||
@@ -138,9 +138,9 @@ def create_notification_bar():
|
||||
|
||||
def update_battery_icon(timer=None):
|
||||
try:
|
||||
percent = mpos.battery_voltage.get_battery_percentage()
|
||||
percent = BatteryManager.get_battery_percentage()
|
||||
except Exception as e:
|
||||
print(f"battery_voltage.get_battery_percentage got exception, not updating battery_icon: {e}")
|
||||
print(f"BatteryManager.get_battery_percentage got exception, not updating battery_icon: {e}")
|
||||
return
|
||||
if percent > 80:
|
||||
battery_icon.set_text(lv.SYMBOL.BATTERY_FULL)
|
||||
|
||||
Reference in New Issue
Block a user