From 8b7e9690d89e8a0c732d59f1542098d538df109a Mon Sep 17 00:00:00 2001 From: shenlei Date: Mon, 9 Nov 2026 17:53:55 +0900 Subject: [PATCH] fix(cellular, touch): prevent baseband crash loop, add touch NULL guard, and safe SIM info queries - Guard cellular auto-dialing: check for active IPA/rmnet hardware datapath before connecting, avoiding Hexagon modem DSP assert panics. - Disable connection.autoconnect on cellular network profiles to prevent NetworkManager auto-dial loops. - Add QMI fallback for modem/SIM status queries when ModemManager lacks netdev port. - Fix Novatek touchscreen driver NULL pointer dereference on panel unprepare/suspend (0041 patch). - Bump candidate kernel release to 7.2.12-r14 with updated checksums and DT binding supplies. - Add comprehensive test coverage for cellular datapath detection and connection guards. --- ...tina-touch-dual-panel-vsp-power-dvfs.patch | 5 +- .../0041-novatek-nvt-ts-null-check.patch | 41 +++ .../linux-postmarketos-qcom-sdm660/APKBUILD | 6 +- project/sources.lock.json | 2 +- scripts/image-runtime.py | 1 + scripts/phone-cellular-setup.py | 309 ++++++++++++++++-- scripts/phone-headless.start | 3 + tests/test_cellular_setup.py | 128 +++++++- tests/test_image_runtime.py | 1 + 9 files changed, 460 insertions(+), 36 deletions(-) create mode 100644 ports/candidate/linux-postmarketos-qcom-sdm660/0041-novatek-nvt-ts-null-check.patch diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch index cb830d6..fce324e 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch @@ -8,7 +8,7 @@ Subject: [PATCH] arm64: dts: qcom: platina: add dual touch, BOE panel, cut VSP/V --- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts +++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts -@@ -1182,3 +1182,50 @@ +@@ -1182,3 +1182,51 @@ &pm660_haptics { status = "okay"; }; @@ -32,7 +32,8 @@ Subject: [PATCH] arm64: dts: qcom: platina: add dual touch, BOE panel, cut VSP/V + compatible = "novatek,NVT-ts", "novatek,nt36672a-ts"; + reg = <0x62>; + -+ vddio-supply = <&vreg_l11a_1p8>; ++ vcc-supply = <&panel_vsp>; ++ iovcc-supply = <&vreg_l11a_1p8>; + panel = <&panel>; + + pinctrl-0 = <&ts_int_active &ts_rst_n>; diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0041-novatek-nvt-ts-null-check.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0041-novatek-nvt-ts-null-check.patch new file mode 100644 index 0000000..01451a1 --- /dev/null +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0041-novatek-nvt-ts-null-check.patch @@ -0,0 +1,41 @@ +From: Antigravity +Subject: [PATCH] Input: novatek-nvt-ts - fix NULL pointer dereference in follower unprepare + +When on_novatek_panel_prepared fails to initialize the touch controller +(e.g., due to unsupported parameters or communication error), data->input +is never allocated. During unprepare or suspend, accessing data->input->mutex +causes a kernel NULL pointer dereference. +Add NULL checks before accessing data->input in unprepare, suspend, and resume. + +--- a/drivers/input/touchscreen/novatek-nvt-ts.c ++++ b/drivers/input/touchscreen/novatek-nvt-ts.c +@@ -194,6 +194,9 @@ + if (data->is_panel_follower) + return 0; + ++ if (!data->input) ++ return 0; ++ + guard(mutex)(&data->input->mutex); + + if (input_device_enabled(data->input)) +@@ -208,6 +211,9 @@ + if (data->is_panel_follower) + return 0; + ++ if (!data->input) ++ return 0; ++ + guard(mutex)(&data->input->mutex); + + if (input_device_enabled(data->input)) +@@ -350,6 +356,9 @@ + struct nvt_ts_data *data = container_of(follower, struct nvt_ts_data, panel_follower); + dev_info(&data->client->dev, "%s\n", __func__); // REMOVEME + ++ if (!data->input) ++ return 0; ++ + guard(mutex)(&data->input->mutex); + + if (input_device_enabled(data->input)) diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD index 49f4710..914d47f 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD @@ -3,7 +3,7 @@ maintainer="Alexey Minnekhanov " _flavor="postmarketos-qcom-sdm660" pkgname=linux-$_flavor pkgver=7.2.12 -pkgrel=13 +pkgrel=14 pkgdesc="Close to mainline linux kernel for Qualcomm Snapdragon 660 SoC" arch="aarch64" url="https://kernel.org/" @@ -68,6 +68,7 @@ source=" 0038-imx363-platina-legacy-frequency.patch 0039-venus-legacy-h264-transform.patch 0040-platina-touch-dual-panel-vsp-power-dvfs.patch + 0041-novatek-nvt-ts-null-check.patch stable-7.2.3-4.patch stable-7.2.4-5.patch stable-7.2.5-6.patch @@ -163,7 +164,8 @@ ecfee5c3fde9c5342195d5e25f7103d909144d9602497aa4de713fc55d9c03f89601081535d43da7 62031fc20f13bec1bc9a0a67134a2967acbf76cd2d9d3eea9cf5d8176d5bbe61e0063b165b9caf959ec8d923fbb8897cb7421c723d38d695da51a2cb3eddf6c2 0037-imx363-full-field-binning.patch b1094708de883b3aecaf52ddc7f9315c150f6234165ab02ef7a021bc18da4d56cc5eab0f9239583a3b596c307ef71b891f0d735d889156e783b7bb21ba26b448 0038-imx363-platina-legacy-frequency.patch 61a598e63d83c0489ba130231cd0a4c2dc4351de5c122cef9b7170f7f516bae7573c744535035c53e2642a96d13fe5048c07e4c908de8f64c90a3cd8809ee84c 0039-venus-legacy-h264-transform.patch -10c8cfcdb1dd5019d02f2657fdb6bc8a53fe9ac1fe3fd64a1ebaea3aee67717492606b1a97f47d58d6d9812c0ae332e8633e3abaac0d6e08050dbaf800ca563b 0040-platina-touch-dual-panel-vsp-power-dvfs.patch +2af6e0d149474ae8fabdd78d7156ef6f68ae5a86ceac2565c80daa517bfb9ab04bbf9c96ccec8ae121c211ead1e8304e2d572be489c61022e0157ed00c21097e 0040-platina-touch-dual-panel-vsp-power-dvfs.patch +8281e2c1f453410f2e0a76791bc9387117e92d9390d70e75bb24b6f3aa727860ae7b35645cd2adc79fba3789f9c8bea7203743a0527a7f323fecfd2152a0ee81 0041-novatek-nvt-ts-null-check.patch 1a7f9cf2443c0f059ac64a78dddee77fca584288edeea943aa45db05fb5e3b7b2930dab595f6c0911671bf5517bd64550a65b097f47d5179cc7454ec90db56cd stable-7.2.3-4.patch 303d4a717c67d5dbb5d17c37882b3ef1b6b44b3cf9b17723a611efe1f028019d5ef53c0e3595ed79f5468a46ede2d640171b9dd97ce2dd99b487d0406ef79f16 stable-7.2.4-5.patch b09a94d0eb3c0382ad8998843019ea0d52ae5a89ad7ba54072b21eeea2c7ee602c57a32a0d9b99a2c5ae1f581dadc4d4395096e905b54678affc18125d9b8cba stable-7.2.5-6.patch diff --git a/project/sources.lock.json b/project/sources.lock.json index e36f373..14aa9b9 100644 --- a/project/sources.lock.json +++ b/project/sources.lock.json @@ -16,7 +16,7 @@ "candidate": { "ports": "ports/candidate", "kernel": "7.2.12", - "kernel_package": "7.2.12-r13", + "kernel_package": "7.2.12-r14", "device_package": "5-r31", "firmware_package": "2-r5" } diff --git a/scripts/image-runtime.py b/scripts/image-runtime.py index 06fae98..aa69887 100644 --- a/scripts/image-runtime.py +++ b/scripts/image-runtime.py @@ -26,6 +26,7 @@ HELPERS = { 'scripts/phone-headless.start': 'etc/local.d/platina-headless.start', 'scripts/phone-usb-power.py': 'usr/local/sbin/platina-usb-power', 'scripts/phone-usb-power-dispatcher.sh': 'etc/NetworkManager/dispatcher.d/90-platina-usb-power', + 'scripts/phone-cellular-setup.py': 'usr/local/sbin/platina-cellular', 'scripts/image-runtime.py': 'usr/local/libexec/platina-image-runtime', } CONFIG = 'etc/conf.d/platina-power-chord' diff --git a/scripts/phone-cellular-setup.py b/scripts/phone-cellular-setup.py index f1f2af1..0292f7e 100755 --- a/scripts/phone-cellular-setup.py +++ b/scripts/phone-cellular-setup.py @@ -3,25 +3,32 @@ """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 @@ -38,7 +45,17 @@ def detect_apn_for_operator(operator_code, fallback='internet'): if not operator_code: return fallback clean_code = str(operator_code).strip() - return KNOWN_OPERATOR_APNS.get(clean_code, fallback) + 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): @@ -84,6 +101,29 @@ def parse_mmcli_modem_info(raw_text): return info +def has_cellular_datapath(sys_path='/sys'): + """Check if kernel has an active hardware cellular data path (bound IPA device or rmnet/wwan network interface).""" + p = Path(sys_path) + net_dir = p / 'class/net' + if net_dir.is_dir(): + try: + for iface in net_dir.iterdir(): + if iface.name.startswith(('rmnet', 'ipa', 'wwan0')): + return True + except OSError: + pass + ipa_driver = p / 'bus/platform/drivers/ipa' + if ipa_driver.is_dir(): + try: + ignored = {'bind', 'unbind', 'uevent', 'module'} + for item in ipa_driver.iterdir(): + if item.name not in ignored: + return True + except OSError: + pass + return False + + 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 [] @@ -92,7 +132,7 @@ def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*' commands.append(['nmcli', 'connection', 'modify', con_name, 'gsm.apn', apn, 'gsm.auto-config', 'yes', - 'connection.autoconnect', 'yes', + 'connection.autoconnect', 'no', 'connection.interface-name', ifname if ifname != '*' else '']) else: cmd = ['nmcli', 'connection', 'add', @@ -101,28 +141,92 @@ def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*' 'ifname', ifname, 'apn', apn, 'gsm.auto-config', 'yes', - 'connection.autoconnect', 'yes'] + 'connection.autoconnect', 'no'] 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'} +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 = 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)} + 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): @@ -150,13 +254,131 @@ def configure_cellular(apn=None, ifname='*', executor=subprocess.run): return {'connection': CONNECTION_NAME, 'apn': chosen_apn, 'ifname': ifname} -def toggle_cellular(activate=True, executor=subprocess.run): +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 hardware IPA or rmnet cellular data path in kernel; activation skipped to protect modem stability.") 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): + """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...") + + if not datapath_checker(): + logger("No hardware IPA or rmnet cellular data path detected in kernel; dialing skipped to maintain modem and Wi-Fi stability.") + return False + + attempts = 0 + last_operator = None + last_state = None + + while True: + attempts += 1 + if max_attempts is not None and attempts > max_attempts: + logger(f"Reached maximum attempts ({max_attempts}), stopping.") + return False + + 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 + + # 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') @@ -165,6 +387,11 @@ def main(): 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') args = parser.parse_args() @@ -172,20 +399,40 @@ def main(): if args.status: result = query_modem_info() if args.json: + result['has_datapath'] = has_cellular_datapath() 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'))}") + 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 has_cellular_datapath(): + print("Data Path: Disabled (IPA hardware datapath not present in kernel)") 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, + ) + return 0 if success else 1 + if args.setup: res = configure_cellular(apn=args.apn, ifname=args.interface) if args.json: @@ -195,9 +442,13 @@ def main(): return 0 if args.up: - toggle_cellular(activate=True) - print(f"Activated {CONNECTION_NAME}") - return 0 + 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) diff --git a/scripts/phone-headless.start b/scripts/phone-headless.start index 477c8c9..10df8e8 100755 --- a/scripts/phone-headless.start +++ b/scripts/phone-headless.start @@ -24,4 +24,7 @@ if [ -x /usr/local/sbin/platina-splash ] && [ -r /usr/local/share/platina/curren done ) >> /var/log/platina-splash.log 2>&1 & fi +if [ -x /usr/local/sbin/platina-cellular ]; then + /usr/local/sbin/platina-cellular --auto >> /var/log/platina-cellular.log 2>&1 & +fi exit 0 diff --git a/tests/test_cellular_setup.py b/tests/test_cellular_setup.py index a00cc4a..265162a 100644 --- a/tests/test_cellular_setup.py +++ b/tests/test_cellular_setup.py @@ -74,6 +74,10 @@ class CellularSetupTests(unittest.TestCase): self.assertIn('add', cmds[0]) self.assertIn('cmnet', cmds[0]) self.assertIn('platina-cellular', cmds[0]) + # Ensure autoconnect is disabled to prevent NetworkManager dialing without IPA + self.assertIn('connection.autoconnect', cmds[0]) + idx = cmds[0].index('connection.autoconnect') + self.assertEqual(cmds[0][idx + 1], 'no') def test_build_nmcli_setup_commands_existing(self): cmds = cellular.build_nmcli_setup_commands( @@ -86,6 +90,9 @@ class CellularSetupTests(unittest.TestCase): self.assertIn('modify', cmds[0]) self.assertIn('3gnet', cmds[0]) self.assertIn('platina-cellular', cmds[0]) + self.assertIn('connection.autoconnect', cmds[0]) + idx = cmds[0].index('connection.autoconnect') + self.assertEqual(cmds[0][idx + 1], 'no') def test_configure_cellular_invokes_executor(self): recorded_calls = [] @@ -112,12 +119,129 @@ class CellularSetupTests(unittest.TestCase): recorded_calls.append(cmd) return subprocess.CompletedProcess(cmd, 0) - cellular.toggle_cellular(activate=True, executor=mock_executor) + cellular.toggle_cellular(activate=True, executor=mock_executor, datapath_checker=lambda: True) self.assertEqual(recorded_calls[-1], ['nmcli', 'connection', 'up', 'platina-cellular']) - cellular.toggle_cellular(activate=False, executor=mock_executor) + cellular.toggle_cellular(activate=False, executor=mock_executor, datapath_checker=lambda: True) self.assertEqual(recorded_calls[-1], ['nmcli', 'connection', 'down', 'platina-cellular']) + # Without datapath, activating must raise RuntimeError + with self.assertRaises(RuntimeError): + cellular.toggle_cellular(activate=True, executor=mock_executor, datapath_checker=lambda: False) + + def test_is_cellular_active(self): + def mock_active(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, 0, stdout='platina-usb\nplatina-cellular\n', stderr='') + + def mock_inactive(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, 0, stdout='platina-usb\n', stderr='') + + def mock_error(cmd, **kwargs): + raise subprocess.CalledProcessError(1, cmd) + + self.assertTrue(cellular.is_cellular_active(executor=mock_active)) + self.assertFalse(cellular.is_cellular_active(executor=mock_inactive)) + self.assertFalse(cellular.is_cellular_active(executor=mock_error)) + + def test_enable_modem(self): + recorded_calls = [] + + def mock_executor(cmd, **kwargs): + recorded_calls.append(cmd) + return subprocess.CompletedProcess(cmd, 0) + + res = cellular.enable_modem(modem_index=0, executor=mock_executor) + self.assertTrue(res) + self.assertEqual(recorded_calls[-1], ['mmcli', '-m', '0', '-e']) + + def test_run_auto_connect(self): + recorded_calls = [] + logs = [] + + active_state = [False] + + def mock_executor(cmd, **kwargs): + recorded_calls.append(cmd) + cmd_str = ' '.join(cmd) + if 'mmcli -L' in cmd_str: + return subprocess.CompletedProcess(cmd, 0, + stdout='/org/freedesktop/ModemManager1/Modem/0 [QUALCOMM] SDM660\n', stderr='') + if 'mmcli -m 0' in cmd_str: + return subprocess.CompletedProcess(cmd, 0, stdout=SAMPLE_MMCLI_OUTPUT, stderr='') + if 'connection show --active' in cmd_str: + out = 'platina-cellular\n' if active_state[0] else 'platina-usb\n' + return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr='') + if 'connection show' in cmd_str: + return subprocess.CompletedProcess(cmd, 0, stdout='platina-usb\n', stderr='') + if 'connection up' in cmd_str: + active_state[0] = True + return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='') + return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='') + + # Run with max_attempts=1, daemon=False, with hardware datapath present + res = cellular.run_auto_connect( + daemon=False, + poll_interval=1, + max_attempts=2, + executor=mock_executor, + sleeper=lambda s: None, + logger=logs.append, + datapath_checker=lambda: True, + ) + self.assertTrue(res) + self.assertTrue(active_state[0]) + self.assertTrue(any('Detected carrier' in log for log in logs)) + self.assertTrue(any('Connection platina-cellular activated' in log for log in logs)) + + def test_has_cellular_datapath(self): + import tempfile + with tempfile.TemporaryDirectory() as tmpdir: + base = Path(tmpdir) + # Case 1: Empty sysfs -> False + self.assertFalse(cellular.has_cellular_datapath(tmpdir)) + + # Case 2: Driver dir exists with only control files -> False + driver_dir = base / 'bus/platform/drivers/ipa' + driver_dir.mkdir(parents=True) + for f in ('bind', 'unbind', 'uevent', 'module'): + (driver_dir / f).touch() + self.assertFalse(cellular.has_cellular_datapath(tmpdir)) + + # Case 3: Driver dir has bound device symlink/dir -> True + (driver_dir / '1e40000.ipa').mkdir() + self.assertTrue(cellular.has_cellular_datapath(tmpdir)) + (driver_dir / '1e40000.ipa').rmdir() + + # Case 4: Network interface rmnet0 exists -> True + net_dir = base / 'class/net' + net_dir.mkdir(parents=True) + (net_dir / 'lo').mkdir() + (net_dir / 'usb0').mkdir() + self.assertFalse(cellular.has_cellular_datapath(tmpdir)) + (net_dir / 'rmnet0').mkdir() + self.assertTrue(cellular.has_cellular_datapath(tmpdir)) + + def test_run_auto_connect_no_datapath_skips_dialing(self): + recorded_calls = [] + logs = [] + + def mock_executor(cmd, **kwargs): + recorded_calls.append(cmd) + return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='') + + res = cellular.run_auto_connect( + daemon=False, + poll_interval=1, + max_attempts=2, + executor=mock_executor, + sleeper=lambda s: None, + logger=logs.append, + datapath_checker=lambda: False, + ) + self.assertFalse(res) + self.assertEqual(recorded_calls, []) + self.assertTrue(any('dialing skipped' in log for log in logs)) + if __name__ == '__main__': unittest.main() diff --git a/tests/test_image_runtime.py b/tests/test_image_runtime.py index 5b89584..3be244f 100644 --- a/tests/test_image_runtime.py +++ b/tests/test_image_runtime.py @@ -46,6 +46,7 @@ class ImageRuntimeTests(unittest.TestCase): files = {str(p.relative_to(self.root)) for p in self.root.rglob('*') if p.is_file()} self.assertFalse(any('usb-off' in name or name.endswith('.ko') for name in files)) self.assertTrue((self.root / 'etc/NetworkManager/dispatcher.d/90-platina-usb-power').is_file()) + self.assertTrue((self.root / 'usr/local/sbin/platina-cellular').is_file()) self.assertFalse((self.root / 'etc/platina/usb-power.json').exists()) def test_missing_shutdown_helper_is_rejected(self):