feat(battery): enhance battery guard with thermal runaway protection and openrc service

- 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.
This commit is contained in:
shen
2026-11-08 05:26:21 -08:00
parent 810a467ad3
commit db9d190d7b
3 changed files with 72 additions and 6 deletions
+18
View File
@@ -0,0 +1,18 @@
#!/sbin/openrc-run
description="Platina battery health and anti-swelling daemon (maintains 50-65% SoC)"
command="/usr/local/sbin/platina-battery-guard"
command_user="root:root"
command_args="--low ${low:-50} --high ${high:-65} --max-temp ${max_temp:-45} --interval ${interval:-60}"
command_background="yes"
pidfile="/run/platina-battery-guard.pid"
output_log="/var/log/platina-battery-guard.log"
error_log="/var/log/platina-battery-guard.log"
depend() {
need localmount
after udev-trigger
}
start_pre() {
checkpath --file --mode 0640 --owner root:root "$output_log"
}
+41 -6
View File
@@ -28,17 +28,34 @@ def find_supply(paths):
class BatteryPolicy:
def __init__(self, low=50, high=65):
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, current_state=None):
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
@@ -48,6 +65,18 @@ class BatteryPolicy:
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
@@ -110,11 +139,12 @@ 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)
policy = BatteryPolicy(args.low, args.high, max_temp=args.max_temp)
battery_dir = find_supply(BATTERY_PATHS)
charger_dir = find_supply(CHARGER_PATHS)
@@ -129,11 +159,16 @@ def main():
while not stop_event:
capacity = get_capacity(battery_dir)
temp = get_temp(battery_dir)
if capacity is not None:
action = policy.evaluate(capacity)
action = policy.evaluate(capacity, temp=temp)
set_charging(battery_dir, charger_dir, action)
status_str = 'Charging enabled' if action else 'Charging paused (protective threshold reached)'
print(f'platina-battery-guard: capacity={capacity}%, threshold=[{args.low}%-{args.high}%], state={status_str}', flush=True)
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
+13
View File
@@ -58,6 +58,19 @@ class BatteryGuardTests(unittest.TestCase):
self.assertEqual((charger / 'charging_enabled').read_text().strip(), '1')
self.assertEqual((charger / 'current_max').read_text().strip(), '1500000')
def test_thermal_protection(self):
policy = guard.BatteryPolicy(low=50, high=65, max_temp=45)
# Low capacity, normal temp (30°C represented as 300 tenths): should charge
self.assertTrue(policy.evaluate(45, temp=300))
# Over-temperature (46°C / 460 tenths): should cut off charging despite low SoC
self.assertFalse(policy.evaluate(45, temp=460))
self.assertTrue(policy.thermal_throttled)
# Cooling slightly (44°C): still paused due to 3°C hysteresis
self.assertFalse(policy.evaluate(45, temp=440))
# Cooled below (max_temp - 3) = 42°C (41°C / 410 tenths): resumes charging
self.assertTrue(policy.evaluate(45, temp=410))
self.assertFalse(policy.thermal_throttled)
if __name__ == '__main__':
unittest.main()