From 512ec97f45f61e869f13647eea06c553f5d37518 Mon Sep 17 00:00:00 2001 From: dirwin31 <83434411+dirwin31@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:42:31 -0700 Subject: [PATCH 01/14] Navigation: End navigation when parked at the destination --- openpilot/starpilot/galaxy/server.py | 2 +- openpilot/starpilot/galaxy/settings.py | 26 ++++- .../galaxy/tests/test_evidence_lifecycle.py | 31 ++++++ openpilot/starpilot/navigation/runtime.py | 57 +++++++++- .../navigation/tests/test_route_runtime.py | 101 +++++++++++++++++- .../navigation/tests/test_search_places.py | 2 +- 6 files changed, 212 insertions(+), 7 deletions(-) diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index 4f5cc87241..e769075d84 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -209,7 +209,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe def context_source(params): from openpilot.starpilot.galaxy.settings import LiveContextSource - return LiveContextSource(params, messages=evidence_source, evidence_wait_ms=0) if evidence_source is not None else LiveContextSource(params) + return LiveContextSource(params, messages=evidence_source) if evidence_source is not None else LiveContextSource(params) if parked is None: from openpilot.common.params import Params diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index 9c775ec371..d8b26f3da0 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -247,7 +247,9 @@ class LiveContextSource: timeout = 0 while True: if sm is None: - return False + sm = self._refreshed_snapshot(deadline) + if sm is None: + return False if hasattr(sm, "after_mono_ns"): self.device_after_mono_ns = max(self.device_after_mono_ns, sm.after_mono_ns) self.device_offset_ns = sm.device_offset_ns @@ -282,10 +284,32 @@ class LiveContextSource: remaining_ms = int((deadline - self.wait_clock()) * 1000) if remaining_ms <= 0: return False + if hasattr(sm, "after_mono_ns"): + # A snapshot never advances by itself; one stale or skewed sample must not read as onroad. + sm = self._refreshed_snapshot(deadline) + if sm is None: + return False + continue timeout = min(50, remaining_ms) except (OSError, RuntimeError, AttributeError, TypeError, ValueError, OverflowError): return False + def _refreshed_snapshot(self, deadline): + """Wait for the shared collector's next deviceState and pandaStates, then sample it again. + + Called with self.lock held; it is released while waiting so concurrent Galaxy requests wait in parallel. + """ + refresh = getattr(self.messages, "refresh", None) + remaining_ms = int((deadline - self.wait_clock()) * 1000) + if refresh is None or remaining_ms <= 0: + return None + self.lock.release() + try: + refreshed = refresh(remaining_ms) is True + finally: + self.lock.acquire() + return self._messages() if refreshed and not self.closed else None + def configuration_allowed(self) -> bool: """Allow configuration in effective offroad mode or a fresh stationary Park.""" if self.offroad(): diff --git a/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py b/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py index b2da14254c..ea5947294b 100644 --- a/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py +++ b/openpilot/starpilot/galaxy/tests/test_evidence_lifecycle.py @@ -280,6 +280,37 @@ def test_refresh_updates_cached_onroad_and_reverse_transition(tmp_path): assert not source.thread.is_alive() and messages.socket_closed +def test_stale_sample_waits_for_next_publishers_instead_of_reading_onroad(tmp_path): + messages, source, _ = refresh_readers(tmp_path) + params = NS(get_param_path=lambda key: str(tmp_path / key)) + authority = LiveContextSource(params, source, mono_clock=time.monotonic_ns, + boot_clock=lambda: time.monotonic_ns() + 1_000_000_000, evidence_wait_ms=750) + try: + assert refresh_with_frames(source, messages, {}) + time.sleep(0.4) # Past the Panda TTL: a parked editor's 5 s poll must not flip on one late frame. + timer = threading.Timer(0.1, messages.queue) + timer.start() + assert authority.parked() + timer.join() + time.sleep(0.4) + started = time.monotonic() + assert not authority.parked() # Silent publishers still fail closed once the wait expires. + assert time.monotonic() - started < 1.5 + # Concurrent requests share one authority; their waits overlap instead of queueing on its lock. + results = [] + waiters = [threading.Thread(target=lambda: results.append(authority.parked())) for _ in range(3)] + started = time.monotonic() + for waiter in waiters: + waiter.start() + for waiter in waiters: + waiter.join(timeout=3) + assert results == [False, False, False] + assert time.monotonic() - started < 1.5 + finally: + authority.close() + source.close() + + @pytest.mark.parametrize('frame', [None, {'services': ('deviceState',)}, {'services': ('pandaStates',)}, {'replay': True}]) def test_refresh_requires_both_post_request_publishers(tmp_path, frame): messages, source, authority = refresh_readers(tmp_path) diff --git a/openpilot/starpilot/navigation/runtime.py b/openpilot/starpilot/navigation/runtime.py index ab210202a4..d72a9a4948 100644 --- a/openpilot/starpilot/navigation/runtime.py +++ b/openpilot/starpilot/navigation/runtime.py @@ -7,13 +7,16 @@ import time import uuid from openpilot.starpilot.navigation.owner import ConflictError, NavigationOwner, ValidationError, ROUTE_AVOIDANCES -from openpilot.starpilot.navigation.route_engine import MapboxRouteEngine +from openpilot.starpilot.navigation.route_engine import MapboxRouteEngine, distance from openpilot.starpilot.gps.phone import read_phone_gps from openpilot.starpilot.gps.source import GPS_MAX_AGE_NS, GPS_SERVICES, bearing, select_location ARRIVED_NS = 5_000_000_000 # stopped at the destination this long shows "You have arrived" END_ROUTE_NS = 15_000_000_000 # ...and this long ends navigation, like tapping End navigation +STOPPED_RADIUS_M = 100. # stopped this close to the destination arrives, wherever the route itself ends +PARKED_RADIUS_M = 300. # a drive that ends or starts this close to the destination arrived (garages lose GPS) +DRIVE_END_NS = 5_000_000_000 # the car has been off this long, not a deviceState hiccup def location(sm, now_ns: int, phone_fix=None): @@ -44,6 +47,11 @@ class RouteRuntime: self.arrived_since = 0 self.ended_revision = None self.session = uuid.uuid4().hex + self.drive = 0 + self.drive_fix = None + self.drive_off_since = 0 + self.drive_start_pending = False + self.parked_revision = None def update(self, now_ns: int, position, drive_id: int) -> dict: if position is not None: @@ -53,6 +61,14 @@ class RouteRuntime: if position is None: self.owner.position_store.flush() settings = self.owner.read_routing() + if self._parked_at_destination(now_ns, position, drive_id, settings): + self.parked_revision = settings['revision'] + if self.parked_revision is not None: + if self.parked_revision == settings['revision'] and self.ended_revision != settings['revision']: + self._end_route(settings['revision']) + settings = self.owner.read_routing() + if self.parked_revision != settings['revision'] or self.ended_revision == settings['revision']: + self.parked_revision = None selected = settings['destination'] destination_key = None if selected is None else (selected['id'], selected['longitude'], selected['latitude']) exclusions = tuple(value for key, value in ROUTE_AVOIDANCES.items() if settings[key]) @@ -121,7 +137,9 @@ class RouteRuntime: progress = self.route.progress(coordinates, speed, bearing) fresh = now_ns <= stamp + GPS_MAX_AGE_NS self.off_route_since = (self.off_route_since or now_ns) if fresh and progress.off_route else 0 - self.arrived_since = (self.arrived_since or now_ns) if fresh and progress.arrived else 0 + arriving = progress.arrived or (speed is not None and speed < 2 and + distance(coordinates, (selected['longitude'], selected['latitude'])) < STOPPED_RADIUS_M) + self.arrived_since = (self.arrived_since or now_ns) if fresh and arriving else 0 if self.off_route_since and now_ns - self.off_route_since >= 2_000_000_000: self.route = None self.routes = [] @@ -132,9 +150,42 @@ class RouteRuntime: self._end_route(settings['revision']) result.update(status='arrived' if arrived else 'guiding', instruction=progress.instruction, nextManeuver=progress.next_maneuver, route=self.route.preview(), - controlValid=bool(speed is not None and fresh and drive_id > 0 and not progress.off_route and not progress.arrived and stamp >= drive_id)) + controlValid=bool(speed is not None and fresh and drive_id > 0 and not progress.off_route and not arriving and stamp >= drive_id)) return result + @staticmethod + def _near_destination(settings, coordinates) -> bool: + selected = settings['destination'] + return (selected is not None and coordinates is not None and + distance(coordinates, (selected['longitude'], selected['latitude'])) < PARKED_RADIUS_M) + + def _parked_at_destination(self, now_ns: int, position, drive_id: int, settings) -> bool: + """A parking garage loses GPS before the route ends, so the stopped-at-the-end check never fires there. + A drive that ends near the destination arrived, as does one that starts near it (after a reboot, say).""" + fresh = position is not None and 0 < position[0] <= now_ns <= position[0] + GPS_MAX_AGE_NS + if not drive_id: + if not self.drive: + return False + self.drive_off_since = self.drive_off_since or now_ns + if now_ns - self.drive_off_since < DRIVE_END_NS: + return False + parked = self._near_destination(settings, self.drive_fix) + self.drive, self.drive_fix, self.drive_off_since = 0, None, 0 + return parked + self.drive_off_since = 0 + parked = False + if drive_id != self.drive: + # Where the car was last seen, then the first fix of this drive + self.drive, self.drive_fix, self.drive_start_pending = drive_id, None, True + saved = self.owner.position_store.read() + parked = saved is not None and self._near_destination(settings, (saved['longitude'], saved['latitude'])) + if fresh: + self.drive_fix = position[1] + if self.drive_start_pending: + self.drive_start_pending = False + parked = parked or self._near_destination(settings, position[1]) + return parked + def _end_route(self, revision: str) -> None: # Once per destination; a concurrent change (new destination, Galaxy edit) wins over arrival. if self.ended_revision == revision: diff --git a/openpilot/starpilot/navigation/tests/test_route_runtime.py b/openpilot/starpilot/navigation/tests/test_route_runtime.py index 84117c5f32..41f6f99f19 100644 --- a/openpilot/starpilot/navigation/tests/test_route_runtime.py +++ b/openpilot/starpilot/navigation/tests/test_route_runtime.py @@ -132,6 +132,7 @@ def test_arrival_ends_navigation_after_a_short_stop(tmp_path, route): runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor) def at(t, speed=0.): return runtime.update(t * 1_000_000_000, (t * 1_000_000_000 - 1_000_000, (.01, 0.), speed, 90.), 1_000_000_000) + runtime.update(9_000_000_000, (8_999_000_000, (0., 0.), 5., 90.), 1_000_000_000) # the drive starts away from it at(10, 5.) executor.jobs[0].set_result(route) assert at(11, 5.)['status'] == 'guiding' @@ -146,11 +147,109 @@ def test_arrival_ends_navigation_after_a_short_stop(tmp_path, route): assert at(37)['status'] == 'noDestination' +def guided(tmp_path, route): + owner, executor = configured(tmp_path), Executor() + runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor) + def at(t, coordinates=(.005, 0.), speed=5., drive=1_000_000_000): + fix = None if coordinates is None else (t * 1_000_000_000 - 1_000_000, coordinates, speed, 90.) + return runtime.update(t * 1_000_000_000, fix, drive) + at(10) + executor.jobs[0].set_result(route) + assert at(11)['status'] == 'guiding' + return owner, runtime, at + + +def test_stopping_near_the_destination_arrives_short_of_the_route_end(tmp_path, route): + owner, _runtime, at = guided(tmp_path, route) + # ~110 m short of the pin: a stop at a light, not an arrival + assert at(12, (.009, 0.), 0.)['status'] == 'guiding' + assert at(30, (.009, 0.), 0.)['status'] == 'guiding' and owner.read()['destination'] is not None + # ~55 m short, where a parking lot entrance would be: beyond the route-end check's 40 m + assert at(31, (.0095, 0.), 0.)['status'] == 'guiding' + assert at(36, (.0095, 0.), 0.)['status'] == 'arrived' + assert at(46, (.0095, 0.), 0.)['status'] == 'arrived' + assert owner.read()['destination'] is None + + +def test_drive_ending_in_a_garage_near_the_destination_ends_navigation(tmp_path, route): + owner, _runtime, at = guided(tmp_path, route) + at(12, (.008, 0.), 3.) # last fix ~220 m out, entering the garage + at(13, None) # GPS lost inside + at(20, None, drive=0) + at(24, None, drive=0) + assert owner.read()['destination'] is not None, 'a deviceState hiccup is not the car turning off' + at(25, None, drive=0) + assert owner.read()['destination'] is None + assert at(26, None, drive=0)['status'] == 'noDestination' + + +def test_brief_stop_far_from_the_destination_keeps_navigation(tmp_path, route): + owner, _runtime, at = guided(tmp_path, route) + at(12, (.0, 0.), 0.) # ~1.1 km out: a gas station on the way + at(13, None, drive=0) + at(30, None, drive=0) + assert owner.read()['destination'] is not None + assert at(31, (.0, 0.), drive=31_000_000_000)['status'] == 'routing' + assert owner.read()['destination'] is not None + + +def test_device_state_hiccup_near_the_destination_keeps_navigation(tmp_path, route): + owner, _runtime, at = guided(tmp_path, route) + at(12, (.008, 0.), 10.) + at(13, (.008, 0.), 10., drive=0) + at(16, (.008, 0.), 10., drive=0) + assert at(17, (.0085, 0.), 10.)['status'] == 'routing' + assert owner.read()['destination'] is not None + + +def test_drive_starting_near_the_destination_ends_navigation(tmp_path): + # A reboot in the garage: the saved position is where the car was parked + owner = configured(tmp_path) + owner.position_store.record({'longitude': .008, 'latitude': 0.}) + owner.position_store.flush(force=True) + executor = Executor() + runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor) + assert runtime.update(10_000_000_000, None, 9_000_000_000)['status'] == 'noDestination' + assert owner.read()['destination'] is None and not executor.jobs + + +def test_first_fix_near_the_destination_ends_navigation(tmp_path): + owner = configured(tmp_path) + executor = Executor() + runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor) + assert runtime.update(10_000_000_000, None, 9_000_000_000)['status'] == 'waitingForLocation' + runtime.update(11_000_000_000, (10_999_000_000, (.008, 0.), 2., 90.), 9_000_000_000) + assert owner.read()['destination'] is None + # Only the drive's first fix counts: a destination picked later is routed even nearby + owner.select({'name': 'Next door', 'longitude': .009, 'latitude': 0.}, owner.read()['revision'], True) + assert runtime.update(12_000_000_000, (11_999_000_000, (.008, 0.), 2., 90.), 9_000_000_000)['status'] == 'routing' + + +def test_parked_arrival_retries_after_clear_io_failure(tmp_path, monkeypatch, route): + owner, _runtime, at = guided(tmp_path, route) + clear = owner.clear + calls = 0 + def fail_once(*args): + nonlocal calls + calls += 1 + if calls == 1: + raise OSError('temporary write failure') + return clear(*args) + monkeypatch.setattr(owner, 'clear', fail_once) + at(12, (.008, 0.), 3.) + at(13, None, drive=0) + at(18, None, drive=0) + assert owner.read()['destination'] is not None + at(19, None, drive=0) + assert calls == 2 and owner.read()['destination'] is None + + def test_arrival_does_not_override_a_newer_destination(tmp_path, route): owner, executor = configured(tmp_path), Executor() runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor) def at(t): return runtime.update(t * 1_000_000_000, (t * 1_000_000_000 - 1_000_000, (.01, 0.), 0., 90.), 1_000_000_000) + runtime.update(9_000_000_000, (8_999_000_000, (0., 0.), 5., 90.), 1_000_000_000) at(10) executor.jobs[0].set_result(route) at(11) @@ -361,7 +460,7 @@ def test_saved_origin_failure_backoff_and_destination_change(tmp_path, monkeypat def test_unknown_speed_does_not_arrive_or_authorize_control(tmp_path, route): owner = configured(tmp_path) runtime = RouteRuntime(owner, executor=Executor()) - runtime.update(10_000_000_000, (10_000_000_000, (.01, 0.), None, None), 1) + runtime.update(10_000_000_000, (10_000_000_000, (0., 0.), None, None), 1) runtime.route = route for second in (11, 20, 40): now = second * 1_000_000_000 diff --git a/openpilot/starpilot/navigation/tests/test_search_places.py b/openpilot/starpilot/navigation/tests/test_search_places.py index ce4be065da..9ba81abc84 100644 --- a/openpilot/starpilot/navigation/tests/test_search_places.py +++ b/openpilot/starpilot/navigation/tests/test_search_places.py @@ -48,7 +48,7 @@ def test_selected_place_routes_without_persisting_temporary_coordinates(owner): second = NavigationOwner(owner.root, runtime_source=lambda:None, transient_root=owner.transient_root) executor = Executor() runtime = RouteRuntime(second, engine=type('Engine',(),{'fetch':None})(), executor=executor) - assert runtime.update(10, (9,(-90.,40.),0.,0.),1)['destinationName'] == 'Coffee Shop' + assert runtime.update(10, (9,(-90.01,40.),0.,0.),1)['destinationName'] == 'Coffee Shop' assert len(executor.jobs) == 1 with pytest.raises(ValidationError): choose(owner, result) From d87411b874b8c024f140d7e1256c9b9fdf5f95dd Mon Sep 17 00:00:00 2001 From: Danny Date: Sun, 8 Nov 2026 22:26:41 -0800 Subject: [PATCH 02/14] Navigation: Google map and traffic routes --- openpilot/starpilot/galaxy/server.py | 16 +- .../galaxy/tests/test_navigation_http.py | 26 + .../galaxy/tests/test_share_destination.mjs | 10 +- .../starpilot/galaxy/web/js/navigation.js | 87 ++- .../galaxy/web/js/share-destination.js | 8 + .../starpilot/navigation/google_routes.py | 256 +++++++++ .../starpilot/navigation/google_tiles.py | 513 ++++++++++++++++++ openpilot/starpilot/navigation/navtilesd.py | 11 +- openpilot/starpilot/navigation/owner.py | 87 ++- .../starpilot/navigation/route_engine.py | 57 +- openpilot/starpilot/navigation/runtime.py | 90 ++- .../navigation/tests/test_google_routes.py | 265 +++++++++ .../navigation/tests/test_google_tiles.py | 256 +++++++++ .../navigation/tests/test_navtilesd.py | 20 + .../starpilot/navigation/tests/test_owner.py | 83 +++ .../navigation/tests/test_route_runtime.py | 63 ++- .../system/starport/projection_onroad.py | 4 +- openpilot/starpilot/ui/onroad_google_map.py | 225 ++++++++ openpilot/starpilot/ui/onroad_map.py | 172 +++++- openpilot/starpilot/ui/onroad_map_layer.py | 4 +- .../starpilot/ui/tests/test_onroad_map.py | 112 +++- .../ui/tests/test_onroad_map_layer.py | 4 +- 22 files changed, 2297 insertions(+), 72 deletions(-) create mode 100644 openpilot/starpilot/navigation/google_routes.py create mode 100644 openpilot/starpilot/navigation/google_tiles.py create mode 100644 openpilot/starpilot/navigation/tests/test_google_routes.py create mode 100644 openpilot/starpilot/navigation/tests/test_google_tiles.py create mode 100644 openpilot/starpilot/ui/onroad_google_map.py diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index e769075d84..4dc4d7b934 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -1895,21 +1895,27 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe fields = {'configure': {'patch'}, 'select': {'destination'}, 'selectPlace': {'id', 'searchId'}, 'cancelSearch': {'searchId'}, 'clear': set(), 'favorite': {'destination'}, 'favoritePlace': {'id', 'searchId'}, 'removeFavorite': {'id'}, 'labelFavorite': {'id', 'label'}, - 'removeRecent': {'id'}, 'clearRecents': set(), 'selectRoute': {'index'}} + 'removeRecent': {'id'}, 'clearRecents': set(), 'selectRoute': {'index'}, 'testGoogleKey': set(), + 'resolveShare': {'text'}} action = payload.get('action') - optional = {'label'} if action in ('favorite', 'favoritePlace') and 'label' in payload else set() + optional = ({'label'} if action in ('favorite', 'favoritePlace') and 'label' in payload else + {'key'} if action == 'testGoogleKey' and 'key' in payload else set()) if type(action) is not str or action not in fields or set(payload) != {'action', 'revision'} | fields[action] | optional: raise ValidationError('Invalid navigation action') - needs_park = action == 'configure' and isinstance(payload['patch'], dict) and 'token' in payload['patch'] + needs_park = action == 'configure' and isinstance(payload['patch'], dict) and bool({'token', 'googleKey'} & payload['patch'].keys()) def authorized(): return self.settings_session() == identity and (not needs_park or configuration_allowed()) - with (nullcontext() if action in ('selectPlace', 'favoritePlace') else effect_lock): + with (nullcontext() if action in ('selectPlace', 'favoritePlace', 'testGoogleKey', 'resolveShare') else effect_lock): if not authorized(): - raise PermissionError('Park your car before changing the Mapbox key' if needs_park else 'Sign in to Galaxy') + raise PermissionError('Park your car before changing a map key' if needs_park else 'Sign in to Galaxy') nav = navigation_owner() keywords = {'expected_revision': payload['revision'], 'authorized': authorized} if action == 'configure': result = nav.configure(payload['patch'], **keywords) + elif action == 'testGoogleKey': + result = dict(nav.snapshot(), googleKeyTest=nav.test_google_key(payload.get('key'))) + elif action == 'resolveShare': + result = dict(nav.snapshot(), sharedText=nav.resolve_share(payload['text'])) elif action == 'selectPlace': result = nav.select_place(payload['id'], payload['searchId'], identity, **keywords) elif action == 'cancelSearch': diff --git a/openpilot/starpilot/galaxy/tests/test_navigation_http.py b/openpilot/starpilot/galaxy/tests/test_navigation_http.py index a9fd032a82..31e079633e 100644 --- a/openpilot/starpilot/galaxy/tests/test_navigation_http.py +++ b/openpilot/starpilot/galaxy/tests/test_navigation_http.py @@ -160,6 +160,32 @@ class NavigationHttpTest(unittest.TestCase): self.assertEqual(self.action('configure', patch={'enabled': True})[0], 200) self.assertEqual(self.action('select', destination=PLACE)[0], 200) + def test_google_key_needs_parked_and_test_key_reports_without_leaking(self): + key = 'AIzaSyFixtureKey_0123456789abcdef' + self.parked = False + self.assertEqual(self.action('configure', patch={'googleKey': key})[0], 409) + self.assertFalse(self.navigation.snapshot()['hasGoogleKey']) + self.parked = True + status, body, _ = self.action('configure', patch={'googleKey': key, 'mapProvider': 'google'}) + self.assertEqual((status, body['hasGoogleKey'], body['mapProvider']), (200, True, 'google')) + self.assertNotIn(key, json.dumps(self.request('/api/navigation/status', cookie=self.local_cookie)[1])) + with patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': False, 'message': 'Billing is off'}) as tested: + self.parked = False + status, body, _ = self.action('testGoogleKey') + self.assertEqual((status, body['googleKeyTest']['message'], body['hasGoogleKey']), (200, 'Billing is off', True)) + self.assertEqual(self.action('testGoogleKey', key='AIzaSyOtherKey_0123456789abcdefgh')[0], 200) + self.assertEqual([call.args[0] for call in tested.call_args_list], [key, 'AIzaSyOtherKey_0123456789abcdefgh']) + self.assertEqual(self.action('testGoogleKey', key='bad key')[0], 400) + self.assertEqual(self.action('testGoogleKey', other=True)[0], 400) + + def test_shared_short_link_is_followed_on_the_comma(self): + with patch.object(type(self.navigation), 'resolve_share', return_value='https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1') as resolved: + status, body, _ = self.action('resolveShare', text='Bellagio https://maps.app.goo.gl/abc123') + self.assertEqual((status, body['sharedText']), (200, 'https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1')) + self.assertIn('revision', body) + resolved.assert_called_once_with('Bellagio https://maps.app.goo.gl/abc123') + self.assertEqual(self.action('resolveShare')[0], 400) + def test_stale_or_invalid_actions_never_overwrite_configuration(self): self.action('configure', patch={'enabled': True}) before = self.navigation.path.read_bytes() diff --git a/openpilot/starpilot/galaxy/tests/test_share_destination.mjs b/openpilot/starpilot/galaxy/tests/test_share_destination.mjs index 608203ad6c..02b940d171 100644 --- a/openpilot/starpilot/galaxy/tests/test_share_destination.mjs +++ b/openpilot/starpilot/galaxy/tests/test_share_destination.mjs @@ -1,6 +1,6 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { parseSharedDestination as parse } from '../web/js/share-destination.js' +import { isMapLink, parseSharedDestination as parse } from '../web/js/share-destination.js' for (const text of ['https://maps.google.com/@12.3,-45.6,15z', 'https://maps.google.com/?q=12.3,-45.6', 'geo:12.3,-45.6(Home)', 'google.navigation:q=12.3,-45.6', 'https://maps.google.com/?daddr=12.3,-45.6', 'https://maps.google.com/@1,2,15z/data=!3d12.3!4d-45.6']) { @@ -9,3 +9,11 @@ for (const text of ['https://maps.google.com/@12.3,-45.6,15z', 'https://maps.goo test('address search', () => assert.equal(parse('geo:0,0?q=10+Main+Street').query, '10 Main Street')) test('invalid coordinate does not route', () => assert.equal(parse('geo:123,456').destination, undefined)) test('encoded coordinates', () => assert.equal(parse('https://maps.google.com/?q=12.3%2C-45.6').destination.longitude, -45.6)) +test('pasted map links open their place; words search', () => { + assert.ok(isMapLink('Bellagio Hotel https://maps.app.goo.gl/AbC123')) + assert.ok(isMapLink('https://goo.gl/maps/xyz')) + assert.ok(isMapLink('https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1')) + assert.ok(!isMapLink('Starbucks')) + assert.ok(!isMapLink('10 Main Street')) + assert.ok(!isMapLink('http://maps.app.goo.gl/AbC123')) +}) diff --git a/openpilot/starpilot/galaxy/web/js/navigation.js b/openpilot/starpilot/galaxy/web/js/navigation.js index f70649078a..c2c25315e2 100644 --- a/openpilot/starpilot/galaxy/web/js/navigation.js +++ b/openpilot/starpilot/galaxy/web/js/navigation.js @@ -1,4 +1,4 @@ -import { parseSharedDestination } from "./share-destination.js" +import { SHORT_MAP_LINK, isMapLink, parseSharedDestination } from "./share-destination.js" import { GxNotice } from "./notice.js" import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js" import { connectionError } from "./polling.js" @@ -216,7 +216,8 @@ export class NavigationClient { this.busy = operation !== "status" if (operation !== "status") this.error = "" this.emit() - const deadline = this.later(() => controller.abort(), operation === "search" ? 24000 : operation === "action" && body?.action === "selectPlace" ? 12000 : 4000) + const deadline = this.later(() => controller.abort(), operation === "search" ? 24000 : operation === "action" && body?.action === "selectPlace" ? 12000 : + operation === "action" && body?.action === "testGoogleKey" ? 45000 : operation === "action" && body?.action === "resolveShare" ? 20000 : 4000) try { // Status polls name the route lines they already hold; the comma then leaves them out. const query = operation === "status" && this.data?.routeKey ? `?routeKey=${this.data.routeKey}` : "" @@ -297,7 +298,7 @@ export const NavigationPage = { components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect }, props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true }, go: { type: Function, default: null }, initialTab: { type: String, default: "route" }, tabs: { type: Array, required: true } }, - data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", searched: false, + data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, searched: false, suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false } }, watch: { initialTab(value) { this.tab = value } }, computed: { @@ -335,6 +336,9 @@ export const NavigationPage = { return [["searchSessions", "Searches"], ["geocoding", "Address lookups"], ["directions", "Routes"], ["staticTiles", "Map views"]] .filter(([key]) => usage[key]).map(([key, label]) => ({ key, label, ...usage[key] })) }, + googleUsage() { return this.data?.googleMap?.usage || null }, + googleRouteUsage() { return this.data?.googleRoutes?.usage || null }, + googleEssentialUsage() { return this.data?.googleRoutes?.essentials || null }, path() { return routePath(this.data?.route) }, summary() { const instruction = this.data?.instruction, route = this.data?.alternatives?.[this.data?.selectedRoute || 0] @@ -363,17 +367,11 @@ export const NavigationPage = { if (!share || !this.client.data || this.client.stale || !this.client.active) return params.delete('share') history.replaceState(history.state, '', `${location.pathname}${params.size ? '?' + params : ''}${location.hash}`) - const parsed = parseSharedDestination(share) - if (parsed.destination) await this.client.action('select', { destination: parsed.destination }) - else { - // Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick. - this.query = parsed.query - await this.client.search(parsed.query) - } + await this.openShared(share) }) } }, - beforeUnmount() { document.removeEventListener("visibilitychange", this.visibilityHandler); clearTimeout(this.suggestTimer); this.client.stop(); this.token = "" }, + beforeUnmount() { document.removeEventListener("visibilitychange", this.visibilityHandler); clearTimeout(this.suggestTimer); this.client.stop(); this.token = ""; this.googleKey = "" }, methods: { reportSave, async openGpsSetup() { @@ -386,6 +384,18 @@ export const NavigationPage = { this.tab = tab this.go?.(tab === 'route' ? '/navigation' : `/navigation/${tab}`) }, + async openShared(text) { + let parsed = parseSharedDestination(text) + // A Google Maps short link is followed on the comma to the full link, which carries the coordinates. + if (!parsed.destination && SHORT_MAP_LINK.test(text)) { + const resolved = (await this.client.action('resolveShare', { text: String(text).slice(0, 8192) }))?.sharedText + if (resolved) parsed = parseSharedDestination(resolved) + } + if (parsed.destination) { await this.client.action('select', { destination: parsed.destination }); return } + // Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick. + this.query = parsed.query + await this.client.search(parsed.query) + }, async search() { if (this.searchPending) return clearTimeout(this.suggestTimer) @@ -393,13 +403,13 @@ export const NavigationPage = { this.savedSuggestionPlaces = {} this.favoritePicker = null this.searchPending = true - try { await this.client.search(this.query) } + try { await (isMapLink(this.query) ? this.openShared(this.query) : this.client.search(this.query)) } finally { this.searchPending = false } }, typed() { clearTimeout(this.suggestTimer) this.suggestOpen = true - if (!this.query.trim()) { this.client.endSuggestions(); return } + if (!this.query.trim() || isMapLink(this.query)) { this.client.endSuggestions(); return } this.favoritePicker = null this.suggestTimer = setTimeout(() => this.client.suggest(this.query), 150) }, @@ -459,6 +469,12 @@ export const NavigationPage = { placeName(place) { return LABELS[place.label]?.name || place.name }, placeDetail(place) { return place.label ? place.name : place.address || place.description || "" }, async saveKey(enable = false) { const token = this.token.trim(); this.token = ""; await this.client.action("configure", { patch: enable ? { token, enabled: true } : { token } }) }, + async saveGoogleKey() { const googleKey = this.googleKey.trim(); this.googleKey = ""; this.googleTest = null; await this.client.action("configure", { patch: { googleKey } }) }, + async testGoogleKey() { + const key = this.googleKey.trim() + this.googleTest = null + this.googleTest = (await this.client.action("testGoogleKey", key ? { key } : {}))?.googleKeyTest || null + }, distance(value) { const metric = this.data?.isMetric !== false return metric ? value < 1000 ? `${Math.round(value)} m` : `${(value / 1000).toFixed(1)} km` : @@ -551,6 +567,51 @@ export const NavigationPage = { +
+
Google map and routes
+

