fix(cellular, touch): prevent baseband crash loop, add touch NULL guard, and safe SIM info queries
Offline project checks / check (push) Canceled after 0s
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.
This commit is contained in:
@@ -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'
|
||||
|
||||
+280
-29
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user