diff --git a/openpilot/starpilot/system/starport/car_interface.py b/openpilot/starpilot/system/starport/car_interface.py index e89601be6f..4ab0fecfc2 100644 --- a/openpilot/starpilot/system/starport/car_interface.py +++ b/openpilot/starpilot/system/starport/car_interface.py @@ -30,6 +30,8 @@ READY_TIMEOUT_S = 5.0 DEDICATED_TIMEOUTS = 2 HOME_RETRY_S = 60.0 HOME_RETRY_MAX_S = 300.0 +HOME_CHECK_S = 30.0 # how often a held wlan0 looks for an allowed network to join +HOTSPOT_PAUSE_WAIT_S = 10.0 class DedicatedInterface: @@ -85,11 +87,24 @@ class DedicatedInterface: child.stdout.close() +def _join_policy() -> dict: + from openpilot.starpilot.galaxy.network_prefs import read_prefs + return read_prefs() + + +def _hotspot(): + try: + from openpilot.starpilot.galaxy import hotspot + return hotspot + except Exception: + return None + + class DedicatedLease: """The car's Wi-Fi on aa0, falling back to the legacy lease on wlan0 for a session that cannot use it.""" def __init__(self, log: Callable[..., None], fallback_interface: str, lease_factory, interface_factory=None, - enabled: bool = True): + enabled: bool = True, join_policy: Callable[[], dict] | None = None, hotspot=None): self.log, self.fallback_interface = log, fallback_interface self.lease_factory, self.interface_factory = lease_factory, interface_factory or DedicatedInterface self.enabled = enabled @@ -106,6 +121,8 @@ class DedicatedLease: self._home_lock = threading.Lock() self._home_retry: threading.Timer | None = None self._home_holds = 0 + self._join_stalled = False + self.join_policy, self.hotspot = join_policy or _join_policy, hotspot if hotspot is not None else _hotspot() @property def local_ip(self): @@ -163,7 +180,11 @@ class DedicatedLease: def hold_home_wifi(self) -> None: """Hold wlan0 off the shared radio; each hold lasts longer, up to HOME_RETRY_MAX_S.""" with self._home_lock: - if self.legacy or self._cancel.is_set() or self.home is not None: + if self.legacy or self._cancel.is_set(): + return + if self.home is not None: + if self._home_retry is None: + self._arm(HOME_CHECK_S) # the network joined during this drive was lost again return home = self.lease_factory(self.log, self.fallback_interface) try: @@ -177,14 +198,71 @@ class DedicatedLease: self.home = home after_s = min(HOME_RETRY_S * 2 ** min(self._home_holds, 5), HOME_RETRY_MAX_S) self._home_holds += 1 - self._home_retry = threading.Timer(after_s, self._release_home) - self._home_retry.daemon = True - self._home_retry.start() + self._arm(after_s) self.log("wifi_home_held", interface=self.fallback_interface, retry_after_s=after_s) + def _arm(self, after_s: float) -> None: + self._home_retry = threading.Timer(after_s, self._retry_home) + self._home_retry.daemon = True + self._home_retry.start() + def stop_home_join(self) -> None: """Stop a wlan0 join that stalls the car.""" - self.hold_home_wifi() + with self._home_lock: + home = self.home + if home is None: + self.hold_home_wifi() + return + self._join_stalled = True + try: + home.hold_autoconnect() # stops the join this drive started by hand + except NetworkError as error: + self.log("wifi_home_hold_failed", error=str(error)) + + def _retry_home(self) -> None: + """When a hold runs out, join an allowed network by hand; wlan0 never hunts by itself during a drive.""" + with self._home_lock: + home, self._home_retry = self.home, None + join = getattr(home, "drive_join", None) + if home is None or join is None: + self._release_home() + return + self._join_stalled = False + try: + prefs = self.join_policy() + parked_only = set(prefs.get("parkedOnly", ())) + pause = bool(prefs.get("pauseHotspot")) and self.hotspot is not None + outcome = join(lambda uuid: uuid not in parked_only, + before=self._pause_hotspot if pause else lambda: True, + after=self.hotspot.clear_pause if pause else lambda: None) + except Exception as error: # a join is optional; the car link must never depend on it + self.log("wifi_drive_join_failed", error=str(error) or type(error).__name__) + outcome = "failed" + if outcome in ("joined", "failed") or self._join_stalled: + self.log("wifi_drive_join", interface=self.fallback_interface, outcome="stalled" if self._join_stalled else outcome) + with self._home_lock: + if self.home is not home or self._cancel.is_set(): + return + if outcome == "joined" and not self._join_stalled: + self._home_holds = 0 + return # the next loss of this network arms the check again + if outcome == "failed" or self._join_stalled: + after_s = min(HOME_RETRY_S * 2 ** min(self._home_holds, 5), HOME_RETRY_MAX_S) + self._home_holds += 1 + else: + after_s = HOME_CHECK_S + self._arm(after_s) + + def _pause_hotspot(self) -> bool: + """Stand the Galaxy hotspot down and wait until its interface is gone; a join with it up can crash the radio.""" + self.hotspot.request_pause(HOTSPOT_PAUSE_WAIT_S + 30.0) + deadline = time.monotonic() + HOTSPOT_PAUSE_WAIT_S + while Path(f"/sys/class/net/{self.hotspot.INTERFACE}").exists(): + if time.monotonic() >= deadline or self._cancel.is_set(): + self.log("wifi_drive_join_skipped", reason="hotspot_still_up") + return False + time.sleep(0.2) + return True def _release_home(self) -> None: with self._home_lock: @@ -275,6 +353,8 @@ class DedicatedLease: retry, self._home_retry, self._home_holds = self._home_retry, None, 0 if retry is not None: retry.cancel() + if self.hotspot is not None: + self.hotspot.clear_pause() self._release_home() if self.iface is not None: self.iface.close() diff --git a/openpilot/starpilot/system/starport/network.py b/openpilot/starpilot/system/starport/network.py index 6404eadc51..9da2de6acd 100644 --- a/openpilot/starpilot/system/starport/network.py +++ b/openpilot/starpilot/system/starport/network.py @@ -62,6 +62,8 @@ SECURITY_WPA3 = (32,) AUTOCONNECT_MARKER = DATA_DIR / "wifi_autoconnect_paused.json" REJOIN_MARKER = DATA_DIR / "wifi_rejoin.json" REJOIN_ATTEMPTS = 2 +DRIVE_JOIN_TIMEOUT_S = 20.0 +DEVICE_STATE_FAILED = 120 class NetworkError(RuntimeError): @@ -475,7 +477,11 @@ class NetworkLease: return False state = int(self._get(self.device_path, NM_DEVICE_IFACE, "State")) if state == DEVICE_STATE_ACTIVATED: - return False # connected again; nothing to hold + if self._carrier(): + return False # connected again; nothing to hold + # NetworkManager reports a lost network as connected for 15 s, then joins the next one by itself. + self._pause_autoconnect() + return self.autoconnect_paused self._pause_autoconnect() if DEVICE_STATE_PREPARE <= state < DEVICE_STATE_ACTIVATED: self._remember_join() @@ -485,6 +491,67 @@ class NetworkLease: self.log("wifi_hold_disconnect_failed", error=str(error)) return self.autoconnect_paused + def _carrier(self) -> bool: + try: + return Path(f"/sys/class/net/{self.interface}/carrier").read_text().strip() == "1" + except OSError: + return True + + def drive_join(self, allowed: Callable[[str], bool], before: Callable[[], bool] = lambda: True, + after: Callable[[], None] = lambda: None, timeout: float = DRIVE_JOIN_TIMEOUT_S) -> str: + """Join the best allowed saved network in range by hand while auto-join stays paused. + + Returns "connected" (already on a network), "none" (nothing to join), "joined" or "failed". + """ + with self._lock: + path = self.device_path or next((path for path, name in self._wifi_devices() if name == self.interface), "") + if not path: + return "none" + state = int(self._get(path, NM_DEVICE_IFACE, "State")) + if state == DEVICE_STATE_ACTIVATED: + return "connected" if self._carrier() else "none" + if state != DEVICE_STATE_DISCONNECTED: + return "none" + candidates = [] + for connection in self._get(path, NM_DEVICE_IFACE, "AvailableConnections"): + profile = self._call(connection, NM_SETTINGS_CONNECTION_IFACE, "GetSettings")[0].get("connection", {}) + values = {key: entry[1] for key, entry in profile.items()} + if values.get("id") == CONNECTION_ID or not values.get("autoconnect", True) or not allowed(values.get("uuid", "")): + continue + candidates.append((int(values.get("autoconnect-priority", 0)), int(values.get("timestamp", 0)), connection)) + if not candidates: + return "none" + target = max(candidates)[2] + if not before(): + after() + return "none" + try: + with self._lock: + self._call(NM_PATH, NM_IFACE, "ActivateConnection", "ooo", (target, path, "/")) + deadline, started = time.monotonic() + timeout, False + while time.monotonic() < deadline: + time.sleep(0.25) + with self._lock: + state = int(self._get(path, NM_DEVICE_IFACE, "State")) + if state == DEVICE_STATE_ACTIVATED: + return "joined" + if state >= DEVICE_STATE_PREPARE: + started = state != DEVICE_STATE_FAILED + if started and state in (DEVICE_STATE_DISCONNECTED, DEVICE_STATE_FAILED): + return "failed" # refused, or stopped because the car link stalled + return "failed" + except NetworkError as error: + self.log("wifi_drive_join_failed", error=str(error)) + return "failed" + finally: + after() + if self.autoconnect_paused: + try: + with self._lock: + self._set(path, NM_DEVICE_IFACE, "Autoconnect", "b", False) # joining by hand turns auto-join back on + except NetworkError as error: + self.log("wifi_autoconnect_pause_failed", error=str(error)) + def _remember_join(self) -> None: """Disconnect blocks the network being joined from autoconnecting; note it so it can be rejoined after the session.""" try: diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index 96cd9f4901..361920961b 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -2129,6 +2129,8 @@ class Supervisor: on_stall=getattr(lease, "stop_home_join", None)).start() session.radio_change = radio.recent session.radio_stalled = radio.stalled + if not radio._carrier() and getattr(lease, "hold_home_wifi", None) is not None: + lease.hold_home_wifi() # wlan0 is not on a network: it joins one under StarPort's control, not by itself try: from openpilot.starpilot.system.starport.media_audio import MediaAudio, music_control from openpilot.starpilot.system.starport.media_status import MediaStatus diff --git a/openpilot/starpilot/system/starport/tests/test_car_interface.py b/openpilot/starpilot/system/starport/tests/test_car_interface.py index 371f37d69f..b05a0ad13a 100644 --- a/openpilot/starpilot/system/starport/tests/test_car_interface.py +++ b/openpilot/starpilot/system/starport/tests/test_car_interface.py @@ -564,3 +564,72 @@ def test_daemon_saves_and_reports_the_dedicated_wifi_choice(identity, tmp_path, assert json.loads(identity_store.CONFIG_PATH.read_text())["dedicated_wifi_interface"] is True daemon.handle(sup, {"command": "set_dedicated_wifi", "enabled": "yes"}) # only a real true turns it on assert sup.status()["dedicated_wifi_interface"] is False + + +class JoiningLease(FakeLease): + outcomes: list = [] + calls: list = [] + + def hold_autoconnect(self): + self.held = True + return True + + def drive_join(self, allowed, before=lambda: True, after=lambda: None): + JoiningLease.calls.append((allowed("parked-only"), allowed("anywhere"), before())) + after() + return JoiningLease.outcomes.pop(0) + + +class FakeHotspot: + INTERFACE = "no-such-interface" + + def __init__(self): + self.events = [] + + def request_pause(self, seconds): + self.events.append("pause") + + def clear_pause(self): + self.events.append("clear") + + +def make_joining(outcomes, prefs): + JoiningLease.outcomes, JoiningLease.calls = list(outcomes), [] + log, hotspot = Log(), FakeHotspot() + lease = DedicatedLease(log, "wlan0", lambda log, interface, dedicated=False: JoiningLease(log, interface, dedicated), + interface_factory=lambda log: FakeInterface(log), join_policy=lambda: prefs, hotspot=hotspot) + lease.acquire(credentials()) + return lease, log, hotspot + + +def test_a_hold_that_runs_out_joins_an_allowed_network_with_the_hotspot_paused(monkeypatch): + monkeypatch.setattr(car_interface, "HOME_RETRY_S", 0.02) + monkeypatch.setattr(car_interface, "HOME_CHECK_S", 0.02) + lease, log, hotspot = make_joining(["none", "joined"], {"parkedOnly": ["parked-only"], "pauseHotspot": True}) + lease.hold_home_wifi() + deadline = time.monotonic() + 2 + while "wifi_drive_join" not in log.names(): + assert time.monotonic() < deadline + time.sleep(0.01) + assert JoiningLease.calls == [(False, True, True)] * 2 and hotspot.events == ["pause", "clear"] * 2 + assert lease.home is not None and lease._home_retry is None # still held: wlan0 never hunts by itself during a drive + assert "wifi_home_released" not in log.names() + lease.hold_home_wifi() # the joined network was lost again + assert lease._home_retry is not None + lease.release(restore=True) + assert lease.home is None and "wifi_home_released" in log.names() + + +def test_a_failed_or_stalled_drive_join_backs_off_and_never_pauses_the_hotspot_when_switched_off(monkeypatch): + monkeypatch.setattr(car_interface, "HOME_RETRY_S", 0.02) + lease, log, hotspot = make_joining(["failed"], {"parkedOnly": [], "pauseHotspot": False}) + lease.hold_home_wifi() + deadline = time.monotonic() + 2 + while "wifi_drive_join" not in log.names(): + assert time.monotonic() < deadline + time.sleep(0.01) + time.sleep(0.01) + assert lease._home_holds == 2 and hotspot.events == [] and JoiningLease.calls == [(True, True, True)] + lease.stop_home_join() # a stall while already held stops the join instead of taking a second hold + assert lease._join_stalled and log.names().count("wifi_home_held") == 1 + lease.release(restore=True) diff --git a/openpilot/starpilot/system/starport/tests/test_starport.py b/openpilot/starpilot/system/starport/tests/test_starport.py index 158ea11a29..0667727a18 100644 --- a/openpilot/starpilot/system/starport/tests/test_starport.py +++ b/openpilot/starpilot/system/starport/tests/test_starport.py @@ -1417,3 +1417,32 @@ def test_discovery_waits_past_the_message_timeout_for_a_slow_adapter(): sender.join() a.close() b.close() + + +def test_drive_join_picks_the_best_allowed_network_and_re_pauses_auto_join(monkeypatch): + from openpilot.starpilot.system.starport import network + profiles = {"/settings/home": {"uuid": ("s", "home"), "autoconnect-priority": ("i", 2)}, + "/settings/phone": {"uuid": ("s", "phone"), "autoconnect-priority": ("i", 5)}, + "/settings/off": {"uuid": ("s", "off"), "autoconnect": ("b", False), "autoconnect-priority": ("i", 9)}, + "/settings/car": {"uuid": ("s", "car"), "id": ("s", network.CONNECTION_ID)}} + state, calls, sets, order = [30], [], [], [] + monkeypatch.setattr(network.NetworkLease, "_wifi_devices", lambda lease: [("/dev/wlan0", "wlan0")]) + props = {"State": lambda: state[0], "AvailableConnections": lambda: list(profiles)} + monkeypatch.setattr(network.NetworkLease, "_get", lambda lease, path, interface, name: props[name]()) + def call(lease, path, interface, member, signature=None, body=(), timeout=10.0): + if member == "GetSettings": + return ({"connection": profiles[path]},) + calls.append(body) + state[0] = 100 + monkeypatch.setattr(network.NetworkLease, "_call", call) + monkeypatch.setattr(network.NetworkLease, "_set", lambda lease, *args: sets.append(args[2:])) + monkeypatch.setattr(network.time, "sleep", lambda _s: None) + lease = network.NetworkLease(lambda *a, **k: None, "wlan0") + lease.autoconnect_paused = True + outcome = lease.drive_join(lambda uuid: uuid != "phone", before=lambda: order.append("pause") or True, after=lambda: order.append("resume")) + assert outcome == "joined" and calls == [("/settings/home", "/dev/wlan0", "/")] and order == ["pause", "resume"] + assert sets == [("Autoconnect", "b", False)] + state[0], calls[:] = 30, [] + assert lease.drive_join(lambda uuid: False) == "none" and calls == [] + state[0] = 50 + assert lease.drive_join(lambda uuid: True) == "none" and calls == []