feat(battery): implement emergency safe shutdown when battery <= 5% discharging
Offline project checks / check (push) Canceled after 0s

- 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.
This commit is contained in:
shen
2026-11-08 05:32:04 -08:00
parent db9d190d7b
commit 23989f4a18
3 changed files with 119 additions and 7 deletions
+2 -2
View File
@@ -1,8 +1,8 @@
#!/sbin/openrc-run #!/sbin/openrc-run
description="Platina battery health and anti-swelling daemon (maintains 50-65% SoC)" description="Platina battery health and emergency shutdown daemon (50-65% SoC, auto-poweroff <= 5%)"
command="/usr/local/sbin/platina-battery-guard" command="/usr/local/sbin/platina-battery-guard"
command_user="root:root" command_user="root:root"
command_args="--low ${low:-50} --high ${high:-65} --max-temp ${max_temp:-45} --interval ${interval:-60}" command_args="--low ${low:-50} --high ${high:-65} --max-temp ${max_temp:-45} --shutdown-at ${shutdown_at:-5} --interval ${interval:-60}"
command_background="yes" command_background="yes"
pidfile="/run/platina-battery-guard.pid" pidfile="/run/platina-battery-guard.pid"
output_log="/var/log/platina-battery-guard.log" output_log="/var/log/platina-battery-guard.log"
+67 -5
View File
@@ -1,12 +1,16 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Battery health daemon: maintains battery state of charge (SoC) between 50% and 65% """Battery health and emergency protection daemon:
Prevents battery swelling, chemical degradation and overcharge heat during 24/7 server operation. 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 argparse
import os import os
from pathlib import Path from pathlib import Path
import shutil
import signal import signal
import subprocess
import sys import sys
import time import time
@@ -28,12 +32,15 @@ def find_supply(paths):
class BatteryPolicy: class BatteryPolicy:
def __init__(self, low=50, high=65, max_temp=45): def __init__(self, low=50, high=65, max_temp=45, shutdown_at=5):
if not 10 <= low < high <= 95: if not 10 <= low < high <= 95:
raise ValueError('Invalid battery thresholds (expected 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.low = low
self.high = high self.high = high
self.max_temp = max_temp self.max_temp = max_temp
self.shutdown_at = shutdown_at
self.charging_state = True self.charging_state = True
self.thermal_throttled = False self.thermal_throttled = False
@@ -64,6 +71,12 @@ class BatteryPolicy:
return True return True
return self.charging_state 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): def get_temp(battery_dir):
if not battery_dir: if not battery_dir:
@@ -89,6 +102,46 @@ def get_capacity(battery_dir):
return None 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): def set_charging(battery_dir, charger_dir, enable):
applied = False applied = False
val = '1' if enable else '0' val = '1' if enable else '0'
@@ -139,12 +192,13 @@ def main():
parser = argparse.ArgumentParser(description=__doc__) 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('--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('--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('--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('--interval', type=float, default=60, help='Poll interval in seconds (default: 60)')
parser.add_argument('--once', action='store_true', help='Evaluate once and exit') parser.add_argument('--once', action='store_true', help='Evaluate once and exit')
args = parser.parse_args() args = parser.parse_args()
policy = BatteryPolicy(args.low, args.high, max_temp=args.max_temp) policy = BatteryPolicy(args.low, args.high, max_temp=args.max_temp, shutdown_at=args.shutdown_at)
battery_dir = find_supply(BATTERY_PATHS) battery_dir = find_supply(BATTERY_PATHS)
charger_dir = find_supply(CHARGER_PATHS) charger_dir = find_supply(CHARGER_PATHS)
@@ -160,7 +214,14 @@ def main():
while not stop_event: while not stop_event:
capacity = get_capacity(battery_dir) capacity = get_capacity(battery_dir)
temp = get_temp(battery_dir) temp = get_temp(battery_dir)
discharging = is_battery_discharging(battery_dir, charger_dir)
if capacity is not None: 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) action = policy.evaluate(capacity, temp=temp)
set_charging(battery_dir, charger_dir, action) set_charging(battery_dir, charger_dir, action)
if policy.thermal_throttled: if policy.thermal_throttled:
@@ -168,7 +229,8 @@ def main():
else: else:
status_str = 'Charging enabled' if action else 'Charging paused (protective threshold reached)' 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 '') 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) 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: if args.once or stop_event:
break break
+50
View File
@@ -71,6 +71,56 @@ class BatteryGuardTests(unittest.TestCase):
self.assertTrue(policy.evaluate(45, temp=410)) self.assertTrue(policy.evaluate(45, temp=410))
self.assertFalse(policy.thermal_throttled) self.assertFalse(policy.thermal_throttled)
def test_emergency_low_battery_shutdown(self):
policy = guard.BatteryPolicy(low=50, high=65, shutdown_at=5)
# Above shutdown threshold: no shutdown
self.assertFalse(policy.should_shutdown(10, is_discharging=True))
self.assertFalse(policy.should_shutdown(6, is_discharging=True))
# At or below threshold (<= 5) while discharging: should shutdown
self.assertTrue(policy.should_shutdown(5, is_discharging=True))
self.assertTrue(policy.should_shutdown(3, is_discharging=True))
self.assertTrue(policy.should_shutdown(1, is_discharging=True))
# At or below threshold BUT charging / on external power: do NOT shutdown
self.assertFalse(policy.should_shutdown(4, is_discharging=False))
self.assertFalse(policy.should_shutdown(None, is_discharging=True))
def test_invalid_shutdown_thresholds_rejected(self):
with self.assertRaises(ValueError):
guard.BatteryPolicy(low=50, high=65, shutdown_at=0)
with self.assertRaises(ValueError):
guard.BatteryPolicy(low=50, high=65, shutdown_at=50)
def test_is_battery_discharging_sysfs(self):
with tempfile.TemporaryDirectory() as temp:
battery = Path(temp) / 'battery'
charger = Path(temp) / 'charger'
battery.mkdir()
charger.mkdir()
(battery / 'status').write_text('Discharging\n')
self.assertTrue(guard.is_battery_discharging(battery, charger))
(battery / 'status').write_text('Charging\n')
self.assertFalse(guard.is_battery_discharging(battery, charger))
(battery / 'status').unlink()
(charger / 'online').write_text('0\n')
self.assertTrue(guard.is_battery_discharging(battery, charger))
(charger / 'online').write_text('1\n')
self.assertFalse(guard.is_battery_discharging(battery, charger))
def test_trigger_shutdown_executor(self):
called = []
def mock_executor(cmd, **kwargs):
called.append(cmd)
return None
guard.trigger_shutdown(executor=mock_executor)
self.assertEqual(len(called), 1)
self.assertTrue(any('poweroff' in part for part in called[0]))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()