#!/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 os from pathlib import Path import re import shutil import subprocess import sys import time KNOWN_OPERATOR_APNS = { # China Mobile '46000': 'cmnet', '46002': 'cmnet', '46004': 'cmnet', '46007': 'cmnet', '46008': 'cmnet', # China Unicom '46001': '3gnet', '46006': '3gnet', '46009': '3gnet', '46010': '3gnet', # China Telecom '46003': 'ctnet', '46005': 'ctnet', '46011': 'ctnet', # China Broadnet '46015': 'cbnet', # 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() if clean_code in KNOWN_OPERATOR_APNS: return KNOWN_OPERATOR_APNS[clean_code] if clean_code.startswith('460'): if clean_code in ('46003', '46005', '46011'): return 'ctnet' if clean_code in ('46001', '46006', '46009', '46010'): return '3gnet' if clean_code in ('46015',): return 'cbnet' return 'cmnet' return 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 cellular_datapath_status(sys_path='/sys'): """Inspect cellular hardware transport readiness under sysfs. Legacy IPA v2.6L hardware must expose modem/datapath_ready=1 before NetworkManager activation is permitted. """ root = Path(sys_path) rows = [] def read(path): try: return path.read_text().strip() except OSError: return '' def transport(iface, seen): resolved = iface.resolve() if resolved in seen: return False, 'cyclic lower-interface relationship' seen = seen | {resolved} for lower in sorted(iface.glob('lower_*')): ready, reason = transport(lower, seen) if ready: return ready, reason device = iface / 'device' if not (device / 'driver').exists(): return False, 'no bound hardware transport' version = read(device / 'ipa_version') compatible = read(device / 'of_node/compatible').split('\0') legacy = (version.startswith('2.') or any(value in ('qcom,sdm660-ipa', 'qcom,ipa-v2.6') for value in compatible)) if legacy: if read(device / 'modem/datapath_ready') != '1': return False, 'IPA v2.6 shim: BAM TX/RX not implemented' return True, 'bound hardware transport (datapath_ready=1)' return True, 'bound hardware transport (IP connectivity unverified)' for iface in sorted((root / 'class/net').glob('*')): if iface.name.startswith(('rmnet', 'ipa', 'wwan')): ready, reason = transport(iface, set()) rows.append({'interface': iface.name, 'ready': ready, 'reason': reason}) return {'ready': any(row['ready'] for row in rows), 'interfaces': rows} def has_cellular_datapath(sys_path='/sys'): """Return whether a hardware transport is available for NM activation.""" return cellular_datapath_status(sys_path)['ready'] def check_battery_gate(min_capacity=15, min_voltage_uv=3700000, sys_path='/sys'): """Check if battery has sufficient capacity and voltage to safely support RF power burst.""" p = Path(sys_path) / 'class/power_supply' capacity = None voltage_uv = None bat_dirs = [] if (p / 'qcom-battery').is_dir(): bat_dirs.append(p / 'qcom-battery') if p.is_dir(): for d in p.iterdir(): if d.name.startswith(('battery', 'qcom-battery', 'bms')) and d not in bat_dirs: bat_dirs.append(d) for b in bat_dirs: cap_file = b / 'capacity' volt_file = b / 'voltage_now' if cap_file.exists(): try: capacity = int(cap_file.read_text().strip()) except (ValueError, OSError): pass if volt_file.exists(): try: voltage_uv = int(volt_file.read_text().strip()) except (ValueError, OSError): pass if capacity is not None or voltage_uv is not None: break if capacity is None and voltage_uv is None: return True, "Battery status unavailable in sysfs; gating skipped." reasons = [] if capacity is not None and capacity < min_capacity: reasons.append(f"capacity {capacity}% < {min_capacity}%") if voltage_uv is not None and voltage_uv < min_voltage_uv: reasons.append(f"voltage {voltage_uv}uV ({voltage_uv/1e6:.2f}V) < {min_voltage_uv}uV ({min_voltage_uv/1e6:.2f}V)") if reasons: return False, f"Battery gate failed: {', '.join(reasons)}. Modem held in low-power to prevent brownout." desc = [] if capacity is not None: desc.append(f"{capacity}%") if voltage_uv is not None: desc.append(f"{voltage_uv/1e6:.2f}V") return True, f"Battery gate passed: {', '.join(desc)}." def configure_radio_bands(rat='lte', bands='1,3', executor=subprocess.run): """Lock RAT and frequency bands via qmicli and mmcli to eliminate blind RF scanning.""" results = [] if shutil.which('qmicli') or executor is not subprocess.run: qmi_args = [] if rat: qmi_args.append(f'mode-pref={rat}') if bands: qmi_args.append(f'lte-band-preference={bands}') pref_str = ','.join(qmi_args) cmd = ['qmicli', '-p', '-d', 'qrtr://0', f'--nas-set-system-selection-preference={pref_str}'] try: executor(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) results.append(('qmicli-nas-pref', True, pref_str)) except Exception as exc: results.append(('qmicli-nas-pref', False, str(exc))) if shutil.which('mmcli') or executor is not subprocess.run: mm_mode = '4g' if rat.lower() == 'lte' else rat cmd = ['mmcli', '-m', 'any', f'--set-allowed-modes={mm_mode}', f'--set-preferred-mode={mm_mode}'] try: executor(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) results.append(('mmcli-modes', True, mm_mode)) except Exception as exc: results.append(('mmcli-modes', False, str(exc))) return results def set_operating_mode(mode='online', executor=subprocess.run): """Set modem operating mode (online, low-power, offline) via qmicli.""" cmd = ['qmicli', '-p', '-d', 'qrtr://0', f'--dms-set-operating-mode={mode}'] return executor(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) def load_modem_modules(executor=subprocess.run): """Load modem remoteproc and IPA kernel modules using --ignore-install to bypass modprobe.d disarm.""" cmds = [ ['modprobe', '--ignore-install', 'qcom_q6v5_mss'], ['modprobe', '--ignore-install', 'ipa'], ] results = [] for cmd in cmds: try: res = executor(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) results.append((cmd[-1], res.returncode == 0, res.stderr.strip() or res.stdout.strip())) except Exception as exc: results.append((cmd[-1], False, str(exc))) return results 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', 'no', 'ipv4.route-metric', '700', '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', 'no', 'ipv4.route-metric', '700'] commands.append(cmd) return commands def query_qmi_modem_info(executor=subprocess.run): """Query primary modem info directly via qmicli over qrtr://0 as fallback.""" if executor is subprocess.run and not shutil.which('qmicli'): return None try: proc_rev = executor(['qmicli', '-p', '-d', 'qrtr://0', '--dms-get-revision'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=3) if proc_rev.returncode != 0: return None revision_m = re.search(r"Revision:\s*'([^']+)'", proc_rev.stdout) revision = revision_m.group(1) if revision_m else 'SDM660' proc_ids = executor(['qmicli', '-p', '-d', 'qrtr://0', '--dms-get-ids'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=3) imei_m = re.search(r"IMEI:\s*'([^']+)'", proc_ids.stdout) imei = imei_m.group(1) if imei_m else None proc_uim = executor(['qmicli', '-p', '-d', 'qrtr://0', '--uim-get-card-status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=3) sim_state = 'absent' app_state = 'none' if proc_uim.returncode == 0: slot1_match = re.search(r"Slot \[1\]:.*?(?=Slot \[2\]|\Z)", proc_uim.stdout, re.DOTALL) if slot1_match: slot1_text = slot1_match.group(0) card_m = re.search(r"Card state:\s*'([^']+)'", slot1_text) app_m = re.search(r"Application state:\s*'([^']+)'", slot1_text) if card_m: sim_state = card_m.group(1) if app_m: app_state = app_m.group(1) proc_nas = executor(['qmicli', '-p', '-d', 'qrtr://0', '--nas-get-serving-system'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=3) reg_state = 'searching' if proc_nas.returncode == 0: reg_m = re.search(r"Registration state:\s*'([^']+)'", proc_nas.stdout) if reg_m: reg_state = reg_m.group(1) return { 'modem_path': 'qrtr://0', 'modem_index': '0 (QMI)', 'state': reg_state, 'equipment_id': imei, 'manufacturer': 'QUALCOMM INCORPORATED', 'model': 'SDM660', 'revision': revision, 'sim_slot_1': f"{sim_state} ({app_state})", 'signal_percent': None, 'operator_name': None, 'operator_code': None, 'access_tech': None, 'bearer_path': None, } except Exception: return None def query_modem_info(executor=subprocess.run): """Query primary modem info via mmcli, falling back to direct QMI over QRTR.""" if not (executor is subprocess.run and not shutil.which('mmcli')): 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 modem_matches: 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: pass qmi_info = query_qmi_modem_info(executor=executor) if qmi_info: return {'status': 'ok', 'modem': qmi_info} return {'status': 'no_modem', 'message': 'No Qualcomm modem detected by ModemManager or QMI'} 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, datapath_checker=has_cellular_datapath): """Activate or deactivate cellular data connection.""" if activate and not datapath_checker(): raise RuntimeError("No usable cellular hardware transport; an IPA v2.6 shim or interface name alone cannot carry data.") action = 'up' if activate else 'down' cmd = ['nmcli', 'connection', action, CONNECTION_NAME] return executor(cmd, check=True) def is_cellular_active(con_name=CONNECTION_NAME, executor=subprocess.run): """Check if the cellular connection is currently active.""" try: proc = executor(['nmcli', '-t', '-f', 'NAME', 'connection', 'show', '--active'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) active_names = [line.strip() for line in proc.stdout.splitlines() if line.strip()] return con_name in active_names except Exception: return False def enable_modem(modem_index=0, executor=subprocess.run): """Enable modem via mmcli.""" try: executor(['mmcli', '-m', str(modem_index), '-e'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) return True except Exception: return False def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None, executor=subprocess.run, sleeper=time.sleep, logger=print, datapath_checker=has_cellular_datapath, battery_checker=check_battery_gate, band_locker=configure_radio_bands, rat='lte', bands='1,3'): """Wait for modem and SIM, configure APN automatically, and connect. If daemon is True, runs continuously monitoring connection and carrier state. """ logger("Starting Platina cellular auto-connect...") attempts = 0 last_operator = None last_state = None rf_locked = False while True: attempts += 1 if max_attempts is not None and attempts > max_attempts: logger(f"Reached maximum attempts ({max_attempts}), stopping.") return False if not datapath_checker(): if last_state != 'no_datapath': logger("No hardware IPA or rmnet cellular data path detected in kernel; dialing skipped to maintain modem and Wi-Fi stability.") last_state = 'no_datapath' if not daemon: return False sleeper(poll_interval) continue # Battery gate check: do not allow RF transmit if battery voltage/capacity is low bat_ok, bat_msg = battery_checker() if not bat_ok: logger(bat_msg) try: set_operating_mode('low-power', executor=executor) except Exception: pass if not daemon and max_attempts is not None and attempts >= max_attempts: return False sleeper(poll_interval) continue # Lock radio frequency bands and RAT to eliminate blind scanning if not rf_locked: logger(f"Locking radio to RAT={rat}, bands={bands} to prevent RF peak current spikes...") band_locker(rat=rat, bands=bands, executor=executor) try: set_operating_mode('online', executor=executor) except Exception: pass rf_locked = True modem_info = query_modem_info(executor=executor) if modem_info.get('status') != 'ok': if last_state != 'no_modem': logger(f"Waiting for modem: {modem_info.get('message')}") last_state = 'no_modem' if not daemon and max_attempts is not None and attempts >= max_attempts: return False sleeper(poll_interval) continue modem = modem_info['modem'] modem_idx = modem.get('modem_index', '0') state = modem.get('state', 'unknown') operator_code = modem.get('operator_code') operator_name = modem.get('operator_name') if state == 'disabled': logger(f"Modem {modem_idx} is disabled; enabling...") enable_modem(modem_idx, executor=executor) sleeper(2) continue if state in ('failed', 'locked'): if last_state != state: logger(f"Modem state: {state} (cannot auto-connect in this state)") last_state = state if not daemon: return False sleeper(poll_interval) continue if state in ('searching', 'initializing', 'enabling') and not operator_code: if daemon or (max_attempts is None or attempts < max_attempts): wait_key = f'waiting_{state}' if last_state != wait_key: logger(f"Modem state is {state} without operator PLMN; waiting for registration...") last_state = wait_key sleeper(poll_interval) continue # Determine APN for current operator apn = detect_apn_for_operator( operator_code, fallback='cmnet' if (operator_code and str(operator_code).startswith('460')) else 'internet' ) # If operator changed or initial setup if operator_code != last_operator or last_operator is None: carrier_desc = operator_name or 'Unknown' code_desc = operator_code or 'N/A' logger(f"Detected carrier: {carrier_desc} (MCC/MNC: {code_desc}), APN: '{apn}'") try: configure_cellular(apn=apn, executor=executor) last_operator = operator_code logger(f"Configured {CONNECTION_NAME} with APN '{apn}'") except Exception as exc: logger(f"Failed to configure cellular connection: {exc}") # Check and ensure connection activation active = is_cellular_active(CONNECTION_NAME, executor=executor) if not active: if state in ('registered', 'connected', 'enabled', 'searching'): logger(f"Modem state is {state}; activating {CONNECTION_NAME}...") try: toggle_cellular(activate=True, executor=executor, datapath_checker=datapath_checker) logger(f"Connection {CONNECTION_NAME} activated.") last_state = 'active' except Exception as exc: logger(f"Activation failed (will retry): {exc}") else: if last_state != 'active': logger(f"Cellular connection {CONNECTION_NAME} is active and connected.") last_state = 'active' if not daemon: return is_cellular_active(CONNECTION_NAME, executor=executor) # In daemon mode, sleep before next monitoring cycle sleeper(poll_interval) 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('--auto', action='store_true', help='Automatically detect SIM, configure APN and connect') parser.add_argument('--daemon', action='store_true', help='Run continuously in background to maintain connection') parser.add_argument('--once', action='store_true', help='Run auto setup once and exit') parser.add_argument('--poll-interval', type=int, default=10, help='Polling interval in seconds (default: 10)') parser.add_argument('--max-attempts', type=int, default=None, help='Maximum attempts for non-daemon auto mode') parser.add_argument('--json', action='store_true', help='Output in JSON format') parser.add_argument('--optimize-rf', action='store_true', help='Lock RAT and frequency bands (default: LTE B1,B3 for Unicom)') parser.add_argument('--rat', type=str, default='lte', help='Radio Access Technology preference (default: lte)') parser.add_argument('--bands', type=str, default='1,3', help='LTE band preference list (default: 1,3)') parser.add_argument('--battery-check', action='store_true', help='Check battery gate threshold and exit') parser.add_argument('--load-modules', action='store_true', help='Load modem and IPA kernel modules via --ignore-install') parser.add_argument('--low-power', action='store_true', help='Set modem to low-power operating mode') parser.add_argument('--online', action='store_true', help='Set modem to online operating mode (with battery gate check)') parser.add_argument('--force', action='store_true', help='Bypass battery gate checks') args = parser.parse_args() if args.battery_check: ok, msg = check_battery_gate() print(f"[{'PASS' if ok else 'FAIL'}] {msg}") return 0 if ok else 1 if args.load_modules: if not args.force: ok, msg = check_battery_gate() if not ok: print(f"[REJECTED] {msg} (use --force to override)") return 1 print("Loading modem and IPA kernel modules (with --ignore-install)...") results = load_modem_modules() all_ok = True for mod, ok, detail in results: status = 'OK' if ok else 'FAIL' if not ok: all_ok = False print(f" [{status}] {mod}: {detail}") return 0 if all_ok else 1 if args.optimize_rf: print(f"Applying RF band locks: RAT={args.rat}, bands={args.bands}...") results = configure_radio_bands(rat=args.rat, bands=args.bands) for name, ok, detail in results: print(f" [{'OK' if ok else 'FAIL'}] {name}: {detail}") return 0 if args.low_power: try: set_operating_mode('low-power') print("Modem set to low-power mode.") return 0 except Exception as exc: print(f"Failed to set low-power mode: {exc}") return 1 if args.online: if not args.force: ok, msg = check_battery_gate() if not ok: print(f"[REJECTED] {msg} (use --force to override)") return 1 try: set_operating_mode('online') print("Modem set to online mode.") return 0 except Exception as exc: print(f"Failed to set online mode: {exc}") return 1 if args.status: result = query_modem_info() datapath = cellular_datapath_status() if args.json: result['has_datapath'] = datapath['ready'] result['datapath'] = datapath print(json.dumps(result, indent=2)) else: if result.get('status') == 'ok': modem = result['modem'] print(f"Modem Path: {modem.get('modem_path', 'unknown')}") print(f"Modem Index: {modem.get('modem_index', '0')}") print(f"State: {modem.get('state', 'unknown')}") if modem.get('equipment_id'): print(f"IMEI: {modem.get('equipment_id')}") if modem.get('sim_slot_1'): print(f"SIM Slot 1: {modem.get('sim_slot_1')}") if modem.get('operator_name') or modem.get('operator_code'): print(f"Operator: {modem.get('operator_name')} ({modem.get('operator_code')})") print(f"Recommended APN: {detect_apn_for_operator(modem.get('operator_code'))}") if modem.get('signal_percent') is not None: print(f"Signal Quality: {modem.get('signal_percent')}%") if modem.get('access_tech'): print(f"Access Tech: {modem.get('access_tech')}") if not datapath['ready']: print("Data Path: Unavailable (no usable hardware transport)") for row in datapath['interfaces']: print(f" {row['interface']}: {row['reason']}") else: print(f"Cellular Status: {result.get('message')}") return 0 if args.auto or args.daemon: daemon_mode = args.daemon or (args.auto and not args.once) success = run_auto_connect( daemon=daemon_mode, poll_interval=args.poll_interval, max_attempts=args.max_attempts, rat=args.rat, bands=args.bands, ) return 0 if success else 1 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: if not args.force: ok, msg = check_battery_gate() if not ok: print(f"[REJECTED] {msg} (use --force to override)") return 1 try: toggle_cellular(activate=True) print(f"Activated {CONNECTION_NAME}") return 0 except Exception as exc: print(f"Cannot activate {CONNECTION_NAME}: {exc}") return 1 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())