Files
mi8-platina-linux/scripts/phone-cellular-setup.py
T
shenandshen 810a467ad3 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.
2026-11-07 23:27:43 -08:00

213 lines
7.9 KiB
Python
Executable File

#!/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())