- Add max_temp thermal protection with 3°C hysteresis to prevent high-temp battery swelling. - Provide scripts/phone-battery-guard.openrc for automated OpenRC service management. - Update tests/test_battery_guard.py with thermal throttling tests.
181 lines
5.8 KiB
Python
Executable File
181 lines
5.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Battery health daemon: maintains battery state of charge (SoC) between 50% and 65%
|
|
|
|
Prevents battery swelling, chemical degradation and overcharge heat during 24/7 server operation.
|
|
"""
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
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):
|
|
if not 10 <= low < high <= 95:
|
|
raise ValueError('Invalid battery thresholds (expected 10 <= low < high <= 95)')
|
|
self.low = low
|
|
self.high = high
|
|
self.max_temp = max_temp
|
|
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 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 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('--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)
|
|
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)
|
|
if capacity is not None:
|
|
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 '')
|
|
print(f'platina-battery-guard: capacity={capacity}%{temp_str}, 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()
|