From 0563f12f7b22f0bd60ee3151f9aa558cd88d0c20 Mon Sep 17 00:00:00 2001 From: Danny Date: Wed, 18 Nov 2026 09:40:16 -0800 Subject: [PATCH 1/2] Network: Join phone hotspots during drives without long pauses --- openpilot/starpilot/galaxy/network_prefs.py | 4 +- .../galaxy/tests/test_network_prefs.py | 18 ++++- openpilot/starpilot/galaxy/web/js/networks.js | 2 +- .../system/starport/car_interface.py | 15 +++-- .../starpilot/system/starport/network.py | 67 ++++++++++++++++++- .../starport/tests/test_car_interface.py | 8 ++- .../system/starport/tests/test_starport.py | 66 ++++++++++++++++-- 7 files changed, 158 insertions(+), 22 deletions(-) diff --git a/openpilot/starpilot/galaxy/network_prefs.py b/openpilot/starpilot/galaxy/network_prefs.py index d7eb1dac9e..b848df0676 100644 --- a/openpilot/starpilot/galaxy/network_prefs.py +++ b/openpilot/starpilot/galaxy/network_prefs.py @@ -19,7 +19,7 @@ from typing import cast from openpilot.starpilot.galaxy import hotspot from openpilot.starpilot.galaxy.hotspot import atomic_json, bounded_json -DEFAULT = {'prefer': 'wifi', 'pauseHotspot': True, 'parkedOnly': []} +DEFAULT = {'prefer': 'wifi', 'pauseHotspot': False, 'parkedOnly': []} CELLULAR_FIRST_METRIC = 2000 # above the modem's own default route (1000), so cellular wins while it is up OWN_PROFILES = ('starpilot-starport',) UUID = re.compile(r'[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}') @@ -303,7 +303,7 @@ class NetworkSettings: return True def _with_hotspot_paused(self, effect) -> None: - paused = self._pause_hotspot() + paused = read_prefs(self.root)['pauseHotspot'] and self._pause_hotspot() try: effect() finally: diff --git a/openpilot/starpilot/galaxy/tests/test_network_prefs.py b/openpilot/starpilot/galaxy/tests/test_network_prefs.py index 7f706efe27..4ed315962a 100644 --- a/openpilot/starpilot/galaxy/tests/test_network_prefs.py +++ b/openpilot/starpilot/galaxy/tests/test_network_prefs.py @@ -50,7 +50,7 @@ def test_only_client_wifi_networks_are_listed_best_priority_first(tmp_path): snapshot = made.snapshot(True) assert [(n['name'], n['connected'], n['signal'], n['whileDriving']) for n in snapshot['networks']] == [ ('Phone: 5G', False, None, True), ('Home', True, 80, True)] - assert snapshot['prefer'] == 'wifi' and snapshot['cellular']['enabled'] and snapshot['pauseHotspot'] + assert snapshot['prefer'] == 'wifi' and snapshot['cellular']['enabled'] and not snapshot['pauseHotspot'] def test_order_writes_priorities_and_rejects_a_stale_list(tmp_path): @@ -110,8 +110,8 @@ def test_cellular_switch_uses_the_existing_setting_and_changes_need_park(tmp_pat made.apply({'action': 'cellular', 'value': False}, lambda: True) params.put_bool.assert_called_once_with('CellularDisabled', True) with pytest.raises(PermissionError): - made.apply({'action': 'pauseHotspot', 'value': False}, lambda: False) - assert changes(calls) == [] and network_prefs.read_prefs(tmp_path)['pauseHotspot'] is True + made.apply({'action': 'pauseHotspot', 'value': True}, lambda: False) + assert changes(calls) == [] and network_prefs.read_prefs(tmp_path)['pauseHotspot'] is False def test_scan_join_connect_and_forget(tmp_path): @@ -150,6 +150,7 @@ def test_scan_join_connect_and_forget(tmp_path): def test_join_pauses_the_hotspot_and_cleans_up_a_failed_profile(tmp_path, monkeypatch): + network_prefs.atomic_json(network_prefs.prefs_path(tmp_path), {**network_prefs.DEFAULT, 'pauseHotspot': True}) calls, events = [], [] iface = tmp_path / 'galaxy0' iface.touch() @@ -178,6 +179,7 @@ def test_join_pauses_the_hotspot_and_cleans_up_a_failed_profile(tmp_path, monkey def test_join_refuses_when_the_hotspot_stays_up(tmp_path, monkeypatch): + network_prefs.atomic_json(network_prefs.prefs_path(tmp_path), {**network_prefs.DEFAULT, 'pauseHotspot': True}) iface, calls, events = tmp_path / 'galaxy0', [], [] iface.touch() monkeypatch.setattr(network_prefs.hotspot, 'request_pause', lambda seconds: events.append('pause')) @@ -225,3 +227,13 @@ def test_a_failed_background_join_keeps_the_reason(tmp_path): def test_only_hotspot_addresses_count_as_hotspot_clients(): assert network_prefs.via_hotspot('172.31.254.23') assert not network_prefs.via_hotspot('192.168.1.20') and not network_prefs.via_hotspot('127.0.0.1') and not network_prefs.via_hotspot('bad') + + +def test_join_leaves_the_hotspot_up_when_the_pause_is_off(tmp_path, monkeypatch): + iface, calls, events = tmp_path / 'galaxy0', [], [] + iface.touch() + monkeypatch.setattr(network_prefs.hotspot, 'request_pause', lambda seconds: events.append('pause')) + made = NetworkSettings(tmp_path, NetworkManagerCli(fake_run(calls)), Mock(), link=lambda: {'link': 'wifi'}, + hotspot_iface=iface, sleep=lambda _s: None) + made.apply({'action': 'connect', 'uuid': PHONE}, lambda: True) + assert events == [] and ['--wait', '15', 'connection', 'up', 'uuid', PHONE, 'ifname', 'wlan0'] in calls diff --git a/openpilot/starpilot/galaxy/web/js/networks.js b/openpilot/starpilot/galaxy/web/js/networks.js index dfd7f7424a..ff98c429a8 100644 --- a/openpilot/starpilot/galaxy/web/js/networks.js +++ b/openpilot/starpilot/galaxy/web/js/networks.js @@ -221,7 +221,7 @@ export const NetworksPage = { -
Nearby networks{{ availableNetworks.length }} diff --git a/openpilot/starpilot/system/starport/car_interface.py b/openpilot/starpilot/system/starport/car_interface.py index 4ab0fecfc2..985809950e 100644 --- a/openpilot/starpilot/system/starport/car_interface.py +++ b/openpilot/starpilot/system/starport/car_interface.py @@ -28,9 +28,9 @@ LEASE_TIMEOUT_S = 10.0 READY_TIMEOUT_S = 5.0 # The car's network never appeared this many times on aa0; finish the session on wlan0 in case aa0 is the reason. DEDICATED_TIMEOUTS = 2 -HOME_RETRY_S = 60.0 +HOME_RETRY_S = 15.0 HOME_RETRY_MAX_S = 300.0 -HOME_CHECK_S = 30.0 # how often a held wlan0 looks for an allowed network to join +HOME_CHECK_S = 15.0 # how often a held wlan0 looks for an allowed network to join HOTSPOT_PAUSE_WAIT_S = 10.0 @@ -122,6 +122,7 @@ class DedicatedLease: self._home_retry: threading.Timer | None = None self._home_holds = 0 self._join_stalled = False + self._last_join = "" self.join_policy, self.hotspot = join_policy or _join_policy, hotspot if hotspot is not None else _hotspot() @property @@ -238,19 +239,21 @@ class DedicatedLease: 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) + shown = "stalled" if self._join_stalled else outcome + if shown != self._last_join or shown in ("joined", "failed", "stalled"): + self.log("wifi_drive_join", interface=self.fallback_interface, outcome=shown) + self._last_join = shown 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: + if 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 + after_s = HOME_CHECK_S # a refused network is skipped for a while, so the next one is tried soon self._arm(after_s) def _pause_hotspot(self) -> bool: diff --git a/openpilot/starpilot/system/starport/network.py b/openpilot/starpilot/system/starport/network.py index 13fbc00df3..f814cd8f24 100644 --- a/openpilot/starpilot/system/starport/network.py +++ b/openpilot/starpilot/system/starport/network.py @@ -63,6 +63,10 @@ AUTOCONNECT_MARKER = DATA_DIR / "wifi_autoconnect_paused.json" REJOIN_MARKER = DATA_DIR / "wifi_rejoin.json" REJOIN_ATTEMPTS = 2 DRIVE_JOIN_TIMEOUT_S = 20.0 +DRIVE_SCAN_WAIT_S = 5.0 +DRIVE_SCAN_EVERY_S = 45.0 # a forced scan takes the shared radio off the car's channel, so not on every check +AP_FRESH_S = 20.0 # a network not heard in the latest scan has been driven away from +FAILED_SKIP_S = 120.0 # a network that just refused a join is passed over for this long DEVICE_STATE_FAILED = 120 @@ -240,6 +244,8 @@ class NetworkLease: self.endpoint_ip: Callable[[], str] = lambda: "" self.marker = AUTOCONNECT_MARKER self.rejoin_marker = REJOIN_MARKER + self._failed_at: dict[str, float] = {} + self._scanned_at = -DRIVE_SCAN_EVERY_S self._lock = threading.Lock() def _open(self) -> DBusRouter: @@ -512,13 +518,22 @@ class NetworkLease: return "connected" if self._carrier() else "none" if state != DEVICE_STATE_DISCONNECTED: return "none" + self._scan(path) + with self._lock: + heard = self._heard(path) + now = time.monotonic() + self._failed_at = {key: at for key, at in self._failed_at.items() if now - at < FAILED_SKIP_S} 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()} + settings = self._call(connection, NM_SETTINGS_CONNECTION_IFACE, "GetSettings")[0] + values = {key: entry[1] for key, entry in settings.get("connection", {}).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)) + wireless = settings.get("802-11-wireless", {}) + strength = heard.get(bytes(wireless["ssid"][1]), -1) if "ssid" in wireless else -1 + if strength < 0 or connection in self._failed_at: + continue + candidates.append((int(values.get("autoconnect-priority", 0)), strength, connection)) if not candidates: return "none" target = max(candidates)[2] @@ -536,12 +551,15 @@ class NetworkLease: if state == DEVICE_STATE_ACTIVATED: return "joined" if state == DEVICE_STATE_FAILED or (started and state == DEVICE_STATE_DISCONNECTED): + self._failed_at[target] = time.monotonic() return "failed" # refused, or stopped because the car link stalled if state >= DEVICE_STATE_PREPARE: started = True + self._failed_at[target] = time.monotonic() return "failed" except NetworkError as error: self.log("wifi_drive_join_failed", error=str(error)) + self._failed_at[target] = time.monotonic() return "failed" finally: after() @@ -552,6 +570,49 @@ class NetworkLease: except NetworkError as error: self.log("wifi_autoconnect_pause_failed", error=str(error)) + def _scan(self, path: str) -> None: + """NetworkManager stops scanning a disconnected wlan0 while its auto-join is paused, so ask for a scan and wait for it.""" + if time.monotonic() - self._scanned_at < DRIVE_SCAN_EVERY_S: + return + self._scanned_at = time.monotonic() + try: + with self._lock: + before = int(self._get(path, NM_WIRELESS_IFACE, "LastScan")) + self._call(path, NM_WIRELESS_IFACE, "RequestScan", "a{sv}", ({},)) + except NetworkError: + return # already scanning, or scans refused; the access points heard so far still count + deadline = time.monotonic() + DRIVE_SCAN_WAIT_S + while time.monotonic() < deadline: + time.sleep(0.25) + try: + with self._lock: + if int(self._get(path, NM_WIRELESS_IFACE, "LastScan")) != before: + return + except NetworkError: + return + + def _heard(self, path: str) -> dict[bytes, int]: + """Strongest signal per network name among access points heard in the latest scan.""" + try: + last_scan = int(self._get(path, NM_WIRELESS_IFACE, "LastScan")) / 1000 + except NetworkError: + last_scan = -1 + now = time.clock_gettime(getattr(time, "CLOCK_BOOTTIME", time.CLOCK_MONOTONIC)) + since = now - AP_FRESH_S + if 0 < now - last_scan <= DRIVE_SCAN_EVERY_S + DRIVE_SCAN_WAIT_S + 5: + since = min(since, last_scan - 5) # between forced scans, what the last one heard still counts + heard: dict[bytes, int] = {} + for access_point in self._get(path, NM_WIRELESS_IFACE, "AccessPoints"): + try: + seen = int(self._get(access_point, NM_AP_IFACE, "LastSeen")) + if seen < 0 or seen < since: + continue + ssid = bytes(self._get(access_point, NM_AP_IFACE, "Ssid")) + heard[ssid] = max(heard.get(ssid, 0), int(self._get(access_point, NM_AP_IFACE, "Strength"))) + except NetworkError: + continue + return heard + 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/tests/test_car_interface.py b/openpilot/starpilot/system/starport/tests/test_car_interface.py index b05a0ad13a..7c899a6f9e 100644 --- a/openpilot/starpilot/system/starport/tests/test_car_interface.py +++ b/openpilot/starpilot/system/starport/tests/test_car_interface.py @@ -608,10 +608,11 @@ def test_a_hold_that_runs_out_joins_an_allowed_network_with_the_hotspot_paused(m 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(): + while log.names().count("wifi_drive_join") < 2: assert time.monotonic() < deadline time.sleep(0.01) assert JoiningLease.calls == [(False, True, True)] * 2 and hotspot.events == ["pause", "clear"] * 2 + assert [fields["outcome"] for event, fields in log.events if event == "wifi_drive_join"] == ["none", "joined"] 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 @@ -620,7 +621,7 @@ def test_a_hold_that_runs_out_joins_an_allowed_network_with_the_hotspot_paused(m 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): +def test_a_failed_drive_join_retries_soon_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() @@ -629,7 +630,8 @@ def test_a_failed_or_stalled_drive_join_backs_off_and_never_pauses_the_hotspot_w 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)] + assert lease._home_holds == 1 and hotspot.events == [] and JoiningLease.calls == [(True, True, True)] + assert lease._home_retry.interval == car_interface.HOME_CHECK_S 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 f38f0416dc..a556591c81 100644 --- a/openpilot/starpilot/system/starport/tests/test_starport.py +++ b/openpilot/starpilot/system/starport/tests/test_starport.py @@ -1425,13 +1425,17 @@ def test_drive_join_picks_the_best_allowed_network_and_re_pauses_auto_join(monke "/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], [], [], [] + state, calls, sets, order, scans = [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, "_heard", lambda lease, path: {b"home": 40, b"phone": 70, b"off": 90}) + props = {"State": lambda: state[0], "AvailableConnections": lambda: list(profiles), + "LastScan": lambda: scans.append(1) or len(scans)} 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]},) + return ({"connection": profiles[path], "802-11-wireless": {"ssid": ("ay", path.rsplit("/", 1)[1].encode())}},) + if member == "RequestScan": + return calls.append(body) state[0] = 100 monkeypatch.setattr(network.NetworkLease, "_call", call) @@ -1456,13 +1460,18 @@ def test_drive_join_resumes_hotspot_promptly_after_failure(monkeypatch, states): def get(lease, path, interface, name): if name == "AvailableConnections": return ["/settings/home"] + if name == "LastScan": + return 1 reads[0] += 1 return network.DEVICE_STATE_DISCONNECTED if reads[0] == 1 else states[min(reads[0] - 2, len(states) - 1)] def call(lease, path, interface, member, *args): if member == "GetSettings": - return ({"connection": {"uuid": ("s", "home")}},) + return ({"connection": {"uuid": ("s", "home")}, "802-11-wireless": {"ssid": ("ay", b"home")}},) + if member == "RequestScan": + raise network.NetworkError("busy") + monkeypatch.setattr(network.NetworkLease, "_heard", lambda lease, path: {b"home": 50}) monkeypatch.setattr(network.NetworkLease, "_get", get) monkeypatch.setattr(network.NetworkLease, "_call", call) monkeypatch.setattr(network.NetworkLease, "_set", lambda lease, *args: sets.append(args[2:])) @@ -1480,3 +1489,52 @@ def test_drive_join_resumes_hotspot_promptly_after_failure(monkeypatch, states): assert reads[0] == len(states) + 1 assert order == ["pause", "resume"] assert sets == [("Autoconnect", "b", False)] + + +def test_drive_join_skips_a_network_no_longer_heard_and_one_that_just_refused(monkeypatch): + from openpilot.starpilot.system.starport import network + profiles = {"/settings/home": ("home", 9), "/settings/phone": ("phone", 1)} + heard, calls, state = {b"phone": 60}, [], [30] + monkeypatch.setattr(network.NetworkLease, "_heard", lambda lease, path: dict(heard)) + monkeypatch.setattr(network.NetworkLease, "_scan", lambda lease, path: None) + 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": + uuid, priority = profiles[path] + return ({"connection": {"uuid": ("s", uuid), "autoconnect-priority": ("i", priority)}, + "802-11-wireless": {"ssid": ("ay", uuid.encode())}},) + calls.append(body[0]) + state[0] = network.DEVICE_STATE_FAILED + monkeypatch.setattr(network.NetworkLease, "_call", call) + monkeypatch.setattr(network.NetworkLease, "_set", lambda lease, *args: None) + monkeypatch.setattr(network.time, "sleep", lambda _s: None) + lease = network.NetworkLease(lambda *a, **k: None, "wlan0") + lease.device_path = "/dev/wlan0" + assert lease.drive_join(lambda uuid: True) == "failed" and calls == ["/settings/phone"] # home is out of range + state[0], heard[b"home"] = 30, 80 + assert lease.drive_join(lambda uuid: True) == "failed" and calls[-1] == "/settings/home" + state[0] = 30 + assert lease.drive_join(lambda uuid: True) == "none" and len(calls) == 2 # both refused just now + + +def test_heard_networks_come_from_the_latest_scan_only(monkeypatch): + from openpilot.starpilot.system.starport import network + now = 1000. + aps = {"/ap/home": (b"home", 400, 90), "/ap/phone": (b"phone", 975, 40), "/ap/cafe": (b"cafe", 995, 70)} + last_scan = [976_000] + + def get(lease, path, interface, name): + if name == "LastScan": + return last_scan[0] + if name == "AccessPoints": + return list(aps) + ssid, seen, strength = aps[path] + return {"LastSeen": seen, "Ssid": ssid, "Strength": strength}[name] + + monkeypatch.setattr(network.NetworkLease, "_get", get) + monkeypatch.setattr(network.time, "clock_gettime", lambda _clock: now) + lease = network.NetworkLease(lambda *a, **k: None, "wlan0") + assert lease._heard("/dev/wlan0") == {b"phone": 40, b"cafe": 70} # home was only heard long ago + last_scan[0] = 300_000 # an old scan does not vouch for what it heard + assert lease._heard("/dev/wlan0") == {b"cafe": 70} From 14f802360ab92a826b77d8d310e2cfe6d0fbf7aa Mon Sep 17 00:00:00 2001 From: Prabhaav Pillai Date: Thu, 19 Nov 2026 16:14:37 -0500 Subject: [PATCH 2/2] Enhance drive join functionality with cancellation support and improved logging --- .../system/starport/car_interface.py | 5 +- .../starpilot/system/starport/network.py | 19 ++++- .../starport/tests/test_car_interface.py | 12 ++- .../system/starport/tests/test_starport.py | 78 ++++++++++++++++++- 4 files changed, 103 insertions(+), 11 deletions(-) diff --git a/openpilot/starpilot/system/starport/car_interface.py b/openpilot/starpilot/system/starport/car_interface.py index 985809950e..c85f881685 100644 --- a/openpilot/starpilot/system/starport/car_interface.py +++ b/openpilot/starpilot/system/starport/car_interface.py @@ -235,12 +235,13 @@ class DedicatedLease: 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) + after=self.hotspot.clear_pause if pause else lambda: None, + cancelled=lambda: self._cancel.is_set() or self._join_stalled or self.home is not home) 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" shown = "stalled" if self._join_stalled else outcome - if shown != self._last_join or shown in ("joined", "failed", "stalled"): + if shown != self._last_join: self.log("wifi_drive_join", interface=self.fallback_interface, outcome=shown) self._last_join = shown with self._home_lock: diff --git a/openpilot/starpilot/system/starport/network.py b/openpilot/starpilot/system/starport/network.py index f814cd8f24..b94ab360b4 100644 --- a/openpilot/starpilot/system/starport/network.py +++ b/openpilot/starpilot/system/starport/network.py @@ -504,12 +504,15 @@ class NetworkLease: 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: + after: Callable[[], None] = lambda: None, timeout: float = DRIVE_JOIN_TIMEOUT_S, + cancelled: Callable[[], bool] = lambda: False) -> 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: + if cancelled(): + return "none" path = self.device_path or next((path for path, name in self._wifi_devices() if name == self.interface), "") if not path: return "none" @@ -518,8 +521,10 @@ class NetworkLease: return "connected" if self._carrier() else "none" if state != DEVICE_STATE_DISCONNECTED: return "none" - self._scan(path) + self._scan(path, cancelled) with self._lock: + if cancelled() or int(self._get(path, NM_DEVICE_IFACE, "State")) != DEVICE_STATE_DISCONNECTED: + return "none" heard = self._heard(path) now = time.monotonic() self._failed_at = {key: at for key, at in self._failed_at.items() if now - at < FAILED_SKIP_S} @@ -542,6 +547,8 @@ class NetworkLease: return "none" try: with self._lock: + if cancelled() or int(self._get(path, NM_DEVICE_IFACE, "State")) != DEVICE_STATE_DISCONNECTED: + return "none" self._call(NM_PATH, NM_IFACE, "ActivateConnection", "ooo", (target, path, "/")) deadline, started = time.monotonic() + timeout, False while time.monotonic() < deadline: @@ -570,13 +577,15 @@ class NetworkLease: except NetworkError as error: self.log("wifi_autoconnect_pause_failed", error=str(error)) - def _scan(self, path: str) -> None: - """NetworkManager stops scanning a disconnected wlan0 while its auto-join is paused, so ask for a scan and wait for it.""" + def _scan(self, path: str, cancelled: Callable[[], bool] = lambda: False) -> None: + """Request a scan while auto-join is paused and wait briefly for completion.""" if time.monotonic() - self._scanned_at < DRIVE_SCAN_EVERY_S: return self._scanned_at = time.monotonic() try: with self._lock: + if cancelled(): + return before = int(self._get(path, NM_WIRELESS_IFACE, "LastScan")) self._call(path, NM_WIRELESS_IFACE, "RequestScan", "a{sv}", ({},)) except NetworkError: @@ -586,6 +595,8 @@ class NetworkLease: time.sleep(0.25) try: with self._lock: + if cancelled(): + return if int(self._get(path, NM_WIRELESS_IFACE, "LastScan")) != before: return except NetworkError: diff --git a/openpilot/starpilot/system/starport/tests/test_car_interface.py b/openpilot/starpilot/system/starport/tests/test_car_interface.py index 7c899a6f9e..bea2a1d5f8 100644 --- a/openpilot/starpilot/system/starport/tests/test_car_interface.py +++ b/openpilot/starpilot/system/starport/tests/test_car_interface.py @@ -574,7 +574,7 @@ class JoiningLease(FakeLease): self.held = True return True - def drive_join(self, allowed, before=lambda: True, after=lambda: None): + def drive_join(self, allowed, before=lambda: True, after=lambda: None, cancelled=lambda: False): JoiningLease.calls.append((allowed("parked-only"), allowed("anywhere"), before())) after() return JoiningLease.outcomes.pop(0) @@ -635,3 +635,13 @@ def test_a_failed_drive_join_retries_soon_and_never_pauses_the_hotspot_when_swit 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) + + +def test_drive_join_logs_only_outcome_changes(monkeypatch): + lease, log, _ = make_joining(["failed", "failed", "none", "failed"], {"pauseHotspot": False}) + lease.home = JoiningLease(log, "wlan0") + monkeypatch.setattr(lease, "_arm", lambda seconds: None) + for _ in range(4): + lease._retry_home() + assert [fields["outcome"] for event, fields in log.events if event == "wifi_drive_join"] == ["failed", "none", "failed"] + 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 a556591c81..fd52e8f85f 100644 --- a/openpilot/starpilot/system/starport/tests/test_starport.py +++ b/openpilot/starpilot/system/starport/tests/test_starport.py @@ -1463,7 +1463,7 @@ def test_drive_join_resumes_hotspot_promptly_after_failure(monkeypatch, states): if name == "LastScan": return 1 reads[0] += 1 - return network.DEVICE_STATE_DISCONNECTED if reads[0] == 1 else states[min(reads[0] - 2, len(states) - 1)] + return network.DEVICE_STATE_DISCONNECTED if reads[0] <= 3 else states[min(reads[0] - 4, len(states) - 1)] def call(lease, path, interface, member, *args): if member == "GetSettings": @@ -1486,20 +1486,22 @@ def test_drive_join_resumes_hotspot_promptly_after_failure(monkeypatch, states): assert result == "failed" assert now[0] == len(states) * 0.25 - assert reads[0] == len(states) + 1 + assert reads[0] == len(states) + 3 assert order == ["pause", "resume"] assert sets == [("Autoconnect", "b", False)] def test_drive_join_skips_a_network_no_longer_heard_and_one_that_just_refused(monkeypatch): from openpilot.starpilot.system.starport import network + now = [1000.0] + monkeypatch.setattr(network.time, "monotonic", lambda: now[0]) profiles = {"/settings/home": ("home", 9), "/settings/phone": ("phone", 1)} heard, calls, state = {b"phone": 60}, [], [30] monkeypatch.setattr(network.NetworkLease, "_heard", lambda lease, path: dict(heard)) - monkeypatch.setattr(network.NetworkLease, "_scan", lambda lease, path: None) + monkeypatch.setattr(network.NetworkLease, "_scan", lambda lease, path, cancelled: None) 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): + def call(lease, path, interface, member, signature=None, body: tuple = (), timeout=10.0): if member == "GetSettings": uuid, priority = profiles[path] return ({"connection": {"uuid": ("s", uuid), "autoconnect-priority": ("i", priority)}, @@ -1516,6 +1518,74 @@ def test_drive_join_skips_a_network_no_longer_heard_and_one_that_just_refused(mo assert lease.drive_join(lambda uuid: True) == "failed" and calls[-1] == "/settings/home" state[0] = 30 assert lease.drive_join(lambda uuid: True) == "none" and len(calls) == 2 # both refused just now + now[0] += network.FAILED_SKIP_S + assert lease.drive_join(lambda uuid: True) == "failed" and calls == ["/settings/phone", "/settings/home", "/settings/home"] + + +@pytest.mark.parametrize("during", ["scan", "pause"]) +@pytest.mark.parametrize("change", ["cancel", "state"]) +def test_drive_join_does_not_activate_after_cancellation_or_state_change(monkeypatch, during, change): + from openpilot.starpilot.system.starport import network + stopped, state, calls, cleanup = [False], [30], [], [] + + def interrupt(): + if change == "cancel": + stopped[0] = True + else: + state[0] = network.DEVICE_STATE_ACTIVATED + + def scan(lease, path, cancelled): + if during == "scan": + interrupt() + + def before(): + if during == "pause": + interrupt() + return True + + def call(lease, path, interface, member, *args): + if member == "GetSettings": + return ({"connection": {"uuid": ("s", "home")}, "802-11-wireless": {"ssid": ("ay", b"home")}},) + calls.append(member) + + monkeypatch.setattr(network.NetworkLease, "_scan", scan) + monkeypatch.setattr(network.NetworkLease, "_heard", lambda lease, path: {b"home": 60}) + monkeypatch.setattr(network.NetworkLease, "_get", lambda lease, path, interface, name: + state[0] if name == "State" else ["/settings/home"]) + monkeypatch.setattr(network.NetworkLease, "_call", call) + lease = network.NetworkLease(lambda *a, **k: None, "wlan0") + lease.device_path = "/dev/wlan0" + assert lease.drive_join(lambda uuid: True, before=before, after=lambda: cleanup.append(True), cancelled=lambda: stopped[0]) == "none" + assert calls == [] and cleanup == ([True] if during == "pause" else []) + + +@pytest.mark.parametrize("result", ["complete", "busy", "timeout", "cancel"]) +def test_drive_scan_is_bounded_and_throttled(monkeypatch, result): + from openpilot.starpilot.system.starport import network + now, scans, stopped = [1000.0], [], [False] + + def sleep(seconds): + now[0] += seconds + stopped[0] = result == "cancel" + + def call(lease, path, interface, member, *args): + scans.append(now[0]) + if result == "busy": + raise network.NetworkError("busy") + + monkeypatch.setattr(network.time, "monotonic", lambda: now[0]) + monkeypatch.setattr(network.time, "sleep", sleep) + monkeypatch.setattr(network.NetworkLease, "_call", call) + monkeypatch.setattr(network.NetworkLease, "_get", lambda *args: + int(now[0] * 1000) if result == "complete" else 0) + lease = network.NetworkLease(lambda *a, **k: None, "wlan0") + lease._scan("/dev/wlan0", lambda: stopped[0]) + assert now[0] - 1000 == {"complete": 0.25, "busy": 0, "timeout": network.DRIVE_SCAN_WAIT_S, "cancel": 0.25}[result] + lease._scan("/dev/wlan0") + assert scans == [1000.0] + now[0] = 1000 + network.DRIVE_SCAN_EVERY_S + lease._scan("/dev/wlan0") + assert scans == [1000.0, 1000 + network.DRIVE_SCAN_EVERY_S] def test_heard_networks_come_from_the_latest_scan_only(monkeypatch):