Merge Di's StarPort touch, Networks, and layout magnifier PRs (#315, #316, #317)

Includes regression-tested prompt hotspot recovery after failed Wi-Fi joins, validated network-order inputs, and network module type corrections.
This commit is contained in:
Dom
2026-11-17 14:25:35 -06:00
35 changed files with 2218 additions and 58 deletions
+22
View File
@@ -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)
+7 -2
View File
@@ -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()})
+407
View File
@@ -0,0 +1,407 @@
"""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
from functools import partial
from ipaddress import ip_address, ip_network
import json
import re
import subprocess
import threading
import time
from pathlib import Path
from typing import cast
from openpilot.starpilot.galaxy import hotspot
from openpilot.starpilot.galaxy.hotspot import atomic_json, bounded_json
DEFAULT = {'prefer': 'wifi', 'pauseHotspot': True, 'parkedOnly': []}
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
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]:
"""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(cast(list[str], 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': []}
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, timeout: float = 10) -> str:
try:
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: dict[str, dict] = {}
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:
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)
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:
signal, _ = self.scan(rescan=False)
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 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)
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,
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
@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)
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 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, '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 _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 == '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 any(type(uuid) is not str for uuid in order) 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(cast(list[str], 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)
+42 -1
View File
@@ -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,27 @@ 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:
from openpilot.starpilot.galaxy.network_prefs import via_hotspot
with effect_lock:
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:
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:
@@ -18,6 +18,8 @@ assert.ok(GalaxyPage.template.indexOf('<RemoteAccess') < GalaxyPage.template.ind
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
assert.ok(GalaxyPage.template.includes('<h3>Get the app</h3>'))
assert.ok(GalaxyPage.template.includes('<InstallApp :url="url" />'))
assert.ok(GalaxyPage.template.includes('href="#/networks"'))
assert.ok(GalaxyPage.template.indexOf('<InstallApp') < GalaxyPage.template.indexOf('#/networks'))
assert.ok(!GalaxyPage.template.includes('PWA'))
assert.ok(DriveStatePanel.template.includes('gx-card gx-force-drive'))
const css = readFileSync(new URL('../web/css/galaxy.css', import.meta.url), 'utf8')
@@ -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()
@@ -0,0 +1,227 @@
"""Saved Wi-Fi order and per-network choices: only Wi-Fi profiles are ever changed."""
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from openpilot.starpilot.galaxy import network_prefs
from openpilot.starpilot.galaxy.network_prefs import NetworkManagerCli, NetworkSettings, split_terse
HOME, PHONE, AP = (f'{digit * 8}-{digit * 4}-{digit * 4}-{digit * 4}-{digit * 12}' for digit in 'abc')
LISTING = '\n'.join([f'{HOME}:802-11-wireless:yes:0:yes:openpilot connection Home',
'ffffffff-1111-2222-3333-444444444444:gsm:yes:2:no:esim',
f'{AP}:802-11-wireless:no:0:no:Hotspot',
f'{PHONE}:802-11-wireless:yes:5:no:openpilot connection Phone\\: 5G', ''])
def details(metric='-1'):
rows = [(HOME, 'Home', 'infrastructure'), (AP, 'weedle', 'ap'), (PHONE, 'Phone: 5G', 'infrastructure')]
return '\n\n'.join(f'connection.uuid:{uuid}\n802-11-wireless.ssid:{name.replace(":", chr(92) + ":")}\n802-11-wireless.mode:{mode}\n' +
f'connection.metered:unknown\nipv4.route-metric:{metric}' for uuid, name, mode in rows) + '\n'
def fake_run(calls, metric='-1'):
def run(argv, **_kwargs):
calls.append(argv[1:])
if 'modify' in argv or 'reapply' in argv:
return SimpleNamespace(returncode=0, stdout='', stderr='')
if 'wifi' in argv:
return SimpleNamespace(returncode=0, stdout='Home:80\nHome:40\n', stderr='')
return SimpleNamespace(returncode=0, stdout=details(metric) if 'connection.uuid' in ' '.join(argv) else LISTING, stderr='')
return run
def settings(tmp_path, calls, metric='-1'):
params = Mock()
params.get_bool.return_value = False
return NetworkSettings(tmp_path, NetworkManagerCli(fake_run(calls, metric)), params, link=lambda: {'link': 'wifi'}), params
def changes(calls):
return [call for call in calls if 'modify' in call or 'reapply' in call]
def test_terse_lines_keep_colons_inside_names():
assert split_terse('a:b:name\\: with\\\\colon:x', 3) == ['a', 'b', 'name: with\\colon:x']
def test_only_client_wifi_networks_are_listed_best_priority_first(tmp_path):
made, _ = settings(tmp_path, [])
snapshot = made.snapshot(True)
assert [(n['name'], n['connected'], n['signal'], n['whileDriving']) for n in snapshot['networks']] == [
('Phone: 5G', False, None, True), ('Home', True, 80, True)]
assert snapshot['prefer'] == 'wifi' and snapshot['cellular']['enabled'] and snapshot['pauseHotspot']
def test_order_writes_priorities_and_rejects_a_stale_list(tmp_path):
calls = []
made, _ = settings(tmp_path, calls)
made.apply({'action': 'order', 'uuids': [HOME, PHONE]}, lambda: True)
assert changes(calls) == [['connection', 'modify', HOME, 'connection.autoconnect-priority', '2'],
['connection', 'modify', PHONE, 'connection.autoconnect-priority', '1']]
with pytest.raises(FileExistsError):
made.apply({'action': 'order', 'uuids': [HOME]}, lambda: True)
with pytest.raises(FileExistsError):
made.apply({'action': 'order', 'uuids': [HOME, AP]}, lambda: True)
@pytest.mark.parametrize('order', [[HOME, []], [HOME, 1], [HOME, False]])
def test_order_rejects_non_string_ids_without_modifying_profiles(tmp_path, order):
calls = []
made, _ = settings(tmp_path, calls)
with pytest.raises(FileExistsError):
made.apply({'action': 'order', 'uuids': order}, lambda: True)
assert changes(calls) == []
def test_per_network_choices(tmp_path):
calls = []
made, _ = settings(tmp_path, calls)
snapshot = made.apply({'action': 'network', 'uuid': PHONE, 'setting': 'whileDriving', 'value': False}, lambda: True)
assert [n['whileDriving'] for n in snapshot['networks']] == [False, True] and changes(calls) == []
assert network_prefs.read_prefs(tmp_path)['parkedOnly'] == [PHONE]
made.apply({'action': 'network', 'uuid': HOME, 'setting': 'metered', 'value': 'Metered'}, lambda: True)
made.apply({'action': 'network', 'uuid': PHONE, 'setting': 'autoJoin', 'value': False}, lambda: True)
assert changes(calls) == [['connection', 'modify', HOME, 'connection.metered', 'yes'], ['device', 'reapply', 'wlan0'],
['connection', 'modify', PHONE, 'connection.autoconnect', 'no']]
for bad in ({'action': 'network', 'uuid': AP, 'setting': 'autoJoin', 'value': True},):
with pytest.raises(FileExistsError):
made.apply(bad, lambda: True)
for bad in ({'action': 'network', 'uuid': HOME, 'setting': 'metered', 'value': 'yes'}, {'action': 'reboot'}, []):
with pytest.raises(ValueError):
made.apply(bad, lambda: True)
def test_preferring_cellular_raises_only_the_wifi_route_cost(tmp_path):
calls = []
made, _ = settings(tmp_path, calls)
assert made.apply({'action': 'prefer', 'value': 'cellular'}, lambda: True)['prefer'] == 'cellular'
assert changes(calls) == [['connection', 'modify', PHONE, 'ipv4.route-metric', '2000', 'ipv6.route-metric', '2000'],
['connection', 'modify', HOME, 'ipv4.route-metric', '2000', 'ipv6.route-metric', '2000'],
['device', 'reapply', 'wlan0']]
assert all('esim' not in ' '.join(call) and 'gsm' not in ' '.join(call) for call in changes(calls))
calls.clear()
assert network_prefs.apply_preference(tmp_path, NetworkManagerCli(fake_run(calls, '2000'))) == 0 and changes(calls) == []
def test_cellular_switch_uses_the_existing_setting_and_changes_need_park(tmp_path):
calls = []
made, params = settings(tmp_path, calls)
made.apply({'action': 'cellular', 'value': False}, lambda: True)
params.put_bool.assert_called_once_with('CellularDisabled', True)
with pytest.raises(PermissionError):
made.apply({'action': 'pauseHotspot', 'value': False}, lambda: False)
assert changes(calls) == [] and network_prefs.read_prefs(tmp_path)['pauseHotspot'] is True
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')
@@ -0,0 +1,68 @@
import assert from 'node:assert/strict'
import { compile } from '../web/vendor/vue/vue.esm-browser.js'
import { NetworksPage, validNetworks } from '../web/js/networks.js'
const network = (uuid, name, extra = {}) => ({ 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('<GalaxyHotspot'))
assert.ok(NetworksPage.template.includes('<GxDialog v-if="joinOpen"'))
for (const label of ['Cellular data', 'Prefer', 'Join while StarPort is on', 'Pause Galaxy hotspot while joining Wi-Fi'])
assert.ok(NetworksPage.template.includes(label), label)
function instance() {
const vm = { ...NetworksPage.data(), mode: 'local', unauthorized() {} }
for (const [name, fn] of Object.entries(NetworksPage.methods)) vm[name] = fn.bind(vm)
return vm
}
const vm = instance()
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)
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)
assert.equal(sent.length, before)
vm.stop()
@@ -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"]))
@@ -609,6 +609,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; }
@@ -912,3 +915,27 @@ 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__header-btn { min-height: 36px; padding: 0 var(--sp-3); }
.gx-networks__header-actions { margin-left: auto; }
.gx-networks__subhead { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); border-top: 1px solid var(--outline); }
.gx-networks__link-btn { border: 0; padding: 0; background: none; font: inherit; font-size: var(--fs-sm); cursor: pointer; }
.gx-networks__dialog { display: grid; gap: var(--sp-3); }
.gx-networks__label { display: grid; gap: var(--sp-1); font-size: var(--fs-sm); color: var(--on-surface-variant); }
.gx-networks__password { display: flex; gap: var(--sp-2); align-items: center; }
.gx-networks__password .gx-field { flex: 1; min-width: 0; }
.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__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; }
}
@@ -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",
+3 -1
View File
@@ -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({
<Tools v-else-if="route.path === '/tools'" :tools="visibleTools" :mode="state.monitorMode" />
<SettingsPage @nested="ensureBackEntry" ref="activeSettings" v-else-if="route.path === '/developer/connect'" :mode="state.monitorMode" :unauthorized="sessionExpired" initial-section="developer" />
<GalaxyPage v-else-if="route.path === '/galaxy'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
<NetworksPage v-else-if="route.path === '/networks'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
<OnroadLayoutPage ref="activeLayout" v-else-if="['/theme_maker', '/theme_maker/starport', '/appearance'].includes(route.path)" :key="route.path" :projection="route.path === '/theme_maker/starport'" :initial-panel="route.path === '/appearance' ? 'display' : 'widgets'" :mode="state.monitorMode" :unauthorized="sessionExpired" @target="go($event === 'projection' ? '/theme_maker/starport' : '/theme_maker')" @close="routeBack" />
<SettingsRecoveryPage v-else-if="route.path === '/settings/recovery'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
<Logs v-else-if="route.path === '/logs' || route.path.startsWith('/logs/') || ['/troubleshoot', '/manage_tmux'].includes(route.path)" :path="route.path === '/troubleshoot' ? '/logs/troubleshoot' : route.path === '/manage_tmux' ? '/logs/tmux' : route.path" :mode="state.monitorMode" :unauthorized="sessionExpired" :tools="currentTool?.children || []" />
+4 -3
View File
@@ -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: `<div class="gx-settings gx-tunnel">
@@ -24,6 +23,8 @@ export const GalaxyPage = {
</div>
</li>
</ol>
<GalaxyHotspot :mode="mode" :unauthorized="unauthorized" />
<section class="gx-card gx-panel gx-stack"><div class="gx-section__header"><i class="bi bi-wifi" aria-hidden="true"></i><span class="gx-section__title">Galaxy Wi-Fi Hotspot</span></div>
<p>The hotspot, preferred Wi-Fi networks and cellular data are on the Networks page.</p>
<div class="gx-actions"><a class="gx-btn gx-btn--tonal" href="#/networks">Open Networks</a></div></section>
</div>`,
}
+31 -23
View File
@@ -83,34 +83,42 @@ export const GalaxyHotspot = {
}
},
},
template: `<section class="gx-card gx-panel gx-stack"><div class="gx-section__header"><i class="bi bi-wifi" aria-hidden="true"></i><span class="gx-section__title">Galaxy Wi-Fi Hotspot</span></div>
<p>Local Galaxy access for iPhone and Android. No Android Auto, Bluetooth browser support, or cellular connection needed.</p>
template: `<section class="gx-card gx-settings__section gx-hotspot"><div class="gx-section__header"><i class="bi bi-broadcast-pin" aria-hidden="true"></i><span class="gx-section__title">Galaxy Wi-Fi Hotspot</span><span v-if="snapshot" class="gx-chip">{{ snapshot.config.ssid }}</span></div>
<GxState v-if="mode !== 'local'">Connect to your comma to configure the hotspot.</GxState>
<GxState v-else-if="!snapshot && !error" loading>Loading hotspot settings…</GxState>
<template v-if="snapshot && draft">
<GxNotice :busy="snapshot.state === 'starting'" :tone="['error', 'unavailable'].includes(snapshot.state) ? 'warn' : 'info'">Status: {{ snapshot.state }} {{ snapshot.reason }}</GxNotice>
<GalaxySettingRow feedback="draft" :row="switchRow('Broadcast hotspot automatically', draft.enabled)" :index="0"
<GxNotice v-if="['starting', 'error', 'unavailable'].includes(snapshot.state)" class="gx-inset" :busy="snapshot.state === 'starting'" :tone="['error', 'unavailable'].includes(snapshot.state) ? 'warn' : 'info'">Status: {{ snapshot.state }} {{ snapshot.reason }}</GxNotice>
<GalaxySettingRow feedback="draft" :row="switchRow('Broadcast hotspot automatically', draft.enabled, snapshot.config.ssid + ' · Status: ' + snapshot.state + (snapshot.reason ? ' (' + snapshot.reason + ')' : ''))" :index="0"
:busy="busy" :disabled="!snapshot.editable" :save-value="(index, value) => { draft.enabled = value === 'On' }" />
<div class="gx-stack">
<p>Network name: <strong>{{ snapshot.config.ssid }}</strong></p>
<p class="gx-note">Fixed to TheGalaxy- plus the last four characters of your comma dongle ID. Once saved, the switch and password survive restarts.</p>
<label class="gx-field-group">Password <input class="gx-field" :type="showPassword ? 'text' : 'password'" v-model="draft.password" :disabled="busy || !snapshot.editable" maxlength="63" autocomplete="new-password" placeholder="Blank generates a password" @input="saveError = ''" /></label>
<div class="gx-row gx-row--borderless"><div class="gx-row__info"><span class="gx-row__label">Show password</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Show password" v-model="showPassword" :disabled="busy || !snapshot.editable"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<p v-if="!passwordValid" class="gx-note">Use a 12–63 character password without spaces, or leave it blank to generate one.</p>
<div class="gx-settings__controls gx-actions"><button class="gx-btn" type="button" :disabled="!dirty || busy || !snapshot.editable || !passwordValid" @click="save">{{ busy ? 'Saving…' : 'Save hotspot' }}</button></div>
<div class="gx-row gx-hotspot__row">
<div class="gx-row__info">
<label for="gx-hotspot-password" class="gx-row__label">Password</label>
<span class="gx-row__desc" :class="{ 'gx-note--danger': !passwordValid }">12–63 characters without spaces, or leave blank to generate one.</span>
</div>
<div class="gx-actions gx-hotspot__controls">
<input id="gx-hotspot-password" class="gx-field gx-hotspot__field" :type="showPassword ? 'text' : 'password'" v-model="draft.password" :disabled="busy || !snapshot.editable" maxlength="63" autocomplete="new-password" placeholder="Blank generates a password" @input="saveError = ''" />
<button type="button" class="gx-icon-btn" :aria-label="showPassword ? 'Hide password' : 'Show password'" :aria-pressed="showPassword" :disabled="busy || !snapshot.editable" @click="showPassword = !showPassword"><i class="bi" :class="showPassword ? 'bi-eye-slash' : 'bi-eye'" aria-hidden="true"></i></button>
<button class="gx-btn" type="button" :disabled="!dirty || busy || !snapshot.editable || !passwordValid" @click="save">{{ busy ? 'Saving…' : 'Save hotspot' }}</button>
</div>
</div>
<GxNotice v-if="!snapshot.editable">Park before changing hotspot settings.</GxNotice>
<p>Join the network and stay connected if warned of no Internet. Open the address below, then bookmark it.</p>
<div class="gx-actions"><a class="gx-btn gx-btn--tonal" :href="snapshot.url">Open {{ snapshot.url }}</a></div>
<div class="gx-row gx-hotspot__row">
<div class="gx-row__info">
<span class="gx-row__label">Local Galaxy address</span>
<span class="gx-row__desc">Join {{ snapshot.config.ssid }} (keep connected if warned of no Internet), then open or bookmark this link.</span>
</div>
<a class="gx-btn gx-btn--tonal" :href="snapshot.url">Open {{ snapshot.url }}</a>
</div>
<details class="gx-hotspot__details gx-starport-wiki">
<summary>How hotspot access works</summary>
<ul class="gx-install-benefits">
<li><i class="bi bi-power" aria-hidden="true"></i><span>Starts automatically when enabled. Needs the comma on and Wi-Fi available.</span></li>
<li><i class="bi bi-wifi" aria-hidden="true"></i><span>Works standalone, or shares the channel of connected Wi-Fi or Android Auto.</span></li>
<li><i class="bi bi-phone" aria-hidden="true"></i><span>Local access without Internet; no Internet sharing.</span></li>
<li><i class="bi bi-arrow-repeat" aria-hidden="true"></i><span>Network or channel changes may interrupt access. Changing the password or disabling the hotspot disconnects phones.</span></li>
<li><i class="bi bi-globe" aria-hidden="true"></i><span>The public galaxy.firestar.link address still needs Internet and its tunnel.</span></li>
</ul>
</details>
</template>
<ul class="gx-install-benefits">
<li><i class="bi bi-power" aria-hidden="true"></i><span>Starts automatically when enabled. Needs the comma on and Wi-Fi available.</span></li>
<li><i class="bi bi-wifi" aria-hidden="true"></i><span>Works standalone, or shares the channel of connected Wi-Fi or Android Auto.</span></li>
<li><i class="bi bi-phone" aria-hidden="true"></i><span>Local access without Internet; no Internet sharing.</span></li>
<li><i class="bi bi-arrow-repeat" aria-hidden="true"></i><span>Network or channel changes may interrupt access. Changing the password or disabling the hotspot disconnects phones.</span></li>
<li><i class="bi bi-globe" aria-hidden="true"></i><span>The public galaxy.firestar.link address still needs Internet and its tunnel.</span></li>
</ul>
<GxNotice v-if="error || saveError" tone="danger">{{ saveError || error }}</GxNotice><GxNotice v-if="notice" tone="success">{{ notice }}</GxNotice>
<GxNotice v-if="error || saveError" class="gx-inset" tone="danger">{{ saveError || error }}</GxNotice><GxNotice v-if="notice" class="gx-inset" tone="success">{{ notice }}</GxNotice>
</section>`,
}
@@ -0,0 +1,264 @@
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"
import { GxDialog } from "./dialog.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) {
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)) &&
(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 })
export const NetworksPage = {
name: "NetworksPage",
components: { GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog },
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
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' },
joinOpen() { return this.hiddenOpen || !!this.joiningSsid },
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' }) : ''
},
cellularDetail() {
const cellular = this.snapshot.cellular
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.'
},
},
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.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; 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 = item.ssid
this.joinPassword = ''
this.showJoinPassword = false
},
openHidden() {
this.joiningSsid = ''
this.joinPassword = ''
this.hiddenSsid = ''
this.showJoinPassword = false
this.hiddenOpen = true
},
closeJoin() { if (!this.busy) this.cancelJoin() },
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()
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 = this.joining ? '' : error.message
} finally {
if (this.active && generation === this.generation) this.timer = setTimeout(() => this.refresh(), this.joining ? 3000 : 5000)
}
},
async send(body) {
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', { 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)
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: `<section class="gx-driving gx-networks" aria-label="Networks">
<header class="gx-settings__header gx-page-header"><div><h2>Networks</h2><p>Wi-Fi priority, cellular data, and local hotspot access.</p></div></header>
<GxState v-if="mode !== 'local'">Connect to your comma to manage its networks.</GxState>
<GxState v-else-if="!snapshot && !error" loading>Loading network settings…</GxState>
<template v-if="snapshot">
<GxNotice v-if="!snapshot.editable" tone="warn">Park before changing network settings.</GxNotice>
<GxNotice v-if="snapshot.lastJoin?.state === 'joining'" tone="info" busy>Joining {{ snapshot.lastJoin.ssid }}. The Galaxy hotspot pauses for up to 30 seconds; your phone should reconnect on its own and this page will update.</GxNotice>
<GxNotice v-else-if="snapshot.lastJoin?.state === 'joined'" tone="success">Joined {{ snapshot.lastJoin.ssid }}.</GxNotice>
<GxNotice v-else-if="snapshot.lastJoin?.state === 'failed'" tone="danger">Couldn't join {{ snapshot.lastJoin.ssid }}. {{ snapshot.lastJoin.error }}</GxNotice>
<section class="gx-card gx-settings__section"><div class="gx-section__header"><i class="bi bi-arrow-left-right" aria-hidden="true"></i><span class="gx-section__title">Connection</span><span class="gx-chip">{{ linkName }}<template v-if="changed"> · {{ changed }}</template></span></div>
<GalaxySettingRow :row="choiceRow('Prefer', snapshot.prefer === 'cellular' ? 'Cellular' : 'Wi-Fi', ['Wi-Fi', 'Cellular'], 'Used when both are available; apps reconnect automatically.')" :index="0"
:busy="busy" :disabled="!snapshot.editable" :save-value="(index, value) => send({ action: 'prefer', value: value === 'Cellular' ? 'cellular' : 'wifi' })" />
<GalaxySettingRow :row="switchRow('Cellular data', snapshot.cellular.enabled, cellularDetail)" :index="1"
:busy="busy" :disabled="!snapshot.editable" :save-value="(index, value) => send({ action: 'cellular', value: value === 'On' })" />
</section>
<section class="gx-card gx-settings__section"><div class="gx-section__header"><i class="bi bi-wifi" aria-hidden="true"></i><span class="gx-section__title">Saved Wi-Fi networks</span><span v-if="snapshot.networks.length" class="gx-section__count">{{ snapshot.networks.length }}</span></div>
<p v-if="!snapshot.networks.length" class="gx-empty">No saved Wi-Fi networks yet. Scan for nearby networks below to join one.</p>
<p v-else class="gx-note gx-networks__caption">Joined in priority order when in range.</p>
<div v-for="(network, index) in snapshot.networks" :key="network.uuid" class="gx-networks__item">
<div class="gx-row gx-networks__row">
<button type="button" class="gx-row__info gx-networks__toggle" :aria-expanded="isOpen(network)" @click="toggleNetwork(network.uuid)">
<span class="gx-row__label">{{ index + 1 }}. {{ network.name }}</span>
<span class="gx-row__desc">{{ networkSummary(network) }}</span>
</button>
<div class="gx-actions">
<button type="button" class="gx-icon-btn" :aria-label="'Move ' + network.name + ' up'" :disabled="busy || !snapshot.editable || index === 0" @click="move(index, -1)"><i class="bi bi-arrow-up" aria-hidden="true"></i></button>
<button type="button" class="gx-icon-btn" :aria-label="'Move ' + network.name + ' down'" :disabled="busy || !snapshot.editable || index === snapshot.networks.length - 1" @click="move(index, 1)"><i class="bi bi-arrow-down" aria-hidden="true"></i></button>
<button v-if="snapshot.networks.length > 1" type="button" class="gx-icon-btn" :aria-label="(isOpen(network) ? 'Collapse ' : 'Configure ') + network.name" :aria-expanded="isOpen(network)" @click="toggleNetwork(network.uuid)"><i class="bi" :class="isOpen(network) ? 'bi-chevron-up' : 'bi-chevron-down'" aria-hidden="true"></i></button>
</div>
</div>
<div v-show="isOpen(network)" class="gx-networks__details">
<GalaxySettingRow :row="switchRow('Join automatically', network.autoJoin)" :index="index"
:busy="busy" :disabled="!snapshot.editable" :save-value="(i, value) => setNetwork(network, 'autoJoin', value === 'On')" />
<GalaxySettingRow :row="switchRow('Join while StarPort is on', network.whileDriving, 'When off, stays on the current connection until the drive ends.')" :index="index"
:busy="busy" :disabled="!snapshot.editable || !network.autoJoin" :save-value="(i, value) => setNetwork(network, 'whileDriving', value === 'On')" />
<GalaxySettingRow :row="choiceRow('Data limit', network.metered, ['Auto', 'Metered', 'Unmetered'], 'Metered networks skip large uploads.')" :index="index"
:busy="busy" :disabled="!snapshot.editable" :save-value="(i, value) => setNetwork(network, 'metered', value)" />
<div class="gx-row gx-networks__saved-actions">
<div class="gx-row__info"><span class="gx-row__label">Connection</span><span class="gx-row__desc">{{ forgetUuid === network.uuid ? (network.connected ? 'The comma will leave this network now.' : 'Tap again to forget this network.') : network.connected ? 'Currently active' : network.signal != null ? 'Available in range' : 'Out of range' }}</span></div>
<div class="gx-actions">
<button v-if="!network.connected && network.signal != null" type="button" class="gx-btn gx-btn--tonal" :disabled="busy || !snapshot.editable" @click="connectSaved(network)">Connect</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy || !snapshot.editable" @click="forgetSaved(network)">{{ forgetUuid === network.uuid ? 'Confirm forget' : 'Forget' }}</button>
<button v-if="forgetUuid === network.uuid" type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="forgetUuid = null">Keep</button>
</div>
</div>
</div>
</div>
<GalaxySettingRow :row="switchRow('Pause Galaxy hotspot while joining Wi-Fi', snapshot.pauseHotspot, 'Briefly pauses the hotspot during a drive so joining Wi-Fi does not disturb StarPort.')" :index="0"
:busy="busy" :disabled="!snapshot.editable" :save-value="(index, value) => send({ action: 'pauseHotspot', value: value === 'On' })" />
</section>
<section class="gx-card gx-settings__section"><div class="gx-section__header"><i class="bi bi-broadcast" aria-hidden="true"></i><span class="gx-section__title">Nearby networks</span><span v-if="adding && availableNetworks.length" class="gx-section__count">{{ availableNetworks.length }}</span>
<div class="gx-actions gx-networks__header-actions">
<button type="button" class="gx-btn gx-btn--tonal gx-networks__header-btn" :disabled="busy || !snapshot.editable" @click="adding ? scanNetworks() : openScan()"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i> {{ busy && adding ? 'Scanning…' : adding ? 'Rescan' : 'Scan' }}</button>
<button v-if="adding" type="button" class="gx-btn gx-btn--tonal gx-networks__header-btn" :disabled="busy" @click="closeScan">Done</button>
</div></div>
<p v-if="!adding" class="gx-empty">Scan to find Wi-Fi networks to join.</p>
<p v-else-if="!availableNetworks.length" class="gx-empty" role="status">{{ busy ? 'Scanning for nearby Wi-Fi networks…' : 'No new Wi-Fi networks found nearby.' }}</p>
<template v-else><div v-for="item in availableNetworks" :key="item.ssid" class="gx-row gx-networks__row">
<div class="gx-row__info">
<span class="gx-row__label"><i class="bi" :class="item.security === 'open' ? 'bi-wifi' : 'bi-lock-fill'" aria-hidden="true"></i> {{ item.ssid }}</span>
<span class="gx-row__desc">Signal {{ item.signal }}% · {{ item.security === 'open' ? 'Open' : item.security === 'unsupported' ? 'Enterprise Wi-Fi (unsupported)' : 'Password required' }}</span>
</div>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy || !snapshot.editable || item.security === 'unsupported'" @click="selectAvailable(item)">Join</button>
</div></template>
<div class="gx-networks__subhead"><span class="gx-row__desc">Network not listed?</span><button type="button" class="gx-link gx-networks__link-btn" :disabled="busy || !snapshot.editable" @click="openHidden">Join hidden network</button></div>
</section>
<GxDialog v-if="joinOpen" :inert="busy" labelledby="gx-networks-join-title" describedby="gx-networks-join-note" @close="closeJoin">
<form class="gx-networks__dialog" @submit.prevent="canSubmitJoin && submitJoin()">
<h3 id="gx-networks-join-title">{{ hiddenOpen ? 'Join hidden network' : 'Join ' + joiningSsid }}</h3>
<p id="gx-networks-join-note" class="gx-row__desc">Joining pauses the Galaxy hotspot for up to 30 seconds. If your phone is on it, it reconnects afterwards.</p>
<label v-if="hiddenOpen" class="gx-networks__label">Network name (SSID)
<input class="gx-field" type="text" v-model="hiddenSsid" maxlength="64" autocomplete="off" autofocus />
</label>
<label class="gx-networks__label">{{ hiddenOpen ? 'Password (blank if open)' : 'Password · 8–64 characters' }}
<span class="gx-networks__password">
<input class="gx-field" :type="showJoinPassword ? 'text' : 'password'" v-model="joinPassword" maxlength="64" autocomplete="new-password" :autofocus="!hiddenOpen" />
<button type="button" class="gx-icon-btn" :aria-label="showJoinPassword ? 'Hide password' : 'Show password'" :aria-pressed="showJoinPassword" @click="showJoinPassword = !showJoinPassword"><i class="bi" :class="showJoinPassword ? 'bi-eye-slash' : 'bi-eye'" aria-hidden="true"></i></button>
</span>
</label>
<GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
<div class="gx-actions gx-settings__controls"><button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="cancelJoin">Cancel</button>
<button type="submit" class="gx-btn" :disabled="busy || !snapshot.editable || !canSubmitJoin">{{ busy ? 'Joining…' : 'Join' }}</button></div>
</form>
</GxDialog>
</template>
<GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
<GalaxyHotspot v-if="mode === 'local'" :mode="mode" :unauthorized="unauthorized" />
</section>`,
}
@@ -73,6 +73,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<svg ref="preview" class="gx-layout__preview" :style="{'--layout-glow': state.profile === 'compact' ? '4px' : '14px'}" :viewBox="'0 0 ' + profile.width + ' ' + profile.height" :width="profile.width" :height="profile.height"
@pointermove="moveDrag" @pointerup="endDrag" @pointercancel="cancelDrag" @lostpointercapture="cancelDrag"
role="group" :aria-label="projection ? 'StarPort layout preview' : (state.profile === 'large' ? 'Big' : 'Small') + ' layout preview'">
<g id="gx-layout-stage">
<image v-if="nativeBackdropReady" :href="state.backdrop.url" :width="profile.width" :height="profile.height" preserveAspectRatio="none" data-preview-source="device-backdrop" />
<template v-else>
<rect width="100%" height="100%" fill="#252b32" />
@@ -160,8 +161,12 @@ export const ONROAD_LAYOUT_TEMPLATE = `
:y1="guide.axis === 'y' ? guide.value : 0" :y2="guide.axis === 'y' ? guide.value : profile.height" vector-effect="non-scaling-stroke" />
</g>
<rect v-if="state.showEditingAids && selectionBox" class="gx-layout__outline" :x="selectionBox.x" :y="selectionBox.y" :width="selectionBox.width" :height="selectionBox.height" rx="4" fill="none" stroke="#d4baff" stroke-width="2" vector-effect="non-scaling-stroke" />
</g>
</svg>
</div>
<Teleport to="body"><div v-if="loupe" class="gx-layout__loupe" aria-hidden="true" :style="loupe.style">
<svg :viewBox="loupe.viewBox" preserveAspectRatio="xMidYMid meet"><use href="#gx-layout-stage" /></svg>
</div></Teleport>
<!-- The Small screen is too short to carry the chip over the layout; it sits underneath instead. -->
<span v-if="!projection && state.showFavoriteZones && state.showEditingAids && state.profile === 'compact'" class="gx-layout__stage-chip gx-layout__stage-chip--below" aria-hidden="true"><i class="bi bi-grid-3x3-gap"></i>Tap areas</span>
<GxCollapse><div v-show="state.tipsOpen" id="gx-layout-tips" class="gx-layout__tips">
@@ -564,6 +564,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) => {
@@ -1250,6 +1278,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 }
+42 -1
View File
@@ -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():
@@ -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'
+241
View File
@@ -0,0 +1,241 @@
"""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
from collections.abc import Callable
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('<L', int(fields[2], 16)))))
except (ValueError, OSError):
continue
return sorted(routes)
def gateway_hardware(link: str, gateway: str, text: str | None = None) -> 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: Callable[[str], tuple | None] = signature
connections: Callable[[], set[Connection]] = list_connections
close: Callable[[Connection], bool] = 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()
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)
if __name__ == '__main__':
main()
@@ -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()
+143 -1
View File
@@ -60,6 +60,10 @@ 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
DRIVE_JOIN_TIMEOUT_S = 20.0
DEVICE_STATE_FAILED = 120
class NetworkError(RuntimeError):
@@ -106,6 +110,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 +239,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:
@@ -411,15 +477,91 @@ 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()
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 _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_FAILED or (started and state == DEVICE_STATE_DISCONNECTED):
return "failed" # refused, or stopped because the car link stalled
if state >= DEVICE_STATE_PREPARE:
started = True
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:
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:
+27 -7
View File
@@ -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:
@@ -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()
@@ -415,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"
@@ -1878,13 +1884,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
@@ -2123,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
@@ -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
@@ -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()
@@ -558,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)
@@ -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:
@@ -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:
@@ -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
@@ -1328,3 +1417,66 @@ 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 == []
@pytest.mark.parametrize("states", [(120,), (40, 120), (40, 30)])
def test_drive_join_resumes_hotspot_promptly_after_failure(monkeypatch, states):
from openpilot.starpilot.system.starport import network
now, reads, order, sets = [0.0], [0], [], []
def get(lease, path, interface, name):
if name == "AvailableConnections":
return ["/settings/home"]
reads[0] += 1
return network.DEVICE_STATE_DISCONNECTED if reads[0] == 1 else states[min(reads[0] - 2, len(states) - 1)]
def call(lease, path, interface, member, *args):
if member == "GetSettings":
return ({"connection": {"uuid": ("s", "home")}},)
monkeypatch.setattr(network.NetworkLease, "_get", get)
monkeypatch.setattr(network.NetworkLease, "_call", call)
monkeypatch.setattr(network.NetworkLease, "_set", lambda lease, *args: sets.append(args[2:]))
monkeypatch.setattr(network.time, "monotonic", lambda: now[0])
monkeypatch.setattr(network.time, "sleep", lambda seconds: now.__setitem__(0, now[0] + seconds))
lease = network.NetworkLease(lambda *a, **k: None, "wlan0")
lease.device_path = "/dev/wlan0"
lease.autoconnect_paused = True
result = lease.drive_join(lambda uuid: True, before=lambda: order.append("pause") or True,
after=lambda: order.append("resume"))
assert result == "failed"
assert now[0] == len(states) * 0.25
assert reads[0] == len(states) + 1
assert order == ["pause", "resume"]
assert sets == [("Autoconnect", "b", False)]
@@ -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")]
@@ -0,0 +1,115 @@
"""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
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
@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})]
+1 -1
View File
@@ -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 []
@@ -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")]
neighbors = "IP address HW type Flags HW address Mask Device\n10.10.99.2 0x1 0x2 ac:bc:32:ab:eb:8f * wlan0\n"
assert netwatch.gateway_hardware("wlan0", "10.10.99.2", neighbors) == "ac:bc:32:ab: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")
@@ -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",
+1 -1
View File
@@ -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]: