diff --git a/openpilot/starpilot/galaxy/controller_diagnostics.py b/openpilot/starpilot/galaxy/controller_diagnostics.py index 25f8ca1daf..e6d69fcb1a 100644 --- a/openpilot/starpilot/galaxy/controller_diagnostics.py +++ b/openpilot/starpilot/galaxy/controller_diagnostics.py @@ -1,7 +1,7 @@ """Capture the USB and Bluetooth input inventory without opening any event device.""" from base64 import b64encode -from datetime import datetime, timezone +from datetime import UTC, datetime import hashlib from io import BytesIO import json @@ -49,7 +49,7 @@ def controller_input_report(): def controller_capture(): - report = {'schemaVersion': 1, 'capturedAt': datetime.now(timezone.utc).isoformat(timespec='seconds'), **controller_input_report()} + report = {'schemaVersion': 1, 'capturedAt': datetime.now(UTC).isoformat(timespec='seconds'), **controller_input_report()} output = BytesIO() with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive: archive.writestr('bluetooth-log.json', json.dumps(report, indent=2) + '\n') diff --git a/openpilot/starpilot/galaxy/local_access.py b/openpilot/starpilot/galaxy/local_access.py index c8d7cead04..a62fba4ccf 100644 --- a/openpilot/starpilot/galaxy/local_access.py +++ b/openpilot/starpilot/galaxy/local_access.py @@ -3,7 +3,7 @@ from base64 import b64encode from concurrent.futures import ThreadPoolExecutor from io import BytesIO -from datetime import datetime, timezone +from datetime import UTC, datetime from ipaddress import IPv4Address, ip_network import json import re @@ -82,22 +82,22 @@ class LocalAccess: DISCOVERY_UNIT = 'galaxy-lan-discovery.service' -DISCOVERY_MESSAGE = re.compile( - r'(Galaxy Wi-Fi discovery available on [0-9]{1,3} local interface\(s\)|' +DISCOVERY_MESSAGE = re.compile(''.join(( + r'(Galaxy Wi-Fi discovery available on [0-9]{1,3} local interface\(s\)|', r'Wi-Fi discovery unavailable: [A-Za-z][A-Za-z0-9_]{0,63}|LAN publisher cleanup failed)\Z', -) +))) BLE_UNIT = 'galaxy-ble-fork.service' -BLE_MESSAGE = re.compile( - r'(Pairing credentials changed; [0-9]{1,4} phone\(s\) paired|Phone claimed pairing window|' - r'Galaxy BLE handshake challenge requested; active sessions=[0-9]{1,4}|' - r'Rejected invalid or unauthenticated BLE message|Notification transfer interrupted \([A-Za-z0-9_]{1,64}\); reconnect to check request outcome|' - r'BLE advertisement released by BlueZ; bridge will re-register after restart|Registering Galaxy BLE advertisement|' - r'Starting Galaxy bridge pid=[0-9]{1,10} source=[0-9a-f]{12}|' - r'Galaxy BLE bridge ready on /org/bluez/hci[0-9]{1,3}; forwarding to localhost:[0-9]{1,5}|' +BLE_MESSAGE = re.compile(''.join(( + r'(Pairing credentials changed; [0-9]{1,4} phone\(s\) paired|Phone claimed pairing window|', + r'Galaxy BLE handshake challenge requested; active sessions=[0-9]{1,4}|', + r'Rejected invalid or unauthenticated BLE message|Notification transfer interrupted \([A-Za-z0-9_]{1,64}\); reconnect to check request outcome|', + r'BLE advertisement released by BlueZ; bridge will re-register after restart|Registering Galaxy BLE advertisement|', + r'Starting Galaxy bridge pid=[0-9]{1,10} source=[0-9a-f]{12}|', + r'Galaxy BLE bridge ready on /org/bluez/hci[0-9]{1,3}; forwarding to localhost:[0-9]{1,5}|', r'Stopping Galaxy bridge; clearing ready status and Bluetooth sessions)\Z', -) +))) INTERFACE_NAME = re.compile(r'[A-Za-z0-9_.:-]{1,32}\Z') @@ -194,7 +194,7 @@ def _service_capture(run, unit, pattern, label): if isinstance(message, str) and pattern.fullmatch(message): stamp = entry.get('__REALTIME_TIMESTAMP', '') if isinstance(stamp, str) and re.fullmatch(r'[0-9]{1,16}', stamp): - timestamp = datetime.fromtimestamp(int(stamp) / 1e6, timezone.utc).isoformat(timespec='seconds') + timestamp = datetime.fromtimestamp(int(stamp) / 1e6, UTC).isoformat(timespec='seconds') message = f'{timestamp} {message}' events.append(message) except (ValueError, OSError, OverflowError): @@ -207,7 +207,7 @@ def _service_capture(run, unit, pattern, label): def connection_capture(addresses, *, configuration_allowed=None, run=subprocess.run): lines = ['StarPilot connection capture', 'Capture schema: 2', - f'Captured at (UTC): {datetime.now(timezone.utc).isoformat(timespec="seconds")}', + f'Captured at (UTC): {datetime.now(UTC).isoformat(timespec="seconds")}', 'Galaxy endpoint: HTTP port 8082', 'Bonjour service: _sp-galaxy._tcp.local.'] try: with open('/proc/uptime') as stream: diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index 3b18a92d7f..5cb318aea2 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -1098,7 +1098,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe except ValueError: route_key = '' try: - result = navigation_owner().snapshot(route_key if re.fullmatch(r'[0-9a-hjkmnp-tv-z]{12}', route_key) else None) + result = navigation_owner().snapshot(route_key if re.fullmatch(r'[0-9a-f]{16}', route_key) else None) except (OSError, ValueError, RuntimeError): self.json(503, {'error': 'Navigation status is unavailable'}) else: @@ -1763,7 +1763,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe '/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink', '/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete', '/api/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/software/action', '/api/drives/ignore', - '/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete', '/api/crash-reports/delete', + '/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete', + '/api/crash-reports/delete', '/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action', '/api/toyota-tools/action', '/api/vehicle-selection/preview', '/api/vehicle-selection/confirm'): self.json(405, {'error': 'Method unavailable'}) @@ -2057,9 +2058,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe simulation_busy.set() try: threading.Thread(target=capture_simulation, name='sentry-simulation', daemon=True).start() - except RuntimeError: + except RuntimeError as error: simulation_busy.clear() - raise NotificationUnavailable("Could not start Sentry simulation") + raise NotificationUnavailable("Could not start Sentry simulation") from error last_simulation[0] = clock() result = notification_owner.snapshot() else: diff --git a/openpilot/starpilot/galaxy/tests/test_diagnostic_http.py b/openpilot/starpilot/galaxy/tests/test_diagnostic_http.py index 7bcb204600..c2611a367b 100644 --- a/openpilot/starpilot/galaxy/tests/test_diagnostic_http.py +++ b/openpilot/starpilot/galaxy/tests/test_diagnostic_http.py @@ -1,4 +1,3 @@ -from unittest.mock import Mock, patch """Authenticated diagnostics over the same local and remote HTTP handler.""" import http.client @@ -8,6 +7,7 @@ import tempfile import threading from types import SimpleNamespace import unittest +from unittest.mock import Mock, patch from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.server import make_server @@ -75,7 +75,7 @@ class DiagnosticHTTPTest(unittest.TestCase): def test_support_code_captures_on_device_and_confirms_delivery(self): _, _, self.cookie = self.request('/api/auth/session') - code = 'ab12' * 3 + code = 'ab12' * 4 path = '/api/companion/support-ticket' def post(action): return self.request(path, method='POST', payload={'code': code, 'action': action}) @@ -84,7 +84,7 @@ class DiagnosticHTTPTest(unittest.TestCase): receipt = Mock(status_code=200) receipt.json.return_value = {'sent': True} with patch('requests.post', side_effect=[ticket, ticket, receipt]) as relay: - self.assertEqual(post('check')[1]['title'], 'Lost network') + self.assertEqual(post('check')[:2], (200, {'kind': 'connection', 'title': 'Lost network'})) self.assertEqual(post('send')[:2], (200, {'sent': True})) self.assertTrue(relay.call_args.kwargs['json']['archive'].startswith('UEsD')) self.assertFalse(relay.call_args.kwargs['allow_redirects']) diff --git a/openpilot/starpilot/galaxy/tests/test_edit_panel_reveal.mjs b/openpilot/starpilot/galaxy/tests/test_edit_panel_reveal.mjs index 78ce53241b..ba8be86e78 100644 --- a/openpilot/starpilot/galaxy/tests/test_edit_panel_reveal.mjs +++ b/openpilot/starpilot/galaxy/tests/test_edit_panel_reveal.mjs @@ -53,5 +53,5 @@ scrolls.length = 0 delayedAlign() assert.deepEqual(scrolls, [], "a delayed alignment leaves the Widgets scroll position alone") -assert.match(ONROAD_LAYOUT_TEMPLATE, /@click="openEditPanel\(\)">Edit/) +assert.match(ONROAD_LAYOUT_TEMPLATE, /@click="state\.inspectorPanel === 'lead' \? revealEditPanel\(\) : openEditPanel\(\)">Edit/) globalThis.setTimeout = realTimeout diff --git a/openpilot/starpilot/galaxy/tests/test_galaxy_access.mjs b/openpilot/starpilot/galaxy/tests/test_galaxy_access.mjs index 3d61ea94e4..830c594438 100644 --- a/openpilot/starpilot/galaxy/tests/test_galaxy_access.mjs +++ b/openpilot/starpilot/galaxy/tests/test_galaxy_access.mjs @@ -64,8 +64,8 @@ try { for (const tile of tiles) tile.props.onClick() nodes.find(item => item.type === 'button' && item.text === 'Get help').props.onClick() assert.deepEqual(visits, ['/networks', '/bluetooth', '/logs/help']) - assert.equal(requests.length, 1, 'A browser reads remote pairing status without polling Android internet-sharing status') - assert.equal(requests[0][0], './api/galaxy/status') + assert.deepEqual(requests.map(([path]) => path).sort(), ['./api/galaxy/qr.svg', './api/galaxy/status'], + 'A browser reads the pairing status and QR code without polling Android internet-sharing status') assert.equal(vm.url, link, 'Remote link reaches the web installer') const steps = vm.$.subTree.children.find(child => child.props?.class === 'gx-steps') const remote = steps.children.find(child => child.type === RemoteAccess).component.proxy diff --git a/openpilot/starpilot/galaxy/tests/test_preview_contract.py b/openpilot/starpilot/galaxy/tests/test_preview_contract.py index d80ec88dc1..85797a9858 100644 --- a/openpilot/starpilot/galaxy/tests/test_preview_contract.py +++ b/openpilot/starpilot/galaxy/tests/test_preview_contract.py @@ -18,8 +18,10 @@ 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", "/networks", "/system", - "/theme_maker", "/tuning", "/starport"]) + ["/cameras", "/galaxy", "/manage_models", "/navigation", "/system", "/theme_maker", "/tuning", "/starport"]) + galaxy = next(tool for tool in catalog["tools"] if tool["path"] == "/galaxy") + self.assertEqual([(tool["path"], tool["availability"]) for tool in galaxy["children"]], + [("/networks", "local-only"), ("/bluetooth", "local-only")]) 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"])) self.assertTrue(all(tool["name"] and tool["description"] and tool["icon"] for tool in catalog["tools"])) diff --git a/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py b/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py index 554aa40712..292d795f83 100644 --- a/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py +++ b/openpilot/starpilot/galaxy/tests/test_sentry_notifications_http.py @@ -60,6 +60,10 @@ class NotificationHTTPTests(unittest.TestCase): self.assertEqual(photos, []) self.assertEqual(request({'action': 'simulate'}, cookie)[0], 403) parked[0] = True + self.assertEqual(request(test, cookie, test_route)[0], 503) + self.assertEqual(request({'action': 'configure', 'channel': 'appPush', 'enabled': True, + 'url': 'https://relay.example.test', 'token': ''}, cookie)[0], 200) + photos.clear() self.assertEqual(request(test, cookie, test_route)[:2], (200, {'queued': True})) self.assertEqual(photos, ['cabin']) event_id = next(iter(owner.test_photos)) diff --git a/openpilot/starpilot/system/starport/frame_source.py b/openpilot/starpilot/system/starport/frame_source.py index 0846166cc2..f7927d1afd 100644 --- a/openpilot/starpilot/system/starport/frame_source.py +++ b/openpilot/starpilot/system/starport/frame_source.py @@ -124,6 +124,20 @@ def luma_summary(frame: Frame, left: int, top: int, width: int, height: int) -> return {"mean": round(mean, 1), "std": round(spread, 1), "dark_pct": round(100 * dark / count, 1), "samples": count} +def frame_brightness(frame, mode) -> dict: + """Brightness of the last sent frame inside the area the car shows, and across the whole frame, for the stats log.""" + if frame is None or mode is None or not mode.width or not mode.height: + return {} + sx, sy = frame.width / mode.width, frame.height / mode.height + margin_w, margin_h = mode.margin_width or 0, mode.margin_height or 0 + left = mode.content_left if mode.content_left is not None else margin_w // 2 + top = mode.content_top if mode.content_top is not None else margin_h - margin_h // 2 + visible = luma_summary(frame, round(left * sx), round(top * sy), round((mode.width - margin_w) * sx), + round((mode.height - margin_h) * sy)) + whole = luma_summary(frame, 0, 0, frame.width, frame.height) + return {"luma_visible": visible, "luma_frame": whole} if visible else {} + + def fit_content(source_w: int, source_h: int, width: int, height: int, margin_w: int, margin_h: int) -> tuple[int, int, int, int]: """Largest undistorted rectangle for the source inside the receiver's visible area. diff --git a/openpilot/starpilot/system/starport/reachability.py b/openpilot/starpilot/system/starport/reachability.py index af8e8d071e..eb74f53ea4 100644 --- a/openpilot/starpilot/system/starport/reachability.py +++ b/openpilot/starpilot/system/starport/reachability.py @@ -1,5 +1,8 @@ """Classify live and logged connection failures to select retry delays.""" +import errno +import socket + ASLEEP = "asleep" # the car did not answer a page at all: off, or still waking NOT_READY = "not_ready" # the car answered, but its Android Auto service or Wi-Fi handshake is not up yet LOCAL = "local" # this comma's own Bluetooth stack refused or was busy; the car says nothing @@ -53,3 +56,27 @@ def retry_delay(reach: str, attempt: int, standard: float) -> float: def keeps_cached_channel(reach: str) -> bool: """A sleeping car says nothing about which RFCOMM channel is right, so its cached channel is kept.""" return reach in (ASLEEP, LOCAL) + + +def _open_projection(ip: str, ports: list[int], advertised: int, local_ip: str, log) -> socket.socket: + error: OSError | None = None + for port in ports: + try: + sock = socket.create_connection((ip, port), timeout=5.0, source_address=(local_ip, 0) if local_ip else None) + except OSError as failure: + error = error or failure # the first port's failure decides how patiently to retry + continue + if port != advertised: + log("tcp_port_fallback", advertised=advertised, port=port) + return sock + assert error is not None + raise error + +def _tcp_failure_kind(error: OSError) -> str: + if isinstance(error, (TimeoutError, socket.timeout)): + return "timeout" + if isinstance(error, ConnectionRefusedError): + return "refused" + if getattr(error, "errno", None) in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, errno.EHOSTDOWN): + return "unreachable" + return "other" diff --git a/openpilot/starpilot/system/starport/supervisor.py b/openpilot/starpilot/system/starport/supervisor.py index 69a2ff4e4a..4da7980227 100644 --- a/openpilot/starpilot/system/starport/supervisor.py +++ b/openpilot/starpilot/system/starport/supervisor.py @@ -26,8 +26,9 @@ from openpilot.starpilot.system.starport.bootstrap import MODERN_MAJOR, NAMES, B from openpilot.starpilot.system.starport.bugsink_report import PairingAttempt from openpilot.starpilot.system.starport.event_log import EventLog from openpilot.starpilot.system.starport.frame_source import (DEFAULT_PATH as DEFAULT_FRAME_PATH, FLAG_ASYNC_READBACK, FLAG_NV12, - FORMAT_NV12, FrameRequest, luma_summary) + FORMAT_NV12, FrameRequest, frame_brightness) from openpilot.starpilot.system.starport.projection_control import DEFAULT_CONTROL_SOCKET, NATIVE_FOCUS +from openpilot.starpilot.system.starport.reachability import _open_projection, _tcp_failure_kind from openpilot.starpilot.system.starport.radio_watch import (RADIO_CHANGE_WINDOW as RADIO_CHANGE_WINDOW, RADIO_CHECK_INTERVAL as RADIO_CHECK_INTERVAL, SharedRadioWatch) from openpilot.starpilot.system.starport.touch import DEFAULT_TOUCH_SOCKET, TouchEvent @@ -71,31 +72,6 @@ REPORTED_SETTINGS = ("connection", "usb_mode", "view", "encoder", "fps", "bitrat "unacked_video", "patient_tcp", "wired_handsfree", "head_unit_experiments", "head_unit_experiment_rules") -def _open_projection(ip: str, ports: list[int], advertised: int, local_ip: str, log) -> socket.socket: - error: OSError | None = None - for port in ports: - try: - sock = socket.create_connection((ip, port), timeout=5.0, source_address=(local_ip, 0) if local_ip else None) - except OSError as failure: - error = error or failure # the first port's failure decides how patiently to retry - continue - if port != advertised: - log("tcp_port_fallback", advertised=advertised, port=port) - return sock - assert error is not None - raise error - - -def _tcp_failure_kind(error: OSError) -> str: - if isinstance(error, (TimeoutError, socket.timeout)): - return "timeout" - if isinstance(error, ConnectionRefusedError): - return "refused" - if getattr(error, "errno", None) in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, errno.EHOSTDOWN): - return "unreachable" - return "other" - - HANDSFREE_UUID = "0000111e-0000-1000-8000-00805f9b34fb" REFUSED_CAR_HINT_S = 120.0 @@ -104,20 +80,6 @@ def short_uuids(device: dict) -> list[str]: return sorted(uuid[4:8] for uuid in device.get("uuids", []) if uuid.endswith("-0000-1000-8000-00805f9b34fb")) -def frame_brightness(frame, mode) -> dict: - """Brightness of the last sent frame inside the area the car shows, and across the whole frame, for the stats log.""" - if frame is None or mode is None or not mode.width or not mode.height: - return {} - sx, sy = frame.width / mode.width, frame.height / mode.height - margin_w, margin_h = mode.margin_width or 0, mode.margin_height or 0 - left = mode.content_left if mode.content_left is not None else margin_w // 2 - top = mode.content_top if mode.content_top is not None else margin_h - margin_h // 2 - visible = luma_summary(frame, round(left * sx), round(top * sy), round((mode.width - margin_w) * sx), - round((mode.height - margin_h) * sy)) - whole = luma_summary(frame, 0, 0, frame.width, frame.height) - return {"luma_visible": visible, "luma_frame": whole} if visible else {} - - def encoder_preference(configured: str) -> str: return 'hardware' if COMMA_HARDWARE else configured diff --git a/prebuilt.json b/prebuilt.json index 8870fb6872..da9e5f025d 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "d5c1f322228933a75d790d0500dd3135b4d607bb0b7e356411ad52b1f246b079", "schema_version": 1} +{"protected_inventory_sha256": "d408ff0b721469dda343b7c3cff1153f0c5bb1abae234fd11e38797e5bcca571", "schema_version": 1}