Files
mi8-platina-linux/scripts/phone-battery-guard.py
T
shenandshen 23989f4a18
Offline project checks / check (push) Canceled after 0s
feat(battery): implement emergency safe shutdown when battery <= 5% discharging
- Add should_shutdown() check in BatteryPolicy and trigger_shutdown() in phone-battery-guard.py.
- Auto sync filesystems and invoke safe poweroff if SoC drops to 5% while on battery/discharging.
- Do not power off if external charger is actively connected and charging.
- Update openrc service command args with --shutdown-at 5.
- Add unit tests for emergency shutdown, discharging detection, and threshold validation.
2026-11-08 05:32:04 -08:00

243 lines
8.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""Battery health and emergency protection daemon:
1. Maintains battery state of charge (SoC) between 50% and 65% when plugged in.
2. Cuts off charging if battery temperature exceeds max_temp (default 45°C).
3. Automatically triggers safe filesystem sync and shutdown if battery <= 5% while discharging.
"""
import argparse
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import time
BATTERY_PATHS = [
Path('/sys/class/power_supply/battery'),
Path('/sys/class/power_supply/bms'),
]
CHARGER_PATHS = [
Path('/sys/class/power_supply/pm660-charger'),
Path('/sys/class/power_supply/qpnp-smbcharger'),
]
def find_supply(paths):
for path in paths:
if path.exists():
return path
return None
class BatteryPolicy:
def __init__(self, low=50, high=65, max_temp=45, shutdown_at=5):
if not 10 <= low < high <= 95:
raise ValueError('Invalid battery thresholds (expected 10 <= low < high <= 95)')
if not 1 <= shutdown_at < low:
raise ValueError('Invalid shutdown threshold (expected 1 <= shutdown_at < low)')
self.low = low
self.high = high
self.max_temp = max_temp
self.shutdown_at = shutdown_at
self.charging_state = True
self.thermal_throttled = False
def evaluate(self, capacity, temp=None, current_state=None):
"""Returns True to charge, False to stop charging, or None for no change."""
if current_state is not None:
self.charging_state = current_state
# Temperature safety cutoff: prevent thermal runaway and pouch swelling
if temp is not None:
deg_c = temp / 10.0 if temp > 150 else float(temp)
if deg_c >= self.max_temp:
self.thermal_throttled = True
self.charging_state = False
return False
elif self.thermal_throttled:
# 3°C hysteresis before resuming
if deg_c <= self.max_temp - 3:
self.thermal_throttled = False
else:
return False
if capacity >= self.high:
self.charging_state = False
return False
if capacity <= self.low:
self.charging_state = True
return True
return self.charging_state
def should_shutdown(self, capacity, is_discharging=True):
"""Returns True if battery is critically low and actively discharging."""
if capacity is None:
return False
return bool(is_discharging and capacity <= self.shutdown_at)
def get_temp(battery_dir):
if not battery_dir:
return None
try:
temp_file = battery_dir / 'temp'
if temp_file.exists():
return int(temp_file.read_text().strip())
except (OSError, ValueError):
pass
return None
def get_capacity(battery_dir):
if not battery_dir:
return None
try:
cap_file = battery_dir / 'capacity'
if cap_file.exists():
return int(cap_file.read_text().strip())
except (OSError, ValueError):
pass
return None
def is_battery_discharging(battery_dir, charger_dir=None):
"""Determine whether the battery is currently discharging / running without external power."""
if battery_dir:
status_file = battery_dir / 'status'
if status_file.exists():
try:
status = status_file.read_text().strip().lower()
if status == 'discharging':
return True
if status in ('charging', 'full'):
return False
except OSError:
pass
if charger_dir:
online_file = charger_dir / 'online'
if online_file.exists():
try:
return online_file.read_text().strip() == '0'
except OSError:
pass
return False
def trigger_shutdown(executor=subprocess.run):
"""Sync filesystem and execute safe poweroff."""
print('platina-battery-guard: CRITICAL: battery <= 5% and discharging; emergency poweroff to protect filesystem', flush=True)
try:
os.sync()
except Exception:
pass
bin_candidates = [
shutil.which('platina-poweroff'),
'/usr/local/sbin/platina-poweroff',
shutil.which('poweroff'),
'/usr/sbin/poweroff',
]
target_bin = next((b for b in bin_candidates if b and (Path(b).exists() or shutil.which(b))), '/usr/sbin/poweroff')
return executor([target_bin], check=True)
def set_charging(battery_dir, charger_dir, enable):
applied = False
val = '1' if enable else '0'
# 1. Try battery charging_enabled
if battery_dir:
for node in ('charging_enabled', 'charge_control_limit_max'):
target = battery_dir / node
if target.exists():
try:
target.write_text(val + '\n')
applied = True
except OSError:
pass
# 2. Try charger module charging_enabled
if charger_dir:
for node in ('charging_enabled',):
target = charger_dir / node
if target.exists():
try:
target.write_text(val + '\n')
applied = True
except OSError:
pass
# 3. Fallback: throttle charger current to 0 on disable
if not enable:
cur_target = charger_dir / 'current_max'
if cur_target.exists():
try:
cur_target.write_text('0\n')
applied = True
except OSError:
pass
else:
cur_target = charger_dir / 'current_max'
if cur_target.exists():
try:
cur_target.write_text('1500000\n')
applied = True
except OSError:
pass
return applied
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--low', type=int, default=50, help='Lower SoC percentage to resume charging (default: 50)')
parser.add_argument('--high', type=int, default=65, help='Upper SoC percentage to stop charging (default: 65)')
parser.add_argument('--shutdown-at', type=int, default=5, help='Emergency shutdown SoC percentage when discharging (default: 5)')
parser.add_argument('--max-temp', type=int, default=45, help='Thermal cutoff threshold in Celsius (default: 45)')
parser.add_argument('--interval', type=float, default=60, help='Poll interval in seconds (default: 60)')
parser.add_argument('--once', action='store_true', help='Evaluate once and exit')
args = parser.parse_args()
policy = BatteryPolicy(args.low, args.high, max_temp=args.max_temp, shutdown_at=args.shutdown_at)
battery_dir = find_supply(BATTERY_PATHS)
charger_dir = find_supply(CHARGER_PATHS)
stop_event = False
def on_signal(*_):
nonlocal stop_event
stop_event = True
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, on_signal)
while not stop_event:
capacity = get_capacity(battery_dir)
temp = get_temp(battery_dir)
discharging = is_battery_discharging(battery_dir, charger_dir)
if capacity is not None:
# Emergency low-battery safety shutdown: prevent brownout filesystem corruption
if policy.should_shutdown(capacity, is_discharging=discharging):
trigger_shutdown()
break
action = policy.evaluate(capacity, temp=temp)
set_charging(battery_dir, charger_dir, action)
if policy.thermal_throttled:
status_str = 'Charging paused (thermal limit exceeded)'
else:
status_str = 'Charging enabled' if action else 'Charging paused (protective threshold reached)'
temp_str = f', temp={temp/10:.1f}°C' if temp is not None and temp > 150 else (f', temp={temp}°C' if temp is not None else '')
power_mode = 'discharging' if discharging else 'external-power'
print(f'platina-battery-guard: capacity={capacity}%{temp_str}, power={power_mode}, threshold=[{args.low}%-{args.high}%], state={status_str}', flush=True)
if args.once or stop_event:
break
time.sleep(args.interval)
if __name__ == '__main__':
main()