mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-28 15:53:43 +08:00
Merge pull request #323 from dirwin31:HotspotDriveJoin
Network: Join phone hotspots during drives without long pauses
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -221,7 +221,7 @@ export const NetworksPage = {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<GalaxySettingRow :row="switchRow('Pause Galaxy hotspot while joining Wi-Fi', snapshot.pauseHotspot, 'Briefly pauses the hotspot during a drive so joining Wi-Fi does not disturb StarPort.')" :index="0"
|
||||
<GalaxySettingRow :row="switchRow('Pause Galaxy hotspot while joining Wi-Fi', snapshot.pauseHotspot, 'Briefly pauses the hotspot whenever the comma joins Wi-Fi. Only needed if joins disturb StarPort.')" :index="0"
|
||||
:busy="busy" :disabled="!snapshot.editable" :save-value="(index, value) => send({ action: 'pauseHotspot', value: value === 'On' })" />
|
||||
</section>
|
||||
<section class="gx-card gx-settings__section"><div class="gx-section__header"><i class="bi bi-broadcast" aria-hidden="true"></i><span class="gx-section__title">Nearby networks</span><span v-if="adding && availableNetworks.length" class="gx-section__count">{{ availableNetworks.length }}</span>
|
||||
|
||||
@@ -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
|
||||
@@ -234,23 +235,26 @@ 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"
|
||||
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:
|
||||
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:
|
||||
|
||||
@@ -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:
|
||||
@@ -498,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"
|
||||
@@ -512,13 +521,24 @@ class NetworkLease:
|
||||
return "connected" if self._carrier() else "none"
|
||||
if state != DEVICE_STATE_DISCONNECTED:
|
||||
return "none"
|
||||
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}
|
||||
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]
|
||||
@@ -527,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:
|
||||
@@ -536,12 +558,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 +577,53 @@ class NetworkLease:
|
||||
except NetworkError as error:
|
||||
self.log("wifi_autoconnect_pause_failed", error=str(error))
|
||||
|
||||
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:
|
||||
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 cancelled():
|
||||
return
|
||||
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:
|
||||
|
||||
@@ -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)
|
||||
@@ -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,18 @@ 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)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -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)]
|
||||
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":
|
||||
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:]))
|
||||
@@ -1477,6 +1486,125 @@ 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, 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: tuple = (), 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
|
||||
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):
|
||||
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}
|
||||
|
||||
Reference in New Issue
Block a user