mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 08:53:41 +08:00
Enhance drive join functionality with cancellation support and improved logging
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user