#!/usr/bin/env python3 """Battery health and emergency protection daemon: 1. Maintains battery state of charge (SoC) between 50% and 80% 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/qcom-battery'), 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=80, 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 # Power-supply sysfs reports temperature in tenths of a degree Celsius. if temp is not None: deg_c = temp / 10.0 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 elif self.thermal_throttled: self.charging_state = False 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): """Request orderly init shutdown without relying on a display or suspend helper.""" print('platina-battery-guard: CRITICAL: battery below shutdown threshold and discharging; emergency poweroff', flush=True) try: os.sync() except Exception: pass candidates = ['/usr/sbin/poweroff', '/sbin/poweroff', shutil.which('poweroff')] attempted = set() for command in candidates: if not command or command in attempted: continue attempted.add(command) try: return executor([command], check=True, timeout=10) except (OSError, subprocess.SubprocessError): continue raise RuntimeError('No orderly poweroff command succeeded') def set_charging(battery_dir, charger_dir, enable): """Use charging switches only; USB input-current policy belongs to the driver/USB helper.""" for supply in (battery_dir, charger_dir): if supply is None: continue behaviour = supply / 'charge_behaviour' try: supported = behaviour.read_text().replace('[', '').replace(']', '').split() if {'auto', 'inhibit-charge'} <= set(supported): behaviour.write_text(('auto' if enable else 'inhibit-charge') + '\n') return True except OSError: pass target = supply / 'charging_enabled' if target.exists(): try: target.write_text(('1' if enable else '0') + '\n') return True except OSError: pass return False 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=80, help='Upper SoC percentage to stop charging (default: 80)') 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): try: trigger_shutdown() except RuntimeError as error: print(f'platina-battery-guard: {error}; retrying next poll', file=sys.stderr, flush=True) # Keep monitoring until init actually terminates the daemon. action = policy.evaluate(capacity, temp=temp) applied = set_charging(battery_dir, charger_dir, action) if not applied: status_str = 'Charging control unavailable (no writable charging switch); input limit unchanged' elif 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 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()