|
| 1 | +""" MacOS airport functions """ |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | +import typing as T |
| 5 | +import shutil |
| 6 | +import io |
| 7 | +import logging |
| 8 | +import subprocess |
| 9 | +import re |
| 10 | + |
| 11 | +EXE = shutil.which("airport", path="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources") |
| 12 | +if not EXE: |
| 13 | + raise ImportError("Could not find Airport") |
| 14 | + |
| 15 | + |
| 16 | +def cli_config_check() -> bool: |
| 17 | + # %% check that Airport is available and WiFi is active |
| 18 | + ret = subprocess.run([EXE, "--getinfo"], stdout=subprocess.PIPE, text=True, timeout=30) |
| 19 | + |
| 20 | + if ret.returncode != 0: |
| 21 | + return False |
| 22 | + |
| 23 | + stdout = ret.stdout.strip().lower() |
| 24 | + if len(stdout) == "airport: off": |
| 25 | + return False |
| 26 | + |
| 27 | + if "state: running" in stdout: |
| 28 | + return True |
| 29 | + |
| 30 | + logging.error("could not determine WiFi state.") |
| 31 | + return False |
| 32 | + |
| 33 | + |
| 34 | +def get_signal() -> list[dict[str, T.Any]]: |
| 35 | + |
| 36 | + ret = subprocess.run([EXE, "-s"], timeout=30.0, stdout=subprocess.PIPE, text=True) |
| 37 | + |
| 38 | + if ret.returncode != 0: |
| 39 | + logging.error("consider slowing scan cadence.") |
| 40 | + |
| 41 | + pat = re.compile(r"\s*([0-9a-zA-Z\-\.]+)\s+([0-9a-f]{2}(?::[0-9a-f]{2}){5})\s+(-\d{2,3})") |
| 42 | + dat: list[dict[str, str]] = [] |
| 43 | + |
| 44 | + for line in io.StringIO(ret.stdout): |
| 45 | + mat = pat.match(line) |
| 46 | + if mat: |
| 47 | + ssid = mat.group(1) |
| 48 | + # optout |
| 49 | + if ssid.endswith("_nomap"): |
| 50 | + continue |
| 51 | + |
| 52 | + dat.append({"ssid": ssid, "macAddress": mat.group(2), "signalStrength": mat.group(3)}) |
| 53 | + |
| 54 | + return dat |
0 commit comments