Merge pull request #304 from dirwin31:AddGoogleandAppShare

Google Maps and Share to StarPilot Navigation
This commit is contained in:
prabhaavp
2026-11-14 00:08:44 -05:00
committed by GitHub
50 changed files with 4481 additions and 300 deletions
+29 -14
View File
@@ -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
@@ -1011,15 +1011,19 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
self.json(400, {'error': 'Invalid map tile'})
return
try:
query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=1)
theme = query.get('theme', ['light'])[0]
if set(query) - {'theme'} or theme not in ('light', 'dark'):
query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=2)
theme = query.get('theme', ['light'])
provider = query.get('provider', ['mapbox'])
if (set(query) - {'theme', 'provider'} or len(theme) != 1 or theme[0] not in ('light', 'dark') or
len(provider) != 1 or provider[0] not in ('mapbox', 'google')):
raise ValueError('Invalid map theme')
except ValueError:
self.json(400, {'error': 'Invalid map theme'})
return
try:
tile = navigation_owner().map_tile(*(int(value) for value in match.groups()), theme)
coords = (int(value) for value in match.groups())
tile = (navigation_owner().map_tile(*coords, theme[0], provider='google')
if provider[0] == 'google' else navigation_owner().map_tile(*coords, theme[0]))
except (OSError, ValueError, RuntimeError):
self.json(503, {'error': 'Map tiles are unavailable'})
else:
@@ -1888,28 +1892,38 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
raise ValidationError('Enter a destination to search')
if 'autocomplete' in payload and payload['autocomplete'] is not True:
raise ValidationError('Enter a destination to search')
result = {'results': (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'],
autocomplete='autocomplete' in payload)
if 'searchId' in payload else navigation_owner().search(payload['query']))}
results = (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'],
autocomplete='autocomplete' in payload)
if 'searchId' in payload else navigation_owner().search(payload['query']))
result = {'results': results, 'provider': getattr(results, 'provider', 'mapbox')}
else:
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'}, 'share': {'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
{'intentId'} if action == 'share' and 'intentId' 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', 'share') 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 == 'share':
result = nav.share(payload['text'], intent_id=payload.get('intentId'), **keywords)
elif action == 'selectPlace':
result = nav.select_place(payload['id'], payload['searchId'], identity, **keywords)
elif action == 'cancelSearch':
@@ -1939,7 +1953,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
except ConflictError as error:
self.json(409, {'error': str(error)})
except ValidationError as error:
self.json(400, {'error': str(error)})
query = getattr(error, 'query', None)
self.json(400, {'error': str(error), **({'query': query} if query else {})})
except PermissionError as error:
if self.require_session():
self.json(409, {'error': str(error)})
+22 -1
View File
@@ -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,29 @@ 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 next deviceState and pandaStates, then sample again; call with self.lock held."""
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():
@@ -87,14 +87,14 @@ const status = { enabled: true, hasKey: true, isMetric: true, status: 'noDestina
await page.screenshot({ path: `/private/tmp/navigation-offline-${width}.png`, fullPage: true })
}
await offlineLink.click()
await page.getByText('Map Overlay Roads', { exact: true }).waitFor()
await page.getByText('Offline Map Management', { exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true')
await page.getByRole('button', { name: 'Destination', exact: true }).click()
status.network = 'unknown'
await page.evaluate(() => window.navigation.client.load())
assert.equal(await offlineLink.count(), 0, 'unknown device state must not be presented as offline')
await page.goto('http://navigation.test/?shell=1#/navigation/maps')
await page.getByText('Map Overlay Roads', { exact: true }).waitFor()
await page.getByText('Offline Map Management', { exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true')
await page.getByRole('button', { name: 'Destination', exact: true }).click()
await page.waitForURL('**#/navigation')
@@ -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)
@@ -257,4 +257,49 @@ console.log("Local HTTP search UUID fallback passed")
assert.ok(NavigationPage.template.includes('<BluetoothNotice v-if="bluetooth" feature="Map preview"'))
assert.ok(NavigationPage.template.includes('<NavigationMap v-else-if="ready"'))
}
{
// Shared text the comma can't pin down comes back as a 400 with the search to show; navigation turns on for it.
const sent = [], states = []
let off = true
const answers = { share: (body) => body.text.includes("!3d") ? response({ ...snapshot("s"), enabled: true, destination: place, shared: place }) :
body.text === "Atlantis" ? response({ error: "No map location found for Atlantis" }, 400) :
response({ error: "Open StarPilot to search for Starbucks", query: "Starbucks" }, 400),
configure: () => { off = false; return response({ ...snapshot("c"), enabled: true }) } }
const client = new NavigationClient({ publish: (state) => states.push(state), later: () => 0, cancelTimer: () => {},
fetcher: async (url, options) => {
const body = options.body ? JSON.parse(options.body) : null
sent.push({ url, body })
if (url.includes("/search")) return response({ results: [place], provider: "google" })
if (body?.action) return answers[body.action](body)
return response({ ...snapshot(), enabled: !off })
} })
await client.start()
const page = { client, query: "" }
await NavigationPage.methods.openShared.call(page, "Starbucks")
assert.deepEqual(sent.slice(1).map(({ url, body }) => body?.action || url), ["share", "configure", "./api/navigation/search"])
assert.equal(page.query, "Starbucks")
assert.equal(sent.at(-1).body.query, "Starbucks")
const shown = states.at(-1)
assert.deepEqual([shown.results, shown.resultsProvider, shown.error, shown.stale, shown.data.enabled], [[place], "google", "", false, true])
sent.length = 0
await NavigationPage.methods.openShared.call(page, "https://www.google.com/maps/place/Library/data=!3d41!4d-88")
assert.deepEqual(sent.map(({ body }) => body?.action), ["share"])
assert.equal(states.at(-1).data.destination.name, "Library")
sent.length = 0
page.query = ""
await NavigationPage.methods.openShared.call(page, "Atlantis")
assert.deepEqual([sent.length, page.query, states.at(-1).error], [1, "", "No map location found for Atlantis"])
assert.equal(client.refusal, null)
client.stop()
assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "google", hasGoogleKey: true } }), true)
assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "mapbox", hasGoogleKey: true } }), false)
const tests = NavigationPage.computed.googleTests.call({ googleTest: { ok: true, message: "map", routes: { ok: false, failure: "disabled", message: "off" },
places: { ok: false, failure: "budget", message: "used up" } } })
assert.deepEqual(tests.map((row) => [row.name, row.ok, row.missing, row.link?.href]), [["Map Tiles API", true, false, undefined],
["Routes API", false, true, "https://console.cloud.google.com/apis/library/routes.googleapis.com"], ["Places API (New)", false, false, undefined]])
assert.equal(NavigationPage.computed.googleWorking.call({ googleTests: tests }), "2 of 3 APIs working")
assert.ok(NavigationPage.template.includes("Google isn't used until the Mapbox key above is added too."))
console.log("Shared places: comma lookup, 400 query search, navigation turned on, Google source and key test summary passed")
}
await import("./test_navigation_map.mjs")
@@ -160,6 +160,84 @@ 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,
patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': True, 'failure': None, 'message': 'routes'}),
patch('openpilot.starpilot.navigation.google_places.test_places', return_value={'ok': True, 'failure': None, 'message': 'places'})):
self.parked = False
status, body, _ = self.action('testGoogleKey')
self.assertEqual((status, body['googleKeyTest']['message'], body['hasGoogleKey']), (200, 'Billing is off', True))
self.assertEqual((body['googleKeyTest']['routes']['ok'], body['googleKeyTest']['places']['message']), (True, 'places'))
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_shared_place_turns_navigation_on_and_starts_the_route(self):
self.assertEqual(self.action('share', text='geo:40.5,-89.5')[1], {'error': 'Add your Mapbox access token first'})
self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True)
self.assertFalse(self.navigation.snapshot()['enabled'])
status, body, _ = self.action('share', remote=True, text='https://www.google.com/maps/place/Bellagio/data=!3d36.1126!4d-115.1767')
self.assertEqual(status, 200)
self.assertEqual(body['shared'], {'name': 'Bellagio', 'latitude': 36.1126, 'longitude': -115.1767})
self.assertTrue(body['enabled'] and body['hasKey'])
self.assertEqual((body['destination']['latitude'], body['revision']), (36.1126, self.navigation.snapshot()['revision']))
self.assertNotIn('pk.test', json.dumps(body))
feature = {'features': [{'properties': {'name': '3600 S Las Vegas Blvd', 'full_address': '3600 S Las Vegas Blvd, Las Vegas, NV'},
'geometry': {'coordinates': [-115.17, 36.11]}}]}
with patch('openpilot.starpilot.navigation.owner.response_json', return_value=feature) as geocode:
status, body, _ = self.action('share', text='https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV/data=!4m2!3m1!1s0x1:0x2')
self.assertEqual((status, body['shared']), (200, {'name': 'Bellagio', 'latitude': 36.11, 'longitude': -115.17}))
self.assertEqual(geocode.call_args.args[2]['q'], '3600 S Las Vegas Blvd, Las Vegas, NV')
with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'features': []}):
self.assertEqual(self.action('share', text='https://maps.google.com/?q=Nowhere,+Atlantis')[1],
{'error': 'No map location found for Nowhere', 'query': 'Nowhere, Atlantis'})
self.assertEqual(self.action('share', text='Starbucks')[:2], (400, {'error': 'Open StarPilot to search for Starbucks', 'query': 'Starbucks'}))
revision = self.navigation.read()['revision']
stale = {'action': 'share', 'revision': '0', 'text': 'geo:40.5,-89.5'}
self.assertEqual(self.request('/api/navigation/action', payload=stale, cookie=self.local_cookie)[0], 409)
self.assertEqual(self.navigation.read()['revision'], revision)
self.assertEqual(self.action('share')[0], 400)
self.assertNotIn('query', self.action('share', text='x' * 8193)[1])
def test_shared_intent_retry_after_cancel_does_not_restart_navigation(self):
self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True)
request = {'action': 'share', 'revision': self.navigation.read()['revision'],
'text': 'geo:40.5,-89.5', 'intentId': 'durable-phone-share'}
first = self.request('/api/navigation/action', payload=request, remote=True, cookie=self.remote_cookie)
self.assertEqual(first[0], 200)
self.assertIsNotNone(first[1]['destination'])
cancelled = self.action('clear', remote=True)
replay = self.request('/api/navigation/action', payload=request, remote=True, cookie=self.remote_cookie)
self.assertEqual(replay[0], 200)
self.assertIsNone(replay[1]['destination'])
self.assertEqual(replay[1]['revision'], cancelled[1]['revision'])
changed = dict(request, text='geo:41,-89.5')
self.assertEqual(self.request('/api/navigation/action', payload=changed, remote=True, cookie=self.remote_cookie)[0], 400)
def test_invalid_shared_intent_is_rejected(self):
self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True)
for intent in ('../bad', '', 'x' * 65, 7):
request = {'action': 'share', 'revision': self.navigation.read()['revision'], 'text': 'geo:40.5,-89.5', 'intentId': intent}
self.assertEqual(self.request('/api/navigation/action', payload=request, remote=True, cookie=self.remote_cookie)[0], 400)
self.assertIsNone(self.navigation.read()['destination'])
def test_stale_or_invalid_actions_never_overwrite_configuration(self):
self.action('configure', patch={'enabled': True})
before = self.navigation.path.read_bytes()
@@ -207,6 +285,27 @@ class NavigationHttpTest(unittest.TestCase):
self.assertEqual(self.action('clearRecents')[1]['recents'],[])
self.assertEqual(self.action('removeFavorite',id=place)[1]['favorites'],[])
def test_search_names_the_provider_that_found_the_places(self):
self.action('configure', patch={'token':'pk.synthetic','enabled':True})
def search():
return {'query':'bellagio', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())}
suggestion = {'suggestions':[{'mapbox_id':'poi/id','name':'Coffee Shop','feature_type':'poi'}]}
with patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion):
self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox')
key = 'AIzaSyFixtureKey_0123456789abcdef'
self.action('configure', patch={'googleKey':key, 'routeProvider':'google'})
found = [{'name':'Bellagio','address':'3600 S Las Vegas Blvd','latitude':36.1126,'longitude':-115.1767}]
with patch('openpilot.starpilot.navigation.google_places.text_search', return_value=found) as google:
status, result, _ = self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)
self.assertEqual((status, result['provider'], result['results'][0]['name']), (200, 'google', 'Bellagio'))
self.assertNotIn('searchId', result['results'][0])
self.assertEqual(google.call_args.args[1], key)
self.assertNotIn(key, json.dumps(result))
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed
with (patch('openpilot.starpilot.navigation.google_places.text_search', side_effect=GooglePlacesFailed('budget')),
patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion)):
self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox')
def test_temporary_search_result_cannot_be_saved(self):
self.action('configure', patch={'token':'pk.synthetic','enabled':True})
search = {'query':'coffee', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())}
@@ -186,3 +186,33 @@ console.log('Follow, pinch and double-tap zoom passed')
globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf
}
console.log('Live map theme changes: correct requests, cache disposal, late-response isolation, camera preservation and observer cleanup passed')
{
// Switching mapProvider between Mapbox and Google clears cached tiles, appends provider=google, and crops 256px parent tiles.
const savedFetch = globalThis.fetch, savedBitmap = globalThis.createImageBitmap
globalThis.requestAnimationFrame = fn => { frames.set(++frameId, fn); return frameId }
globalThis.cancelAnimationFrame = id => frames.delete(id)
const urls = []
let closed = 0
globalThis.fetch = async url => { urls.push(url); return { ok: true, blob: async () => ({}) } }
globalThis.createImageBitmap = async () => ({ width: 256, close() { closed++ } })
const switched = new RasterMap(canvas)
switched.draw = () => {}
switched.update({ mapProvider: 'mapbox', hasGoogleKey: true }, false)
await switched.load('1/0/0')
assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark'))
assert.equal(switched.tiles.size, 1)
const crop = switched.placeholder(2, 1, 1)
assert.deepEqual(crop.slice(1), [128, 128, 128], '256px Google/custom tiles crop using their actual bitmap width')
switched.update({ mapProvider: 'google', hasGoogleKey: true }, false)
assert.equal(switched.tiles.size, 0, 'switching map provider clears cached tiles from the previous provider')
assert.equal(closed, 1)
await switched.load('1/0/0')
assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark&provider=google'))
switched.update({ mapProvider: 'google', hasGoogleKey: true, googleMap: { failure: 'Quota reached' } }, false)
assert.equal(switched.provider, 'mapbox', 'a Google map failure falls back to Mapbox tiles')
switched.close()
globalThis.fetch = savedFetch; globalThis.createImageBitmap = savedBitmap
globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf
}
console.log('Map provider switching: Google tile URL, cache invalidation, fallback, and 256px placeholder cropping passed')
@@ -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,17 @@ 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('waze links', () => {
assert.deepEqual(parse('https://waze.com/ul/h9q8yy4').destination, { name: 'Shared destination', latitude: 37.762756, longitude: -122.426147 })
assert.equal(parse('https://waze.com/live-map/directions?to=ll.37.77%2C-122.41').destination.longitude, -122.41)
assert.equal(parse('https://waze.com/ul?q=Starbucks%20Main%20St&navigate=yes').query, 'Starbucks Main St')
assert.ok(isMapLink('https://waze.com/ul?q=Starbucks&navigate=yes'))
})
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'))
})
@@ -1390,7 +1390,7 @@ background: var(--surface-container-high); color: var(--on-surface-variant); bor
.gx-starport-pill:has(> i)::before { display: none; }
.gx-starport-pill--ready { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, transparent); background: color-mix(in srgb, var(--success) 12%, transparent); }
.gx-starport-pill--soon { color: var(--warning); border-color: color-mix(in srgb, var(--warning) 40%, transparent); background: color-mix(in srgb, var(--warning) 12%, transparent); }
.gx-starport-pill--expired, .gx-starport-pill--broken { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); }
.gx-starport-pill--expired, .gx-starport-pill--broken, .gx-starport-pill--danger, .gx-starport-pill--error { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); }
.gx-starport-list { list-style: none; margin: 0; padding: 0; display: grid; border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; }
.gx-starport-list > .gx-starport-row + .gx-starport-row { border-top: 1px solid var(--outline); }
.gx-starport-row { display: flex; align-items: center; gap: var(--sp-3); min-width: 0; margin: 0; padding: var(--sp-3) var(--sp-4); }
@@ -122,6 +122,72 @@
.gx-navigation__token-link { margin-bottom: var(--sp-4); }
.gx-navigation__gps { scroll-margin-top: 100px; }
.gx-navigation__gps li { margin-block: var(--sp-2); line-height: 1.5; }
.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: list-item; align-content: center; }
.gx-navigation__gps { scroll-margin-top: 100px; display: grid; gap: var(--sp-3); }
.gx-navigation__gps li { margin-block: var(--sp-1); line-height: 1.45; }
.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; }
.gx-navigation__gps-status { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0; }
.gx-navigation__gps-guides { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--sp-3); margin-top: var(--sp-3); }
.gx-navigation__gps-card { display: grid; gap: var(--sp-2); align-content: start; padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container); }
.gx-navigation__gps-card > strong { display: inline-flex; align-items: center; gap: var(--sp-2); color: var(--on-surface); }
.gx-navigation__gps-card > strong .bi { color: var(--primary); }
.gx-navigation__prefs { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-top: var(--sp-3); margin-top: var(--sp-2); border-top: 1px solid var(--outline); }
.gx-navigation__prefs-head { display: grid; gap: 2px; min-width: 200px; flex: 1 1 220px; }
.gx-navigation__pref-chips { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
.gx-navigation__pref { display: inline-flex; align-items: center; gap: var(--sp-2); min-height: 40px; padding: 0 14px; border-radius: var(--radius-full); border: 1px solid var(--outline); background: var(--surface-container); color: var(--on-surface); font-size: .88rem; font-weight: var(--fw-medium); cursor: pointer; user-select: none; transition: background var(--motion-fast), border-color var(--motion-fast), color var(--motion-fast); }
.gx-navigation__pref > i { font-size: .95rem; color: var(--text-muted); }
.gx-navigation__pref--on { background: color-mix(in srgb, var(--primary) 16%, var(--surface-container)); border-color: var(--primary); color: var(--primary); }
.gx-navigation__pref--on > i { color: var(--primary); }
.gx-navigation__pref:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; }
.gx-navigation__pref--disabled { opacity: .55; cursor: default; }
.gx-navigation__step-title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-1); }
.gx-navigation__step-title h3 { margin: 0; }
.gx-navigation__step-title .gx-starport-pill { padding: 2px 10px; font-size: .75rem; }
/* Setup choices: compact M3 choice buttons with an expandable info popover. */
.gx-choice { border: 0; margin: 0; padding: 0; min-width: 0; display: grid; gap: var(--sp-2); }
.gx-choice__head { display: flex; align-items: center; gap: var(--sp-2); }
.gx-choice__legend { font-weight: var(--fw-medium); }
.gx-choice__info-btn { color: var(--text-muted); font-size: .95rem; }
.gx-choice__info-btn:hover, .gx-choice__info-btn[aria-expanded="true"] { background: var(--surface-container-high); color: var(--primary); }
.gx-choice__hint { margin: 0; color: var(--text-muted); font-size: .85rem; }
.gx-choice__grid { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
.gx-choice__card { flex: 1 1 160px; display: flex; align-items: center; min-height: 44px; padding: 8px 14px; border: 1px solid var(--outline);
border-radius: var(--radius-md); background: var(--surface-container); cursor: pointer; min-width: 0; transition: background var(--motion-fast), border-color var(--motion-fast); }
.gx-choice__card--on { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 14%, var(--surface-container)); box-shadow: 0 0 0 1px var(--primary); }
.gx-choice__card--off { opacity: .6; cursor: default; }
.gx-choice__card:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; }
.gx-choice__title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); width: 100%; min-width: 0; line-height: 1.3; }
.gx-choice__title strong { flex: 1 1 auto; min-width: 0; font-size: .9rem; }
.gx-choice__title .bi { flex: 0 0 auto; color: var(--text-muted); font-size: 1rem; }
.gx-choice__card--on .gx-choice__title .bi { color: var(--primary); }
.gx-choice__title .gx-starport-pill { padding: 2px 8px; font-size: .72rem; margin-left: auto; }
.gx-choice__active-summary { margin: 0; color: var(--text-muted); font-size: .83rem; line-height: 1.4; }
.gx-choice__popover { display: grid; gap: var(--sp-2); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container-high, var(--surface-container)); font-size: .85rem; }
.gx-choice__popover-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }
.gx-choice__popover-close { color: var(--text-muted); }
.gx-choice__popover-close:hover { background: var(--glass-active-bg); color: var(--on-surface); }
.gx-choice__popover-list { margin: 0; display: grid; gap: var(--sp-2); }
.gx-choice__popover-item { display: grid; gap: 2px; padding-top: var(--sp-2); border-top: 1px solid var(--outline); }
.gx-choice__popover-item dt { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
.gx-choice__popover-item dt .gx-starport-pill { padding: 1px 8px; font-size: .7rem; }
.gx-choice__popover-item dd { margin: 0; color: var(--on-surface-variant, var(--text-muted)); line-height: 1.45; }
.gx-choice__limit { color: var(--text-muted); font-size: .82rem; line-height: 1.4; }
.gx-compare { display: grid; margin-top: var(--sp-3); border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; }
.gx-compare__row { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1fr); gap: var(--sp-3); padding: var(--sp-2) var(--sp-3); font-size: .85rem; }
.gx-compare__row + .gx-compare__row { border-top: 1px solid var(--outline); }
.gx-compare__row--head { font-weight: var(--fw-medium); background: var(--surface-container); }
.gx-compare__row > :first-child { color: var(--text-muted); }
.gx-compare__row--head > :first-child { color: inherit; }
.gx-navigation__sources { display: flex; flex-wrap: wrap; gap: var(--sp-2); list-style: none; margin: 0; padding: 0; }
.gx-navigation__sources .gx-navigation__chip { text-decoration: none; border: 1px solid var(--outline); }
.gx-navigation__power .gx-row__info { display: grid; gap: 2px; }
.gx-navigation .gx-starport-step__body { padding-left: 0; }
@media (min-width: 640px) { .gx-navigation .gx-starport-step__body { padding-left: calc(36px + var(--sp-4)); } }
@media (max-width: 540px) { .gx-compare__row { grid-template-columns: 1fr; gap: 2px; } .gx-compare__row--head { display: none; } .gx-compare__row > :nth-child(2)::before { content: "Mapbox: "; } .gx-compare__row > :nth-child(3)::before { content: "Google: "; } }
.gx-navigation__guide { border: 1px solid var(--outline); border-radius: var(--radius-sm); padding: var(--sp-3); }
.gx-navigation__guide > summary { font-weight: var(--fw-bold, 700); }
.gx-navigation__guide a { color: var(--primary); font-weight: var(--fw-bold, 700); text-decoration: underline; text-underline-offset: 3px; }
.gx-navigation__guide li strong { color: var(--on-surface); }
@@ -1,26 +1,28 @@
/* Offline road maps for the Android Auto overlay (#/navigation, Offline Maps tab). */
.gx-navigation__offline { display: grid; gap: 16px; padding: 0 0 96px; }
.gx-offline-roads { padding: 24px; display: grid; gap: 14px; }
/* Keep the section header flush with the card's rounded top like every other Galaxy card. */
.gx-offline-roads > .gx-section__header { margin: -24px -24px 0; }
.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; }
.gx-offline-roads__stat { display: grid; gap: 2px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 6%, transparent); }
.gx-offline-roads__stat span { font-size: .78rem; opacity: .7; }
.gx-navigation__offline { display: grid; gap: var(--sp-4, 16px); padding: 0 0 96px; }
.gx-offline-roads { padding: var(--panel-padding, 20px); display: grid; gap: var(--sp-4, 16px); min-width: 0; }
.gx-offline-roads__head { display: flex; align-items: flex-start; gap: var(--sp-4, 16px); min-width: 0; }
.gx-offline-roads__head > div { flex: 1; min-width: 0; }
.gx-offline-roads__head .gx-note { margin: 0; line-height: 1.45; }
.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: var(--sp-3, 12px); }
.gx-offline-roads__stat { display: grid; gap: 2px; padding: var(--sp-3, 12px) var(--sp-4, 16px); border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); }
.gx-offline-roads__stat span { font-size: .78rem; color: var(--text-muted); }
.gx-offline-roads__stat strong { font-size: 1.05rem; }
.gx-offline-roads__stat small { opacity: .7; font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; }
.gx-offline-roads__stat small { color: var(--text-muted); font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; }
.gx-offline-roads__stat--wide { grid-column: 1 / -1; }
.gx-offline-roads__bar { display: flex; height: 8px; border-radius: 6px; overflow: hidden; background: color-mix(in srgb, currentColor 12%, transparent); margin: 6px 0 2px; }
.gx-offline-roads__bar i { display: block; height: 100%; transition: width .4s ease; }
.gx-offline-roads__legend { display: inline-flex; align-items: center; gap: 6px; }
.gx-offline-roads__legend b { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr); gap: 14px; align-items: start; }
.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(240px, 1fr); gap: var(--sp-3, 12px); align-items: start; }
@media (max-width: 760px) { .gx-offline-roads__picker { grid-template-columns: 1fr; } }
.gx-offline-roads__map { position: relative; border-radius: 16px; overflow: hidden; background: #0e0e1a; height: 340px; }
.gx-offline-roads__map { position: relative; border-radius: var(--radius-md, 16px); border: 1px solid var(--outline); overflow: hidden; background: var(--navigation-land, #191a1a); height: clamp(260px, 42svh, 360px); }
.gx-offline-roads__map canvas { width: 100%; height: 100%; display: block; cursor: crosshair; touch-action: none; }
.gx-offline-roads__provider { position: absolute; left: 10px; top: 10px; padding: 4px 10px; border-radius: var(--radius-full, 20px); border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .75rem; font-weight: var(--fw-medium, 500); pointer-events: none; }
.gx-offline-roads__map .gx-navigation-map__controls { position: absolute; right: 10px; top: 10px; display: grid; gap: 6px; }
.gx-offline-roads__hint { position: absolute; left: 12px; bottom: 10px; padding: 6px 10px; border-radius: 10px; background: #0e0e1acc; color: #e8e6f5; font-size: .8rem; pointer-events: none; }
.gx-offline-roads__form { display: grid; gap: 8px; }
.gx-offline-roads__hint { position: absolute; left: 10px; right: 10px; bottom: 10px; width: fit-content; max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 10px; border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .8rem; pointer-events: none; }
.gx-offline-roads__form { display: grid; gap: 8px; padding: var(--sp-3, 12px); border: 1px solid var(--outline); border-radius: var(--radius-md, 14px); background: var(--surface-container); }
.gx-offline-roads__areas { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.gx-offline-roads__areas li { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 5%, transparent); }
.gx-offline-roads__area { display: grid; gap: 2px; min-width: 0; flex: 1; }
.gx-offline-roads__area small { opacity: .72; }
.gx-offline-roads__areas li { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); }
.gx-offline-roads__area { display: grid; gap: 2px; min-width: 160px; flex: 1; }
.gx-offline-roads__area small { color: var(--text-muted); }
@@ -143,7 +143,7 @@
"name": "Setup",
"path": "/navigation/setup",
"tab": "setup",
"description": "Configure navigation and Mapbox",
"description": "Keys, map and route sources, and GPS",
"icon": "bi-gear"
}
]
+1 -1
View File
@@ -218,7 +218,7 @@ createApp({
</div>
</aside>
<main class="gx-content" :style="{'--route-direction': routeDirection}"><div class="gx-route-stage">
<Transition name="gx-route" @before-enter="setPageActive($event, true)" @before-leave="setPageActive($event, false)"><div class="gx-route" :key="isActive('/recordings') ? '/recordings' : route.path">
<Transition name="gx-route" @before-enter="setPageActive($event, true)" @before-leave="setPageActive($event, false)"><div class="gx-route" :key="isActive('/recordings') ? '/recordings' : route.path.startsWith('/navigation') ? '/navigation' : route.path">
<template v-if="state.loading && !state.error"></template>
<GxNotice v-else-if="state.error" tone="danger">{{ state.error }}</GxNotice>
<section v-else-if="state.monitorMode === 'local' && authState.status !== 'authenticated'" class="gx-card gx-auth" aria-label="Galaxy sign in">
@@ -139,6 +139,11 @@ export class RasterMap {
const theme = value === 'light' ? 'light' : 'dark'
if (this.closed || this.theme === theme) return
this.theme = theme
this.clearTiles()
this.changed('')
this.draw()
}
clearTiles() {
for (const controller of this.pending.values()) controller.abort()
this.pending.clear()
for (const image of this.tiles.values()) image.close()
@@ -147,8 +152,6 @@ export class RasterMap {
this.failures = 0
clearTimeout(this.retryTimer)
this.retryTimer = null
this.changed('')
this.draw()
}
pause() {
if (this.follow) { this.follow = false; this.changed() }
@@ -206,6 +209,9 @@ export class RasterMap {
if (data?.location && (this.locationFresh || data.location.lastKnown === true && !this.lastLocation)) {
this.lastLocation = { ...data.location, bearing: Number.isFinite(data.location.bearing) ? data.location.bearing : this.lastLocation?.bearing }
}
const provider = data?.mapProvider === 'google' && data?.hasGoogleKey && !data?.googleMap?.failure ? 'google' : 'mapbox'
if (this.provider && this.provider !== provider) this.clearTiles()
this.provider = provider
this.data = data || {}
this.stale = stale
// A newly chosen route is shown whole once; Recenter returns to following the car.
@@ -253,7 +259,7 @@ export class RasterMap {
for (let up = 1; up <= 5 && zoom - up >= 0; up++) {
const image = this.tiles.get(`${zoom - up}/${x >> up}/${y >> up}`)
if (image) {
const span = SIZE / 2 ** up
const span = (image.width || SIZE) / 2 ** up
return [image, (x - ((x >> up) << up)) * span, (y - ((y >> up) << up)) * span, span]
}
}
@@ -348,8 +354,9 @@ export class RasterMap {
timedOut = true;
controller.abort()
}, 8000)
const providerQuery = this.provider === 'google' ? '&provider=google' : ''
try {
const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}`, {
const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}${providerQuery}`, {
credentials: 'same-origin', signal: controller.signal
});
if (!response.ok) throw new Error('Map tiles unavailable')
@@ -359,22 +366,26 @@ export class RasterMap {
return
}
this.tiles.set(key, image);
this.failed.delete(key);
this.failures = 0
while (this.tiles.size > TILE_BITMAPS) {
const oldest = this.tiles.keys().next().value;
this.tiles.get(oldest).close();
this.tiles.delete(oldest)
}
if (!this.failed.size) this.changed('')
this.changed('')
if (this.failed.size && !this.retryTimer) {
this.retryTimer = setTimeout(() => { this.retryTimer = null; this.retry() }, 400)
}
} catch (error) {
if (this.pending.get(key) === controller && (timedOut || !controller.signal.aborted)) {
this.failed.add(key);
if (this.failed.size > 64) this.failed.delete(this.failed.values().next().value);
// A quick refusal (a busy moment) is retried quickly and silently; a hung request or a run of failures is reported.
this.failures = (this.failures || 0) + 1
const persistent = timedOut || this.failures >= 6
const persistent = timedOut || this.failures >= 8
if (persistent) this.changed('Map tiles unavailable. Check the saved key and connection. Reconnecting automatically…')
this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 5000 : 800)
this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 3000 : 600)
}
} finally {
clearTimeout(timer);
@@ -410,6 +421,9 @@ export const NavigationMap = {
props: ['data', 'stale'], data: () => ({
error: '', map: null, locationFresh: false, lastLocation: null, following: true
}),
computed: {
googleMap() { return this.data?.mapProvider === 'google' && !!this.data?.hasGoogleKey && !this.data?.googleMap?.failure },
},
mounted() {
this.map = markRaw(new RasterMap(this.$refs.canvas, (error) => {
if (error !== undefined) this.error = error
@@ -447,9 +461,12 @@ export const NavigationMap = {
<button type="button" class="gx-navigation-map__control" :class="{'gx-navigation-map__control--active':!following}" @click="map.recenter()" :aria-pressed="following" aria-label="Recenter and follow"><i class="bi bi-crosshair" aria-hidden="true"></i></button>
</div>
<GxNotice v-if="error" tone="danger">{{error}}</GxNotice>
<a class="gx-navigation-map__logo" href="https://www.mapbox.com/" target="_blank" rel="noopener noreferrer" aria-label="Mapbox">
<a v-if="!googleMap" class="gx-navigation-map__logo" href="https://www.mapbox.com/" target="_blank" rel="noopener noreferrer" aria-label="Mapbox">
</a>
<div class="gx-navigation-map__credits">
<div v-if="googleMap" class="gx-navigation-map__credits">
<a class="gx-link" href="https://www.google.com/maps" target="_blank" rel="noopener noreferrer">Google Maps</a> · <span>{{ data?.googleMap?.copyright || 'Map data © Google' }}</span> · <a class="gx-link" href="https://www.google.com/intl/en-US_US/help/terms_maps/" target="_blank" rel="noopener noreferrer">Terms</a>
</div>
<div v-else class="gx-navigation-map__credits">
<a class="gx-link" href="https://www.mapbox.com/about/maps/" target="_blank" rel="noopener noreferrer">© Mapbox</a> · <a class="gx-link" href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">© OpenStreetMap</a> · <a class="gx-link" href="https://apps.mapbox.com/feedback/" target="_blank" rel="noopener noreferrer">Improve this map</a>
</div>
</section>`
@@ -0,0 +1,81 @@
// Pieces of the navigation setup page: a compact M3 choice group with an info popover and the Mapbox/Google comparison.
export const ChoiceGroup = {
name: "ChoiceGroup",
props: { label: { type: String, required: true }, hint: { type: String, default: "" }, modelValue: { type: String, default: "" },
options: { type: Array, required: true }, disabled: { type: Boolean, default: false } },
emits: ["update:modelValue"],
data() { return { infoOpen: false } },
computed: {
selectedOption() { return this.options.find((option) => option.value === this.modelValue) || this.options[0] || null },
},
methods: {
pick(event, option) {
event.target.checked = this.modelValue === option.value
if (!option.disabled && !this.disabled) this.$emit("update:modelValue", option.value)
},
},
template: `
<fieldset class="gx-choice" :disabled="disabled" :aria-label="label">
<div class="gx-choice__head">
<strong class="gx-choice__legend">{{ label }}</strong>
<button type="button" class="gx-icon-btn gx-choice__info-btn" :aria-expanded="infoOpen" :aria-label="'More info about ' + label"
:title="'More info about ' + label" @click="infoOpen = !infoOpen">
<i class="bi" :class="infoOpen ? 'bi-info-circle-fill' : 'bi-info-circle'" aria-hidden="true"></i>
</button>
</div>
<p v-if="hint" class="gx-choice__hint">{{ hint }}</p>
<div class="gx-choice__grid">
<label v-for="option in options" :key="option.value" class="gx-choice__card"
:class="{ 'gx-choice__card--on': modelValue === option.value, 'gx-choice__card--off': option.disabled }">
<input type="radio" class="gx-sr-only" :name="label" :value="option.value" :checked="modelValue === option.value"
:disabled="option.disabled || disabled" @change="pick($event, option)">
<span class="gx-choice__title">
<i class="bi" :class="modelValue === option.value ? 'bi-check-circle-fill' : 'bi-circle'" aria-hidden="true"></i>
<strong>{{ option.label }}</strong>
<span v-if="option.badge" class="gx-starport-pill gx-starport-pill--soon">{{ option.badge }}</span>
</span>
</label>
</div>
<p v-if="selectedOption?.detail && !infoOpen" class="gx-choice__active-summary">{{ selectedOption.detail }}</p>
<div v-if="infoOpen" class="gx-choice__popover" role="region" :aria-label="label + ' details'">
<div class="gx-choice__popover-head">
<strong>{{ label }} options</strong>
<button type="button" class="gx-icon-btn gx-choice__popover-close" aria-label="Close details" @click="infoOpen = false">
<i class="bi bi-x-lg" aria-hidden="true"></i>
</button>
</div>
<dl class="gx-choice__popover-list">
<div v-for="option in options" :key="option.value" class="gx-choice__popover-item">
<dt><strong>{{ option.label }}</strong> <span v-if="option.badge" class="gx-starport-pill gx-starport-pill--soon">{{ option.badge }}</span></dt>
<dd>{{ option.detail }} <span v-if="option.limit" class="gx-choice__limit">{{ option.limit }}</span></dd>
</div>
</dl>
</div>
</fieldset>`,
}
// Provider capabilities and limits.
export const COMPARE_ROWS = [
["Place search and addresses", "Yes", "Yes, when Google gives directions; Mapbox is the fallback"],
["Offline road maps", "Yes", "No, Google tiles can't be saved"],
["Lane arrows on the turn card", "Yes", "No"],
["Traffic in route times", "Yes", "Yes, with a correction every 7½ minutes"],
["Map picture", "Road lines", "Street map with traffic colors"],
["Needs", "Mapbox token", "Google key with billing on"],
["Free monthly allowance", "Set by Mapbox; counted for this comma", "100,000 map tiles, 10,000 routes, 5,000 traffic routes"],
["When the allowance runs out", "Typing suggestions, address lookups and offline downloads pause until the 1st", "The comma stops at 99% and uses Mapbox until it resets"],
]
export const SourceCompare = {
name: "SourceCompare",
data() { return { rows: COMPARE_ROWS } },
template: `
<details class="gx-starport-wiki"><summary>Compare Mapbox and Google</summary>
<div class="gx-compare" role="table" aria-label="Mapbox compared with Google">
<div class="gx-compare__row gx-compare__row--head" role="row"><span role="columnheader">What you get</span><span role="columnheader">Mapbox</span><span role="columnheader">Google</span></div>
<div v-for="row in rows" :key="row[0]" class="gx-compare__row" role="row">
<span role="rowheader">{{ row[0] }}</span><span role="cell">{{ row[1] }}</span><span role="cell">{{ row[2] }}</span></div>
</div>
<p class="gx-note">Counts cover this comma only. Mapbox and Google bill everything that uses your key, including other apps.</p>
</details>`,
}
+260 -96
View File
@@ -1,4 +1,4 @@
import { parseSharedDestination } from "./share-destination.js"
import { isMapLink } from "./share-destination.js"
import { GxNotice } from "./notice.js"
import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
import { connectionError } from "./polling.js"
@@ -7,6 +7,7 @@ import { MapOperationsPanel } from "./map-operations.js"
import { OfflineRoadMapsPanel } from "./offline-road-maps.js"
import { GalaxySelect } from "./galaxy-select.js"
import { reportSave } from "./save-feedback.js"
import { ChoiceGroup, SourceCompare } from "./navigation-setup.js"
export function searchUuid() {
if (typeof crypto.randomUUID === "function") return crypto.randomUUID()
@@ -24,8 +25,10 @@ export function remainingLocationLease(lease, requestStarted, now = performance.
const STATUS = new Set(["disabled", "needsKey", "noDestination", "waitingForLocation", "routing", "guiding", "arrived", "routeUnavailable", "stale"])
const ROUTE_AVOIDANCES = [{ key: "avoidTolls", label: "Avoid tolls" }, { key: "avoidHighways", label: "Avoid highways" },
{ key: "avoidFerries", label: "Avoid ferries" }]
const GPS_MODES = [{ value: "backup", label: "Phone GPS as backup" }, { value: "comma", label: "Comma and car GPS only" },
{ value: "phone", label: "Prefer phone GPS" }]
const GPS_MODES = [
{ value: "backup", label: "Comma and car, phone as backup", hint: "Uses the comma's or car's GPS. The phone fills in only when neither has a fix." },
{ value: "comma", label: "Comma and car only", hint: "Never uses the phone. Choose this if you don't share phone GPS." },
{ value: "phone", label: "Phone first", hint: "Uses the phone whenever it has a recent fix, otherwise the comma or car." }]
const GPS_NAMES = { comma: "Comma", car: "Car", phone: "Phone" }
const coordinate = (value) => !!value && Number.isFinite(value.latitude) && Math.abs(value.latitude) <= 90 &&
Number.isFinite(value.longitude) && Math.abs(value.longitude) <= 180
@@ -94,12 +97,13 @@ export class NavigationClient {
this.busy = false
this.error = ""
this.stale = false
this.refusal = null
}
emit() { this.publish({ data: this.data, results: this.results, searched: this.searched, busy: this.busy, error: this.error, stale: this.stale,
suggestions: this.suggestions }) }
stop() {
if (this.searchId && this.data) {
suggestions: this.suggestions, resultsProvider: this.resultsProvider, suggestionsProvider: this.suggestionsProvider }) }
stop(keep = false) {
if (!keep && this.searchId && this.data) {
this.fetcher("./api/navigation/action", { method: "POST", credentials: "same-origin", cache: "no-store",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "cancelSearch",
revision: this.data.revision, searchId: this.searchId }) }).catch(() => {})
@@ -110,15 +114,17 @@ export class NavigationClient {
this.controller?.abort()
if (this.timer !== null) this.cancelTimer(this.timer)
this.controller = this.timer = null
this.data = null
this.results = []
this.searched = false
if (!keep) {
this.data = null
this.results = []
this.searched = false
}
this.error = ""
this.busy = this.stale = false
this.endSuggestions(false)
this.emit()
}
start() { this.stop(); this.active = true; return this.load() }
start(keep = false) { this.stop(keep); this.active = true; return this.load() }
load() { return this.run("status") }
async search(query) {
const text = query.trim()
@@ -179,6 +185,7 @@ export class NavigationClient {
this.suggestions = []
} else {
this.suggestions = payload.results
this.suggestionsProvider = payload.provider
this.suggestionResultsQuery = text
}
this.emit()
@@ -205,6 +212,7 @@ export class NavigationClient {
}
async run(operation, body = null) {
this.refusal = null
if (!this.active || this.busy) return null
this.controller?.abort()
if (this.timer !== null) this.cancelTimer(this.timer)
@@ -216,7 +224,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 : operation === "action" && body?.action === "share" ? 30000 : 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}` : ""
@@ -231,12 +240,17 @@ export class NavigationClient {
if (response.status === 401 || response.status === 503 && ["access_unavailable", "setup_required"].includes(payload?.code)) {
this.stop(); this.unauthorized(); return null
}
if (!response.ok) throw new Error(payload?.error || "Navigation could not complete this request.")
if (!response.ok) {
// A shared place the comma could not pin down comes back with the search to show instead.
if (response.status === 400 && body?.action === "share" && typeof payload?.query === "string") { this.refusal = payload; return null }
throw new Error(payload?.error || "Navigation could not complete this request.")
}
this.error = ""
if (operation === "search") {
if (!Array.isArray(payload.results) || payload.results.length > 20 || !payload.results.every(validSearchResult))
throw new Error("Search results could not be read.")
this.results = payload.results
this.resultsProvider = payload.provider
this.searched = true
} else {
if (payload?.routeUnchanged === true) {
@@ -259,7 +273,7 @@ export class NavigationClient {
}
if (!sameSnapshot(payload, this.data)) this.data = payload
this.stale = false
if (operation === "action" && ["select", "selectPlace", "clear"].includes(body.action)) { this.results = []; this.searched = false }
if (operation === "action" && ["select", "selectPlace", "clear", "share"].includes(body.action)) { this.results = []; this.searched = false }
}
return payload
} catch (error) {
@@ -294,15 +308,33 @@ export const FavoriteChoices = {
export const NavigationPage = {
name: "NavigationPage",
components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect },
components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect, ChoiceGroup, SourceCompare },
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,
suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false } },
data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, mapboxOpen: false, googleOpen: false, searched: false,
suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false, resultsProvider: null, suggestionsProvider: null } },
watch: { initialTab(value) { this.tab = value } },
computed: {
routeAvoidances() { return ROUTE_AVOIDANCES },
gpsModes() { return GPS_MODES },
googleReady() { return !!this.data?.hasGoogleKey },
mapChoices() {
return [{ value: "mapbox", label: "Mapbox", detail: "Road lines, drawn from saved or live Mapbox data.", limit: "Works offline once roads are saved." },
{ value: "google", label: "Google", detail: "Google's street map with traffic colors.", disabled: !this.googleReady, badge: !this.data || this.googleReady ? "" : "Needs key",
limit: "Needs internet and the Mapbox key. Google tiles can't be saved offline." }]
},
routeChoices() {
return [{ value: "mapbox", label: "Mapbox", detail: "Turn-by-turn with lane arrows.", limit: "Counted against your Mapbox allowance." },
{ value: "google", label: "Google", detail: "Routes that follow live traffic, and place search by Google.", disabled: !this.googleReady, badge: !this.data || this.googleReady ? "" : "Needs key",
limit: "Needs the Mapbox key too. No lane arrows. Falls back to Mapbox when its limits run out." }]
},
gpsChoices() { return GPS_MODES.map((mode) => ({ value: mode.value, label: mode.label, detail: mode.hint })) },
destinationWays() {
return [{ icon: "bi-search", title: "Search here", detail: "Type an address or place on the Destination page." },
{ icon: "bi-link-45deg", title: "Paste a Google Maps link", detail: "Paste a place link into search, short links included." },
{ icon: "bi-android2", title: "Share from Android", detail: "Google Maps → Share → StarPilot. The route starts on your comma." },
{ icon: "bi-apple", title: "Share from iPhone", detail: "Google Maps or Apple Maps → Share → StarPilot. The route starts on your comma." }]
},
gpsLabel() {
if (this.mode !== "local" || !this.ready || this.stale) return "GPS Source"
const source = this.data?.location?.lastKnown ? null : GPS_NAMES[this.data?.location?.source]
@@ -335,6 +367,33 @@ 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] }))
},
// Place search follows the Directions choice, as on the comma.
googlePlaces() { return this.data?.routeProvider === "google" && !!this.data?.hasGoogleKey },
sources() {
if (!this.data) return []
const google = (value) => value === "google" && !!this.data.hasGoogleKey ? "Google" : "Mapbox"
return [{ label: "Map", value: google(this.data.mapProvider), icon: "bi-map" },
{ label: "Directions", value: google(this.data.routeProvider), icon: "bi-signpost-split" },
{ label: "Places", value: google(this.data.routeProvider), icon: "bi-geo-alt" },
{ label: "Position", value: this.gpsLabel.replace("GPS: ", ""), icon: "bi-crosshair" }]
},
googleUsage() { return this.data?.googleMap?.usage || null },
googleRouteUsage() { return this.data?.googleRoutes?.usage || null },
googleEssentialUsage() { return this.data?.googleRoutes?.essentials || null },
googlePlaceUsage() { return this.data?.googlePlaces?.usage || null },
googleSuggestionUsage() { return this.data?.googlePlaces?.suggestions || null },
googleTests() {
const test = this.googleTest
if (!test) return []
return [["Map Tiles API", test, "tile.googleapis.com"], ["Routes API", test.routes, "routes.googleapis.com"], ["Places API (New)", test.places, "places.googleapis.com"]]
.filter(([, result]) => result).map(([name, result, api]) => ({ name, ok: !!result.ok, message: result.message, missing: !result.ok && result.failure !== "budget",
link: result.failure === "billing" ? { href: "https://console.cloud.google.com/billing", label: "Turn on billing" } :
["key", "disabled"].includes(result.failure) ? { href: `https://console.cloud.google.com/apis/library/${api}`, label: `Open ${name} in Google Cloud` } : null }))
},
googleWorking() {
const rows = this.googleTests
return rows.length ? `${rows.length - rows.filter((row) => row.missing).length} of ${rows.length} APIs working` : ""
},
path() { return routePath(this.data?.route) },
summary() {
const instruction = this.data?.instruction, route = this.data?.alternatives?.[this.data?.selectedRoute || 0]
@@ -354,7 +413,7 @@ export const NavigationPage = {
created() { this.client = new NavigationClient({ publish: (state) => Object.assign(this.$data, state), unauthorized: this.unauthorized }) },
mounted() {
if (this.mode !== "local") return
this.visibilityHandler = () => document.visibilityState === "hidden" ? this.client.stop() : this.client.start()
this.visibilityHandler = () => document.visibilityState === "hidden" ? this.client.stop(true) : this.client.start(true)
document.addEventListener("visibilitychange", this.visibilityHandler)
if (document.visibilityState !== "hidden") {
this.client.start().then(async () => {
@@ -363,17 +422,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 +439,16 @@ export const NavigationPage = {
this.tab = tab
this.go?.(tab === 'route' ? '/navigation' : `/navigation/${tab}`)
},
// The comma opens the link, looks the place up, turns navigation on and starts the route.
async openShared(text) {
if (await this.client.action('share', { text: String(text).slice(0, 8192) })) return
const query = this.client.refusal?.query
if (!query) return
// Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick.
if (!this.client.data?.enabled && !await this.client.action('configure', { patch: { enabled: true } })) return
this.query = query
await this.client.search(query)
},
async search() {
if (this.searchPending) return
clearTimeout(this.suggestTimer)
@@ -393,13 +456,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 +522,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` :
@@ -469,87 +538,180 @@ export const NavigationPage = {
template: `
<div class="gx-view gx-navigation" :inert="busy || searchPending" :aria-busy="busy || searchPending || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Navigation</h2>
<p>Set a destination, prepare offline maps, and configure navigation and Mapbox.</p></div></header>
<p>Pick a destination, save maps for offline use, and choose where maps, directions and position come from.</p></div></header>
<ul v-if="sources.length" class="gx-navigation__sources" aria-label="Current sources">
<li v-for="source in sources" :key="source.label"><a class="gx-navigation__chip" href="#/navigation/setup" @click.prevent="selectTab('setup')"><i class="bi" :class="source.icon" aria-hidden="true"></i><span>{{ source.label }}: {{ source.value }}</span></a></li>
</ul>
<div class="gx-tabs gx-actions" role="group" aria-label="Navigation tools">
<button v-for="item in tabs" :key="item.tab"
type="button" class="gx-btn" :class="tab === item.tab ? '' : 'gx-btn--tonal'" :aria-pressed="tab === item.tab" @click="selectTab(item.tab)">{{ item.name }}</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="openGpsSetup">{{ gpsLabel }}</button>
</div>
<div v-if="tab === 'maps'" class="gx-navigation__offline">
<OfflineRoadMapsPanel :mode="mode" :unauthorized="unauthorized" :has-key="!!data?.hasKey" :metric="data?.isMetric !== false" />
<MapOperationsPanel :mode="mode" :unauthorized="unauthorized" />
</div>
<template v-else-if="tab === 'setup'">
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to set up navigation and choose a destination.</p>
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to set up navigation.</p>
<GxNotice tone="danger" v-if="error">{{ error }}</GxNotice>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-compass" aria-hidden="true"></i><span class="gx-section__title">Navigation</span></div>
<p>Show directions on your comma. Navigation works with every driving model. Route guidance helps prepare for turns; steering and speed control follow your normal engagement settings.</p>
<div v-if="data" class="gx-row gx-row--borderless"><span class="gx-row__info gx-row__label">Navigation</span>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Navigation" :checked="data.enabled" :disabled="!controlsAvailable"
<section class="gx-card gx-navigation__section gx-navigation__power">
<div class="gx-row gx-row--borderless"><span class="gx-row__info"><strong class="gx-row__label">Navigation</strong><small class="gx-note">Turn-by-turn guidance on your comma. It works with every driving model and never steers for you.</small></span>
<label v-if="data" class="gx-switch"><input type="checkbox" role="switch" aria-label="Navigation" :checked="data.enabled" :disabled="!controlsAvailable"
@change="$event.target.checked=data.enabled; reportSave(() => client.action('configure', {patch: {enabled: !data.enabled}}))"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
</section>
<section ref="gpsSetup" tabindex="-1" class="gx-card gx-navigation__section gx-navigation__gps" aria-labelledby="navigation-gps-heading">
<h3 id="navigation-gps-heading">GPS Source</h3>
<p>Choose where your comma gets its position for navigation and map speed limits. Phone GPS comes from the StarPilot app over Bluetooth or local Wi-Fi.</p>
<div class="gx-row gx-row--stack gx-row--borderless">
<span class="gx-row__label" id="navigation-gps-mode">Use</span>
<GalaxySelect class="gx-field gx-field--full" aria-labeledby="navigation-gps-mode" :value="data?.gpsSource || 'backup'" :disabled="!available || !data"
@change="client.action('configure', {patch: {gpsSource: $event.target.value}})">
<option v-for="option in gpsModes" :key="option.value" :value="option.value">{{ option.label }}</option>
</GalaxySelect>
</div>
<p v-if="data?.phoneGps">Phone updates: {{ data.phoneGps.usable ? 'usable' : 'waiting for a usable fix' }}.
Last update {{ Math.round(data.phoneGps.receivedAgeMs / 1000) }} seconds ago.
<span v-if="!data.phoneGps.accepted">{{ ({poorAccuracy: 'Position accuracy is too low.', outOfOrder: 'An older or repeated update was ignored.', delayed: 'An update arrived too late.'})[data.phoneGps.reason] || 'The last update was invalid.' }}</span>
</p>
<h4>Set up GPS sharing</h4>
<div class="gx-actions" role="group" aria-label="GPS setup guides">
<button v-for="source in [{id:'android',label:'Android App'},{id:'iphone',label:'iPhone'}]" :key="source.id"
type="button" class="gx-btn" :class="gpsGuide === source.id ? '' : 'gx-btn--tonal'" :aria-pressed="gpsGuide === source.id"
@click="gpsGuide = source.id">{{ source.label }}</button>
</div>
<div v-if="gpsGuide === 'android'">
<ol><li>Open the StarPilot companion app and connect to your comma over Bluetooth or Galaxy Wi-Fi.</li>
<li>Open Connections → Phone GPS → <strong>Share phone GPS with comma</strong>.</li>
<li>Allow precise location. Keep the app’s GPS-sharing notification active while driving.</li></ol>
<p>To stop, open Connections and select <strong>Stop sharing phone GPS</strong>.</p>
</div>
<div v-else>
<ol><li>Open the StarPilot iPhone companion app and connect to your comma over Bluetooth or Wi-Fi.</li>
<li>On the app’s main Settings page, turn on <strong>Share Phone Location</strong>.</li>
<li>Set location access to <strong>Always</strong> and enable Precise Location in iPhone Settings. The app continues sharing in the background while the switch is on.</li></ol>
<p>Turn off <strong>Share Phone Location</strong> on the app’s main Settings page to stop sharing.</p>
</div>
<details><summary>About phone GPS and switching phones</summary>
<p>The GPS source you choose is used for navigation and for map-based speed limits and curves. The phone must reach the comma over Bluetooth or local Wi-Fi; the remote tunnel doesn't carry GPS.</p>
<p>To change phones, stop GPS sharing in the old app and enable it in the other app. Both apps need a version with phone GPS support, and your comma must support receiving it.</p>
</details>
</section>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-signpost-split" aria-hidden="true"></i><span class="gx-section__title">Route preferences</span></div>
<p>Apply to new routes and automatic reroutes. Changing a preference recalculates your current route.</p>
<div v-for="option in routeAvoidances" :key="option.key" class="gx-row">
<span class="gx-row__info gx-row__label">{{ option.label }}</span>
<label class="gx-switch"><input type="checkbox" role="switch" :aria-label="option.label" :checked="!!data?.[option.key]"
:disabled="!available" @change="reportSave(() => client.action('configure', {patch: {[option.key]: $event.target.checked}}))"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label>
<div class="gx-navigation__prefs" role="group" aria-label="Route preferences">
<div class="gx-navigation__prefs-head">
<strong class="gx-row__label">Route preferences</strong>
<small class="gx-note">Applies to new routes and reroutes, and recalculates your current route.</small>
</div>
<div class="gx-navigation__pref-chips">
<label v-for="option in routeAvoidances" :key="option.key" class="gx-navigation__pref" :class="{ 'gx-navigation__pref--on': !!data?.[option.key], 'gx-navigation__pref--disabled': !available }">
<input type="checkbox" role="switch" class="gx-sr-only" :aria-label="option.label" :checked="!!data?.[option.key]"
:disabled="!available" @change="reportSave(() => client.action('configure', {patch: {[option.key]: $event.target.checked}}))">
<i class="bi" :class="data?.[option.key] ? 'bi-check-lg' : 'bi-slash-circle'" aria-hidden="true"></i>
<span>{{ option.label }}</span>
</label>
</div>
</div>
</section>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-map" aria-hidden="true"></i><span class="gx-section__title">Mapbox</span></div>
<p>One public Mapbox access token (starting with pk.) handles the map, place and address search, and routes. A separate secret token is not needed.</p>
<p>Save your token while parked. Galaxy keeps it on your comma and never displays it after saving. Address searches use temporary geocoding. Search suggestions are temporary and used only for the current route. Favorites and recent destinations are also kept on your comma; going to one skips search, so it uses none of your search allowance. URL-restricted keys may reject map requests.</p>
<p class="gx-note">Typing suggestions, address lookups and offline road maps stop just short of their free monthly allowances and resume on the 1st. Routes, full place searches and map views are counted but not limited. These counts cover this comma only; Mapbox bills total account usage, including other apps and devices.</p>
<dl v-if="usageRows.length" class="gx-navigation__usage" aria-label="Mapbox use this month">
<template v-for="row in usageRows" :key="row.key"><dt>{{ row.label }}</dt><dd>{{ row.used.toLocaleString() }} of {{ row.limit.toLocaleString() }} free this month</dd></template>
</dl>
<a class="gx-btn gx-btn--tonal gx-navigation__token-link" href="https://account.mapbox.com/access-tokens/" target="_blank" rel="noopener noreferrer">Get a Mapbox access token</a>
<p v-if="data?.hasKey" class="gx-note">A Mapbox key is saved.</p>
<div class="gx-field-group"><label for="navigation-token">Public Mapbox access token</label>
<form @submit.prevent="saveKey(false)" class="gx-navigation__search">
<input id="navigation-token" class="gx-field" type="password" autocomplete="off" v-model="token" placeholder="pk.…" maxlength="2048" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !token.trim()">{{ data?.hasKey ? 'Replace key' : 'Save key' }}</button>
</form></div>
<section class="gx-card gx-starport-step" :class="{ 'gx-starport-step--done': data?.hasKey }">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true"><i v-if="data?.hasKey" class="bi bi-check-lg"></i><template v-else>1</template></span>
<div>
<div class="gx-navigation__step-title"><h3>Mapbox key</h3><span class="gx-starport-pill" :class="data?.hasKey ? 'gx-starport-pill--ready' : 'gx-starport-pill--soon'" role="status">{{ !data ? 'Loading…' : data.hasKey ? 'Key saved' : 'Needs a key' }}</span></div>
<p>Required, with or without Google. Finds places, saves offline roads, plans routes and backs up Google.</p>
</div>
<button v-if="data?.hasKey" type="button" class="gx-btn gx-btn--tonal" :aria-expanded="mapboxOpen" aria-controls="navigation-mapbox" @click="mapboxOpen = !mapboxOpen">{{ mapboxOpen ? 'Hide' : 'Manage' }}</button>
</div>
<div id="navigation-mapbox" v-show="!data?.hasKey || mapboxOpen" class="gx-starport-step__body">
<details class="gx-starport-wiki gx-navigation__guide" :open="!data?.hasKey"><summary>Setup your mapbox key</summary>
<ol><li><strong>Create an account.</strong> Sign up free at <a href="https://account.mapbox.com/auth/signup/" target="_blank" rel="noopener noreferrer">Mapbox ↗</a>, or sign in if you already have one.</li>
<li><strong>Open your tokens.</strong> Go to <a href="https://account.mapbox.com/access-tokens/" target="_blank" rel="noopener noreferrer">Access tokens ↗</a>. The <strong>Default public token</strong> is the one you need. It starts with <strong>pk.</strong></li>
<li><strong>Copy it.</strong> Use the public token only. A secret token (starts with sk.) isn't needed, and URL-restricted tokens may be rejected.</li>
<li><strong>Paste and save.</strong> Paste the token below while parked and press <strong>Save key</strong>.</li></ol>
</details>
<form @submit.prevent="saveKey(false)" class="gx-navigation__search">
<label for="navigation-token" class="gx-sr-only">Public Mapbox access token</label>
<input id="navigation-token" class="gx-field" type="password" autocomplete="off" v-model="token" placeholder="pk.…" maxlength="2048" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !token.trim()">{{ data?.hasKey ? 'Replace key' : 'Save key' }}</button>
</form>
<dl v-if="usageRows.length" class="gx-navigation__usage" aria-label="Mapbox use this month">
<template v-for="row in usageRows" :key="row.key"><dt>{{ row.label }}</dt><dd>{{ row.used.toLocaleString() }} of {{ row.limit.toLocaleString() }} free</dd></template>
</dl>
<details class="gx-starport-wiki"><summary>About the token and your allowance</summary>
<p>Use the public token that starts with pk. A secret token isn't needed, and URL-restricted tokens may be rejected. Galaxy keeps the token on your comma and never shows it again.</p>
<p>Typing suggestions, address lookups and offline road maps stop just short of their free monthly allowances and resume on the 1st. Routes, full searches and map views are counted but not limited. Saved places and recents skip search entirely.</p>
</details>
</div>
</section>
<section class="gx-card gx-starport-step" :class="{ 'gx-starport-step--done': data?.hasGoogleKey }">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true"><i v-if="data?.hasGoogleKey" class="bi bi-check-lg"></i><template v-else>2</template></span>
<div>
<div class="gx-navigation__step-title"><h3>Google key</h3><span class="gx-starport-pill" :class="data?.hasGoogleKey ? 'gx-starport-pill--ready' : ''" role="status">{{ data?.hasGoogleKey ? (googleWorking ? 'Key saved · ' + googleWorking : 'Key saved') : 'Optional' }}</span></div>
<p>Added on top of the Mapbox key. Unlocks Google's street &amp; traffic map, live-traffic routes and place search.</p>
</div>
<button type="button" class="gx-btn gx-btn--tonal" :aria-expanded="googleOpen" aria-controls="navigation-google" @click="googleOpen = !googleOpen">{{ googleOpen ? 'Hide' : data?.hasGoogleKey ? 'Manage' : 'Add key' }}</button>
</div>
<GxNotice v-if="data?.hasGoogleKey && !data?.hasKey" tone="warn">Google isn't used until the Mapbox key above is added too.</GxNotice>
<div id="navigation-google" v-show="googleOpen" class="gx-starport-step__body">
<details class="gx-starport-wiki gx-navigation__guide" :open="!data?.hasGoogleKey"><summary>Setup your google key</summary>
<ol><li><strong>Create a project.</strong> Sign in to <a href="https://console.cloud.google.com/projectcreate" target="_blank" rel="noopener noreferrer">Google Cloud ↗</a> and create a project.</li>
<li><strong>Turn on billing.</strong> Open <a href="https://console.cloud.google.com/billing" target="_blank" rel="noopener noreferrer">Google Cloud Billing ↗</a>. Google asks for a card and puts a temporary $50 hold on it, like a gas station does. It is not a charge and it drops off on its own. StarPilot blocks Google at 99% of the free usage, so you won't be charged.</li>
<li><strong>Enable three APIs.</strong> Press Enable on each: <a href="https://console.cloud.google.com/apis/library/tile.googleapis.com" target="_blank" rel="noopener noreferrer">Map Tiles API ↗</a> for the map, <a href="https://console.cloud.google.com/apis/library/routes.googleapis.com" target="_blank" rel="noopener noreferrer">Routes API ↗</a> for routes and <a href="https://console.cloud.google.com/apis/library/places.googleapis.com" target="_blank" rel="noopener noreferrer">Places API (New) ↗</a> for place search.</li>
<li><strong>Create the key.</strong> Open <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">Credentials ↗</a>, create an API key and limit it to those three APIs. Leave application restrictions off; the comma's address changes on cellular.</li>
<li><strong>Paste and test.</strong> Keep your Mapbox key; Google works alongside it. Paste the Google key below while parked, press <strong>Save key</strong>, then <strong>Test key</strong>. It checks all three APIs.</li></ol>
</details>
<form @submit.prevent="saveGoogleKey" class="gx-navigation__search">
<label for="navigation-google-key" class="gx-sr-only">Google Maps Platform API key</label>
<input id="navigation-google-key" class="gx-field" type="password" autocomplete="off" v-model="googleKey" placeholder="AIza…" maxlength="128" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !googleKey.trim()">{{ data?.hasGoogleKey ? 'Replace key' : 'Save key' }}</button>
</form>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" :disabled="!available || !googleKey.trim() && !data?.hasGoogleKey" @click="testGoogleKey">Test key</button></div>
<p v-if="googleWorking && !data?.hasGoogleKey" class="gx-note" role="status"><strong>{{ googleWorking }}</strong></p>
<GxNotice v-for="row in googleTests" :key="row.name" :tone="row.ok ? 'success' : 'warn'">{{ row.name }}: {{ row.message }}
<a v-if="row.link" :href="row.link.href" target="_blank" rel="noopener noreferrer">{{ row.link.label }}</a></GxNotice>
<GxNotice v-if="data?.googleMap?.failure" tone="warn">{{ data.googleMap.failure }}</GxNotice>
<GxNotice v-if="data?.googleRoutes?.failure" tone="warn">{{ data.googleRoutes.failure }}</GxNotice>
<dl v-if="googleUsage" class="gx-navigation__usage" aria-label="Google use">
<dt>Map tiles this month</dt><dd>{{ googleUsage.monthUsed.toLocaleString() }} of {{ googleUsage.monthLimit.toLocaleString() }} free</dd>
<dt>Map tiles today</dt><dd>{{ googleUsage.dayUsed.toLocaleString() }} of {{ googleUsage.dayLimit.toLocaleString() }} free</dd>
<template v-if="googleEssentialUsage"><dt>Routes this month</dt><dd>{{ googleEssentialUsage.monthUsed.toLocaleString() }} of {{ googleEssentialUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googleRouteUsage"><dt>Traffic routes this month</dt><dd>{{ googleRouteUsage.monthUsed.toLocaleString() }} of {{ googleRouteUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googlePlaceUsage"><dt>Place searches this month</dt><dd>{{ googlePlaceUsage.monthUsed.toLocaleString() }} of {{ googlePlaceUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googleSuggestionUsage"><dt>Typing suggestions this month</dt><dd>{{ googleSuggestionUsage.monthUsed.toLocaleString() }} of {{ googleSuggestionUsage.monthLimit.toLocaleString() }} free</dd></template>
</dl>
<details class="gx-starport-wiki"><summary>How the Google limits work</summary>
<p>The comma stops at 99% of Google's free allowance: 100,000 map tiles a month (15,000 a day), 10,000 routes, 5,000 traffic routes, 5,000 place searches (shared places included) and 10,000 typing suggestions. Every route and reroute uses live traffic, and one more request every 7½ minutes corrects the arrival time.</p>
<p>Past 20 reroutes in an hour, or when traffic routes run out, routes ignore traffic. Past both limits the comma uses Mapbox until they reset. Google routes have no lane arrows. Place search uses Google when Google gives directions, and Mapbox if Google can't answer.</p>
</details>
</div>
</section>
<section class="gx-card gx-starport-step">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true">3</span>
<div><h3>Choose your sources</h3><p>Google choices need both keys. Each one falls back to Mapbox if it can't work.</p></div>
</div>
<div class="gx-starport-step__body">
<ChoiceGroup label="Map picture" :model-value="data?.mapProvider || 'mapbox'" :options="mapChoices" :disabled="!available || !data"
@update:model-value="reportSave(() => client.action('configure', {patch: {mapProvider: $event}}))" />
<ChoiceGroup label="Directions" :model-value="data?.routeProvider || 'mapbox'" :options="routeChoices" :disabled="!available || !data"
@update:model-value="reportSave(() => client.action('configure', {patch: {routeProvider: $event}}))" />
<div ref="gpsSetup" tabindex="-1" class="gx-navigation__gps">
<ChoiceGroup label="Position" :model-value="data?.gpsSource || 'backup'" :options="gpsChoices" :disabled="!available || !data"
@update:model-value="reportSave(() => client.action('configure', {patch: {gpsSource: $event}}))" />
<p v-if="data?.phoneGps" class="gx-navigation__gps-status" role="status">
<span class="gx-starport-pill" :class="data.phoneGps.usable ? 'gx-starport-pill--ready' : 'gx-starport-pill--soon'">
Phone GPS: {{ data.phoneGps.usable ? 'Receiving updates' : 'Waiting for a usable fix' }} · {{ Math.round(data.phoneGps.receivedAgeMs / 1000) }}s ago
</span>
<small v-if="!data.phoneGps.accepted" class="gx-note">{{ ({poorAccuracy: 'Accuracy is too low.', outOfOrder: 'An older update was ignored.', delayed: 'An update arrived late.'})[data.phoneGps.reason] || 'The last update was invalid.' }}</small>
</p>
<details class="gx-starport-wiki">
<summary>How to share phone GPS from the StarPilot app</summary>
<p class="gx-note">Reaches your comma over Bluetooth or local Wi-Fi, never the remote tunnel.</p>
<div class="gx-navigation__gps-guides">
<div class="gx-navigation__gps-card">
<strong><i class="bi bi-android2" aria-hidden="true"></i> Android</strong>
<ol class="gx-starport-mirror-steps">
<li>Open the StarPilot app and connect to your comma.</li>
<li>Open <strong>Connections → Phone GPS</strong> and turn on <strong>Share phone GPS with comma</strong>.</li>
<li>Allow precise location and leave the sharing notification on while driving.</li>
</ol>
</div>
<div class="gx-navigation__gps-card">
<strong><i class="bi bi-apple" aria-hidden="true"></i> iPhone</strong>
<ol class="gx-starport-mirror-steps">
<li>Open the StarPilot app and connect to your comma.</li>
<li>On the main Settings page, turn on <strong>Share Phone Location</strong>.</li>
<li>Set location access to <strong>Always</strong> and turn on <strong>Precise Location</strong> in iPhone Settings.</li>
</ol>
</div>
</div>
<p class="gx-note"><strong>Switching phones:</strong> stop sharing in the old app before turning it on in the new one.</p>
</details>
</div>
<SourceCompare />
</div>
</section>
<section class="gx-card gx-starport-step">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true"><i class="bi bi-send"></i></span>
<div><h3>Ways to send a destination</h3><p>Start a trip from Galaxy or share a place straight from your phone.</p></div>
</div>
<div class="gx-starport-step__body">
<ul class="gx-starport-list" aria-label="Ways to set a destination">
<li v-for="way in destinationWays" :key="way.title" class="gx-starport-row"><i class="bi" :class="way.icon" aria-hidden="true"></i>
<span class="gx-starport-row__text"><strong>{{ way.title }}</strong><small>{{ way.detail }}</small></span></li>
</ul>
<details class="gx-starport-wiki"><summary>How to share a place from your phone</summary>
<p><strong>Android:</strong> open a place in Google Maps, tap Share, then choose StarPilot.</p>
<p><strong>iPhone:</strong> open a place in Google Maps or Apple Maps, tap Share, then choose StarPilot. The first time, scroll the app row to More and turn on StarPilot.</p>
<p>Your comma turns on navigation and starts the route. Places without coordinates are looked up on your comma with your chosen route provider. A name alone opens the StarPilot app as a search.</p>
<p>Both need the latest StarPilot app, a Mapbox key above, and a way to reach your comma: Bluetooth, local Wi-Fi or the remote route. If your comma can't be reached, the phone keeps the place and sends it when it next connects, within 12 hours.</p>
</details>
</div>
</section>
</template>
<template v-else>
@@ -568,7 +730,7 @@ export const NavigationPage = {
<div class="gx-navigation__field">
<i class="bi bi-search" aria-hidden="true"></i>
<label for="navigation-search" class="gx-sr-only">Search destinations</label>
<input id="navigation-search" ref="search" v-model="query" placeholder="Address or place name" minlength="2" maxlength="200" required
<input id="navigation-search" ref="search" v-model="query" placeholder="Address, place or Google Maps link" minlength="2" maxlength="200" required
autocomplete="off" enterkeyhint="search" :disabled="!controlsAvailable" role="searchbox"
@input="typed" @focus="suggestOpen = true" @keydown.escape="closeSuggestions">
<button v-if="query || results.length" type="button" class="gx-navigation__icon" aria-label="Clear search" @mousedown.prevent @click="clearQuery"><i class="bi bi-x-lg" aria-hidden="true"></i></button>
@@ -601,6 +763,7 @@ export const NavigationPage = {
<button type="button" class="gx-navigation__icon" :aria-label="'Save ' + place.name" :aria-expanded="favoritePicker === favoriteKey(place)" :disabled="!controlsAvailable || place.temporary" :title="place.temporary ? 'Search for an address to save this place' : undefined" @click="openFavorite(place)"><i class="bi" :class="isFavorite(place) ? 'bi-star-fill' : 'bi-star'" aria-hidden="true"></i></button>
<FavoriteChoices v-if="favoritePicker === favoriteKey(place)" :available="controlsAvailable" @choose="saveAs(place, $event)" />
</div>
<div v-if="suggestions.length && googlePlaces" class="gx-navigation__group"><span>{{ suggestionsProvider === 'google' ? 'Suggestions from Google' : 'Suggestions from Mapbox, Google unavailable' }}</span></div>
<div v-for="place in suggestions" :key="place.id" class="gx-navigation__row">
<button type="button" class="gx-navigation__suggestion" :disabled="!controlsAvailable" @click="pick(place)">
<i class="bi bi-geo-alt-fill" aria-hidden="true"></i><span><strong><span translate="no">{{ place.name }}</span></strong><small v-if="place.description">{{ place.description }}</small></span></button>
@@ -644,6 +807,7 @@ export const NavigationPage = {
<template v-else>
<p v-if="busy || searchPending" role="status" class="gx-navigation__busy">{{ searchPending ? 'Searching…' : 'Working…' }}</p>
<p v-if="searched && !busy && !error && results.length === 0" class="gx-card gx-navigation__section gx-note">No places found. Try a nearby town or a more specific address.</p>
<p v-if="results.length && googlePlaces" class="gx-note" role="status">{{ resultsProvider === 'google' ? 'Places found with Google.' : "Google couldn't search just now, so these places are from Mapbox." }}</p>
<ul v-if="results.length" class="gx-navigation__places" aria-label="Search results">
<li v-for="place in results" :key="place.id" class="gx-navigation__row">
<button type="button" class="gx-navigation__suggestion" :disabled="!controlsAvailable" @click="pick(place)" :aria-label="'Start navigation to ' + place.name">
@@ -51,13 +51,15 @@ export function areaLabel(area) {
const progress = area.progress
if (!progress) return "Waiting for the downloader"
const percent = progress.total ? Math.floor(progress.done / progress.total * 100) : 0
return ({ queued: "Queued", downloading: `Downloading · ${percent}%`, waiting_wifi: `Waiting for Wi-Fi · ${percent}%`,
complete: "Saved for offline", incomplete: `${progress.failed} tiles missing · retries later`, no_space: "Storage full" })[progress.state]
return ({
queued: "Queued", downloading: `Downloading · ${percent}%`, waiting_wifi: `Waiting for Wi-Fi · ${percent}%`,
complete: "Saved for offline", incomplete: `${progress.failed} tiles missing · retries later`, no_space: "Storage full"
})[progress.state]
}
export class OfflineRoadsClient {
constructor({ publish, unauthorized = () => {}, fetcher = (...args) => fetch(...args),
later = (fn, ms) => setTimeout(fn, ms), cancel = (id) => clearTimeout(id) }) {
constructor({ publish, unauthorized = () => { }, fetcher = (...args) => fetch(...args),
later = (fn, ms) => setTimeout(fn, ms), cancel = (id) => clearTimeout(id) }) {
Object.assign(this, { publish, unauthorized, fetcher, later, cancel })
this.data = null
this.busy = false
@@ -76,9 +78,11 @@ export class OfflineRoadsClient {
const generation = ++this.generation, controller = this.controller = new AbortController()
const deadline = this.later(() => controller.abort(), 10000)
try {
const response = await this.fetcher("./api/navigation/offline", { credentials: "same-origin", cache: "no-store",
const response = await this.fetcher("./api/navigation/offline", {
credentials: "same-origin", cache: "no-store",
signal: controller.signal,
...(body === null ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }) })
...(body === null ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
})
const payload = await response.json().catch(() => null)
if (!this.active || generation !== this.generation) return null
if (controller.signal.aborted) throw new Error("Offline maps did not respond. Try again shortly.")
@@ -120,8 +124,10 @@ export class OfflineRoadsClient {
export const OfflineRoadMapsPanel = {
name: "OfflineRoadMapsPanel",
components: { GxNotice, BluetoothNotice, GalaxySettingRow },
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
hasKey: { type: Boolean, default: false }, metric: { type: Boolean, default: true } },
props: {
mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
hasKey: { type: Boolean, default: false }, metric: { type: Boolean, default: true }
},
data: () => ({ bluetooth: bluetoothConnection(), data: null, busy: false, error: "", point: null, name: "", radius: null, confirmDelete: null, notice: "" }),
created() { this.client = new OfflineRoadsClient({ publish: (update) => Object.assign(this.$data, update), unauthorized: this.unauthorized }) },
mounted() {
@@ -179,7 +185,7 @@ export const OfflineRoadMapsPanel = {
formatBytes, areaLabel, radiusLabel, switchRow,
ensureMap() {
if (this.bluetooth || this.map || !this.hasKey || !this.$refs.canvas) return
this.map = markRaw(new RasterMap(this.$refs.canvas, () => {}))
this.map = markRaw(new RasterMap(this.$refs.canvas, () => { }))
this.map.onTap = (point) => this.pick({ ...point, name: "" })
this.map.update({}, false)
if (this.data?.position) { this.map.center = this.data.position; this.map.zoom = START_ZOOM; this.map.initialized = true }
@@ -204,8 +210,10 @@ export const OfflineRoadMapsPanel = {
},
drawOverlays() {
if (!this.map) return
const saved = (this.data?.areas || []).map((area) => ({ ...area, stroke: area.progress?.state === "complete" ? "#34c778" : "#9d72ff",
fill: area.progress?.state === "complete" ? "#34c77822" : "#9d72ff1f" }))
const saved = (this.data?.areas || []).map((area) => ({
...area, stroke: area.progress?.state === "complete" ? "#34c778" : "#9d72ff",
fill: area.progress?.state === "complete" ? "#34c77822" : "#9d72ff1f"
}))
const draft = this.point ? [{ ...this.point, radiusKm: this.radiusKm, stroke: "#f5b642", fill: "#f5b64226", dash: [8, 6], width: 3 }] : []
const overlays = [...saved, ...draft], signature = JSON.stringify(overlays)
if (signature === this.overlaySignature) return // polls usually change nothing on the map
@@ -226,12 +234,20 @@ export const OfflineRoadMapsPanel = {
},
template: `
<section class="gx-card gx-offline-roads" aria-label="Offline road maps" :inert="busy" :aria-busy="busy || undefined">
<div class="gx-section__header"><i class="bi bi-signpost-split"></i><span class="gx-section__title">Map Overlay Roads</span></div>
<p class="gx-note">Road lines for the Android Auto map overlay. Saved areas stay on your comma, so the overlay keeps drawing roads with no signal. Downloads happen on Wi-Fi.</p>
<div class="gx-offline-roads__head">
<span class="gx-starport-step__num" aria-hidden="true"><i class="bi bi-cloud-download"></i></span>
<div>
<div class="gx-navigation__step-title">
<h3 class="gx-section__title">Offline Map Management</h3>
<span class="gx-starport-pill gx-starport-pill--danger">Mapbox only</span>
</div>
<p class="gx-note">Saves Mapbox road lines on your comma so the map overlay keeps drawing roads with no cell signal. Google Maps tiles require internet and can't be saved offline, so these road lines always back them up. Downloads happen on Wi-Fi.</p>
</div>
</div>
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to manage offline road maps.</p>
<template v-else>
<GxNotice tone="danger" v-if="error">{{ error }}</GxNotice>
<GxNotice tone="warn" v-if="!hasKey">Add your Mapbox key in Setup. Road maps download with the same key.</GxNotice>
<GxNotice tone="warn" v-if="!hasKey">Add your Mapbox key in Setup. Offline road maps download with that key.</GxNotice>
<GxNotice tone="warn" v-else-if="service.failure === 'key'">Mapbox rejected the saved key for map tiles. Check that it is a public (pk.) key without URL restrictions.</GxNotice>
<GxNotice tone="warn" v-if="service.failure === 'budget'">This comma's Mapbox road tile allowance is used up, so downloads pause until the 1st.</GxNotice>
<GxNotice tone="warn" v-if="service.noSpace">The comma's storage is nearly full, so new map areas are paused. Delete an area or free space.</GxNotice>
@@ -247,9 +263,10 @@ export const OfflineRoadMapsPanel = {
:index="0" :busy="busy" :disabled="!data" :save-value="(index, value) => setSaveDriven(value === 'On')" />
<div class="gx-offline-roads__picker">
<BluetoothNotice v-if="bluetooth" feature="Offline area map preview">Saved map settings remain available.</BluetoothNotice>
<div v-else-if="hasKey" class="gx-offline-roads__map"><canvas ref="canvas" tabindex="0" aria-label="Map. Tap or press Enter to center a new offline area; drag or use arrow keys to pan."></canvas>
<div class="gx-navigation-map__controls"><button class="gx-btn" type="button" @click="zoom(1)" aria-label="Zoom in">+</button>
<button class="gx-btn" type="button" @click="zoom(-1)" aria-label="Zoom out">−</button></div>
<div v-else-if="hasKey" class="gx-offline-roads__map"><canvas ref="canvas" tabindex="0" aria-label="Mapbox map. Tap or press Enter to center a new offline area; drag or use arrow keys to pan."></canvas>
<span class="gx-offline-roads__provider">Mapbox preview</span>
<div class="gx-navigation-map__controls"><button class="gx-navigation-map__control" type="button" @click="zoom(1)" aria-label="Zoom in"><i class="bi bi-plus-lg" aria-hidden="true"></i></button>
<button class="gx-navigation-map__control" type="button" @click="zoom(-1)" aria-label="Zoom out"><i class="bi bi-dash-lg" aria-hidden="true"></i></button></div>
<span class="gx-offline-roads__hint">{{ point ? 'Adjust the radius, name it, then save.' : 'Tap the map to center a new area.' }}</span></div>
<div class="gx-offline-roads__form">
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!data?.position" @click="useLocation"><i class="bi bi-crosshair"></i> Around my car</button>
@@ -149,9 +149,23 @@ export class OnroadLayoutFeed {
}
}
// Which map and route provider the comma uses, so the navigation previews match what it draws.
export const navLook = reactive({ map: "mapbox", routes: "mapbox" })
export async function loadNavLook(fetcher = (...args) => fetch(...args)) {
try {
const response = await fetcher("./api/navigation/status", { credentials: "same-origin", cache: "no-store" })
const data = response.ok ? await response.json() : null
navLook.map = data?.mapProvider === "google" && data.hasGoogleKey ? "google" : "mapbox"
navLook.routes = data?.routeProvider === "google" && data.hasGoogleKey ? "google" : "mapbox"
} catch { /* The Mapbox look stays when navigation is unreachable. */ }
}
export const LayoutWidgetPreview = {
props: ["widget", "palette", "profile", "scene", "clock24Hour", "native", "art"],
computed: {
nav() { return navLook },
googleMap() { return navLook.map === "google" },
googleRoutes() { return navLook.routes === "google" },
roadNameSize() { return Math.max(18, Math.min(this.widget.width, this.widget.height) * .075) },
},
methods: {
@@ -280,8 +294,9 @@ export const LayoutWidgetPreview = {
</g>
<g v-else-if="widget.kind === 'nav_card'">
<rect x="1" y="1" :width="widget.width - 2" :height="widget.height - 2" rx="39" fill="#0f0d17f5" stroke="#a07edcbe" stroke-width="2" />
<text x="24" y="66" font-size="54" font-weight="700" fill="white">500 ft</text>
<text x="24" y="100" font-size="30" font-weight="600" fill="#ded6f4">Turn right onto Las Vegas Blvd</text>
<text v-if="!googleRoutes" x="24" y="66" font-size="54" font-weight="700" fill="white">500 ft</text>
<text v-if="!googleRoutes" x="24" y="100" font-size="30" font-weight="600" fill="#ded6f4">Turn right onto Las Vegas Blvd</text>
<template v-if="!googleRoutes">
<g v-for="(lane, i) in [['S', 0], ['S', 0], ['S', 0], ['R', 1], ['R', 1]]" :key="i" :transform="'translate(' + ((widget.width - 320) / 2 + i * 66) + ' 116)'">
<rect width="56" height="44" rx="13" :fill="lane[1] ? '#4e3e80' : '#222030'" />
<g transform="translate(28 22)" fill="none" :stroke="lane[1] ? '#ffffff' : '#70688a'" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round">
@@ -289,6 +304,13 @@ export const LayoutWidgetPreview = {
<path v-else d="M-8 13 V0 Q-8 -7 -1 -7 H10 M4 -13 L10 -7 L4 -1" />
</g>
</g>
</template>
<template v-else>
<g transform="translate(24 28)" fill="none" stroke="white" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"><path d="M12 56 V28 Q12 18 22 18 H48 M34 4 L48 18 L34 32" /></g>
<text x="104" y="66" font-size="54" font-weight="700" fill="white">500 ft</text>
<text x="104" y="100" font-size="30" font-weight="600" fill="#ded6f4">Las Vegas Blvd</text>
<text :x="widget.width - 24" y="150" text-anchor="end" font-size="27" font-weight="500" fill="#d6d2e2">2.4 mi | 6 min</text>
</template>
<rect x="24" y="171" :width="widget.width - 48 - 190" height="6" rx="3" fill="#a07edc3c" />
<rect x="24" y="171" :width="(widget.width - 48 - 190) * .35" height="6" rx="3" fill="#b296ff" />
<text :x="widget.width - 24" y="182" text-anchor="end" font-size="22" font-weight="600" fill="#ebe1ff">ETA 3:51 PM</text>
@@ -300,6 +322,15 @@ export const LayoutWidgetPreview = {
</defs>
<g mask="url(#gx-nav-map-mask)" :transform="'scale(' + widget.width / 600 + ' ' + widget.height / 450 + ')'" fill="none" stroke-linecap="round" stroke-linejoin="round">
<g :opacity="(widget.opacity ?? 50) / 100">
<template v-if="googleMap">
<rect width="600" height="450" fill="#e8eaed" />
<path d="M440 -20 L640 -20 L640 200 Q540 170 440 -20 Z" fill="#aadaff" />
<path d="M-20 120 Q200 150 640 90 M90 -20 L130 480 M430 -20 Q400 200 470 480 M-20 330 L640 360 M260 -20 L250 480" stroke="#ffffff" stroke-width="12" vector-effect="non-scaling-stroke" />
<path d="M-20 120 Q200 150 640 90" stroke="#34a853" stroke-width="5" vector-effect="non-scaling-stroke" />
<path d="M-20 330 L640 360" stroke="#ea4335" stroke-width="5" vector-effect="non-scaling-stroke" />
<path d="M260 -20 L250 480" stroke="#fbbc04" stroke-width="5" vector-effect="non-scaling-stroke" />
</template>
<template v-else>
<rect width="600" height="450" fill="#0b0f16" opacity=".45" />
<g stroke="#000000a8" vector-effect="non-scaling-stroke">
<path d="M-20 120 Q200 150 640 90 M90 -20 L130 480 M430 -20 Q400 200 470 480 M-20 330 L640 360 M260 -20 L250 480" stroke-width="11" vector-effect="non-scaling-stroke" />
@@ -307,6 +338,7 @@ export const LayoutWidgetPreview = {
<path d="M-20 120 Q200 150 640 90 M-20 330 L640 360" stroke="#ebf0f5" stroke-width="6" vector-effect="non-scaling-stroke" />
<path d="M90 -20 L130 480 M430 -20 Q400 200 470 480" stroke="#bec8d2" stroke-width="4" vector-effect="non-scaling-stroke" />
<path d="M260 -20 L250 480" stroke="#ffc45c" stroke-width="8" vector-effect="non-scaling-stroke" />
</template>
</g>
<path d="M300 330 Q258 300 254 250 L262 -20" stroke="#8f6bff55" stroke-width="20" vector-effect="non-scaling-stroke" />
<path d="M300 330 Q258 300 254 250 L262 -20" stroke="#a98bff" stroke-width="9" vector-effect="non-scaling-stroke" />
@@ -318,6 +350,7 @@ export const LayoutWidgetPreview = {
<rect :x="-roadNameSize * 4.4" y="0" :width="roadNameSize * 8.8" :height="roadNameSize * 1.55" :rx="roadNameSize * .78" fill="#080c14be" />
<text x="0" :y="roadNameSize * 1.12" text-anchor="middle" :font-size="roadNameSize" fill="#eceef6">Desert Inn Road</text>
</g>
<text v-if="googleMap" x="16" :y="widget.height - 12" :font-size="Math.max(14, Math.min(widget.width, widget.height) * .04)" font-weight="600" fill="#f0f2fa">Google Maps</text>
</g>
<template v-else>
<rect :width="widget.width" :height="widget.height" :fill="palette.cardFill" :stroke="palette.cardBorder" />
@@ -566,7 +599,7 @@ export const OnroadLayoutPage = {
stockConfidence() { return this.displayValue("StockConfidenceBallWidget") === "Off" },
},
mounted() {
if (this.mode === "local") this.feed.start()
if (this.mode === "local") { this.feed.start(); loadNavLook() }
this._stopUnloadGuard = guardUnload(() => this.dirty || this.state.status === "saving")
// Double-tap zoom stays off across the whole page, app bar included, while a maker page is open.
if (makerPagesOpen++ === 0) document.documentElement.classList.add("gx-maker-open")
@@ -1,11 +1,30 @@
// Destination coordinates take precedence over Google's viewport (@lat,lng).
const GEOHASH = '0123456789bcdefghjkmnpqrstuvwxyz'
const WAZE_SHORT = /https:\/\/(?:www\.)?waze\.com\/ul\/h([0-9b-hjkmnp-z]{4,12})(?![0-9a-z])/i
function wazeGeohash(code) {
const latitude = [-90, 90], longitude = [-180, 180]
let even = true
for (const char of code.toLowerCase()) {
const bits = GEOHASH.indexOf(char)
for (let shift = 4; shift >= 0; shift--) {
const span = even ? longitude : latitude
span[bits >> shift & 1 ? 0 : 1] = (span[0] + span[1]) / 2
even = !even
}
}
return [(latitude[0] + latitude[1]) / 2, (longitude[0] + longitude[1]) / 2].map((value) => Math.round(value * 1e6) / 1e6)
}
export function parseSharedDestination(input) {
let text = String(input || '').slice(0, 8192).trim()
try { text = decodeURIComponent(text.replace(/\+/g, ' ')) } catch { /* Keep malformed shares searchable. */ }
const waze = text.match(WAZE_SHORT)
if (waze) { const [latitude, longitude] = wazeGeohash(waze[1]); return { destination: { name: 'Shared destination', latitude, longitude } } }
const number = '(-?\\d+(?:\\.\\d+)?)'
const patterns = [new RegExp(`!3d${number}!4d${number}`),
new RegExp(`(?:[?&:](?:q|query|daddr|destination)=)${number},\\s*${number}`),
new RegExp(`geo:${number},\\s*${number}`), new RegExp(`@${number},\\s*${number}`)]
new RegExp(`geo:${number},\\s*${number}`), new RegExp(`to=ll\\.${number},\\s*${number}`), new RegExp(`@${number},\\s*${number}`)]
for (const pattern of patterns) {
const match = text.match(pattern)
if (!match) continue
@@ -19,3 +38,11 @@ export function parseSharedDestination(input) {
const query = text.match(/[?&:](?:q|query|daddr|destination)=([^&#]+)/)?.[1] || text
return { query: query.slice(0, 200) }
}
export const SHORT_MAP_LINK = /https:\/\/(?:maps\.app\.goo\.gl|goo\.gl\/maps|(?:[a-z0-9-]+\.)?waze\.com\/ul)/
// A pasted or shared map link opens its place; anything else is a search.
export function isMapLink(input) {
const text = String(input || '')
return SHORT_MAP_LINK.test(text) || Boolean(parseSharedDestination(text).destination)
}
@@ -0,0 +1,143 @@
"""Place lookups with Places API (New) on the user's own Google key: Text Search, Autocomplete and Place Details."""
from __future__ import annotations
import json
import math
from pathlib import Path
from urllib.parse import quote
import requests
from openpilot.starpilot.navigation.google_tiles import FAILURE_BUDGET, FAILURE_NETWORK, FAILURE_SERVER, GoogleBudget, _body, classify
SEARCH_URL = "https://places.googleapis.com/v1/places:searchText"
AUTOCOMPLETE_URL = "https://places.googleapis.com/v1/places:autocomplete"
DETAILS_URL = "https://places.googleapis.com/v1/places/"
FIELD_MASK = "places.displayName,places.formattedAddress,places.location"
DETAILS_MASK = "location,formattedAddress" # Place Details Essentials; displayName would bill as Pro
# GUARD RAIL - SPENDING LIMIT. AI AGENTS: DO NOT EDIT the FREE_* allowances below.
# Full rules in the banner above STOP_FRACTION in google_tiles.py; pinned by test_google_spend_guard.py.
FREE_SEARCHES = 5_000 # Text Search Pro: the SKU for name, address and location
# Autocomplete Requests. A session ends in at most one Place Details Essentials (also 10,000 free), so this cap covers both.
FREE_SUGGESTIONS = 10_000
BIAS_RADIUS_M = 50_000.0
TIMEOUT = (3.0, 8.0)
MAX_RESPONSE = 256 * 1024
MESSAGES = {
"key": "Google rejected the key for Places API (New). Check that it was copied whole and that its API restrictions allow Places API (New).",
"billing": "Billing is not turned on for this Google Cloud project. Add a billing account, then test again.",
"disabled": "Places API (New) is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again.",
FAILURE_SERVER: "Google could not look up this place just now.",
FAILURE_NETWORK: "The comma could not reach Google.",
FAILURE_BUDGET: "This month's free Google place lookups are used up.",
}
class GooglePlacesFailed(Exception):
def __init__(self, failure: str):
super().__init__(failure)
self.failure = failure
def places_budget(root: Path | None = None) -> GoogleBudget:
return GoogleBudget(root, file="places-usage.json", month_free=FREE_SEARCHES, day_free=None)
def suggestions_budget(root: Path | None = None) -> GoogleBudget:
return GoogleBudget(root, file="places-autocomplete-usage.json", month_free=FREE_SUGGESTIONS, day_free=None)
def _bias(proximity: tuple[float, float] | None) -> dict:
if proximity is None:
return {}
return {"locationBias": {"circle": {"center": {"latitude": proximity[1], "longitude": proximity[0]}, "radius": BIAS_RADIUS_M}}}
def _request(send, budget: GoogleBudget | None) -> dict:
if budget is not None and not budget.spend():
raise GooglePlacesFailed(FAILURE_BUDGET)
try:
with send() as response:
status, raw = response.status_code, _body(response, MAX_RESPONSE)
except requests.RequestException:
raise GooglePlacesFailed(FAILURE_NETWORK) from None
except ValueError:
raise GooglePlacesFailed(FAILURE_SERVER) from None
failure = classify(status, raw)
if failure is not None:
raise GooglePlacesFailed(failure)
try:
value = json.loads(raw)
except ValueError:
raise GooglePlacesFailed(FAILURE_SERVER) from None
if not isinstance(value, dict):
raise GooglePlacesFailed(FAILURE_SERVER)
return value
def _location(row: dict) -> tuple[float, float]:
latitude, longitude = float(row["location"]["latitude"]), float(row["location"]["longitude"])
if not math.isfinite(latitude) or not math.isfinite(longitude):
raise ValueError
return latitude, longitude
def text_search(http, key: str, query: str, budget: GoogleBudget, proximity: tuple[float, float] | None = None, timeout=TIMEOUT,
limit: int = 1) -> list[dict]:
"""Google's places for the text as [{name, address, latitude, longitude}], best first."""
body = {"textQuery": query, "pageSize": limit, **_bias(proximity)}
value = _request(lambda: http.post(SEARCH_URL, json=body, headers={"X-Goog-Api-Key": key, "X-Goog-FieldMask": FIELD_MASK},
timeout=timeout, stream=True), budget)
try:
places = []
for row in value.get("places", [])[:limit]:
latitude, longitude = _location(row)
places.append({"name": str(row.get("displayName", {}).get("text") or row.get("formattedAddress") or query),
"address": row.get("formattedAddress"), "latitude": latitude, "longitude": longitude})
return places
except (ValueError, TypeError, KeyError, AttributeError):
raise GooglePlacesFailed(FAILURE_SERVER) from None
def autocomplete(http, key: str, query: str, session: str, budget: GoogleBudget, proximity: tuple[float, float] | None = None,
timeout=TIMEOUT) -> list[dict]:
"""Typing suggestions as [{id, name, description}]; the session token bills them with the Place Details that ends it."""
body = {"input": query, "sessionToken": session, **_bias(proximity)}
value = _request(lambda: http.post(AUTOCOMPLETE_URL, json=body, headers={"X-Goog-Api-Key": key}, timeout=timeout, stream=True), budget)
suggestions = value.get("suggestions")
rows = []
for item in suggestions if isinstance(suggestions, list) else []:
try:
prediction = item["placePrediction"]
identity = prediction["placeId"]
structured = prediction.get("structuredFormat") or {}
name = (structured.get("mainText") or {}).get("text") or prediction["text"]["text"]
description = (structured.get("secondaryText") or {}).get("text") or ""
except (TypeError, KeyError, AttributeError):
continue
if (isinstance(identity, str) and 1 <= len(identity) <= 256 and isinstance(name, str) and 1 <= len(name.strip()) <= 256 and
isinstance(description, str)):
rows.append({"id": identity, "name": name.strip(), "description": description.strip()[:512]})
return rows[:8]
def place_details(http, key: str, identity: str, session: str, timeout=TIMEOUT) -> dict:
"""Coordinates and address of a suggested place; ends its autocomplete session."""
value = _request(lambda: http.get(DETAILS_URL + quote(identity, safe=""), params={"sessionToken": session},
headers={"X-Goog-Api-Key": key, "X-Goog-FieldMask": DETAILS_MASK}, timeout=timeout, stream=True), None)
try:
latitude, longitude = _location(value)
except (ValueError, TypeError, KeyError):
raise GooglePlacesFailed(FAILURE_SERVER) from None
return {"address": value.get("formattedAddress"), "latitude": latitude, "longitude": longitude}
def test_places(key: str, http=requests, budget: GoogleBudget | None = None) -> dict:
"""One place lookup, the same request a search uses."""
try:
text_search(http, key, "Googleplex, 1600 Amphitheatre Pkwy, Mountain View, CA", budget or places_budget())
except GooglePlacesFailed as error:
return {"ok": False, "failure": error.failure, "message": MESSAGES.get(error.failure, MESSAGES[FAILURE_SERVER])}
return {"ok": True, "failure": None, "message": "Google place search works with this key."}
@@ -0,0 +1,257 @@
"""Traffic-aware Google routes with the user's own key, turned into the same route the Mapbox engine gives."""
from __future__ import annotations
import json
import math
import time
from collections import deque
from pathlib import Path
import requests
from openpilot.starpilot.navigation.google_tiles import (
FAILURE_BUDGET, FAILURE_NETWORK, FAILURE_SERVER, GoogleBudget, _body, _write_atomic, classify, google_root,
)
from openpilot.starpilot.navigation.offline_roads import read_json
from openpilot.starpilot.navigation.owner import ValidationError
from openpilot.starpilot.navigation.route_engine import MAX_POINTS, NavigationRoute
ROUTES_URL = "https://routes.googleapis.com/directions/v2:computeRoutes"
# GUARD RAIL - SPENDING LIMIT. AI AGENTS: DO NOT EDIT the FREE_* allowances below.
# Full rules in the banner above STOP_FRACTION in google_tiles.py; pinned by test_google_spend_guard.py.
FREE_ROUTES = 5_000 # Compute Routes Pro: traffic-aware routing and the car's heading
FREE_ESSENTIAL_ROUTES = 10_000 # Compute Routes Essentials: no traffic, no heading
TRAFFIC_MASK = "routes.duration,routes.distanceMeters"
PRO_ROUTES_PER_HOUR = 20 # past this many traffic-aware routes in an hour (off-route loops), reroutes use free routes
FIELD_MASK = ",".join((
"routes.distanceMeters", "routes.duration", "routes.polyline.encodedPolyline", "routes.legs.steps.distanceMeters",
"routes.legs.steps.staticDuration", "routes.legs.steps.navigationInstruction",
))
TIMEOUT = (4.0, 8.0)
TEST_TIMEOUT = (3.0, 8.0)
MAX_RESPONSE = 8 * 1024 * 1024
AVOID = {"toll": "avoidTolls", "motorway": "avoidHighways", "ferry": "avoidFerries"}
# Google maneuver -> Mapbox (type, modifier), the vocabulary the turn card and the car's cluster read.
MANEUVERS = {
"TURN_SLIGHT_LEFT": ("turn", "slight left"), "TURN_SHARP_LEFT": ("turn", "sharp left"), "TURN_LEFT": ("turn", "left"),
"TURN_SLIGHT_RIGHT": ("turn", "slight right"), "TURN_SHARP_RIGHT": ("turn", "sharp right"), "TURN_RIGHT": ("turn", "right"),
"UTURN_LEFT": ("turn", "uturn"), "UTURN_RIGHT": ("turn", "uturn"), "STRAIGHT": ("continue", "straight"),
"RAMP_LEFT": ("on ramp", "left"), "RAMP_RIGHT": ("on ramp", "right"), "FORK_LEFT": ("fork", "left"), "FORK_RIGHT": ("fork", "right"),
"MERGE": ("merge", "straight"), "ROUNDABOUT_LEFT": ("roundabout", "left"), "ROUNDABOUT_RIGHT": ("roundabout", "right"),
"DEPART": ("depart", "straight"), "NAME_CHANGE": ("new name", "straight"), "FERRY": ("notification", "straight"),
"FERRY_TRAIN": ("notification", "straight"),
}
MESSAGES = {
"key": "Google rejected the key for the Routes API. Check that it was copied whole and that its API restrictions allow the Routes API.",
"billing": "Billing is not turned on for this Google Cloud project. Add a billing account, then test again.",
"disabled": "The Routes API is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again.",
FAILURE_SERVER: "Google could not find a route just now, so Mapbox routed this trip.",
FAILURE_NETWORK: "The comma could not reach Google, so Mapbox routed this trip.",
FAILURE_BUDGET: "This month's free Google routes are used up. Mapbox routes until they reset.",
}
class GoogleRoutesFailed(Exception):
"""Google could not route; the caller routes with Mapbox instead."""
def __init__(self, failure: str):
super().__init__(failure)
self.failure = failure
def route_budget(root: Path | None = None) -> GoogleBudget:
return GoogleBudget(root, file="routes-usage.json", month_free=FREE_ROUTES, day_free=None)
def essentials_budget(root: Path | None = None) -> GoogleBudget:
return GoogleBudget(root, file="routes-essentials-usage.json", month_free=FREE_ESSENTIAL_ROUTES, day_free=None)
def write_route_status(root: Path, failure: str | None) -> None:
try:
root.mkdir(parents=True, exist_ok=True)
_write_atomic(root / "routes-status.json", {"failure": failure})
except OSError:
pass
def read_route_failure(root: Path) -> str | None:
value = read_json(root / "routes-status.json", 4096)
failure = value.get("failure") if isinstance(value, dict) else None
return MESSAGES.get(failure) if isinstance(failure, str) else None
def decode_polyline(text: str, limit: int = 400_000) -> list[list[float]]:
"""Google's encoded polyline (precision 5) as [longitude, latitude] pairs."""
points, index, latitude, longitude = [], 0, 0, 0
while index < len(text):
deltas = []
for _ in range(2):
shift = result = 0
while True:
if index >= len(text) or shift > 30:
raise ValidationError("The route line could not be read")
byte = ord(text[index]) - 63
index += 1
result |= (byte & 0x1f) << shift
shift += 5
if byte < 0x20:
break
deltas.append(~(result >> 1) if result & 1 else result >> 1)
latitude += deltas[0]
longitude += deltas[1]
points.append([longitude / 1e5, latitude / 1e5])
if len(points) > limit:
raise ValidationError("The route is too long")
return points
def thin(points: list[list[float]], limit: int = MAX_POINTS) -> list[list[float]]:
if len(points) <= limit:
return points
stride = math.ceil((len(points) - 1) / (limit - 1))
kept = points[::stride]
if kept[-1] != points[-1]:
kept.append(points[-1])
return kept
def seconds(value) -> float:
if not isinstance(value, str) or not value.endswith("s"):
raise ValidationError("The route contains invalid durations")
try:
parsed = float(value[:-1])
except ValueError:
raise ValidationError("The route contains invalid durations") from None
if not math.isfinite(parsed) or parsed < 0:
raise ValidationError("The route contains invalid durations")
return parsed
def mapbox_shape(route: dict) -> dict:
"""One Google route in the shape NavigationRoute reads; step times are scaled to the traffic-aware total."""
coordinates = thin(decode_polyline(route["polyline"]["encodedPolyline"]))
total = seconds(route["duration"])
google_steps = route["legs"][0]["steps"]
static = [seconds(step.get("staticDuration", "0s")) for step in google_steps]
scale = total / sum(static) if sum(static) > 0 else 0.0
steps = []
for step, duration in zip(google_steps, static, strict=True):
instruction = step.get("navigationInstruction") or {}
kind, side = MANEUVERS.get(instruction.get("maneuver"), ("continue", "straight"))
text = str(instruction.get("instructions", ""))[:256]
if kind == "on ramp" and "exit" in text.lower():
kind = "off ramp"
steps.append({"distance": step.get("distanceMeters", 0), "duration": duration * scale,
"maneuver": {"type": kind, "modifier": side, "instruction": text}})
steps.append({"distance": 0, "duration": 0, "maneuver": {"type": "arrive", "modifier": "straight", "instruction": "Arrive at your destination"}})
return {"geometry": {"coordinates": coordinates}, "legs": [{"steps": steps}], "distance": route["distanceMeters"], "duration": total}
def request_body(position, destination: dict, bearing: float | None, exclusions: tuple[str, ...], alternatives: bool = True,
traffic: bool = False) -> dict:
location: dict = {"latLng": {"latitude": position[1], "longitude": position[0]}}
if bearing is not None and math.isfinite(bearing):
location["heading"] = int(bearing % 360)
origin = {"location": location}
return {"origin": origin, "destination": {"location": {"latLng": {"latitude": destination["latitude"], "longitude": destination["longitude"]}}},
"travelMode": "DRIVE", "routingPreference": "TRAFFIC_AWARE" if traffic else "TRAFFIC_UNAWARE",
"computeAlternativeRoutes": alternatives, "languageCode": "en-US",
"polylineQuality": "HIGH_QUALITY",
"routeModifiers": {AVOID[name]: True for name in exclusions if name in AVOID}}
def _post(http, key: str, body: dict, mask: str, timeout) -> list:
try:
with http.post(ROUTES_URL, json=body, headers={"X-Goog-Api-Key": key, "X-Goog-FieldMask": mask},
timeout=timeout, stream=True) as response:
status, raw = response.status_code, _body(response, MAX_RESPONSE)
except requests.RequestException:
raise GoogleRoutesFailed(FAILURE_NETWORK) from None
except ValueError:
raise GoogleRoutesFailed(FAILURE_SERVER) from None
failure = classify(status, raw)
if failure is not None:
raise GoogleRoutesFailed(failure)
try:
rows = json.loads(raw).get("routes", [])
except (ValueError, AttributeError):
raise GoogleRoutesFailed(FAILURE_SERVER) from None
if not isinstance(rows, list) or not rows:
raise GoogleRoutesFailed(FAILURE_SERVER)
return rows
def compute_routes(http, key: str, body: dict, timeout=TIMEOUT) -> list[NavigationRoute]:
"""Up to three routes, or GoogleRoutesFailed saying why not."""
rows = _post(http, key, body, FIELD_MASK, timeout)
try:
routes = [NavigationRoute(mapbox_shape(row)) for row in rows[:3]]
except (ValidationError, ValueError, KeyError, TypeError, IndexError, AttributeError):
raise GoogleRoutesFailed(FAILURE_SERVER) from None
if not routes:
raise GoogleRoutesFailed(FAILURE_SERVER)
return routes
class GoogleRouteEngine:
"""Traffic-aware Pro routes, falling back to Essentials once the Pro or hourly reroute limit is used up."""
def __init__(self, session, budget: GoogleBudget, essentials: GoogleBudget, clock=time.monotonic):
self.session = session
self.budget = budget
self.essentials = essentials
self.clock = clock
self._pro_routes: deque[float] = deque()
def fetch(self, key: str, position, destination: dict, bearing: float | None = None,
exclusions: tuple[str, ...] = ()) -> NavigationRoute:
now = self.clock()
while self._pro_routes and now - self._pro_routes[0] > 3600:
self._pro_routes.popleft()
pro = len(self._pro_routes) < PRO_ROUTES_PER_HOUR and self.budget.spend()
if pro:
self._pro_routes.append(now)
elif not self.essentials.spend():
raise GoogleRoutesFailed(FAILURE_BUDGET)
body = request_body(position, destination, bearing if pro else None, exclusions, traffic=pro)
routes = compute_routes(self.session, key, body)
for route in routes:
route.traffic_aware = pro
routes[0].alternatives = routes
return routes[0]
def traffic(self, key: str, position, destination: dict, bearing: float | None = None,
exclusions: tuple[str, ...] = ()) -> tuple[float, float]:
"""Google's traffic-aware (seconds, meters) from here to the destination, one Pro request."""
if not self.budget.spend():
raise GoogleRoutesFailed(FAILURE_BUDGET)
body = request_body(position, destination, bearing, exclusions, alternatives=False, traffic=True)
row = _post(self.session, key, body, TRAFFIC_MASK, TIMEOUT)[0]
try:
duration, meters = seconds(row["duration"]), float(row["distanceMeters"])
except (ValidationError, KeyError, TypeError, ValueError):
raise GoogleRoutesFailed(FAILURE_SERVER) from None
if not math.isfinite(meters) or meters < 0:
raise GoogleRoutesFailed(FAILURE_SERVER)
return duration, meters
def test_routes(key: str, http=requests, budget: GoogleBudget | None = None) -> dict:
"""One short free (Essentials) route, the same request a trip starts with."""
budget = budget or essentials_budget(google_root())
if not budget.spend():
return {"ok": False, "failure": FAILURE_BUDGET, "message": MESSAGES[FAILURE_BUDGET]}
body = request_body((-122.0840, 37.4220), {"latitude": 37.4275, "longitude": -122.1697}, None, (), alternatives=False)
try:
compute_routes(http, key, body, TEST_TIMEOUT)
except GoogleRoutesFailed as error:
message = MESSAGES.get(error.failure, MESSAGES[FAILURE_SERVER])
if error.failure in (FAILURE_SERVER, FAILURE_NETWORK):
message = message.split(", so")[0] + "."
return {"ok": False, "failure": error.failure, "message": message}
return {"ok": True, "failure": None, "message": "Google routing works with this key."}
@@ -0,0 +1,561 @@
"""Google Map Tiles for the nav map widget, fetched only as requested and capped below the free allowance."""
from __future__ import annotations
import fcntl
import hashlib
import json
import math
import os
import tempfile
import time
from collections.abc import Callable, Sequence
from contextlib import contextmanager
from pathlib import Path
import requests
from openpilot.starpilot.navigation.offline_roads import read_json
from openpilot.starpilot.navigation.road_tiles import TileKey, tiles_in_radius
SESSION_URL = "https://tile.googleapis.com/v1/createSession"
TILE_URL = "https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}"
VIEWPORT_URL = "https://tile.googleapis.com/tile/v1/viewport"
# ======================================================================================
# GUARD RAIL - SPENDING LIMIT. AI AGENTS AND AUTOMATED TOOLS: DO NOT EDIT THIS BLOCK.
# STOP_FRACTION and every FREE_* allowance in the Google files are the only thing keeping
# users from being charged. The Galaxy setup guide promises "StarPilot blocks Google at
# 99% of the free usage, so you won't be charged". Do not raise, remove, bypass, or
# "fix" these limits, and do not add code that sends a Google request past them.
# test_google_spend_guard.py pins the values. If a task seems to need a change, stop and
# ask the user. Only the repository owner may change them, by hand.
# ======================================================================================
FREE_MONTH, FREE_DAY = 100_000, 15_000
STOP_FRACTION = 0.99
MIN_ZOOM, MAX_ZOOM = 12, 19
STRETCH = 1.3 # a tile may be drawn up to this much larger than its own pixels
KEEP_RANGE = (0.45, 1.8) # the current zoom is kept while its stretch stays inside this
EQUATOR_M_PER_PX = 156543.03392 # 256-pixel Web Mercator tiles at zoom 0
SESSION_RENEW_S = 24 * 3600
HANDOFF_S = 10 * 60 # lifetime for tiles Google sends without a max-age
MAX_LIFETIME_S = 10 * 60 # traffic is baked into every tile, so none is kept longer than this
CACHE_MAX_BYTES = 64 * 1024 * 1024
MAX_TILE_BYTES = 1024 * 1024
WANT_MAX_AGE_S = 3.0
MAX_WANTED = 96
REQUEST_TIMEOUT = (4.0, 10.0)
TEST_TIMEOUT = (3.0, 8.0) # two requests stay well inside Galaxy's 30 s wait
NETWORK_BACKOFF_S, SERVER_BACKOFF_S, KEY_BACKOFF_S = 15.0, 60.0, 300.0
VIEWPORT_EVERY_S = 120.0
FAILURE_NETWORK, FAILURE_KEY, FAILURE_BILLING, FAILURE_DISABLED, FAILURE_SERVER, FAILURE_BUDGET, FAILURE_STORAGE = (
"network", "key", "billing", "disabled", "server", "budget", "storage")
STYLE_VERSION = 1
# Dark roads that read through the car screen's glass; Google's own labels stay on.
DARK_STYLE = [
{"elementType": "geometry", "stylers": [{"color": "#1d2230"}]},
{"elementType": "labels.text.fill", "stylers": [{"color": "#c8cedc"}]},
{"elementType": "labels.text.stroke", "stylers": [{"color": "#12151e"}]},
{"featureType": "poi", "stylers": [{"visibility": "off"}]},
{"featureType": "transit", "stylers": [{"visibility": "off"}]},
{"featureType": "road", "elementType": "geometry", "stylers": [{"color": "#3a4256"}]},
{"featureType": "road.arterial", "elementType": "geometry", "stylers": [{"color": "#4a5470"}]},
{"featureType": "road.highway", "elementType": "geometry", "stylers": [{"color": "#7a6a46"}]},
{"featureType": "water", "elementType": "geometry", "stylers": [{"color": "#0e1a2b"}]},
]
def google_root() -> Path:
from openpilot.starpilot.storage import starpilot_storage_root
return starpilot_storage_root() / "navigation" / "google-tiles"
def want_path() -> Path:
return Path("/dev/shm" if os.path.isdir("/dev/shm") else tempfile.gettempdir()) / "starpilot-google-tiles-want.json"
def _wall() -> float:
return time.time() # noqa: TID251 - expiry and calendar days are wall-clock
def session_body(language: str = "en-US", region: str = "US", theme: str = "dark") -> dict:
body = {"mapType": "roadmap", "language": language, "region": region, "imageFormat": "png", "layerTypes": ["layerTraffic"]}
if theme != "light":
body["styles"] = DARK_STYLE
return body
def key_digest(api_key: str, theme: str = "dark") -> str:
suffix = "\nlight" if theme == "light" else ""
return hashlib.sha256(f"{api_key}\n{STYLE_VERSION}{suffix}".encode()).hexdigest()[:24]
def native_m_per_px(latitude: float, zoom: int) -> float:
return EQUATOR_M_PER_PX * math.cos(math.radians(latitude)) / (1 << zoom)
def choose_zoom(latitude: float, m_per_px: float, current: int | None = None) -> int:
"""The lowest zoom whose tiles are stretched at most ``STRETCH``; the current one is kept while it still fits."""
if current is not None and MIN_ZOOM <= current <= MAX_ZOOM:
stretch = native_m_per_px(latitude, current) / m_per_px
if KEEP_RANGE[0] <= stretch <= KEEP_RANGE[1]:
return current
ideal = math.log2(EQUATOR_M_PER_PX * math.cos(math.radians(latitude)) / (m_per_px * STRETCH))
return max(MIN_ZOOM, min(MAX_ZOOM, math.ceil(ideal)))
def plan_tiles(latitude: float, longitude: float, radius_m: float, zoom: int) -> list[TileKey]:
"""Tiles touching the circle, nearest first."""
return tiles_in_radius(latitude, longitude, radius_m, zoom)[:MAX_WANTED]
def write_want(path: Path, keys: Sequence[TileKey], latitude: float, longitude: float, now: float | None = None) -> None:
_write_atomic(path, {"at": _wall() if now is None else now, "latitude": latitude, "longitude": longitude,
"tiles": [[key.z, key.x, key.y] for key in keys[:MAX_WANTED]]})
def read_want(path: Path, now: float | None = None) -> tuple[list[TileKey], tuple[float, float] | None]:
"""Wanted tiles and the car's position, or nothing when the widget stopped asking."""
now = _wall() if now is None else now
try:
with path.open("rb") as handle:
raw = handle.read(16 * 1024 + 1)
value = json.loads(raw)
if len(raw) > 16 * 1024 or not 0 <= now - float(value["at"]) <= WANT_MAX_AGE_S:
return [], None
keys = []
for z, x, y in value["tiles"][:MAX_WANTED]:
if (type(z) is int and type(x) is int and type(y) is int and MIN_ZOOM <= z <= MAX_ZOOM and
0 <= x < 1 << z and 0 <= y < 1 << z):
keys.append(TileKey(z, x, y))
latitude, longitude = float(value["latitude"]), float(value["longitude"])
if not (-85 < latitude < 85 and -180 <= longitude <= 180):
return keys, None
return keys, (latitude, longitude)
except (OSError, ValueError, TypeError, KeyError):
return [], None
def cache_lifetime(headers) -> float:
"""Seconds a tile may be kept: its Cache-Control header, capped so traffic stays current."""
control = str(headers.get("Cache-Control", "") or "").lower()
if "no-store" in control or "no-cache" in control:
return HANDOFF_S
for part in control.split(","):
name, _, value = part.strip().partition("=")
if name == "max-age":
try:
return min(MAX_LIFETIME_S, max(0.0, float(value.strip('"'))))
except ValueError:
return HANDOFF_S
return HANDOFF_S
class GoogleTileStore:
"""One PNG per tile under a folder per key and style; a file's mtime is when it expires."""
def __init__(self, root: Path | None = None):
self.root = Path(root) if root is not None else google_root()
def path(self, digest: str, key: TileKey) -> Path:
return self.root / "tiles" / digest / str(key.z) / str(key.x) / f"{key.y}.png"
def fresh(self, digest: str, key: TileKey, now: float | None = None) -> bool:
try:
info = self.path(digest, key).stat()
except OSError:
return False
return info.st_size > 0 and info.st_mtime > (_wall() if now is None else now)
def read(self, digest: str, key: TileKey, now: float | None = None) -> bytes | None:
if not self.fresh(digest, key, now):
return None
try:
with self.path(digest, key).open("rb") as handle:
data = handle.read(MAX_TILE_BYTES + 1)
except OSError:
return None
return data if 0 < len(data) <= MAX_TILE_BYTES else None
def write(self, digest: str, key: TileKey, data: bytes, lifetime: float, now: float | None = None) -> bool:
path = self.path(digest, key)
try:
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(dir=path.parent, prefix=".tile-")
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
expires = (_wall() if now is None else now) + lifetime
os.utime(temp, (expires, expires))
os.replace(temp, path)
except BaseException:
Path(temp).unlink(missing_ok=True)
raise
except OSError:
return False
return True
def trim(self, max_bytes: int = CACHE_MAX_BYTES, now: float | None = None) -> int:
"""Delete expired tiles, then the soonest to expire until under the cap; returns the size kept."""
now = _wall() if now is None else now
entries, total = [], 0
for directory, _, names in os.walk(self.root / "tiles"):
for name in names:
full = os.path.join(directory, name)
try:
info = os.stat(full)
except OSError:
continue
if info.st_mtime <= now:
Path(full).unlink(missing_ok=True)
continue
entries.append((info.st_mtime, info.st_size, full))
total += info.st_size
for _, size, full in sorted(entries):
if total <= max_bytes:
break
Path(full).unlink(missing_ok=True)
total -= size
return total
def pacific_day(wall: float) -> str:
"""Google's quota day, which starts at midnight US Pacific time; a fixed offset when tzdata is missing."""
from datetime import datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
try:
return datetime.fromtimestamp(wall, ZoneInfo("America/Los_Angeles")).strftime("%Y-%m-%d")
except ZoneInfoNotFoundError:
return time.strftime("%Y-%m-%d", time.gmtime(wall - 8 * 3600))
class GoogleBudget:
"""Tiles counted on the comma, shared by navtilesd and Galaxy's Test key under a file lock."""
def __init__(self, root: Path | None = None, clock: Callable[[], float] = _wall, file: str = "usage.json",
month_free: int = FREE_MONTH, day_free: int | None = FREE_DAY):
self.root = Path(root) if root is not None else google_root()
self.path = self.root / file
self.clock = clock
self.month_free, self.day_free = month_free, day_free
self.month_limit = int(month_free * STOP_FRACTION)
self.day_limit = int(day_free * STOP_FRACTION) if day_free is not None else None
@contextmanager
def _locked(self):
self.root.mkdir(parents=True, exist_ok=True)
with open(self.root / ".usage.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(lock, fcntl.LOCK_UN)
def _load(self) -> dict:
day = pacific_day(self.clock())
value = {"day": day, "month": day[:7], "dayUsed": 0, "monthUsed": 0}
saved = read_json(self.path, 4096)
if not isinstance(saved, dict):
return value
# Counts only reset when the calendar moves forward, so a clock that is briefly behind cannot zero them.
if isinstance(saved.get("month"), str) and saved["month"] >= value["month"] and type(saved.get("monthUsed")) is int:
value["month"], value["monthUsed"] = saved["month"], max(0, saved["monthUsed"])
if isinstance(saved.get("day"), str) and saved["day"] >= day and type(saved.get("dayUsed")) is int:
value["day"], value["dayUsed"] = saved["day"], max(0, saved["dayUsed"])
return value
def snapshot(self) -> dict:
value = self._load()
return {"monthUsed": value["monthUsed"], "monthLimit": self.month_limit, "monthFree": self.month_free,
"dayUsed": value["dayUsed"], "dayLimit": self.day_limit, "dayFree": self.day_free}
def spend(self, count: int = 1) -> bool:
"""Count tiles about to be requested; False, counting nothing, when either allowance is used up."""
with self._locked():
value = self._load()
if value["monthUsed"] + count > self.month_limit or (self.day_limit is not None and value["dayUsed"] + count > self.day_limit):
return False
value["monthUsed"] += count
value["dayUsed"] += count
_write_atomic(self.path, value)
return True
def classify(status: int, body: bytes) -> str | None:
"""Why Google refused, from its status and error text; None for a success."""
if status == 200:
return None
text = body[:4096].decode("utf-8", "replace").lower()
if "billing" in text:
return FAILURE_BILLING
if "has not been used" in text or "is disabled" in text or "service_disabled" in text or "api_key_service_blocked" in text:
return FAILURE_DISABLED
if status in (401, 403) or (status == 400 and ("api key" in text or "api_key" in text)):
return FAILURE_KEY
return FAILURE_SERVER
MESSAGES = {
FAILURE_KEY: "Google rejected the key for the Map Tiles API. Check that it was copied whole and that its API restrictions allow the Map Tiles API.",
FAILURE_BILLING: "Billing is not turned on for this Google Cloud project. Add a billing account, then test again.",
FAILURE_DISABLED: "The Map Tiles API is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again.",
FAILURE_SERVER: "Google is busy or refused the request. Try again in a minute.",
FAILURE_NETWORK: "The comma could not reach Google. Check its internet connection.",
FAILURE_BUDGET: "This month's or today's free Google tiles are used up. The map uses Mapbox road lines until they reset.",
FAILURE_STORAGE: "The comma could not save Google map tiles. Check its free storage.",
}
def _post_session(http, api_key: str, timeout=REQUEST_TIMEOUT, theme: str = "dark") -> tuple[int, bytes]:
with http.post(SESSION_URL, json=session_body(theme=theme), headers={"X-Goog-Api-Key": api_key}, timeout=timeout, stream=True) as response:
return response.status_code, _body(response, 64 * 1024)
def _body(response, limit: int) -> bytes:
chunks, size = [], 0
for chunk in response.iter_content(64 * 1024):
size += len(chunk)
if size > limit:
raise ValueError("response too large")
chunks.append(chunk)
return b"".join(chunks)
def parse_session(body: bytes, now: float) -> dict:
value = json.loads(body)
session, expiry = value["session"], float(value["expiry"])
if not isinstance(session, str) or not 0 < len(session) <= 1024 or not math.isfinite(expiry) or expiry <= now:
raise ValueError("bad session")
return {"session": session, "expiry": expiry}
def test_key(api_key: str, http=requests, budget: GoogleBudget | None = None) -> dict:
"""Creates a session exactly as the map does and fetches one tile; a plain answer either way."""
budget = budget or GoogleBudget()
try:
status, body = _post_session(http, api_key, TEST_TIMEOUT)
failure = classify(status, body)
if failure is not None:
return {"ok": False, "failure": failure, "message": MESSAGES[failure]}
session = parse_session(body, _wall())
if not budget.spend():
return {"ok": False, "failure": FAILURE_BUDGET, "message": MESSAGES[FAILURE_BUDGET]}
with http.get(TILE_URL.format(z=0, x=0, y=0), params={"session": session["session"]}, headers={"X-Goog-Api-Key": api_key},
timeout=TEST_TIMEOUT, stream=True) as response:
status, body = response.status_code, _body(response, MAX_TILE_BYTES)
except requests.RequestException:
return {"ok": False, "failure": FAILURE_NETWORK, "message": MESSAGES[FAILURE_NETWORK]}
except (ValueError, KeyError, TypeError):
return {"ok": False, "failure": FAILURE_SERVER, "message": MESSAGES[FAILURE_SERVER]}
failure = classify(status, body)
if failure is not None:
return {"ok": False, "failure": failure, "message": MESSAGES[failure]}
return {"ok": True, "failure": None, "message": "The key works. The map can use Google."}
def viewport_copyright(http, api_key: str, session: str, position: tuple[float, float], zoom: int, span: float = 0.02) -> str:
"""Google's data attribution around the car (viewport requests are not billed); empty when it cannot be read."""
latitude, longitude = position
params = {"session": session, "zoom": zoom, "north": min(84.9, latitude + span), "south": max(-84.9, latitude - span),
"east": min(179.9, longitude + span), "west": max(-179.9, longitude - span)}
try:
with http.get(VIEWPORT_URL, params=params, headers={"X-Goog-Api-Key": api_key}, timeout=REQUEST_TIMEOUT, stream=True) as response:
value = json.loads(_body(response, 256 * 1024)) if response.status_code == 200 else {}
except (requests.RequestException, ValueError):
return ""
text = value.get("copyright") if isinstance(value, dict) else None
return " ".join(text.split())[:160] if isinstance(text, str) else ""
def fetch_tile(api_key: str, z: int, x: int, y: int, theme: str = "dark", *, http=requests, root: Path | None = None,
wall: Callable[[], float] = _wall) -> bytes:
"""One 2D Google map tile for Galaxy's preview map, sharing the disk store and free-allowance budget."""
root = Path(root) if root is not None else google_root()
store = GoogleTileStore(root)
budget = GoogleBudget(root, wall)
digest = key_digest(api_key, theme)
key = TileKey(z, x, y)
now = wall()
cached = store.read(digest, key, now)
if cached is not None:
return cached
session_file = root / ("session.json" if theme != "light" else "session-light.json")
saved = read_json(session_file, 4096)
session = None
if isinstance(saved, dict) and saved.get("digest") == digest:
try:
if float(saved["expiry"]) - now > SESSION_RENEW_S and isinstance(saved["session"], str):
session = saved["session"]
except (KeyError, TypeError, ValueError):
pass
if session is None:
status, body = _post_session(http, api_key, REQUEST_TIMEOUT, theme=theme)
failure = classify(status, body)
if failure is not None:
raise ValueError(MESSAGES[failure])
parsed = dict(parse_session(body, now), digest=digest)
root.mkdir(parents=True, exist_ok=True)
_write_atomic(session_file, parsed, 0o600)
session = parsed["session"]
if not budget.spend():
raise ValueError(MESSAGES[FAILURE_BUDGET])
with http.get(TILE_URL.format(z=z, x=x, y=y), params={"session": session}, headers={"X-Goog-Api-Key": api_key},
timeout=REQUEST_TIMEOUT, stream=True) as response:
status, body, lifetime = response.status_code, _body(response, MAX_TILE_BYTES), cache_lifetime(response.headers)
failure = classify(status, body)
if failure is not None:
if failure in (FAILURE_KEY, FAILURE_BILLING, FAILURE_DISABLED):
session_file.unlink(missing_ok=True)
raise ValueError(MESSAGES[failure])
if not body or not body.startswith(b"\x89PNG\r\n\x1a\n"):
raise ValueError(MESSAGES[FAILURE_SERVER])
store.write(digest, key, body, lifetime, now)
return body
class GoogleTiles:
"""Fetches the widget's wanted tiles, one per step, within the free allowances."""
def __init__(self, root: Path | None = None, http=None, budget: GoogleBudget | None = None,
clock: Callable[[], float] = time.monotonic, wall: Callable[[], float] = _wall, want: Path | None = None):
self.root = Path(root) if root is not None else google_root()
self.http = http or requests.Session()
self.store = GoogleTileStore(self.root)
self.budget = budget or GoogleBudget(self.root, wall)
self.clock, self.wall = clock, wall
self.want = want or want_path()
self.blocked_until = 0.0
self.failure: str | None = None
self.copyright = ""
self._session: dict | None = None
self._digest: str | None = None
self._viewport_at = -math.inf
self._last_status = -math.inf
self._last_trim = -math.inf
@property
def blocked(self) -> bool:
return self.clock() < self.blocked_until
def _block(self, failure: str, seconds: float) -> None:
self.failure = failure
self.blocked_until = self.clock() + seconds
def _session_for(self, api_key: str) -> str | None:
digest = key_digest(api_key)
now = self.wall()
if self._session is None or self._session.get("digest") != digest:
saved = read_json(self.root / "session.json", 4096)
self._session = saved if isinstance(saved, dict) and saved.get("digest") == digest else None
if self._session is not None:
try:
if float(self._session["expiry"]) - now > SESSION_RENEW_S and isinstance(self._session["session"], str):
return self._session["session"]
except (KeyError, TypeError, ValueError):
pass
status, body = _post_session(self.http, api_key)
failure = classify(status, body)
if failure is not None:
self._refused(failure)
return None
session = dict(parse_session(body, now), digest=digest)
self.root.mkdir(parents=True, exist_ok=True)
_write_atomic(self.root / "session.json", session, 0o600)
self._session = session
return session["session"]
def _refused(self, failure: str) -> None:
if failure in (FAILURE_KEY, FAILURE_BILLING, FAILURE_DISABLED):
self._session = None
(self.root / "session.json").unlink(missing_ok=True)
self._block(failure, KEY_BACKOFF_S)
else:
self._block(failure, SERVER_BACKOFF_S)
def step(self, api_key: str, online: bool) -> float | None:
"""Fetch at most one wanted tile. Returns seconds to wait before the next step, or None when idle."""
self.maintain()
if not api_key or not online:
return None
digest = key_digest(api_key)
if digest != self._digest:
self._digest, self._session, self.failure, self.blocked_until = digest, None, None, 0.0
if self.blocked:
return None
keys, position = read_want(self.want, self.wall())
if not keys:
return None
missing = next((key for key in keys if not self.store.fresh(digest, key, self.wall())), None)
try:
session = self._session_for(api_key)
if session is None:
return None
if position is not None and self.clock() - self._viewport_at >= VIEWPORT_EVERY_S:
self._viewport_at = self.clock()
self.copyright = viewport_copyright(self.http, api_key, session, position, keys[0].z) or self.copyright
if missing is None:
return None
if not self.budget.spend():
self._block(FAILURE_BUDGET, 3600.0)
return None
with self.http.get(TILE_URL.format(z=missing.z, x=missing.x, y=missing.y), params={"session": session},
headers={"X-Goog-Api-Key": api_key}, timeout=REQUEST_TIMEOUT, stream=True) as response:
status, body, lifetime = response.status_code, _body(response, MAX_TILE_BYTES), cache_lifetime(response.headers)
except requests.RequestException:
self._block(FAILURE_NETWORK, NETWORK_BACKOFF_S)
return None
except (ValueError, KeyError, TypeError):
self._block(FAILURE_SERVER, SERVER_BACKOFF_S)
return None
except OSError:
self._block(FAILURE_STORAGE, SERVER_BACKOFF_S)
return None
failure = classify(status, body)
if failure is not None:
self._refused(failure)
return None
if not body or not self.store.write(digest, missing, body, lifetime, self.wall()):
self._block(FAILURE_STORAGE if body else FAILURE_SERVER, SERVER_BACKOFF_S)
return None
self.failure = None
return 0.0
def maintain(self) -> None:
if self.clock() - self._last_trim >= 300.0:
self._last_trim = self.clock()
self.store.trim(now=self.wall())
def write_status(self, force: bool = False) -> None:
if not force and self.clock() - self._last_status < 2.0:
return
self._last_status = self.clock()
value = {"heartbeat": self.wall(), "failure": self.failure, "copyright": self.copyright,
"usage": self.budget.snapshot()}
try:
self.root.mkdir(parents=True, exist_ok=True)
_write_atomic(self.root / "status.json", value)
except OSError:
self.failure = FAILURE_STORAGE
def _write_atomic(path: Path, value: dict, mode: int | None = None) -> None:
fd, temp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-")
try:
with os.fdopen(fd, "w") as handle:
json.dump(value, handle, separators=(",", ":"))
if mode is not None:
os.chmod(temp, mode)
os.replace(temp, path)
except BaseException:
Path(temp).unlink(missing_ok=True)
raise
def read_status(root: Path | None = None) -> dict:
value = read_json((Path(root) if root is not None else google_root()) / "status.json", 64 * 1024)
return value if isinstance(value, dict) else {}
+9 -2
View File
@@ -25,6 +25,7 @@ from pathlib import Path
import requests
from openpilot.starpilot.navigation.google_tiles import GoogleTiles
from openpilot.starpilot.navigation.offline_roads import (
AREA_REFRESH_SECONDS, CACHE_MAX_BYTES, DRIVEN_MAX_BYTES, SAVED_MAX_BYTES, OfflineState, TileStore, Usage, area_tiles,
)
@@ -49,6 +50,7 @@ BUDGET_RECHECK_S = 3600.0
class Environment:
"""What the loop observed this second."""
token: str = ""
google_key: str = "" # only while Google is the chosen map style
network: str = "offline" # offline, cellular, wifi
onroad: bool = False
map_enabled: bool = False
@@ -457,8 +459,9 @@ def _environment(sm, owner, map_enabled: bool, now_ns: int) -> Environment:
try:
settings = owner.read()
env.token = settings["token"]
env.google_key = settings["googleKey"] if settings["mapProvider"] == "google" else ""
except Exception:
env.token = ""
env.token = env.google_key = ""
device = sm["deviceState"]
if sm.valid["deviceState"] and sm.logMonoTime["deviceState"] > 0:
kind = str(device.networkType)
@@ -490,6 +493,7 @@ def main() -> None:
except OSError:
pass
daemon = TileDaemon()
google = GoogleTiles()
owner = NavigationOwner()
from openpilot.starpilot.gps.source import GPS_SERVICES
sm = messaging.SubMaster(["deviceState", *GPS_SERVICES])
@@ -505,13 +509,16 @@ def main() -> None:
idle = False
deadline = time.monotonic() + 0.9
while time.monotonic() < deadline:
wait = daemon.step(env)
wait = google.step(env.google_key, env.network != "offline")
if wait is None:
wait = daemon.step(env)
if wait is None:
idle = True
break
if wait > 0:
time.sleep(min(wait, max(0.0, deadline - time.monotonic())))
daemon.status(env)
google.write_status()
if idle:
time.sleep(1.0)
+308 -45
View File
@@ -8,10 +8,11 @@ import hashlib
import json
import math
import os
import re
import stat
import sys
import subprocess
from urllib.parse import quote
from urllib.parse import quote, urljoin, urlsplit
from pathlib import Path
from itertools import islice
import tempfile
@@ -20,6 +21,7 @@ import time
import uuid
import requests
import requests.adapters
from openpilot.starpilot.storage import starpilot_storage_root
from openpilot.starpilot.navigation.position import LastPositionStore
@@ -33,8 +35,8 @@ MAX_SEARCHES = 32
TILE_CACHE_TTL = 15 * 60
TILE_CACHE_ENTRIES = 256
TILE_CACHE_BYTES = 32 * 1024 * 1024
TILE_SLOTS = 6
TILE_SLOT_WAIT_S = 3.0 # a panned-away request still holds its slot until Mapbox answers; wait instead of failing
TILE_SLOTS = 16
TILE_SLOT_WAIT_S = 5.0 # a panned-away request still holds its slot until Mapbox answers; wait instead of failing
AUTOCOMPLETE_TYPES = {'poi', 'address', 'street', 'place', 'neighborhood', 'locality'}
SUGGESTS_PER_SESSION = 50 # Mapbox starts a new billable session after this many suggestions
MAX_FAVORITES = 100
@@ -43,16 +45,46 @@ FAVORITE_LABELS = ('home', 'work')
ROUTE_AVOIDANCES = {'avoidTolls': 'toll', 'avoidHighways': 'motorway', 'avoidFerries': 'ferry'}
# Fixed provider styles matching Galaxy; cache entries are separate for each theme.
MAP_STYLES = {'light': 'mapbox/light-v11', 'dark': 'mapbox/dark-v11'}
MAP_PROVIDERS = ('mapbox', 'google')
SHORT_MAP_LINK = re.compile(r'https://(?:maps\.app\.goo\.gl|goo\.gl/maps)/[A-Za-z0-9_-]{1,64}')
GOOGLE_MAP_HOST = re.compile(r'(?:maps\.app\.goo\.gl|goo\.gl|(?:[a-z0-9-]+\.)*google\.com)')
CONFIGURABLE = {'enabled', 'token', 'gpsSource', 'mapProvider', 'routeProvider', 'googleKey'}
KEEPS_ACTIVE = {'gpsSource', 'mapProvider', 'routeProvider', 'googleKey'}
GOOGLE_KEY_CHARS = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-')
SAFE_ID = re.compile(r'[a-zA-Z0-9_-]{1,64}')
def valid_google_key(key: str) -> bool:
return key == '' or (20 <= len(key) <= 128 and set(key) <= GOOGLE_KEY_CHARS)
def default_settings() -> dict:
return {'version': 1, 'revision': '0', 'routingRevision': '0', 'enabled': False, 'token': '', 'destination': None, 'favorites': [], 'recents': [],
'gpsSource': 'backup', 'mapProvider': 'mapbox', 'routeProvider': 'mapbox', 'googleKey': '', **dict.fromkeys(ROUTE_AVOIDANCES, False)}
class ValidationError(ValueError):
pass
class ShareQueryError(ValidationError):
"""A shared place the driver has to pick from search results."""
def __init__(self, message: str, query: str):
super().__init__(message)
self.query = query
class ConflictError(ValueError):
pass
class PlaceResults(list):
"""Search results that name the provider that found them."""
def __init__(self, rows, provider: str):
super().__init__(rows)
self.provider = provider
def destination(value: dict) -> dict:
if not isinstance(value, dict):
raise ValidationError('Choose a destination')
@@ -112,12 +144,22 @@ def response_json(session, url: str, params: dict) -> dict:
raise ValidationError('The map service could not complete this request') from None
def _pooled_session() -> requests.Session:
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=8, pool_maxsize=24)
session.mount('https://', adapter)
session.mount('http://', adapter)
return session
class NavigationOwner:
def __init__(self, root: Path | None = None, runtime_source=None, session=requests, transient_root: Path | None = None):
def __init__(self, root: Path | None = None, runtime_source=None, session=None, transient_root: Path | None = None):
self.root = Path(root) if root is not None else starpilot_storage_root() / 'navigation'
self.path = self.root / 'settings.json'
self.position_store = LastPositionStore(self.root)
self.runtime_source, self.session = runtime_source, session
self.google_root = self.root / 'google-tiles'
self.runtime_source = runtime_source
self.session = _pooled_session() if session is None or session is requests else session
self._tile_slots = threading.BoundedSemaphore(TILE_SLOTS)
from openpilot.starpilot.navigation.mapbox_budget import MonthlyBudget
self.search_budget = MonthlyBudget('searchSessions', self.root / 'mapbox-usage')
@@ -146,8 +188,7 @@ class NavigationOwner:
try:
info = os.stat(self.path)
except FileNotFoundError:
return {'version': 1, 'revision': '0', 'enabled': False, 'token': '', 'destination': None, 'favorites': [], 'recents': [], 'gpsSource': 'backup',
**dict.fromkeys(ROUTE_AVOIDANCES, False)}
return default_settings()
key = (info.st_ino, info.st_mtime_ns, info.st_size)
cached = getattr(self, '_read_cache', None)
if cached is not None and cached[0] == key:
@@ -156,8 +197,7 @@ class NavigationOwner:
with self.path.open('rb') as source:
raw = source.read(MAX_DOCUMENT + 1)
except FileNotFoundError:
return {'version': 1, 'revision': '0', 'enabled': False, 'token': '', 'destination': None, 'favorites': [], 'recents': [], 'gpsSource': 'backup',
**dict.fromkeys(ROUTE_AVOIDANCES, False)}
return default_settings()
try:
value = json.loads(raw)
if (len(raw) > MAX_DOCUMENT or not isinstance(value, dict) or value.get('version') != 1 or
@@ -171,6 +211,17 @@ class NavigationOwner:
raise ValueError
if value.get('destination') is not None:
value['destination'] = destination(value['destination'])
routing_revision = value.setdefault('routingRevision', value['revision'])
if not isinstance(routing_revision, str) or SAFE_ID.fullmatch(routing_revision) is None:
raise ValueError
intents = value.setdefault('shareIntents', [])
if (not isinstance(intents, list) or len(intents) > 64 or
any(not isinstance(row, dict) or set(row) != {'id', 'digest'} or
not isinstance(row['id'], str) or SAFE_ID.fullmatch(row['id']) is None or
not isinstance(row['digest'], str) or re.fullmatch('[0-9a-f]{64}', row['digest']) is None for row in intents)):
raise ValueError
if len({row['id'] for row in intents}) != len(intents):
raise ValueError
value['favorites'] = [favorite_place(item) for item in value['favorites']]
value['recents'] = [destination(item) for item in value.get('recents', [])][:MAX_RECENTS]
for setting in ROUTE_AVOIDANCES:
@@ -178,6 +229,10 @@ class NavigationOwner:
raise ValueError
if value.setdefault('gpsSource', 'backup') not in GPS_MODES:
raise ValueError
if value.setdefault('mapProvider', 'mapbox') not in MAP_PROVIDERS or value.setdefault('routeProvider', 'mapbox') not in MAP_PROVIDERS:
raise ValueError
if not isinstance(value.setdefault('googleKey', ''), str) or not valid_google_key(value['googleKey']):
raise ValueError
except (ValueError, TypeError, KeyError):
raise ValidationError('Saved navigation settings could not be read') from None
self._read_cache = (key, copy.deepcopy(value))
@@ -249,13 +304,11 @@ class NavigationOwner:
os.close(directory)
def read_routing(self):
with self._exclusive():
current = self.read()
self._sweep_active(current)
active = self._read_active(current)
if active is not None:
current['destination'] = dict(active['destination'], temporary=True)
return current
current = self.read()
active = self._read_active(current)
if active is not None:
current['destination'] = dict(active['destination'], temporary=True)
return current
@contextmanager
def _exclusive(self):
@@ -272,10 +325,14 @@ class NavigationOwner:
raise ConflictError('Navigation changed; refresh and try again')
self._sweep_active(current)
active = self._read_active(current) if preserve_active else None
routing_fields = ('enabled', 'token', 'routeProvider', 'googleKey', *ROUTE_AVOIDANCES)
routing_before = tuple(current[key] for key in routing_fields)
transform(current)
if not (authorized() if callable(authorized) else authorized is True):
raise PermissionError('Navigation changes are not available right now')
current['revision'] = uuid.uuid4().hex
if not preserve_active or routing_before != tuple(current[key] for key in routing_fields):
current['routingRevision'] = current['revision']
if active_destination is not None:
active = {'version':1, 'destination':active_destination, 'expires':time.monotonic() + ACTIVE_TTL}
if active is not None:
@@ -340,6 +397,21 @@ class NavigationOwner:
result['favorites'] = sorted(document['favorites'], key=lambda row: FAVORITE_LABELS.index(row['label']) if 'label' in row else 2)
from openpilot.starpilot.navigation.mapbox_budget import read_usage
result['mapboxUsage'] = read_usage(self.root / 'mapbox-usage')
result['mapProvider'] = document['mapProvider']
result['hasGoogleKey'] = bool(document['googleKey'])
from openpilot.starpilot.navigation.google_tiles import MESSAGES, GoogleBudget, read_status
google_status = read_status(self.google_root)
failure = google_status.get('failure') if document['mapProvider'] == 'google' else None
copyright_text = google_status.get('copyright')
result['googleMap'] = {'usage': GoogleBudget(self.google_root).snapshot(), 'failure': MESSAGES.get(failure),
**({'copyright': copyright_text} if isinstance(copyright_text, str) and copyright_text else {})}
from openpilot.starpilot.navigation.google_routes import essentials_budget, read_route_failure, route_budget
result['routeProvider'] = document['routeProvider']
google_routing = document['routeProvider'] == 'google' and bool(document['googleKey'])
result['googleRoutes'] = {'usage': route_budget(self.google_root).snapshot(), 'essentials': essentials_budget(self.google_root).snapshot(),
'failure': read_route_failure(self.google_root) if google_routing else None}
from openpilot.starpilot.navigation.google_places import places_budget, suggestions_budget
result['googlePlaces'] = {'usage': places_budget(self.google_root).snapshot(), 'suggestions': suggestions_budget(self.google_root).snapshot()}
result['alternatives'] = [dict(row, geometry=rounded(row['geometry'])) for row in self.route_options(document['revision'])]
result['selectedRoute'] = document.get('routeChoice', 0)
result.update(hasKey=bool(document['token']), status=status, instruction=None, route=[], isMetric=self._is_metric(), location=None,
@@ -415,14 +487,32 @@ class NavigationOwner:
(self.transient_root / 'routes.cache').write_text(json.dumps(value, allow_nan=False))
return self.snapshot()
def map_tile(self, z: int, x: int, y: int, theme: str = 'light') -> bytes:
if theme not in MAP_STYLES:
def map_tile(self, z: int, x: int, y: int, theme: str = 'light', *, provider: str = 'mapbox') -> bytes:
if theme not in MAP_STYLES or provider not in ('mapbox', 'google'):
raise ValidationError('Invalid map theme')
if any(type(v) is not int for v in (z, x, y)) or not 0 <= z <= 18 or not 0 <= x < 2 ** z or not 0 <= y < 2 ** z:
raise ValidationError('Invalid map tile')
token = self.read()['token']
settings = self.read()
token = settings['token']
if not token:
raise ValidationError('Save a Mapbox key to view the map')
google_key = settings.get('googleKey', '') if provider == 'google' and settings.get('mapProvider') == 'google' else ''
if google_key:
if not self._tile_slots.acquire(timeout=TILE_SLOT_WAIT_S):
raise ValidationError('Map is busy; try again')
try:
from openpilot.starpilot.navigation.google_tiles import fetch_tile
tile = fetch_tile(google_key, z, x, y, theme, http=self.session, root=self.google_root)
current = self.read()
if current.get('googleKey', '') != google_key or current.get('mapProvider') != 'google':
raise ValidationError('Map key changed; try again')
return tile
except ValidationError:
raise
except (requests.RequestException, ValueError, OSError):
pass
finally:
self._tile_slots.release()
key = hashlib.sha256(token.encode()).digest()
coordinates = (theme, z, x, y)
with self._tile_lock:
@@ -440,13 +530,13 @@ class NavigationOwner:
try:
started = time.monotonic()
with self.session.get(f'https://api.mapbox.com/styles/v1/{MAP_STYLES[theme]}/tiles/512/{z}/{x}/{y}.png',
params={'access_token': token}, timeout=(2, 2), stream=True, allow_redirects=False) as response:
params={'access_token': token}, timeout=(3.05, 5.0), stream=True, allow_redirects=False) as response:
if response.status_code != 200 or response.headers.get('Content-Type', '').split(';')[0] != 'image/png':
raise ValidationError('Map tiles are unavailable')
raw = bytearray()
for chunk in response.iter_content(64 * 1024):
raw.extend(chunk)
if len(raw) > 2 * 1024 * 1024 or time.monotonic() - started > 5:
if len(raw) > 2 * 1024 * 1024 or time.monotonic() - started > 7:
raise ValidationError('Map tile exceeded the request limit')
if bytes(raw[:8]) != b'\x89PNG\r\n\x1a\n' or bytes(raw[12:16]) != b'IHDR' or bytes(raw[16:24]) != b'\x00\x00\x02\x00' * 2:
raise ValidationError('Invalid map tile response')
@@ -484,8 +574,14 @@ class NavigationOwner:
self._tile_bytes -= len(tile)
def configure(self, patch: dict, expected_revision: str, authorized) -> dict:
if not isinstance(patch, dict) or not patch or set(patch) - ({'enabled', 'token', 'gpsSource'} | ROUTE_AVOIDANCES.keys()):
if not isinstance(patch, dict) or not patch or set(patch) - (CONFIGURABLE | ROUTE_AVOIDANCES.keys()):
raise ValidationError('Unknown navigation setting')
if 'mapProvider' in patch and patch['mapProvider'] not in MAP_PROVIDERS:
raise ValidationError('Choose a map style')
if 'routeProvider' in patch and patch['routeProvider'] not in MAP_PROVIDERS:
raise ValidationError('Choose a route provider')
if 'googleKey' in patch and (not isinstance(patch['googleKey'], str) or not valid_google_key(patch['googleKey'])):
raise ValidationError('Enter a valid Google Maps API key')
if 'gpsSource' in patch and patch['gpsSource'] not in GPS_MODES:
raise ValidationError('Choose a GPS source')
if 'enabled' in patch and type(patch['enabled']) is not bool:
@@ -501,7 +597,7 @@ class NavigationOwner:
if any(key in patch and patch[key] != value[key] for key in ROUTE_AVOIDANCES):
value['routeChoice'] = 0
value.update(patch)
result = self._change(update, expected_revision, authorized, preserve_active=set(patch) <= ROUTE_AVOIDANCES.keys() | {'gpsSource'})
result = self._change(update, expected_revision, authorized, preserve_active=set(patch) <= ROUTE_AVOIDANCES.keys() | KEEPS_ACTIVE)
if 'token' in patch:
with self._tile_lock:
self._tiles.clear()
@@ -509,6 +605,122 @@ class NavigationOwner:
self._tile_key = None
return result
def test_google_key(self, key=None) -> dict:
"""Tries the typed key, or the saved one, on all three Google APIs: one tile, one route and one place lookup."""
key = self.read()['googleKey'] if key is None else key
if not isinstance(key, str) or not key or not valid_google_key(key):
raise ValidationError('Enter a valid Google Maps API key')
from concurrent.futures import ThreadPoolExecutor
from openpilot.starpilot.navigation.google_tiles import GoogleBudget, test_key
from openpilot.starpilot.navigation.google_routes import essentials_budget, test_routes
from openpilot.starpilot.navigation.google_places import places_budget, test_places
with ThreadPoolExecutor(max_workers=3) as pool:
routes = pool.submit(test_routes, key, self.session, essentials_budget(self.google_root))
places = pool.submit(test_places, key, self.session, places_budget(self.google_root))
return dict(test_key(key, self.session, GoogleBudget(self.google_root)), routes=routes.result(), places=places.result())
def resolve_share(self, text) -> str:
"""A shared Google Maps short link followed to the full link, which carries the place's coordinates."""
if not isinstance(text, str) or len(text) > 8192:
raise ValidationError('The shared text could not be read')
match = SHORT_MAP_LINK.search(text)
if match is None:
return text
current = match.group(0)
for _ in range(4):
try:
with self.session.get(current, allow_redirects=False, stream=True, timeout=(2., 2.)) as response:
location = response.headers.get('Location') if 300 <= response.status_code < 400 else None
except requests.RequestException:
break
if not location:
break
following = urljoin(current, location)
parts = urlsplit(following)
if parts.scheme != 'https' or not GOOGLE_MAP_HOST.fullmatch(parts.hostname or '') or len(following) > 8192:
break
current = following
return text.replace(match.group(0), current) if current != match.group(0) else text
def share(self, text, expected_revision: str, authorized, intent_id=None) -> dict:
"""A place shared from a phone: turns navigation on and starts the route."""
if not isinstance(text, str) or not text.strip() or len(text) > 8192:
raise ValidationError('The shared text could not be read')
if intent_id is not None and (not isinstance(intent_id, str) or SAFE_ID.fullmatch(intent_id) is None):
raise ValidationError('The shared destination identity could not be read')
if not (authorized() if callable(authorized) else authorized is True):
raise PermissionError('Navigation changes are not available right now')
digest = hashlib.sha256(text.encode()).hexdigest()
current = self.read()
if intent_id is not None:
previous = next((row for row in current.get('shareIntents', []) if row['id'] == intent_id), None)
if previous is not None:
if previous['digest'] != digest:
raise ValidationError('The shared destination identity was already used')
return self.snapshot()
if not current['token']:
raise ValidationError('Add your Mapbox access token first')
if not isinstance(expected_revision, str) or current['revision'] != expected_revision:
raise ConflictError('Navigation changed; refresh and try again')
from openpilot.starpilot.navigation.share import map_link_query, search_text, shared_coordinates
text = self.resolve_share(text)
shared = shared_coordinates(text)
if shared is None:
query = map_link_query(text)
if query is None:
query = search_text(text)
if not query:
raise ValidationError('This map link could not be opened')
raise ShareQueryError(f'Open StarPilot to search for {query}', query)
shared = self._geocode_share(query)
selected = destination(shared)
def update(doc):
self._reject_temporary_promotion(doc, selected)
doc['enabled'] = True
self._navigate(doc, selected)
if intent_id is not None:
doc['shareIntents'] = [*doc.get('shareIntents', [])[-63:], {'id': intent_id, 'digest': digest}]
result = self._change(update, expected_revision, authorized)
return dict(result, shared={key: selected[key] for key in ('name', 'latitude', 'longitude')})
def _geocode_share(self, query: str) -> dict:
from openpilot.starpilot.navigation.share import place
name, _, rest = query.partition(',')
found = self._google_text_search(self.read(), query, 1)
if found == []:
raise ShareQueryError(f'No map location found for {name.strip() or query}', query[:200])
if found:
top = found[0]
return place(top['name'], top['latitude'], top['longitude'], top['address'] or top['name'])
# Geocoding finds addresses, not names: "Name, 123 Main St, City" tries the street address first.
attempts = ([rest.strip()] if any(ch.isdigit() for ch in rest.split(',')[0]) else []) + [query]
for attempt in attempts:
results = self.search(attempt) if len(attempt.strip()) >= 2 else []
if results:
top = results[0]
return place(name.strip() or query, top['latitude'], top['longitude'], top.get('address') or top['name'])
raise ShareQueryError(f'No map location found for {name.strip() or query}', query[:200])
@staticmethod
def _google_places_key(settings) -> str:
"""Places are found with Google when Google gives directions."""
return settings['googleKey'] if settings['routeProvider'] == 'google' else ''
def _proximity(self):
proximity = self._search_context().get('proximity')
return tuple(float(value) for value in proximity.split(',')) if proximity else None
def _google_text_search(self, settings, query: str, limit: int) -> list[dict] | None:
"""Google's places for the text; None when Google is not chosen or can't answer, so Mapbox looks instead."""
key = self._google_places_key(settings)
if not key:
return None
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed, places_budget, text_search
try:
return text_search(self.session, key, query.strip(), places_budget(self.google_root), self._proximity(), limit=limit)
except GooglePlacesFailed:
return None
def search(self, query: str) -> list[dict]:
if not isinstance(query, str) or not 2 <= len(query.strip()) <= 256:
raise ValidationError('Enter at least two characters to search')
@@ -580,6 +792,16 @@ class NavigationOwner:
current = self.read()
if not current['token']:
raise ValidationError('Add your Mapbox access token first')
if not autocomplete:
found = self._google_text_search(current, query, 8)
if found is not None:
results = []
for row in found:
try:
results.append(destination(row))
except ValidationError:
continue
return PlaceResults(results, 'google')
key = (caller, search_id)
from openpilot.starpilot.navigation.mapbox_budget import BudgetExhausted
with self._lock:
@@ -598,7 +820,7 @@ class NavigationOwner:
entry = previous
entry['expires'] = now + SEARCH_TTL
entry['suggests'] = entry.get('suggests', 0) + 1
if entry['suggests'] % SUGGESTS_PER_SESSION == 0:
if entry['provider'] == 'mapbox' and entry['suggests'] % SUGGESTS_PER_SESSION == 0:
try:
self.search_budget.spend()
except BudgetExhausted as error:
@@ -606,13 +828,16 @@ class NavigationOwner:
else:
if len(self._searches) >= MAX_SEARCHES or sum(key[0] == caller for key in self._searches) >= 8:
raise ValidationError('Too many destination searches; try again shortly')
provider = 'google' if autocomplete and self._google_places_key(current) else 'mapbox'
# The Search button keeps upstream's behavior (counted, never refused); typing suggestions stop at the cap.
try:
self.search_budget.spend(enforce=autocomplete)
if provider == 'mapbox':
self.search_budget.spend(enforce=autocomplete)
except BudgetExhausted as error:
raise ValidationError(str(error)) from None
entry = {'client_id':client_id, 'session':str(uuid.uuid4()), 'expires':now + SEARCH_TTL, 'revision':current['revision'],
'token_digest':hashlib.sha256(current['token'].encode()).digest(), 'ids':set(), 'autocomplete':autocomplete}
'token_digest':hashlib.sha256(current['token'].encode()).digest(), 'ids':set(), 'autocomplete':autocomplete,
'provider':provider, 'google':{}, 'google_session':str(uuid.uuid4())}
self._searches[key] = entry
try:
context = self._search_context()
@@ -620,23 +845,15 @@ class NavigationOwner:
if (self._searches.get(key) is not entry or entry['expires'] <= time.monotonic() or
self.read()['token'] != current['token']):
raise ValidationError('Start a new destination search')
data = response_json(self.session, 'https://api.mapbox.com/search/searchbox/v1/suggest',
{'q':query.strip(), 'access_token':current['token'], 'session_token':entry['session'],
'types':','.join(sorted(AUTOCOMPLETE_TYPES)) if autocomplete else 'poi', 'limit':8, **context})
suggestions = data.get('suggestions')
if not isinstance(suggestions, list):
raise ValidationError('The map service returned invalid search results')
results = []
for item in suggestions[:8]:
if not isinstance(item, dict):
continue
identity, name = item.get('mapbox_id'), item.get('name')
kinds = AUTOCOMPLETE_TYPES if autocomplete else {'poi'}
if (item.get('feature_type') in kinds and isinstance(identity, str) and 1 <= len(identity) <= 256 and
isinstance(name, str) and 1 <= len(name.strip()) <= 256):
description = item.get('full_address') or item.get('place_formatted') or ''
description = description.strip()[:512] if isinstance(description, str) else ''
results.append({'id':identity, 'name':name.strip(), 'description':description, 'searchId':search_id, 'temporary':True})
results = self._google_suggest(entry, current, query, search_id, context) if entry['provider'] == 'google' else None
if results is None:
data = response_json(self.session, 'https://api.mapbox.com/search/searchbox/v1/suggest',
{'q':query.strip(), 'access_token':current['token'], 'session_token':entry['session'],
'types':','.join(sorted(AUTOCOMPLETE_TYPES)) if autocomplete else 'poi', 'limit':8, **context})
suggestions = data.get('suggestions')
if not isinstance(suggestions, list):
raise ValidationError('The map service returned invalid search results')
results = self._mapbox_suggestions(suggestions, search_id, autocomplete)
with self._lock:
if (self._searches.get(key) is not entry or entry['expires'] <= time.monotonic() or
self.read()['token'] != current['token']):
@@ -644,20 +861,58 @@ class NavigationOwner:
# Any suggestion shown during this typing session can still be chosen.
entry['ids'] = (entry['ids'] if autocomplete else set()) | {item['id'] for item in results}
if results or autocomplete:
return results
return PlaceResults(results, entry['provider'])
except ValidationError:
with self._lock:
if (self._searches.get(key) is not entry or entry['expires'] <= time.monotonic() or
self.read()['token'] != current['token']):
raise ValidationError('Start a new destination search') from None
if autocomplete:
return [] # suggestions are best effort; typing never spends address lookups
return PlaceResults([], entry['provider']) # suggestions are best effort; typing never spends address lookups
self.cancel_search(caller, search_id)
# Address search remains available if place search is unavailable.
return self.search(query)
self.cancel_search(caller, search_id)
return self.search(query)
def _google_suggest(self, entry, current, query, search_id, context) -> list[dict] | None:
"""Google's typing suggestions; None after Google fails, and the session continues on Mapbox."""
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed, autocomplete, suggestions_budget
from openpilot.starpilot.navigation.mapbox_budget import BudgetExhausted
proximity = None
if context.get('proximity'):
longitude, latitude = (float(value) for value in context['proximity'].split(','))
proximity = (longitude, latitude)
try:
rows = autocomplete(self.session, current['googleKey'], query.strip(), entry['google_session'], suggestions_budget(self.google_root), proximity)
except GooglePlacesFailed:
with self._lock:
entry['provider'] = 'mapbox'
try:
self.search_budget.spend(enforce=True)
except BudgetExhausted as error:
raise ValidationError(str(error)) from None
return None
results = [dict(row, searchId=search_id, temporary=True) for row in rows]
with self._lock:
entry['google'].update({row['id']: row for row in results})
return results
@staticmethod
def _mapbox_suggestions(suggestions, search_id, autocomplete) -> list[dict]:
results = []
for item in suggestions[:8]:
if not isinstance(item, dict):
continue
identity, name = item.get('mapbox_id'), item.get('name')
kinds = AUTOCOMPLETE_TYPES if autocomplete else {'poi'}
if (item.get('feature_type') in kinds and isinstance(identity, str) and 1 <= len(identity) <= 256 and
isinstance(name, str) and 1 <= len(name.strip()) <= 256):
description = item.get('full_address') or item.get('place_formatted') or ''
description = description.strip()[:512] if isinstance(description, str) else ''
results.append({'id':identity, 'name':name.strip(), 'description':description, 'searchId':search_id, 'temporary':True})
return results
def _retrieve(self, identity, search_id, caller, expected_revision, authorized) -> dict:
"""Temporary coordinates for the selected route."""
if not isinstance(identity, str) or not isinstance(search_id, str):
@@ -671,6 +926,14 @@ class NavigationOwner:
raise ValidationError('Search again before choosing this place')
if not (authorized() if callable(authorized) else authorized is True):
raise PermissionError('Navigation changes are not available right now')
suggested = entry.get('google', {}).get(identity)
if suggested is not None:
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed, place_details
try:
found = place_details(self.session, current['googleKey'], identity, entry['google_session'])
except GooglePlacesFailed:
raise ValidationError('Google could not open this place; search again') from None
return destination(dict(found, name=suggested['name'], address=found['address'] or suggested['description']))
data = response_json(self.session, 'https://api.mapbox.com/search/searchbox/v1/retrieve/' + quote(identity, safe=''),
{'access_token':current['token'], 'session_token':entry['session']})
try:
+51 -7
View File
@@ -4,10 +4,17 @@ from bisect import bisect_right
from dataclasses import dataclass
import math
import numpy as np
from openpilot.starpilot.navigation.owner import ValidationError, response_json
EARTH_RADIUS = 6371007.2
MAX_POINTS = 20000
PREVIEW_POINTS = 512
PREVIEW_TOLERANCE_M = 1.0
HEADING_CHECK_MPS = 8. # pointing away from the route counts as off it only at road speed, not on ramps or in lots
SLOW_MPS = 5.
SLOW_OFF_ROUTE_M = 75. # slower than SLOW_MPS, the car must be this far from the line to be off it
def point(value) -> tuple[float, float]:
@@ -44,6 +51,43 @@ def modifier(value) -> str:
'sharp left', 'sharpLeft').replace('sharp right', 'sharpRight')
def simplify(points, limit: int = PREVIEW_POINTS, tolerance: float = PREVIEW_TOLERANCE_M) -> list[int]:
"""Indices of the points that best keep the line's shape (Douglas-Peucker ranking): corners survive, straight runs thin out."""
count = len(points)
if count <= 2:
return list(range(count))
xy = np.asarray(points, np.float64)[:, :2]
scale = EARTH_RADIUS * math.pi / 180
xy = np.column_stack(((xy[:, 0] - xy[0, 0]) * scale * math.cos(math.radians(float(xy[:, 1].mean()))), (xy[:, 1] - xy[0, 1]) * scale))
importance = np.zeros(count)
importance[0] = importance[-1] = math.inf
stack = [(0, count - 1)]
while stack:
first, last = stack.pop()
if last - first < 2:
continue
a, b = xy[first], xy[last]
inner = xy[first + 1:last]
direction = b - a
length = math.hypot(*direction)
if length < 1e-9:
deviation = np.hypot(*(inner - a).T)
else:
fraction = np.clip((inner - a) @ direction / length ** 2, 0., 1.)
deviation = np.hypot(*(inner - (a + fraction[:, None] * direction)).T)
index = int(np.argmax(deviation))
if deviation[index] <= tolerance:
continue
split = first + 1 + index
importance[split] = deviation[index]
stack.append((first, split))
stack.append((split, last))
ranked = np.flatnonzero(importance > tolerance)
if len(ranked) > limit:
ranked = np.sort(np.argsort(-importance, kind='stable')[:limit])
return [int(i) for i in ranked]
@dataclass(frozen=True)
class Step:
start: float
@@ -81,6 +125,7 @@ class Progress:
next_maneuver: dict
off_route: bool
arrived: bool
separation: float = 0.
class NavigationRoute:
@@ -114,15 +159,12 @@ class NavigationRoute:
if self.total_distance < 1 or offset < 1:
raise ValidationError('The route is empty')
self.starts = [step.start for step in self.steps]
self._preview = [{'longitude': self.points[i][0], 'latitude': self.points[i][1]} for i in simplify(self.points)]
except (KeyError, TypeError, IndexError, AttributeError):
raise ValidationError('The map service returned an incomplete route') from None
def preview(self) -> list[dict]:
stride = max(1, math.ceil((len(self.points) - 1) / 511))
points = self.points[::stride]
if points[-1] != self.points[-1]:
points.append(self.points[-1])
return [{'longitude': x, 'latitude': y} for x, y in points]
return self._preview
def progress(self, position, speed: float | None, bearing: float | None = None) -> Progress:
best = (float('inf'), 0., 0)
@@ -152,15 +194,17 @@ class NavigationRoute:
bucket = min(3, max(0, bisect_right(speeds, threshold_speed) - 1))
fraction = min(1., max(0., (threshold_speed - speeds[bucket]) / (speeds[bucket + 1] - speeds[bucket])))
threshold = distances[bucket] + fraction * (distances[bucket + 1] - distances[bucket])
if threshold_speed < SLOW_MPS:
threshold = max(threshold, SLOW_OFF_ROUTE_M)
misaligned = False
if bearing is not None and known_speed and speed >= 2.5:
if bearing is not None and known_speed and speed >= HEADING_CHECK_MPS:
a, b = self.points[segment], self.points[segment + 1]
lat1, lat2, delta = math.radians(a[1]), math.radians(b[1]), math.radians(b[0] - a[0])
direction = math.degrees(math.atan2(math.sin(delta) * math.cos(lat2),
math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(delta)))
misaligned = abs((direction - bearing + 180) % 360 - 180) > 75
arrived = known_speed and speed < 2 and distance(position, self.points[-1]) < 40 and instruction['remainingDistanceMeters'] < 40
return Progress(instruction, next_maneuver, separation > threshold or misaligned, arrived)
return Progress(instruction, next_maneuver, separation > threshold or misaligned, arrived, separation)
class MapboxRouteEngine:
+136 -10
View File
@@ -7,13 +7,27 @@ 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 SLOW_MPS, MapboxRouteEngine, distance
from openpilot.starpilot.navigation.google_routes import (
GoogleRouteEngine, GoogleRoutesFailed, essentials_budget, route_budget, write_route_status,
)
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
MOVING_MPS = 5. # a Google route asked for faster than this starts the way the car faces
TRAFFIC_EVERY_NS = 450_000_000_000 # Google's traffic corrects the arrival time this often (one Pro request)
TRAFFIC_MIN_M = 2000. # ...but not this close to the destination
TRAFFIC_MATCH_M = 500. # Google's answer must be for about the same remaining distance
OFF_ROUTE_NS = 2_000_000_000 # off the route this long reroutes
SLOW_OFF_ROUTE_NS = 8_000_000_000 # ...or this long when slower than SLOW_MPS (garages, lots)
JOINED_M = 25. # this close to the line, the car has joined the route
UNJOINED_REROUTE_M = 300. # before joining, only this far from where the route starts reroutes (leaving a garage or lot)
def location(sm, now_ns: int, phone_fix=None):
@@ -26,13 +40,23 @@ def location(sm, now_ns: int, phone_fix=None):
class RouteRuntime:
def __init__(self, owner: NavigationOwner, engine=None, executor=None):
def __init__(self, owner: NavigationOwner, engine=None, executor=None, google_engine=None):
self.owner = owner
if engine is None:
from openpilot.starpilot.navigation.mapbox_budget import MonthlyBudget
engine = MapboxRouteEngine(owner.session, MonthlyBudget('directions', owner.root / 'mapbox-usage'))
self.engine = engine
self.google_engine = google_engine or GoogleRouteEngine(owner.session, route_budget(owner.google_root),
essentials_budget(owner.google_root))
self.joined_route = None
self.joined = False
self.eta_route = None
self.eta_ratio = 1.
self.traffic_future = None
self.traffic_job = None
self.traffic_due = 0
self.executor = executor or ThreadPoolExecutor(max_workers=1, thread_name_prefix='route')
self.traffic_executor = executor or ThreadPoolExecutor(max_workers=1, thread_name_prefix='traffic')
self.key = None
self.route = None
self.routes = []
@@ -44,6 +68,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,13 +82,24 @@ 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])
key = settings['enabled'], hashlib.sha256(settings['token'].encode()).digest(), destination_key, drive_id, exclusions
credentials = (settings['token'], settings['googleKey'] if settings['routeProvider'] == 'google' else '')
key = (settings['enabled'], hashlib.sha256('\0'.join(credentials).encode()).digest(), destination_key,
drive_id, exclusions, settings['routeProvider'], settings['routingRevision'])
if key != self.key:
self.key, self.route = key, None
self.routes = []
self.fetch_key = None
self.preview_only = False
self.retry_after = self.off_route_since = self.arrived_since = 0
# A saved origin can draw a preview, but a fresh fix must calculate its own route.
@@ -107,8 +147,8 @@ class RouteRuntime:
if self.future is None and now_ns >= self.retry_after:
self.preview_only = True
self.fetch_key = self.key
self.future = self.executor.submit(self.engine.fetch, settings['token'],
(saved['longitude'], saved['latitude']), settings['destination'], saved.get('bearing'), exclusions)
self.future = self.executor.submit(*self._fetcher(credentials), (saved['longitude'], saved['latitude']),
settings['destination'], None if credentials[1] else saved.get('bearing'), exclusions)
return result
stamp, coordinates, speed, bearing = position
result['locationMonoTime'] = stamp
@@ -116,25 +156,111 @@ class RouteRuntime:
result['status'] = 'routeUnavailable' if self.retry_after > now_ns else 'routing'
if self.future is None and now_ns >= self.retry_after:
self.fetch_key = self.key
self.future = self.executor.submit(self.engine.fetch, settings['token'], coordinates, settings['destination'], bearing, exclusions)
moving = speed is not None and speed >= MOVING_MPS
self.future = self.executor.submit(*self._fetcher(credentials), coordinates, settings['destination'],
bearing if moving or not credentials[1] else None, exclusions)
return result
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
if self.off_route_since and now_ns - self.off_route_since >= 2_000_000_000:
off_route = fresh and progress.off_route and self._may_reroute(coordinates, progress, selected)
self.off_route_since = (self.off_route_since or now_ns) if off_route 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
hold = SLOW_OFF_ROUTE_NS if speed is None or speed < SLOW_MPS else OFF_ROUTE_NS
if self.off_route_since and now_ns - self.off_route_since >= hold:
self.route = None
self.routes = []
result['status'] = 'routing'
return result
arrived = self.arrived_since and now_ns - self.arrived_since >= ARRIVED_NS
self._traffic_eta(now_ns, credentials[1], coordinates, speed, bearing, settings['destination'], exclusions, progress.instruction)
if self.arrived_since and now_ns - self.arrived_since >= END_ROUTE_NS:
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
def _may_reroute(self, coordinates, progress, destination) -> bool:
"""No reroutes before the car first reaches the route near its start, or near the destination (garages, lots)."""
if self.route is not self.joined_route:
self.joined_route, self.joined = self.route, False
if progress.separation <= JOINED_M and not progress.off_route:
self.joined = True
if distance(coordinates, (destination['longitude'], destination['latitude'])) < PARKED_RADIUS_M:
return False
return self.joined or (self.route is not None and distance(coordinates, self.route.points[0]) >= UNJOINED_REROUTE_M)
def _traffic_eta(self, now_ns: int, key: str, coordinates, speed, bearing, destination, exclusions, instruction: dict) -> None:
"""The route's own remaining time, scaled by how far off Google's latest traffic said it was."""
if self.route is not self.eta_route:
self.eta_route, self.eta_ratio, self.traffic_future = self.route, 1., None
self.traffic_due = now_ns + (TRAFFIC_EVERY_NS if getattr(self.route, 'traffic_aware', True) else 0)
if self.traffic_future is not None and self.traffic_future.done() and self.traffic_job is not None:
route, static, meters = self.traffic_job
try:
duration, google_meters = self.traffic_future.result()
except (GoogleRoutesFailed, ValidationError, OSError, ValueError):
duration = None
if duration is not None and route is self.route and static > 0 and abs(google_meters - meters) <= max(TRAFFIC_MATCH_M, meters * .15):
self.eta_ratio = min(4., max(.5, duration / static))
self.traffic_future = None
static, meters = instruction['remainingDurationSeconds'], instruction['remainingDistanceMeters']
if key and self.traffic_future is None and now_ns >= self.traffic_due and meters > TRAFFIC_MIN_M:
self.traffic_due = now_ns + TRAFFIC_EVERY_NS
self.traffic_job = (self.route, static, meters)
moving = speed is not None and speed >= MOVING_MPS
self.traffic_future = self.traffic_executor.submit(self.google_engine.traffic, key, coordinates, destination,
bearing if moving else None, exclusions)
instruction['remainingDurationSeconds'] = static * self.eta_ratio
def _fetcher(self, credentials):
return (self._fetch_google, credentials) if credentials[1] else (self.engine.fetch, credentials[0])
def _fetch_google(self, credentials, position, destination, bearing, exclusions):
"""Google's traffic-aware route; Mapbox routes the trip whenever Google cannot."""
token, key = credentials
try:
route = self.google_engine.fetch(key, position, destination, bearing, exclusions)
except GoogleRoutesFailed as error:
write_route_status(self.owner.google_root, error.failure)
return self.engine.fetch(token, position, destination, bearing, exclusions)
write_route_status(self.owner.google_root, None)
return route
@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 drive that ends or starts near the destination counts as arrived, even without a final GPS fix."""
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:
+72
View File
@@ -0,0 +1,72 @@
import re
from urllib.parse import parse_qs, unquote_plus, urlsplit
# Same rules as galaxy/web/js/share-destination.js: destination coordinates before Google's viewport (@lat,lng).
NUMBER = r'(-?\d+(?:\.\d+)?)'
COORDINATES = (re.compile(rf'!3d{NUMBER}!4d{NUMBER}'), re.compile(rf'[?&:](?:q|query|daddr|destination|ll|coordinate)={NUMBER},\s*{NUMBER}'),
re.compile(rf'geo:{NUMBER},\s*{NUMBER}'), re.compile(rf'to=ll\.{NUMBER},\s*{NUMBER}'), re.compile(rf'@{NUMBER},\s*{NUMBER}'))
WAZE_SHORT = re.compile(r'https://(?:www\.)?waze\.com/ul/h([0-9b-hjkmnp-z]{4,12})(?![0-9a-z])', re.I)
GEOHASH = '0123456789bcdefghjkmnpqrstuvwxyz'
QUERY = re.compile(r'[?&:](?:q|query|daddr|destination)=([^&#]+)')
QUERY_KEYS = ('q', 'query', 'daddr', 'destination')
LINK = re.compile(r'https://[^\s<>"]+')
MAP_HOST = re.compile(r'(?:[a-z0-9-]+\.)*google\.com|(?:maps\.app\.)?goo\.gl|maps\.apple(?:\.com)?|(?:[a-z0-9-]+\.)?waze\.com')
def place(label: str, latitude: float, longitude: float, address: str | None = None) -> dict:
name, _, rest = label.partition(',')
return {'name': name.strip()[:256] or 'Shared destination', 'latitude': latitude, 'longitude': longitude,
'address': address or rest.strip() or None}
def waze_geohash(code: str) -> tuple[float, float]:
latitude, longitude, even = [-90.0, 90.0], [-180.0, 180.0], True
for char in code.lower():
bits = GEOHASH.index(char)
for shift in range(4, -1, -1):
span = longitude if even else latitude
middle = (span[0] + span[1]) / 2
span[0 if bits >> shift & 1 else 1] = middle
even = not even
return round((latitude[0] + latitude[1]) / 2, 6), round((longitude[0] + longitude[1]) / 2, 6)
def shared_coordinates(text: str) -> dict | None:
waze = WAZE_SHORT.search(text)
if waze:
return place('Shared destination', *waze_geohash(waze[1]))
decoded = unquote_plus(text.strip())
for pattern in COORDINATES:
match = pattern.search(decoded)
if match is None:
continue
latitude, longitude = float(match[1]), float(match[2])
if abs(latitude) > 90 or abs(longitude) > 180:
continue
# geo:0,0?q=an address is a search, not a destination in the ocean.
if match[0].startswith('geo:0,0') and re.search(r'[?&:]q=', decoded):
continue
label = (re.search(r'\(([^()]{1,120})\)', decoded) or re.search(r'/place/([^/?#&\n]+)', decoded) or
re.search(r'[?&](?:name|q)=([^&#\n]*[^\d\s,.&#-][^&#\n]*)', decoded))
return place(label[1] if label else 'Shared destination', latitude, longitude)
return None
def map_link_query(text: str) -> str | None:
"""The place a Google or Apple Maps link names, for links without coordinates."""
for link in LINK.findall(text):
parts = urlsplit(link)
if not MAP_HOST.fullmatch(parts.hostname or ''):
continue
named = re.search(r'/place/([^/]+)', parts.path)
values = parse_qs(parts.query)
query = unquote_plus(named[1]) if named else next((values[key][0] for key in QUERY_KEYS if key in values), '')
query = ' '.join(query.split())
if query:
return query[:256]
return None
def search_text(text: str) -> str:
match = QUERY.search(unquote_plus(text.strip()))
return ' '.join((match[1] if match else LINK.sub(' ', text)).split())[:200]
@@ -0,0 +1,269 @@
import json
from contextlib import contextmanager
from types import SimpleNamespace
import pytest
import requests
from openpilot.starpilot.navigation import google_routes as gr
from openpilot.starpilot.navigation.owner import NavigationOwner
from openpilot.starpilot.navigation.runtime import RouteRuntime
from openpilot.starpilot.navigation.tests.test_route_runtime import Executor, configured
KEY = "AIzaSyFixtureKey_0123456789abcdef"
WALL = 1_762_600_000.0
LINE = "_p~iF~ps|U_ulLnnqC_mqNvxq`@" # Google's documented example polyline
def google_route(duration="150s"):
return {"distanceMeters": 1200, "duration": duration, "polyline": {"encodedPolyline": LINE}, "legs": [{"steps": [
{"distanceMeters": 500, "staticDuration": "40s", "navigationInstruction": {"maneuver": "DEPART", "instructions": "Head north on Main St"}},
{"distanceMeters": 400, "staticDuration": "30s", "navigationInstruction": {"maneuver": "TURN_SLIGHT_RIGHT", "instructions": "Slight right onto Oak St"}},
{"distanceMeters": 300, "staticDuration": "30s", "navigationInstruction": {"maneuver": "RAMP_RIGHT", "instructions": "Take exit 12 toward Airport"}},
]}]}
class Http:
def __init__(self, status=200, body=None, error=None):
self.calls = []
self.status, self.error = status, error
self.body = json.dumps({"routes": [google_route(), google_route("200s")]}).encode() if body is None else body
@contextmanager
def post(self, url, **kwargs):
self.calls.append((url, kwargs))
if self.error is not None:
raise self.error
yield SimpleNamespace(status_code=self.status, iter_content=lambda size: iter([self.body]))
def budget(tmp_path):
return gr.GoogleBudget(tmp_path, clock=lambda: WALL, file="routes-usage.json", month_free=gr.FREE_ROUTES, day_free=None)
def essentials(tmp_path):
return gr.GoogleBudget(tmp_path, clock=lambda: WALL, file="routes-essentials-usage.json", month_free=gr.FREE_ESSENTIAL_ROUTES, day_free=None)
def engine(http, tmp_path):
return gr.GoogleRouteEngine(http, budget(tmp_path), essentials(tmp_path))
def test_polyline_decodes_googles_example():
points = [value for point in gr.decode_polyline(LINE) for value in point]
assert points == pytest.approx([-120.2, 38.5, -120.95, 40.7, -126.453, 43.252])
with pytest.raises(gr.ValidationError):
gr.decode_polyline("_p~iF~ps|")
def encode(points):
out, last = [], (0, 0)
for latitude, longitude in points:
current = (round(latitude * 1e5), round(longitude * 1e5))
for delta in (current[0] - last[0], current[1] - last[1]):
value = ~(delta << 1) if delta < 0 else delta << 1
while value >= 0x20:
out.append(chr((0x20 | (value & 0x1f)) + 63))
value >>= 5
out.append(chr(value + 63))
last = current
return "".join(out)
def test_long_detailed_route_is_thinned_not_refused():
points = [(37.0 + index * 1e-5, -122.0) for index in range(gr.MAX_POINTS * 2 + 7)]
route = dict(google_route(), polyline={"encodedPolyline": encode(points)})
shaped = gr.mapbox_shape(route)["geometry"]["coordinates"]
assert len(shaped) <= gr.MAX_POINTS and shaped[0] == [-122.0, 37.0] and shaped[-1] == pytest.approx([-122.0, points[-1][0]])
gr.NavigationRoute(gr.mapbox_shape(route))
def test_google_route_becomes_a_navigation_route_with_traffic_times():
shaped = gr.mapbox_shape(google_route())
steps = shaped["legs"][0]["steps"]
assert [step["maneuver"]["type"] for step in steps] == ["depart", "turn", "off ramp", "arrive"]
assert steps[1]["maneuver"]["modifier"] == "slight right"
assert sum(step["duration"] for step in steps) == pytest.approx(150)
route = gr.NavigationRoute(shaped)
assert route.steps[0].text == "Slight right onto Oak St" and route.steps[-2].text == "Arrive at your destination"
assert route.total_duration == 150 and route.total_distance == 1200
def test_moving_reroute_is_traffic_aware_with_heading_and_key_in_a_header(tmp_path):
http = Http()
route = engine(http, tmp_path).fetch(KEY, (-122.42, 37.77), {"latitude": 37.8, "longitude": -122.4}, 365.0, ("toll", "ferry"))
url, kwargs = http.calls[0]
assert url == gr.ROUTES_URL and KEY not in url
assert kwargs["headers"] == {"X-Goog-Api-Key": KEY, "X-Goog-FieldMask": gr.FIELD_MASK}
body = kwargs["json"]
assert body["routingPreference"] == "TRAFFIC_AWARE" and body["origin"]["location"]["heading"] == 5
assert body["polylineQuality"] == "HIGH_QUALITY"
assert body["routeModifiers"] == {"avoidTolls": True, "avoidFerries": True}
assert len(route.alternatives) == 2 and route.alternatives[1].total_duration == 200 and route.traffic_aware
assert budget(tmp_path).snapshot()["monthUsed"] == 1 and essentials(tmp_path).snapshot()["monthUsed"] == 0
def test_trip_start_is_traffic_aware_without_heading(tmp_path):
http = Http()
route = engine(http, tmp_path).fetch(KEY, (-122.42, 37.77), {"latitude": 37.8, "longitude": -122.4})
body = http.calls[0][1]["json"]
assert body["routingPreference"] == "TRAFFIC_AWARE" and "heading" not in body["origin"]["location"]
assert body["computeAlternativeRoutes"] and body["polylineQuality"] == "HIGH_QUALITY"
assert route.traffic_aware
assert budget(tmp_path).snapshot()["monthUsed"] == 1 and essentials(tmp_path).snapshot()["monthUsed"] == 0
def test_off_route_loop_switches_to_free_routes_for_the_hour(tmp_path):
clock = [1000.]
http = Http()
routes = gr.GoogleRouteEngine(http, budget(tmp_path), essentials(tmp_path), clock=lambda: clock[0])
for _ in range(gr.PRO_ROUTES_PER_HOUR):
assert routes.fetch(KEY, (0., 0.), {"latitude": 0., "longitude": .01}, 90.).traffic_aware
extra = routes.fetch(KEY, (0., 0.), {"latitude": 0., "longitude": .01}, 90.)
assert not extra.traffic_aware and http.calls[-1][1]["json"]["routingPreference"] == "TRAFFIC_UNAWARE"
assert "heading" not in http.calls[-1][1]["json"]["origin"]["location"]
clock[0] += 3601
assert routes.fetch(KEY, (0., 0.), {"latitude": 0., "longitude": .01}, 90.).traffic_aware
def test_routes_fall_back_to_essentials_when_traffic_requests_are_used_up(tmp_path):
spent = budget(tmp_path)
assert spent.spend(spent.month_limit)
http = Http()
engine(http, tmp_path).fetch(KEY, (0., 0.), {"latitude": 0., "longitude": .01}, 90.)
body = http.calls[0][1]["json"]
assert body["routingPreference"] == "TRAFFIC_UNAWARE" and "heading" not in body["origin"]["location"]
def test_traffic_request_asks_only_for_time_and_distance(tmp_path):
http = Http(body=b'{"routes": [{"duration": "900s", "distanceMeters": 12000}]}')
assert engine(http, tmp_path).traffic(KEY, (0., 0.), {"latitude": 0., "longitude": .1}, 90.) == (900., 12000.)
kwargs = http.calls[0][1]
assert kwargs["headers"]["X-Goog-FieldMask"] == gr.TRAFFIC_MASK and kwargs["json"]["routingPreference"] == "TRAFFIC_AWARE"
assert not kwargs["json"]["computeAlternativeRoutes"] and budget(tmp_path).snapshot()["monthUsed"] == 1
with pytest.raises(gr.GoogleRoutesFailed):
engine(Http(body=b'{"routes": [{"duration": "bad"}]}'), tmp_path).traffic(KEY, (0., 0.), {"latitude": 0., "longitude": .1})
@pytest.mark.parametrize("http, failure", [
(Http(403, b'{"error": {"message": "Routes API has not been used in project 1"}}'), "disabled"),
(Http(400, b'{"error": {"message": "API key not valid"}}'), "key"),
(Http(error=requests.ConnectionError()), "network"),
(Http(body=b'{"routes": []}'), "server"),
(Http(body=b'{"routes": [{"duration": "1s"}]}'), "server"),
])
def test_fetch_failures_say_why(tmp_path, http, failure):
with pytest.raises(gr.GoogleRoutesFailed) as raised:
engine(http, tmp_path).fetch(KEY, (0., 0.), {"latitude": 0., "longitude": .01})
assert raised.value.failure == failure
def test_fetch_stops_at_the_free_allowance(tmp_path):
spent = essentials(tmp_path)
assert spent.spend(spent.month_limit)
assert budget(tmp_path).spend(budget(tmp_path).month_limit)
http = Http()
with pytest.raises(gr.GoogleRoutesFailed) as raised:
engine(http, tmp_path).fetch(KEY, (0., 0.), {"latitude": 0., "longitude": .01})
assert raised.value.failure == "budget" and not http.calls
assert spent.snapshot()["monthLimit"] == 9900 and spent.snapshot()["dayLimit"] is None
assert budget(tmp_path).snapshot()["monthLimit"] == 4950 == budget(tmp_path).snapshot()["monthUsed"]
def test_key_test_reports_routes_plainly(tmp_path):
http = Http()
assert gr.test_routes(KEY, http, essentials(tmp_path))["ok"]
assert http.calls[0][1]["json"]["routingPreference"] == "TRAFFIC_UNAWARE"
failed = gr.test_routes(KEY, Http(error=requests.Timeout()), budget(tmp_path))
assert not failed["ok"] and "Mapbox" not in failed["message"]
assert "Routes API is off" in gr.test_routes(KEY, Http(403, b"SERVICE_DISABLED"), budget(tmp_path))["message"]
class RecordingExecutor(Executor):
def __init__(self):
super().__init__()
self.calls = []
def submit(self, *args):
self.calls.append(args)
return super().submit(*args)
def google_runtime(tmp_path, google_fetch):
owner = configured(tmp_path)
revision = owner.read()["revision"]
owner.configure({"routeProvider": "google", "googleKey": KEY}, revision, True)
mapbox = SimpleNamespace(calls=[])
def mapbox_fetch(*args):
mapbox.calls.append(args)
return "mapbox route"
mapbox.fetch = mapbox_fetch
executor = RecordingExecutor()
runtime = RouteRuntime(owner, engine=mapbox, executor=executor, google_engine=SimpleNamespace(fetch=google_fetch))
return owner, runtime, executor, mapbox
def test_google_provider_routes_with_google_and_falls_back_to_mapbox(tmp_path, monkeypatch):
monkeypatch.setattr(NavigationOwner, "_is_metric", lambda self: True)
def refuse(*args):
raise gr.GoogleRoutesFailed("budget")
owner, runtime, executor, mapbox = google_runtime(tmp_path, refuse)
runtime.update(10, (10, (0., 0.), 10., 90.), 1)
fetch, credentials, coordinates = executor.calls[0][:3]
assert credentials == ("pk.test", KEY) and coordinates == (0., 0.)
assert fetch(*executor.calls[0][1:]) == "mapbox route" and mapbox.calls[0][0] == "pk.test"
assert "used up" in owner.snapshot()["googleRoutes"]["failure"]
runtime.google_engine.fetch = lambda *args: "google route"
assert fetch(*executor.calls[0][1:]) == "google route"
assert owner.snapshot()["googleRoutes"]["failure"] is None
def test_google_route_guides_and_reaches_the_car_cluster(tmp_path, monkeypatch):
monkeypatch.setattr(NavigationOwner, "_is_metric", lambda self: True)
owner, runtime, executor, _ = google_runtime(tmp_path, None)
points = [(0.0, index * 1e-4) for index in range(101)]
route = gr.NavigationRoute(gr.mapbox_shape(dict(google_route(), polyline={"encodedPolyline": encode(points)})))
route.alternatives = [route]
runtime.update(10, (10, (0., 0.), 10., 90.), 1)
executor.jobs[0].set_result(route)
result = runtime.update(11, (11, (.002, 0.), 10., 90.), 1)
assert result["status"] == "guiding" and result["instruction"]["text"] == "Slight right onto Oak St"
assert result["nextManeuver"]["maneuverType"] == "off ramp"
assert len(owner.snapshot()["alternatives"]) == 1
from openpilot.starpilot.system.starport.nav_status import EVENT_OFF_RAMP, EVENT_SLIGHT_TURN, maneuver_event
assert maneuver_event(route.steps[0].maneuver_type, route.steps[0].modifier)[0] == EVENT_SLIGHT_TURN
assert maneuver_event(route.steps[1].maneuver_type, route.steps[1].modifier)[0] == EVENT_OFF_RAMP
for kind, side in gr.MANEUVERS.values():
maneuver_event(kind, side)
def test_mapbox_provider_never_asks_google(tmp_path, monkeypatch):
monkeypatch.setattr(NavigationOwner, "_is_metric", lambda self: True)
owner, runtime, executor, mapbox = google_runtime(tmp_path, None)
owner.configure({"routeProvider": "mapbox"}, owner.read()["revision"], True)
runtime.update(10, (10, (0., 0.), 10., 90.), 1)
assert executor.calls[0][0] == mapbox.fetch and executor.calls[0][1] == "pk.test"
def test_traffic_corrects_the_arrival_time_of_a_free_route(tmp_path, monkeypatch):
monkeypatch.setattr(NavigationOwner, "_is_metric", lambda self: True)
owner, runtime, executor, _ = google_runtime(tmp_path, None)
runtime.google_engine.traffic = lambda *args: None
route = gr.NavigationRoute({"distance": 5000., "duration": 500., "geometry": {"coordinates": [[0., 0.], [.045, 0.]]}, "legs": [{"steps": [
{"distance": 5000., "duration": 500., "maneuver": {"type": "depart"}}, {"distance": 0., "duration": 0., "maneuver": {"type": "arrive"}}]}]})
route.traffic_aware, route.alternatives = False, [route]
runtime.update(10, (10, (0., 0.), 1., 90.), 1)
assert executor.calls[0][4] is None, "a trip that starts slowly asks without the car's heading"
executor.jobs[0].set_result(route)
first = runtime.update(11, (11, (.0045, 0.), 10., 90.), 1)
assert first["instruction"]["remainingDurationSeconds"] == pytest.approx(450., rel=.01)
traffic = executor.calls[1]
assert traffic[0] == runtime.google_engine.traffic and traffic[1] == KEY and traffic[2] == (.0045, 0.) and traffic[4] == 90.
executor.jobs[1].set_result((900., 4500.))
corrected = runtime.update(12, (12, (.0045, 0.), 10., 90.), 1)
assert corrected["instruction"]["remainingDurationSeconds"] == pytest.approx(900., rel=.01)
assert len(executor.jobs) == 2, "the next traffic request waits its turn"
runtime.update(12 + 451_000_000_000, (12 + 451_000_000_000, (.0045, 0.), 10., 90.), 1)
executor.jobs[2].set_result((300., 20000.))
ignored = runtime.update(13 + 451_000_000_000, (13 + 451_000_000_000, (.0045, 0.), 10., 90.), 1)
assert ignored["instruction"]["remainingDurationSeconds"] == pytest.approx(900., rel=.01), "an answer for another path is ignored"
@@ -0,0 +1,136 @@
import json
import uuid
from contextlib import nullcontext
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from openpilot.starpilot.navigation.google_places import places_budget, suggestions_budget
from openpilot.starpilot.navigation.owner import NavigationOwner, ValidationError
KEY = 'AIzaSyFixtureKey_0123456789abcdef'
BELLAGIO = {'displayName': {'text': 'Bellagio'}, 'formattedAddress': '3600 S Las Vegas Blvd, Las Vegas, NV',
'location': {'latitude': 36.1126, 'longitude': -115.1767}}
CAESARS = {'displayName': {'text': 'Caesars Palace'}, 'formattedAddress': '3570 S Las Vegas Blvd', 'location': {'latitude': 36.1162, 'longitude': -115.1745}}
PREDICTION = {'placePrediction': {'placeId': 'ChIJbellagio', 'text': {'text': 'Bellagio, Las Vegas'},
'structuredFormat': {'mainText': {'text': 'Bellagio'}, 'secondaryText': {'text': 'Las Vegas Blvd, Las Vegas, NV'}}}}
MAPBOX = {'features': [{'properties': {'name': 'Mapbox Place', 'full_address': '1 Main St'}, 'geometry': {'coordinates': [-90., 40.]}}]}
class Google:
def __init__(self, status=200, places=(), suggestions=(), details=None):
self.status, self.places, self.suggestions, self.details, self.calls = status, list(places), list(suggestions), details, []
def _answer(self, value):
refusal = {'error': {'message': 'Places API (New) has not been used in project 1 before or it is disabled.'}}
body = json.dumps(value if self.status == 200 else refusal).encode()
return nullcontext(SimpleNamespace(status_code=self.status, iter_content=lambda size: [body]))
def post(self, url, **kwargs):
self.calls.append(('post', url, kwargs))
return self._answer({'places': self.places} if url.endswith(':searchText') else {'suggestions': self.suggestions})
def get(self, url, **kwargs):
self.calls.append(('get', url, kwargs))
return self._answer(self.details)
@pytest.fixture
def owner(tmp_path):
result = NavigationOwner(tmp_path / 'saved', runtime_source=lambda: None, transient_root=tmp_path / 'boot')
saved = result.configure({'enabled': True, 'token': 'pk.synthetic', 'googleKey': KEY}, '0', True)
result.configure({'routeProvider': 'google'}, saved['revision'], True)
with patch.object(result, '_search_context', return_value={'proximity': '-115.200000,36.200000'}):
yield result
def search(owner, query='bellagio', autocomplete=False, search_id=None, client=None):
return owner.search_places(query, 'caller', search_id or str(uuid.uuid4()), client or str(uuid.uuid4()), autocomplete=autocomplete)
def test_full_search_uses_google_text_search_when_google_gives_directions(owner):
owner.session = Google(places=[BELLAGIO, CAESARS])
with patch('openpilot.starpilot.navigation.owner.response_json') as mapbox:
results = search(owner)
mapbox.assert_not_called()
assert results.provider == 'google'
assert [(row['name'], row['address'], row['latitude']) for row in results] == [
('Bellagio', '3600 S Las Vegas Blvd, Las Vegas, NV', 36.1126), ('Caesars Palace', '3570 S Las Vegas Blvd', 36.1162)]
assert all('searchId' not in row and 'temporary' not in row for row in results), "plain select and favorite take these"
_, url, request = owner.session.calls[0]
assert url.endswith('places:searchText') and request['json']['pageSize'] == 8 and request['json']['textQuery'] == 'bellagio'
assert request['json']['locationBias']['circle']['center'] == {'latitude': 36.2, 'longitude': -115.2}
assert places_budget(owner.google_root).snapshot()['monthUsed'] == 1
saved = owner.favorite(results[0], owner.read()['revision'], True)
assert saved['favorites'][0]['name'] == 'Bellagio'
assert owner.select(results[1], saved['revision'], True)['destination']['name'] == 'Caesars Palace'
owner.session = Google()
empty = search(owner, 'nowhere')
assert empty == [] and empty.provider == 'google', "Google finding nothing is an answer, not a reason to ask Mapbox"
def test_full_search_falls_back_to_mapbox_when_google_refuses_or_runs_out(owner):
owner.session = Google(status=403)
with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'suggestions': []}), \
patch.object(owner, 'search', return_value=[{'id': 'x', 'name': 'Mapbox Place', 'latitude': 40., 'longitude': -90.}]) as geocode:
results = search(owner)
assert getattr(results, 'provider', 'mapbox') == 'mapbox' and results[0]['name'] == 'Mapbox Place'
geocode.assert_called_once_with('bellagio')
owner.session = Google(places=[BELLAGIO])
with patch('openpilot.starpilot.navigation.google_places.GoogleBudget.spend', return_value=False):
assert getattr(search(owner), 'provider', 'mapbox') == 'mapbox'
assert not owner.session.calls, "a used-up allowance never reaches Google"
def test_mapbox_directions_keep_mapbox_search(owner):
owner.configure({'routeProvider': 'mapbox'}, owner.read()['revision'], True)
owner.session = Google(places=[BELLAGIO])
with patch('openpilot.starpilot.navigation.owner.response_json', return_value=MAPBOX | {'suggestions': []}):
results = search(owner)
assert results[0]['name'] == 'Mapbox Place' and not owner.session.calls
def test_typing_uses_one_google_session_and_choosing_ends_it_with_location_only_details(owner):
owner.session = Google(suggestions=[PREDICTION], details={'location': {'latitude': 36.1126, 'longitude': -115.1767},
'formattedAddress': '3600 S Las Vegas Blvd, Las Vegas, NV 89109'})
search_id, client = str(uuid.uuid4()), str(uuid.uuid4())
with patch('openpilot.starpilot.navigation.owner.response_json') as mapbox:
first = search(owner, 'bel', True, search_id, client)
second = search(owner, 'bella', True, search_id, client)
mapbox.assert_not_called()
assert first.provider == 'google' and second[0] == {'id': 'ChIJbellagio', 'name': 'Bellagio', 'description': 'Las Vegas Blvd, Las Vegas, NV',
'searchId': search_id, 'temporary': True}
tokens = [call[2]['json']['sessionToken'] for call in owner.session.calls]
assert len(tokens) == 2 and tokens[0] == tokens[1] and 'X-Goog-FieldMask' not in owner.session.calls[0][2]['headers']
assert suggestions_budget(owner.google_root).snapshot()['monthUsed'] == 2
status = owner.select_place('ChIJbellagio', search_id, 'caller', owner.read()['revision'], True)
assert status['destination']['name'] == 'Bellagio' and status['destination']['address'] == '3600 S Las Vegas Blvd, Las Vegas, NV 89109'
method, url, request = owner.session.calls[-1]
assert (method, url) == ('get', 'https://places.googleapis.com/v1/places/ChIJbellagio')
assert request['params'] == {'sessionToken': tokens[0]} and request['headers']['X-Goog-FieldMask'] == 'location,formattedAddress'
with pytest.raises(ValidationError, match='cannot be saved'):
owner.favorite_place('ChIJbellagio', search_id, 'caller', status['revision'], True)
def test_typing_continues_on_mapbox_when_google_fails(owner):
owner.session = Google(status=403)
search_id, client = str(uuid.uuid4()), str(uuid.uuid4())
poi = {'mapbox_id': 'poi/b', 'name': 'Bellagio Mapbox', 'feature_type': 'poi'}
with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'suggestions': [poi]}) as mapbox:
first = search(owner, 'bel', True, search_id, client)
second = search(owner, 'bell', True, search_id, client)
assert first.provider == second.provider == 'mapbox' and second[0]['name'] == 'Bellagio Mapbox'
assert len(owner.session.calls) == 1, "after one refusal the session stays on Mapbox"
assert mapbox.call_args_list[0].args[2]['session_token'] == mapbox.call_args_list[1].args[2]['session_token']
owner.session = Google(suggestions=[PREDICTION])
with patch('openpilot.starpilot.navigation.google_places.GoogleBudget.spend', return_value=False), \
patch('openpilot.starpilot.navigation.owner.response_json', return_value={'suggestions': [poi]}):
assert search(owner, 'bel', True).provider == 'mapbox'
assert not owner.session.calls
def test_snapshot_reports_google_place_use_without_the_key(owner):
places = owner.snapshot()['googlePlaces']
assert places['usage']['monthLimit'] == 4950 and places['suggestions']['monthLimit'] == 9900
assert KEY not in json.dumps(owner.snapshot())
@@ -0,0 +1,31 @@
"""GUARD RAIL: pins the Google spending limit. AI agents must not edit these numbers.
The Galaxy setup guide tells users StarPilot blocks Google at 99% of the free usage so they
are not charged. If this test fails, restore the limit; do not change the expected values
without the repository owner's explicit instruction.
"""
from openpilot.starpilot.navigation import google_places as places
from openpilot.starpilot.navigation import google_routes as routes
from openpilot.starpilot.navigation import google_tiles as tiles
def test_stop_fraction_is_99_percent():
assert tiles.STOP_FRACTION == 0.99
def test_free_allowances_are_google_free_tiers():
assert (tiles.FREE_MONTH, tiles.FREE_DAY) == (100_000, 15_000)
assert (routes.FREE_ROUTES, routes.FREE_ESSENTIAL_ROUTES) == (5_000, 10_000)
assert (places.FREE_SEARCHES, places.FREE_SUGGESTIONS) == (5_000, 10_000)
def test_every_budget_stops_at_99_percent(tmp_path):
expected = {
"tiles": (tiles.GoogleBudget(tmp_path), 99_000, 14_850),
"routes": (routes.route_budget(tmp_path), 4_950, None),
"essentials": (routes.essentials_budget(tmp_path), 9_900, None),
"places": (places.places_budget(tmp_path), 4_950, None),
"suggestions": (places.suggestions_budget(tmp_path), 9_900, None),
}
for name, (budget, month, day) in expected.items():
assert (budget.month_limit, budget.day_limit) == (month, day), name
@@ -0,0 +1,273 @@
import json
import os
from contextlib import contextmanager
from types import SimpleNamespace
import pytest
import requests
from openpilot.starpilot.navigation import google_tiles as gt
from openpilot.starpilot.navigation.road_tiles import TileKey
KEY = "AIzaSyFixtureKey_0123456789abcdef"
PNG = b"\x89PNG\r\n\x1a\nfixture"
SESSION = json.dumps({"session": "tok", "expiry": "4102444800", "tileWidth": 256, "tileHeight": 256, "imageFormat": "png"}).encode()
WALL = 1_762_600_000.0 # 2025-11-08 in Pacific time
class Http:
"""Google's endpoints: answers by URL, records every call."""
def __init__(self, session=(200, SESSION), tile=(200, PNG, {"Cache-Control": "public, max-age=86400"}),
viewport=(200, b'{"copyright": "Map data \\u00a92026 Google"}')):
self.calls = []
self.session, self.tile, self.viewport = session, tile, viewport
@contextmanager
def post(self, url, **kwargs):
self.calls.append(("post", url, kwargs))
status, body = self.session
yield SimpleNamespace(status_code=status, headers={}, iter_content=lambda size: iter([body]))
@contextmanager
def get(self, url, **kwargs):
self.calls.append(("get", url, kwargs))
if url == gt.VIEWPORT_URL:
status, body = self.viewport
headers = {}
else:
status, body, headers = self.tile
yield SimpleNamespace(status_code=status, headers=headers, iter_content=lambda size: iter([body]))
def want(path, keys, now=WALL, position=(37.77, -122.42)):
gt.write_want(path, keys, *position, now=now)
def tiles(tmp_path, http, wall=WALL, clock=None):
clock = clock or [0.0]
return gt.GoogleTiles(tmp_path / "google", http=http, clock=lambda: clock[0], wall=lambda: wall, want=tmp_path / "want.json")
# ---------------------------------------------------------------- planning
def test_zoom_follows_scale_and_holds_through_junction_zoom():
city = gt.choose_zoom(37.77, 0.9)
highway = gt.choose_zoom(37.77, 3.4)
assert city == 17 and highway == 15
assert gt.choose_zoom(37.77, 0.8, highway) == city # far outside the kept range: switch
assert gt.choose_zoom(37.77, 1.4, city) == city # a junction zoom-out keeps the same tiles
assert gt.MIN_ZOOM <= gt.choose_zoom(0.0, 500.0) and gt.choose_zoom(0.0, 0.001) <= gt.MAX_ZOOM
def test_plan_is_nearest_first_and_bounded():
keys = gt.plan_tiles(37.77, -122.42, 600.0, 17)
x, y = gt.tiles_in_radius(37.77, -122.42, 0.0, 17)[0].x, gt.tiles_in_radius(37.77, -122.42, 0.0, 17)[0].y
assert keys[0] == TileKey(17, x, y)
assert 4 <= len(keys) <= gt.MAX_WANTED
assert len(gt.plan_tiles(37.77, -122.42, 50_000.0, 17)) == gt.MAX_WANTED
def test_want_file_round_trip_expires_and_rejects_bad_tiles(tmp_path):
path = tmp_path / "want.json"
keys = [TileKey(17, 21000, 50000), TileKey(16, 10500, 25000)]
want(path, keys)
assert gt.read_want(path, WALL + 1) == (keys, (37.77, -122.42))
assert gt.read_want(path, WALL + gt.WANT_MAX_AGE_S + 1) == ([], None)
assert gt.read_want(path, WALL - 1) == ([], None)
path.write_text(json.dumps({"at": WALL, "latitude": 1, "longitude": 2, "tiles": [[3, 0, 0], [17, -1, 0], [17, 1 << 17, 0], [17, 1, True]]}))
assert gt.read_want(path, WALL) == ([], (1.0, 2.0))
path.write_text("{bad")
assert gt.read_want(path, WALL) == ([], None)
# ---------------------------------------------------------------- cache and caps
@pytest.mark.parametrize("header,seconds", [
("public, max-age=120", 120), ("max-age=0", 0), ("no-store", gt.HANDOFF_S), ("", gt.HANDOFF_S),
("public, max-age=86400", 600), ("max-age=oops", gt.HANDOFF_S)])
def test_cache_lifetime_follows_cache_control_but_keeps_traffic_current(header, seconds):
assert gt.cache_lifetime({"Cache-Control": header}) == seconds
def test_store_serves_only_unexpired_tiles_and_trims(tmp_path):
store = gt.GoogleTileStore(tmp_path)
key, other = TileKey(17, 1, 2), TileKey(17, 3, 4)
assert store.write("d", key, PNG, 60, WALL) and store.write("d", other, PNG * 2, 600, WALL)
assert store.read("d", key, WALL + 59) == PNG
assert store.read("d", key, WALL + 61) is None and not store.fresh("other", key, WALL)
assert store.trim(len(PNG) * 2, now=WALL + 61) == len(PNG) * 2
assert not store.path("d", key).exists() and store.fresh("d", other, WALL + 61)
assert store.trim(1, now=WALL) == 0 and not store.path("d", other).exists()
def test_budget_stops_at_99_percent_of_day_and_month_and_resets_on_pacific_calendar(tmp_path):
clock = [WALL]
budget = gt.GoogleBudget(tmp_path, lambda: clock[0])
assert budget.day_limit is not None
assert budget.spend(budget.day_limit) and not budget.spend()
assert budget.snapshot()["dayUsed"] == budget.day_limit == 14_850
clock[0] += 24 * 3600
assert budget.spend()
(tmp_path / "usage.json").write_text(json.dumps({**json.loads((tmp_path / "usage.json").read_text()), "monthUsed": budget.month_limit}))
assert not budget.spend() and budget.snapshot()["monthLimit"] == 99_000
clock[0] += 31 * 24 * 3600
assert budget.spend() and budget.snapshot()["monthUsed"] == 1
def test_pacific_day_lags_utc():
midnight = 1_762_588_800.0 # 08:00 UTC Nov 8 is midnight Pacific
assert gt.pacific_day(midnight - 1) == "2025-11-07" and gt.pacific_day(midnight) == "2025-11-08"
@pytest.mark.parametrize("status,body,failure", [
(200, b"", None),
(403, b'{"error":{"message":"This API method requires billing to be enabled"}}', gt.FAILURE_BILLING),
(403, b'{"error":{"message":"Map Tiles API has not been used in project 1 before or it is disabled"}}', gt.FAILURE_DISABLED),
(400, b'{"error":{"message":"API key not valid. Please pass a valid API key."}}', gt.FAILURE_KEY),
(403, b'{"error":{"message":"Requests from this app are blocked."}}', gt.FAILURE_KEY),
(400, b'{"error":{"message":"Invalid style"}}', gt.FAILURE_SERVER),
(429, b"", gt.FAILURE_SERVER), (503, b"", gt.FAILURE_SERVER)])
def test_classify_names_what_to_fix(status, body, failure):
assert gt.classify(status, body) == failure
# ---------------------------------------------------------------- Test key
def test_key_test_uses_the_map_session_and_keeps_the_key_out_of_urls(tmp_path):
http = Http()
result = gt.test_key(KEY, http, gt.GoogleBudget(tmp_path))
assert result["ok"] is True
(_, url, post), (_, tile_url, get) = http.calls
assert post["json"] == gt.session_body() and post["json"]["layerTypes"] == ["layerTraffic"]
assert post["headers"] == {"X-Goog-Api-Key": KEY} and get["headers"] == {"X-Goog-Api-Key": KEY}
assert KEY not in url + tile_url + json.dumps(get["params"])
assert gt.GoogleBudget(tmp_path).snapshot()["monthUsed"] == 1
def test_key_test_reports_each_failure(tmp_path):
billing = Http(session=(403, b"billing must be enabled"))
assert gt.test_key(KEY, billing, gt.GoogleBudget(tmp_path))["failure"] == gt.FAILURE_BILLING
assert len(billing.calls) == 1
class Down(Http):
@contextmanager
def post(self, url, **kwargs):
raise requests.ConnectionError(url)
yield
assert gt.test_key(KEY, Down(), gt.GoogleBudget(tmp_path))["failure"] == gt.FAILURE_NETWORK
assert gt.test_key(KEY, Http(session=(200, b"{}")), gt.GoogleBudget(tmp_path))["failure"] == gt.FAILURE_SERVER
spent = gt.GoogleBudget(tmp_path)
assert spent.day_limit is not None
spent.spend(spent.day_limit)
assert gt.test_key(KEY, Http(), spent)["failure"] == gt.FAILURE_BUDGET
# ---------------------------------------------------------------- navtilesd's side
def test_fetches_only_wanted_tiles_nearest_first_and_reuses_the_session(tmp_path):
http = Http()
google = tiles(tmp_path, http)
first, second = TileKey(17, 21000, 50000), TileKey(17, 21001, 50000)
assert google.step(KEY, True) is None and http.calls == [] # nothing wanted
want(tmp_path / "want.json", [first, second])
assert google.step(KEY, True) == 0.0
assert google.step(KEY, True) == 0.0
assert google.step(KEY, True) is None # both fresh on disk
posts = [call for call in http.calls if call[0] == "post"]
fetched = [call[1] for call in http.calls if call[1].startswith("https://tile.googleapis.com/v1/2dtiles")]
assert len(posts) == 1 and fetched == [gt.TILE_URL.format(z=17, x=21000, y=50000), gt.TILE_URL.format(z=17, x=21001, y=50000)]
assert all(KEY not in call[1] and KEY not in json.dumps(call[2].get("params", {})) for call in http.calls)
assert google.store.read(gt.key_digest(KEY), first, WALL) == PNG
assert google.copyright == "Map data ©2026 Google"
assert os.stat(tmp_path / "google" / "session.json").st_mode & 0o777 == 0o600
again = tiles(tmp_path, Http())
want(tmp_path / "want.json", [TileKey(17, 9, 9)])
assert again.step(KEY, True) == 0.0 and not [call for call in again.http.calls if call[0] == "post"]
def test_refusals_back_off_and_a_bad_key_drops_its_session(tmp_path):
clock = [0.0]
http = Http(tile=(403, b"API key not valid", {}))
google = tiles(tmp_path, http, clock=clock)
want(tmp_path / "want.json", [TileKey(17, 1, 1)])
assert google.step(KEY, True) is None
assert google.failure == gt.FAILURE_KEY and google.blocked
assert not (tmp_path / "google" / "session.json").exists()
calls = len(http.calls)
assert google.step(KEY, True) is None and len(http.calls) == calls
clock[0] += gt.KEY_BACKOFF_S
assert not google.blocked
def test_offline_or_unchosen_does_nothing_and_budget_stops_fetching(tmp_path):
http = Http()
google = tiles(tmp_path, http)
want(tmp_path / "want.json", [TileKey(17, 1, 1)])
assert google.step("", True) is None and google.step(KEY, False) is None and http.calls == []
google.budget.spend(google.budget.day_limit)
assert google.step(KEY, True) is None and google.failure == gt.FAILURE_BUDGET
assert not [call for call in http.calls if "2dtiles" in call[1]]
def test_network_and_storage_failures_are_reported(tmp_path):
class Down(Http):
@contextmanager
def get(self, url, **kwargs):
if "2dtiles" in url:
raise requests.Timeout(url)
with super().get(url, **kwargs) as response:
yield response
google = tiles(tmp_path, Down())
want(tmp_path / "want.json", [TileKey(17, 1, 1)])
assert google.step(KEY, True) is None and google.failure == gt.FAILURE_NETWORK
stored = tiles(tmp_path / "other", Http())
stored.store.write = lambda *args: False
(tmp_path / "other").mkdir()
want(tmp_path / "other" / "want.json", [TileKey(17, 1, 1)])
assert stored.step(KEY, True) is None and stored.failure == gt.FAILURE_STORAGE
def test_status_carries_usage_failure_and_copyright(tmp_path):
google = tiles(tmp_path, Http())
google.failure, google.copyright = gt.FAILURE_BILLING, "Map data ©2026 Google"
google.write_status(force=True)
status = gt.read_status(tmp_path / "google")
assert status["failure"] == gt.FAILURE_BILLING and status["copyright"] == "Map data ©2026 Google"
assert status["usage"]["dayLimit"] == 14_850
assert gt.read_status(tmp_path / "missing") == {}
def test_a_new_key_clears_the_old_keys_refusal(tmp_path):
http = Http(tile=(403, b"API key not valid", {}))
google = tiles(tmp_path, http)
want(tmp_path / "want.json", [TileKey(17, 1, 1)])
assert google.step(KEY, True) is None and google.blocked
http.tile = (200, PNG, {})
assert google.step(KEY + "x", True) == 0.0 and google.failure is None
def test_a_clock_running_behind_never_zeroes_the_counts(tmp_path):
clock = [WALL]
budget = gt.GoogleBudget(tmp_path, lambda: clock[0])
assert budget.spend(500)
clock[0] -= 40 * 24 * 3600
assert budget.spend() and budget.snapshot()["monthUsed"] == 501 and budget.snapshot()["dayUsed"] == 501
clock[0] = WALL
assert budget.snapshot()["monthUsed"] == 501
def test_fetch_tile_caches_and_separates_light_and_dark_themes(tmp_path):
http = Http()
root = tmp_path / "google"
assert gt.fetch_tile(KEY, 12, 655, 1583, "light", http=http, root=root, wall=lambda: WALL) == PNG
assert gt.fetch_tile(KEY, 12, 655, 1583, "light", http=http, root=root, wall=lambda: WALL) == PNG
posts = [call for call in http.calls if call[0] == "post"]
assert len(posts) == 1 and "styles" not in posts[0][2]["json"]
assert len([call for call in http.calls if "2dtiles/12/655/1583" in call[1]]) == 1
assert gt.fetch_tile(KEY, 12, 655, 1583, "dark", http=http, root=root, wall=lambda: WALL) == PNG
posts = [call for call in http.calls if call[0] == "post"]
assert len(posts) == 2 and "styles" in posts[1][2]["json"]
assert gt.GoogleBudget(root, lambda: WALL).snapshot()["dayUsed"] == 2
@@ -177,3 +177,27 @@ def test_theme_tiles_have_separate_cache_entries(tmp_path):
with pytest.raises(ValidationError, match='Invalid map theme'):
owner.map_tile(2, 3, 1, 'custom/style')
assert len(provider.calls) == 2
def test_google_map_provider_serves_google_tiles_and_falls_back_to_mapbox(tmp_path, monkeypatch):
google_png = PNG + b'-google'
calls = []
def fake_fetch_tile(api_key, z, x, y, theme='dark', *, http=None, root=None):
calls.append((api_key, z, x, y, theme))
if theme == 'dark':
raise ValueError('quota reached')
return google_png
monkeypatch.setattr('openpilot.starpilot.navigation.google_tiles.fetch_tile', fake_fetch_tile)
provider = Provider()
owner = tile_owner(tmp_path, provider)
owner.read = lambda: {'token': 'pk.fixture', 'googleKey': 'AIzaSyTestKey123456', 'mapProvider': 'google'}
assert owner.map_tile(4, 2, 5, 'light', provider='google') == google_png
assert calls == [('AIzaSyTestKey123456', 4, 2, 5, 'light')]
assert not provider.calls
assert owner.map_tile(4, 2, 5, 'light') == PNG, 'offline maps and unflagged requests always use Mapbox even when Google is selected'
assert len(provider.calls) == 1
assert owner.map_tile(4, 2, 5, 'dark', provider='google') == PNG
assert len(provider.calls) == 2
assert '/mapbox/dark-v11/tiles/512/4/2/5.png' in provider.calls[1][0]
@@ -351,3 +351,23 @@ def test_main_subscribes_to_registered_gps_carriers(monkeypatch):
monkeypatch.setattr(navtilesd.os, "nice", lambda _: None)
with pytest.raises(SubscriptionsChecked):
navtilesd.main()
def test_environment_passes_the_google_key_only_while_google_is_chosen():
from types import SimpleNamespace
from unittest.mock import patch
from openpilot.starpilot.navigation import navtilesd
class SubMaster:
valid = {"deviceState": False, "starpilotNavigation": False}
logMonoTime = {"deviceState": 0}
def __getitem__(self, name):
return None
sm = SubMaster()
settings = {"token": "pk.test", "mapProvider": "google", "googleKey": "AIzaSyFixtureKey_0123456789abcdef"}
owner = SimpleNamespace(read=lambda: dict(settings))
with patch("openpilot.starpilot.navigation.runtime.location", return_value=None):
assert navtilesd._environment(sm, owner, True, 0).google_key == settings["googleKey"]
settings["mapProvider"] = "mapbox"
env = navtilesd._environment(sm, owner, True, 0)
assert env.google_key == "" and env.token == "pk.test"
@@ -26,6 +26,54 @@ def test_settings_private_atomic_and_revision_scoped(owner):
assert 'pk.test' not in json.dumps(owner.snapshot())
def test_share_intent_retry_after_cancel_or_restart_does_not_restart_route(owner):
owner.configure({'token': 'pk.test'}, '0', True)
first_revision = owner.read()['revision']
first = owner.share('geo:40.5,-89.5', first_revision, True, intent_id='phone-intent-1')
assert first['destination'] is not None
owner.clear(owner.read()['revision'], True)
cancelled_revision = owner.read()['revision']
restarted = NavigationOwner(owner.root, runtime_source=lambda: None, transient_root=owner.transient_root)
replay = restarted.share('geo:40.5,-89.5', first_revision, True, intent_id='phone-intent-1')
assert replay['destination'] is None and replay['revision'] == cancelled_revision
with pytest.raises(ValidationError, match='already used'):
restarted.share('geo:41,-89.5', cancelled_revision, True, intent_id='phone-intent-1')
with pytest.raises(PermissionError):
restarted.share('geo:40.5,-89.5', cancelled_revision, False, intent_id='phone-intent-1')
restarted.share('geo:40.5,-89.5', cancelled_revision, True, intent_id='phone-intent-2')
assert restarted.read()['destination'] is not None
def test_settings_saved_before_share_intents_still_load_and_save(owner):
owner.configure({'token': 'pk.test'}, '0', True)
saved = json.loads(owner.path.read_text())
owner.path.write_text(json.dumps({key: value for key, value in saved.items() if key not in ('routingRevision', 'shareIntents')}))
current = owner.read()
assert current['routingRevision'] == current['revision'] and current['shareIntents'] == []
owner.favorite(PLACE, current['revision'], True)
assert owner.read()['favorites'][0]['name'] == 'Home'
def test_share_intent_history_keeps_the_newest_64(owner):
owner.configure({'token': 'pk.test'}, '0', True)
for index in range(65):
owner.share('geo:40.5,-89.5', owner.read()['revision'], True, intent_id=f'intent-{index}')
intents = owner.read()['shareIntents']
assert len(intents) == 64 and intents[0]['id'] == 'intent-1' and intents[-1]['id'] == 'intent-64'
@pytest.mark.parametrize('ledger', [None, [{}], [{'id': '../bad', 'digest': '0' * 64}],
[{'id': 'test', 'digest': 'bad'}],
[{'id': 'test', 'digest': '0' * 64}] * 2,
[{'id': str(i), 'digest': '0' * 64} for i in range(65)]])
def test_corrupt_share_intent_history_is_rejected(owner, ledger):
owner.configure({'token': 'pk.test'}, '0', True)
saved = json.loads(owner.path.read_text())
owner.path.write_text(json.dumps({**saved, 'shareIntents': ledger}))
with pytest.raises(ValidationError):
owner.read()
def test_authority_rechecked_after_flush(owner):
calls = iter((True, False))
with pytest.raises(PermissionError):
@@ -96,3 +144,286 @@ def test_reads_reparse_only_after_a_write(owner):
assert owner.read()['favorites'] == [], "cached copies are independent of what callers change"
assert owner.select(PLACE, saved['revision'], True)['destination']['name'] == 'Home'
assert owner.read()['destination']['name'] == 'Home'
GOOGLE_KEY = 'AIzaSyFixtureKey_0123456789abcdef'
def test_google_map_style_is_saved_without_exposing_the_key(owner):
assert owner.snapshot()['mapProvider'] == 'mapbox' and owner.snapshot()['hasGoogleKey'] is False
selected = owner.select(PLACE, owner.configure({'enabled': True, 'token': 'pk.test'}, '0', True)['revision'], True)
saved = owner.configure({'mapProvider': 'google', 'googleKey': GOOGLE_KEY}, selected['revision'], True)
assert saved['mapProvider'] == 'google' and saved['hasGoogleKey'] is True
assert saved['destination']['name'] == 'Home'
assert GOOGLE_KEY not in json.dumps(owner.snapshot())
assert saved['googleMap']['usage']['monthLimit'] == 99_000 and saved['googleMap']['failure'] is None
assert owner.read()['googleKey'] == GOOGLE_KEY
@pytest.mark.parametrize('patch', [{'mapProvider': 'apple'}, {'googleKey': 'short'}, {'googleKey': 'AIza key with spaces 0123456789'},
{'googleKey': 7}, {'googleKey': 'A' * 129}])
def test_invalid_google_settings_rejected(owner, patch):
with pytest.raises(ValidationError):
owner.configure(patch, '0', True)
def test_older_settings_files_read_with_google_defaults(owner):
owner.path.write_text(json.dumps({'version': 1, 'revision': 'abc', 'enabled': True, 'token': 'pk.test', 'destination': None,
'favorites': []}))
settings = owner.read()
assert settings['mapProvider'] == 'mapbox' and settings['googleKey'] == ''
def test_google_key_test_checks_all_three_apis_whatever_the_route_provider(owner):
with (patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': True}) as tested,
patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': False}) as routed,
patch('openpilot.starpilot.navigation.google_places.test_places', return_value={'ok': True, 'message': 'works'}) as placed):
with pytest.raises(ValidationError):
owner.test_google_key()
both = {'ok': True, 'routes': {'ok': False}, 'places': {'ok': True, 'message': 'works'}}
assert owner.test_google_key(GOOGLE_KEY) == both
saved = owner.configure({'googleKey': GOOGLE_KEY}, '0', True)
assert owner.read()['routeProvider'] == 'mapbox' and owner.test_google_key() == both
owner.configure({'routeProvider': 'google'}, saved['revision'], True)
assert owner.test_google_key() == both
for mock in (tested, routed, placed):
assert [call.args[0] for call in mock.call_args_list] == [GOOGLE_KEY] * 3
class GoogleRefusal:
def __init__(self, status, text):
self.status, self.text = status, text
def _answer(self, *args, **kwargs):
from contextlib import nullcontext
from types import SimpleNamespace
return nullcontext(SimpleNamespace(status_code=self.status, iter_content=lambda size: [json.dumps({'error': {'message': self.text}}).encode()]))
post = get = _answer
@pytest.mark.parametrize('status, text, failure, words', [
(403, 'Places API (New) has not been used in project 1 before or it is disabled.', 'disabled',
"Enable it in Google Cloud and allow it in the key's API restrictions"),
(403, 'Requests to this API are blocked. API_KEY_SERVICE_BLOCKED', 'disabled', "allow it in the key's API restrictions"),
(400, 'API key not valid. Please pass a valid API key.', 'key', 'copied whole'),
(403, 'This API method requires billing to be enabled.', 'billing', 'Add a billing account')])
def test_google_key_test_names_each_api_and_what_to_fix(tmp_path, status, text, failure, words):
from openpilot.starpilot.navigation.google_places import places_budget, test_places
from openpilot.starpilot.navigation.google_routes import essentials_budget, test_routes
from openpilot.starpilot.navigation.google_tiles import GoogleBudget, test_key
http = GoogleRefusal(status, text)
results = {'Map Tiles API': test_key(GOOGLE_KEY, http, GoogleBudget(tmp_path)), 'Routes API': test_routes(GOOGLE_KEY, http, essentials_budget(tmp_path)),
'Places API (New)': test_places(GOOGLE_KEY, http, places_budget(tmp_path))}
for api, result in results.items():
assert result['ok'] is False and result['failure'] == failure and words in result['message']
assert failure == 'billing' or api in result['message']
def test_route_provider_is_saved_and_reports_google_route_use(owner):
snapshot = owner.snapshot()
assert snapshot['routeProvider'] == 'mapbox' and snapshot['googleRoutes']['usage']['monthLimit'] == 4950
assert snapshot['googleRoutes']['failure'] is None
saved = owner.configure({'routeProvider': 'google', 'googleKey': GOOGLE_KEY}, snapshot['revision'], True)
assert saved['routeProvider'] == 'google' and owner.read()['routeProvider'] == 'google'
from openpilot.starpilot.navigation.google_routes import write_route_status
write_route_status(owner.google_root, 'budget')
assert 'used up' in owner.snapshot()['googleRoutes']['failure']
with pytest.raises(ValidationError, match='route provider'):
owner.configure({'routeProvider': 'apple'}, saved['revision'], True)
class Redirects:
def __init__(self, hops):
self.hops, self.calls = dict(hops), []
def get(self, url, **kwargs):
from contextlib import nullcontext
from types import SimpleNamespace
self.calls.append((url, kwargs))
location = self.hops.get(url)
return nullcontext(SimpleNamespace(status_code=302 if location else 200, headers={'Location': location} if location else {}))
def test_shared_short_link_follows_google_redirects_only(owner):
owner.session = Redirects({'https://maps.app.goo.gl/abc123': 'https://www.google.com/maps/place/X/@36.1,-115.1,17z/data=!3d36.1!4d-115.1'})
resolved = owner.resolve_share('Bellagio\nhttps://maps.app.goo.gl/abc123')
assert resolved == 'Bellagio\nhttps://www.google.com/maps/place/X/@36.1,-115.1,17z/data=!3d36.1!4d-115.1'
assert owner.session.calls[0][1]['allow_redirects'] is False and owner.session.calls[0][1]['stream'] is True
owner.session = Redirects({'https://maps.app.goo.gl/abc123': 'https://evil.example/maps?q=1'})
assert owner.resolve_share('https://maps.app.goo.gl/abc123') == 'https://maps.app.goo.gl/abc123'
owner.session = Redirects({'https://maps.app.goo.gl/abc123': 'http://www.google.com/maps'})
assert owner.resolve_share('https://maps.app.goo.gl/abc123') == 'https://maps.app.goo.gl/abc123'
owner.session = Redirects({})
assert owner.resolve_share('Starbucks') == 'Starbucks' and not owner.session.calls
with pytest.raises(ValidationError):
owner.resolve_share(None)
def geocoded(places):
def respond(session, url, params):
assert url.endswith('/geocode/v6/forward')
hit = places.get(params['q'])
return {'features': [{'properties': {'name': hit[0], 'full_address': hit[1]}, 'geometry': {'coordinates': [hit[3], hit[2]]}}] if hit else []}
return patch('openpilot.starpilot.navigation.owner.response_json', side_effect=respond)
@pytest.fixture
def keyed(owner):
owner.configure({'token': 'pk.synthetic'}, owner.read()['revision'], True)
return owner
def test_share_with_coordinates_turns_navigation_on_and_routes(keyed):
with geocoded({}) as provider:
status = keyed.share('https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd/@36.2,-115.2,17z/data=!3d36.1126!4d-115.1767',
keyed.read()['revision'], True)
provider.assert_not_called()
assert status['enabled'] is True
assert status['shared'] == {'name': 'Bellagio', 'latitude': 36.1126, 'longitude': -115.1767}
assert status['destination']['address'] == '3600 S Las Vegas Blvd'
assert keyed.read()['destination']['latitude'] == 36.1126
geo = keyed.share('geo:40.5,-89.5?q=40.5,-89.5(Library)', status['revision'], True)
assert geo['shared'] == {'name': 'Library', 'latitude': 40.5, 'longitude': -89.5}
apple = keyed.share('https://maps.apple.com/?ll=41.25,-88.75&q=Park', geo['revision'], True)
assert apple['shared'] == {'name': 'Park', 'latitude': 41.25, 'longitude': -88.75}
apple = keyed.share('https://maps.apple.com/place?coordinate=41.5,-88.5&name=Apple+Park&place-id=I1', apple['revision'], True)
assert apple['shared'] == {'name': 'Apple Park', 'latitude': 41.5, 'longitude': -88.5}
plain = keyed.share('https://maps.google.com/?q=41.75,-88.25', apple['revision'], True)
assert plain['shared']['name'] == 'Shared destination'
def test_share_geocodes_place_links_without_coordinates(keyed):
places = {'3600 S Las Vegas Blvd, Las Vegas, NV 89109': ('3600 S Las Vegas Blvd', '3600 S Las Vegas Blvd, Las Vegas, NV 89109', 36.11, -115.17),
'Springfield Library, Springfield, IL 62701': ('Springfield', 'Springfield, Illinois', 39.8, -89.6),
'123 Main St, Springfield, IL 62701': ('123 Main St', '123 Main St, Springfield, IL 62701', 39.7, -89.7)}
with geocoded(places) as provider:
status = keyed.share('Bellagio\nhttps://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV+89109/data=!4m2!3m1!1s0x80c8:0x1',
keyed.read()['revision'], True)
assert [call.args[2]['q'] for call in provider.call_args_list] == ['3600 S Las Vegas Blvd, Las Vegas, NV 89109']
assert status['shared'] == {'name': 'Bellagio', 'latitude': 36.11, 'longitude': -115.17}
assert status['destination']['address'] == '3600 S Las Vegas Blvd, Las Vegas, NV 89109' and status['enabled']
provider.reset_mock()
status = keyed.share('https://maps.google.com/?q=Springfield+Library,+Springfield,+IL+62701&ftid=0x1:0x2', status['revision'], True)
assert [call.args[2]['q'] for call in provider.call_args_list] == ['Springfield Library, Springfield, IL 62701']
assert status['shared']['name'] == 'Springfield Library'
provider.reset_mock()
status = keyed.share('https://www.google.com/maps/place/123+Main+St,+Springfield,+IL+62701/data=!4m2', status['revision'], True)
assert [call.args[2]['q'] for call in provider.call_args_list] == ['123 Main St, Springfield, IL 62701']
assert status['shared']['name'] == '123 Main St'
provider.reset_mock()
with pytest.raises(ValidationError, match='No map location found for Nowhere') as error:
keyed.share('https://www.google.com/maps/place/Nowhere,+1+Lost+Rd,+Atlantis/data=!4m2', status['revision'], True)
assert error.value.query == 'Nowhere, 1 Lost Rd, Atlantis'
assert [call.args[2]['q'] for call in provider.call_args_list] == ['1 Lost Rd, Atlantis', 'Nowhere, 1 Lost Rd, Atlantis']
def test_share_without_a_map_place_asks_for_a_search(keyed):
revision = keyed.read()['revision']
with geocoded({}) as provider:
with pytest.raises(ValidationError, match='Open StarPilot to search for Starbucks') as error:
keyed.share('Starbucks', revision, True)
assert error.value.query == 'Starbucks'
with pytest.raises(ValidationError) as error:
keyed.share('geo:0,0?q=1600+Amphitheatre+Pkwy', revision, True)
assert error.value.query == '1600 Amphitheatre Pkwy'
provider.assert_not_called()
keyed.session = Redirects({})
with pytest.raises(ValidationError, match='could not be opened') as error:
keyed.share('https://maps.app.goo.gl/abc123', revision, True)
assert not hasattr(error.value, 'query')
assert keyed.read()['revision'] == revision and not keyed.read()['enabled']
def test_share_follows_short_links_and_checks_token_revision_and_authority(owner):
with pytest.raises(ValidationError, match='Mapbox access token'):
owner.share('geo:40.5,-89.5', owner.read()['revision'], True)
revision = owner.configure({'token': 'pk.synthetic'}, owner.read()['revision'], True)['revision']
with pytest.raises(ConflictError):
owner.share('geo:40.5,-89.5', '0', True)
with pytest.raises(PermissionError):
owner.share('geo:40.5,-89.5', revision, lambda: False)
with pytest.raises(ValidationError):
owner.share('', revision, True)
owner.session = Redirects({'https://maps.app.goo.gl/abc123': 'https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1'})
status = owner.share('X https://maps.app.goo.gl/abc123', revision, True)
assert status['shared'] == {'name': 'X', 'latitude': 36.1, 'longitude': -115.1} and status['enabled']
class GooglePlaces:
def __init__(self, status=200, places=()):
self.status, self.places, self.posts = status, list(places), []
def post(self, url, **kwargs):
from contextlib import nullcontext
from types import SimpleNamespace
self.posts.append((url, kwargs))
body = json.dumps({'places': self.places} if self.status == 200 else {'error': {'status': 'PERMISSION_DENIED',
'message': 'Places API (New) has not been used in project 1 before or it is disabled.'}}).encode()
return nullcontext(SimpleNamespace(status_code=self.status, iter_content=lambda size: [body]))
@pytest.fixture
def google(keyed):
keyed.configure({'routeProvider': 'google', 'googleKey': GOOGLE_KEY}, keyed.read()['revision'], True)
with patch.object(keyed, '_search_context', return_value={'proximity': '-115.200000,36.200000'}):
yield keyed
def test_share_with_google_routing_looks_the_place_up_with_google(google):
google.session = GooglePlaces(places=[{'displayName': {'text': 'Bellagio Hotel & Casino'}, 'formattedAddress': '3600 S Las Vegas Blvd, Las Vegas, NV 89109',
'location': {'latitude': 36.1126, 'longitude': -115.1767}}])
with geocoded({}) as mapbox:
status = google.share('https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV+89109/data=!4m2!3m1!1s0x1:0x2',
google.read()['revision'], True)
mapbox.assert_not_called()
assert status['shared'] == {'name': 'Bellagio Hotel & Casino', 'latitude': 36.1126, 'longitude': -115.1767} and status['enabled']
assert status['destination']['address'] == '3600 S Las Vegas Blvd, Las Vegas, NV 89109'
url, request = google.session.posts[0]
assert url == 'https://places.googleapis.com/v1/places:searchText'
assert request['json']['textQuery'] == 'Bellagio, 3600 S Las Vegas Blvd, Las Vegas, NV 89109' and request['json']['pageSize'] == 1
assert request['json']['locationBias']['circle']['center'] == {'latitude': 36.2, 'longitude': -115.2}
assert request['headers'] == {'X-Goog-Api-Key': GOOGLE_KEY, 'X-Goog-FieldMask': 'places.displayName,places.formattedAddress,places.location'}
google.session = GooglePlaces()
with pytest.raises(ValidationError, match='No map location found for Nowhere') as error:
google.share('https://maps.google.com/?q=Nowhere', status['revision'], True)
assert error.value.query == 'Nowhere'
google.session = GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}])
assert google.share('geo:40.5,-89.5', status['revision'], True)['shared']['latitude'] == 40.5
assert not google.session.posts
def test_share_falls_back_to_mapbox_when_google_lookup_is_refused(google):
google.session = GooglePlaces(status=403)
with geocoded({'Springfield Library': ('Springfield Library', 'Springfield, IL', 39.8, -89.6)}) as mapbox:
status = google.share('https://maps.google.com/?q=Springfield+Library', google.read()['revision'], True)
assert len(google.session.posts) == 1 and mapbox.call_args.args[2]['q'] == 'Springfield Library'
assert status['shared'] == {'name': 'Springfield Library', 'latitude': 39.8, 'longitude': -89.6}
from openpilot.starpilot.navigation.google_places import places_budget
budget = places_budget(google.google_root)
assert budget.snapshot()['monthUsed'] == 1 and budget.month_limit == 4950
with patch('openpilot.starpilot.navigation.google_places.GoogleBudget.spend', return_value=False):
google.session = GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}])
with geocoded({'Springfield Library': ('Springfield Library', 'Springfield, IL', 39.8, -89.6)}):
assert google.share('https://maps.google.com/?q=Springfield+Library', status['revision'], True)['shared']['latitude'] == 39.8
assert not google.session.posts
def test_share_with_google_only_setup_still_needs_the_mapbox_token_routing_uses(owner):
owner.configure({'routeProvider': 'google', 'googleKey': GOOGLE_KEY, 'mapProvider': 'google'}, owner.read()['revision'], True)
owner.session = GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}])
with pytest.raises(ValidationError, match='Add your Mapbox access token first') as error:
owner.share('https://maps.google.com/?q=Bellagio', owner.read()['revision'], True)
assert not hasattr(error.value, 'query') and not owner.session.posts
assert owner.snapshot()['status'] == 'disabled' and not owner.snapshot()['hasKey']
def test_google_place_lookup_test_reports_disabled_api():
from openpilot.starpilot.navigation.google_places import places_budget, test_places
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
assert test_places(GOOGLE_KEY, GooglePlaces(status=403), places_budget(root)) == {'ok': False, 'failure': 'disabled',
'message': "Places API (New) is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again."}
assert test_places(GOOGLE_KEY, GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}]), places_budget(root))['ok']
@@ -83,7 +83,9 @@ def test_route_interpolation_preserves_distance_and_advice(route):
assert abs(progress.instruction['distanceMeters'] - 556.) < .01
assert progress.instruction['text'] == 'Turn right on First Street'
assert not progress.off_route and not progress.arrived
assert route.progress((.005, 0.), 5., 270.).off_route
assert route.progress((.005, 0.), 10., 270.).off_route
assert not route.progress((.005, 0.), 5., 270.).off_route, "turning around on a ramp or in a lot is not off the route"
assert not route.progress((.005, .0005), 2., 90.).off_route and route.progress((.005, .0008), 2., 90.).off_route
assert route.progress((.01, 0.), 0.).arrived
assert project((0, 0), (0, 0), (0, .001))[0] == 0
assert distance((0, 0), (0, .001)) == pytest.approx(111.195, abs=.01)
@@ -127,11 +129,38 @@ def test_generation_discard_and_current_drive_control(tmp_path, route):
assert result['status'] == 'routing' and not result['controlValid']
@pytest.mark.parametrize('change', ['cancelReselect', 'sameDestination', 'avoidanceRoundTrip', 'providerRoundTrip', 'disableEnable'])
def test_route_intent_changes_between_polls_discard_delayed_response(tmp_path, route, change):
owner, executor = configured(tmp_path), Executor()
runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor)
position = (10_000_000_000, (.001, 0.), 5., 90.)
runtime.update(10_000_000_000, position, 1)
selected = owner.read()['destination']
if change == 'cancelReselect':
owner.clear(owner.read()['revision'], True)
owner.select(selected, owner.read()['revision'], True)
elif change == 'sameDestination':
owner.select(selected, owner.read()['revision'], True)
else:
key, first, second = {'avoidanceRoundTrip': ('avoidTolls', True, False),
'providerRoundTrip': ('routeProvider', 'google', 'mapbox'),
'disableEnable': ('enabled', False, True)}[change]
owner.configure({key: first}, owner.read()['revision'], True)
owner.configure({key: second}, owner.read()['revision'], True)
executor.jobs[0].set_result(route)
result = runtime.update(11_000_000_000, (11_000_000_000, *position[1:]), 1)
assert result['status'] == 'routing' and not result['controlValid']
assert runtime.route is None and len(executor.jobs) == 2
executor.jobs[1].set_result(route)
assert runtime.update(12_000_000_000, (12_000_000_000, *position[1:]), 1)['controlValid']
def test_arrival_ends_navigation_after_a_short_stop(tmp_path, route):
owner, executor = configured(tmp_path), Executor()
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 +175,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 +488,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
@@ -401,3 +528,67 @@ def test_lane_guidance_comes_from_the_banner_and_reaches_the_instruction():
{'components': [{'type': 'lane', 'active': True, 'directions': ['left']}] * 9}])
def test_missing_unusable_or_malformed_lane_data_is_ignored(sub):
assert lane_route(sub).progress((.005, 0.), 5., 90.).instruction['lanes'] == []
def test_route_line_keeps_corners_and_thins_straight_road():
from openpilot.starpilot.navigation.route_engine import PREVIEW_POINTS, simplify
east = [[i * 1e-5, 0.] for i in range(5000)]
north = [[east[-1][0], i * 1e-5] for i in range(1, 5000)]
route = NavigationRoute({'distance': 1100., 'duration': 100., 'geometry': {'coordinates': east + north}, 'legs': [{'steps': [
{'distance': 1100., 'duration': 100., 'maneuver': {'type': 'depart'}},
{'distance': 0., 'duration': 0., 'maneuver': {'type': 'arrive'}}]}]})
preview = route.preview()
assert {'longitude': east[-1][0], 'latitude': 0.} in preview and len(preview) == 3
assert route.preview() is preview
wiggle = [[i * 1e-5, (i % 2) * 1e-4] for i in range(4000)]
assert len(simplify(wiggle)) == PREVIEW_POINTS
def test_route_line_preserves_a_collinear_turnaround():
from openpilot.starpilot.navigation.route_engine import simplify
assert simplify([(0., 0.), (.01, 0.), (.005, 0.)]) == [0, 1, 2]
def garage_runtime(tmp_path, monkeypatch):
monkeypatch.setattr(NavigationOwner, '_is_metric', lambda self: True)
owner = NavigationOwner(tmp_path, runtime_source=lambda: None)
settings = owner.configure({'enabled': True, 'token': 'pk.test'}, '0', True)
owner.select({'name': 'Far', 'longitude': .05, 'latitude': 0.}, settings['revision'], True)
executor = Executor()
runtime = RouteRuntime(owner, engine=SimpleNamespace(fetch=None), executor=executor)
long_route = NavigationRoute({'distance': 5560., 'duration': 400., 'geometry': {'coordinates': [[0., 0.], [.05, 0.]]}, 'legs': [{'steps': [
{'distance': 5560., 'duration': 400., 'maneuver': {'type': 'depart'}}, {'distance': 0., 'duration': 0., 'maneuver': {'type': 'arrive'}}]}]})
runtime.update(1, (1, (0., 0.), 0., None), 1)
executor.jobs[0].set_result(long_route)
return runtime, executor
def drive(runtime, start_ns, seconds, coordinates, speed, bearing):
result = None
for tick in range(seconds + 1):
now = start_ns + tick * 1_000_000_000
result = runtime.update(now, (now, coordinates, speed, bearing), 1)
return result
def test_leaving_a_garage_before_reaching_the_route_does_not_reroute(tmp_path, monkeypatch):
runtime, executor = garage_runtime(tmp_path, monkeypatch)
assert drive(runtime, 2, 30, (.0005, .0015), 3., 200.)['status'] == 'guiding', "spiral ramp 170 m from the street"
assert len(executor.jobs) == 1
assert drive(runtime, 40_000_000_000, 5, (-.004, .002), 12., 270.)['status'] == 'routing', "really went the other way"
assert len(executor.jobs) == 2
def test_slow_off_route_waits_longer_once_joined(tmp_path, monkeypatch):
runtime, executor = garage_runtime(tmp_path, monkeypatch)
drive(runtime, 2, 2, (.01, 0.), 15., 90.)
assert drive(runtime, 10_000_000_000, 6, (.02, .001), 3., 0.)['status'] == 'guiding'
assert drive(runtime, 17_000_000_000, 2, (.02, .001), 3., 0.)['status'] == 'routing'
assert len(executor.jobs) == 2
def test_no_reroute_in_the_destination_garage(tmp_path, monkeypatch):
runtime, executor = garage_runtime(tmp_path, monkeypatch)
drive(runtime, 2, 2, (.03, 0.), 15., 90.)
assert drive(runtime, 10_000_000_000, 20, (.049, .0015), 3., 180.)['status'] in ('guiding', 'arrived')
assert len(executor.jobs) == 1
@@ -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)
@@ -0,0 +1,19 @@
from openpilot.starpilot.navigation.share import map_link_query, shared_coordinates
def test_waze_short_link_decodes_geohash():
found = shared_coordinates('https://waze.com/ul/h9q8yy4')
assert found is not None
assert (found['latitude'], found['longitude']) == (37.762756, -122.426147)
def test_waze_coordinate_links():
coordinates = shared_coordinates('https://waze.com/ul?ll=37.7749,-122.4194&navigate=yes')
assert coordinates is not None and coordinates['longitude'] == -122.4194
directions = shared_coordinates('https://waze.com/live-map/directions?to=ll.37.77%2C-122.41')
assert directions is not None and directions['latitude'] == 37.77
def test_waze_named_link_is_a_search():
assert shared_coordinates('https://waze.com/ul?q=Starbucks%20Main%20St&navigate=yes') is None
assert map_link_query('https://waze.com/ul?q=Starbucks%20Main%20St&navigate=yes') == 'Starbucks Main St'
@@ -4,7 +4,9 @@ import time
from openpilot.starpilot.navigation.owner import NavigationOwner
from openpilot.starpilot.system.starport.projection_layout import BOOKMARK_WIDGET, DISPLAY_WIDGETS, FAVORITE_WIDGETS, FAVORITE_SIZE, FAVORITE_ICON_SIZE
from openpilot.starpilot.ui.onroad_customization import widget_order
from openpilot.starpilot.ui.navigation_favorites_state import favorite_visible
from openpilot.starpilot.ui.navigation_favorites_state import MAP_END_SLOP, active_favorite, favorite_visible, map_end_rect, map_end_visible
MAP_END = 'map_end'
def destination_label(document):
@@ -25,6 +27,7 @@ class ProjectionFavorites:
self.document = None
self.error = ''
self.card_bounds = None
self.map_rect = lambda: None
self.bookmark = lambda: False
self._read_at = float('-inf')
self._press = None
@@ -35,28 +38,37 @@ class ProjectionFavorites:
return
self._read_at = now
try:
self.document = self.owner.read()
self.document = self.owner.read_routing()
except (OSError, ValueError):
self.document = None
if self._press is not None and self._press[0] != BOOKMARK_WIDGET:
self.cancel()
def action(self, key):
def action(self, key, state):
if key == BOOKMARK_WIDGET:
return ('bookmark',)
doc = self.document
if key == MAP_END:
return ('end', doc['revision'], doc['destination']) if doc is not None and self.bounds(key, state) is not None else None
if doc is None or key not in FAVORITE_WIDGETS:
return None
if doc['destination'] is not None:
if key != active_favorite(doc, state.customization['layouts']['large']):
return None
return ('end', doc['revision'], doc['destination'])
label = key.removeprefix('nav_')
place = next((row for row in doc['favorites'] if row.get('label') == label), None)
if place is None:
if place is None or not (doc['enabled'] and doc['token']):
return None
active = doc['destination'] is not None and doc['destination']['id'] == place['id']
if not active and not (doc['enabled'] and doc['token']):
return None
return ('end' if active else 'start', doc['revision'], place)
return ('start', doc['revision'], place)
def bounds(self, key, state):
if key == MAP_END:
placed = self.map_rect()
if placed is None or state.alert.size == 'full' or not map_end_visible(self.document, state.customization['layouts']['large']):
return None
x, y, size = map_end_rect(placed['x'], placed['y'], placed['width'], placed['height'])
return {'x': x - MAP_END_SLOP, 'y': y - MAP_END_SLOP, 'size': size + 2 * MAP_END_SLOP}
if state.alert.size != 'none':
return None
placements = state.customization['layouts']['large']
@@ -74,18 +86,25 @@ class ProjectionFavorites:
if placed is not None and placed['enabled']:
px, py = placed['x'], placed['y']
if key == 'nav_map':
drawn = self.map_rect()
if drawn is not None:
px, py = drawn['x'], drawn['y']
width, height = placed['width'], placed['height']
elif key == 'nav_card' and self.card_bounds is not None and (rect := self.card_bounds(state)) is not None:
px, py, width, height = rect.x, rect.y, rect.width, rect.height
else:
width = height = 0
if px <= x < px + width and py <= y < py + height:
return None
return MAP_END if key == 'nav_map' and self._in_map_end(x, y, state) else None
if key in DISPLAY_WIDGETS and (placed := self.bounds(key, state)) is not None:
width, height = (FAVORITE_ICON_SIZE, FAVORITE_ICON_SIZE) if placed.get('display') == 'icons' else FAVORITE_SIZE
if placed['x'] <= x < placed['x'] + width and placed['y'] <= y < placed['y'] + height:
return key
return None
return MAP_END if 'nav_map' not in order and self._in_map_end(x, y, state) else None
def _in_map_end(self, x, y, state):
placed = self.bounds(MAP_END, state)
return placed is not None and placed['x'] <= x < placed['x'] + placed['size'] and placed['y'] <= y < placed['y'] + placed['size']
def touch(self, kind, x, y, state, drive):
if kind == 'cancel' or not self.authorized():
@@ -95,7 +114,7 @@ class ProjectionFavorites:
self.cancel()
self.refresh(force=True)
key = self.hit(x, y, state)
if key is not None and (action := self.action(key)) is not None:
if key is not None and (action := self.action(key, state)) is not None:
self.error = ''
self._press = (key, x, y, action, drive)
return
@@ -115,7 +134,7 @@ class ProjectionFavorites:
# A changed destination or relabeled favorite must never turn a held tap
# into a different command. The owner's revision check covers concurrent writers.
self.refresh(force=True)
if self.action(key) != action:
if self.action(key, state) != action:
return
command, revision, place = action
def authorized():
@@ -77,7 +77,7 @@ def native_dependencies():
from openpilot.starpilot.ui.onroad import OnroadView
from openpilot.starpilot.ui.onroad_customization import CAMERA_WIDGETS, placement, widget_size
from openpilot.starpilot.ui.onroad_dm import DriverMonitorLayer
from openpilot.starpilot.ui.onroad_map import MapFeed, MapOverlay
from openpilot.starpilot.ui.onroad_map import MapFeed, live_overlay
from openpilot.starpilot.ui.onroad_state import AlertSize, OnroadAlert
from openpilot.starpilot.ui.pip_preferences import read_pip
from openpilot.starpilot.ui.pip_render import PiPRenderer
@@ -148,7 +148,7 @@ def native_dependencies():
pip_warning=PiPWarningSource, read_vasm=read_vasm_preferences, clock_pair_ns=clock_pair_ns,
car_schema=car_schema,
pip_rect=Rect, pip_widgets=CAMERA_WIDGETS, placement=placement, widget_size=widget_size,
alert=OnroadAlert, alert_size=AlertSize, map_overlay=MapOverlay, map_feed=MapFeed,
alert=OnroadAlert, alert_size=AlertSize, map_overlay=live_overlay, map_feed=MapFeed,
favorites=ProjectionFavorites, standby_logo=standby_logo, now_playing_feed=ProjectionNowPlayingFeed,
jetlink_feed=JetlinkStatusFeed)
@@ -240,6 +240,7 @@ class ProjectionOnroad:
self.favorites = native.favorites(lambda: native.ui_state.started)
self.favorites.bookmark = lambda: self.bookmark()
self.favorites.card_bounds = getattr(getattr(self.onroad, 'navigation', None), 'bounds', None)
self.favorites.map_rect = lambda: self._map_placement() if self.map is not None else None
self._resources.callback(self.favorites.close)
except BaseException:
self._resources.close()
@@ -381,6 +382,9 @@ class ProjectionOnroad:
if placed is not None and self.map is not None:
self.map.draw(self.native.rl.Rectangle(placed['x'], placed['y'], placed['width'], placed['height']),
placed['opacity'] / 100.0)
if state is not None and self.favorites is not None:
self.onroad.navigation_favorites.render_map_end(placed['x'], placed['y'], placed['width'], placed['height'],
state.customization['layouts']['large'])
def _pip_layer(self, rect, state, *, submit=None):
"""Shared camera crops, with Android Auto's own blind-spot trigger and placements."""
@@ -19,6 +19,7 @@ from openpilot.starpilot.system.starport.projection_layout import (
from openpilot.starpilot.system.starport.touch import InputConfig, TouchMapper, TouchReceiver, TouchSender
from openpilot.starpilot.system.starport.wire import field
from openpilot.starpilot.ui.onroad_customization import default_document
from openpilot.starpilot.ui.navigation_favorites_state import map_end_rect
VIEWPORT = (2880, 1080)
@@ -147,7 +148,7 @@ def test_home_work_start_hide_other_and_end_navigation(favorites, ordered, displ
tap(favorites, view, 'nav_home')
doc = favorites.owner.read()
assert doc['destination']['name'] == 'My home'
assert favorites.action('nav_home')[0] == 'end'
assert favorites.action('nav_home', view)[0] == 'end'
assert favorites.bounds('nav_work', view) is None
assert doc['recents'][0]['name'] == 'My home'
tap(favorites, view, 'nav_work')
@@ -159,7 +160,7 @@ def test_home_work_start_hide_other_and_end_navigation(favorites, ordered, displ
assert favorites.bounds('nav_home', view) is None
tap(favorites, view, 'nav_work')
assert favorites.owner.read()['destination'] is None
assert favorites.action('nav_work')[0] == 'start'
assert favorites.action('nav_work', view)[0] == 'start'
assert favorites.bounds('nav_home', view) is not None
@@ -201,6 +202,93 @@ def test_unconfigured_and_disabled_navigation_do_not_write(favorites):
assert favorites.owner.read()['destination'] is None
@pytest.mark.parametrize('temporary', [False, True])
@pytest.mark.parametrize('display', ['words', 'icons'])
def test_phone_sent_route_ends_from_first_favorite_slot(favorites, temporary, display):
view = state()
for key in FAVORITE_WIDGETS:
view.customization['layouts']['large'][key]['display'] = display
sent = destination({'name': 'Costco', 'latitude': 36.3, 'longitude': -115.3})
if temporary:
favorites.owner._change(lambda doc: doc.update(destination=None), 'initial', True, active_destination=sent)
assert favorites.owner.read()['destination'] is None
else:
favorites.owner.select(sent, 'initial', True)
favorites.refresh(force=True)
assert destination_label(favorites.document) == 'Costco'
assert favorites.action('nav_home', view)[0] == 'end'
assert favorites.bounds('nav_work', view) is None
tap(favorites, view, 'nav_home')
assert favorites.owner.read_routing()['destination'] is None
assert favorites.bounds('nav_work', view) is not None
def test_phone_sent_route_x_moves_to_work_and_needs_no_saved_home(favorites):
view = state()
favorites.owner.label_favorite(favorites.document['favorites'][0]['id'], None, 'initial', True)
favorites.refresh(force=True)
sent = destination({'name': 'Costco', 'latitude': 36.3, 'longitude': -115.3})
favorites.owner.select(sent, favorites.document['revision'], True)
favorites.refresh(force=True)
assert favorites.action('nav_home', view)[0] == 'end', 'Home has no saved place but still ends the route'
view.customization['layouts']['large']['nav_home']['enabled'] = False
assert favorites.action('nav_work', view)[0] == 'end'
tap(favorites, view, 'nav_work')
assert favorites.owner.read()['destination'] is None
def map_view(favorites, *, width=600, height=400, home=False, work=False):
view = state(ordered=True)
placements = view.customization['layouts']['large']
placements['nav_home']['enabled'], placements['nav_work']['enabled'] = home, work
placements['nav_map'].update(enabled=True, x=1500, y=300, width=width, height=height)
drawn = {'x': 1500, 'y': 300, 'width': width, 'height': height}
favorites.map_rect = lambda: drawn
return view
def map_end_point(view):
placed = view.customization['layouts']['large']['nav_map']
x, y, size = map_end_rect(placed['x'], placed['y'], placed['width'], placed['height'])
return x + size / 2, y + size / 2
@pytest.mark.parametrize('temporary', [False, True])
@pytest.mark.parametrize('size', [(600, 400), (260, 200)])
def test_map_end_button_ends_route_when_no_favorite_slot_is_on(favorites, temporary, size):
view = map_view(favorites, width=size[0], height=size[1])
x, y = map_end_point(view)
assert favorites.hit(x, y, view) is None, 'no button without a route'
sent = destination({'name': 'Costco', 'latitude': 36.3, 'longitude': -115.3})
if temporary:
favorites.owner._change(lambda doc: doc.update(destination=None), 'initial', True, active_destination=sent)
else:
favorites.owner.select(sent, 'initial', True)
favorites.refresh(force=True)
assert favorites.hit(x, y, view) == 'map_end'
assert favorites.hit(1500 + size[0] / 2, 300 + size[1] - 20, view) is None, 'the rest of the map is not a button'
favorites.touch('down', x, y, view, 1)
favorites.touch('up', x, y, view, 1)
assert favorites.owner.read_routing()['destination'] is None
assert favorites.hit(x, y, view) is None
def test_map_end_button_hides_when_a_favorite_slot_ends_the_route_or_map_is_gone(favorites):
view = map_view(favorites, work=True)
x, y = map_end_point(view)
favorites.owner.select(destination({'name': 'Costco', 'latitude': 36.3, 'longitude': -115.3}), 'initial', True)
favorites.refresh(force=True)
assert favorites.hit(x, y, view) is None
assert favorites.action('nav_work', view)[0] == 'end'
view.customization['layouts']['large']['nav_work']['enabled'] = False
assert favorites.hit(x, y, view) == 'map_end'
view.alert.size = 'full'
assert favorites.hit(x, y, view) is None
view.alert.size = 'none'
favorites.map_rect = lambda: None
assert favorites.action('map_end', view) is None
def test_overlap_uses_saved_order_and_removed_widget_cannot_intercept(favorites):
view = state(ordered=True)
placements = view.customization['layouts']['large']
@@ -218,6 +306,8 @@ def test_overlap_uses_saved_order_and_removed_widget_cannot_intercept(favorites)
placements['nav_home']['enabled'] = False
placements['nav_work']['enabled'] = True
tap(favorites, view, 'nav_work')
assert favorites.owner.read()['destination'] is None, 'with Home hidden, Work ends the Home route'
tap(favorites, view, 'nav_work')
assert favorites.owner.read()['destination']['name'] == 'My work'
@@ -6,15 +6,30 @@ FAVORITES = ('nav_home', 'nav_work')
def active_favorite(document, placements):
if not document or not document['destination']:
return None
for key in FAVORITES:
placed = placements.get(key)
if placed and placed['enabled'] and any(
row.get('label') == key.removeprefix('nav_') and row['id'] == document['destination']['id']
for row in document['favorites']):
enabled = [key for key in FAVORITES if (placed := placements.get(key)) and placed['enabled']]
for key in enabled:
if any(row.get('label') == key.removeprefix('nav_') and row['id'] == document['destination']['id']
for row in document['favorites']):
return key
return None
# Any other route, such as one sent from the phone, ends from the first favorite slot.
return enabled[0] if enabled else None
def favorite_visible(key, document, placements):
active = active_favorite(document, placements)
return active is None or key == active
MAP_END_SIZE = 60
MAP_END_SLOP = 14
def map_end_visible(document, placements):
"""The map's own end button, for a route no Home or Work slot can end."""
return bool(document and document['destination']) and active_favorite(document, placements) is None
def map_end_rect(map_x, map_y, map_width, map_height):
"""Top-left of the map; a fixed size so it stays easy to hit on a small map."""
inset = max(14.0, min(map_width, map_height) * 0.05)
return map_x + inset, map_y + inset, MAP_END_SIZE
+8 -4
View File
@@ -1,6 +1,8 @@
from dataclasses import dataclass
import math
ARRIVED_DISPLAY_M = 10.0 # this close to the final "arrive" maneuver, the card reads "Arrived"
@dataclass(frozen=True)
class NavigationDisplay:
@@ -31,17 +33,19 @@ def navigation_display(message, *, now_ns: int, drive_id: int) -> NavigationDisp
distances = (instruction.distanceMeters, instruction.remainingDistanceMeters, instruction.remainingDurationSeconds)
if not all(math.isfinite(value) and value >= 0 for value in distances):
return None
text = 'You have arrived' if message.status == 'arrived' else ' '.join(instruction.text.split())[:240]
arrived = message.status == 'arrived' or (
instruction.maneuverType == 'arrive' and instruction.distanceMeters <= ARRIVED_DISPLAY_M)
text = 'You have arrived' if arrived else ' '.join(instruction.text.split())[:240]
if not text:
return None
lanes = tuple((lane.active, tuple(lane.directions), lane.activeDirection) for lane in list(instruction.lanes)[:8])
then = message.nextManeuver
then_type = '' if message.status == 'arrived' else then.maneuverType
then_type = '' if arrived else then.maneuverType
then_distance = then.distanceMeters if then_type and math.isfinite(then.distanceMeters) else None
return NavigationDisplay((message.sessionId, drive_id), text, instruction.maneuverType,
instruction.maneuverModifier, *distances, message.status == 'arrived',
instruction.maneuverModifier, *distances, arrived,
then_type, then.maneuverModifier if then_type else '', then_distance,
() if message.status == 'arrived' else lanes)
() if arrived else lanes)
except (AttributeError, TypeError, ValueError, OverflowError):
return None
+222
View File
@@ -0,0 +1,222 @@
"""Google map tiles for the map widget: decoded on a worker thread, uploaded on the render thread."""
from __future__ import annotations
import io
import math
import threading
import time
from collections import OrderedDict
from collections.abc import Callable, Sequence
from pathlib import Path
from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.navigation.google_tiles import (
GoogleTileStore, choose_zoom, google_root, key_digest, plan_tiles, read_status, want_path, write_want,
)
from openpilot.starpilot.navigation.offline_roads import read_json
from openpilot.starpilot.navigation.road_tiles import TileKey
TEXTURE_CACHE = 16
TEXTURE_SPARE = 8 # textures kept past the wanted set, for a zoom step back
UPLOADS_PER_FRAME = 3
SETTINGS_EVERY_S = 5.0
STATUS_EVERY_S = 10.0
WANT_EVERY_S = 1.0
MISSING_RETRY_S = 1.0
ATTRIBUTION = "Google Maps"
def _settings_path() -> Path:
from openpilot.starpilot.storage import starpilot_storage_root
return starpilot_storage_root() / "navigation" / "settings.json"
def chosen_key(path: Path) -> str:
"""The Google key while Google is the chosen map style, else empty."""
value = read_json(path, 256 * 1024)
if not isinstance(value, dict) or value.get("mapProvider") != "google":
return ""
key = value.get("googleKey")
return key if isinstance(key, str) else ""
def decode_png(data: bytes | None) -> tuple[int, int, bytes] | None:
"""RGBA pixels of a tile, or None for a missing or broken one."""
if not data:
return None
from PIL import Image, UnidentifiedImageError
try:
with Image.open(io.BytesIO(data)) as image:
if image.format != "PNG" or not 0 < image.width <= 1024 or not 0 < image.height <= 1024:
return None
rgba = image.convert("RGBA")
return rgba.width, rgba.height, rgba.tobytes()
except (UnidentifiedImageError, OSError, ValueError):
return None
class GoogleRaster:
def __init__(self, root: Path | None = None, settings: Path | None = None, want: Path | None = None,
clock: Callable[[], float] = time.monotonic, wall: Callable[[], float] = time.time): # noqa: TID251
self.root = Path(root) if root is not None else google_root()
self.store = GoogleTileStore(self.root)
self.settings = settings or _settings_path()
self.want = want or want_path()
self.clock, self.wall = clock, wall
self._lock = threading.Condition()
self._digest: str | None = None
self._zoom: int | None = None
self._wanted: tuple[TileKey, ...] = ()
self._center: tuple[float, float] | None = None
self._decoded: dict[TileKey, tuple[int, int, bytes]] = {}
self._expires: dict[TileKey, float] = {}
self._missing: dict[TileKey, float] = {}
self._reset = False
self._textures: OrderedDict[TileKey, rl.Texture] = OrderedDict()
self.generation = 0
self.copyright = ""
self._stopped = False
self._thread = threading.Thread(target=self._run, name="google-tiles", daemon=True)
self._thread.start()
@property
def active(self) -> bool:
with self._lock:
return self._digest is not None
def plan(self, latitude: float, longitude: float, m_per_px: float, radius_m: float) -> tuple[TileKey, ...]:
"""The tiles a canvas around this point should draw; also what navtilesd is asked to fetch."""
with self._lock:
if self._digest is None:
self._wanted, self._center = (), None
return ()
self._zoom = choose_zoom(latitude, m_per_px, self._zoom)
self._wanted = tuple(plan_tiles(latitude, longitude, radius_m, self._zoom))
self._center = (latitude, longitude)
self._lock.notify()
return self._wanted
def upload(self, limit: int = UPLOADS_PER_FRAME) -> None:
"""Render thread: turn a few decoded tiles into textures; ``generation`` changes when there is something new to draw."""
with self._lock:
reset, self._reset = self._reset, False
ready = list(self._decoded.items())[:limit]
for key, _ in ready:
del self._decoded[key]
keep = max(TEXTURE_CACHE, len(self._wanted) + TEXTURE_SPARE)
changed = False
if reset and self._textures:
for texture in self._textures.values():
rl.unload_texture(texture)
self._textures.clear()
changed = True
for key, (width, height, pixels) in ready:
texture = rl.load_texture_from_image(rl.Image(None, width, height, 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8))
if not texture.id:
continue
rl.update_texture(texture, pixels)
rl.set_texture_filter(texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR)
rl.set_texture_wrap(texture, rl.TextureWrap.TEXTURE_WRAP_CLAMP)
old = self._textures.pop(key, None)
if old is not None:
rl.unload_texture(old)
self._textures[key] = texture
changed = True
evicted = []
while len(self._textures) > keep:
key, texture = self._textures.popitem(last=False)
rl.unload_texture(texture)
evicted.append(key)
if evicted:
with self._lock:
for key in evicted:
self._expires.pop(key, None) # read from disk again if it is wanted later
if changed:
self.generation += 1
def textures(self, keys: Sequence[TileKey]) -> dict[TileKey, rl.Texture]:
found = {}
for key in keys:
texture = self._textures.get(key)
if texture is not None:
self._textures.move_to_end(key)
found[key] = texture
return found
# ---- worker
def _run(self) -> None:
settings_at = status_at = want_at = -math.inf
while True:
with self._lock:
if self._stopped:
return
self._lock.wait(timeout=0.25)
if self._stopped:
return
now = self.clock()
if now - settings_at >= SETTINGS_EVERY_S:
settings_at = now
key = chosen_key(self.settings)
digest = key_digest(key) if key else None
with self._lock:
if digest != self._digest:
self._digest, self._reset = digest, True
self._decoded.clear()
self._expires.clear()
self._missing.clear()
self._wanted, self._center = (), None
with self._lock:
digest, wanted, center = self._digest, self._wanted, self._center
if digest is None:
continue
if now - status_at >= STATUS_EVERY_S:
status_at = now
text = read_status(self.root).get("copyright")
self.copyright = text if isinstance(text, str) else ""
if wanted and center is not None and now - want_at >= WANT_EVERY_S:
want_at = now
try:
write_want(self.want, wanted, *center, now=self.wall())
except OSError:
pass
self._load(digest, wanted)
def _load(self, digest: str, wanted: tuple[TileKey, ...]) -> None:
wall, now = self.wall(), self.clock()
with self._lock:
# An expired tile stays on screen until navtilesd's fresh copy replaces it.
for key in [key for key, expires in self._expires.items() if expires <= wall]:
del self._expires[key]
todo = [key for key in wanted if key not in self._expires and key not in self._decoded and
self._missing.get(key, -math.inf) <= now]
for key in todo[:8]:
image = decode_png(self.store.read(digest, key, wall))
if image is None:
with self._lock:
self._missing[key] = now + MISSING_RETRY_S
continue
try:
expires = self.store.path(digest, key).stat().st_mtime
except OSError:
expires = wall + 60.0
with self._lock:
if self._digest != digest:
return
self._missing.pop(key, None)
self._decoded[key] = image
self._expires[key] = expires
def close(self) -> None:
with self._lock:
self._stopped = True
self._lock.notify()
self._thread.join(timeout=1.0)
with self._lock:
self._decoded.clear()
if rl.is_window_ready():
for texture in self._textures.values():
rl.unload_texture(texture)
self._textures.clear()
+226 -31
View File
@@ -32,11 +32,12 @@ from openpilot.starpilot.gps.acquisition import GpsAcquisition, acquisition_prog
from openpilot.starpilot.gps.source import GPS_MAX_AGE_NS, PHONE_MAX_AGE_NS
from openpilot.starpilot.navigation.road_tiles import (
DATA_ZOOM, EXTENT, LINK, MAJOR, MINOR, MOTORWAY, STREET, RoadTile, TileFormatError, TileKey, decode_road_tile,
encode_road_tile, meters_per_tile, world_xy,
encode_road_tile, lat_lon, meters_per_tile, world_xy,
)
from openpilot.system.ui.lib.application import GL_VERSION
SUPERSAMPLE = 1.5 # canvas pixels per screen pixel: edges are smoothed when it is scaled down
RASTER_SUPERSAMPLE = 1.0 # Google's pictures gain nothing from it, and the canvas needs under half the memory
MAX_CANVAS = 2560
TILE_CACHE = 48
MISSING_RETRY_S = 3.0
@@ -48,10 +49,19 @@ DESTINATION_MAX_CHARS = 32
CAR_ANCHOR = 0.68 # the car sits below center so more road ahead is visible
ZOOM_SLOW_M_PER_PX = 0.9 # parking-lot and city detail
ZOOM_FAST_M_PER_PX = 3.4 # highway overview
ZOOM_ROUTE_M_PER_PX = 1.8 # on a route: one steady level at any speed, closer only for turns
# Route steps that do not change direction (a road renaming, "continue straight") do not zoom in.
NO_ZOOM_MANEUVERS = frozenset({'continue', 'new name', 'notification', 'depart', 'merge'}) # unknown types still zoom
NO_ZOOM_MODIFIERS = frozenset({'', 'none', 'straight'})
MIN_HEADING_SPEED = 1.5 # m/s; GPS heading is noise below this
ROTATE_MIN_SPEED = 3.0 # m/s; below this the map holds its rotation
HEADING_DEADBAND_DEG = 3.0 # heading changes smaller than this leave the map still
HEADING_SETTLE_DEG = 0.5 # ...and once it turns, it keeps turning until this close, not stopping at the deadband edge
HEADING_FILTER_RATE = 2.0 # 1/s: GPS and route headings are smoothed this fast before the map follows them
HEADING_RATE = 1.5 # 1/s: how quickly the map eases toward the heading
HEADING_LOOKAHEAD_S = 2.0 # on the route, the map faces the line this far ahead, not the segment under the car
HEADING_LOOKAHEAD_MIN_M, HEADING_LOOKAHEAD_MAX_M = 20.0, 80.0
GUIDANCE_SUPERSAMPLE = 2 # the route line and puck are drawn at this scale and filtered down, so edges are smooth
MAX_TURN_DEG_S = 45.0 # the map never spins faster than this
JUNCTION_LOOKAHEAD_S = 14.0 # zoom in on the next maneuver this far ahead
JUNCTION_MIN_M, JUNCTION_MAX_M = 80.0, 300.0
@@ -61,6 +71,11 @@ OVERVIEW_MIN_MANEUVER_M = 50.0 # ...unless a maneuver is about to happen
NAME_HOLD_S = 1.5 # a new road name must hold this long to replace the old one
ROAD_NAME_MAX_AGE_S = 3.0
GUIDANCE_SLACK_PX = 4.0 # screen pixels of driven route left under the puck before guidance is trimmed again
RASTER_REDRAW_S = 0.25 # newly arrived Google tiles redraw the canvas at most this often
SNAP_M = 22.0 # the car is drawn on the route line when it is this close to it
SNAP_HEADING_DEG = 45.0 # ...and, while moving, heading along it
SNAP_AHEAD = 400 # route points searched past the last snapped one
SNAP_RATE = 4.0 # 1/s: how quickly the car eases onto and off the line
@dataclass(frozen=True)
@@ -101,9 +116,9 @@ def zoom_for_speed(speed_mps: float) -> float:
return ZOOM_SLOW_M_PER_PX + (ZOOM_FAST_M_PER_PX - ZOOM_SLOW_M_PER_PX) * t
def zoom_target(speed_mps: float, maneuver_m: float | None = None, stopped_s: float = 0.0) -> float:
"""Meters per screen pixel: speed-based, closer ahead of a maneuver, wider after sitting still."""
base = zoom_for_speed(speed_mps)
def zoom_target(speed_mps: float, maneuver_m: float | None = None, stopped_s: float = 0.0, guided: bool = False) -> float:
"""Meters per screen pixel: follows speed off-route, holds steady on a route and zooms in for the next turn."""
base = ZOOM_ROUTE_M_PER_PX if guided else zoom_for_speed(speed_mps)
near = maneuver_m is not None and maneuver_m <= OVERVIEW_MIN_MANEUVER_M
if stopped_s >= OVERVIEW_AFTER_S and not near:
return ZOOM_FAST_M_PER_PX
@@ -179,6 +194,8 @@ class CanvasRequest:
route: np.ndarray | None # (N, 2) world points ahead of the car
route_done: np.ndarray | None # (N, 2) world points already driven
tiles: tuple[TileKey, ...]
raster: tuple[TileKey, ...] = () # Google tiles drawn over the road lines
supersample: float = SUPERSAMPLE # canvas pixels per screen pixel
@dataclass
@@ -192,12 +209,12 @@ class CanvasGeometry:
def build_canvas(request: CanvasRequest, tiles: dict[TileKey, RoadTile], latitude: float) -> CanvasGeometry:
"""Screen-space strips for a north-up canvas. Pure numpy; runs off the render thread."""
side = request.side
px_per_m = SUPERSAMPLE / request.m_per_px
px_per_m = request.supersample / request.m_per_px
px_per_unit = meters_per_tile(latitude) * px_per_m # canvas pixels per world tile unit
cx, cy = request.center
bounds = (-8.0, -8.0, side + 8.0, side + 8.0)
ratio = math.sqrt(REFERENCE_M_PER_PX / request.m_per_px)
width_scale = SUPERSAMPLE * min(1.35, max(0.7, ratio))
width_scale = request.supersample * min(1.35, max(0.7, ratio))
geometry = CanvasGeometry(request)
per_class: dict[int, list[tuple[np.ndarray, np.ndarray]]] = {}
for key in request.tiles:
@@ -240,9 +257,9 @@ def route_guidance(route, request: CanvasRequest, latitude: float):
"""Build only the remaining route; the road canvas never bakes in a driven tail."""
if route is None or len(route) < 2:
return []
scale = meters_per_tile(latitude) * SUPERSAMPLE / request.m_per_px
scale = meters_per_tile(latitude) * request.supersample / request.m_per_px
points = ((route - request.center) * scale + request.side / 2).astype(np.float32)
width_scale = SUPERSAMPLE * min(1.35, max(0.7, math.sqrt(REFERENCE_M_PER_PX / request.m_per_px)))
width_scale = request.supersample * min(1.35, max(0.7, math.sqrt(REFERENCE_M_PER_PX / request.m_per_px)))
bounds = (-8.0, -8.0, request.side + 8.0, request.side + 8.0)
# Every frame draws these strips: keep only the stretches that can reach the canvas, widest line included.
reach = 8.0 + 17.0 * width_scale / 2
@@ -273,6 +290,60 @@ def visible_runs(points: np.ndarray, bounds: tuple[float, float, float, float])
return np.concatenate(runs), np.concatenate(([0], np.cumsum([len(run) for run in runs]))).astype(np.int32)
def snap_to_route(route: np.ndarray, position: tuple[float, float], bearing: float | None, max_offset: float,
start: int | None = None) -> tuple[tuple[float, float], int, float] | None:
"""(point, segment, bearing) of the nearest route point ahead of ``start`` within ``max_offset``, or None."""
if route is None or len(route) < 2:
return None
first = 0 if start is None else max(0, start - 1)
last = len(route) - 1 if start is None else min(len(route) - 1, start + SNAP_AHEAD)
a, b = route[first:last], route[first + 1:last + 1]
if not len(a):
return None
ab = b - a
lengths = np.einsum('ij,ij->i', ab, ab)
p = np.asarray(position, np.float64)
t = np.clip(np.einsum('ij,ij->i', p - a, ab) / np.maximum(lengths, 1e-18), 0.0, 1.0)
nearest = a + ab * t[:, None]
offsets = np.hypot(*(nearest - p).T)
headings = np.degrees(np.arctan2(ab[:, 0], -ab[:, 1])) % 360.0
usable = (offsets <= max_offset) & (lengths > 0)
if bearing is not None:
usable &= np.abs((headings - bearing + 180.0) % 360.0 - 180.0) <= SNAP_HEADING_DEG
if not usable.any():
return None
index = int(np.argmin(np.where(usable, offsets, np.inf)))
return (float(nearest[index, 0]), float(nearest[index, 1])), first + index, float(headings[index])
def route_lengths(route: np.ndarray) -> np.ndarray:
"""Distance along the route to each point, in world units."""
return np.concatenate(([0.0], np.cumsum(np.hypot(*np.diff(route, axis=0).T))))
def lookahead_heading(route: np.ndarray, lengths: np.ndarray, segment: int, point: tuple[float, float],
ahead: float) -> float | None:
"""Bearing from ``point`` (on ``segment``) to the spot ``ahead`` world units farther along the route."""
segment = min(max(segment, 0), len(route) - 2)
a = route[segment]
along = float(lengths[segment]) + math.hypot(point[0] - a[0], point[1] - a[1]) + ahead
if along >= lengths[-1]:
target = route[-1]
else:
j = min(len(route) - 2, max(segment, int(np.searchsorted(lengths, along, side='right')) - 1))
span = float(lengths[j + 1] - lengths[j])
target = route[j] + (route[j + 1] - route[j]) * (0.0 if span <= 0 else min(1.0, (along - lengths[j]) / span))
dx, dy = float(target[0] - point[0]), float(target[1] - point[1])
if math.hypot(dx, dy) < ahead * 0.25:
return None # at the end of the route: too short to trust
return math.degrees(math.atan2(dx, -dy)) % 360.0
def angle_delta(target: float, current: float) -> float:
"""Signed shortest rotation from ``current`` to ``target``, in degrees."""
return (target - current + 540.0) % 360.0 - 180.0
def split_route(route: np.ndarray | None, position: tuple[float, float]) -> tuple[np.ndarray | None, np.ndarray | None]:
"""(driven, ahead) world polylines, split at the point on the route nearest the car."""
if route is None or len(route) < 2:
@@ -306,7 +377,7 @@ class MapInput:
gps_wait_seconds: float = 0.0
destination: str = '' # where navigation is going: "Home", "Work" or the place name
source: str = '' # where the fix comes from: comma, car or phone
maneuver_distance_m: float | None = None # meters to the next maneuver while guiding
maneuver_distance_m: float | None = None # meters to the next turn while guiding (None for straight-on steps)
road_name: str = '' # the road the car is on, from the map data
@@ -433,8 +504,9 @@ class MapOverlay:
"""Owns two canvases (front/back), a widget texture and the mask shader."""
def __init__(self, root: Path | None = None, *, reader: TileReader | SampleTileReader | None = None, fonts=None,
clock: Callable[[], float] = time.monotonic):
clock: Callable[[], float] = time.monotonic, raster=None):
self.reader = reader or TileReader(root, clock)
self.raster = raster
self.fonts = fonts
self.clock = clock
self._lock = threading.Lock()
@@ -453,8 +525,13 @@ class MapOverlay:
self._uniform_values = (rl.Vector2(), np.zeros(1, dtype=np.float32), np.zeros(1, dtype=np.float32), np.zeros(1, dtype=np.float32))
self._pending_at = -math.inf
self.has_roads = False
self._geometry: CanvasGeometry | None = None
self._raster_drawn = 0
self._raster_generation = 0
self._raster_redrawn = -math.inf
self._route_key: tuple | None = None
self._route_world: np.ndarray | None = None
self._route_lengths: np.ndarray | None = None
self._route_last_shown: float | None = None # clock time the route was last available this navigation session
self._starting_since: float | None = None # clock time "Starting navigation" went up
self._generation_built = -1
@@ -462,13 +539,18 @@ class MapOverlay:
self._world: tuple[float, float] | None = None
self._latitude = 0.0
self._bearing = 0.0
self._heading_target = 0.0 # smoothed GPS or route heading the map rotates toward
self._turning = False
self._has_heading = False
self._stopped_since: float | None = None
self._name = ''
self._name_candidate = ''
self._name_since = 0.0
self._name_layout: tuple | None = None
self._attribution_layout: tuple | None = None
self._m_per_px = ZOOM_SLOW_M_PER_PX
self._snap_index: int | None = None
self._snap_weight = 0.0
self._last_prepare: float | None = None
self.status = "waiting"
self._input = MapInput(None)
@@ -486,16 +568,43 @@ class MapOverlay:
return
target_world = world_xy(fix.latitude, fix.longitude)
age = min(PHONE_DEAD_RECKON_S if data.source == "phone" else DEAD_RECKON_S, max(0.0, now - fix.monotonic))
if fix.bearing is not None and fix.speed > MIN_HEADING_SPEED:
moving = fix.bearing is not None and fix.speed > MIN_HEADING_SPEED
if moving:
units = fix.speed * age / meters_per_tile(fix.latitude)
heading = math.radians(fix.bearing)
target_world = (target_world[0] + math.sin(heading) * units, target_world[1] - math.cos(heading) * units)
delta = (fix.bearing - self._bearing + 540.0) % 360.0 - 180.0
snap = None
if data.navigation_active and self._route_world is not None:
snap = snap_to_route(self._route_world, target_world, fix.bearing if moving else None,
SNAP_M / meters_per_tile(fix.latitude), self._snap_index)
self._snap_index = snap[1] if snap is not None else None
self._snap_weight += ((1.0 if snap is not None else 0.0) - self._snap_weight) * min(1.0, dt * SNAP_RATE)
if snap is not None:
w = self._snap_weight
target_world = (target_world[0] + (snap[0][0] - target_world[0]) * w, target_world[1] + (snap[0][1] - target_world[1]) * w)
if moving:
assert fix.bearing is not None
road_bearing = fix.bearing
if snap is not None:
assert self._route_world is not None and self._route_lengths is not None
ahead_m = min(HEADING_LOOKAHEAD_MAX_M, max(HEADING_LOOKAHEAD_MIN_M, fix.speed * HEADING_LOOKAHEAD_S))
ahead = lookahead_heading(self._route_world, self._route_lengths, snap[1], snap[0], ahead_m / meters_per_tile(fix.latitude))
road_bearing = snap[2] if ahead is None else ahead
if not self._has_heading:
self._bearing, self._has_heading = fix.bearing % 360.0, True
elif fix.speed > ROTATE_MIN_SPEED and abs(delta) > HEADING_DEADBAND_DEG:
limit = MAX_TURN_DEG_S * dt
self._bearing = (self._bearing + max(-limit, min(limit, delta * min(1.0, dt * HEADING_RATE)))) % 360.0
self._bearing = self._heading_target = road_bearing % 360.0
self._has_heading, self._turning = True, False
else:
# Smooth the heading, then rotate with hysteresis past the deadband.
self._heading_target = (self._heading_target + angle_delta(road_bearing, self._heading_target) *
min(1.0, dt * HEADING_FILTER_RATE)) % 360.0
delta = angle_delta(self._heading_target, self._bearing)
if fix.speed <= ROTATE_MIN_SPEED or abs(delta) < HEADING_SETTLE_DEG:
self._turning = False
elif abs(delta) > HEADING_DEADBAND_DEG:
self._turning = True
if self._turning:
limit = MAX_TURN_DEG_S * dt
self._bearing = (self._bearing + max(-limit, min(limit, delta * min(1.0, dt * HEADING_RATE)))) % 360.0
if self._world is None or math.hypot(target_world[0] - self._world[0], target_world[1] - self._world[1]) > 0.5:
self._world = target_world # first fix or a jump: no slow glide across town
else:
@@ -510,7 +619,8 @@ class MapOverlay:
self._stopped_since = now
stopped_s = 0.0 if self._stopped_since is None else now - self._stopped_since
maneuver = data.maneuver_distance_m if data.navigation_active else None
target_zoom = zoom_target(fix.speed, maneuver, stopped_s) if math.isfinite(fix.speed) else self._m_per_px
guided = data.navigation_active and self._route_world is not None
target_zoom = zoom_target(fix.speed, maneuver, stopped_s, guided) if math.isfinite(fix.speed) else self._m_per_px
self._m_per_px += (target_zoom - self._m_per_px) * min(1.0, dt * 0.8)
def _track_name(self, name: str, now: float) -> None:
@@ -525,7 +635,9 @@ class MapOverlay:
return # MapFeed hands back the same tuple until the route changes
if route != self._route_key:
self._guidance_key = None
self._snap_index = None
self._route_world = np.array([world_xy(lat, lon) for lat, lon in route], np.float64) if len(route) >= 2 else None
self._route_lengths = route_lengths(self._route_world) if self._route_world is not None else None
self._route_key = route
def _track_route(self, data: MapInput, now: float) -> None:
@@ -559,8 +671,11 @@ class MapOverlay:
"""Screen pixels from the car to the widget's farthest corner, at any rotation."""
return math.hypot(width / 2, height * max(CAR_ANCHOR, 1 - CAR_ANCHOR))
def _supersample(self) -> float:
return RASTER_SUPERSAMPLE if self.raster is not None and self.raster.active else SUPERSAMPLE
def _canvas_side(self, width: int, height: int) -> int:
return int(min(MAX_CANVAS, math.ceil(self._reach(width, height) * 2 * 1.6 * SUPERSAMPLE / 64) * 64))
return int(min(MAX_CANVAS, math.ceil(self._reach(width, height) * 2 * 1.6 * self._supersample() / 64) * 64))
def _needs_canvas(self, side: int) -> bool:
request = self._canvas_request
@@ -568,15 +683,17 @@ class MapOverlay:
return True
assert self._world is not None
assert self._widget_size is not None
px_per_unit = meters_per_tile(self._latitude) * SUPERSAMPLE / request.m_per_px
px_per_unit = meters_per_tile(self._latitude) * request.supersample / request.m_per_px
drift = math.hypot(self._world[0] - request.center[0], self._world[1] - request.center[1]) * px_per_unit
reach = self._reach(*self._widget_size) * SUPERSAMPLE * self._m_per_px / request.m_per_px
reach = self._reach(*self._widget_size) * request.supersample * self._m_per_px / request.m_per_px
ratio = request.m_per_px / self._m_per_px
return drift > (side / 2 - reach) * 0.5 or not 0.82 < ratio < 1.22 or self.reader.generation != self._generation_built
replan = (self.raster is not None and not request.raster and self.raster.active) or request.supersample != self._supersample()
return drift > (side / 2 - reach) * 0.5 or not 0.82 < ratio < 1.22 or self.reader.generation != self._generation_built or replan
def _request(self, side: int) -> CanvasRequest:
assert self._world is not None
reach_m = side / SUPERSAMPLE * self._m_per_px * 0.75
supersample = self._supersample()
reach_m = side / supersample * self._m_per_px * 0.75
reach = reach_m / meters_per_tile(self._latitude)
x, y = self._world
tiles = tuple(TileKey(DATA_ZOOM, tx % (1 << DATA_ZOOM), ty)
@@ -584,7 +701,16 @@ class MapOverlay:
for tx in range(int(math.floor(x - reach)), int(math.floor(x + reach)) + 1)
if 0 <= ty < 1 << DATA_ZOOM)
done, ahead = split_route(self._route_world, self._world) if self._route_world is not None else (None, None)
return CanvasRequest(self._world, self._m_per_px, side, ahead, done, tiles)
return CanvasRequest(self._world, self._m_per_px, side, ahead, done, tiles, self._raster_plan(side, supersample), supersample)
def _raster_plan(self, side: int, supersample: float = SUPERSAMPLE) -> tuple[TileKey, ...]:
"""Google tiles out to the widget's farthest corner plus the drift and zoom a canvas allows before it is rebuilt."""
if self.raster is None or self._world is None or self._widget_size is None:
return ()
reach = self._reach(*self._widget_size)
drift = max(0.0, side / supersample / 2 - reach) * 0.5
latitude, longitude = lat_lon(*self._world)
return self.raster.plan(latitude, longitude, self._m_per_px, (reach + drift) * self._m_per_px * 1.22)
def _schedule(self, request: CanvasRequest) -> None:
self._pending = request
@@ -610,7 +736,7 @@ class MapOverlay:
if self._guidance is not None:
rl.unload_render_texture(self._guidance)
self._widget = rl.load_render_texture(width, height)
self._guidance = rl.load_render_texture(width, height)
self._guidance = rl.load_render_texture(width * GUIDANCE_SUPERSAMPLE, height * GUIDANCE_SUPERSAMPLE)
self._widget_size = None
if not self._widget.id or not self._guidance.id:
for target in (self._widget, self._guidance):
@@ -646,11 +772,33 @@ class MapOverlay:
strip = np.ascontiguousarray(strip, np.float32)
rl.draw_triangle_strip(strip, len(strip), color)
rl.end_blend_mode()
self._raster_drawn = self._draw_raster(geometry.request)
finally:
rl.end_texture_mode()
self._geometry = geometry
self._guidance_key = None
self._canvas_request = geometry.request
self.has_roads = geometry.tiles_missing < len(geometry.request.tiles)
self.has_roads = geometry.tiles_missing < len(geometry.request.tiles) or self._raster_drawn > 0
def _draw_raster(self, request: CanvasRequest) -> int:
"""Google tiles over the road lines, which show through wherever a tile has not arrived yet."""
if self.raster is None or not request.raster:
return 0
self._raster_generation = self.raster.generation
textures = self.raster.textures(request.raster)
px_per_unit = meters_per_tile(lat_lon(*request.center)[0]) * request.supersample / request.m_per_px
rl.begin_blend_mode(rl.BlendMode.BLEND_ALPHA)
try:
for key, texture in textures.items():
scale = 2.0 ** (DATA_ZOOM - key.z)
x = (key.x * scale - request.center[0]) * px_per_unit + request.side / 2
y = (key.y * scale - request.center[1]) * px_per_unit + request.side / 2
size = scale * px_per_unit + 1.0 # a pixel of overlap hides seams between tiles
rl.draw_texture_pro(texture, rl.Rectangle(0, 0, texture.width, texture.height), rl.Rectangle(x, y, size, size),
rl.Vector2(0, 0), 0, rl.WHITE)
finally:
rl.end_blend_mode()
return len(textures)
def _puck(self, x: float, y: float) -> None:
rl.draw_circle_v(rl.Vector2(x, y), 26, premultiplied((150, 110, 255, 70)))
@@ -677,16 +825,20 @@ class MapOverlay:
try:
rl.clear_background(rl.BLANK)
rl.begin_blend_mode(rl.BlendMode.BLEND_ALPHA_PREMULTIPLY)
# Drawn at 2x and downsampled in the mask shader, since render textures have no MSAA.
rl.rl_push_matrix()
if guidance:
rl.rl_scalef(GUIDANCE_SUPERSAMPLE, GUIDANCE_SUPERSAMPLE, 1)
if not guidance:
rl.draw_rectangle(0, 0, width, height, premultiplied(GLASS))
request = self._canvas_request
if self._canvas is not None and request is not None and self._world is not None:
px_per_unit = meters_per_tile(self._latitude) / request.m_per_px
zoom = request.m_per_px / self._m_per_px / SUPERSAMPLE
zoom = request.m_per_px / self._m_per_px / request.supersample
side = request.side
# The car's spot on the canvas, in canvas pixels.
car_x = (self._world[0] - request.center[0]) * px_per_unit * SUPERSAMPLE + side / 2
car_y = (self._world[1] - request.center[1]) * px_per_unit * SUPERSAMPLE + side / 2
car_x = (self._world[0] - request.center[0]) * px_per_unit * request.supersample + side / 2
car_y = (self._world[1] - request.center[1]) * px_per_unit * request.supersample + side / 2
anchor = rl.Vector2(width / 2, height * CAR_ANCHOR)
if guidance:
# Road geometry is cached across many frames. Guidance is trimmed at the
@@ -719,6 +871,7 @@ class MapOverlay:
rl.draw_texture_pro(self._canvas.texture, rl.Rectangle(0, 0, side, -side),
rl.Rectangle(anchor.x, anchor.y, side * zoom, side * zoom),
rl.Vector2(car_x * zoom, car_y * zoom), -self._bearing, rl.WHITE)
rl.rl_pop_matrix()
rl.end_blend_mode()
finally:
rl.end_texture_mode()
@@ -735,8 +888,8 @@ class MapOverlay:
if not self._ensure_targets(width, height, 0):
return
now = self.clock()
self._advance(data, now)
self._route(data.route)
self._advance(data, now)
self._track_route(data, now)
if self._world is not None:
side = self._canvas_side(width, height)
@@ -744,6 +897,12 @@ class MapOverlay:
ready, self._ready = self._ready, None
if ready is not None:
self._draw_canvas(ready)
if self.raster is not None:
self.raster.upload()
if (self._geometry is not None and self.raster.generation != self._raster_generation and
now - self._raster_redrawn >= RASTER_REDRAW_S):
self._raster_redrawn = now
self._draw_canvas(self._geometry)
in_flight = self._pending is not None and self._canvas_request is not self._pending and now - self._pending_at < 2.0
if not in_flight and self._needs_canvas(side):
self._schedule(self._request(side))
@@ -772,6 +931,8 @@ class MapOverlay:
finally:
rl.end_shader_mode()
rl.end_blend_mode()
if self._raster_drawn:
self._draw_attribution(rect)
if self.status == "waiting":
self._draw_gps_status(rect)
return
@@ -807,6 +968,28 @@ class MapOverlay:
rl.draw_rectangle_rounded_lines_ex(pill, 0.5, 8, 1.5, rl.Color(150, 140, 200, 255))
self.fonts.draw(text, FontRole.MEDIUM, size, pill.x + pad, pill.y + size * 0.27, rl.Color(240, 242, 250, 255))
def _draw_attribution(self, rect: rl.Rectangle) -> None:
"""Google's name and data credit along the bottom edge, solid whatever the map's opacity."""
if self.fonts is None:
return
from openpilot.starpilot.ui.onroad_google_map import ATTRIBUTION
from openpilot.starpilot.ui.presentation import FontRole
scale = max(.7, min(1.0, rect.width / 560, rect.height / 420))
inset, bottom = 16 * scale, rect.y + rect.height - 10 * scale
logo = self.fonts.measure(ATTRIBUTION, FontRole.SEMI_BOLD, 17 * scale)
self.fonts.draw(ATTRIBUTION, FontRole.SEMI_BOLD, 17 * scale, rect.x + inset, bottom - logo.height, rl.Color(240, 242, 250, 255))
size, room = 13 * scale, rect.width - logo.width - inset * 3
key = (self.raster.copyright if self.raster is not None else '', size, round(room))
if self._attribution_layout is None or self._attribution_layout[0] != key:
text = key[0] if room > 0 else ''
while len(text) > 3 and self.fonts.measure(text, FontRole.NORMAL, size).width > room:
text = text[:-4] + "..." if text.endswith("...") else text[:-1] + "..."
self._attribution_layout = key, text, self.fonts.measure(text, FontRole.NORMAL, size) if text else None
_, text, measured = self._attribution_layout
if measured is not None:
self.fonts.draw(text, FontRole.NORMAL, size, rect.x + rect.width - inset - measured.width, bottom - measured.height,
rl.Color(214, 218, 230, 255))
def _draw_source_chip(self, rect: rl.Rectangle) -> None:
"""Where the fix comes from, left of the compass; solid whatever the map's opacity so it always reads."""
label = SOURCE_LABELS.get(self._input.source)
@@ -886,6 +1069,8 @@ class MapOverlay:
def close(self) -> None:
self.reader.close()
if self.raster is not None:
self.raster.close()
if rl.is_window_ready():
for target in (self._canvas, self._widget, self._guidance):
if target is not None:
@@ -897,6 +1082,12 @@ class MapOverlay:
self._shader = None
def live_overlay(fonts=None) -> MapOverlay:
"""The driving map: road lines from disk, with Google tiles over them when Google is the chosen map style."""
from openpilot.starpilot.ui.onroad_google_map import GoogleRaster
return MapOverlay(fonts=fonts, raster=GoogleRaster())
# ---------------------------------------------------------------- live input
def fix_hold_seconds(source: str) -> float:
@@ -992,7 +1183,12 @@ class MapFeed:
@staticmethod
def _maneuver(nav) -> float | None:
meters = float(nav.instruction.distanceMeters)
"""Distance to the next turn worth zooming in for, or None for a step that keeps going straight."""
instruction = nav.instruction
meters = float(instruction.distanceMeters)
if (getattr(instruction, 'maneuverType', '') in NO_ZOOM_MANEUVERS and
getattr(instruction, 'maneuverModifier', '') in NO_ZOOM_MODIFIERS):
return None
return meters if nav.status == "guiding" and math.isfinite(meters) and meters >= 0 else None
def _road_name(self, now: float) -> str:
@@ -1051,7 +1247,6 @@ class SampleTileReader:
def sample_input() -> MapInput:
from openpilot.starpilot.navigation.road_tiles import lat_lon
def world(x, y):
return lat_lon(SAMPLE_TILE.x + x / EXTENT, SAMPLE_TILE.y + y / EXTENT)
latitude, longitude = world(*SAMPLE_CAR)
+2 -2
View File
@@ -29,8 +29,8 @@ class NativeMapLayer:
self._release()
return
if self.map is None:
from openpilot.starpilot.ui.onroad_map import MapFeed, MapOverlay
self.map = MapOverlay(fonts=self.fonts)
from openpilot.starpilot.ui.onroad_map import MapFeed, live_overlay
self.map = live_overlay(self.fonts)
self.feed = MapFeed()
self.map.prepare(self.feed.read(self.ui.sm), placed["width"], placed["height"])
self.prepared_size = (placed["width"], placed["height"])
@@ -4,7 +4,7 @@ from itertools import pairwise
from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.ui.presentation import FontRole
from openpilot.starpilot.ui.navigation_favorites_state import favorite_visible
from openpilot.starpilot.ui.navigation_favorites_state import active_favorite, favorite_visible, map_end_rect, map_end_visible
class NavigationFavorites:
@@ -18,16 +18,19 @@ class NavigationFavorites:
if placed is None or not placed['enabled'] or state.alert.size != 'none':
return
bookmark = key == 'bookmark'
if not bookmark and not favorite_visible(key, self.document, state.customization['layouts']['large']):
placements = state.customization['layouts']['large']
if not bookmark and not favorite_visible(key, self.document, placements):
return
label = key.removeprefix('nav_').title()
doc = self.document
place = next((row for row in doc['favorites'] if row.get('label') == label.lower()), None) if doc else None
active = not bookmark and bool(place and doc and doc['destination'] and doc['destination']['id'] == place['id'])
active = not bookmark and key == active_favorite(doc, placements)
available = bool(bookmark or active or place and doc and doc['enabled'] and doc['token'])
action = self.error or ('End route' if active else 'Navigate' if available else 'Set in Galaxy' if place is None else 'Enable navigation')
title = label if bookmark else action
detail = 'Save event' if bookmark else label
if active and doc is not None and not (place and doc['destination']['id'] == place['id']):
detail = self.fit(doc['destination'].get('name') or 'Route', FontRole.SEMI_BOLD, 34, 290)
icons = placed.get('display') == 'icons'
rect = rl.Rectangle(placed['x'], placed['y'], 110 if icons else 320, 110)
opacity = placed.get('opacity', 100) / 100
@@ -45,7 +48,7 @@ class NavigationFavorites:
rl.Vector2(rect.x + end[0], rect.y + end[1]), 6, ink)
else:
self.draw_icon(key, rect, ink)
badge = '' if bookmark else '!' if self.error else '+' if place is None else '!' if not available else ''
badge = '' if bookmark else '!' if self.error else '' if active else '+' if place is None else '!' if not available else ''
if badge:
if background:
rl.draw_circle(int(rect.x + 91), int(rect.y + 19), 14, rl.Color(15, 13, 23, alpha))
@@ -59,6 +62,25 @@ class NavigationFavorites:
self.fonts.draw(text, role, size, rect.x + (rect.width - measured.width) / 2, rect.y + offset,
ink)
def render_map_end(self, map_x, map_y, map_width, map_height, placements):
if not map_end_visible(self.document, placements):
return
x, y, size = map_end_rect(map_x, map_y, map_width, map_height)
center, radius, arm = rl.Vector2(x + size / 2, y + size / 2), size / 2, size * 0.18
tint = rl.Color(240, 150, 150, 255)
rl.draw_circle_v(center, radius, rl.Color(15, 13, 23, 235))
rl.draw_ring(center, radius - 2.5, radius, 0, 360, 48, tint)
for dx, dy in ((1, 1), (1, -1)):
rl.draw_line_ex(rl.Vector2(center.x - arm * dx, center.y - arm * dy),
rl.Vector2(center.x + arm * dx, center.y + arm * dy), 5, tint)
def fit(self, text, role, size, width):
if self.fonts.measure(text, role, size).width <= width:
return text
while text and self.fonts.measure(text + '…', role, size).width > width:
text = text[:-1]
return text.rstrip() + '…'
@staticmethod
def draw_icon(key, rect, color):
paths = (((3, 11), (12, 3), (21, 11)), ((5, 9), (5, 21), (10, 21), (10, 14), (14, 14), (14, 21), (19, 21), (19, 9))) if key == 'nav_home' else (
@@ -75,9 +75,9 @@ def test_card_changes_to_end_navigation_only_for_its_destination(key):
card.render(key, state)
assert [call.args[0] for call in fonts.draw.call_args_list] == ['End route', label.title()]
fonts.draw.reset_mock()
card.document['destination'] = {'id': 'another-place'}
card.document['destination'] = {'id': 'another-place', 'name': 'Costco'}
card.render(key, state)
assert [call.args[0] for call in fonts.draw.call_args_list] == ['Navigate', label.title()]
assert [call.args[0] for call in fonts.draw.call_args_list] == ['End route', 'Costco']
for change in ['alert', 'removed']:
fonts.draw.reset_mock()
state.alert.size = 'full' if change == 'alert' else 'none'
@@ -140,3 +140,22 @@ def test_other_favorite_is_hidden_until_route_ends(active, display):
card.document['destination'] = None
card.render(other, state)
background.assert_called_once()
def test_map_end_button_draws_only_when_no_favorite_slot_can_end_the_route():
card = NavigationFavorites(Mock())
place = {'id': 'home', 'label': 'home'}
placements = {'nav_home': {'x': 0, 'y': 0, 'enabled': False}}
card.document = {'favorites': [place], 'destination': None, 'enabled': True, 'token': 'key'}
with patch('raylib_nb.draw_circle_v') as circle, patch('raylib_nb.draw_ring'), patch('raylib_nb.draw_line_ex') as line:
card.render_map_end(100, 50, 240, 180, placements)
circle.assert_not_called()
card.document['destination'] = {'id': 'elsewhere', 'name': 'Costco'}
card.render_map_end(100, 50, 240, 180, placements)
center, radius = circle.call_args.args[:2]
assert radius == 30 and 100 < center.x < 160 and 50 < center.y < 110
assert line.call_count == 2
circle.reset_mock()
placements['nav_home']['enabled'] = True
card.render_map_end(100, 50, 240, 180, placements)
circle.assert_not_called()
+148 -1
View File
@@ -1,5 +1,6 @@
"""Map overlay geometry (CPU) and rendering (STARPILOT_AUTO_GL_TEST=1 for a real GL context)."""
import json
import math
import os
import time
@@ -17,7 +18,7 @@ from openpilot.starpilot.navigation.road_tiles import (
)
from openpilot.starpilot.ui.onroad_map import (
CAR_ANCHOR, HEADING_DEADBAND_DEG, MAX_TURN_DEG_S, ZOOM_FAST_M_PER_PX, ZOOM_SLOW_M_PER_PX, CanvasRequest, MapFix, MapInput, MapOverlay, TileReader,
build_canvas, line_strip, route_guidance, split_route, zoom_for_speed, zoom_target,
build_canvas, line_strip, route_guidance, snap_to_route, split_route, zoom_for_speed, zoom_target,
)
from openpilot.starpilot.system.starport.tests import test_gpu_nv12
@@ -160,6 +161,44 @@ def test_tile_reader_finishes_canvas_larger_than_cache(tmp_path):
reader.close()
def test_snap_to_route_keeps_the_car_on_the_line_ahead():
from openpilot.starpilot.navigation.road_tiles import meters_per_tile
meter = 1 / meters_per_tile(CENTER[0])
x, y = world_xy(*CENTER)
out_and_back = np.array([(x, y), (x + 500 * meter, y), (x + 500 * meter, y - 10 * meter), (x, y - 10 * meter)])
snapped = snap_to_route(out_and_back, (x + 100 * meter, y - 8 * meter), 90., 22 * meter)
assert snapped is not None and snapped[1] == 0 and snapped[0] == pytest.approx((x + 100 * meter, y))
assert snapped[2] == pytest.approx(90.)
assert snap_to_route(out_and_back, (x + 100 * meter, y + 40 * meter), 90., 22 * meter) is None
back = snap_to_route(out_and_back, (x + 100 * meter, y - 2 * meter), 270., 22 * meter)
assert back is not None and back[1] == 2, "heading picks the leg the car is driving"
resumed = snap_to_route(out_and_back, (x + 100 * meter, y - 2 * meter), None, 22 * meter, start=2)
assert resumed is not None and resumed[1] == 2
def test_car_eases_onto_the_route_and_turns_with_it(tmp_path):
from openpilot.starpilot.navigation.road_tiles import meters_per_tile
overlay = MapOverlay(tmp_path)
try:
meter = 1 / meters_per_tile(CENTER[0])
east = tuple(lat_lon(world_xy(*CENTER)[0] + i * 50 * meter, world_xy(*CENTER)[1]) for i in range(40))
overlay._route(east)
north_of_route = lat_lon(world_xy(*CENTER)[0] + 5 * meter, world_xy(*CENTER)[1] - 12 * meter)
for frame in range(200):
now = 100. + frame / 50
overlay._advance(MapInput(MapFix(*north_of_route, 80., 0.2, now), east, True), now)
assert overlay._world is not None and abs(overlay._world[1] - world_xy(*CENTER)[1]) < 0.5 * meter
overlay._advance(MapInput(MapFix(*north_of_route, 80., 10., 104.), east, True), 104.)
for frame in range(1, 300):
now = 104. + frame / 50
overlay._advance(MapInput(MapFix(*north_of_route, 80., 10., now), east, True), now)
assert overlay._bearing == pytest.approx(90., abs=HEADING_DEADBAND_DEG)
overlay._advance(MapInput(MapFix(*north_of_route, 80., 0.2, 200.), east, False), 200.)
assert overlay._snap_index is None
finally:
overlay.close()
def test_lost_gps_marks_previous_position_stale(tmp_path):
overlay = MapOverlay(tmp_path)
try:
@@ -731,6 +770,20 @@ def test_zoom_closes_in_before_a_maneuver_and_never_widens():
assert zoom_target(2., 60.) <= zoom_for_speed(2.)
def test_route_zoom_ignores_speed_and_closes_in_only_for_turns():
from openpilot.starpilot.ui.onroad_map import ZOOM_ROUTE_M_PER_PX, MapFeed
assert {zoom_target(v, 2000., guided=True) for v in (5., 15., 30.)} == {ZOOM_ROUTE_M_PER_PX}
assert zoom_target(30., None, guided=True) == ZOOM_ROUTE_M_PER_PX
assert zoom_target(30., 20., guided=True) == pytest.approx(ZOOM_SLOW_M_PER_PX)
def nav(kind, modifier):
return NS(status='guiding', instruction=NS(distanceMeters=120., maneuverType=kind, maneuverModifier=modifier))
assert MapFeed._maneuver(nav('turn', 'left')) == 120.
assert MapFeed._maneuver(nav('off ramp', 'slight right')) == 120.
assert MapFeed._maneuver(nav('continue', 'straight')) is None, "a straight-on step is not a corner"
assert MapFeed._maneuver(nav('new name', 'none')) is None
assert MapFeed._maneuver(nav('continue', 'left')) == 120., "a 'continue' that bends still zooms"
def test_stopped_overview_waits_then_yields_to_a_close_maneuver():
assert zoom_target(0., None, 29.) == ZOOM_SLOW_M_PER_PX
assert zoom_target(0., None, 31.) == ZOOM_FAST_M_PER_PX
@@ -775,6 +828,28 @@ def test_map_rotation_ignores_heading_wobble_and_turns_gently(tmp_path):
overlay.close()
def test_map_stays_still_along_a_kinked_straight_route(tmp_path):
from openpilot.starpilot.navigation.road_tiles import meters_per_tile
overlay = MapOverlay(tmp_path)
try:
meter = 1 / meters_per_tile(CENTER[0])
x0, y0 = world_xy(*CENTER)
# A straight east road whose simplified line zigzags 1.5 m every 15 m: each segment is ~6 degrees off.
route = tuple(lat_lon(x0 + i * 15 * meter, y0 + (1.5 * meter if i % 2 else 0.)) for i in range(200))
overlay._route(route)
bearings = []
for frame in range(400):
now = 100. + frame / 20
car = lat_lon(x0 + (20 + 15 * now - 1500) * meter, y0 + .75 * meter)
overlay._advance(MapInput(MapFix(*car, 90. + (3. if frame % 7 < 3 else -3.), 15., now), route, True), now)
if frame > 40:
bearings.append(overlay._bearing)
assert max(bearings) - min(bearings) < 1.0, "route kinks and GPS noise do not twist the map"
assert min(bearings) == pytest.approx(90., abs=HEADING_DEADBAND_DEG)
finally:
overlay.close()
def test_road_name_waits_before_replacing_and_clears_when_empty(tmp_path):
overlay = MapOverlay(tmp_path)
try:
@@ -825,3 +900,75 @@ def test_map_feed_reports_maneuver_distance_and_road_name(monkeypatch):
assert feed.read(sm).road_name == "Desert Inn Road"
sm.valid["mapdOut"] = False
assert feed.read(sm).road_name == "", "an invalid road match clears its name"
def google_overlay(tmp_path):
import io
from PIL import Image
from openpilot.starpilot.navigation.google_tiles import GoogleTileStore, key_digest, tiles_in_radius
from openpilot.starpilot.ui.onroad_google_map import GoogleRaster
key = "AIzaSyFixtureKey_0123456789abcdef"
settings = tmp_path / "settings.json"
settings.write_text(json.dumps({"mapProvider": "google", "googleKey": key}))
store = GoogleTileStore(tmp_path / "google")
# Each pixel carries its own position inside its tile, so any misplacement or flip shows in the colors.
x, y = np.meshgrid(np.arange(256), np.arange(256))
for tile in tiles_in_radius(*CENTER, 1500.0, 17):
pixels = np.stack((x, y, np.full_like(x, 60 + 120 * (tile.x % 2)), np.full_like(x, 255)), axis=-1).astype(np.uint8)
out = io.BytesIO()
Image.fromarray(pixels, "RGBA").save(out, "PNG")
store.write(key_digest(key), tile, out.getvalue(), 3600)
raster = GoogleRaster(tmp_path / "google", settings=settings, want=tmp_path / "want.json")
return MapOverlay(tmp_path / "roads", raster=raster)
def test_google_tiles_line_up_with_the_car_and_heading(gl, tmp_path):
rl = gl
overlay = google_overlay(tmp_path)
width, height = 560, 420
data = MapInput(MapFix(*CENTER, 0.0, 3.0, time.monotonic() + 3600), ())
try:
for _ in range(80):
overlay.prepare(data, width, height)
if overlay._raster_drawn and overlay.raster.generation == overlay._raster_generation and not overlay.raster._decoded:
break
time.sleep(0.05)
overlay.prepare(data, width, height)
assert overlay._raster_drawn > 4 and overlay.has_roads
from openpilot.starpilot.ui.onroad_map import RASTER_SUPERSAMPLE, SUPERSAMPLE
assert overlay._canvas_request.supersample == RASTER_SUPERSAMPLE
side = math.ceil(MapOverlay._reach(width, height) * 2 * 1.6 * RASTER_SUPERSAMPLE / 64) * 64
assert overlay._canvas.texture.width == side < math.ceil(MapOverlay._reach(width, height) * 2 * 1.6 * SUPERSAMPLE / 64) * 64
assert len(overlay.raster._textures) <= max(16, len(overlay.raster._wanted) + 8)
target = rl.load_render_texture(width, height)
rl.begin_texture_mode(target)
rl.clear_background(rl.Color(0, 0, 0, 255))
overlay.draw(rl.Rectangle(0, 0, width, height), 1.0)
rl.end_texture_mode()
image = rl.load_image_from_texture(target.texture)
rl.image_flip_vertical(image)
pixels = np.frombuffer(image.data[:width * height * 4], np.uint8).reshape(height, width, 4).copy()
rl.unload_image(image)
rl.unload_render_texture(target)
finally:
overlay.close()
# Heading north, 60 screen pixels left of the car is 60 * 0.9 m west of it.
from openpilot.starpilot.navigation.road_tiles import meters_per_tile
cx, cy = world_xy(*CENTER, 17)
expected_x = (cx - 60 * ZOOM_SLOW_M_PER_PX / meters_per_tile(CENTER[0], 17)) % 1 * 256
r, g = pixels[int(height * CAR_ANCHOR), width // 2 - 60, :2].astype(int)
assert abs(r - expected_x) <= 4 and abs(g - cy % 1 * 256) <= 4
# 60 pixels above the car is north of it: the same column, a smaller row in the tile (or the tile above).
r2, g2 = pixels[int(height * CAR_ANCHOR) - 60, width // 2, :2].astype(int)
assert abs(r2 - cx % 1 * 256) <= 4 and abs(g2 - (cy - 60 * ZOOM_SLOW_M_PER_PX / meters_per_tile(CENTER[0], 17)) % 1 * 256) <= 4
assert json.loads((tmp_path / "want.json").read_text())["tiles"]
def test_google_layer_is_off_unless_google_is_chosen(tmp_path):
from openpilot.starpilot.ui.onroad_google_map import chosen_key
path = tmp_path / "settings.json"
assert chosen_key(path) == ""
path.write_text(json.dumps({"mapProvider": "mapbox", "googleKey": "AIzaSyFixtureKey_0123456789abcdef"}))
assert chosen_key(path) == ""
path.write_text(json.dumps({"mapProvider": "google", "googleKey": "AIzaSyFixtureKey_0123456789abcdef"}))
assert chosen_key(path) == "AIzaSyFixtureKey_0123456789abcdef"
@@ -7,7 +7,7 @@ from openpilot.starpilot.ui.onroad_map_layer import NativeMapLayer
def test_native_map_prepares_outside_render_and_releases_when_hidden_disabled_or_offroad():
with patch('openpilot.starpilot.ui.onroad_map_layer.gui_app') as app, \
patch('openpilot.starpilot.ui.onroad_map.MapOverlay') as overlay, \
patch('openpilot.starpilot.ui.onroad_map.live_overlay') as overlay, \
patch('openpilot.starpilot.ui.onroad_map.MapFeed') as feed:
ui = NS(started=True, sm=Mock())
layer = NativeMapLayer(Mock(), ui)
@@ -52,7 +52,7 @@ def test_native_map_prepares_outside_render_and_releases_when_hidden_disabled_or
def test_native_map_yields_while_starport_draws_its_own():
with patch('openpilot.starpilot.ui.onroad_map_layer.gui_app'), \
patch('openpilot.starpilot.ui.onroad_map_layer.projection_map_active') as lease, \
patch('openpilot.starpilot.ui.onroad_map.MapOverlay') as overlay, \
patch('openpilot.starpilot.ui.onroad_map.live_overlay') as overlay, \
patch('openpilot.starpilot.ui.onroad_map.MapFeed'):
ui = NS(started=True, sm=Mock())
layer = NativeMapLayer(Mock(), ui)
@@ -76,6 +76,21 @@ def test_bad_distance_and_empty_instruction_do_not_render():
assert navigation_display(nav, now_ns=NOW, drive_id=DRIVE).text == 'You have arrived'
def test_reaching_the_arrive_maneuver_reads_arrived_before_the_car_stops():
nav = message()
nav.instruction = {'text': 'Arrive at your destination', 'maneuverType': 'arrive', 'maneuverModifier': 'straight',
'distanceMeters': 150, 'remainingDistanceMeters': 150, 'remainingDurationSeconds': 20}
nav.nextManeuver = {'maneuverType': 'arrive', 'maneuverModifier': 'straight', 'distanceMeters': 150}
approaching = navigation_display(nav, now_ns=NOW, drive_id=DRIVE)
assert approaching is not None and not approaching.arrived and approaching.text == 'Arrive at your destination'
nav.instruction.distanceMeters = nav.instruction.remainingDistanceMeters = 0
there = navigation_display(nav, now_ns=NOW, drive_id=DRIVE)
assert there is not None and there.arrived and there.text == 'You have arrived' and there.then_type == '', "no '0 ft' while still rolling"
nav.instruction.maneuverType = 'turn'
turning = navigation_display(nav, now_ns=NOW, drive_id=DRIVE)
assert turning is not None and not turning.arrived, "only the final maneuver means arrival"
@pytest.mark.parametrize('meters,metric,expected', [(120, False, '400 ft'), (120, True, '125 m'),
(1609.344, False, '1.0 mi'), (2000, True, '2.0 km')])
def test_distance_units(meters, metric, expected):