diff --git a/openpilot/starpilot/system/starport/network.py b/openpilot/starpilot/system/starport/network.py index 08408563ab..6404eadc51 100644 --- a/openpilot/starpilot/system/starport/network.py +++ b/openpilot/starpilot/system/starport/network.py @@ -60,6 +60,8 @@ BSSID_SHARE = 0.75 CONNECTION_ID = "starpilot-starport" SECURITY_WPA3 = (32,) AUTOCONNECT_MARKER = DATA_DIR / "wifi_autoconnect_paused.json" +REJOIN_MARKER = DATA_DIR / "wifi_rejoin.json" +REJOIN_ATTEMPTS = 2 class NetworkError(RuntimeError): @@ -106,6 +108,67 @@ def recover_autoconnect(log: Callable[..., None], marker: Path = AUTOCONNECT_MAR return True +def _rejoin_state(marker: Path) -> dict: + try: + state = json.loads(marker.read_text()) + except (OSError, ValueError): + return {} + return state if isinstance(state, dict) and state.get("boot") == _boot_id() else {} + + +def _remember_interrupted(marker: Path, interface: str, connection: str) -> None: + state = _rejoin_state(marker) + connections = [path for path in state.get("connections", []) if path != connection] + [connection] + marker.parent.mkdir(parents=True, exist_ok=True) + marker.write_text(json.dumps({"interface": interface, "boot": _boot_id(), "connections": connections})) + + +def rejoin_interrupted(log: Callable[..., None], marker: Path = REJOIN_MARKER) -> bool: + """Rejoin a saved network a hold stopped mid-join; NetworkManager blocks its autoconnect until then. True when done.""" + if not marker.exists(): + return True + state = _rejoin_state(marker) + connections = [path for path in state.get("connections", []) if isinstance(path, str)] + if not connections: + marker.unlink(missing_ok=True) # a reboot clears NetworkManager's block + return True + saved = state.get("failures") + failures: dict[str, int] = saved if isinstance(saved, dict) else {} + lease = NetworkLease(log, state.get("interface", "wlan0")) + try: + path = next((path for path, name in lease._wifi_devices() if name == lease.interface), "") + if not path or not lease._get(path, NM_DEVICE_IFACE, "Autoconnect"): + return False + if int(lease._get(path, NM_DEVICE_IFACE, "State")) != DEVICE_STATE_DISCONNECTED: + return False # busy or on another network; wait until it is idle + available = set(lease._get(path, NM_DEVICE_IFACE, "AvailableConnections")) + connection = next((connection for connection in reversed(connections) if connection in available), "") # newest first + if not connection: + return False + try: + lease._call(NM_PATH, NM_IFACE, "ActivateConnection", "ooo", (connection, path, "/")) + log("wifi_rejoined", interface=lease.interface) + except NetworkError as error: + failures[connection] = failures.get(connection, 0) + 1 + log("wifi_rejoin_failed", error=str(error), attempt=failures[connection]) + if failures[connection] < REJOIN_ATTEMPTS: + marker.write_text(json.dumps({**state, "failures": failures})) + return False + except NetworkError as error: + log("wifi_rejoin_failed", error=str(error)) + return False + finally: + if lease.router is not None: + lease.router.close() + connections.remove(connection) + failures.pop(connection, None) + if connections: + marker.write_text(json.dumps({**state, "connections": connections, "failures": failures})) + return False + marker.unlink(missing_ok=True) + return True + + def static_address(endpoint_ip: str) -> str: """An unused address beside the dongle's own, for dongles whose DHCP server never answers.""" try: @@ -174,6 +237,7 @@ class NetworkLease: self.static_ip = "" self.endpoint_ip: Callable[[], str] = lambda: "" self.marker = AUTOCONNECT_MARKER + self.rejoin_marker = REJOIN_MARKER self._lock = threading.Lock() def _open(self) -> DBusRouter: @@ -414,12 +478,23 @@ class NetworkLease: return False # connected again; nothing to hold self._pause_autoconnect() if DEVICE_STATE_PREPARE <= state < DEVICE_STATE_ACTIVATED: + self._remember_join() try: self._call(self.device_path, NM_DEVICE_IFACE, "Disconnect") # a join already under way except NetworkError as error: self.log("wifi_hold_disconnect_failed", error=str(error)) return self.autoconnect_paused + def _remember_join(self) -> None: + """Disconnect blocks the network being joined from autoconnecting; note it so it can be rejoined after the session.""" + try: + active = self._get(self.device_path, NM_DEVICE_IFACE, "ActiveConnection") + connection = self._get(active, NM_ACTIVE_IFACE, "Connection") if active and active != "/" else "" + if connection and connection != "/": + _remember_interrupted(self.rejoin_marker, self.interface, connection) + except (NetworkError, OSError) as error: + self.log("wifi_rejoin_note_failed", error=str(error)) + def _pause_autoconnect(self) -> None: """Keep NetworkManager from rejoining home Wi-Fi between attempts; release(restore=True) turns it back on.""" if self.autoconnect_paused: diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index 80f46cfbdb..f021334669 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -1878,13 +1878,13 @@ class Supervisor: raise errors[0] def recover_wifi(self, now: float | None = None) -> None: - """Turn wlan0 autoconnect back on if a session paused it and crashed. Retried while idle until it works.""" + """Turn wlan0 autoconnect back on and rejoin a network a session stopped. Retried while idle until done.""" now = time.monotonic() if now is None else now if now < self._wifi_recover_at or self._session_alive(): return - from openpilot.starpilot.system.starport.network import recover_autoconnect + from openpilot.starpilot.system.starport import network try: - done = recover_autoconnect(self.log) + done = network.recover_autoconnect(self.log) and network.rejoin_interrupted(self.log) except Exception as error: self.log("wifi_autoconnect_recover_failed", error=str(error)) done = False diff --git a/openpilot/starpilot/system/starport/tests/test_car_interface.py b/openpilot/starpilot/system/starport/tests/test_car_interface.py index 7b92a25fb5..371f37d69f 100644 --- a/openpilot/starpilot/system/starport/tests/test_car_interface.py +++ b/openpilot/starpilot/system/starport/tests/test_car_interface.py @@ -1,4 +1,5 @@ from typing import Any +import json import os import subprocess import sys @@ -397,9 +398,14 @@ def test_hold_autoconnect_on_lost_home_wifi(tmp_path, state, held, disconnected) lease._call, lease._get, lease._set = nm.call, nm.get, nm.set_property lease.router = type("R", (), {"close": lambda self: None})() lease.marker = tmp_path / "paused.json" + lease.rejoin_marker = tmp_path / "rejoin.json" assert lease.hold_autoconnect() is held assert ("Disconnect" in nm.calls) is disconnected assert nm.set == ([("/dev/wlan0", "Autoconnect", False)] if held else []) + # NetworkManager blocks a network stopped mid-join, so only that one is noted for a rejoin + assert lease.rejoin_marker.exists() is disconnected + if disconnected: + assert json.loads(lease.rejoin_marker.read_text())["connections"] == ["/settings/home"] lease.release(restore=True) assert nm.autoconnect and not lease.marker.exists() diff --git a/openpilot/starpilot/system/starport/tests/test_starport.py b/openpilot/starpilot/system/starport/tests/test_starport.py index 7ae9806c69..158ea11a29 100644 --- a/openpilot/starpilot/system/starport/tests/test_starport.py +++ b/openpilot/starpilot/system/starport/tests/test_starport.py @@ -1266,11 +1266,100 @@ def test_autoconnect_stays_on_when_recovery_marker_cannot_be_written(tmp_path, m assert not lease.autoconnect_paused and changes == [] +class RejoinNM: + def __init__(self, state=30, autoconnect=True, available=("/settings/home",)): + self.state, self.autoconnect, self.available = state, autoconnect, list(available) + self.activated = [] + self.refuse = False + + def install(self, monkeypatch, network): + monkeypatch.setattr(network.NetworkLease, "_wifi_devices", lambda lease: [("/dev/wlan0", "wlan0")]) + props = {"Autoconnect": lambda: self.autoconnect, "State": lambda: self.state, "AvailableConnections": lambda: self.available} + monkeypatch.setattr(network.NetworkLease, "_get", lambda lease, path, interface, name: props[name]()) + def call(lease, path, interface, member, signature=None, body=(), timeout=10.0): + self.activated.append((member, body)) + if self.refuse: + raise network.NetworkError("No connection with that path") + monkeypatch.setattr(network.NetworkLease, "_call", call) + + +def rejoin_marker(tmp_path, network, connections=("/settings/home",), boot=None): + marker = tmp_path / "rejoin.json" + marker.write_text(json.dumps({"interface": "wlan0", "boot": boot or network._boot_id(), "connections": list(connections)})) + return marker + + +def test_rejoin_reactivates_the_network_a_hold_interrupted(tmp_path, monkeypatch): + from openpilot.starpilot.system.starport import network + nm, log = RejoinNM(), [] + nm.install(monkeypatch, network) + marker = rejoin_marker(tmp_path, network) + assert network.rejoin_interrupted(lambda event, **fields: log.append(event), marker) + assert nm.activated == [("ActivateConnection", ("/settings/home", "/dev/wlan0", "/"))] and not marker.exists() + assert log == ["wifi_rejoined"] + + +@pytest.mark.parametrize("nm", [RejoinNM(state=100), RejoinNM(state=50), RejoinNM(autoconnect=False), RejoinNM(available=())], + ids=["connected", "joining", "held", "out_of_range"]) +def test_rejoin_waits_until_wlan0_is_idle_and_the_network_is_in_range(tmp_path, monkeypatch, nm): + from openpilot.starpilot.system.starport import network + nm.install(monkeypatch, network) + marker = rejoin_marker(tmp_path, network) + assert not network.rejoin_interrupted(lambda *a, **k: None, marker) + assert nm.activated == [] and marker.exists() + + +def test_rejoin_prefers_the_latest_interrupted_network(tmp_path, monkeypatch): + from openpilot.starpilot.system.starport import network + nm = RejoinNM(available=("/settings/hotspot", "/settings/home")) + nm.install(monkeypatch, network) + marker = rejoin_marker(tmp_path, network, connections=("/settings/hotspot", "/settings/home")) + assert not network.rejoin_interrupted(lambda *a, **k: None, marker) + assert nm.activated == [("ActivateConnection", ("/settings/home", "/dev/wlan0", "/"))] + assert json.loads(marker.read_text())["connections"] == ["/settings/hotspot"] + + +def test_rejoin_gives_up_on_a_network_after_two_refused_joins(tmp_path, monkeypatch): + from openpilot.starpilot.system.starport import network + nm = RejoinNM() + nm.refuse = True + nm.install(monkeypatch, network) + marker = rejoin_marker(tmp_path, network) + assert not network.rejoin_interrupted(lambda *a, **k: None, marker) + assert marker.exists() + assert network.rejoin_interrupted(lambda *a, **k: None, marker) + assert len(nm.activated) == 2 and not marker.exists() + + +def test_rejoin_keeps_waiting_while_networkmanager_is_unavailable(tmp_path, monkeypatch): + from openpilot.starpilot.system.starport import network + nm = RejoinNM() + nm.install(monkeypatch, network) + + def unavailable(lease): + raise network.NetworkError("NetworkManager is not running") + monkeypatch.setattr(network.NetworkLease, "_wifi_devices", unavailable) + marker = rejoin_marker(tmp_path, network) + for _ in range(3): + assert not network.rejoin_interrupted(lambda *a, **k: None, marker) + assert marker.exists() and "failures" not in json.loads(marker.read_text()) + + +def test_rejoin_is_dropped_after_a_reboot(tmp_path, monkeypatch): + from openpilot.starpilot.system.starport import network + nm = RejoinNM() + nm.install(monkeypatch, network) + marker = rejoin_marker(tmp_path, network, boot="an earlier boot") + assert network.rejoin_interrupted(lambda *a, **k: None, marker) + assert nm.activated == [] and not marker.exists() + + def test_supervisor_retries_wifi_recovery_while_idle(monkeypatch): from openpilot.starpilot.system.starport import network, supervisor results = [False, True] calls = [] monkeypatch.setattr(network, "recover_autoconnect", lambda log: calls.append(1) or results.pop(0)) + monkeypatch.setattr(network, "rejoin_interrupted", lambda log: True) sup = supervisor.Supervisor.__new__(supervisor.Supervisor) sup.log, sup._wifi_recover_at = (lambda *a, **k: None), 0.0 # ty: ignore[invalid-assignment] # test double sup._session_alive = lambda: False # ty: ignore[invalid-assignment] # test double