65 lines
2.3 KiB
Python
65 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only ModemManager inventory for the adaptive shell.
|
|
|
|
No SIM secrets are read, no privileged actions are attempted. JSON is stable
|
|
across a missing mmcli, an empty device list, and transient modem removal.
|
|
"""
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
|
|
|
|
def run(*args):
|
|
proc = subprocess.run(['mmcli', *args, '--output-json'], capture_output=True,
|
|
text=True, timeout=8, check=False)
|
|
if proc.returncode:
|
|
raise RuntimeError(proc.stderr.strip()[:240] or 'ModemManager unavailable')
|
|
return json.loads(proc.stdout)
|
|
|
|
|
|
def modem_paths(payload):
|
|
value = payload.get('modem-list', [])
|
|
if isinstance(value, dict):
|
|
value = value.get('modems', [])
|
|
return [p for p in value if isinstance(p, str) and re.fullmatch(r'/org/freedesktop/ModemManager1/Modem/\d+', p)]
|
|
|
|
|
|
def describe(payload, path):
|
|
modem = payload.get('modem', {})
|
|
generic = modem.get('generic', {})
|
|
threegpp = modem.get('3gpp', {})
|
|
signal = generic.get('signal-quality', {})
|
|
if isinstance(signal, dict):
|
|
signal = signal.get('value', 0)
|
|
sim = generic.get('sim', '')
|
|
return {
|
|
'id': path.rsplit('/', 1)[-1],
|
|
'manufacturer': str(generic.get('manufacturer', '')),
|
|
'model': str(generic.get('model', '')),
|
|
'state': str(generic.get('state', 'unknown')),
|
|
'signal': signal if isinstance(signal, (int, float)) else 0,
|
|
'simPresent': isinstance(sim, str) and bool(sim) and sim != '--',
|
|
'operator': str(threegpp.get('operator-name', '')),
|
|
}
|
|
|
|
|
|
def snapshot():
|
|
if not shutil.which('mmcli'):
|
|
return {'backend': 'unavailable', 'modems': [], 'error': 'mmcli not installed'}
|
|
try:
|
|
paths = modem_paths(run('-L'))
|
|
devices = []
|
|
for path in paths:
|
|
try:
|
|
devices.append(describe(run('-m', path), path))
|
|
except (RuntimeError, ValueError, subprocess.TimeoutExpired) as exc:
|
|
devices.append({'id': path.rsplit('/', 1)[-1], 'state': 'error', 'error': str(exc)})
|
|
return {'backend': 'available', 'modems': devices, 'error': ''}
|
|
except (RuntimeError, ValueError, subprocess.TimeoutExpired, OSError) as exc:
|
|
return {'backend': 'error', 'modems': [], 'error': str(exc)}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
print(json.dumps(snapshot(), ensure_ascii=False))
|