Offline project checks / check (push) Canceled after 0s
- 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.
464 lines
18 KiB
Python
Executable File
464 lines
18 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 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 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 []
|
|
commands = []
|
|
if con_name in existing:
|
|
commands.append(['nmcli', 'connection', 'modify', con_name,
|
|
'gsm.apn', apn,
|
|
'gsm.auto-config', 'yes',
|
|
'connection.autoconnect', 'no',
|
|
'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']
|
|
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 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')
|
|
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')
|
|
|
|
args = parser.parse_args()
|
|
|
|
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 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:
|
|
print(json.dumps(res, indent=2))
|
|
else:
|
|
print(f"Configured {res['connection']} with APN '{res['apn']}'")
|
|
return 0
|
|
|
|
if args.up:
|
|
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())
|