fix(platina): resolve touchscreen, dual panel, charging reboot, battery guard, camera auth, and internal SIM cellular data

- Add patch 0040: cut panel VSP/VSN always-on rails, attach panel follower to Synaptics TCM touch, add Novatek NT36672A touch node, add BOE panel DTS, and extend DVFS up to 1.84/2.2 GHz.
- Prevent Qualcomm ABL infinite reboot loop on poweroff while charger connected via standby detection in phone-poweroff.py.
- Implement HTTP Basic Auth in camera web preview server with secure digest verification.
- Add battery guard daemon and unit tests to maintain SoC between 50% and 65%.
- Implement Option 2 for cellular data: disable ZRAM swap to prevent Hexagon DMA fragmentation crash, add modem modules to initfs, enable ModemManager/NetworkManager WWAN packages and services, and add phone-cellular-setup.py CLI utility with unit tests.
- Update recipe checksums and verify 109 unit tests and public index boundaries.
This commit is contained in:
shen
2026-11-07 23:27:43 -08:00
parent 655d0f5b49
commit 810a467ad3
15 changed files with 775 additions and 11 deletions
+145
View File
@@ -0,0 +1,145 @@
#!/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):
if not 10 <= low < high <= 95:
raise ValueError('Invalid battery thresholds (expected 10 <= low < high <= 95)')
self.low = low
self.high = high
self.charging_state = True
def evaluate(self, capacity, 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
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_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('--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)
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)
if capacity is not None:
action = policy.evaluate(capacity)
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 args.once or stop_event:
break
time.sleep(args.interval)
if __name__ == '__main__':
main()
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
"""Platina cellular data management: internal SIM detection, APN configuration, and NetworkManager control."""
import argparse
import json
import re
import shutil
import subprocess
import sys
KNOWN_OPERATOR_APNS = {
# China Mobile
'46000': 'cmnet',
'46002': 'cmnet',
'46007': 'cmnet',
'46008': 'cmnet',
# China Unicom
'46001': '3gnet',
'46006': '3gnet',
'46009': '3gnet',
# China Telecom
'46003': 'ctnet',
'46005': 'ctnet',
'46011': 'ctnet',
# Common International
'310260': 'fast.t-mobile.com', # T-Mobile US
'310410': 'nxtgenphone', # AT&T
'311480': 'vzwinternet', # Verizon
'23410': 'everywhere', # EE UK
'23415': 'vodafone', # Vodafone UK
}
CONNECTION_NAME = 'platina-cellular'
def detect_apn_for_operator(operator_code, fallback='internet'):
"""Return matching APN for MCC/MNC operator code, or fallback."""
if not operator_code:
return fallback
clean_code = str(operator_code).strip()
return KNOWN_OPERATOR_APNS.get(clean_code, fallback)
def parse_mmcli_modem_info(raw_text):
"""Parse mmcli -m output into key-value dictionary."""
info = {
'modem_path': None,
'state': 'unknown',
'operator_name': None,
'operator_code': None,
'signal_percent': None,
'access_tech': None,
'equipment_id': None,
'bearer_path': None,
}
for line in raw_text.splitlines():
line = line.strip()
if not line or line.startswith('---'):
continue
if '|' in line:
line = line.split('|', 1)[1].strip()
if ':' in line:
k, v = line.split(':', 1)
k = k.strip().lower()
v = v.strip()
if k == 'path':
info['modem_path'] = v
elif k == 'state':
info['state'] = v
elif k == 'operator name':
info['operator_name'] = v if v != '--' else None
elif k == 'operator id':
info['operator_code'] = v if v != '--' else None
elif k == 'signal quality':
match = re.search(r'(\d+)%', v)
if match:
info['signal_percent'] = int(match.group(1))
elif k == 'access tech':
info['access_tech'] = v if v != '--' else None
elif k == 'equipment id':
info['equipment_id'] = v if v != '--' else None
elif (k in ('bearer', 'paths') or 'bearer' in k) and '/Bearer/' in v:
info['bearer_path'] = v if v != '--' else None
return info
def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*', existing_connections=None):
"""Build list of nmcli commands required to configure cellular connection."""
existing = existing_connections or []
commands = []
if con_name in existing:
commands.append(['nmcli', 'connection', 'modify', con_name,
'gsm.apn', apn,
'gsm.auto-config', 'yes',
'connection.autoconnect', 'yes',
'connection.interface-name', ifname if ifname != '*' else ''])
else:
cmd = ['nmcli', 'connection', 'add',
'type', 'gsm',
'con-name', con_name,
'ifname', ifname,
'apn', apn,
'gsm.auto-config', 'yes',
'connection.autoconnect', 'yes']
commands.append(cmd)
return commands
def query_modem_info(executor=subprocess.run):
"""Query primary modem info via mmcli."""
if not shutil.which('mmcli'):
return {'status': 'error', 'message': 'mmcli utility not found'}
try:
proc = executor(['mmcli', '-L'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
modem_matches = re.findall(r'(/org/freedesktop/ModemManager1/Modem/(\d+))', proc.stdout)
if not modem_matches:
return {'status': 'no_modem', 'message': 'No Qualcomm modem detected by ModemManager'}
first_modem_idx = modem_matches[0][1]
proc_modem = executor(['mmcli', '-m', first_modem_idx], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, check=True)
info = parse_mmcli_modem_info(proc_modem.stdout)
info['modem_index'] = first_modem_idx
return {'status': 'ok', 'modem': info}
except Exception as exc:
return {'status': 'error', 'message': str(exc)}
def configure_cellular(apn=None, ifname='*', executor=subprocess.run):
"""Configure NetworkManager cellular connection, auto-resolving APN if unspecified."""
chosen_apn = apn
if not chosen_apn:
info_result = query_modem_info(executor)
if info_result.get('status') == 'ok':
op_code = info_result['modem'].get('operator_code')
chosen_apn = detect_apn_for_operator(op_code, fallback='cmnet')
else:
chosen_apn = 'cmnet'
existing = []
try:
proc = executor(['nmcli', '-t', '-f', 'NAME', 'connection', 'show'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
existing = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
except Exception:
pass
cmds = build_nmcli_setup_commands(CONNECTION_NAME, chosen_apn, ifname, existing)
for cmd in cmds:
executor(cmd, check=True)
return {'connection': CONNECTION_NAME, 'apn': chosen_apn, 'ifname': ifname}
def toggle_cellular(activate=True, executor=subprocess.run):
"""Activate or deactivate cellular data connection."""
action = 'up' if activate else 'down'
cmd = ['nmcli', 'connection', action, CONNECTION_NAME]
return executor(cmd, check=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--status', action='store_true', help='Show cellular modem and connection status')
parser.add_argument('--setup', action='store_true', help='Configure NetworkManager cellular connection')
parser.add_argument('--apn', type=str, default=None, help='APN override (auto-detected if omitted)')
parser.add_argument('--interface', type=str, default='*', help='Network interface (default: any)')
parser.add_argument('--up', action='store_true', help='Bring up cellular data connection')
parser.add_argument('--down', action='store_true', help='Bring down cellular data connection')
parser.add_argument('--json', action='store_true', help='Output in JSON format')
args = parser.parse_args()
if args.status:
result = query_modem_info()
if args.json:
print(json.dumps(result, indent=2))
else:
if result.get('status') == 'ok':
modem = result['modem']
print(f"Modem Index: {modem.get('modem_index')}")
print(f"State: {modem.get('state')}")
print(f"Operator: {modem.get('operator_name')} ({modem.get('operator_code')})")
print(f"Signal Quality: {modem.get('signal_percent')}%")
print(f"Access Tech: {modem.get('access_tech')}")
print(f"Recommended APN: {detect_apn_for_operator(modem.get('operator_code'))}")
else:
print(f"Cellular Status: {result.get('message')}")
return 0
if args.setup:
res = configure_cellular(apn=args.apn, ifname=args.interface)
if args.json:
print(json.dumps(res, indent=2))
else:
print(f"Configured {res['connection']} with APN '{res['apn']}'")
return 0
if args.up:
toggle_cellular(activate=True)
print(f"Activated {CONNECTION_NAME}")
return 0
if args.down:
toggle_cellular(activate=False)
print(f"Deactivated {CONNECTION_NAME}")
return 0
parser.print_help()
return 0
if __name__ == '__main__':
sys.exit(main())
+41 -2
View File
@@ -11,7 +11,44 @@ import sys
import time
def request_shutdown():
def is_charger_connected():
for name in ('pm660-charger', 'battery', 'qpnp-smbcharger', 'usb'):
supply = Path(f'/sys/class/power_supply/{name}')
if not supply.exists():
continue
try:
online = supply / 'online'
if online.exists() and online.read_text().strip() in ('1', 'true'):
return True
status = supply / 'status'
if status.exists() and status.read_text().strip() in ('Charging', 'Full'):
return True
except OSError:
pass
return False
def enter_charger_standby():
print('platina-poweroff: external power connected; entering low-power suspend standby', flush=True)
state_file = Path('/sys/power/state')
if state_file.exists():
for mode in ('mem', 'freeze'):
try:
state_file.write_text(mode + '\n')
print(f'platina-poweroff: woke from {mode} standby', flush=True)
return
except OSError:
continue
try:
subprocess.run(['pm-suspend'], check=True, timeout=10)
except (OSError, subprocess.SubprocessError):
pass
def request_shutdown(force=False, standby=False):
if not force and (standby or is_charger_connected()):
enter_charger_standby()
return
subprocess.run(['/usr/sbin/poweroff'], check=True, timeout=10)
print('platina-poweroff: init accepted shutdown; keeping screen until shutdown', flush=True)
# Shutdown should terminate this process. If it does not, restore the display
@@ -23,6 +60,8 @@ def request_shutdown():
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--preview', action='store_true', help='Show the screen for 5s without shutting down')
parser.add_argument('--force', action='store_true', help='Force immediate poweroff even if external charger is attached')
parser.add_argument('--standby', action='store_true', help='Enter low-power suspend standby rather than full poweroff')
args = parser.parse_args()
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
@@ -33,7 +72,7 @@ def main():
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
with control['device']() as fb:
control['show'](fb, directory, 5 if args.preview else 3, 25,
after_display=None if args.preview else request_shutdown)
after_display=None if args.preview else lambda: request_shutdown(force=args.force, standby=args.standby))
if __name__ == '__main__':
+10 -2
View File
@@ -50,8 +50,16 @@ def build(output, release=None):
logo.thumbnail((960, 960), Image.Resampling.LANCZOS)
screen.paste(logo, ((width - logo.width) // 2, 410))
draw = ImageDraw.Draw(screen)
font_path = Path('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf')
font = ImageFont.truetype(str(font_path), 44)
font_candidates = [
Path('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'),
Path('/System/Library/Fonts/Supplemental/Arial.ttf'),
Path('/Library/Fonts/Arial.ttf'),
]
font_path = next((p for p in font_candidates if p.exists()), None)
if font_path:
font = ImageFont.truetype(str(font_path), 44)
else:
font = ImageFont.load_default()
label = 'v' + release['version']
box = draw.textbbox((0, 0), label, font=font)
text_width, text_height = box[2] - box[0], box[3] - box[1]