feat: add WCN3990 Wi-Fi bringup service, battery protection, and bringup automation
Offline project checks / check (push) Canceled after 0s

- Add phone-dsp.openrc to initialize Hexagon DSP, rmtfs, pd-mapper, and ath10k_snoc
- Update phone-battery-guard threshold to 80% with power supply node fallbacks
- Enhance phone-cellular-setup with battery gate checks, RF locks, and unit tests
- Include bringup, flashing, and inspection automation scripts for platina
- Update candidate IPA v2.6 patches and package locks
This commit is contained in:
shenlei
2026-11-12 14:54:23 +09:00
parent 225ad54930
commit 530a3690da
34 changed files with 4103 additions and 47 deletions
+196 -1
View File
@@ -124,6 +124,108 @@ def has_cellular_datapath(sys_path='/sys'):
return False
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 []
@@ -286,7 +388,10 @@ def enable_modem(modem_index=0, executor=subprocess.run):
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):
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.
@@ -300,6 +405,7 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
attempts = 0
last_operator = None
last_state = None
rf_locked = False
while True:
attempts += 1
@@ -307,6 +413,29 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
logger(f"Reached maximum attempts ({max_attempts}), stopping.")
return False
# 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':
@@ -393,9 +522,68 @@ def main():
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()
if args.json:
@@ -430,6 +618,8 @@ def main():
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
@@ -442,6 +632,11 @@ def main():
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}")