Show Google's road map with live traffic in the map widget, and route with Google's traffic, using your own Google Maps Platform key. Mapbox still handles search and offline road maps, its road lines show wherever a Google tile hasn't loaded, and it routes whenever Google can't.

+
+ Map style + + + + +
+
+ Routes + + + + +
+
Get a Google key (about 10 minutes, once) +
  1. Sign in to Google Cloud and create a project.
  2. +
  3. Turn on billing for it. Google asks for a card even though the comma stays inside the free allowance.
  4. +
  5. Enable the Map Tiles API, and the Routes API for Google routes.
  6. +
  7. Create an API key and restrict it to those APIs. Leave application restrictions off; the comma's address changes on cellular.
  8. +
  9. Paste the key below while parked, then press Test key.
+
+

The comma stops at 99% of Google's free 100,000 map tiles a month and 15,000 a day, and at 99% of Google's free routes: 10,000 a month without traffic, and 5,000 traffic requests. Every route, including a reroute, uses live traffic (one traffic request each), and every 7½ minutes one more corrects the arrival time. Past 20 reroutes in an hour, or once traffic requests run out, routes ignore traffic; past both limits the comma uses Mapbox until they reset. Google routes have no lane arrows. These counts cover this comma only; Google bills everything that uses the key.

+
+
Map tiles this month
{{ googleUsage.monthUsed.toLocaleString() }} of {{ googleUsage.monthLimit.toLocaleString() }} free
+
Map tiles today
{{ googleUsage.dayUsed.toLocaleString() }} of {{ googleUsage.dayLimit.toLocaleString() }} free
+ + +
+ {{ data.googleMap.failure }} + {{ data.googleRoutes.failure }} +

A Google key is saved.

+
+
+
+ Map: {{ googleTest.message }} + Routes: {{ googleTest.routes.message }} +