From 3d6c33e720d971cfd12e25585ca2a60555be4192 Mon Sep 17 00:00:00 2001 From: Danny Date: Sun, 15 Nov 2026 13:15:18 -0800 Subject: [PATCH 01/14] Starport: Auto Wifi Rejoin Fix --- .../starpilot/system/starport/network.py | 75 ++++++++++++++++ .../starpilot/system/starport/supervisor.py | 6 +- .../starport/tests/test_car_interface.py | 6 ++ .../system/starport/tests/test_starport.py | 89 +++++++++++++++++++ 4 files changed, 173 insertions(+), 3 deletions(-) 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 From 7c0b4bf06bd636021b0fee6cb2ac8efb5e3cfe5b Mon Sep 17 00:00:00 2001 From: dirwin31 <83434411+dirwin31@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:02:09 -0800 Subject: [PATCH 02/14] StarPort: Keep A Home Wi-Fi Join That Already Connected - When the car's acks stall right after the comma's own Wi-Fi changes, stop the join only if it has not connected yet. - A join that already connected (only its address left) is kept and logged as other_wifi_join_kept; the 8 s grace still reconnects the car if acks never return. - 2026-11-16: stopping a connected iPhone hotspot join lost the hotspot and still dropped the car, while a joined hotspot streamed alongside the car for minutes. --- openpilot/starpilot/system/starport/supervisor.py | 7 ++++++- .../starport/tests/test_shared_radio_grace.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index f021334669..f0b042b569 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -289,7 +289,7 @@ class SharedRadioWatch: self.counter = counter or Path(f"/sys/class/net/{interface}/carrier_changes") self.carrier = carrier or Path(f"/sys/class/net/{interface}/carrier") self.on_down = on_down # the other network was lost, not just roamed - self.on_stall = on_stall # the car's acks stopped after a change + self.on_stall = on_stall # the car's acks stopped after a change that has not connected yet self.changed_at: float | None = None self._stop = threading.Event() self._thread = threading.Thread(target=self._run, name="aa_radio_watch", daemon=True) @@ -329,6 +329,11 @@ class SharedRadioWatch: self.log("other_wifi_hold_failed", error=str(error) or type(error).__name__) def stalled(self) -> None: + # A join that already connected has only its address left. Stopping it there lost the hotspot and still + # dropped the car on 2026-11-16, while a joined hotspot then streamed alongside the car for minutes. + if self._carrier(): + self.log("other_wifi_join_kept", interface=self.interface) + return if self.on_stall is not None: self.on_stall() diff --git a/openpilot/starpilot/system/starport/tests/test_shared_radio_grace.py b/openpilot/starpilot/system/starport/tests/test_shared_radio_grace.py index fab1f2c971..3b06e72bdc 100644 --- a/openpilot/starpilot/system/starport/tests/test_shared_radio_grace.py +++ b/openpilot/starpilot/system/starport/tests/test_shared_radio_grace.py @@ -135,6 +135,19 @@ def test_watch_holds_home_wifi_only_when_it_was_lost(tmp_path, carrier, held): watch.stop() +@pytest.mark.parametrize("carrier, stopped", [("1\n", False), ("0\n", True), (None, True)]) +def test_stall_keeps_a_join_that_already_connected(tmp_path, carrier, stopped): + carrier_path = tmp_path / "carrier" + if carrier is not None: + carrier_path.write_text(carrier) + stops, logged = [], [] + watch = SharedRadioWatch(lambda name, **fields: logged.append(name), counter=tmp_path / "carrier_changes", + carrier=carrier_path, on_stall=lambda: stops.append(True)) + watch.stalled() + assert stops == ([True] if stopped else []) + assert logged == ([] if stopped else ["other_wifi_join_kept"]) + + def test_watch_without_the_counter_never_reports(tmp_path): watch = SharedRadioWatch(lambda *a, **k: None, interval=0.01, counter=tmp_path / "missing").start() try: From ecce9caaa074b98955c8f459e9f2c97e38cee2cf Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 09:55:08 -0800 Subject: [PATCH 03/14] StarPort: Record Wi-Fi firmware restarts in stall captures --- .../starpilot/system/starport/supervisor.py | 3 ++- .../starpilot/system/starport/system_slice.py | 26 ++++++++++++++++--- .../starport/tests/test_system_slice.py | 19 ++++++++++++++ 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index f0b042b569..96cd9f4901 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -420,7 +420,8 @@ class EventLog: """Save the last seconds of device logs now; the session's own capture keeps only its newest lines.""" if self.path is not None: now = datetime.now(UTC).timestamp() - system_slice.write_sidecar_async(self.path, now - STALL_CAPTURE_S, now, tag=".stall") + system_slice.write_sidecar_async(self.path, now - STALL_CAPTURE_S, now, tag=".stall", + on_firmware=lambda lines, reason: self("wifi_firmware_restart", lines=lines, reason=reason)) def _line(self, record: dict) -> str: return json.dumps(record, default=str) + "\n" diff --git a/openpilot/starpilot/system/starport/system_slice.py b/openpilot/starpilot/system/starport/system_slice.py index 115d223d07..1f4433aa19 100644 --- a/openpilot/starpilot/system/starport/system_slice.py +++ b/openpilot/starpilot/system/starport/system_slice.py @@ -19,6 +19,8 @@ MAX_LINE = 300 SIDECAR_SUFFIX = ".system.json" QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"") SSID = re.compile(r"(?i)\b(e?ssid)\b[=: ]+\S+") +FIRMWARE = re.compile(r"subsys-restart|failure reason|Root PD|icnss: (PD service down|QMI Service Disconnected)") +MAX_FIRMWARE_LINES = 40 def _timestamp(value: float) -> str: @@ -53,6 +55,12 @@ def _lines(data: bytes) -> list[str]: return [line for line in text.splitlines() if line.strip()][-MAX_LINES:] +def firmware_lines(data: bytes) -> list[str]: + """Wi-Fi and modem firmware restart lines from the whole kernel window, kept apart from the newest-lines cap.""" + text = system_snapshot.redact(data).decode("utf-8", errors="replace") + return [line[:MAX_LINE] for line in text.splitlines() if FIRMWARE.search(line)][:MAX_FIRMWARE_LINES] + + def collect(start: float, end: float, *, collector=system_snapshot.collect) -> dict: """The slice for [start, end] (epoch seconds), each source as {"lines": [...]} or {"error": ...}.""" files = collector(start, DEADLINE_S, command_set=commands(start, end)) @@ -72,6 +80,9 @@ def collect(start: float, end: float, *, collector=system_snapshot.collect) -> d proc = files.get("proc.txt") if proc: result["sources"]["proc"] = {"lines": _lines(proc)} + firmware = firmware_lines(files.get("kernel", b"")) + if firmware: + result["sources"]["firmware"] = {"lines": firmware} return result @@ -80,11 +91,17 @@ def sidecar_path(log_path: Path, tag: str = "") -> Path: return log_path.with_name(f"session-{match[1] if match else log_path.stem}{tag}{SIDECAR_SUFFIX}") -def write_sidecar(log_path: Path, start: float, end: float, *, collector=system_snapshot.collect, tag: str = "") -> None: +def write_sidecar(log_path: Path, start: float, end: float, *, collector=system_snapshot.collect, tag: str = "", + on_firmware=None) -> None: """Capture the window and save it beside the session log; never raises.""" try: path = sidecar_path(log_path, tag) - text = json.dumps(collect(start, end, collector=collector)) + captured = collect(start, end, collector=collector) + firmware = captured["sources"].get("firmware", {}).get("lines", []) + if firmware and on_firmware is not None: + reason = next((line.split("failure reason", 1)[1].strip(" :") for line in firmware if "failure reason" in line), "") + on_firmware(len(firmware), reason[:200]) + text = json.dumps(captured) temporary = path.with_name(path.name + ".tmp") fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w") as handle: @@ -94,8 +111,9 @@ def write_sidecar(log_path: Path, start: float, end: float, *, collector=system_ pass -def write_sidecar_async(log_path: Path, start: float, end: float, tag: str = "") -> threading.Thread: - thread = threading.Thread(target=write_sidecar, args=(log_path, start, end), kwargs={"tag": tag}, name="aa_system_slice", daemon=True) +def write_sidecar_async(log_path: Path, start: float, end: float, tag: str = "", on_firmware=None) -> threading.Thread: + thread = threading.Thread(target=write_sidecar, args=(log_path, start, end), kwargs={"tag": tag, "on_firmware": on_firmware}, + name="aa_system_slice", daemon=True) thread.start() return thread diff --git a/openpilot/starpilot/system/starport/tests/test_system_slice.py b/openpilot/starpilot/system/starport/tests/test_system_slice.py index 85e6245fe0..2123c27b10 100644 --- a/openpilot/starpilot/system/starport/tests/test_system_slice.py +++ b/openpilot/starpilot/system/starport/tests/test_system_slice.py @@ -67,3 +67,22 @@ def test_a_collector_that_raises_leaves_no_sidecar(tmp_path): system_slice.write_sidecar(log, 0.0, 1.0, collector=broken) assert system_slice.read_sidecar(log) == {} + + +def test_firmware_restart_lines_survive_the_cap_and_are_reported(tmp_path): + def crashed(since, deadline, *, command_set): + files = fake_collector(since, deadline, command_set=command_set) + manifest = json.loads(files["manifest.json"]) + del manifest["commands"]["kernel"]["error"] + files["manifest.json"] = json.dumps(manifest).encode() + files["kernel"] = (b"modem subsystem failure reason: wlan_fw.c:12: assert\nsubsys-restart: Shutting down modem\n" + + b"noise\n" * (system_slice.MAX_LINES + 5)) + return files + + log = tmp_path / "session-000009-20261116-120000.jsonl" + log.write_text("") + seen = [] + system_slice.write_sidecar(log, 1_000_000.0, 1_000_060.0, collector=crashed, tag=".stall", on_firmware=lambda *a: seen.append(a)) + saved = json.loads((tmp_path / "session-000009.stall.system.json").read_text())["sources"] + assert len(saved["firmware"]["lines"]) == 2 and "failure reason" not in "".join(saved["kernel"]["lines"]) + assert seen == [(2, "wlan_fw.c:12: assert")] From 6e6702961b73b0af05d19f9b4be36c599275e481 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 10:02:02 -0800 Subject: [PATCH 04/14] Network: Reconnect apps after the comma changes networks --- openpilot/starpilot/soloist/supervisor.py | 43 +++- .../starpilot/soloist/tests/test_runtime.py | 27 ++ openpilot/starpilot/system/netwatch.py | 232 ++++++++++++++++++ .../starpilot/system/tests/test_netwatch.py | 73 ++++++ openpilot/system/manager/process_config.py | 2 + openpilot/system/manager/process_health.py | 2 +- 6 files changed, 377 insertions(+), 2 deletions(-) create mode 100644 openpilot/starpilot/system/netwatch.py create mode 100644 openpilot/starpilot/system/tests/test_netwatch.py diff --git a/openpilot/starpilot/soloist/supervisor.py b/openpilot/starpilot/soloist/supervisor.py index cd6a3f3b2f..5d66c6b647 100644 --- a/openpilot/starpilot/soloist/supervisor.py +++ b/openpilot/starpilot/soloist/supervisor.py @@ -24,6 +24,7 @@ from openpilot.starpilot.soloist import backend, bluealsa_runtime, bugsink_repor from openpilot.starpilot.soloist import now_playing as now_playing_module from openpilot.starpilot.soloist.client import PlayerClient from openpilot.starpilot.soloist.paths import CONTROL_SOCKET, Layout, private_dir +from openpilot.starpilot.system import netwatch A2DP_SINK = '0000110b-0000-1000-8000-00805f9b34fb' EXIT_EXPIRED = 10 @@ -37,6 +38,7 @@ PLAYING_GRACE_SECONDS = 600.0 LOG_LINES = 200 LOGIN_RETRY_MAX_SECONDS = 300.0 LOGIN_REJECTED_AFTER = 3 +NETWORK_RECHECK_SECONDS = 20.0 def network_ready() -> bool: @@ -65,6 +67,20 @@ EXPIRES_IN = re.compile(r'client expires in (\d+) days?') LOGIN_FAILED = re.compile(r'\blogin failed\b') +def network_change() -> float: + return netwatch.read_status().get('changedAt', 0.0) + + +def cloud_connected(pid: int, run=subprocess.run) -> bool: + """True while the player holds a connection to an internet address.""" + try: + listing = run(['ss', '-4tnHp', 'state', 'established'], capture_output=True, text=True, timeout=5).stdout + except (OSError, subprocess.SubprocessError): + return True + lines = '\n'.join(line for line in listing.splitlines() if f'pid={pid},' in line) + return any(netwatch.internet(connection, connection[0]) for connection in netwatch.parse_connections(lines)) + + def _kill_group(process: subprocess.Popen | None) -> None: if process is None or process.poll() is not None: return @@ -135,7 +151,9 @@ class Supervisor: def __init__(self, layout: Layout | None = None, *, output: BluetoothOutput | None = None, spawn: Callable[..., subprocess.Popen] = subprocess.Popen, clock: Callable[[], float] = time.monotonic, make_client: Callable[[Path], PlayerClient] | None = None, - network: Callable[[], bool] = network_ready): + network: Callable[[], bool] = network_ready, + network_change: Callable[[], float] = network_change, + cloud: Callable[[int], bool] = cloud_connected): self.layout = layout or Layout.default() self.output = output or BluetoothOutput() self.spawn, self.clock, self.network = spawn, clock, network @@ -176,6 +194,9 @@ class Supervisor: self.login_failures = 0 self.answered = False self.last_playing = False + self.network_change, self.cloud = network_change, cloud + self.network_seen: float | None = None + self.network_check_at = 0.0 # ---- status --------------------------------------------------------------------------------------- def _set(self, state: str, message: str = '') -> None: @@ -229,6 +250,7 @@ class Supervisor: def stop_children(self, *, release_phone: bool = True) -> None: self.unresponsive_since = None + self.network_check_at = 0.0 self.login_failed = False self.output_generation += 1 self.output_seen, self.output_flips, self.waiting_for = None, 0, '' @@ -472,6 +494,7 @@ class Supervisor: self.unresponsive_since = None if self.answered and now - self.started_at > 60: self.fast_failures = 0 + self._follow_network(now) return self.stop_children() if code == EXIT_EXPIRED: @@ -481,6 +504,24 @@ class Supervisor: detail = 'audio output closed' if server_dead and code is None else f'player exited ({code})' self._fail(now, f'Spotify stopped: {detail}. Retrying…') + def _follow_network(self, now: float) -> None: + """The network watcher closes the player's old connections; restart it only if it stays offline while idle.""" + changed = self.network_change() + if changed != self.network_seen: + if self.network_seen is not None: + self.network_check_at = now + NETWORK_RECHECK_SECONDS + with self.log_lock: + self.log.append('network: the comma changed networks; Spotify is reconnecting') + self.network_seen = changed + if not self.network_check_at or now < self.network_check_at or self.player is None: + return + self.network_check_at = 0.0 + if self.last_playing or self.cloud(self.player.pid): + return + self.stop_children() + self.retry_at = now + self._set('retrying', 'Reconnecting Spotify on the new network…') + def _pull(self, now: float) -> None: snapshot = self.client.snapshot() if self.client is not None else {} if now < self.pull_at or not (snapshot.get('connected') and snapshot.get('loggedIn')) or snapshot.get('active') or parked(): diff --git a/openpilot/starpilot/soloist/tests/test_runtime.py b/openpilot/starpilot/soloist/tests/test_runtime.py index 537d2fa331..394d37a32a 100644 --- a/openpilot/starpilot/soloist/tests/test_runtime.py +++ b/openpilot/starpilot/soloist/tests/test_runtime.py @@ -495,3 +495,30 @@ def test_pull_onroad_takes_spotify_over_only_while_driving(layout, monkeypatch): now[0] += supervisor.PULL_RETRY_SECONDS sup.tick() assert sup.client.sent == [('activate', {})] * 2 + + +def test_network_change_restarts_an_idle_player_only_if_it_stays_offline(layout, monkeypatch): + ready_layout(layout, monkeypatch) + spawned = [] + sup, now = make_supervisor(layout, spawned) + changed, online = [1.0], [True] + sup.network_change, sup.cloud = lambda: changed[0], lambda pid: online[0] + sup.tick() + sup.tick() + changed[0] = 2.0 + sup.tick() + now[0] += supervisor.NETWORK_RECHECK_SECONDS + 1 + sup.tick() + assert len(spawned) == 2 and any('changed networks' in line for line in sup.log) + changed[0], online[0] = 3.0, False + sup.tick() + sup.last_playing = True + now[0] += supervisor.NETWORK_RECHECK_SECONDS + 1 + sup._follow_network(now[0]) + assert sup.player is not None # music from the cache is never cut + changed[0] = 4.0 + sup.tick() + now[0] += supervisor.NETWORK_RECHECK_SECONDS + 1 + sup.last_playing = False + sup._follow_network(now[0]) + assert sup.player is None and sup.status()['state'] == 'retrying' diff --git a/openpilot/starpilot/system/netwatch.py b/openpilot/starpilot/system/netwatch.py new file mode 100644 index 0000000000..791870cdb0 --- /dev/null +++ b/openpilot/starpilot/system/netwatch.py @@ -0,0 +1,232 @@ +"""Closes internet connections left on a network the comma has moved off, so apps reconnect on the new one. + +Linux keeps a connection open after its address is gone, and an app without keepalives then waits on it for +many minutes. Only connections that were open on the old link are closed; the car link, the Galaxy hotspot +and local addresses are never touched. +""" +from __future__ import annotations + +import fcntl +import ipaddress +import json +import os +import signal +import socket +import struct +import subprocess +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path + +LINKS = ('wlan0', 'ppp0') +STATUS_PATH = Path('/dev/shm/starpilot-netwatch.json') +CHANGE_SETTLE_S = 2.0 +DOWN_SETTLE_S = 4.0 +GATEWAY_WAIT_S = 10.0 # longest wait for the new gateway's hardware address before accepting a Wi-Fi change +SIOCGIFADDR = 0x8915 + +Connection = tuple[str, int, str, int] # local address, local port, peer address, peer port + + +def address(link: str) -> str: + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe: + packed = fcntl.ioctl(probe.fileno(), SIOCGIFADDR, struct.pack('256s', link.encode()[:15])) + return socket.inet_ntoa(packed[20:24]) + except OSError: + return '' + + +def _read(path: str) -> str: + try: + return Path(path).read_text() + except OSError: + return '' + + +def default_routes(text: str | None = None) -> list[tuple[int, str, str]]: + """(metric, interface, gateway) for every IPv4 default route, best first.""" + routes = [] + for line in (_read('/proc/net/route') if text is None else text).splitlines()[1:]: + fields = line.split() + try: + if len(fields) > 6 and fields[1] == '00000000' and int(fields[3], 16) & 1: + routes.append((int(fields[6]), fields[0], socket.inet_ntoa(struct.pack(' str: + for line in (_read('/proc/net/arp') if text is None else text).splitlines()[1:]: + fields = line.split() + if len(fields) > 5 and fields[0] == gateway and fields[5] == link and fields[2] != '0x0': + return fields[3] + return '' + + +def signature(link: str) -> tuple | None: + """What identifies the network behind a link, or None while the link carries no internet.""" + local = address(link) + if not local: + return None + if link.startswith('ppp'): + return (_read(f'/sys/class/net/{link}/ifindex').strip(), local) + if _read(f'/sys/class/net/{link}/carrier').strip() != '1': + return None + gateway = next((route[2] for route in default_routes() if route[1] == link), '') + return (local, gateway, gateway_hardware(link, gateway)) if gateway else None + + +def same(first: tuple | None, second: tuple | None) -> bool: + if first is None or second is None: + return first is second + if len(first) == 3 and len(second) == 3 and not (first[2] and second[2]): + return first[:2] == second[:2] + return first == second + + +def local_address(mark: tuple | None) -> str: + return '' if mark is None else mark[1] if len(mark) == 2 else mark[0] + + +def _endpoint(value: str) -> tuple[str, int]: + host, _, port = value.rpartition(':') + return host, int(port) + + +def parse_connections(text: str) -> set[Connection]: + found = set() + for line in text.splitlines(): + fields = line.split() + try: + found.add((*_endpoint(fields[2]), *_endpoint(fields[3]))) + except (IndexError, ValueError): + continue + return found + + +def internet(connection: Connection, local: str) -> bool: + try: + peer = ipaddress.ip_address(connection[2]) + except ValueError: + return False + return connection[0] == local and peer.version == 4 and peer.is_global + + +def list_connections(run=subprocess.run) -> set[Connection]: + try: + return parse_connections(run(['ss', '-4tnH', 'state', 'established'], capture_output=True, text=True, timeout=5).stdout) + except (OSError, subprocess.SubprocessError): + return set() + + +def close_connection(connection: Connection, run=subprocess.run) -> bool: + local, local_port, peer, peer_port = connection + command = ['ss', '-K', '-4tnH', 'state', 'established', 'src', local, 'sport', '=', f':{local_port}', + 'dst', peer, 'dport', '=', f':{peer_port}'] + try: + return bool(run(command if os.geteuid() == 0 else ['sudo', '-n', *command], capture_output=True, text=True, timeout=5).stdout.strip()) + except (OSError, subprocess.SubprocessError): + return False + + +@dataclass +class Link: + stable: tuple | None = None + candidate: tuple | None = None + changing: bool = False + since: float = 0.0 + started: float = 0.0 + pending: set | None = None + + +@dataclass +class Watcher: + read: object = signature + connections: object = list_connections + close: object = close_connection + links: dict = field(default_factory=dict) + changes: int = 0 + closed: int = 0 + changed_at: float = 0.0 + + def start(self) -> None: + self.links = {name: Link(stable=self.read(name)) for name in LINKS} + + def tick(self, now: float) -> list[tuple[str, int]]: + """Returns (link, connections closed) for every change accepted on this pass.""" + accepted = [] + for name, link in self.links.items(): + current = self.read(name) + if same(current, link.stable): + if current is not None and len(current) == 3 and current[2]: + link.stable = current + link.changing, link.candidate, link.pending = False, None, None + continue + if link.pending is None: + old = local_address(link.stable) + link.pending = {c for c in self.connections() if internet(c, old)} if old else set() + link.started = now + if not link.changing or not same(current, link.candidate): + link.changing, link.candidate, link.since = True, current, now + continue + link.candidate = current + waiting_gateway = current is not None and len(current) == 3 and not current[2] and now - link.started < GATEWAY_WAIT_S + if now - link.since < (DOWN_SETTLE_S if current is None else CHANGE_SETTLE_S) or waiting_gateway: + continue + still_open = link.pending & self.connections() if link.pending else set() + count = sum(1 for connection in sorted(still_open) if self.close(connection)) + link.stable, link.changing, link.candidate, link.pending = current, False, None, None + self.changes += 1 + self.closed += count + self.changed_at = time.time() # noqa: TID251 shown to the user as a wall-clock time + accepted.append((name, count)) + return accepted + + def status(self) -> dict: + routes = default_routes() + best = routes[0][1] if routes else '' + return {'link': 'wifi' if best.startswith('wlan') else 'cellular' if best.startswith('ppp') else 'none' if not best else 'other', + 'wifi': self.links['wlan0'].stable is not None, 'cellular': self.links['ppp0'].stable is not None, + 'changes': self.changes, 'closed': self.closed, 'changedAt': self.changed_at, + 'updated': time.monotonic()} + + +def read_status(path: Path = STATUS_PATH, clock=time.monotonic) -> dict: + try: + value = json.loads(path.read_text()) + return value if type(value) is dict and 0 <= clock() - value.get('updated', -1e9) < 15 else {} + except (OSError, ValueError, TypeError): + return {} + + +def publish(status: dict, path: Path = STATUS_PATH) -> None: + temporary = path.with_name(path.name + '.tmp') + try: + temporary.write_text(json.dumps(status)) + os.chmod(temporary, 0o644) + os.replace(temporary, path) + except OSError: + pass + + +def main() -> None: + from openpilot.common.swaglog import cloudlog + os.nice(10) + stop = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stop.set()) + signal.signal(signal.SIGINT, lambda *_: stop.set()) + watcher = Watcher() + watcher.start() + while not stop.is_set(): + now = time.monotonic() + for name, count in watcher.tick(now): + cloudlog.event('netwatch_changed', link=name, closed=count, up=watcher.links[name].stable is not None) + publish(watcher.status()) + stop.wait(1.0) + + +if __name__ == '__main__': + main() diff --git a/openpilot/starpilot/system/tests/test_netwatch.py b/openpilot/starpilot/system/tests/test_netwatch.py new file mode 100644 index 0000000000..69734ed5a7 --- /dev/null +++ b/openpilot/starpilot/system/tests/test_netwatch.py @@ -0,0 +1,73 @@ +"""The network watcher closes only internet connections that were open on a link the comma has left.""" + +from openpilot.starpilot.system import netwatch + +HOME = ("192.168.35.20", "192.168.35.1", "aa:aa") +PHONE = ("172.20.10.4", "172.20.10.1", "bb:bb") +CELL = ("14", "10.230.35.11") +SPOTIFY = ("172.20.10.4", 50000, "35.186.224.24", 443) +CAR = ("172.20.10.4", 50001, "172.20.10.9", 30515) +OTHER = ("10.230.35.11", 50002, "35.186.224.24", 443) + + +def watcher(marks, open_connections): + closed = [] + made = netwatch.Watcher(read=lambda name: marks[name], connections=lambda: set(open_connections), + close=lambda connection: closed.append(connection) or True) + made.start() + return made, closed + + +def test_leaving_wifi_closes_its_internet_connections_after_it_settles(): + marks = {"wlan0": PHONE, "ppp0": CELL} + open_connections = {SPOTIFY, CAR, OTHER} + made, closed = watcher(marks, open_connections) + marks["wlan0"] = None + assert made.tick(0.0) == [] and made.tick(3.0) == [] + assert made.tick(4.5) == [("wlan0", 1)] and closed == [SPOTIFY] + + +def test_a_short_drop_back_onto_the_same_network_closes_nothing(): + marks = {"wlan0": HOME, "ppp0": CELL} + made, closed = watcher(marks, {("192.168.35.20", 1, "35.186.224.24", 443)}) + marks["wlan0"] = None + made.tick(0.0) + marks["wlan0"] = HOME + assert made.tick(2.0) == [] and made.tick(9.0) == [] and closed == [] + + +def test_connections_opened_after_the_change_or_already_closed_are_left_alone(): + marks = {"wlan0": None, "ppp0": CELL} + open_connections = {OTHER, ("10.230.35.11", 50003, "1.1.1.1", 443)} + made, closed = watcher(marks, open_connections) + marks["ppp0"] = ("15", "10.230.35.11") # cellular came back on a new interface with the same address + made.tick(0.0) + open_connections.discard(("10.230.35.11", 50003, "1.1.1.1", 443)) + open_connections.add(("10.230.35.11", 50009, "8.8.8.8", 443)) + made.tick(1.0) + assert made.tick(3.5) == [("ppp0", 1)] and closed == [OTHER] + + +def test_a_wifi_change_waits_for_the_new_gateway_before_it_is_judged(): + marks = {"wlan0": ("192.168.1.5", "192.168.1.1", "aa:aa"), "ppp0": CELL} + made, closed = watcher(marks, {("192.168.1.5", 7, "35.186.224.24", 443)}) + marks["wlan0"] = None + made.tick(0.0) + marks["wlan0"] = ("192.168.1.5", "192.168.1.1", "") + assert made.tick(1.0) == [] and closed == [] + marks["wlan0"] = ("192.168.1.5", "192.168.1.1", "cc:cc") # same addresses, a different network + made.tick(2.0) + assert made.tick(5.0) == [("wlan0", 1)] and len(closed) == 1 + + +def test_parsers_read_routes_neighbours_and_sockets(): + routes = "\n".join(["Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask", + "ppp0\t00000000\t4040400A\t0003\t0\t0\t1000\t00000000", + "wlan0\t00000000\t02630A0A\t0003\t0\t0\t600\t00000000", + "wlan0\t00630A0A\t00000000\t0001\t0\t0\t600\t00FFFFFF"]) + assert netwatch.default_routes(routes) == [(600, "wlan0", "10.10.99.2"), (1000, "ppp0", "10.64.64.64")] + neighbours = "IP address HW type Flags HW address Mask Device\n10.10.99.2 0x1 0x2 ac:bc:32:ba:eb:8f * wlan0\n" + assert netwatch.gateway_hardware("wlan0", "10.10.99.2", neighbours) == "ac:bc:32:ba:eb:8f" + sockets = "0 0 10.10.99.177:50176 35.186.224.31:443\n0 0 127.0.0.1:45953 127.0.0.1:60136\n" + assert netwatch.parse_connections(sockets) == {("10.10.99.177", 50176, "35.186.224.31", 443), ("127.0.0.1", 45953, "127.0.0.1", 60136)} + assert not netwatch.internet(CAR, "172.20.10.4") and netwatch.internet(SPOTIFY, "172.20.10.4") diff --git a/openpilot/system/manager/process_config.py b/openpilot/system/manager/process_config.py index e6961b67ce..9ea6b4b642 100644 --- a/openpilot/system/manager/process_config.py +++ b/openpilot/system/manager/process_config.py @@ -192,6 +192,8 @@ procs = [ enabled=COMMA_HARDWARE and not os.environ.get('OPENPILOT_PREFIX'), restart_on_exit=True, ), + PythonProcess("netwatchd", "openpilot.starpilot.system.netwatch", galaxy_local, + enabled=COMMA_HARDWARE and not os.environ.get('OPENPILOT_PREFIX'), restart_on_exit=True), PythonProcess( "companion_uplink", "openpilot.starpilot.galaxy.companion_uplink_daemon", diff --git a/openpilot/system/manager/process_health.py b/openpilot/system/manager/process_health.py index 02a125232b..7e317d6b66 100644 --- a/openpilot/system/manager/process_health.py +++ b/openpilot/system/manager/process_health.py @@ -3,7 +3,7 @@ # Projection and local phone access are optional even when requested. # Their lifecycles remain visible in managerState and their own status. # A dead Jetlink owner sends the drive back to the small model. -ANCILLARY_PROCESSES = frozenset({'starportd', 'galaxy_hotspot', 'jetlinkd'}) +ANCILLARY_PROCESSES = frozenset({'starportd', 'galaxy_hotspot', 'jetlinkd', 'netwatchd'}) def driving_process_failures(processes) -> set[str]: From 501c40fc610def6401e3c1c39bfee5e37ae60c2f Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 10:10:00 -0800 Subject: [PATCH 05/14] Galaxy: Networks page with preferred Wi-Fi, cellular data and the hotspot --- openpilot/starpilot/galaxy/network_prefs.py | 233 ++++++++++++++++++ openpilot/starpilot/galaxy/server.py | 41 ++- .../galaxy/tests/test_home_polish.mjs | 2 + .../galaxy/tests/test_network_prefs.py | 105 ++++++++ .../starpilot/galaxy/tests/test_networks.mjs | 36 +++ .../galaxy/tests/test_preview_contract.py | 2 +- .../starpilot/galaxy/web/data/catalog.json | 7 + openpilot/starpilot/galaxy/web/js/app.js | 4 +- openpilot/starpilot/galaxy/web/js/galaxy.js | 7 +- openpilot/starpilot/galaxy/web/js/networks.js | 133 ++++++++++ openpilot/starpilot/system/netwatch.py | 8 + 11 files changed, 572 insertions(+), 6 deletions(-) create mode 100644 openpilot/starpilot/galaxy/network_prefs.py create mode 100644 openpilot/starpilot/galaxy/tests/test_network_prefs.py create mode 100644 openpilot/starpilot/galaxy/tests/test_networks.mjs create mode 100644 openpilot/starpilot/galaxy/web/js/networks.js diff --git a/openpilot/starpilot/galaxy/network_prefs.py b/openpilot/starpilot/galaxy/network_prefs.py new file mode 100644 index 0000000000..98d53c00ca --- /dev/null +++ b/openpilot/starpilot/galaxy/network_prefs.py @@ -0,0 +1,233 @@ +"""Saved Wi-Fi order and per-network choices for the Galaxy Networks page. + +NetworkManager stays the owner of each saved network; this module only changes Wi-Fi profiles. +Cellular profiles, the modem and its routes are never touched: cellular data is switched with the +same CellularDisabled setting the comma's own screen uses. +""" +from __future__ import annotations + +import json +import re +import subprocess +import threading +import time +from pathlib import Path + +from openpilot.starpilot.galaxy.hotspot import atomic_json, bounded_json + +DEFAULT = {'prefer': 'wifi', 'pauseHotspot': True, '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}') +METERED = {'Auto': 'unknown', 'Metered': 'yes', 'Unmetered': 'no'} +MODEM_STATE = Path('/dev/shm/modem') +MAX_NETWORKS = 64 + + +def split_terse(line: str, count: int) -> list[str]: + """Split one `nmcli -t` line into ``count`` fields; nmcli escapes ':' and '\\' inside values.""" + fields, current, index = [], '', 0 + while index < len(line): + character = line[index] + if character == '\\' and index + 1 < len(line): + current += line[index + 1] + index += 2 + continue + if character == ':' and len(fields) < count - 1: + fields.append(current) + current = '' + else: + current += character + index += 1 + return [*fields, current] + + +def validate_prefs(value) -> dict: + if (type(value) is not dict or set(value) != set(DEFAULT) or value['prefer'] not in ('wifi', 'cellular') or + type(value['pauseHotspot']) is not bool or type(value['parkedOnly']) is not list or len(value['parkedOnly']) > MAX_NETWORKS or + any(type(item) is not str or not UUID.fullmatch(item) for item in value['parkedOnly'])): + raise ValueError('Invalid network preferences') + return {**value, 'parkedOnly': sorted(set(value['parkedOnly']))} + + +def prefs_path(root=None) -> Path: + if root is None: + from openpilot.starpilot.storage import galaxy_storage_root + root = galaxy_storage_root() + return Path(root) / 'network.json' + + +def read_prefs(root=None) -> dict: + try: + return validate_prefs(bounded_json(prefs_path(root))) + except (OSError, ValueError): + return {**DEFAULT, 'parkedOnly': []} + + +class NetworkManagerCli: + def __init__(self, run=subprocess.run): + self.run = run + + def call(self, *args: str) -> str: + try: + result = self.run(['nmcli', *args], capture_output=True, text=True, timeout=10) + except subprocess.SubprocessError as error: + raise OSError('NetworkManager did not answer') from error + if result.returncode != 0: + raise OSError((result.stderr or 'NetworkManager refused the request').strip()[:200]) + return result.stdout + + def saved(self) -> list[dict]: + """Saved Wi-Fi networks the comma joins as a client, best auto-join priority first.""" + rows = {} + for line in self.call('-t', '-f', 'UUID,TYPE,AUTOCONNECT,AUTOCONNECT-PRIORITY,ACTIVE,NAME', 'connection', 'show').splitlines(): + fields = split_terse(line, 6) + if len(fields) != 6: + continue + uuid, kind, autoconnect, priority, active, name = fields + if kind == '802-11-wireless' and UUID.fullmatch(uuid) and name not in OWN_PROFILES: + rows[uuid] = {'uuid': uuid, 'autoJoin': autoconnect == 'yes', 'priority': int(priority) if priority.lstrip('-').isdigit() else 0, + 'connected': active == 'yes'} + if not rows: + return [] + details = self.call('-t', '-f', 'connection.uuid,802-11-wireless.ssid,802-11-wireless.mode,connection.metered,ipv4.route-metric', + 'connection', 'show', *rows) + for block in details.split('\n\n'): + values = dict(pair for pair in (split_terse(line, 2) for line in block.splitlines()) if len(pair) == 2) + row = rows.get(values.get('connection.uuid', '')) + if row is None: + continue + if values.get('802-11-wireless.mode') != 'infrastructure': + del rows[row['uuid']] + continue + metered = values.get('connection.metered', 'unknown') + row.update(name=values.get('802-11-wireless.ssid', '')[:64], metered=next((k for k, v in METERED.items() if v == metered), 'Auto'), + metric=int(values['ipv4.route-metric']) if values.get('ipv4.route-metric', '').lstrip('-').isdigit() else -1) + rows = {uuid: row for uuid, row in rows.items() if 'name' in row} + signal = {} + try: + for line in self.call('-t', '-f', 'SSID,SIGNAL', 'device', 'wifi', 'list', '--rescan', 'no').splitlines(): + ssid, _, strength = line.rpartition(':') + ssid = split_terse(ssid, 1)[0] + if ssid and strength.isdigit(): + signal[ssid] = max(signal.get(ssid, 0), int(strength)) + except OSError: + pass + for row in rows.values(): + row['signal'] = signal.get(row['name']) + return sorted(rows.values(), key=lambda row: (-row['priority'], row['name'].lower()))[:MAX_NETWORKS] + + def modify(self, uuid: str, *settings: str) -> None: + self.call('connection', 'modify', uuid, *settings) + + def reapply(self, interface: str = 'wlan0') -> None: + try: + self.call('device', 'reapply', interface) + except OSError: + pass + + +def apply_preference(root=None, cli: NetworkManagerCli | None = None) -> int: + """Make every saved Wi-Fi network's route cost match the Wi-Fi/cellular preference; returns profiles changed.""" + cli = cli or NetworkManagerCli() + wanted = CELLULAR_FIRST_METRIC if read_prefs(root)['prefer'] == 'cellular' else -1 + changed, live = 0, False + for row in cli.saved(): + if row['metric'] != wanted: + cli.modify(row['uuid'], 'ipv4.route-metric', str(wanted), 'ipv6.route-metric', str(wanted)) + changed += 1 + live = live or row['connected'] + if live: + cli.reapply() + return changed + + +def cellular_status(params) -> dict: + status = {'enabled': not params.get_bool('CellularDisabled'), 'connected': False, 'type': '', 'operator': ''} + try: + modem = json.loads(MODEM_STATE.read_text()) + status.update(connected=modem.get('connected') is True, type=str(modem.get('network_type') or '')[:12], + operator=str(modem.get('operator') or '')[:40]) + except (OSError, ValueError, AttributeError): + pass + return status + + +class NetworkSettings: + def __init__(self, root=None, cli: NetworkManagerCli | None = None, params=None, link=None, clock=time.monotonic): + self.root, self.cli, self.clock = root, cli or NetworkManagerCli(), clock + self._params, self._link = params, link + self.lock = threading.Lock() + self._cache: tuple[float, list[dict]] | None = None + + @property + def params(self): + if self._params is None: + from openpilot.common.params import Params + self._params = Params() + return self._params + + def link(self) -> dict: + if self._link is not None: + return self._link() + from openpilot.starpilot.system import netwatch + status = netwatch.read_status() + return {'link': status.get('link', 'unknown'), 'changedAt': status.get('changedAt', 0.0), 'changes': status.get('changes', 0)} + + def saved(self, fresh: bool = False) -> list[dict]: + if fresh or self._cache is None or self.clock() - self._cache[0] > 3: + self._cache = (self.clock(), self.cli.saved()) + return self._cache[1] + + def snapshot(self, parked: bool, fresh: bool = False) -> dict: + prefs = read_prefs(self.root) + networks = [{key: row[key] for key in ('uuid', 'name', 'autoJoin', 'connected', 'metered', 'signal')} | + {'whileDriving': row['uuid'] not in prefs['parkedOnly']} for row in self.saved(fresh)] + return {'version': 1, 'editable': bool(parked), 'prefer': prefs['prefer'], 'pauseHotspot': prefs['pauseHotspot'], + 'cellular': cellular_status(self.params), 'link': self.link(), 'networks': networks} + + def _save_prefs(self, prefs: dict) -> None: + atomic_json(prefs_path(self.root), validate_prefs(prefs)) + + def apply(self, payload, permitted) -> dict: + if type(payload) is not dict or type(payload.get('action')) is not str: + raise ValueError('Invalid network change') + with self.lock: + if not permitted(): + raise PermissionError('Park and sign in before changing network settings.') + action, prefs = payload['action'], read_prefs(self.root) + known = {row['uuid']: row for row in self.saved(fresh=True)} + if action == 'order' and set(payload) == {'action', 'uuids'}: + order = payload['uuids'] + if type(order) is not list or len(order) != len(known) or set(order) != set(known): + raise FileExistsError('The saved networks changed; refresh and try again.') + for index, uuid in enumerate(order): + priority = len(order) - index + if known[uuid]['priority'] != priority: + self.cli.modify(uuid, 'connection.autoconnect-priority', str(priority)) + elif action == 'network' and set(payload) == {'action', 'uuid', 'setting', 'value'}: + uuid, setting, value = payload['uuid'], payload['setting'], payload['value'] + if uuid not in known: + raise FileExistsError('That network is no longer saved; refresh and try again.') + if setting == 'autoJoin' and type(value) is bool: + self.cli.modify(uuid, 'connection.autoconnect', 'yes' if value else 'no') + elif setting == 'metered' and value in METERED: + self.cli.modify(uuid, 'connection.metered', METERED[value]) + if known[uuid]['connected']: + self.cli.reapply() + elif setting == 'whileDriving' and type(value) is bool: + parked_only = set(prefs['parkedOnly']) & set(known) + parked_only = parked_only - {uuid} if value else parked_only | {uuid} + self._save_prefs({**prefs, 'parkedOnly': sorted(parked_only)}) + else: + raise ValueError('Invalid network setting') + elif action == 'prefer' and set(payload) == {'action', 'value'} and payload['value'] in ('wifi', 'cellular'): + self._save_prefs({**prefs, 'prefer': payload['value']}) + apply_preference(self.root, self.cli) + elif action == 'pauseHotspot' and set(payload) == {'action', 'value'} and type(payload['value']) is bool: + self._save_prefs({**prefs, 'pauseHotspot': payload['value']}) + elif action == 'cellular' and set(payload) == {'action', 'value'} and type(payload['value']) is bool: + self.params.put_bool('CellularDisabled', not payload['value']) + else: + raise ValueError('Invalid network change') + return self.snapshot(permitted(), fresh=True) diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index e3abe64cfd..c9fcd18bf9 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -124,6 +124,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe hotspot_source = HotspotSettings() return hotspot_source + network_source = None + + def network_owner(): + nonlocal network_source + with hotspot_source_lock: + if network_source is None: + from openpilot.starpilot.galaxy.network_prefs import NetworkSettings + network_source = NetworkSettings() + return network_source + def cloud_status(): from openpilot.starpilot.connect.provider import status return cloud.status() if cloud is not None else status() @@ -859,6 +869,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe else: if self.require_session(): self.json(200, result) + elif path == '/api/galaxy/networks': + if not self.require_session(): + return + try: + result = network_owner().snapshot(parked()) + except (OSError, ValueError): + self.json(503, {'error': 'Network settings are unavailable.'}) + else: + if self.require_session(): + self.json(200, result) elif path in ('/api/galaxy/session', '/api/galaxy/session/qr.svg'): record = pairing.read() remote = getattr(self.server, 'remote_transport', False) @@ -1706,7 +1726,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe '/api/settings/reset-default', '/api/settings/restore', '/api/recordings/action', '/api/replay/start', '/api/replay/control', '/api/replay/stop', '/api/replay/export-start', - '/api/galaxy/pair', '/api/galaxy/unpair', '/api/galaxy/device-name', '/api/galaxy/hotspot', + '/api/galaxy/pair', '/api/galaxy/unpair', '/api/galaxy/device-name', '/api/galaxy/hotspot', '/api/galaxy/networks', '/api/cameras/snapshot', '/api/cameras/white-balance', '/api/starport/layout', '/api/starport/enable', '/api/starport/control', '/api/starport/pairing', '/api/starport/logs/send', @@ -1813,6 +1833,25 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe else: self.json(200, result) return + if path == '/api/galaxy/networks': + identity = self.settings_session() + if identity is None: + self.json(401, {'error': 'Sign in to Galaxy'}) + return + try: + with effect_lock: + result = network_owner().apply(payload, lambda: self.settings_session() == identity and parked()) + except PermissionError: + self.json(409, {'error': 'Park before changing network settings.'}) + except FileExistsError as error: + self.json(409, {'error': str(error)}) + except ValueError as error: + self.json(400, {'error': str(error)}) + except OSError: + self.json(503, {'error': 'Network settings are unavailable.'}) + else: + self.json(200, result) + return if path == '/api/galaxy/hotspot': identity = self.settings_session() if identity is None: diff --git a/openpilot/starpilot/galaxy/tests/test_home_polish.mjs b/openpilot/starpilot/galaxy/tests/test_home_polish.mjs index 3a1ef5a524..61d020c91d 100644 --- a/openpilot/starpilot/galaxy/tests/test_home_polish.mjs +++ b/openpilot/starpilot/galaxy/tests/test_home_polish.mjs @@ -18,6 +18,8 @@ assert.ok(GalaxyPage.template.indexOf('Get the app')) assert.ok(GalaxyPage.template.includes('')) +assert.ok(GalaxyPage.template.includes('href="#/networks"')) +assert.ok(GalaxyPage.template.indexOf(' ({ uuid, name, autoJoin: true, whileDriving: true, connected: false, metered: 'Auto', signal: null, ...extra }) +const first = '11111111-1111-4111-8111-111111111111', second = '22222222-2222-4222-8222-222222222222' +const value = { version: 1, editable: true, prefer: 'wifi', pauseHotspot: true, cellular: { enabled: true, connected: true, type: 'lte', operator: 'Carrier' }, + link: { link: 'wifi', changedAt: 0, changes: 0 }, networks: [network(first, 'Home', { connected: true }), network(second, 'Phone', { signal: 60 })] } +assert.equal(validNetworks(value), true) +assert.equal(validNetworks({ ...value, prefer: 'both' }), false) +assert.equal(validNetworks({ ...value, networks: [{ ...value.networks[0], metered: 'Sometimes' }] }), false) +compile(NetworksPage.template, { decodeEntities: text => text }) +assert.ok(NetworksPage.template.includes(' { sent.push(options?.body ? JSON.parse(options.body) : null); return { ok: true, json: async () => value } } +await vm.move(1, -1) +assert.deepEqual(sent.at(-1), { action: 'order', uuids: [second, first] }) +assert.equal(vm.move(0, -1), undefined) +await vm.setNetwork(value.networks[1], 'whileDriving', false) +assert.deepEqual(sent.at(-1), { action: 'network', uuid: second, setting: 'whileDriving', value: false }) +vm.adopt({ ...value, editable: false }) +const before = sent.length +assert.equal(await vm.send({ action: 'cellular', value: false }), false) +assert.equal(sent.length, before) +vm.stop() diff --git a/openpilot/starpilot/galaxy/tests/test_preview_contract.py b/openpilot/starpilot/galaxy/tests/test_preview_contract.py index 8c320fff91..eb36bd1fb9 100644 --- a/openpilot/starpilot/galaxy/tests/test_preview_contract.py +++ b/openpilot/starpilot/galaxy/tests/test_preview_contract.py @@ -18,7 +18,7 @@ class PreviewContractTest(unittest.TestCase): self.assertTrue(all(path.startswith("/") and path != "/tools" for path in paths)) self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "partial-preview"], ["/logs"]) self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "local-only"], - ["/bluetooth", "/cameras", "/galaxy", "/manage_models", "/navigation", "/system", + ["/bluetooth", "/cameras", "/galaxy", "/manage_models", "/navigation", "/networks", "/system", "/theme_maker", "/tuning", "/starport"]) self.assertEqual([tool["path"] for tool in catalog["tools"] if tool["availability"] == "always"], []) self.assertTrue(all(tool["availability"] in {"always", "unavailable", "partial-preview", "local-only"} for tool in catalog["tools"])) diff --git a/openpilot/starpilot/galaxy/web/data/catalog.json b/openpilot/starpilot/galaxy/web/data/catalog.json index 42c62eaad1..d5a8d0226b 100644 --- a/openpilot/starpilot/galaxy/web/data/catalog.json +++ b/openpilot/starpilot/galaxy/web/data/catalog.json @@ -141,6 +141,13 @@ } ] }, + { + "name": "Networks", + "path": "/networks", + "icon": "bi-wifi", + "description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot", + "availability": "local-only" + }, { "name": "System Tools", "path": "/system", diff --git a/openpilot/starpilot/galaxy/web/js/app.js b/openpilot/starpilot/galaxy/web/js/app.js index 7daf91e795..cf820278ad 100644 --- a/openpilot/starpilot/galaxy/web/js/app.js +++ b/openpilot/starpilot/galaxy/web/js/app.js @@ -42,6 +42,7 @@ const StarPortPage = page(() => import("./starport.js").then((module) => module. const SpotifyPage = page(() => import("./spotify.js").then((module) => module.SpotifyPage)) const OnroadLayoutPage = page(() => import("./onroad-layout.js").then((module) => module.OnroadLayoutPage)) const GalaxyPage = page(() => import("./galaxy.js").then((module) => module.GalaxyPage)) +const NetworksPage = page(() => import("./networks.js").then((module) => module.NetworksPage)) import { DevicePicker } from "./device-picker.js" import { DeviceState } from "./device-state.js" import { spawnAmbientStars, pauseStarsOnSlowFirefoxScroll } from "./ambient-stars.js" @@ -90,7 +91,7 @@ const auth = new LocalAuth({ publish: (update) => { createApp({ - components: { AppDownloadReminder, BottomNav, Home, LocalAccess, Tools, Logs, SoftwarePage, NavigationPage, ModelsPage, SettingsPage, SettingsRecoveryPage, ToggleSearch, SaveFeedback, FlmPage, LocalRecordingsPage, CamerasPage, SentryEventsPage, VasmPage, PipPage, DrivingPage, DevicePreferencesPage, BluetoothPage, StarPortPage, SpotifyPage, LongitudinalCurvesPage, OnroadLayoutPage, GalaxyPage, DevicePicker, DeviceState, MenuTile }, + components: { AppDownloadReminder, BottomNav, Home, LocalAccess, Tools, Logs, SoftwarePage, NavigationPage, ModelsPage, SettingsPage, SettingsRecoveryPage, ToggleSearch, SaveFeedback, FlmPage, LocalRecordingsPage, CamerasPage, SentryEventsPage, VasmPage, PipPage, DrivingPage, DevicePreferencesPage, BluetoothPage, StarPortPage, SpotifyPage, LongitudinalCurvesPage, OnroadLayoutPage, GalaxyPage, NetworksPage, DevicePicker, DeviceState, MenuTile }, data: () => ({ state, authState, authForm, route, NAV, routeDirection: 1, updateRestart, deviceRestart, nextLayoutLeavePresentation: "inline" }), computed: { visibleTools() { return state.tools.filter(tool => tool.visibility !== "authenticated" || @@ -249,6 +250,7 @@ createApp({ + diff --git a/openpilot/starpilot/galaxy/web/js/galaxy.js b/openpilot/starpilot/galaxy/web/js/galaxy.js index 3ee89d900d..b39ce2d11e 100644 --- a/openpilot/starpilot/galaxy/web/js/galaxy.js +++ b/openpilot/starpilot/galaxy/web/js/galaxy.js @@ -2,11 +2,10 @@ import { AppStoreLinks } from './app-downloads.js' import { InstallApp } from './install-app.js' import { RemoteAccess } from './remote-access.js' import { CompanionUpdates } from './companion-updates.js' -import { GalaxyHotspot } from './hotspot.js' export const GalaxyPage = { name: 'GalaxyPage', - components: { AppStoreLinks, InstallApp, RemoteAccess, CompanionUpdates, GalaxyHotspot }, + components: { AppStoreLinks, InstallApp, RemoteAccess, CompanionUpdates }, props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } }, data: () => ({ url: '' }), template: `
@@ -24,6 +23,8 @@ export const GalaxyPage = {
- +
Galaxy Wi-Fi Hotspot
+

The hotspot, preferred Wi-Fi networks and cellular data are on the Networks page.

+
`, } diff --git a/openpilot/starpilot/galaxy/web/js/networks.js b/openpilot/starpilot/galaxy/web/js/networks.js new file mode 100644 index 0000000000..9c46ec0c31 --- /dev/null +++ b/openpilot/starpilot/galaxy/web/js/networks.js @@ -0,0 +1,133 @@ +import { requestJson } from "./startup.js" +import { GxNotice } from "./notice.js" +import { GxState } from "./state.js" +import { GalaxySettingRow, switchRow } from "./galaxy-setting-row.js" +import { GalaxyHotspot } from "./hotspot.js" + +const METERED = ['Auto', 'Metered', 'Unmetered'] +const LINKS = { wifi: 'Wi-Fi', cellular: 'Cellular', none: 'Offline', other: 'Other', unknown: 'Unknown' } + +export function validNetworks(value) { + return value?.version === 1 && typeof value.editable === 'boolean' && ['wifi', 'cellular'].includes(value.prefer) && + typeof value.pauseHotspot === 'boolean' && typeof value.cellular?.enabled === 'boolean' && + typeof value.link?.link === 'string' && Array.isArray(value.networks) && value.networks.every(network => + /^[0-9a-f-]{36}$/.test(network.uuid) && typeof network.name === 'string' && typeof network.autoJoin === 'boolean' && + typeof network.whileDriving === 'boolean' && typeof network.connected === 'boolean' && METERED.includes(network.metered)) +} + +export const choiceRow = (label, value, choices, reason = '') => ({ label, value, reason, choices, available: true, action: true }) + +export const NetworksPage = { + name: "NetworksPage", + components: { GxNotice, GxState, GalaxySettingRow, GalaxyHotspot }, + props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } }, + data: () => ({ snapshot: null, busy: false, error: '', timer: null, controller: null, generation: 0, active: false }), + computed: { + linkName() { return LINKS[this.snapshot?.link.link] || 'Unknown' }, + changed() { + const at = this.snapshot?.link.changedAt + return at ? new Date(at * 1000).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : '' + }, + cellularDetail() { + const cellular = this.snapshot.cellular + if (!cellular.enabled) return 'Cellular data is off. The comma only goes online over Wi-Fi.' + return cellular.connected ? `Connected${cellular.operator ? ' to ' + cellular.operator : ''}${cellular.type ? ' (' + cellular.type.toUpperCase() + ')' : ''}.` : 'Not connected right now.' + }, + }, + mounted() { this.start() }, + beforeUnmount() { this.stop() }, + watch: { mode() { this.stop(); this.start() } }, + methods: { + switchRow, choiceRow, + start() { if (this.mode === 'local') { this.active = true; this.refresh() } }, + stop() { this.active = false; this.generation++; clearTimeout(this.timer); this.controller?.abort(); this.snapshot = null; this.busy = false }, + adopt(value) { + if (!validNetworks(value)) throw new Error('Invalid network status') + this.snapshot = value + }, + async refresh() { + if (!this.active || this.busy) return + clearTimeout(this.timer); this.controller?.abort() + const generation = ++this.generation + this.controller = new AbortController() + try { + const value = await requestJson('./api/galaxy/networks', { request: { signal: this.controller.signal } }) + if (!this.active || generation !== this.generation) return + this.adopt(value); this.error = '' + } catch (error) { + if (!this.active || generation !== this.generation) return + if (error.status === 401) { this.stop(); this.unauthorized(); return } + this.error = error.message + } finally { + if (this.active && generation === this.generation) this.timer = setTimeout(() => this.refresh(), 5000) + } + }, + async send(body) { + if (!this.active || this.busy || !this.snapshot?.editable) return false + clearTimeout(this.timer); this.controller?.abort() + const generation = ++this.generation + this.controller = new AbortController(); this.busy = true; this.error = '' + try { + const value = await requestJson('./api/galaxy/networks', { request: { signal: this.controller.signal, + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } }) + if (!this.active || generation !== this.generation) return false + this.adopt(value) + return true + } catch (error) { + if (!this.active || generation !== this.generation) return false + if (error.status === 401) { this.stop(); this.unauthorized(); return false } + this.error = error.message + return false + } finally { + if (this.active && generation === this.generation) { this.busy = false; this.timer = setTimeout(() => this.refresh(), 2000) } + } + }, + move(index, step) { + const uuids = this.snapshot.networks.map(network => network.uuid), target = index + step + if (target < 0 || target >= uuids.length) return + uuids.splice(target, 0, ...uuids.splice(index, 1)) + return this.send({ action: 'order', uuids }) + }, + setNetwork(network, setting, value) { return this.send({ action: 'network', uuid: network.uuid, setting, value }) }, + signalText(network) { + if (network.connected) return 'Connected' + return network.signal == null ? 'Not in range' : `In range, signal ${network.signal}%` + }, + }, + template: `
+ Connect to your comma to manage its networks. + Loading network settings… + + {{ error }} + +
`, +} diff --git a/openpilot/starpilot/system/netwatch.py b/openpilot/starpilot/system/netwatch.py index 791870cdb0..32c0da3895 100644 --- a/openpilot/starpilot/system/netwatch.py +++ b/openpilot/starpilot/system/netwatch.py @@ -220,11 +220,19 @@ def main() -> None: signal.signal(signal.SIGINT, lambda *_: stop.set()) watcher = Watcher() watcher.start() + reconcile_at = 0.0 while not stop.is_set(): now = time.monotonic() for name, count in watcher.tick(now): cloudlog.event('netwatch_changed', link=name, closed=count, up=watcher.links[name].stable is not None) publish(watcher.status()) + if now >= reconcile_at: + reconcile_at = now + 300 + try: + from openpilot.starpilot.galaxy import network_prefs + network_prefs.apply_preference() # newly saved networks pick up the Wi-Fi/cellular preference + except Exception: + cloudlog.exception('netwatch_preference_failed') stop.wait(1.0) From f7dc16211aa376f45c3f3a910c86b326433214bf Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 12:10:05 -0800 Subject: [PATCH 06/14] Galaxy: Let the hotspot stand down briefly while the comma joins Wi-Fi --- openpilot/starpilot/galaxy/hotspot.py | 22 +++++++++++++++++++ openpilot/starpilot/galaxy/hotspot_daemon.py | 9 ++++++-- .../starpilot/galaxy/tests/test_hotspot.py | 18 +++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/openpilot/starpilot/galaxy/hotspot.py b/openpilot/starpilot/galaxy/hotspot.py index 6b7082dd5a..ac4297435e 100644 --- a/openpilot/starpilot/galaxy/hotspot.py +++ b/openpilot/starpilot/galaxy/hotspot.py @@ -16,6 +16,8 @@ ADDRESS = '172.31.254.1' NETWORK = '172.31.254.0/24' STATUS_PATH = Path('/tmp/starpilot-galaxy-hotspot-status.json') DEFAULT = {'enabled': False, 'ssid': 'Galaxy', 'password': ''} +PAUSE_PATH = Path('/tmp/starpilot-galaxy-hotspot-pause.json') +MAX_PAUSE_S = 120.0 def device_dongle_id(): @@ -38,6 +40,26 @@ def validate_config(value): return dict(value) +def request_pause(seconds, path=PAUSE_PATH, clock=time.monotonic): + """Ask the hotspot to stand down briefly, for example while the comma joins a Wi-Fi network during a drive.""" + atomic_json(path, {'until': clock() + min(float(seconds), MAX_PAUSE_S)}, mode=0o644) + + +def clear_pause(path=PAUSE_PATH): + try: + path.unlink() + except FileNotFoundError: + pass + + +def paused(path=PAUSE_PATH, clock=time.monotonic): + try: + until = bounded_json(path)['until'] + return type(until) in (int, float) and 0 < until - clock() <= MAX_PAUSE_S + except (OSError, ValueError, KeyError, TypeError): + return False + + def atomic_json(path, value, mode=0o600): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent) diff --git a/openpilot/starpilot/galaxy/hotspot_daemon.py b/openpilot/starpilot/galaxy/hotspot_daemon.py index fa179a2ed4..62a737fb0d 100644 --- a/openpilot/starpilot/galaxy/hotspot_daemon.py +++ b/openpilot/starpilot/galaxy/hotspot_daemon.py @@ -7,7 +7,7 @@ import subprocess import threading import time -from openpilot.starpilot.galaxy.hotspot import HotspotSettings, STATUS_PATH, atomic_json +from openpilot.starpilot.galaxy.hotspot import HotspotSettings, STATUS_PATH, atomic_json, paused from openpilot.starpilot.system.pipe_worker import spawn @@ -41,7 +41,8 @@ def main(): runtime = {'active': False, 'state': 'starting', 'reason': 'Starting hotspot service.'} if child.poll() is not None: raise RuntimeError('Worker exited') - child.stdin.write(json.dumps(config).encode() + b'\n') + standing_down = paused() + child.stdin.write(json.dumps({**config, 'enabled': not standing_down}).encode() + b'\n') child.stdin.flush() stdout = child.stdout if stdout is None: @@ -57,6 +58,10 @@ def main(): line, buffer = buffer.split(b'\n', 1) runtime = json.loads(line) last_reply = time.monotonic() + if standing_down: + runtime = {'active': False, 'state': 'waiting', 'reason': 'Paused while the comma joins Wi-Fi.', 'revision': revision} + elif runtime.get('state') == 'disabled': + runtime = {'active': False, 'state': 'starting', 'reason': 'Starting hotspot service.', 'revision': revision} if time.monotonic() - last_reply > 20: raise RuntimeError('Worker unresponsive') atomic_json(STATUS_PATH, {**runtime, 'revision': runtime.get('revision', revision), 'updated': time.monotonic()}) diff --git a/openpilot/starpilot/galaxy/tests/test_hotspot.py b/openpilot/starpilot/galaxy/tests/test_hotspot.py index 4b1f975528..a7e99b320b 100644 --- a/openpilot/starpilot/galaxy/tests/test_hotspot.py +++ b/openpilot/starpilot/galaxy/tests/test_hotspot.py @@ -456,3 +456,21 @@ def test_netlink_new_interface_payloads(): wireless.create('aa0', iftype=2) station = attribute(1, struct.pack('I', 0)) + attribute(4, b'aa0\0') + attribute(5, struct.pack('I', 2)) wireless.query.assert_called_with(22, 7, station, ack=True) + + +def test_a_pause_request_expires_on_its_own_and_a_bad_file_never_pauses(tmp_path): + from openpilot.starpilot.galaxy import hotspot + path, now = tmp_path / 'pause.json', [100.0] + assert not hotspot.paused(path, lambda: now[0]) + hotspot.request_pause(30, path, lambda: now[0]) + assert hotspot.paused(path, lambda: now[0]) + now[0] += 31 + assert not hotspot.paused(path, lambda: now[0]) + hotspot.request_pause(10_000, path, lambda: now[0]) + now[0] += hotspot.MAX_PAUSE_S + 1 + assert not hotspot.paused(path, lambda: now[0]) + path.write_text('{"until": 1e18}') + assert not hotspot.paused(path, lambda: now[0]) # a stale or forged file cannot hold the hotspot down + hotspot.clear_pause(path) + hotspot.clear_pause(path) + assert not path.exists() From e0434a8ac5a1cfc66770f39d9fae1bf7cff8a3f0 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 12:10:05 -0800 Subject: [PATCH 07/14] StarPort: Join Wi-Fi under its own control during a drive --- .../system/starport/car_interface.py | 92 +++++++++++++++++-- .../starpilot/system/starport/network.py | 69 +++++++++++++- .../starpilot/system/starport/supervisor.py | 2 + .../starport/tests/test_car_interface.py | 69 ++++++++++++++ .../system/starport/tests/test_starport.py | 29 ++++++ 5 files changed, 254 insertions(+), 7 deletions(-) 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 == [] From d0857e4018447d064b3cb465bd963f2e09101216 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 12:37:38 -0800 Subject: [PATCH 08/14] Networks: Tidy Page --- .../starpilot/galaxy/tests/test_networks.mjs | 6 ++ .../starpilot/galaxy/web/css/settings.css | 13 ++++ openpilot/starpilot/galaxy/web/js/hotspot.js | 54 +++++++++------- openpilot/starpilot/galaxy/web/js/networks.js | 63 ++++++++++++------- 4 files changed, 89 insertions(+), 47 deletions(-) diff --git a/openpilot/starpilot/galaxy/tests/test_networks.mjs b/openpilot/starpilot/galaxy/tests/test_networks.mjs index 2c8788ff2d..9a924af03d 100644 --- a/openpilot/starpilot/galaxy/tests/test_networks.mjs +++ b/openpilot/starpilot/galaxy/tests/test_networks.mjs @@ -22,6 +22,12 @@ vm.active = true vm.adopt(value) assert.equal(vm.signalText(value.networks[0]), 'Connected') assert.equal(vm.signalText(value.networks[1]), 'In range, signal 60%') +assert.equal(vm.networkSummary(value.networks[0]), 'Connected · Auto-join') +assert.equal(vm.isOpen(value.networks[0]), false) +vm.toggleNetwork(first) +assert.equal(vm.isOpen(value.networks[0]), true) +vm.toggleNetwork(first) +assert.equal(vm.isOpen(value.networks[0]), false) const sent = [] globalThis.fetch = async (_url, options) => { sent.push(options?.body ? JSON.parse(options.body) : null); return { ok: true, json: async () => value } } await vm.move(1, -1) diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css index a8511f2c5a..3b98c71a18 100644 --- a/openpilot/starpilot/galaxy/web/css/settings.css +++ b/openpilot/starpilot/galaxy/web/css/settings.css @@ -911,3 +911,16 @@ html.gx-maker-open, html.gx-maker-open body { touch-action: manipulation; } .gx-sentry-status .gx-status-dot { flex: none; background: currentColor; } .gx-sentry-status--armed .gx-status-dot { background: var(--success); } .gx-sentry-status--warning .gx-status-dot { background: var(--warning); } +.gx-networks > .gx-card { margin-bottom: 0; } +.gx-networks__caption { margin: 0; padding: var(--sp-2) var(--sp-4) var(--sp-3); border-top: 1px solid var(--outline); } +.gx-networks__toggle { border: 0; padding: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } +.gx-networks__toggle:focus-visible { outline: 2px solid var(--primary); outline-offset: 4px; border-radius: var(--radius-sm); } +.gx-networks__details { background: rgba(255, 255, 255, 0.015); box-shadow: inset 3px 0 var(--primary); } +.gx-networks__details > .gx-row { padding-left: calc(var(--sp-4) + var(--sp-2)); } +.gx-hotspot__controls { flex: 1 1 260px; justify-content: flex-end; } +.gx-hotspot__field { flex: 1 1 160px; max-width: 240px; } +.gx-hotspot__details { padding: var(--sp-3) var(--sp-4); } +@media (max-width: 600px) { + .gx-hotspot__field { max-width: none; } + .gx-hotspot__controls { justify-content: stretch; } +} diff --git a/openpilot/starpilot/galaxy/web/js/hotspot.js b/openpilot/starpilot/galaxy/web/js/hotspot.js index de6523152c..c4eed55c19 100644 --- a/openpilot/starpilot/galaxy/web/js/hotspot.js +++ b/openpilot/starpilot/galaxy/web/js/hotspot.js @@ -83,34 +83,42 @@ export const GalaxyHotspot = { } }, }, - template: `
Galaxy Wi-Fi Hotspot
-

Local Galaxy access for iPhone and Android. No Android Auto, Bluetooth browser support, or cellular connection needed.

+ template: `
Galaxy Wi-Fi Hotspot{{ snapshot.config.ssid }}
Connect to your comma to configure the hotspot. Loading hotspot settings… -
    -
  • Starts automatically when enabled. Needs the comma on and Wi-Fi available.
  • -
  • Works standalone, or shares the channel of connected Wi-Fi or Android Auto.
  • -
  • Local access without Internet; no Internet sharing.
  • -
  • Network or channel changes may interrupt access. Changing the password or disabling the hotspot disconnects phones.
  • -
  • The public galaxy.firestar.link address still needs Internet and its tunnel.
  • -
- {{ saveError || error }}{{ notice }} + {{ saveError || error }}{{ notice }}
`, } diff --git a/openpilot/starpilot/galaxy/web/js/networks.js b/openpilot/starpilot/galaxy/web/js/networks.js index 9c46ec0c31..f69f32274e 100644 --- a/openpilot/starpilot/galaxy/web/js/networks.js +++ b/openpilot/starpilot/galaxy/web/js/networks.js @@ -21,7 +21,7 @@ export const NetworksPage = { name: "NetworksPage", components: { GxNotice, GxState, GalaxySettingRow, GalaxyHotspot }, props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } }, - data: () => ({ snapshot: null, busy: false, error: '', timer: null, controller: null, generation: 0, active: false }), + data: () => ({ snapshot: null, busy: false, error: '', openUuid: null, timer: null, controller: null, generation: 0, active: false }), computed: { linkName() { return LINKS[this.snapshot?.link.link] || 'Unknown' }, changed() { @@ -30,7 +30,7 @@ export const NetworksPage = { }, cellularDetail() { const cellular = this.snapshot.cellular - if (!cellular.enabled) return 'Cellular data is off. The comma only goes online over Wi-Fi.' + if (!cellular.enabled) return 'Off · comma goes online over Wi-Fi only.' return cellular.connected ? `Connected${cellular.operator ? ' to ' + cellular.operator : ''}${cellular.type ? ' (' + cellular.type.toUpperCase() + ')' : ''}.` : 'Not connected right now.' }, }, @@ -40,10 +40,18 @@ export const NetworksPage = { methods: { switchRow, choiceRow, start() { if (this.mode === 'local') { this.active = true; this.refresh() } }, - stop() { this.active = false; this.generation++; clearTimeout(this.timer); this.controller?.abort(); this.snapshot = null; this.busy = false }, + stop() { this.active = false; this.generation++; clearTimeout(this.timer); this.controller?.abort(); this.snapshot = null; this.openUuid = null; this.busy = false }, adopt(value) { if (!validNetworks(value)) throw new Error('Invalid network status') this.snapshot = value + if (this.openUuid && !value.networks.some(n => n.uuid === this.openUuid)) this.openUuid = null + }, + isOpen(network) { return this.openUuid === network.uuid || this.snapshot?.networks.length === 1 }, + toggleNetwork(uuid) { this.openUuid = this.openUuid === uuid ? null : uuid }, + networkSummary(network) { + const parts = [this.signalText(network), network.autoJoin ? (network.whileDriving ? 'Auto-join' : 'Parked only') : 'Manual'] + if (network.metered !== 'Auto') parts.push(network.metered) + return parts.join(' · ') }, async refresh() { if (!this.active || this.busy) return @@ -94,40 +102,47 @@ export const NetworksPage = { return network.signal == null ? 'Not in range' : `In range, signal ${network.signal}%` }, }, - template: `
+ template: `
+

Networks

Wi-Fi priority, cellular data, and local hotspot access.

Connect to your comma to manage its networks. Loading network settings… {{ error }} - -
`, + +
`, } From 3d0a89c33f165e4017f13a91929440add491ef99 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 16:15:17 -0800 Subject: [PATCH 09/14] Networks: Scan, join, connect and forget Wi-Fi from Galaxy --- openpilot/starpilot/galaxy/network_prefs.py | 196 ++++++++++++++++-- openpilot/starpilot/galaxy/server.py | 4 +- .../galaxy/tests/test_network_prefs.py | 113 ++++++++++ .../starpilot/galaxy/tests/test_networks.mjs | 25 +++ .../starpilot/galaxy/web/css/settings.css | 11 +- openpilot/starpilot/galaxy/web/js/networks.js | 136 +++++++++++- 6 files changed, 459 insertions(+), 26 deletions(-) diff --git a/openpilot/starpilot/galaxy/network_prefs.py b/openpilot/starpilot/galaxy/network_prefs.py index 98d53c00ca..db8961cf00 100644 --- a/openpilot/starpilot/galaxy/network_prefs.py +++ b/openpilot/starpilot/galaxy/network_prefs.py @@ -6,6 +6,8 @@ same CellularDisabled setting the comma's own screen uses. """ from __future__ import annotations +from functools import partial +from ipaddress import ip_address, ip_network import json import re import subprocess @@ -13,6 +15,7 @@ import threading import time from pathlib import Path +from openpilot.starpilot.galaxy import hotspot from openpilot.starpilot.galaxy.hotspot import atomic_json, bounded_json DEFAULT = {'prefer': 'wifi', 'pauseHotspot': True, 'parkedOnly': []} @@ -22,6 +25,11 @@ UUID = re.compile(r'[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}') METERED = {'Auto': 'unknown', 'Metered': 'yes', 'Unmetered': 'no'} MODEM_STATE = Path('/dev/shm/modem') MAX_NETWORKS = 64 +JOIN_WAIT_S = 15 +HOTSPOT_PAUSE_WAIT_S = 10.0 +JOIN_START_DELAY_S = 1.0 +JOIN_RUNNING_MAX_S = 90.0 +JOIN_RESULT_TTL_S = 600.0 def split_terse(line: str, count: int) -> list[str]: @@ -64,19 +72,66 @@ def read_prefs(root=None) -> dict: return {**DEFAULT, 'parkedOnly': []} +def valid_ssid(value) -> bool: + return type(value) is str and 1 <= len(value.strip()) <= 64 and value not in OWN_PROFILES and not any(ord(c) < 32 or ord(c) == 127 for c in value) + + +def valid_password(value) -> bool: + return type(value) is str and (value == '' or (8 <= len(value) <= 64 and not any(ord(c) < 32 or ord(c) == 127 for c in value))) + + +def parse_wifi_list(text: str) -> tuple[dict[str, int], list[dict]]: + signal: dict[str, int] = {} + nearby: dict[str, dict] = {} + for line in text.splitlines(): + fields = split_terse(line, 64) + if len(fields) < 2: + continue + ssid, strength = fields[0][:64], fields[1] + sec_raw = fields[2] if len(fields) > 2 else '' + if not ssid or not strength.isdigit(): + continue + level = int(strength) + signal[ssid] = max(signal.get(ssid, 0), level) + if ssid in OWN_PROFILES or ssid.startswith(('TheGalaxy-', 'weedle-')): + continue + security = 'open' if sec_raw in ('', '--') else 'unsupported' if ('802.1X' in sec_raw or 'EAP' in sec_raw) else 'wpa' + prior = nearby.get(ssid) + if prior is None or level > prior['signal']: + nearby[ssid] = {'ssid': ssid, 'signal': level, 'security': security if prior is None or prior['security'] == 'open' else prior['security']} + return signal, sorted(nearby.values(), key=lambda row: (-row['signal'], row['ssid'].lower()))[:MAX_NETWORKS] + + +def via_hotspot(address) -> bool: + try: + return ip_address(address) in ip_network(hotspot.NETWORK) + except ValueError: + return False + + +def start_thread(work) -> None: + threading.Thread(target=work, name='galaxy-wifi-join', daemon=True).start() + + class NetworkManagerCli: def __init__(self, run=subprocess.run): self.run = run + self.last_available: list[dict] = [] - def call(self, *args: str) -> str: + def call(self, *args: str, timeout: float = 10) -> str: try: - result = self.run(['nmcli', *args], capture_output=True, text=True, timeout=10) + result = self.run(['nmcli', *args], capture_output=True, text=True, timeout=timeout) except subprocess.SubprocessError as error: raise OSError('NetworkManager did not answer') from error if result.returncode != 0: raise OSError((result.stderr or 'NetworkManager refused the request').strip()[:200]) return result.stdout + def scan(self, rescan: bool = False) -> tuple[dict[str, int], list[dict]]: + signal, nearby = parse_wifi_list(self.call('-t', '-f', 'SSID,SIGNAL,SECURITY', 'device', 'wifi', 'list', '--rescan', 'yes' if rescan else 'no', timeout=20)) + self.last_available = nearby + return signal, nearby + def saved(self) -> list[dict]: """Saved Wi-Fi networks the comma joins as a client, best auto-join priority first.""" rows = {} @@ -89,6 +144,10 @@ class NetworkManagerCli: rows[uuid] = {'uuid': uuid, 'autoJoin': autoconnect == 'yes', 'priority': int(priority) if priority.lstrip('-').isdigit() else 0, 'connected': active == 'yes'} if not rows: + try: + self.scan(rescan=False) + except OSError: + pass return [] details = self.call('-t', '-f', 'connection.uuid,802-11-wireless.ssid,802-11-wireless.mode,connection.metered,ipv4.route-metric', 'connection', 'show', *rows) @@ -106,11 +165,7 @@ class NetworkManagerCli: rows = {uuid: row for uuid, row in rows.items() if 'name' in row} signal = {} try: - for line in self.call('-t', '-f', 'SSID,SIGNAL', 'device', 'wifi', 'list', '--rescan', 'no').splitlines(): - ssid, _, strength = line.rpartition(':') - ssid = split_terse(ssid, 1)[0] - if ssid and strength.isdigit(): - signal[ssid] = max(signal.get(ssid, 0), int(strength)) + signal, _ = self.scan(rescan=False) except OSError: pass for row in rows.values(): @@ -120,6 +175,20 @@ class NetworkManagerCli: def modify(self, uuid: str, *settings: str) -> None: self.call('connection', 'modify', uuid, *settings) + def join(self, ssid: str, password: str = '', hidden: bool = False) -> None: + args = ['--wait', str(JOIN_WAIT_S), 'device', 'wifi', 'connect', ssid, 'ifname', 'wlan0'] + if password: + args += ['password', password] + if hidden: + args += ['hidden', 'yes'] + self.call(*args, timeout=JOIN_WAIT_S + 5) + + def activate(self, uuid: str) -> None: + self.call('--wait', str(JOIN_WAIT_S), 'connection', 'up', 'uuid', uuid, 'ifname', 'wlan0', timeout=JOIN_WAIT_S + 5) + + def delete(self, uuid: str) -> None: + self.call('connection', 'delete', 'uuid', uuid) + def reapply(self, interface: str = 'wlan0') -> None: try: self.call('device', 'reapply', interface) @@ -154,8 +223,11 @@ def cellular_status(params) -> dict: class NetworkSettings: - def __init__(self, root=None, cli: NetworkManagerCli | None = None, params=None, link=None, clock=time.monotonic): + def __init__(self, root=None, cli: NetworkManagerCli | None = None, params=None, link=None, clock=time.monotonic, + hotspot_iface: Path = Path('/sys/class/net') / hotspot.INTERFACE, sleep=time.sleep, spawn=start_thread): self.root, self.cli, self.clock = root, cli or NetworkManagerCli(), clock + self.hotspot_iface, self.sleep, self.spawn = hotspot_iface, sleep, spawn + self._join_state: dict | None = None self._params, self._link = params, link self.lock = threading.Lock() self._cache: tuple[float, list[dict]] | None = None @@ -181,23 +253,123 @@ class NetworkSettings: def snapshot(self, parked: bool, fresh: bool = False) -> dict: prefs = read_prefs(self.root) + saved_rows = self.saved(fresh) + saved_names = {row['name'] for row in saved_rows} networks = [{key: row[key] for key in ('uuid', 'name', 'autoJoin', 'connected', 'metered', 'signal')} | - {'whileDriving': row['uuid'] not in prefs['parkedOnly']} for row in self.saved(fresh)] + {'whileDriving': row['uuid'] not in prefs['parkedOnly']} for row in saved_rows] + available = [row for row in getattr(self.cli, 'last_available', ()) if row['ssid'] not in saved_names] return {'version': 1, 'editable': bool(parked), 'prefer': prefs['prefer'], 'pauseHotspot': prefs['pauseHotspot'], - 'cellular': cellular_status(self.params), 'link': self.link(), 'networks': networks} + 'cellular': cellular_status(self.params), 'link': self.link(), 'networks': networks, 'available': available, + 'lastJoin': self._last_join()} + + def _last_join(self) -> dict | None: + state = self._join_state + if state is None or self.clock() - state['at'] > JOIN_RESULT_TTL_S: + return None + return {key: state[key] for key in ('ssid', 'state', 'error')} + + def _joining(self) -> bool: + state = self._join_state + return state is not None and state['state'] == 'joining' and self.clock() - state['at'] < JOIN_RUNNING_MAX_S + + def _join_later(self, name: str, effect, parked: bool) -> dict: + self._join_state = {'ssid': name, 'state': 'joining', 'error': '', 'at': self.clock()} + + def work(): + self.sleep(JOIN_START_DELAY_S) + result = {'state': 'joined', 'error': ''} + try: + self._with_hotspot_paused(effect) + except Exception as error: # the hotspot client is offline; keep the reason for when it reconnects + result = {'state': 'failed', 'error': str(error)[:200] or 'Could not join that network.'} + self._cache = None + self._join_state = {'ssid': name, **result, 'at': self.clock()} + + self.spawn(work) + return self.snapshot(parked) + + def _pause_hotspot(self) -> bool: + """Stand the Galaxy hotspot down before the radio joins Wi-Fi; returns whether it was paused.""" + if not self.hotspot_iface.exists(): + return False + hotspot.request_pause(HOTSPOT_PAUSE_WAIT_S + JOIN_WAIT_S + 15) + deadline = self.clock() + HOTSPOT_PAUSE_WAIT_S + while self.hotspot_iface.exists(): + if self.clock() >= deadline: + hotspot.clear_pause() + raise ValueError('The Galaxy hotspot did not pause; try again in a moment.') + self.sleep(0.2) + return True + + def _with_hotspot_paused(self, effect) -> None: + paused = self._pause_hotspot() + try: + effect() + finally: + if paused: + hotspot.clear_pause() def _save_prefs(self, prefs: dict) -> None: atomic_json(prefs_path(self.root), validate_prefs(prefs)) - def apply(self, payload, permitted) -> dict: + def _join(self, known: dict, ssid: str, password: str, hidden: bool) -> None: + try: + self.cli.join(ssid, password, hidden) + except OSError as error: + for row in self.cli.saved(): + if row['uuid'] not in known and row['name'] == ssid: + try: + self.cli.delete(row['uuid']) + except OSError: + pass + raise ValueError('Could not join that network. Check the password and signal, then try again.') from error + apply_preference(self.root, self.cli) + + def _activate(self, uuid: str) -> None: + try: + self.cli.activate(uuid) + except OSError as error: + raise ValueError('Could not connect to that network right now.') from error + + def apply(self, payload, permitted, background: bool = False) -> dict: if type(payload) is not dict or type(payload.get('action')) is not str: raise ValueError('Invalid network change') with self.lock: if not permitted(): raise PermissionError('Park and sign in before changing network settings.') + if self._joining(): + raise FileExistsError('The comma is still joining Wi-Fi; try again in a moment.') action, prefs = payload['action'], read_prefs(self.root) + if action == 'scan' and set(payload) == {'action'}: + try: + self.cli.scan(rescan=True) + except OSError: + pass + return self.snapshot(permitted(), fresh=True) known = {row['uuid']: row for row in self.saved(fresh=True)} - if action == 'order' and set(payload) == {'action', 'uuids'}: + if action == 'join' and set(payload) <= {'action', 'ssid', 'password', 'hidden'} and 'ssid' in payload: + ssid, password, hidden = payload['ssid'], payload.get('password', ''), payload.get('hidden', False) + if not valid_ssid(ssid) or not valid_password(password) or type(hidden) is not bool: + raise ValueError('Enter a valid network name and an 8–64 character password (or leave blank for an open network).') + effect = partial(self._join, known, ssid, password, hidden) + if background: + return self._join_later(ssid, effect, permitted()) + self._with_hotspot_paused(effect) + elif action == 'connect' and set(payload) == {'action', 'uuid'}: + if payload['uuid'] not in known: + raise FileExistsError('That network is no longer saved; refresh and try again.') + effect = partial(self._activate, payload['uuid']) + if background: + return self._join_later(known[payload['uuid']]['name'], effect, permitted()) + self._with_hotspot_paused(effect) + elif action == 'forget' and set(payload) == {'action', 'uuid'}: + uuid = payload['uuid'] + if uuid not in known: + raise FileExistsError('That network is no longer saved; refresh and try again.') + self.cli.delete(uuid) + if uuid in prefs['parkedOnly']: + self._save_prefs({**prefs, 'parkedOnly': sorted((set(prefs['parkedOnly']) & set(known)) - {uuid})}) + elif action == 'order' and set(payload) == {'action', 'uuids'}: order = payload['uuids'] if type(order) is not list or len(order) != len(known) or set(order) != set(known): raise FileExistsError('The saved networks changed; refresh and try again.') diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index c9fcd18bf9..eff2d80f7e 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -1839,8 +1839,10 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe self.json(401, {'error': 'Sign in to Galaxy'}) return try: + from openpilot.starpilot.galaxy.network_prefs import via_hotspot with effect_lock: - result = network_owner().apply(payload, lambda: self.settings_session() == identity and parked()) + result = network_owner().apply(payload, lambda: self.settings_session() == identity and parked(), + background=via_hotspot(self.client_address[0])) except PermissionError: self.json(409, {'error': 'Park before changing network settings.'}) except FileExistsError as error: diff --git a/openpilot/starpilot/galaxy/tests/test_network_prefs.py b/openpilot/starpilot/galaxy/tests/test_network_prefs.py index ea30292894..6fb4042cfd 100644 --- a/openpilot/starpilot/galaxy/tests/test_network_prefs.py +++ b/openpilot/starpilot/galaxy/tests/test_network_prefs.py @@ -103,3 +103,116 @@ def test_cellular_switch_uses_the_existing_setting_and_changes_need_park(tmp_pat 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 + + +def test_scan_join_connect_and_forget(tmp_path): + calls = [] + + def run(argv, **_kwargs): + calls.append(argv[1:]) + if 'wifi' in argv and 'list' in argv: + return SimpleNamespace(returncode=0, stdout='Home:80:WPA2\nGuest\\: Wi-Fi:72:\nOffice:65:WPA2\nCorp:50:WPA2 802.1X\nTheGalaxy-1234:90:WPA2\n', stderr='') + if 'connect' in argv or 'up' in argv or 'delete' in argv or 'modify' in argv or 'reapply' in argv: + return SimpleNamespace(returncode=0, stdout='', stderr='') + return SimpleNamespace(returncode=0, stdout=details('-1') if 'connection.uuid' in ' '.join(argv) else LISTING, stderr='') + + params = Mock() + params.get_bool.return_value = False + made = NetworkSettings(tmp_path, NetworkManagerCli(run), params, link=lambda: {'link': 'wifi'}) + scanned = made.apply({'action': 'scan'}, lambda: True) + assert scanned['available'] == [ + {'ssid': 'Guest: Wi-Fi', 'signal': 72, 'security': 'open'}, + {'ssid': 'Office', 'signal': 65, 'security': 'wpa'}, + {'ssid': 'Corp', 'signal': 50, 'security': 'unsupported'}, + ] + assert ['-t', '-f', 'SSID,SIGNAL,SECURITY', 'device', 'wifi', 'list', '--rescan', 'yes'] in calls + + made.apply({'action': 'join', 'ssid': 'Office', 'password': 'correct-password', 'hidden': False}, lambda: True) + assert ['--wait', '15', 'device', 'wifi', 'connect', 'Office', 'ifname', 'wlan0', 'password', 'correct-password'] in calls + + made.apply({'action': 'connect', 'uuid': PHONE}, lambda: True) + assert ['--wait', '15', 'connection', 'up', 'uuid', PHONE, 'ifname', 'wlan0'] in calls + + made.apply({'action': 'forget', 'uuid': PHONE}, lambda: True) + assert ['connection', 'delete', 'uuid', PHONE] in calls + + with pytest.raises(ValueError): + made.apply({'action': 'join', 'ssid': 'Office', 'password': 'short'}, lambda: True) + + +def test_join_pauses_the_hotspot_and_cleans_up_a_failed_profile(tmp_path, monkeypatch): + calls, events = [], [] + iface = tmp_path / 'galaxy0' + iface.touch() + monkeypatch.setattr(network_prefs.hotspot, 'request_pause', lambda seconds: (events.append('pause'), iface.unlink())) + monkeypatch.setattr(network_prefs.hotspot, 'clear_pause', lambda: events.append('resume')) + new, tried = 'dddddddd-dddd-dddd-dddd-dddddddddddd', [] + + def run(argv, **_kwargs): + calls.append(argv[1:]) + if 'connect' in argv: + events.append('join') + tried.append(True) + return SimpleNamespace(returncode=4, stdout='', stderr='Secrets were required') + if 'wifi' in argv or 'delete' in argv: + return SimpleNamespace(returncode=0, stdout='', stderr='') + extra = f'\n\nconnection.uuid:{new}\n802-11-wireless.ssid:Office\n802-11-wireless.mode:infrastructure\n' if tried else '' + if 'connection.uuid' in ' '.join(argv): + return SimpleNamespace(returncode=0, stdout=details() + extra, stderr='') + return SimpleNamespace(returncode=0, stdout=LISTING + (f'{new}:802-11-wireless:yes:0:no:Office\n' if tried else ''), stderr='') + + made = NetworkSettings(tmp_path, NetworkManagerCli(run), Mock(), link=lambda: {'link': 'wifi'}, hotspot_iface=iface, sleep=lambda _s: None) + with pytest.raises(ValueError): + made.apply({'action': 'join', 'ssid': 'Office', 'password': 'wrong-password'}, lambda: True) + assert events == ['pause', 'join', 'resume'] + assert ['connection', 'delete', 'uuid', new] in calls + + +def test_join_refuses_when_the_hotspot_stays_up(tmp_path, monkeypatch): + iface, calls, events = tmp_path / 'galaxy0', [], [] + iface.touch() + monkeypatch.setattr(network_prefs.hotspot, 'request_pause', lambda seconds: events.append('pause')) + monkeypatch.setattr(network_prefs.hotspot, 'clear_pause', lambda: events.append('resume')) + ticks = iter(range(0, 100, 5)) + made = NetworkSettings(tmp_path, NetworkManagerCli(fake_run(calls)), Mock(), link=lambda: {'link': 'wifi'}, + clock=lambda: next(ticks), hotspot_iface=iface, sleep=lambda _s: None) + with pytest.raises(ValueError): + made.apply({'action': 'connect', 'uuid': PHONE}, lambda: True) + assert events == ['pause', 'resume'] and not any('up' in call for call in calls) + + +def test_a_hotspot_client_gets_an_answer_before_the_join_runs(tmp_path, monkeypatch): + calls, jobs, events = [], [], [] + monkeypatch.setattr(network_prefs.hotspot, 'request_pause', lambda seconds: events.append('pause')) + monkeypatch.setattr(network_prefs.hotspot, 'clear_pause', lambda: events.append('resume')) + made = NetworkSettings(tmp_path, NetworkManagerCli(fake_run(calls)), Mock(), link=lambda: {'link': 'wifi'}, + hotspot_iface=tmp_path / 'galaxy0', sleep=lambda _s: None, spawn=jobs.append) + accepted = made.apply({'action': 'connect', 'uuid': PHONE}, lambda: True, background=True) + assert accepted['lastJoin'] == {'ssid': 'Phone: 5G', 'state': 'joining', 'error': ''} + assert not any('up' in call for call in calls) + with pytest.raises(FileExistsError): + made.apply({'action': 'forget', 'uuid': PHONE}, lambda: True) + jobs.pop()() + assert ['--wait', '15', 'connection', 'up', 'uuid', PHONE, 'ifname', 'wlan0'] in calls + assert made.snapshot(True)['lastJoin'] == {'ssid': 'Phone: 5G', 'state': 'joined', 'error': ''} + + +def test_a_failed_background_join_keeps_the_reason(tmp_path): + jobs = [] + + def run(argv, **kwargs): + if 'connect' in argv: + return SimpleNamespace(returncode=4, stdout='', stderr='Secrets were required') + return fake_run([])(argv, **kwargs) + + made = NetworkSettings(tmp_path, NetworkManagerCli(run), Mock(), link=lambda: {'link': 'wifi'}, + hotspot_iface=tmp_path / 'galaxy0', sleep=lambda _s: None, spawn=jobs.append) + made.apply({'action': 'join', 'ssid': 'Office', 'password': 'wrong-password'}, lambda: True, background=True) + jobs.pop()() + last = made.snapshot(True)['lastJoin'] + assert last['state'] == 'failed' and 'password' in last['error'] + + +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') diff --git a/openpilot/starpilot/galaxy/tests/test_networks.mjs b/openpilot/starpilot/galaxy/tests/test_networks.mjs index 9a924af03d..35121bcf6e 100644 --- a/openpilot/starpilot/galaxy/tests/test_networks.mjs +++ b/openpilot/starpilot/galaxy/tests/test_networks.mjs @@ -35,6 +35,31 @@ assert.deepEqual(sent.at(-1), { action: 'order', uuids: [second, first] }) assert.equal(vm.move(0, -1), undefined) await vm.setNetwork(value.networks[1], 'whileDriving', false) assert.deepEqual(sent.at(-1), { action: 'network', uuid: second, setting: 'whileDriving', value: false }) +await vm.openScan() +assert.equal(vm.adding, true) +assert.deepEqual(sent.at(-1), { action: 'scan' }) +await vm.selectAvailable({ ssid: 'Cafe', signal: 75, security: 'open' }) +assert.deepEqual(sent.at(-1), { action: 'join', ssid: 'Cafe', password: '' }) +vm.selectAvailable({ ssid: 'Office', signal: 80, security: 'wpa' }) +assert.equal(vm.joiningSsid, 'Office') +vm.joinPassword = 'my-wifi-password' +await vm.submitJoin() +assert.deepEqual(sent.at(-1), { action: 'join', ssid: 'Office', password: 'my-wifi-password', hidden: false }) +assert.equal(vm.joiningSsid, '') +const sentBeforeForget = sent.length +assert.equal(await vm.forgetSaved(value.networks[0]), false) +assert.equal(sent.length, sentBeforeForget) +await vm.forgetSaved(value.networks[0]) +assert.deepEqual(sent.at(-1), { action: 'forget', uuid: value.networks[0].uuid }) +assert.equal(vm.forgetUuid, null) +assert.equal(validNetworks({ ...value, lastJoin: { ssid: 'Office', state: 'joining', error: '' } }), true) +assert.equal(validNetworks({ ...value, lastJoin: { ssid: 'Office', state: 'maybe', error: '' } }), false) +vm.adopt({ ...value, lastJoin: { ssid: 'Office', state: 'joining', error: '' } }) +vm.joining = vm.snapshot.lastJoin.state === 'joining' +const sentWhileJoining = sent.length +assert.equal(await vm.send({ action: 'scan' }), false) +assert.equal(sent.length, sentWhileJoining) +vm.joining = false vm.adopt({ ...value, editable: false }) const before = sent.length assert.equal(await vm.send({ action: 'cellular', value: false }), false) diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css index 3b98c71a18..6e79a1ee34 100644 --- a/openpilot/starpilot/galaxy/web/css/settings.css +++ b/openpilot/starpilot/galaxy/web/css/settings.css @@ -913,6 +913,13 @@ html.gx-maker-open, html.gx-maker-open body { touch-action: manipulation; } .gx-sentry-status--warning .gx-status-dot { background: var(--warning); } .gx-networks > .gx-card { margin-bottom: 0; } .gx-networks__caption { margin: 0; padding: var(--sp-2) var(--sp-4) var(--sp-3); border-top: 1px solid var(--outline); } +.gx-networks__header-btn { min-height: 36px; padding: 0 var(--sp-3); } +.gx-networks__scan { border-top: 1px solid var(--outline); background: rgba(255, 255, 255, 0.015); } +.gx-networks__subhead { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4) var(--sp-2); } +.gx-networks__link-btn { border: 0; padding: 0; background: none; font: inherit; font-size: var(--fs-sm); cursor: pointer; } +.gx-networks__join-row { flex-wrap: wrap; background: rgba(255, 255, 255, 0.02); } +.gx-networks__join-form { flex: 1 1 280px; justify-content: flex-end; } +.gx-networks__field { flex: 1 1 160px; max-width: 240px; } .gx-networks__toggle { border: 0; padding: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } .gx-networks__toggle:focus-visible { outline: 2px solid var(--primary); outline-offset: 4px; border-radius: var(--radius-sm); } .gx-networks__details { background: rgba(255, 255, 255, 0.015); box-shadow: inset 3px 0 var(--primary); } @@ -921,6 +928,6 @@ html.gx-maker-open, html.gx-maker-open body { touch-action: manipulation; } .gx-hotspot__field { flex: 1 1 160px; max-width: 240px; } .gx-hotspot__details { padding: var(--sp-3) var(--sp-4); } @media (max-width: 600px) { - .gx-hotspot__field { max-width: none; } - .gx-hotspot__controls { justify-content: stretch; } + .gx-networks__field, .gx-hotspot__field { max-width: none; } + .gx-networks__join-form, .gx-hotspot__controls { justify-content: stretch; } } diff --git a/openpilot/starpilot/galaxy/web/js/networks.js b/openpilot/starpilot/galaxy/web/js/networks.js index f69f32274e..ccf3c4b015 100644 --- a/openpilot/starpilot/galaxy/web/js/networks.js +++ b/openpilot/starpilot/galaxy/web/js/networks.js @@ -5,6 +5,9 @@ import { GalaxySettingRow, switchRow } from "./galaxy-setting-row.js" import { GalaxyHotspot } from "./hotspot.js" const METERED = ['Auto', 'Metered', 'Unmetered'] +const SECURITY = ['open', 'wpa', 'unsupported'] +const JOIN_STATES = ['joining', 'joined', 'failed'] +const SLOW_ACTIONS = ['scan', 'join', 'connect'] const LINKS = { wifi: 'Wi-Fi', cellular: 'Cellular', none: 'Offline', other: 'Other', unknown: 'Unknown' } export function validNetworks(value) { @@ -12,7 +15,11 @@ export function validNetworks(value) { typeof value.pauseHotspot === 'boolean' && typeof value.cellular?.enabled === 'boolean' && typeof value.link?.link === 'string' && Array.isArray(value.networks) && value.networks.every(network => /^[0-9a-f-]{36}$/.test(network.uuid) && typeof network.name === 'string' && typeof network.autoJoin === 'boolean' && - typeof network.whileDriving === 'boolean' && typeof network.connected === 'boolean' && METERED.includes(network.metered)) + typeof network.whileDriving === 'boolean' && typeof network.connected === 'boolean' && METERED.includes(network.metered)) && + (value.available === undefined || (Array.isArray(value.available) && value.available.every(item => + typeof item?.ssid === 'string' && Number.isInteger(item.signal) && SECURITY.includes(item.security)))) && + (value.lastJoin == null || (typeof value.lastJoin.ssid === 'string' && JOIN_STATES.includes(value.lastJoin.state) && + typeof value.lastJoin.error === 'string')) } export const choiceRow = (label, value, choices, reason = '') => ({ label, value, reason, choices, available: true, action: true }) @@ -21,9 +28,19 @@ export const NetworksPage = { name: "NetworksPage", components: { GxNotice, GxState, GalaxySettingRow, GalaxyHotspot }, props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } }, - data: () => ({ snapshot: null, busy: false, error: '', openUuid: null, timer: null, controller: null, generation: 0, active: false }), + data: () => ({ snapshot: null, busy: false, error: '', openUuid: null, adding: false, joiningSsid: '', joinPassword: '', + hiddenOpen: false, hiddenSsid: '', showJoinPassword: false, forgetUuid: null, timer: null, controller: null, generation: 0, active: false }), computed: { linkName() { return LINKS[this.snapshot?.link.link] || 'Unknown' }, + availableNetworks() { return this.snapshot?.available || [] }, + joining() { return this.snapshot?.lastJoin?.state === 'joining' }, + canSubmitJoin() { + const ssid = this.hiddenOpen ? this.hiddenSsid.trim() : this.joiningSsid + if (!ssid || ssid.length > 64) return false + return this.hiddenOpen + ? (this.joinPassword === '' || (this.joinPassword.length >= 8 && this.joinPassword.length <= 64)) + : (this.joinPassword.length >= 8 && this.joinPassword.length <= 64) + }, changed() { const at = this.snapshot?.link.changedAt return at ? new Date(at * 1000).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : '' @@ -40,19 +57,70 @@ export const NetworksPage = { methods: { switchRow, choiceRow, start() { if (this.mode === 'local') { this.active = true; this.refresh() } }, - stop() { this.active = false; this.generation++; clearTimeout(this.timer); this.controller?.abort(); this.snapshot = null; this.openUuid = null; this.busy = false }, + stop() { + this.active = false; this.generation++; clearTimeout(this.timer); this.controller?.abort() + this.snapshot = null; this.openUuid = null; this.forgetUuid = null; this.adding = false; this.cancelJoin(); this.busy = false + }, adopt(value) { if (!validNetworks(value)) throw new Error('Invalid network status') this.snapshot = value if (this.openUuid && !value.networks.some(n => n.uuid === this.openUuid)) this.openUuid = null }, isOpen(network) { return this.openUuid === network.uuid || this.snapshot?.networks.length === 1 }, - toggleNetwork(uuid) { this.openUuid = this.openUuid === uuid ? null : uuid }, + toggleNetwork(uuid) { this.openUuid = this.openUuid === uuid ? null : uuid; this.forgetUuid = null }, networkSummary(network) { const parts = [this.signalText(network), network.autoJoin ? (network.whileDriving ? 'Auto-join' : 'Parked only') : 'Manual'] if (network.metered !== 'Auto') parts.push(network.metered) return parts.join(' · ') }, + openScan() { + this.adding = true + this.cancelJoin() + return this.scanNetworks() + }, + closeScan() { + this.adding = false + this.cancelJoin() + }, + scanNetworks() { return this.send({ action: 'scan' }) }, + cancelJoin() { + this.joiningSsid = '' + this.joinPassword = '' + this.hiddenOpen = false + this.hiddenSsid = '' + this.showJoinPassword = false + }, + selectAvailable(item) { + if (item.security === 'unsupported') return + if (item.security === 'open') { + this.cancelJoin() + return this.send({ action: 'join', ssid: item.ssid, password: '' }) + } + this.hiddenOpen = false + this.joiningSsid = this.joiningSsid === item.ssid ? '' : item.ssid + this.joinPassword = '' + this.showJoinPassword = false + }, + openHidden() { + this.joiningSsid = '' + this.joinPassword = '' + this.hiddenSsid = '' + this.showJoinPassword = false + this.hiddenOpen = !this.hiddenOpen + }, + async submitJoin() { + const ssid = this.hiddenOpen ? this.hiddenSsid.trim() : this.joiningSsid + if (!ssid) return false + const joined = await this.send({ action: 'join', ssid, password: this.joinPassword, hidden: this.hiddenOpen }) + if (joined) this.cancelJoin() + return joined + }, + connectSaved(network) { return this.send({ action: 'connect', uuid: network.uuid }) }, + forgetSaved(network) { + if (this.forgetUuid !== network.uuid) { this.forgetUuid = network.uuid; return false } + this.forgetUuid = null + return this.send({ action: 'forget', uuid: network.uuid }) + }, async refresh() { if (!this.active || this.busy) return clearTimeout(this.timer); this.controller?.abort() @@ -65,18 +133,18 @@ export const NetworksPage = { } catch (error) { if (!this.active || generation !== this.generation) return if (error.status === 401) { this.stop(); this.unauthorized(); return } - this.error = error.message + this.error = this.joining ? '' : error.message } finally { - if (this.active && generation === this.generation) this.timer = setTimeout(() => this.refresh(), 5000) + if (this.active && generation === this.generation) this.timer = setTimeout(() => this.refresh(), this.joining ? 3000 : 5000) } }, async send(body) { - if (!this.active || this.busy || !this.snapshot?.editable) return false + if (!this.active || this.busy || this.joining || !this.snapshot?.editable) return false clearTimeout(this.timer); this.controller?.abort() const generation = ++this.generation this.controller = new AbortController(); this.busy = true; this.error = '' try { - const value = await requestJson('./api/galaxy/networks', { request: { signal: this.controller.signal, + const value = await requestJson('./api/galaxy/networks', { timeout: SLOW_ACTIONS.includes(body.action) ? 60000 : 8000, request: { signal: this.controller.signal, method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } }) if (!this.active || generation !== this.generation) return false this.adopt(value) @@ -108,15 +176,53 @@ export const NetworksPage = { Loading network settings… {{ error }} From d1b65dcb652cae87833cd8cbfaeb49a4da357ce1 Mon Sep 17 00:00:00 2001 From: Danny Date: Mon, 16 Nov 2026 05:42:22 -0800 Subject: [PATCH 11/14] Layout: Show a magnified view clear of your finger while dragging widgets on touch --- .../starpilot/galaxy/web/css/settings.css | 3 ++ .../galaxy/web/js/onroad-layout-template.js | 5 ++++ .../starpilot/galaxy/web/js/onroad-layout.js | 30 +++++++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css index a8511f2c5a..894f834c4b 100644 --- a/openpilot/starpilot/galaxy/web/css/settings.css +++ b/openpilot/starpilot/galaxy/web/css/settings.css @@ -608,6 +608,9 @@ input[type="range"].gx-slider:active::-moz-range-thumb { .gx-layout__layer.is-drop-target.is-drop-after::before { top: auto; bottom: -5px; } .gx-layout__drag-ghost { position: fixed; z-index: 1000; pointer-events: none; display: flex; align-items: center; gap: 12px; padding: 12px 16px; min-height: 44px; box-sizing: border-box; border: 2px solid var(--primary); border-radius: 16px; background: var(--background); color: var(--on-surface); box-shadow: 0 12px 32px #0008; transform: scale(1.03); } .gx-layout__drag-ghost strong { flex: 1; } +.gx-layout__loupe { position: fixed; z-index: 1000; pointer-events: none; overflow: hidden; box-sizing: border-box; border: 2px solid var(--primary); border-radius: 16px; box-shadow: 0 12px 32px #0008; + background: repeating-linear-gradient(135deg, #090c10 0 6px, #131820 6px 12px); } +.gx-layout__loupe svg { display: block; width: 100%; height: 100%; } .gx-layout__outline { pointer-events: none; } .gx-layout__help > summary { cursor: pointer; min-height: 40px; align-content: center; } .gx-layout__layer.is-dragging { opacity: .45; } diff --git a/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js b/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js index 8c6d9e4e48..6a7dd1f9a2 100644 --- a/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js +++ b/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js @@ -73,6 +73,7 @@ export const ONROAD_LAYOUT_TEMPLATE = ` + + +
diff --git a/openpilot/starpilot/galaxy/web/js/onroad-layout.js b/openpilot/starpilot/galaxy/web/js/onroad-layout.js index 0703ab5df7..216768c37c 100644 --- a/openpilot/starpilot/galaxy/web/js/onroad-layout.js +++ b/openpilot/starpilot/galaxy/web/js/onroad-layout.js @@ -556,6 +556,34 @@ export const OnroadLayoutPage = { width: widget.width, height: widget.height + widget.visualInsetTop + widget.visualInsetBottom } }, + // On touch, a magnified copy of the area around the dragged widget sits clear of the finger. + loupe() { + const drag = this.state.drag + if (!drag?.touch || !drag.moved || drag.resize || (drag.fromTray && !drag.inside) || drag.clientX == null || !this.$refs.preview) return null + const rect = this.$refs.preview.getBoundingClientRect(), viewWidth = window.innerWidth, viewHeight = window.innerHeight + if (!rect.width) return null + const gap = 48, edge = 8, x = drag.clientX, y = drag.clientY + let width = Math.round(Math.max(150, Math.min(240, viewWidth / 2 - 8))), height = Math.round(width * .62) + let left = Math.max(edge, Math.min(viewWidth - width - edge, x - width / 2)), top = y - gap - height + if (top < edge) { + // No room above: sit beside the finger on the roomier side, narrower if needed, before falling back to below. + const right = x < viewWidth / 2, beside = Math.min(width, Math.floor((right ? viewWidth - x : x) - 24 - edge)) + if (beside >= 140) { + width = beside + height = Math.round(width * .62) + left = right ? x + 24 : x - 24 - width + top = Math.max(edge, Math.min(viewHeight - height - edge, y - height / 2)) + } else top = Math.min(viewHeight - height - edge, y + gap) + } + const [widgetWidth, widgetHeight] = widgetSize(this.profile.widgets[drag.id], this.layout[drag.id]) + const span = Math.max(width / (rect.width / this.profile.width * 2), widgetWidth * 1.5, widgetHeight * 1.5 * width / height) + const spanY = span * height / width + const centerX = this.previewX(drag.id) + widgetWidth / 2, centerY = this.layout[drag.id].y + widgetHeight / 2 + return { + viewBox: [centerX - span / 2, centerY - spanY / 2, span, spanY].map(value => Math.round(value * 10) / 10).join(" "), + style: { left: Math.round(left) + "px", top: Math.round(top) + "px", width: width + "px", height: height + "px" } + } + }, activeWidgets() { return this.widgets.filter(({ id }) => this.layout[id].enabled) }, renderWidgets() { return this.layerWidgets.filter(item => !this.previewHidden(item.id)).reverse().map((item) => { @@ -1242,6 +1270,8 @@ export const OnroadLayoutPage = { // A finger wobbles a few pixels on every tap; only a deliberate move drags the widget. if (!drag.moved && Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) < DRAG_SLOP) return drag.moved = true + drag.clientX = event.clientX + drag.clientY = event.clientY drag.inside = point.x >= 0 && point.y >= 0 && point.x <= this.profile.width && point.y <= this.profile.height if (!drag.fromTray || drag.inside) { const raw = { x: point.x - drag.offsetX, y: point.y - drag.offsetY } From d95be127443df27b7f8f5f9ee789adc950e282fd Mon Sep 17 00:00:00 2001 From: dirwin31 <83434411+dirwin31@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:58:41 -0800 Subject: [PATCH 12/14] Fix omitted touch action default in Starport --- .../system/starport/tests/test_touch.py | 32 +++++++++++++++++++ openpilot/starpilot/system/starport/touch.py | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 openpilot/starpilot/system/starport/tests/test_touch.py diff --git a/openpilot/starpilot/system/starport/tests/test_touch.py b/openpilot/starpilot/system/starport/tests/test_touch.py new file mode 100644 index 0000000000..0118824e93 --- /dev/null +++ b/openpilot/starpilot/system/starport/tests/test_touch.py @@ -0,0 +1,32 @@ +"""Receiver touch packets must preserve protobuf defaults and pointer state.""" + +import pytest + +from openpilot.starpilot.system.starport.touch import InputConfig, TouchEvent, TouchMapper +from openpilot.starpilot.system.starport.wire import field + + +def packet(action, x=640, y=360): + # A zero pointer ID and action index may also be omitted by the receiver. + location = field(1, x) + field(2, y) + touch = field(1, location) + if action is not None: + touch += field(3, action) + return field(3, touch) + + +@pytest.mark.parametrize('press', [None, 0]) +def test_default_and_explicit_press_both_start_a_complete_gesture(press): + mapper = TouchMapper(InputConfig(touch_width=1280, touch_height=720), 1280, 720, 0, 0) + assert mapper.decode(packet(press)) == [TouchEvent('down', .5, .5)] + assert mapper.decode(packet(2, 960)) == [TouchEvent('move', .75, .5)] + assert mapper.decode(packet(1, 960)) == [TouchEvent('up', .75, .5)] + assert mapper.pointer is None + assert mapper.decode(packet(press)) == [TouchEvent('down', .5, .5)] + + +def test_move_without_a_press_does_not_start_a_gesture(): + mapper = TouchMapper(InputConfig(), 1280, 720, 0, 0) + assert mapper.decode(packet(2)) == [] + assert mapper.decode(packet(1)) == [] + assert mapper.pointer is None diff --git a/openpilot/starpilot/system/starport/touch.py b/openpilot/starpilot/system/starport/touch.py index 9ec5228462..6af708d1a4 100644 --- a/openpilot/starpilot/system/starport/touch.py +++ b/openpilot/starpilot/system/starport/touch.py @@ -132,7 +132,7 @@ class TouchMapper: if isinstance(raw, bytes): loc = parse_fields(raw) locations.append((int(one(loc, 3, 0) or 0), int(one(loc, 1, 0) or 0), int(one(loc, 2, 0) or 0))) - action = one(fields, 3, ACTION_DRAG) + action = one(fields, 3, ACTION_PRESS) index = int(one(fields, 2, 0) or 0) if not locations: return [] From 56cb80cdb7c1979e4e44eddd075077a36b1da71f Mon Sep 17 00:00:00 2001 From: dirwin31 <83434411+dirwin31@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:16:27 -0800 Subject: [PATCH 13/14] Log Starport touch input and channel diagnostics --- .../starpilot/system/starport/session.py | 34 ++++++-- .../starport/tests/test_media_controls.py | 2 +- .../system/starport/tests/test_touch.py | 83 +++++++++++++++++++ 3 files changed, 111 insertions(+), 8 deletions(-) diff --git a/openpilot/starpilot/system/starport/session.py b/openpilot/starpilot/system/starport/session.py index 1a79933bac..68bffc48a0 100644 --- a/openpilot/starpilot/system/starport/session.py +++ b/openpilot/starpilot/system/starport/session.py @@ -102,6 +102,8 @@ CODEC_NAMES = {3: "H.264", 5: "VP9", 6: "AV1", 7: "H.265"} # kind and then every hundredth, so a head unit repeating one cannot flood the session log. IGNORED_LOG_FIRST = 5 IGNORED_LOG_EVERY = 100 +INPUT_LOG_FIRST = 20 +INPUT_LOG_EVERY = 100 FRAME_RATES = {1: 60, 2: 30} # Software H.264 on the comma is the constraint: prefer 720p, then 480p. 1080p # is accepted only when nothing smaller is offered. @@ -797,6 +799,9 @@ class ProjectionSession(Session): """Open the touch/key channel so input is acknowledged; failures are not fatal.""" inputs = [ch for ch in self.channels if ch.get("input")] channel = next((ch for ch in inputs if ch.get("display_id") in (None, 0)), inputs[0] if inputs else None) + self.event("input_channels", channels=[{"channel": ch["id"], "display_id": ch.get("display_id"), + "config": str(ch.get("input_config") or InputConfig())} for ch in inputs], + selected=channel["id"] if channel is not None else None) if channel is None: return try: @@ -812,9 +817,14 @@ class ProjectionSession(Session): self.touch = TouchMapper(config, self.mode.width, self.mode.height, self.mode.margin_width, self.mode.margin_height, content_left=self.mode.content_left, content_top=self.mode.content_top) self.event("input_opened", channel=channel["id"], keycodes=list(config.keycodes), - touch=f"{config.touch_width}x{config.touch_height}") + touch=f"{config.touch_width}x{config.touch_height}", display_id=channel.get("display_id"), + mapping={"touch_width": self.touch.touch_width, "touch_height": self.touch.touch_height, + "video_width": self.touch.video_width, "video_height": self.touch.video_height, + "content_left": self.touch.left, "content_top": self.touch.top, + "content_width": self.touch.content_width, "content_height": self.touch.content_height, + "content_space": self.touch.content_space} if self.touch is not None else None) except (TimeoutError, ValueError) as error: - self.event("input_unavailable", error=str(error)) + self.event("input_unavailable", channel=channel["id"], error=str(error)) def _open_optional(self, channel: dict, name: str) -> bool: try: @@ -968,21 +978,31 @@ class ProjectionSession(Session): elif channel == self.input_channel: if kind == INPUT_EVENT: self.input_events += 1 + mapped = [] + disposition = "no_mapper" if self.touch is None else "unfocused" if not self.focused else "no_touch_event" if self.touch is not None and self.focused: try: - self.touch_events.extend(self.touch.decode(data)) + mapped = self.touch.decode(data) + self.touch_events.extend(mapped) + if mapped: + disposition = "queued" except ValueError as error: - self.event("input_invalid", error=str(error)) + disposition = "invalid" + self.event("input_invalid", channel=channel, kind=kind, error=str(error)) + if self.input_events <= INPUT_LOG_FIRST or self.input_events % INPUT_LOG_EVERY == 0: + self.event("input_event", channel=channel, kind=kind, count=self.input_events, bytes=len(data), + focused=self.focused, disposition=disposition, message=describe(data), + mapped=[{"kind": event.kind, "x": round(event.x, 5), "y": round(event.y, 5)} for event in mapped]) # The driver may be on the car's own screen while Android Auto plays the music. try: for action in self.keys.decode(data): - self.event("media_key", action=action) + self.event("media_key", channel=channel, action=action) if self.media_control is not None: self.media_control(action) except ValueError as error: - self.event("input_invalid", error=str(error)) + self.event("input_invalid", channel=channel, kind=kind, error=str(error)) elif kind == INPUT_BINDING_RESPONSE: - self.event("input_bound", status=signed(one(fields, 1, 0))) + self.event("input_bound", channel=channel, status=signed(one(fields, 1, 0))) else: self.ignored("input_ignored", channel, kind, data) elif channel is not None and channel == self.sensor_channel: diff --git a/openpilot/starpilot/system/starport/tests/test_media_controls.py b/openpilot/starpilot/system/starport/tests/test_media_controls.py index e26f1939a2..3bc4507954 100644 --- a/openpilot/starpilot/system/starport/tests/test_media_controls.py +++ b/openpilot/starpilot/system/starport/tests/test_media_controls.py @@ -53,7 +53,7 @@ def test_session_sends_media_keys_even_on_the_cars_own_screen(focused): session.handle(3, INPUT_EVENT, keys(key(87, False))) session.handle(3, INPUT_EVENT, keys(key(88, True))) assert session.actions == ['next', 'previous'] - assert ('media_key', {'action': 'next'}) in session.events + assert ('media_key', {'channel': 3, 'action': 'next'}) in session.events class Session: diff --git a/openpilot/starpilot/system/starport/tests/test_touch.py b/openpilot/starpilot/system/starport/tests/test_touch.py index 0118824e93..71ecb84ba9 100644 --- a/openpilot/starpilot/system/starport/tests/test_touch.py +++ b/openpilot/starpilot/system/starport/tests/test_touch.py @@ -1,7 +1,10 @@ """Receiver touch packets must preserve protobuf defaults and pointer state.""" import pytest +from unittest.mock import Mock +from openpilot.starpilot.system.starport.session import INPUT_BINDING_RESPONSE, INPUT_EVENT, VideoMode +from openpilot.starpilot.system.starport.tests.test_media_controls import session_with_input from openpilot.starpilot.system.starport.touch import InputConfig, TouchEvent, TouchMapper from openpilot.starpilot.system.starport.wire import field @@ -30,3 +33,83 @@ def test_move_without_a_press_does_not_start_a_gesture(): assert mapper.decode(packet(2)) == [] assert mapper.decode(packet(1)) == [] assert mapper.pointer is None + + +@pytest.fixture +def session(): + value = session_with_input(True) + value.touch = TouchMapper(InputConfig(), 1280, 720, 0, 0) + return value + + +def test_logs_wire_packet_and_mapped_gesture(session): + for action in (None, 2, 1): + session.handle(3, INPUT_EVENT, packet(action)) + records = [values for name, values in session.events if name == 'input_event'] + assert [row['mapped'][0]['kind'] for row in records] == ['down', 'move', 'up'] + assert all(row['channel'] == 3 and row['disposition'] == 'queued' for row in records) + assert records[0]['message'][3][0][1][0] == {1: [640], 2: [360]} + assert records[0]['mapped'] == [{'kind': 'down', 'x': .5, 'y': .5}] + assert len(session.touch_events) == 3 + + +@pytest.mark.parametrize('reason', ['unfocused', 'no_mapper', 'no_touch_event', 'invalid']) +def test_logs_why_touch_did_not_queue(session, reason): + data = packet(None) + if reason == 'unfocused': + session.focused = False + elif reason == 'no_mapper': + session.touch = None + elif reason == 'no_touch_event': + data = packet(2) + else: + data = field(3, b'\x80') + session.handle(3, INPUT_EVENT, data) + record = next(values for name, values in session.events if name == 'input_event') + assert record['disposition'] == reason + assert record['mapped'] == [] + assert session.touch_events == [] + + +def test_input_log_sampling_does_not_drop_gestures(session): + for _ in range(100): + session.handle(3, INPUT_EVENT, packet(None)) + session.handle(3, INPUT_EVENT, packet(1)) + records = [values for name, values in session.events if name == 'input_event'] + assert [row['count'] for row in records] == [*range(1, 21), 100, 200] + assert len(session.touch_events) == 200 + + +def test_channel_selection_and_mapping_are_logged(session): + session.channels = [{'id': 4, 'input': True, 'display_id': 1}, + {'id': 3, 'input': True, 'display_id': 0, 'input_config': InputConfig((), 1280, 720)}] + session.mode = VideoMode(5, 0, 1280, 720, 30, 0, 240) + session.send = Mock() + session.wait_for = Mock(return_value=field(1, 0)) + session.open_input() + selection = next(values for name, values in session.events if name == 'input_channels') + assert selection['selected'] == 3 + assert [ch['channel'] for ch in selection['channels']] == [4, 3] + opened = next(values for name, values in session.events if name == 'input_opened') + assert opened['channel'] == 3 + assert opened['mapping']['content_height'] == 480 + assert opened['mapping']['content_top'] == 120 + + +def test_no_advertised_input_channel_is_logged(session): + session.channels = [] + session.open_input() + assert session.events == [('input_channels', {'channels': [], 'selected': None})] + + +def test_failed_input_channel_is_identified(session): + session.channels = [{'id': 7, 'input': True}] + session.send = Mock() + session.wait_for = Mock(side_effect=TimeoutError('no response')) + session.open_input() + assert ('input_unavailable', {'channel': 7, 'error': 'no response'}) in session.events + + +def test_binding_response_includes_channel(session): + session.handle(3, INPUT_BINDING_RESPONSE, field(1, 0)) + assert session.events == [('input_bound', {'channel': 3, 'status': 0})] From 6e0126d83707cb6e64ecb88f51c356981a9c97ab Mon Sep 17 00:00:00 2001 From: Danny Date: Tue, 17 Nov 2026 11:31:29 -0800 Subject: [PATCH 14/14] Layout Squeezed Text --- openpilot/starpilot/galaxy/web/css/settings.css | 7 +++++-- openpilot/starpilot/galaxy/web/js/hotspot.js | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css index 405f94e66c..200d0794c1 100644 --- a/openpilot/starpilot/galaxy/web/css/settings.css +++ b/openpilot/starpilot/galaxy/web/css/settings.css @@ -929,6 +929,9 @@ html.gx-maker-open, html.gx-maker-open body { touch-action: manipulation; } .gx-hotspot__field { flex: 1 1 160px; max-width: 240px; } .gx-hotspot__details { padding: var(--sp-3) var(--sp-4); } @media (max-width: 600px) { - .gx-hotspot__field { max-width: none; } - .gx-hotspot__controls { justify-content: stretch; } + .gx-hotspot__row { flex-direction: column; align-items: stretch; } + .gx-hotspot__row > .gx-row__info, .gx-hotspot__controls { flex: none; } + .gx-hotspot__row .gx-row__desc { overflow-wrap: anywhere; } + .gx-hotspot__field { min-width: 0; max-width: none; } + .gx-hotspot__controls { justify-content: flex-start; } } diff --git a/openpilot/starpilot/galaxy/web/js/hotspot.js b/openpilot/starpilot/galaxy/web/js/hotspot.js index c4eed55c19..120d51e19c 100644 --- a/openpilot/starpilot/galaxy/web/js/hotspot.js +++ b/openpilot/starpilot/galaxy/web/js/hotspot.js @@ -101,7 +101,7 @@ export const GalaxyHotspot = {
-
+
Local Galaxy address Join {{ snapshot.config.ssid }} (keep connected if warned of no Internet), then open or bookmark this link.