Compare commits

...
12 Commits
Author SHA1 Message Date
dasemu f38f361c5b Merge pull request #17 from Dasemu/feat/gpx-road-routing-tft-camera
feat: road-route imported GPX stops and widen the TFT camera
2026-10-26 17:26:18 +01:00
dasemuandClaude Opus 5.5 997816f2e4 feat: route GPX deviations back to the nearest point ahead
After a sustained deviation from an imported route, a road leg from the
current position is prepended to the rest of the route, starting at the
nearest point ahead of the progress made (never behind). While off the
route, passing within 100 m of a later point counts as reaching it.
The imported geometry itself is never replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:17:33 +01:00
dasemuandClaude Opus 5.5 31eea182b9 feat: reroute the leg to an imported route's first point
Leaving the prepended leg before reaching the GPX recalculates that leg
from the current position under the normal off-route policy. Deviations
on the imported route itself are still never rerouted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:05:20 +01:00
dasemuandClaude Opus 5.5 646a4a2a2a fix: wait for a precise fix on start and route GPX from the rider
- Start no longer fails when the first fix is coarser than 25 m: both
  searched and imported routes wait up to 60 s for guidance accuracy.
- Starting an imported route more than 150 m from its first point
  prepends a road leg from the current position; traces stay traces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:43:41 +01:00
dasemuandClaude Opus 5.5 b7bf2c2b43 feat: road-route imported GPX stops and widen the TFT camera
- Route points, waypoints and sparse tracks are joined along roads with
  multi-location Valhalla requests (chunks of 20, merged legs); failures
  offer a retry instead of straight lines.
- TFT camera: lower zoom, 45 degree pitch and rider lower in the frame;
  rider zoom offset from Settings and NaviLite zoom requests 51/52.
- Online map failures fall back to an installed offline pack for 30 s.
- Production-facing copy cleanup and docs; version 0.14.8 (25).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:27:51 +01:00
dasemu 694fefd98b Merge pull request #15 from Dasemu/feat/gpx-route-road-calculation
Feat/gpx route road calculation
2026-10-26 09:38:49 +01:00
dasemu e5f4cfd8bd chore: bump GPX feature version to 0.14.7 2026-10-26 09:35:45 +01:00
dasemu 6a04c38a77 chore: bump GPX feature version to 0.14.7 2026-10-26 09:35:43 +01:00
dasemu a7f7198fd3 fix: render route preview warning on a new line 2026-10-26 09:29:40 +01:00
dasemu b14c625263 feat: support road calculation for imported GPX stops 2026-10-26 09:28:46 +01:00
dasemu 196b7da8ea feat: support road calculation for imported GPX stops 2026-10-26 09:28:42 +01:00
dasemu 0ee1f621cf feat: support road calculation for imported GPX stops 2026-10-26 09:28:39 +01:00
22 changed files with 766 additions and 97 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ NavFrame is an experimental Android navigation app that renders its own 480×240
The owner has confirmed static and synthetic NavFrame frames on a Xiaomi 11 Lite 5G NE running Android 14 and a 2026 Yamaha MT-07, and the bundled Asturias map working offline on the phone. On 2026-10-12, the owner reported that the latest version displayed the map on the TFT for about 20 minutes, then showed `Mapa no disponible` in La Corredoria (Oviedo) for the rest of the trip while the phone map continued working. An offline map was installed. The exact installed build, diagnostic code and background state were not recorded; the cause is under investigation. This establishes a successful map display followed by a persistent failure, not sustained TFT reliability.
The current checkout is version 0.14.6. The 0.13 series adds voice/routing language selection for Spanish, English, German, French, and Italian, plus a system-language option; unsupported system locales resolve to English. Speech still depends on the Android TextToSpeech engine and its installed voice data. The app includes offline map and place data for Asturias, plus installable regional packages. Worldwide regions can be discovered and built on demand through the [regional package workflow](docs/GLOBAL_OFFLINE.md); this is not complete worldwide coverage. Installed packages currently provide map and local place/camera data. Offline route calculation, global camera completeness, and complete worldwide font coverage are not provided.
The current checkout is version 0.14.8. The 0.13 series adds voice/routing language selection for Spanish, English, German, French, and Italian, plus a system-language option; unsupported system locales resolve to English. Speech still depends on the Android TextToSpeech engine and its installed voice data. The app includes offline map and place data for Asturias, plus installable regional packages. Worldwide regions can be discovered and built on demand through the [regional package workflow](docs/GLOBAL_OFFLINE.md); this is not complete worldwide coverage. Installed packages currently provide map and local place/camera data. Offline route calculation, global camera completeness, and complete worldwide font coverage are not provided.
Route calculation and address search use configurable online services. Spoken output uses the selected language when Android provides voice data; voice availability and offline behavior depend on the device's TextToSpeech engine. Physical validation of route guidance, voice playback, camera alerts, sustained TFT map rendering, and a 30-minute screen-off session remains pending unless a newer test report says otherwise.
+2 -2
View File
@@ -15,8 +15,8 @@ android {
applicationId = "dev.navframe.app"
minSdk = 26
targetSdk = 35
versionName = "0.14.6"
versionCode = 23
versionName = "0.14.8"
versionCode = 25
}
if (hasReleaseSigning) {
signingConfigs.create("production") {
@@ -23,6 +23,7 @@ open class MainActivity : Activity() {
private var searchJob: Job? = null
private var positionWait: Job? = null
private var importJob: Job? = null
private var lastImportedRoute: ImportedRoute? = null
private var pendingImportUri: Uri? = null
private var searchGeneration = 0L
private var updatingDestination = false
@@ -148,9 +149,9 @@ open class MainActivity : Activity() {
})
guidance = label("", 20f); progress = label("", 14f); routeInfo = label("", 14f)
permissionInfo = label("", 12f)
origin = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("GPS real", "DEMO · posición simulada")) }
origin = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("Desde mi ubicación", "Simulación (sin GPS)")) }
profileButton = button(profileLabel()) { chooseProfile() }
stopButton = button("STOP · Detener ruta") { positionWait?.cancel(); service?.stopRoute(); routeDialog?.dismiss(); hint.text = ""; stopButton.visibility = View.GONE }.apply { visibility = View.GONE; setTextColor(Color.WHITE); background = rounded(0xEEA83939.toInt(), 18) }
stopButton = button("Detener ruta") { positionWait?.cancel(); service?.stopRoute(); routeDialog?.dismiss(); hint.text = ""; stopButton.visibility = View.GONE }.apply { visibility = View.GONE; setTextColor(Color.WHITE); background = rounded(0xEEA83939.toInt(), 18) }
root.addView(stopButton, FrameLayout.LayoutParams(-1, dp(56), android.view.Gravity.BOTTOM).apply { setMargins(dp(16), 0, dp(16), dp(28)) })
root.addView(button("◎") { withPermissions(Action.POSITION) }.apply { contentDescription = "Centrar en mi posición y seguir el mapa"; background = rounded(0xFF50D5B6.toInt(), 28); setTextColor(0xFF0D191C.toInt()); elevation = dp(8).toFloat() }, FrameLayout.LayoutParams(dp(56), dp(56), android.view.Gravity.BOTTOM or android.view.Gravity.END).apply { setMargins(0, 0, dp(16), dp(104)) })
positionNotice = label("", 13f).apply {
@@ -213,8 +214,8 @@ open class MainActivity : Activity() {
NavigationStatus.ARRIVED -> "Has llegado al destino"
NavigationStatus.ROUTE_PREVIEW -> "Vista previa de ruta"
NavigationStatus.IDLE -> "Listo para navegar"
else -> state.nextManeuver?.instruction ?: if (state.route == null) "GPS listo · elige un destino" else if (state.route?.imported == true) "Sigue el trazado GPX · sin giros anunciados" else "Continúa por la ruta"
}.let { if (demo) "DEMO · $it" else it }
else -> state.nextManeuver?.instruction ?: if (state.route == null) "GPS listo · elige un destino" else if (state.route?.let { it.imported && it.maneuvers.isEmpty() } == true) "Sigue el trazado GPX" else "Continúa por la ruta"
}.let { if (demo) "Simulación · $it" else it }
val next = state.distanceToNextManeuverMeters?.let { "$it m" } ?: ""
val remaining = state.remainingDistanceMeters?.let { "%.1f km restantes".format(java.util.Locale.ROOT, it / 1000.0) } ?: ""
val eta = state.etaEpochMillis?.let { "ETA " + java.text.SimpleDateFormat("HH:mm", java.util.Locale.ROOT).format(java.util.Date(it)) } ?: ""
@@ -232,7 +233,7 @@ open class MainActivity : Activity() {
if (needsLocation) required += Manifest.permission.ACCESS_FINE_LOCATION
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
val blocked = missing.any { permissionsPreferences.getBoolean(it, false) && !shouldShowRequestPermissionRationale(it) }
if (blocked) { AlertDialog.Builder(this).setTitle("Permiso necesario").setMessage("Activa ubicación precisa o dispositivos cercanos para esta función. Puedes seguir explorando mapas y usando la demo.").setPositiveButton("Abrir ajustes") { _, _ -> openAppSettings() }.setNegativeButton("Cancelar", null).show(); return }
if (blocked) { AlertDialog.Builder(this).setTitle("Permiso necesario").setMessage("Activa ubicación precisa o dispositivos cercanos para esta función. Puedes seguir explorando mapas y usando la simulación.").setPositiveButton("Abrir ajustes") { _, _ -> openAppSettings() }.setNegativeButton("Cancelar", null).show(); return }
val request = missing.toMutableList()
if (missing.contains(Manifest.permission.ACCESS_FINE_LOCATION)) request += Manifest.permission.ACCESS_COARSE_LOCATION
if ((action == Action.CONNECT || action == Action.CHANGE_CONNECT || ((action == Action.ROUTE || action == Action.IMPORT_ROUTE) && service?.routeUsesGps() == true)) && Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED && !permissionsPreferences.getBoolean(Manifest.permission.POST_NOTIFICATIONS, false)) request += Manifest.permission.POST_NOTIFICATIONS
@@ -251,7 +252,7 @@ open class MainActivity : Activity() {
refreshPermissions()
val needsFine = action == Action.IMPORT_ROUTE || action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
val allowed = (!needsFine || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && ((action != Action.CONNECT && action != Action.CHANGE_CONNECT) || Build.VERSION.SDK_INT < 31 || checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED)
if (action != null && allowed) perform(action) else hint.text = "Permiso denegado · puedes usar la demo. Toca el aviso de permisos para abrir ajustes."
if (action != null && allowed) perform(action) else hint.text = "Permiso denegado · puedes usar la simulación o concederlo en los ajustes de la app."
}
private fun refreshPermissions() {
if (!::permissionInfo.isInitialized) return
@@ -281,6 +282,7 @@ open class MainActivity : Activity() {
Action.IMPORT_ROUTE -> startImportedRoute()
Action.ROUTE, Action.PREVIEW -> {
if (action == Action.ROUTE && service?.hasPreparedRoute() != true) return
if (action == Action.ROUTE && service?.routeUsesGps() == true && service?.hasGuidanceGpsFix() != true) { startWhenGuidanceReady("Esperando GPS preciso para iniciar la ruta…") { perform(Action.ROUTE) }; return }
if (action == Action.ROUTE) startRequested = true
if (action == Action.PREVIEW) service?.previewPreparedRoute()
else if (service?.routeUsesGps() == true) try { startForegroundService(Intent(this, TftService::class.java).setAction(TftService.ACTION_ROUTE_GPS).putExtra(TftService.EXTRA_PREVIEW, action == Action.PREVIEW)) } catch (_: RuntimeException) { hint.text = "No se pudo iniciar · revisa permisos de ubicación" }
@@ -355,11 +357,11 @@ open class MainActivity : Activity() {
ensureActive()
val current = service ?: run { hint.text = "Servicio no disponible · vuelve a cargar el GPX"; return@launch }
cancelSearch(); routeDialog?.dismiss()
current.prepareImportedRoute(imported)
lastImportedRoute = imported
destination = null; destinationName = ""
hint.text = "Ruta GPX cargada"
hint.text = ""
showImportedRouteSheet(imported.name)
withPermissions(Action.IMPORT_ROUTE)
prepareImported(current, imported)
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) {
// Parser messages contain no coordinates, file paths or document contents.
@@ -367,6 +369,10 @@ open class MainActivity : Activity() {
}
}
}
/** Road-routes GPX stops first; navigation starts automatically once a route is ready. */
private fun prepareImported(current: TftService, imported: ImportedRoute) {
current.calculateImportedStops(imported) { if (lastImportedRoute === imported && routeDialog?.isShowing == true) withPermissions(Action.IMPORT_ROUTE) }
}
private fun showImportedRouteSheet(name: String?) {
routeDialog?.dismiss()
(routeInfo.parent as? android.view.ViewGroup)?.removeView(routeInfo)
@@ -375,7 +381,12 @@ open class MainActivity : Activity() {
box.addView(routeInfo)
routeLoading = ProgressBar(this).apply { visibility = View.GONE }
box.addView(routeLoading)
retryRouteButton = null
retryRouteButton = button("Reintentar") {
val current = service ?: return@button
// A GPS-wait timeout keeps the calculated route: only restart navigation.
if (current.hasPreparedRoute()) withPermissions(Action.IMPORT_ROUTE) else lastImportedRoute?.let { prepareImported(current, it) }
}.apply { visibility = View.GONE }
box.addView(retryRouteButton)
startButton = button("Iniciar navegación") { withPermissions(Action.IMPORT_ROUTE) }
box.addView(startButton)
val dialog = AlertDialog.Builder(this).setView(box).setNegativeButton("Cerrar", null).create()
@@ -386,10 +397,24 @@ open class MainActivity : Activity() {
private fun startImportedRoute() {
val current = service ?: return
if (!current.preparedRouteIsImported()) { hint.text = "Vuelve a cargar la ruta GPX"; return }
startWhenGuidanceReady("Esperando GPS preciso para iniciar el GPX…") {
if (!current.preparedRouteIsImported()) return@startWhenGuidanceReady
routeLoading?.visibility = View.VISIBLE
current.prepareImportedApproach { approached ->
routeLoading?.visibility = View.GONE
if (!approached) hint.text = "No se pudo calcular el camino hasta el inicio del GPX · dirígete al primer punto"
// The sheet may have been closed while the leg was calculated: then do not start.
if (routeDialog?.isShowing == true && current.preparedRouteIsImported()) perform(Action.ROUTE)
}
}
}
/** Coarse first fixes are common: wait for guidance accuracy instead of refusing to start. */
private fun startWhenGuidanceReady(message: String, start: () -> Unit) {
val current = service ?: return
positionWait?.cancel()
if (current.hasGuidanceGpsFix()) { perform(Action.ROUTE); return }
if (current.hasGuidanceGpsFix()) { start(); return }
current.setPhoneVisible(true)
hint.text = "Esperando GPS preciso para iniciar el GPX…"
hint.text = message
routeLoading?.visibility = View.VISIBLE
startButton?.isEnabled = false
positionWait = scope.launch {
@@ -398,10 +423,13 @@ open class MainActivity : Activity() {
// Map readiness stays true while accuracy improves from 100 m to 25 m.
while (!current.hasGuidanceGpsFix()) delay(200)
}
ensureActive()
if (current.preparedRouteIsImported()) perform(Action.ROUTE)
} catch (_: TimeoutCancellationException) { hint.text = "Sin GPS preciso · activa ubicación y pulsa Iniciar navegación de nuevo" }
finally { routeLoading?.visibility = View.GONE; startButton?.isEnabled = current.hasPreparedRoute() }
} catch (_: TimeoutCancellationException) {
hint.text = "Sin GPS preciso · activa ubicación y pulsa Iniciar de nuevo"
return@launch
} finally { routeLoading?.visibility = View.GONE; startButton?.isEnabled = current.hasPreparedRoute() }
ensureActive()
hint.text = ""
start()
}
}
private fun cancelSearch() { searchGeneration++; searchJob?.cancel(); searchJob = null }
@@ -613,6 +641,16 @@ open class MainActivity : Activity() {
try { startActivity(Intent("com.android.settings.TTS_SETTINGS")) }
catch (_: ActivityNotFoundException) { openAppSettings() }
})
content.addView(label("Zoom del mapa en la pantalla de la moto", 14f))
val zoomLabel = label("", 13f)
fun showZoom(message: String = "") { zoomLabel.text = message.ifEmpty { if (current.tftZoomOffset == 0.0) "Automático según velocidad" else "Automático %+.1f".format(java.util.Locale("es", "ES"), current.tftZoomOffset) } }
content.addView(row().apply {
addView(button("−") { current.adjustTftZoom(-1); showZoom(current.tftZoomInfo.value.takeIf { it.endsWith("mínimo") }.orEmpty()) }.apply { contentDescription = "Alejar mapa TFT" }, LinearLayout.LayoutParams(0, dp(48), 1f))
addView(button("Auto") { current.adjustTftZoom(-(current.tftZoomOffset / TftCameraPolicy.ZOOM_STEP).toInt()); showZoom() }.apply { contentDescription = "Restablecer zoom TFT" }, LinearLayout.LayoutParams(0, dp(48), 1f).apply { setMargins(dp(8), 0, dp(8), 0) })
addView(button("+") { current.adjustTftZoom(1); showZoom(current.tftZoomInfo.value.takeIf { it.endsWith("máximo") }.orEmpty()) }.apply { contentDescription = "Acercar mapa TFT" }, LinearLayout.LayoutParams(0, dp(48), 1f))
})
showZoom()
content.addView(zoomLabel)
val routeEndpoint = entry("Servidor Valhalla HTTPS", current.routingEndpoint())
val geocoderEndpoint = entry("Servidor búsqueda HTTPS", getSharedPreferences("geocoder", MODE_PRIVATE).getString("endpoint", NominatimGeocoder.DEFAULT_ENDPOINT) ?: NominatimGeocoder.DEFAULT_ENDPOINT)
val catalogPreferences = getSharedPreferences("regional_downloads", MODE_PRIVATE)
@@ -678,7 +716,7 @@ open class MainActivity : Activity() {
}.setNegativeButton("Cancelar", null).show()
}
private fun showInfo() {
val text = "NavFrame ${BuildConfig.VERSION_NAME} · mapas OpenStreetMap. Móvil y Yamaha comparten estado; el TFT se renderiza directamente a 480 × 240, sin captura de pantalla.\n\nDEMO es ficticia. GPS/ETA/guiado deben probarse en condiciones reales. Rutas y búsqueda necesitan conexión; los mapas y lugares incluidos de Asturias se consultan offline. Calcular rutas sigue necesitando Internet.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No envíes información personal/confidencial. Prototipo con máximo 1 petición/s agregado y caché.\n\nNaviLite adaptado de Pillion · PolyForm Noncommercial 1.0.0\nRequired Notice: Copyright 2026 the Pillion authors\n\nFuente online predeterminada incluida: OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors.\n\nAsturias offline: datos © OpenStreetMap contributors, extracto Geofabrik 28/09/2026, licencia ODbL. Límites 42,9–43,75 N / 7,2–4,45 O; zoom 6–14. Tipografía Noto Sans, SIL OFL 1.1."
val text = "NavFrame ${BuildConfig.VERSION_NAME} · mapas OpenStreetMap. Móvil y Yamaha comparten estado; el TFT se renderiza directamente a 480 × 240, sin captura de pantalla.\n\nLa simulación usa posiciones ficticias. Calcular rutas y buscar direcciones necesita conexión; los mapas y lugares incluidos de Asturias funcionan sin conexión.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No escribas información personal o confidencial. Las peticiones se limitan a 1 por segundo y se guardan en caché.\n\nNaviLite adaptado de Pillion · PolyForm Noncommercial 1.0.0\nRequired Notice: Copyright 2026 the Pillion authors\n\nFuente online predeterminada incluida: OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors.\n\nAsturias offline: datos © OpenStreetMap contributors, extracto Geofabrik 28/09/2026, licencia ODbL. Límites 42,9–43,75 N / 7,2–4,45 O; zoom 6–14. Tipografía Noto Sans, SIL OFL 1.1."
val box = column().apply { setPadding(dp(16), 0, dp(16), 0); addView(label(text + "\n\nFuente activa: ${service?.mapSource()?.attribution ?: ConfiguredMapDataSource.DEFAULT_ATTRIBUTION}\nSi una fuente personalizada no declara atribución, corrige el estilo en Ajustes.", 14f)); addView(button("Diagnóstico del mapa TFT") { showMapDiagnostic() }) }
AlertDialog.Builder(this).setTitle("Información y licencias").setView(ScrollView(this).apply { addView(box) }).setPositiveButton("Cerrar", null).setNeutralButton("Licencias") { _, _ -> showLicenses() }.setNegativeButton("Política búsqueda") { _, _ -> openUrl("https://operations.osmfoundation.org/policies/nominatim/") }.show()
}
@@ -739,6 +777,7 @@ open class MainActivity : Activity() {
check(selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)))
rebuildPhoneMap() // Release native readers before removing an active private archive.
}
service?.releaseMapFallback()
offlineManager.delete(pack.id)
hint.text = "Paquete offline borrado"
} catch (_: Exception) { hint.text = "No se pudo borrar el paquete" }
@@ -761,6 +800,7 @@ open class MainActivity : Activity() {
check(selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)))
rebuildPhoneMap()
}
service?.releaseMapFallback()
regionalManager.delete(region.folderId)
displayedPlaces = emptyList(); phoneMap?.setPlaces(emptyList())
hint.text = "Región borrada"
@@ -61,7 +61,7 @@ class MapFrameComposer {
if (warning != null) {
text(fitted(warning, 16f, 460f), 10f, 39f, 16f, if (state.navigationStatus == NavigationStatus.ARRIVED) accent else Color.YELLOW)
} else {
val imported = state.route?.imported == true
val imported = state.route?.let { it.imported && it.maneuvers.isEmpty() } == true
val maneuver = state.nextManeuver
val direction = maneuverDirection(maneuver?.type).name
canvas.save()
@@ -85,7 +85,7 @@ class MapFrameComposer {
}
} else if (preview) {
val route = requireNotNull(state.route)
val summary = if (route.imported) "GPX · %.1f km · seguir trazado".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0) else "PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60)
val summary = if (route.imported && route.maneuvers.isEmpty()) "GPX · %.1f km · seguir trazado".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0) else "PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60)
text(fitted(summary, 13f, 460f), 8f, 31f, 13f)
}
@@ -25,7 +25,7 @@ import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/** The service owns this dedicated 480×240 GPU snapshot target, not a phone MapView or Activity. */
class MapLibreTftRenderer(context: Context, private val source: MapDataSource, private val reportStage: (MapRenderStage) -> Unit = {}) : TftRenderer {
class MapLibreTftRenderer(context: Context, private val source: MapDataSource, private val zoomOffset: () -> Double = { 0.0 }, private val reportStage: (MapRenderStage) -> Unit = {}) : TftRenderer {
private val context = context.applicationContext
private val main = Handler(Looper.getMainLooper())
private val composer = MapFrameComposer()
@@ -71,9 +71,11 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
// (including screen off) and initialize from the current network, not a stale event.
connectivity.refresh()
val position = LatLng(state.position.latitude, state.position.longitude)
val camera = TftCameraPolicy().parameters(state)
val camera = TftCameraPolicy(zoomOffset()).parameters(state)
// Top padding moves the focal point (the rider) down to riderAnchorY of the frame height.
val cameraPosition = CameraPosition.Builder().target(position).zoom(camera.zoom)
.bearing(camera.bearingDegrees.toDouble()).padding(0.0, 50.0, 0.0, 0.0).build()
.bearing(camera.bearingDegrees.toDouble()).tilt(camera.pitchDegrees)
.padding(0.0, ((2 * camera.riderAnchorY - 1) * 240.0).coerceAtLeast(0.0), 0.0, 0.0).build()
val current = snapshotter ?: run {
val tile = source.tileSource()
val builder = if (tile.uri.startsWith("asset://")) Style.Builder().fromJson(context.assets.open(tile.uri.removePrefix("asset://")).bufferedReader().use { it.readText() })
@@ -12,7 +12,7 @@ import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/** Button-triggered prototype search only: no autocomplete, GPS, viewbox or persisted query history. */
/** Button-triggered search only: no autocomplete, GPS, viewbox or persisted query history. */
class NominatimGeocoder(
private val endpoint: String = DEFAULT_ENDPOINT,
private val openConnection: (String) -> HttpURLConnection = { URI(it).toURL().openConnection() as HttpURLConnection },
@@ -54,7 +54,7 @@ class NominatimGeocoder(
http.requestMethod = "GET"
http.connectTimeout = 8_000; http.readTimeout = 12_000
http.instanceFollowRedirects = false
http.setRequestProperty("User-Agent", "NavFrame/0.6 (Android navigation prototype)")
http.setRequestProperty("User-Agent", "NavFrame/${BuildConfig.VERSION_NAME} (Android navigation)")
http.setRequestProperty("Accept", "application/json")
val status = http.responseCode
if (status != 200) {
+212 -20
View File
@@ -19,7 +19,7 @@ class TftService : Service() {
private var routeJob: Job? = null
private var routeGeneration = 0L
private var preparedGeneration = 0L
internal var routingEngineFactory: (String) -> RoutingEngine = { ValhallaRoutingEngine(it, "dev.navframe.app/0.6-prototype", language = { NavigationVoicePreferences.language(this).tag }) }
internal var routingEngineFactory: (String) -> RoutingEngine = { ValhallaRoutingEngine(it, "dev.navframe.app/${BuildConfig.VERSION_NAME}", language = { NavigationVoicePreferences.language(this).tag }) }
internal var mapRenderOverride: (suspend (NavigationState, NavigationMode) -> TftFrame)? = null
private var routePlan: RoutePlan? = null
private var preparedDestinationDirty = false
@@ -32,11 +32,18 @@ class TftService : Service() {
private val reroutePolicy = ReroutePolicy()
private var rerouteFailures = 0
private var reroutePaused = false
/** True once the rider is past the leg prepended to reach an imported route's first point. */
private var approachDone = false
/** Metres reached along the imported part still to ride (the plan's importedBase, or the route). */
private var importedProgressMeters = 0.0
private var importedLength: Pair<RouteResult, Double>? = null
private fun importedLength(route: RouteResult): Double =
importedLength?.takeIf { it.first === route }?.second ?: routeLength(route).also { importedLength = route to it }
private var lastGpsFix: LocationFix? = null
private var lastGpsElapsed = 0L
private val mutableRouteInfo = MutableStateFlow("Sin ruta calculada")
val routeInfo = mutableRouteInfo.asStateFlow()
private data class RoutePlan(val route: RouteResult, val origin: GeoPoint, val demo: Boolean, val options: RouteOptions = RouteOptions())
private data class RoutePlan(val route: RouteResult, val origin: GeoPoint, val demo: Boolean, val options: RouteOptions = RouteOptions(), val importedBase: RouteResult? = null)
private var navigationJob: Job? = null
private var locationProvider: AndroidLocationProvider? = null
private var gpsRequested = false
@@ -52,7 +59,7 @@ class TftService : Service() {
private var latestNavigationState = NavigationState()
set(value) {
field = value; mutableNavigationState.value = value
if (shownRoute?.demo == false && !routePreview && value.route?.imported != true) voice?.update(value)
if (shownRoute?.demo == false && !routePreview && value.route?.let { !it.imported || it.maneuvers.isNotEmpty() } != false) voice?.update(value)
else voice?.reset()
}
private var voice: NavigationVoiceController? = null
@@ -77,6 +84,19 @@ class TftService : Service() {
private var mapRenderStarted = 0L
private var mapRenderStage = MapRenderStage.INITIALIZE
private var mapRetryAt = 0L
/** Rider zoom adjustment on top of the speed-based TFT camera; persisted across sessions. */
var tftZoomOffset: Double = 0.0
private set
private var forceMapRedraw = false
/** Installed offline map used for the TFT while the online source keeps failing. */
private var fallbackRenderer: MapLibreTftRenderer? = null
private var fallbackUri: String? = null
private var onlineRetryAt = 0L
private var offlineSources: List<Pair<RegionalBounds, TileSource>> = emptyList()
private var offlineSourcesAt = 0L
private val mutableTftZoomInfo = MutableStateFlow("")
val tftZoomInfo = mutableTftZoomInfo.asStateFlow()
private var dashboardRequests = sortedMapOf<Int, Int>()
private var mapFailures = 0
private var unavailableMapFrame: TftFrame? = null
private val mutableMode = MutableStateFlow(NavigationMode.IDLE)
@@ -91,7 +111,7 @@ class TftService : Service() {
val connectionState = mutableState.asStateFlow()
private val mutableFrame = MutableStateFlow<TftFrame?>(null)
val lastFrame = mutableFrame.asStateFlow()
private val mutableMessage = MutableStateFlow("Listo para prueba TFT")
private val mutableMessage = MutableStateFlow("Listo")
val message = mutableMessage.asStateFlow()
private val mutableInterval = MutableStateFlow(1_000L)
val intervalMs = mutableInterval.asStateFlow()
@@ -100,6 +120,7 @@ class TftService : Service() {
override fun onCreate() {
super.onCreate()
mutableInterval.value = getSharedPreferences("tft", MODE_PRIVATE).getLong("interval_ms", 1_000).coerceIn(500, 3_000)
tftZoomOffset = TftCameraPolicy.stepOffset(getSharedPreferences("tft_camera", MODE_PRIVATE).getFloat("zoom_offset", 0f).toDouble(), 0)
voice = NavigationVoiceController(this).also { controller ->
mutableVoiceEnabled.value = controller.enabled.value
scope.launch { controller.status.collect { mutableVoiceStatus.value = it } }
@@ -223,7 +244,7 @@ class TftService : Service() {
while (isActive) { delay(30_000); lock.acquire(120_000) }
}
TftSessionRunner(
transportFactory = { NaviLiteTransport(applicationContext, address) },
transportFactory = { NaviLiteTransport(applicationContext, address, ::onDashboardRequest) },
latestFrame = { requireNotNull(mutableFrame.value) },
policy = { TftSessionPolicy(effectiveInterval()) },
clockMs = { SystemClock.elapsedRealtime() },
@@ -369,7 +390,7 @@ class TftService : Service() {
else DemoNavigation.stateAt(now - start, startEpoch)
latestNavigationState = if (map) withRoute(simulated, true) else simulated
scheduler.offer(latestNavigationState)
val ready = scheduler.takeIfDue(now) ?: if (map && mapRetryAt > 0 && now >= mapRetryAt) latestNavigationState else null
val ready = scheduler.takeIfDue(now) ?: if (map && ((mapRetryAt > 0 && now >= mapRetryAt) || consumeForcedRedraw())) latestNavigationState else null
if (ready != null) {
publishFrame(renderNavigationFrame(ready, mode))
scheduler.markRendered(ready, SystemClock.elapsedRealtime())
@@ -451,7 +472,7 @@ class TftService : Service() {
checkSpeedCameras(state, now)
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && reroutePolicy.shouldRequest(state, now)) requestReroute(false)
scheduler.offer(state)
val ready = scheduler.takeIfDue(now) ?: if (map && mapRetryAt > 0 && now >= mapRetryAt) latestNavigationState else null
val ready = scheduler.takeIfDue(now) ?: if (map && ((mapRetryAt > 0 && now >= mapRetryAt) || consumeForcedRedraw())) latestNavigationState else null
if (ready != null) {
publishFrame(renderNavigationFrame(ready, mode))
scheduler.markRendered(ready, SystemClock.elapsedRealtime())
@@ -576,16 +597,94 @@ class TftService : Service() {
if (generation == preparedGeneration && routePreview) publishFrame(frame)
}
}
/** Import never contacts a routing server or replaces active guidance before Start. */
/** Import never replaces active guidance before Start; a raw trace never contacts a routing server. */
fun prepareImportedRoute(imported: ImportedRoute) {
require(imported.route.imported && imported.route.maneuvers.isEmpty())
require(imported.route.imported && !imported.needsRoadRouting)
RouteGuidanceTracker(imported.route) // Validate before invalidating an existing plan.
invalidateRoutePlan()
routePlan = RoutePlan(imported.route, imported.route.geometry.first(), false)
preparedDestinationDirty = false
mutableRouteInfo.value = "GPX · %.1f km · %d puntos\nSigue el trazado: sin instrucciones de giro, ETA ni recálculo automático. Revisa el recorrido antes de iniciar.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, imported.route.geometry.size)
mutableRouteInfo.value = if (imported.route.maneuvers.isNotEmpty())
"GPX por carreteras · %.1f km · %d min\nIndicaciones de giro activas. Si te desvías, vuelve a la ruta: no se recalcula para respetar tus puntos.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, (imported.route.durationSeconds + 59) / 60)
else "Traza GPX · %.1f km · %d puntos\nSigue el trazado: sin indicaciones de giro ni ETA. Revisa el recorrido antes de iniciar.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, imported.route.geometry.size)
if (!hasActiveGuidance()) showPreparedPreview()
}
/** Join GPX route points, waypoints or a sparse track along roads; a detailed track is followed as is. */
fun calculateImportedStops(imported: ImportedRoute, onReady: () -> Unit = {}) {
if (!imported.needsRoadRouting) { prepareImportedRoute(imported); onReady(); return }
invalidateRoutePlan() // Never offer the straight lines between stops as a route.
val generation = preparedGeneration
// A sparse recorded track may follow motorways; planned stops keep the scenic default.
val options = if (imported.isTrack) RouteOptions(profile = RouteProfile.FASTEST, avoidUnpaved = true) else RouteOptions(profile = RouteProfile.AVOID_MOTORWAYS, avoidMotorways = true, avoidUnpaved = true)
mutableRouteInfo.value = "Calculando la ruta por carreteras · ${imported.stops.size} puntos…"
routeJob?.cancel()
routeJob = scope.launch {
try {
val result = routingEngineFactory(routingEndpoint()).calculateRouteThrough(imported.stops, options)
ensureActive()
if (generation != preparedGeneration) return@launch
if (result.geometry.size !in 2..100_000) throw IllegalArgumentException("Geometría de ruta inválida")
prepareImportedRoute(ImportedRoute(imported.name, result.copy(imported = true), isTrack = imported.isTrack))
onReady()
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (generation == preparedGeneration)
mutableRouteInfo.value = if (error is RoutingHttpException && error.status == 429) "No se pudo calcular: servidor de rutas ocupado. Espera un minuto y pulsa Reintentar."
else "No se pudo calcular la ruta por carreteras. Comprueba la conexión a Internet y pulsa Reintentar."
}
}
}
/**
* Before starting an imported route away from its first point, prepend a road leg from the
* current position. [onReady] receives false when that leg could not be calculated.
*/
fun prepareImportedApproach(onReady: (Boolean) -> Unit) {
val plan = routePlan?.takeIf { !preparedDestinationDirty && it.route.imported } ?: return onReady(true)
val base = plan.importedBase ?: plan.route
val position = lastGpsFix?.position?.takeIf { hasGuidanceGpsFix() } ?: return onReady(false)
if (!needsApproach(position, base)) { if (plan.importedBase != null) routePlan = plan.copy(route = base, origin = base.geometry.first(), importedBase = null); return onReady(true) }
val generation = preparedGeneration
mutableRouteInfo.value = "Calculando el camino hasta el inicio del GPX…"
routeJob?.cancel()
routeJob = scope.launch {
try {
val approach = routingEngineFactory(routingEndpoint()).calculateRoute(position, base.geometry.first(), APPROACH_OPTIONS)
ensureActive()
if (generation != preparedGeneration || routePlan !== plan) return@launch
val route = prependApproach(approach, base)
RouteGuidanceTracker(route) // Validate before replacing the plan.
routePlan = plan.copy(route = route, origin = position, importedBase = base)
mutableRouteInfo.value = "Camino hasta el inicio del GPX calculado · %.1f km".format(java.util.Locale.ROOT, approach.distanceMeters / 1000.0)
onReady(true)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Exception) {
if (generation == preparedGeneration && routePlan === plan) { routePlan = plan.copy(route = base, origin = base.geometry.first(), importedBase = null); mutableRouteInfo.value = "Sin camino hasta el inicio del GPX · dirígete al primer punto"; onReady(false) }
}
}
}
/** Positive steps zoom in. Called from the phone and from handlebar requests. */
fun adjustTftZoom(steps: Int) {
val next = TftCameraPolicy.stepOffset(tftZoomOffset, steps)
if (next == tftZoomOffset) { mutableTftZoomInfo.value = if (steps > 0) "Zoom máximo" else "Zoom mínimo"; return }
tftZoomOffset = next
getSharedPreferences("tft_camera", MODE_PRIVATE).edit().putFloat("zoom_offset", next.toFloat()).apply()
mutableTftZoomInfo.value = "Zoom TFT %+.1f".format(java.util.Locale("es", "ES"), next)
forceMapRedraw = true
if (routePreview && shownRoute != null && navigationJob?.isActive != true) showPreparedPreview()
}
private fun consumeForcedRedraw(): Boolean = forceMapRedraw.also { forceMapRedraw = false }
private fun onDashboardRequest(service: Int, payloadSize: Int) {
android.util.Log.i("NavFrame", "NAVILITE_REQUEST service=$service bytes=$payloadSize")
scope.launch {
dashboardRequests[service] = (dashboardRequests[service] ?: 0) + 1
when (service) {
NaviLiteTransport.ZOOM_IN_REQUEST -> adjustTftZoom(1)
NaviLiteTransport.ZOOM_OUT_REQUEST -> adjustTftZoom(-1)
}
}
}
fun preparedRouteIsImported() = hasPreparedRoute() && routePlan?.route?.imported == true
fun hasPreparedRoute() = !preparedDestinationDirty && routePlan != null
fun routeUsesGps() = !preparedDestinationDirty && routePlan?.demo == false
@@ -606,9 +705,12 @@ class TftService : Service() {
reroutePolicy.reset()
rerouteFailures = 0
reroutePaused = false
approachDone = false
importedProgressMeters = 0.0
if (plan.demo) startDemo(true, preserveRoute = true) else startGps(true, preserveRoute = true)
if (plan.route.imported) {
mutableRouteInfo.value = "GPX iniciado · GPS real · %.1f km\nSigue el trazado · sin giros anunciados, ETA ni recálculo automático.".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
mutableRouteInfo.value = if (plan.route.maneuvers.isNotEmpty()) "Ruta GPX iniciada · %.1f km · indicaciones de giro activas".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
else "Traza GPX iniciada · %.1f km · sigue el trazado".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
return
}
mutableRouteInfo.value = "${if (preview) "Vista previa" else "Guiado iniciado"} · ${if (plan.demo) "posición DEMO simulada" else "GPS real"} · %.1f km · %d min planificados\nGuiado por geometría · ETA estimada. ${if (plan.demo) "Recorrido DEMO ficticio, sin GPS real ni recálculo automático." else "Recálculo por desvío sostenido; no sustituye señales viales."}".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0, (plan.route.durationSeconds + 59) / 60)
@@ -644,13 +746,40 @@ class TftService : Service() {
val fix = lastGpsFix ?: return state.copy(route = plan.route, navigationStatus = NavigationStatus.GPS_LOST)
requireNotNull(guidance).update(fix, SystemClock.elapsedRealtime(), System.currentTimeMillis(), SystemClock.elapsedRealtime() - lastGpsElapsed)
}
if (!demo && plan.route.imported) trackImportedProgress(plan, guided)
return if (rerouteJob?.isActive == true && guided.navigationStatus != NavigationStatus.GPS_LOST) guided.copy(navigationStatus = NavigationStatus.REROUTING, nextManeuver = null, distanceToNextManeuverMeters = null, remainingDistanceMeters = null, etaEpochMillis = null) else guided
}
private fun trackImportedProgress(plan: RoutePlan, state: NavigationState) {
val base = plan.importedBase ?: plan.route
val length = importedLength(base)
val remaining = state.remainingDistanceMeters
if (state.navigationStatus != NavigationStatus.OFF_ROUTE && remaining != null && remaining <= length) {
approachDone = true
importedProgressMeters = maxOf(importedProgressMeters, length - remaining)
}
// Off the route, passing close to a later point and heading on counts as having reached it.
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && (approachDone || plan.importedBase == null))
passedAlong(base, state.position, importedProgressMeters)?.let { importedProgressMeters = maxOf(importedProgressMeters, it) }
}
fun requestReroute(manual: Boolean = true) {
val plan = shownRoute ?: return
if (plan.route.imported) {
if (manual) mutableRouteInfo.value = "Ruta GPX · vuelve al trazado; no se modifica ni recalcula la ruta importada."
// An imported route is never replaced: only the way back to it is calculated. Before reaching
// it, that is its first point; afterwards, the nearest point ahead of the progress made.
if (plan.route.imported && manual && latestNavigationState.navigationStatus != NavigationStatus.OFF_ROUTE) {
if (rerouteJob?.isActive != true) mutableRouteInfo.value = "Ruta GPX · se recalcula el camino de vuelta solo cuando te desvías."
return
}
val rejoin = if (!plan.route.imported) null else {
val base = plan.importedBase ?: plan.route
val position = lastGpsFix?.position
if (plan.importedBase != null && !approachDone) base
else position?.let { rejoinRemainder(base, it, importedProgressMeters) }
}
if (plan.route.imported && rejoin == null) {
if (manual) mutableRouteInfo.value = "Ruta GPX · estás cerca del final; continúa hasta el último punto."
else SystemClock.elapsedRealtime().let { if (reroutePolicy.shouldRequest(latestNavigationState, it)) { reroutePolicy.markRequested(it); reroutePolicy.markFinished(it) } } // Cool down.
return
}
if (plan.demo || routePreview || rerouteJob?.isActive == true) return
@@ -673,10 +802,14 @@ class TftService : Service() {
rerouteJob = scope.launch {
var retryAfterMs = 0L
try {
val result = routingEngineFactory(routingEndpoint()).calculateRoute(fix.position, plan.route.destination ?: plan.route.geometry.last(), plan.options)
val engine = routingEngineFactory(routingEndpoint())
val result = if (rejoin != null) prependApproach(engine.calculateRoute(fix.position, rejoin.geometry.first(), APPROACH_OPTIONS), rejoin)
else engine.calculateRoute(fix.position, plan.route.destination ?: plan.route.geometry.last(), plan.options)
ensureActive()
if (epoch != navigationEpoch || generation != routeGeneration || shownRoute !== plan) return@launch
val replacement = RoutePlan(result, fix.position, false, plan.options)
val replacement = RoutePlan(result, fix.position, false, plan.options, rejoin)
// A new base starts where the rider rejoins: the route has been reached.
if (rejoin != null && rejoin !== plan.importedBase) { importedProgressMeters = 0.0; approachDone = true }
shownRoute = replacement
if (!preparedDestinationDirty && routePlan === plan) routePlan = replacement
guidance = RouteGuidanceTracker(result)
@@ -717,7 +850,7 @@ class TftService : Service() {
val age = if (fix == null) "SIN FIX" else if (SystemClock.elapsedRealtime() - lastGpsElapsed <= 15_000) "RECIENTE" else "CADUCADO"
val network = when (mapRenderer?.networkConnected ?: lastMapNetworkConnected) { true -> "CONECTADA"; false -> "SIN CONEXIÓN"; null -> "SIN COMPROBAR" }
val historyWarning = if (mapHistoryWriteFailed) "\nHistorial persistente: último evento no guardado (TFT_MAP_HISTORY_WRITE_FAILED)." else ""
return "NavFrame ${BuildConfig.VERSION_NAME} · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\nRed TFT: $network\n${mutableMapDiagnostic.value}\nÚltimo fallo: $lastMapFailureDiagnostic\nGPS: $age · precisión $accuracy · ${mutableNavigationState.value.navigationStatus}\nTFT: ${mutableState.value} · modo ${mutableMode.value}\nSin coordenadas, consultas, direcciones ni URLs.$historyWarning"
return "NavFrame ${BuildConfig.VERSION_NAME} · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\nRed TFT: $network\n${mutableMapDiagnostic.value}\nÚltimo fallo: $lastMapFailureDiagnostic\nGPS: $age · precisión $accuracy · ${mutableNavigationState.value.navigationStatus}\nTFT: ${mutableState.value} · modo ${mutableMode.value}\nZoom TFT: ${"%+.1f".format(java.util.Locale.ROOT, tftZoomOffset)} · peticiones de la moto: ${dashboardRequests.entries.joinToString { "${it.key}×${it.value}" }.ifEmpty { "ninguna" }}\nSin coordenadas, consultas, direcciones ni URLs.$historyWarning"
}
fun isRealSessionRequested(): Boolean = realRequested
fun isGpsSessionActive(): Boolean = gpsRequested
@@ -777,6 +910,7 @@ class TftService : Service() {
if (next == previous) return
// Release the previous local archive even if restarting GPS fails permission/provider checks.
mapRenderer?.close(); mapRenderer = null
releaseMapFallback(); onlineRetryAt = 0
when (mutableMode.value) {
NavigationMode.MAP_DEMO -> if (routePreview && shownRoute != null) showPreparedPreview() else startDemo(true, preserveRoute = true)
NavigationMode.MAP_GPS -> if (routePreview && !gpsRequested && shownRoute != null) showPreparedPreview() else startGps(true, preserveRoute = true)
@@ -791,16 +925,20 @@ class TftService : Service() {
}
val now = SystemClock.elapsedRealtime()
if (mapRetryAt > now) return MapFrameComposer().compose(null, null, state, mode, source.attribution, unavailable = true, failureCode = mutableMapDiagnostic.value.split(" · ").getOrNull(1)).also { unavailableMapFrame = it }
val online = !source.uri.startsWith("file:")
if (online && now < onlineRetryAt) offlineFallbackFrame(state, mode)?.let { return it }
mapRenderStarted = SystemClock.elapsedRealtime()
mapRenderStage = MapRenderStage.INITIALIZE
try {
val frame = mapRenderOverride?.invoke(state, mode) ?: run {
val current = mapRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution, applicationContext)) { stage ->
val current = mapRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution, applicationContext), { tftZoomOffset }) { stage ->
mapRenderStage = stage
mutableMapDiagnostic.value = "TFT MAP · ${stage.name} · ${if (source.uri.startsWith("file:")) "LOCAL" else "ONLINE"}"
}.also { mapRenderer = it }
current.render(state, mode)
}
onlineRetryAt = 0
releaseMapFallback()
if (mapFailures > 0) recordMapEvent(MapDiagnosticKind.RECOVERED, state, mode, source, retryMs = 0)
mutableMapDiagnostic.value = "TFT MAP · OK · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · 480×240"
mapFailures = 0
@@ -810,11 +948,62 @@ class TftService : Service() {
return frame
} catch (cancelled: CancellationException) {
currentCoroutineContext().ensureActive() // A local map timeout is recoverable; STOP is not.
return mapUnavailable(state, mode, source, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage))
return onlineFailed(state, mode, source, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage))
} catch (error: Exception) {
return mapUnavailable(state, mode, source, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName)))
return onlineFailed(state, mode, source, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName)))
}
}
/**
* A still snapshot fails as a whole when any tile request fails, which is common with
* patchy mobile coverage. Prefer an installed offline map over an error frame.
*/
private suspend fun onlineFailed(state: NavigationState, mode: NavigationMode, source: TileSource, error: MapRenderException): TftFrame {
if (source.uri.startsWith("file:")) return mapUnavailable(state, mode, source, error)
android.util.Log.w("NavFrame", "MAP_ONLINE_FAILED code=${error.failure.name} stage=${error.stage.name} detail=${error.detail.safeText()}")
mapRenderer?.close(); mapRenderer = null
onlineRetryAt = SystemClock.elapsedRealtime() + ONLINE_RETRY_MS
lastMapFailureDiagnostic = "TFT MAP · ${error.failure.name} · ${error.stage.name} · ${error.detail.safeText()} · ONLINE"
val frame = offlineFallbackFrame(state, mode)
if (frame != null) return frame
onlineRetryAt = 0
return mapUnavailable(state, mode, source, error)
}
private suspend fun offlineFallbackFrame(state: NavigationState, mode: NavigationMode): TftFrame? {
val now = SystemClock.elapsedRealtime()
if (offlineSourcesAt == 0L || now - offlineSourcesAt > 60_000) {
offlineSourcesAt = now
offlineSources = try {
val packs = OfflineMapManager(applicationContext).let { it.refresh(); it.packs.value }
.filter { it.state == OfflinePackState.READY }
.map { RegionalBounds(it.bounds.south, it.bounds.west, it.bounds.north, it.bounds.east) to it.source }
val regions = RegionalPackManager(applicationContext).let { it.refresh(); RegionalPackManager.latest(it.regions.value) }
.map { it.manifest.bounds to it.source }
packs + regions
} catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { emptyList() }
}
val position = state.position
val source = offlineSources.firstOrNull { (bounds, _) -> position.latitude in bounds.south..bounds.north && position.longitude in bounds.west..bounds.east }?.second
?: return null
if (fallbackUri != source.uri) releaseMapFallback()
mapRenderStarted = SystemClock.elapsedRealtime()
return try {
val renderer = fallbackRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(source.uri, source.attribution, applicationContext), { tftZoomOffset })
.also { fallbackRenderer = it; fallbackUri = source.uri }
renderer.render(state, mode).also {
mutableMapDiagnostic.value = "TFT MAP · OFFLINE DE RESPALDO · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · reintento online en ${ONLINE_RETRY_MS / 1000} s"
mapFailures = 0; mapRetryAt = 0; unavailableMapFrame = null
}
} catch (cancelled: CancellationException) {
currentCoroutineContext().ensureActive()
releaseMapFallback(); null
} catch (_: Exception) { releaseMapFallback(); null }
}
/** Closes the offline fallback renderer, for example before deleting its archive. */
fun releaseMapFallback() {
fallbackRenderer?.close(); fallbackRenderer = null; fallbackUri = null
// Do not rescan (and reopen) packs that may be in the middle of being deleted.
offlineSources = emptyList(); offlineSourcesAt = SystemClock.elapsedRealtime()
}
private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, source: TileSource, error: MapRenderException): TftFrame {
lastMapNetworkConnected = mapRenderer?.networkConnected ?: lastMapNetworkConnected
mapRenderer?.close()
@@ -870,7 +1059,7 @@ class TftService : Service() {
return Notification.Builder(this, "tft")
.setSmallIcon(android.R.drawable.ic_menu_compass)
.setContentTitle("NavFrame · Yamaha TFT")
.setContentText(if (realRequested) "$notificationText · ${mutableMode.value}" else "GPS activo · sin conexión TFT")
.setContentText(if (realRequested) notificationText + when (mutableMode.value) { NavigationMode.GPS, NavigationMode.MAP_GPS -> " · navegando"; NavigationMode.DEMO, NavigationMode.MAP_DEMO -> " · simulación"; NavigationMode.IDLE -> "" } else "GPS activo · sin conexión TFT")
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true)
.addAction(Notification.Action.Builder(null, "Detener todo", stop).build()).build()
}
@@ -885,6 +1074,7 @@ class TftService : Service() {
navigationJob?.cancel()
mapRenderer?.close()
mapRenderer = null
releaseMapFallback()
try { locationProvider?.close() } catch (_: SecurityException) { }
locationProvider = null
scope.cancel() // Cancelling runner closes its socket in NonCancellable cleanup.
@@ -893,9 +1083,11 @@ class TftService : Service() {
super.onDestroy()
}
companion object {
private const val ONLINE_RETRY_MS = 30_000L
const val ACTION_REAL = "dev.navframe.CONNECT_REAL"
const val ACTION_GPS = "dev.navframe.START_GPS"
const val ACTION_MAP_GPS = "dev.navframe.START_MAP_GPS"
private val APPROACH_OPTIONS = RouteOptions(profile = RouteProfile.FASTEST, avoidUnpaved = true)
const val ACTION_ROUTE_GPS = "dev.navframe.START_ROUTE_GPS"
const val ACTION_STOP_NAVIGATION = "dev.navframe.STOP_NAVIGATION"
const val ACTION_STOP = "dev.navframe.DISCONNECT"
@@ -13,13 +13,29 @@ import kotlin.coroutines.resumeWithException
class RoutingHttpException(val status: Int, val retryAfterMs: Long) : IOException("Servidor de rutas: HTTP $status")
/** Explicit prototype requests only. No automatic recalc, request retry or location history. */
/** Explicit requests only. No automatic recalc, request retry or location history. */
class ValhallaRoutingEngine(private val endpoint: String, private val clientId: String, private val language: () -> String = { "es-ES" }, private val openConnection: (String) -> HttpURLConnection = { URI(it).toURL().openConnection() as HttpURLConnection }) : RoutingEngine {
init { validateEndpoint(endpoint) }
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
validatePoint(origin); validatePoint(destination)
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult =
calculateChunk(listOf(origin, destination), options)
/** Consecutive requests of at most [MAX_REQUEST_LOCATIONS] stops, sharing their boundary stop. */
override suspend fun calculateRouteThrough(stops: List<GeoPoint>, options: RouteOptions): RouteResult {
require(stops.size >= 2) { "Se necesitan al menos dos puntos" }
val parts = ArrayList<RouteResult>()
var start = 0
while (start < stops.lastIndex) {
val end = minOf(start + MAX_REQUEST_LOCATIONS - 1, stops.lastIndex)
parts += calculateChunk(stops.subList(start, end + 1), options)
start = end
}
return mergeRouteLegs(parts).copy(destination = stops.last())
}
private suspend fun calculateChunk(stops: List<GeoPoint>, options: RouteOptions): RouteResult {
stops.forEach(::validatePoint)
val destination = stops.last()
val locale = GuidanceLanguage.resolve(language()).tag
val body = buildValhallaRequest(origin, destination, options, locale)
val body = buildValhallaRequest(stops, options, locale)
val response = withTimeout(25_000) {
rateGate.withLock {
val wait = 1_000 - (System.nanoTime() / 1_000_000 - lastRequestMs)
@@ -46,7 +62,7 @@ class ValhallaRoutingEngine(private val endpoint: String, private val clientId:
http.connectTimeout = 10_000; http.readTimeout = 15_000
http.instanceFollowRedirects = false
http.setRequestProperty("Content-Type", "application/json; charset=utf-8")
http.setRequestProperty("User-Agent", "NavFrame/0.5 (Android prototype)")
http.setRequestProperty("User-Agent", "NavFrame/${BuildConfig.VERSION_NAME} (Android)")
http.setRequestProperty("X-Client-Id", clientId)
http.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
val status = http.responseCode
@@ -25,7 +25,22 @@ import java.time.Duration
@LooperMode(LooperMode.Mode.PAUSED)
class ImportedRouteTest {
class PhoneWithoutGpu : MainActivity() { override fun createPhoneMap(savedState: Bundle?): PhoneMapView? = null }
private fun imported() = GpxRouteImporter.parse("""<gpx><rte><name>Weekend</name><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/></rte></gpx>""".byteInputStream())
/** A detailed trace (about 11 m between points) is followed as is, without a routing server. */
private fun imported() = GpxRouteImporter.parse(("<gpx><trk><name>Weekend</name><trkseg>" +
(0..90).joinToString("") { "<trkpt lat=\"${43.36 + it * 0.0001}\" lon=\"-5.85\"/>" } + "</trkseg></trk></gpx>").byteInputStream())
private class RoadEngine(val fail: Boolean = false) : RoutingEngine {
val requests = mutableListOf<Pair<GeoPoint, GeoPoint>>()
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
requests += origin to destination
if (fail) throw java.io.IOException("offline")
val bend = GeoPoint((origin.latitude + destination.latitude) / 2, origin.longitude + 0.002)
return RouteResult(listOf(origin, bend, destination), listOf(
Maneuver("Gire a la derecha", 600, type = 10, beginShapeIndex = 1, endShapeIndex = 2),
Maneuver("Ha llegado", 0, type = 4, beginShapeIndex = 2, endShapeIndex = 2),
), 1_200, 120, destination)
}
override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = error("unused")
}
private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
private fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true }
@@ -59,7 +74,7 @@ class ImportedRouteTest {
assertTrue(service.hasActiveGuidance())
assertSame(route.route, service.navigationState.value.route)
service.requestReroute(); tick()
assertTrue(service.routeInfo.value.contains("no se modifica"))
assertTrue(service.routeInfo.value.contains("solo cuando te desvías"))
assertSame(route.route, service.navigationState.value.route)
assertNull(service.navigationState.value.nextManeuver)
assertNull(service.navigationState.value.etaEpochMillis)
@@ -127,8 +142,17 @@ class ImportedRouteTest {
try {
shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
field("service").set(activity, service)
importDocument("""<gpx><rte><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/></rte></gpx>""")
val engine = RoadEngine()
service.routingEngineFactory = { engine }
importDocument("""<gpx><rte><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/><rtept lat="43.38" lon="-5.85"/></rte></gpx>""")
tick()
// Route points are joined along roads, keeping turn instructions, never by straight lines.
assertEquals(2, engine.requests.size)
assertTrue(service.preparedRouteIsImported())
val routed = requireNotNull(service.navigationState.value.route)
assertEquals(5, routed.geometry.size)
assertEquals(listOf(10, 10, 4), routed.maneuvers.map { it.type })
assertEquals(GeoPoint(43.38, -5.85), routed.destination)
assertEquals("IMPORT_ROUTE", (field("pendingAction").get(activity) as Enum<*>).name)
assertFalse(service.hasActiveGuidance())
val oldRoute = service.navigationState.value.route
@@ -182,6 +206,7 @@ class ImportedRouteTest {
assertTrue(service.gpsReady.value)
assertTrue(service.hasFreshGpsFix())
assertFalse(service.hasGuidanceGpsFix())
MainActivity::class.java.getDeclaredMethod("showImportedRouteSheet", String::class.java).apply { isAccessible = true }.invoke(activity, "Weekend")
MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity)
val pending = field("positionWait").get(activity) as kotlinx.coroutines.Job
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
@@ -197,4 +222,107 @@ class ImportedRouteTest {
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun failedRoadCalculationNeverOffersStraightLinesAndCanBeRetried() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
val stops = GpxRouteImporter.parse("""<gpx><rte><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/></rte></gpx>""".byteInputStream())
assertTrue(stops.needsRoadRouting)
service.routingEngineFactory = { RoadEngine(fail = true) }
var ready = false
service.calculateImportedStops(stops) { ready = true }; tick()
assertFalse(ready)
assertFalse(service.hasPreparedRoute())
assertTrue(service.routeInfo.value.startsWith("No se pudo"))
service.routingEngineFactory = { RoadEngine() }
service.calculateImportedStops(stops) { ready = true }; tick()
assertTrue(ready)
assertTrue(service.preparedRouteIsImported())
assertEquals(3, service.navigationState.value.route?.geometry?.size)
} finally { controller.destroy() }
}
@Test fun importedStartAwayFromTheFirstPointRoutesThereFirst() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
val application = RuntimeEnvironment.getApplication()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
field("service").set(activity, service)
val manager = application.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
val route = imported()
service.prepareImportedRoute(route); tick()
service.setPhoneVisible(true); tick()
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 43.35; longitude = -5.85; accuracy = 5f // About 1.1 km before the first point.
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
val engine = RoadEngine()
service.routingEngineFactory = { engine }
MainActivity::class.java.getDeclaredMethod("showImportedRouteSheet", String::class.java).apply { isAccessible = true }.invoke(activity, "Weekend")
MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity); tick()
assertEquals(listOf(GeoPoint(43.35, -5.85) to route.route.geometry.first()), engine.requests)
assertEquals(TftService.ACTION_ROUTE_GPS, shadowOf(activity).nextStartedService.action)
service.startRoute(); tick()
val started = service.navigationState.value.route!!
assertEquals(GeoPoint(43.35, -5.85), started.geometry.first())
assertEquals(route.route.geometry.last(), started.geometry.last())
assertTrue(started.maneuvers.isEmpty())
assertNull(service.navigationState.value.etaEpochMillis)
// Leaving the leg to the first point recalculates only that leg.
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 43.34; longitude = -5.84; accuracy = 5f
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
service.requestReroute(false); tick()
assertEquals(GeoPoint(43.34, -5.84) to route.route.geometry.first(), engine.requests.last())
val shown = TftService::class.java.getDeclaredField("shownRoute").apply { isAccessible = true }.get(service)!!
val rerouted = shown.javaClass.getDeclaredMethod("getRoute").apply { isAccessible = true }.invoke(shown) as RouteResult
assertEquals(GeoPoint(43.34, -5.84), rerouted.geometry.first())
assertEquals(route.route.geometry.last(), rerouted.geometry.last())
assertTrue(rerouted.imported)
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun deviationFromAnImportedTraceRoutesBackToTheNearestPointAhead() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
val application = RuntimeEnvironment.getApplication()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
val manager = application.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
fun fix(latitude: Double, longitude: Double) {
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
this.latitude = latitude; this.longitude = longitude; accuracy = 5f
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
}
val route = imported()
service.prepareImportedRoute(route); tick()
service.setPhoneVisible(true); tick()
fix(43.36, -5.85)
service.startRoute(); tick()
assertTrue(service.hasActiveGuidance())
val engine = RoadEngine()
service.routingEngineFactory = { engine }
fix(43.365, -5.847) // About 240 m east of the trace's midpoint.
service.requestReroute(false); tick()
assertEquals(GeoPoint(43.365, -5.847) to GeoPoint(43.365, -5.85), engine.requests.single())
val shown = TftService::class.java.getDeclaredField("shownRoute").apply { isAccessible = true }.get(service)!!
val rerouted = shown.javaClass.getDeclaredMethod("getRoute").apply { isAccessible = true }.invoke(shown) as RouteResult
assertEquals(GeoPoint(43.365, -5.847), rerouted.geometry.first())
assertEquals(route.route.geometry.last(), rerouted.geometry.last())
assertTrue(rerouted.imported)
assertTrue(rerouted.maneuvers.isEmpty())
} finally { controller.destroy() }
}
}
@@ -43,7 +43,7 @@ class NominatimGeocoderTest {
assertFalse(url.contains("viewbox")); assertFalse(url.contains("lat=")); assertFalse(url.contains("lon="))
assertTrue(result.name.contains("Asturias"))
assertTrue(result.attribution.contains("OpenStreetMap"))
assertTrue(http.getRequestProperty("User-Agent").startsWith("NavFrame/0.6"))
assertTrue(http.getRequestProperty("User-Agent").startsWith("NavFrame/${BuildConfig.VERSION_NAME} "))
}
@Test fun cancellingSearchClosesItsConnectionAndBlockingRead() = runBlocking {
val http = Connection(block = true)
@@ -58,6 +58,12 @@ data class RouteOptions(
interface RoutingEngine {
suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult
suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions): RouteResult
/** Route along roads through ordered stops. The default joins independent legs. */
suspend fun calculateRouteThrough(stops: List<GeoPoint>, options: RouteOptions): RouteResult {
require(stops.size >= 2) { "At least two stops are required" }
return mergeRouteLegs(stops.zipWithNext().map { (from, to) -> calculateRoute(from, to, options) })
.copy(destination = stops.last())
}
}
data class SearchResult(
val name: String,
@@ -9,12 +9,22 @@ import org.xml.sax.SAXException
import org.xml.sax.ext.DefaultHandler2
import kotlin.math.*
data class ImportedRoute(val name: String?, val route: RouteResult)
/**
* [stops] is non-empty when the geometry is a list of points to be joined along roads
* (route points, waypoints or a sparse track) rather than a trace that can be followed as is.
*/
data class ImportedRoute(val name: String?, val route: RouteResult, val isTrack: Boolean = false, val stops: List<GeoPoint> = emptyList()) {
val needsRoadRouting: Boolean get() = stops.size >= 2
}
/** Imports geometry only: GPX points do not establish road turns, speeds or travel time. */
object GpxRouteImporter {
const val MAX_BYTES = 5 * 1024 * 1024
const val MAX_POINTS = 10_000
/** Upper bound of points sent to the routing server for one import. */
const val MAX_STOPS = 400
/** Recorded or road-snapped traces are much denser; planners' hand-placed points are not. */
const val SPARSE_TRACK_MEDIAN_METERS = 250.0
const val MAX_DEPTH = 64
private val namespaces = setOf("", "http://www.topografix.com/GPX/1/0", "http://www.topografix.com/GPX/1/1")
@@ -49,18 +59,31 @@ object GpxRouteImporter {
if (points.size < 2) fail("El GPX necesita al menos dos puntos de ruta o track.")
val distance = points.zipWithNext().sumOf { (a, b) -> distance(a, b) }
if (!distance.isFinite() || distance <= 0.0) fail("El GPX necesita al menos dos puntos distintos.")
val stops = if (!handler.isTrack || isSparse(points)) downsample(points.filterIndexed { i, point -> i == 0 || point != points[i - 1] }) else emptyList()
return ImportedRoute(handler.name?.trim()?.takeIf { it.isNotEmpty() }, RouteResult(
geometry = points.toList(), maneuvers = emptyList(), distanceMeters = distance.roundToInt().coerceAtLeast(1),
durationSeconds = 0, destination = points.last(), imported = true,
))
), handler.isTrack, stops)
}
private fun isSparse(points: List<GeoPoint>): Boolean {
val gaps = points.zipWithNext().map { (a, b) -> distance(a, b) }.filter { it > 0.0 }.sorted()
return gaps.isNotEmpty() && gaps[gaps.size / 2] > SPARSE_TRACK_MEDIAN_METERS
}
/** Keep the endpoints and an even spread of the remaining points. */
private fun downsample(points: List<GeoPoint>): List<GeoPoint> {
if (points.size <= MAX_STOPS) return points
return (0 until MAX_STOPS).map { points[(it.toLong() * points.lastIndex / (MAX_STOPS - 1)).toInt()] }
}
private class Handler : DefaultHandler2() {
private val routePoints = mutableListOf<GeoPoint>()
private val trackPoints = mutableListOf<GeoPoint>()
private val waypoints = mutableListOf<GeoPoint>()
private var routeName: String? = null
private var trackName: String? = null
val points: List<GeoPoint> get() = if (tracks > 0) trackPoints else routePoints
val points: List<GeoPoint> get() = if (tracks > 0) trackPoints else if (routes > 0) routePoints else waypoints
val isTrack: Boolean get() = tracks > 0
val name: String? get() = if (tracks > 0) trackName else routeName
private val path = mutableListOf<String>()
private var rootNamespace = ""
@@ -87,15 +110,16 @@ object GpxRouteImporter {
}
if (path == listOf("gpx", "trk", "trkseg")) segmentPoints = 0
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) nameText = StringBuilder()
if (path == listOf("gpx", "rte", "rtept") || path == listOf("gpx", "trk", "trkseg", "trkpt")) {
if (routePoints.size + trackPoints.size >= MAX_POINTS) fail("El GPX supera los 10000 puntos. Simplifica la ruta antes de importarla.")
if (path == listOf("gpx", "rte", "rtept") || path == listOf("gpx", "trk", "trkseg", "trkpt") || path == listOf("gpx", "wpt")) {
if (routePoints.size + trackPoints.size + waypoints.size >= MAX_POINTS) fail("El GPX supera los 10000 puntos. Simplifica la ruta antes de importarla.")
val lat = attributes.getValue("lat")?.toDoubleOrNull()
val lon = attributes.getValue("lon")?.toDoubleOrNull()
if (lat == null || lon == null || !lat.isFinite() || !lon.isFinite() || lat !in -90.0..90.0 || lon !in -180.0..180.0) fail("El GPX contiene coordenadas inválidas.")
if (path[1] == "trk") {
trackPoints.add(GeoPoint(lat, lon))
segmentPoints++
} else routePoints.add(GeoPoint(lat, lon))
when (path[1]) {
"trk" -> { trackPoints.add(GeoPoint(lat, lon)); segmentPoints++ }
"rte" -> routePoints.add(GeoPoint(lat, lon))
else -> waypoints.add(GeoPoint(lat, lon))
}
}
}
override fun characters(ch: CharArray, start: Int, length: Int) {
@@ -22,6 +22,9 @@ data class GuidanceConfig(
}
}
/** Raw imported traces carry no travel time; road-routed imports keep the server's estimate. */
val RouteResult.hasEta: Boolean get() = !imported || durationSeconds > 0
/** Stateful projection/progress for one route. Create another tracker when replacing the route. */
class RouteGuidanceTracker(private val route: RouteResult, private val config: GuidanceConfig = GuidanceConfig()) {
private val line = RouteLine(route)
@@ -55,7 +58,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
val distinct = lastTimestamp != fix.timestampMs
if (!distinct) return lastState ?: base.copy(navigationStatus = NavigationStatus.GPS_LOST)
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (!route.hasEta) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) {
outside.reset(); arrival.reset(); rejoin.reset(); rejoinProgress = null
needsRecovery = false
@@ -119,7 +122,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
earthDistance(fix.position, route.geometry.last()) <= config.arrivalRadiusMeters
arrived = arrival.observe(close, distinct, nowMs, config.arrivalFixes, config.arrivalDurationMs)
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (!route.hasEta) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
return remember(line.guidedState(base, progress, epochMs))
}
}
@@ -154,9 +157,9 @@ class RouteDemo(private val route: RouteResult, private val speedMetersPerSecond
val base = NavigationState(position = position, bearing = bearing, speed = speedMetersPerSecond,
route = route, accuracyMeters = 3f)
if (progress >= line.total) return base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)
etaEpochMillis = if (!route.hasEta) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)
val state = line.guidedState(base, progress, epochMs)
return state.copy(etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
return state.copy(etaEpochMillis = if (!route.hasEta) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
}
}
@@ -249,7 +252,7 @@ private class RouteLine(private val route: RouteResult) {
val etaMs = (route.durationSeconds * 1000.0 * remaining / total).roundToLong()
return base.copy(nextManeuver = next?.first,
distanceToNextManeuverMeters = next?.let { (it.second - progress).coerceAtLeast(0.0).roundToInt() },
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, etaMs),
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (!route.hasEta) null else saturatedAdd(epochMs, etaMs),
navigationStatus = NavigationStatus.NAVIGATING)
}
fun pointAt(progress: Double): Pair<GeoPoint, Float> {
@@ -272,6 +275,57 @@ private class RouteLine(private val route: RouteResult) {
private fun validPoint(point: GeoPoint) = point.latitude.isFinite() && point.longitude.isFinite() &&
point.latitude in -90.0..90.0 && point.longitude in -180.0..180.0
private fun wrappedLongitude(value: Double): Double = ((value + 180) % 360 + 360) % 360 - 180
/** Farther than this from an imported route's first point, a road leg to it is prepended on start. */
const val IMPORTED_APPROACH_MIN_METERS = 150.0
fun needsApproach(position: GeoPoint, route: RouteResult): Boolean =
route.geometry.isNotEmpty() && earthDistance(position, route.geometry.first()) > IMPORTED_APPROACH_MIN_METERS
/** Length of [route]'s geometry in metres, as measured by guidance. */
fun routeLength(route: RouteResult): Double = route.geometry.zipWithNext().sumOf { (a, b) -> earthDistance(a, b) }
/**
* Off an imported route, passing within [radiusMeters] of a later point counts as having reached it:
* returns the furthest such distance along [route] in the [windowMeters] after [fromMeters], or null.
*/
fun passedAlong(route: RouteResult, position: GeoPoint, fromMeters: Double, radiusMeters: Double = 100.0, windowMeters: Double = 3_000.0): Double? {
var along = 0.0
var passed: Double? = null
route.geometry.forEachIndexed { i, point ->
if (i > 0) along += earthDistance(route.geometry[i - 1], point)
if (along > fromMeters + windowMeters) return passed
if (along >= fromMeters && earthDistance(position, point) <= radiusMeters) passed = along
}
return passed
}
/**
* The rest of [route] from its point nearest to [position] among those in the [windowMeters] after
* [fromMeters] (never behind it), with maneuvers rebased and distance/duration prorated. Null when
* only the final point is left.
*/
fun rejoinRemainder(route: RouteResult, position: GeoPoint, fromMeters: Double, windowMeters: Double = 10_000.0): RouteResult? {
val cumulative = DoubleArray(route.geometry.size)
for (i in 1 until route.geometry.size) cumulative[i] = cumulative[i - 1] + earthDistance(route.geometry[i - 1], route.geometry[i])
val total = cumulative.last()
val start = cumulative.indexOfFirst { it >= fromMeters }.takeIf { it >= 0 } ?: return null
var best = start
var bestDistance = Double.POSITIVE_INFINITY
for (i in start until route.geometry.size) {
if (cumulative[i] > fromMeters + windowMeters) break
val distance = earthDistance(position, route.geometry[i])
if (distance < bestDistance) { best = i; bestDistance = distance }
}
if (best >= route.geometry.lastIndex) return null
if (best == 0) return route
val share = if (total > 0) (total - cumulative[best]) / total else 0.0
return route.copy(
geometry = route.geometry.drop(best),
maneuvers = route.maneuvers.filter { (it.beginShapeIndex ?: -1) >= best }.map {
it.copy(beginShapeIndex = it.beginShapeIndex?.minus(best), endShapeIndex = it.endShapeIndex?.minus(best))
},
distanceMeters = (route.distanceMeters * share).roundToInt().coerceAtLeast(1),
durationSeconds = (route.durationSeconds * share).roundToInt(),
)
}
private fun earthDistance(a: GeoPoint, b: GeoPoint): Double {
val lat1 = Math.toRadians(a.latitude); val lat2 = Math.toRadians(b.latitude)
val dlat = lat2 - lat1; val dlon = Math.toRadians(wrappedLongitude(b.longitude - a.longitude))
@@ -4,20 +4,35 @@ package dev.navframe.core
data class TftCameraParameters(
val bearingDegrees: Float,
val zoom: Double,
val riderAnchorY: Float = 0.72f,
/** Rider position as a fraction of the frame height, measured from the top. */
val riderAnchorY: Float = 0.78f,
/** Perspective tilt; the road ahead stays visible further away than in a flat view. */
val pitchDegrees: Double = 0.0,
)
class TftCameraPolicy {
/**
* Wide enough to read the next bends before reaching them. [zoomOffset] is the rider's own
* adjustment (handlebar or phone controls), added to the speed-based level.
*/
class TftCameraPolicy(private val zoomOffset: Double = 0.0) {
fun parameters(state: NavigationState): TftCameraParameters {
val kmh = state.speed.coerceAtLeast(0f) * 3.6f
val approachingTurn = state.nextManeuver != null &&
state.distanceToNextManeuverMeters?.let { it in 0..150 } == true
val zoom = when {
approachingTurn -> 17.5
kmh < 30 -> 17.0
kmh <= 70 -> 16.0
else -> 15.0
state.distanceToNextManeuverMeters?.let { it in 0..200 } == true
val base = when {
approachingTurn -> 15.5
kmh < 30 -> 15.5
kmh <= 70 -> 15.0
else -> 14.5
}
return TftCameraParameters(normalizeBearing(state.bearing), zoom)
val zoom = (base + zoomOffset.coerceIn(MIN_OFFSET, MAX_OFFSET)).coerceIn(12.0, 18.0)
return TftCameraParameters(normalizeBearing(state.bearing), zoom, pitchDegrees = PITCH_DEGREES)
}
companion object {
const val PITCH_DEGREES = 45.0
const val ZOOM_STEP = 0.5
const val MIN_OFFSET = -2.0
const val MAX_OFFSET = 2.0
fun stepOffset(current: Double, steps: Int): Double = (current + steps * ZOOM_STEP).coerceIn(MIN_OFFSET, MAX_OFFSET)
}
}
@@ -9,22 +9,28 @@ import kotlin.math.roundToInt
private const val MAX_RESPONSE_CHARS = 2 * 1024 * 1024
private const val MAX_SHAPE_POINTS = 100_000
/** Public Valhalla instances commonly cap a request at 20 locations. */
const val MAX_REQUEST_LOCATIONS = 20
private val routeJson = GsonBuilder().setStrictness(Strictness.STRICT).create()
/** Original adapter; no Valhalla implementation code is embedded. Errors omit response contents. */
class ValhallaRouteException(message: String) : IllegalArgumentException(message)
/** Explicit coordinate request. The HTTP adapter owns rate limits, headers and cancellation. */
fun buildValhallaRequest(origin: GeoPoint, destination: GeoPoint, options: RouteOptions = RouteOptions(), language: String = "es-ES"): String {
validatePoint(origin)
validatePoint(destination)
fun buildValhallaRequest(origin: GeoPoint, destination: GeoPoint, options: RouteOptions = RouteOptions(), language: String = "es-ES"): String =
buildValhallaRequest(listOf(origin, destination), options, language)
/** Intermediate stops are `through` locations: one leg, no arrival announcements or U-turns at them. */
fun buildValhallaRequest(stops: List<GeoPoint>, options: RouteOptions = RouteOptions(), language: String = "es-ES"): String {
if (stops.size !in 2..MAX_REQUEST_LOCATIONS) invalid("Invalid routing location count")
stops.forEach(::validatePoint)
val request = JsonObject()
request.add("locations", JsonArray().apply {
listOf(origin, destination).forEach { point ->
stops.forEachIndexed { index, point ->
add(JsonObject().apply {
addProperty("lat", point.latitude)
addProperty("lon", point.longitude)
addProperty("type", "break")
addProperty("type", if (index == 0 || index == stops.lastIndex) "break" else "through")
})
}
})
@@ -153,6 +159,49 @@ fun parseValhallaRoute(json: String, destination: GeoPoint? = null): RouteResult
}
}
/**
* Join consecutive routes that share their boundary stop into one route. Maneuver indices are
* rebased onto the merged geometry and arrivals at intermediate boundaries are dropped.
*/
fun mergeRouteLegs(parts: List<RouteResult>): RouteResult {
require(parts.isNotEmpty()) { "No route parts" }
if (parts.size == 1) return parts.single()
val geometry = ArrayList<GeoPoint>()
val maneuvers = ArrayList<Maneuver>()
var meters = 0L
var seconds = 0L
parts.forEachIndexed { index, part ->
require(part.geometry.size >= 2) { "Route part has insufficient geometry" }
val skipFirst = geometry.isNotEmpty() && geometry.last() == part.geometry.first()
val offset = geometry.size - if (skipFirst) 1 else 0
geometry.addAll(if (skipFirst) part.geometry.drop(1) else part.geometry)
val last = index == parts.lastIndex
// Chunk boundaries are not real stops: drop their arrivals and the next chunk's depart (types 1-3).
part.maneuvers.filter { (last || maneuverDirection(it.type) != ManeuverDirection.ARRIVAL) && (index == 0 || it.type !in 1..3) }.mapTo(maneuvers) {
it.copy(beginShapeIndex = it.beginShapeIndex?.plus(offset), endShapeIndex = it.endShapeIndex?.plus(offset))
}
meters += part.distanceMeters
seconds += part.durationSeconds
}
if (geometry.size > MAX_SHAPE_POINTS + 1) invalid("Too many route shape points")
val surfaces = parts.map { it.hasUnpaved }
return parts.last().copy(geometry = geometry, maneuvers = maneuvers,
distanceMeters = meters.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(),
durationSeconds = seconds.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(),
hasUnpaved = if (true in surfaces) true else if (surfaces.all { it == false }) false else null,
guidanceLanguage = parts.first().guidanceLanguage)
}
/**
* Prefix [route] with a road leg from the rider's position to its first point. A trace stays a
* trace: no turn instructions or ETA, the leg only extends the line to follow.
*/
fun prependApproach(approach: RouteResult, route: RouteResult): RouteResult {
val merged = mergeRouteLegs(listOf(approach, route))
// Raw traces carry no travel time; road-routed imports keep it even if no maneuver is left ahead.
return if (route.imported && route.durationSeconds == 0) merged.copy(maneuvers = emptyList(), durationSeconds = 0) else merged
}
private fun validatePoint(point: GeoPoint) {
if (!point.latitude.isFinite() || !point.longitude.isFinite() ||
point.latitude !in -90.0..90.0 || point.longitude !in -180.0..180.0) invalid("Invalid routing coordinate")
@@ -34,8 +34,19 @@ class DemoNavigationTest {
assertTrue(fast.zoom < slow.zoom)
assertEquals(359f, slow.bearingDegrees)
assertEquals(1f, fast.bearingDegrees)
assertTrue(fast.riderAnchorY in 0.66f..0.8f)
assertTrue(fast.riderAnchorY in 0.7f..0.85f)
assertTrue(fast.pitchDegrees > 0)
val approaching = policy.parameters(NavigationState(speed = 25f, nextManeuver = Maneuver("derecha", 100), distanceToNextManeuverMeters = 100))
assertTrue(approaching.zoom > slow.zoom)
assertTrue(approaching.zoom > fast.zoom)
// Never so close that the bend after the turn is off screen.
assertTrue(approaching.zoom <= slow.zoom)
}
@Test fun riderZoomOffsetIsBoundedAndApplied() {
val state = NavigationState(speed = 10f)
val base = TftCameraPolicy().parameters(state).zoom
assertEquals(base + 1.0, TftCameraPolicy(1.0).parameters(state).zoom, 1e-9)
assertEquals(base + TftCameraPolicy.MAX_OFFSET, TftCameraPolicy(99.0).parameters(state).zoom, 1e-9)
assertEquals(TftCameraPolicy.MIN_OFFSET, TftCameraPolicy.stepOffset(-1.5, -3), 1e-9)
assertEquals(0.5, TftCameraPolicy.stepOffset(0.0, 1), 1e-9)
}
}
@@ -103,4 +103,27 @@ class GpxRouteImporterTest {
assertNull(outside.etaEpochMillis)
}
@Test fun `route points and waypoints are stops to join along roads`() {
val route = parse("<gpx><rte>$points<rtept lat=\"43.001\" lon=\"-5\"/></rte></gpx>")
assertTrue(route.needsRoadRouting)
// Consecutive duplicates would only produce zero-length legs.
assertEquals(listOf(GeoPoint(43.0, -5.0), GeoPoint(43.001, -5.0)), route.stops)
val waypoints = parse("<gpx><metadata/><wpt lat=\"43\" lon=\"-5\"/><wpt lat=\"43.2\" lon=\"-5.1\"/><wpt lat=\"43.4\" lon=\"-5\"/></gpx>")
assertFalse(waypoints.isTrack)
assertEquals(3, waypoints.stops.size)
}
@Test fun `detailed tracks are followed but sparse tracks are road routed`() {
fun track(step: Double, count: Int) = parse("<gpx><trk><trkseg>" +
(0 until count).joinToString("") { "<trkpt lat=\"${43 + it * step}\" lon=\"-5\"/>" } + "</trkseg></trk></gpx>")
val recorded = track(0.0002, 200) // About 22 m apart.
assertTrue(recorded.isTrack)
assertFalse(recorded.needsRoadRouting)
val planned = track(0.01, 30) // About 1.1 km apart: straight lines between clicks.
assertTrue(planned.needsRoadRouting)
assertEquals(30, planned.stops.size)
val long = track(0.004, 1_000)
assertEquals(GpxRouteImporter.MAX_STOPS, long.stops.size)
assertEquals(long.route.geometry.first(), long.stops.first())
assertEquals(long.route.geometry.last(), long.stops.last())
}
}
@@ -163,4 +163,72 @@ class ValhallaRouteTest {
try { block(); fail("Expected invalid routing data to be rejected") }
catch (_: ValhallaRouteException) { /* expected */ }
}
@Test fun `multi stop request routes through intermediate stops in one leg`() {
val stops = (0..4).map { GeoPoint(43.3 + it * 0.01, -5.8) }
val locations = JsonParser.parseString(buildValhallaRequest(stops)).asJsonObject.getAsJsonArray("locations")
assertEquals(listOf("break", "through", "through", "through", "break"), locations.map { it.asJsonObject["type"].asString })
assertEquals(43.32, locations[2].asJsonObject["lat"].asDouble, 1e-9)
try { buildValhallaRequest(List(MAX_REQUEST_LOCATIONS + 1) { stops[0] }); fail("Expected location limit") } catch (_: ValhallaRouteException) { }
}
@Test fun `merged legs rebase maneuvers and drop intermediate arrivals`() {
val a = GeoPoint(43.0, -5.0); val b = GeoPoint(43.01, -5.0); val c = GeoPoint(43.02, -5.0); val d = GeoPoint(43.03, -5.0)
fun part(from: GeoPoint, mid: GeoPoint, to: GeoPoint, unpaved: Boolean?) = RouteResult(listOf(from, mid, to), listOf(
Maneuver("start", 10, type = 1, beginShapeIndex = 0, endShapeIndex = 1),
Maneuver("right", 10, type = 10, beginShapeIndex = 1, endShapeIndex = 2),
Maneuver("arrive", 0, type = 4, beginShapeIndex = 2, endShapeIndex = 2),
), 1_000, 60, to, hasUnpaved = unpaved)
val merged = mergeRouteLegs(listOf(part(a, b, c, false), part(c, GeoPoint(43.025, -5.0), d, null)))
assertEquals(5, merged.geometry.size)
assertEquals(listOf(1, 10, 10, 4), merged.maneuvers.map { it.type })
assertEquals(listOf(0, 1, 3, 4), merged.maneuvers.map { it.beginShapeIndex })
assertEquals(2_000, merged.distanceMeters)
assertEquals(120, merged.durationSeconds)
assertNull(merged.hasUnpaved)
assertEquals(d, merged.destination)
// Independently snapped endpoints that do not coincide keep both points.
assertEquals(6, mergeRouteLegs(listOf(part(a, b, c, true), part(GeoPoint(43.0201, -5.0), GeoPoint(43.025, -5.0), d, false))).geometry.size)
}
@Test fun `imported routes get a road leg from a distant rider position`() {
val start = GeoPoint(43.0, -5.0)
val trace = RouteResult(listOf(start, GeoPoint(43.01, -5.0)), emptyList(), 1_100, 0, GeoPoint(43.01, -5.0), imported = true)
assertFalse(needsApproach(GeoPoint(43.0005, -5.0), trace)) // About 55 m away.
assertTrue(needsApproach(GeoPoint(42.99, -5.0), trace))
val approach = RouteResult(listOf(GeoPoint(42.99, -5.0), start), listOf(
Maneuver("start", 1_100, type = 1, beginShapeIndex = 0, endShapeIndex = 1),
Maneuver("arrive", 0, type = 4, beginShapeIndex = 1, endShapeIndex = 1),
), 1_100, 90, start)
val merged = prependApproach(approach, trace)
assertEquals(3, merged.geometry.size)
assertTrue(merged.maneuvers.isEmpty()) // Still a trace to follow.
assertEquals(2_200, merged.distanceMeters)
assertTrue(merged.imported)
assertEquals(trace.destination, merged.destination)
assertEquals(0, merged.durationSeconds) // A trace never shows an ETA.
}
@Test fun `rejoining an imported route never goes back and counts points passed nearby`() {
val points = (0..10).map { GeoPoint(43.0 + it * 0.001, -5.0) } // About 111 m apart.
val route = RouteResult(points, listOf(
Maneuver("right", 100, type = 10, beginShapeIndex = 3, endShapeIndex = 4),
Maneuver("left", 100, type = 15, beginShapeIndex = 7, endShapeIndex = 8),
), 1_110, 100, points.last(), imported = true)
val step = routeLength(route) / 10
// Off to the side of point 2, but progress already reached point 5.
val ahead = rejoinRemainder(route, GeoPoint(43.002, -4.998), 5 * step - 1)!!
assertEquals(points[5], ahead.geometry.first())
assertEquals(listOf(15), ahead.maneuvers.map { it.type })
assertEquals(2, ahead.maneuvers.single().beginShapeIndex)
assertEquals(555, ahead.distanceMeters)
assertEquals(50, ahead.durationSeconds)
// Nearest point ahead, not the next one.
assertEquals(points[8], rejoinRemainder(route, GeoPoint(43.008, -4.999), 0.0)!!.geometry.first())
assertNull(rejoinRemainder(route, points.last(), 0.0))
// Riding past point 4 within 100 m counts; a point beyond the window does not.
assertEquals(4 * step, passedAlong(route, GeoPoint(43.004, -4.9995), 0.0)!!, 1e-6)
assertNull(passedAlong(route, GeoPoint(43.004, -4.99), 0.0))
assertNull(passedAlong(route, points[9], 0.0, windowMeters = 500.0))
}
}
+20 -6
View File
@@ -1,23 +1,37 @@
# Importing a GPX route
Open **☰ → Cargar ruta GPX**, then choose a `.gpx` file using Android's document picker. The app displays the name, distance and point count and previews the trace when no other navigation session is active. After a valid file is selected, navigation starts automatically with real GPS as soon as location permission and a recent accurate fix are available. No destination search is needed. A pending import leaves existing navigation running until the new trace can start. The **Iniciar navegación** button retries after a timeout or permission denial.
Open **☰ → Cargar ruta GPX**, then choose a `.gpx` file using Android's document picker. The app displays the name and distance and previews the route when no other navigation session is active. Files made of route points, waypoints or sparse tracks are first joined along roads (see below). After a valid file is selected and any road calculation succeeds, navigation starts automatically with real GPS as soon as location permission and a recent accurate fix are available. No destination search is needed. A pending import leaves existing navigation running until the new trace can start. The **Iniciar navegación** button retries after a timeout or permission denial.
Precise location permission is required to start navigation. If a recent fix with accuracy of 25 metres or better is unavailable, the app waits up to 60 seconds. Close the import panel or stop the route to cancel that wait. When the wait expires, enable location and tap **Iniciar navegación** to retry. Denying permission leaves the trace available for review.
Precise location permission is required to start navigation. If a recent fix with accuracy of 25 metres or better is unavailable, the app waits up to 60 seconds (searched destinations wait the same way instead of refusing to start). Close the import panel or stop the route to cancel that wait. When the wait expires, enable location and tap **Iniciar navegación** to retry. Denying permission leaves the trace available for review.
## Supported files
GPX 1.0 and 1.1 routes (`rte/rtept`) and tracks (`trk/trkseg/trkpt`) are supported, including GPX files without a namespace. Export one route or one track containing a single nonempty continuous segment. A file containing one route plus one track is also supported: the track supplies the detailed geometry and its name; route stops are not connected or added to the trace. An empty or invalid track is rejected rather than silently following the route stops. Multiple routes, multiple tracks or multiple nonempty segments are rejected: the app must not create a fictitious connection between separate tracks. Waypoints alone do not define a route.
GPX 1.0 and 1.1 routes (`rte/rtept`) and tracks (`trk/trkseg/trkpt`) are supported, including GPX files without a namespace. Export one route or one track containing a single nonempty continuous segment. A file containing one route plus one track is also supported: the track supplies the detailed geometry and its name; route stops are not connected or added to the trace. An empty or invalid track is rejected rather than silently following the route stops. Multiple routes, multiple tracks or multiple nonempty segments are rejected: the app must not create a fictitious connection between separate tracks. A file with only waypoints (`wpt`) is treated as an ordered list of stops.
Files are limited to 5 MiB, 10,000 total route and track points and 64 XML nesting levels. Coordinates must be finite and within latitude/longitude bounds, with at least two distinct points. DTD declarations and external entities are rejected. Route names are capped at 256 characters. An invalid or inaccessible file leaves any running navigation untouched.
## Road calculation between points
Route points (`rtept`), waypoints and sparse tracks (median gap between points above 250 m, typical of planner exports with hand-placed clicks) are not drawn as straight lines. The app sends the ordered points to the configured Valhalla server with the motorcycle profile, avoiding unpaved roads; route points and waypoints also avoid motorways, while sparse tracks may use them because the recording may have. The first and last points are `break` locations and the rest are `through`, so the route passes every point without announcing an arrival at each one. Requests carry at most 20 points; longer lists are split into consecutive requests that share their boundary point and are merged into one route. At most 400 points are sent; longer lists are evenly downsampled keeping both ends.
The result has real turn instructions, voice announcements and an ETA. The route itself is never replaced during navigation, so the planned points are respected; deviations are handled as described in [Deviations](#deviations). If the calculation fails (no connection, server busy), the panel says so and offers **Reintentar**; the app never falls back to straight lines. Dense recorded tracks are followed as they are, without contacting the routing server.
## Starting away from the first point
On start, if the rider is more than 150 m from the route's first point, the app calculates a road leg from the current position to that point (fastest motorcycle route, avoiding unpaved roads) and prepends it, so guidance begins where the rider actually is. A dense trace stays a trace: the leg extends the line to follow, without turn instructions or ETA. If you leave that leg before reaching the route, it is recalculated from your position with the normal off-route policy (sustained deviation, 30 s between attempts). If the leg cannot be calculated, navigation starts on the imported route alone and the app asks the rider to head to the first point. Pressing start again later recalculates the leg from the new position.
## Following a trace
The original coordinates are retained locally in memory and drawn on the phone and TFT. GPX import does not send the file or its coordinates to a routing server. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time.
Dense tracks keep their original coordinates in memory and are drawn on the phone and TFT. Following such a trace sends no GPX coordinates to a routing server; only the optional leg from your position to its first point is calculated online. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time.
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace. After a confirmed deviation, three fresh, stable GPS fixes spanning at least two seconds automatically resume progress at the nearest point of the original trace, whether you rejoin ahead of or behind the previous position. GPS jumps and inaccurate fixes cannot confirm a rejoin.
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements or show an ETA. After a confirmed deviation, three fresh, stable GPS fixes spanning at least two seconds automatically resume progress at the nearest point of the original trace, whether you rejoin ahead of or behind the previous position. GPS jumps and inaccurate fixes cannot confirm a rejoin.
The imported route is not persisted across process death or device reboot: reload the original document to resume. The document remains in its selected provider; the app does not request long-term file access or copy the GPX into its own storage. Map diagnostics do not include route coordinates, document paths or route names.
## Deviations
After a sustained deviation from an imported route (the normal off-route policy: confirmed fixes, at most one attempt every 30 s), the app calculates a road leg from your position back to the route and prepends it; the imported geometry itself is kept. Before you have reached the route, the leg goes to its first point. Afterwards it goes to the nearest route point ahead of the progress you had made, searched within the next 10 km, so it never sends you back. While off the route, passing within 100 m of a later route point (within the next 3 km) counts as having reached it: riding past a point towards the next one is fine. Near the last point there is nothing to rejoin and the route simply ends. **Recalcular ahora** only acts while off the route. The leg back follows the same rules as the route: a trace gets no turn instructions or ETA.
## Validation
Core tests exercise standard GPX routes/tracks, namespaces, malicious XML, resource limits and trace guidance without invented turns or ETA. Android unit tests exercise the document picker, cancellation, precise-location permission denial, preview/start/stop and prevention of online recalculation with the renderer replaced to avoid device-only JNI.
Core tests exercise standard GPX routes/tracks, stop extraction for routes, waypoints and sparse tracks, multi-point Valhalla requests and leg merging, rejoin points that never go backwards and points passed nearby, namespaces, malicious XML, resource limits and trace guidance without invented turns or ETA. Android unit tests exercise road calculation of route points and its retry on failure, the document picker, cancellation, precise-location permission denial, preview/start/stop the leg from the rider's position to the first point, rerouting back to the nearest point ahead with the renderer replaced to avoid device-only JNI.
+1 -1
View File
@@ -45,7 +45,7 @@ These values reproduce the observed upstream session, including scale/unit label
## Image and send cycle
Service 0, frameType 6, pointer 1, payload `03 | seq UInt16LE | JPEG`. Sequence starts at 1 and wraps to 0 after 65535. The JPEG is generated by NavFrame at baseline 480×240; it is not a phone-screen capture. Only one frame may be in flight: `sendFrame` writes the packet and waits for IMAGE_ACK service 80 before the next frame. ACK payload format/correlation is not demonstrated; as in Pillion, the implementation filters on service 80. Other services are consumed without executing commands. An ACK confirms protocol exchange acceptance, not that an image was visibly drawn on the TFT.
Service 0, frameType 6, pointer 1, payload `03 | seq UInt16LE | JPEG`. Sequence starts at 1 and wraps to 0 after 65535. The JPEG is generated by NavFrame at baseline 480×240; it is not a phone-screen capture. Only one frame may be in flight: `sendFrame` writes the packet and waits for IMAGE_ACK service 80 before the next frame. ACK payload format/correlation is not demonstrated; as in Pillion, the implementation filters on service 80. Zoom requests from the motorcycle (service 51 zoom in, 52 zoom out, as documented by Pillion) are answered with the ZOOM metadata packet and adjust NavFrame's TFT zoom offset; other incoming services are logged as `NAVILITE_REQUEST` and counted in the TFT diagnostic report without executing commands. Incoming packets are only read while waiting for an ACK, so a request is handled on the next frame. The direction of 51/52 has not been verified on the motorcycle. An ACK confirms protocol exchange acceptance, not that an image was visibly drawn on the TFT.
Connection, handshake, and ACK timeouts and cancellation close the socket, unblock I/O, and set ERROR; `disconnect` closes directly without waiting for a held mutex. The initial version required an explicit reconnect; after ERROR, transport can call `connect()` again with a new socket, full handshake, and reset sequence. Automatic pairing and additional commands are not implemented. The transport has no continuously running reader while no sends occur; it detects a remote close on the next send. Therefore the session keepalive policy needs periodic checks; without them, CONNECTED may remain visible until another send.
+12 -1
View File
@@ -8,7 +8,7 @@ Start the demo with **Start animated demo**. It supports TFT layout iteration an
Drawing uses a logical 480 × 240 `Canvas`, prioritizing the maneuver, route shape, and position marker. `RenderScheduler` keeps only the latest state and avoids repaints for small changes: initial thresholds are 2 m position, 3° bearing, 0.5 m/s speed, and 10 m for visible distance changes. Initial maximum redraw rates are 1 FPS stopped, 5 FPS moving, and 10 FPS turning. These limit redraws; NaviLite keepalive sending is a separate configurable cadence (0.5/1/2 s) that waits for ACK and never queues frames. An ACK delay must not build a frame queue or block the demo.
The accompanying camera policy keeps the marker near 72% screen height and changes simulated zoom by speed/turn distance: 17 below 30 km/h, 16 through 70 km/h, 15 above, and 17.5 within 150 m of a turn. In this phase the renderer draws an illustrative road directly on Canvas; it does not project tiles or a map. These parameters only support future map integration.
In this phase the renderer draws an illustrative road directly on Canvas; it does not project tiles or a map. The camera policy used by the later map renderer is described under [TFT camera and zoom](#tft-camera-and-zoom).
Check by starting the simulated demo and watching the preview for at least one minute. Position/bearing should change, frames should remain 480 × 240, and `DEMO` should remain visible. Stopping the demo should halt its animation and update source. This check does not test GPS or real navigation.
@@ -55,3 +55,14 @@ This phase has no turn-by-turn, active progress, live turns, off-route detection
**Start guidance for calculated route** activates the GPS tracker or DEMO simulation over route geometry. The HUD shows icon, distance to maneuver, remaining distance, and approximate ETA. NO GPS, OFF ROUTE, and RECALCULATING hide stale estimates. Arrival requires distinct position observations. The service retains continuous transport and stop controls.
Native composition is checked using `guidance.png` on a test base. This does not certify MapLibre GPU or physical navigation. See [testing](TESTING.md) and [thresholds and limitations](ROUTING.md).
## TFT camera and zoom
`TftCameraPolicy` places the rider at 78% of the frame height with a 45° pitch, so most of the 480 × 240 image shows the road ahead. Zoom depends on speed and on the next turn: 15.5 below 30 km/h or within 200 m of a turn, 15 up to 70 km/h, and 14.5 above. Earlier versions used zoom 15–17.5 with the rider at 60% and no pitch, which showed only a few hundred metres ahead.
The rider can shift the automatic zoom in 0.5 steps between −2 and +2 from **☰ → Ajustes → Zoom del mapa en la pantalla de la moto**, or with the motorcycle's zoom controls when the TFT sends NaviLite zoom requests (see [NAVILITE.md](NAVILITE.md)). The offset is saved and the next frame is redrawn immediately. Pitch and handlebar zoom still need validation on the motorcycle.
## Online map fallback
A MapLibre snapshot fails as a whole if any tile, glyph or style resource fails, which happens with patchy mobile coverage. When the online map fails, NavFrame records `MAP_ONLINE_FAILED`, renders from an installed offline pack or region covering the position if there is one, and retries the online source after 30 seconds. Without an installed pack for the area, the TFT shows `MAPA NO DISPONIBLE` as before. Installing the bundled Asturias pack (or a regional pack) keeps the TFT map available when coverage drops.
@@ -28,8 +28,11 @@ import java.util.UUID
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/** One selected bonded CCU, one outstanding JPEG; no screen capture. */
class NaviLiteTransport(context: Context, private val deviceAddress: String) : TftTransport {
/**
* One selected bonded CCU, one outstanding JPEG; no screen capture. [onRequest] receives
* dashboard-initiated services (for example handlebar zoom) on the I/O thread; keep it short.
*/
class NaviLiteTransport(context: Context, private val deviceAddress: String, private val onRequest: (service: Int, payloadSize: Int) -> Unit = { _, _ -> }) : TftTransport {
private val context = context.applicationContext
private val state = MutableStateFlow(ConnectionState.DISCONNECTED)
override val connectionState: StateFlow<ConnectionState> = state.asStateFlow()
@@ -168,6 +171,11 @@ class NaviLiteTransport(context: Context, private val deviceAddress: String) : T
while (true) {
val packet = NaviLiteCodec.read(input)
if (packet.service == service) return packet
if (packet.service == ZOOM_IN_REQUEST || packet.service == ZOOM_OUT_REQUEST) {
// Upstream documents MAP_ZOOM_LEVEL_UPDATE as the reply; the label is the setup value.
send(token, ZOOM_LEVEL_UPDATE, true, ZOOM_LABEL)
}
if (packet.service !in setOf(66, 80, 82, 83)) onRequest(packet.service, packet.payload.size)
}
}
@@ -180,7 +188,7 @@ class NaviLiteTransport(context: Context, private val deviceAddress: String) : T
Triple(2, false, byteArrayOf(0, 0)), Triple(31, false, byteArrayOf(1, 0)),
Triple(10, false, byteArrayOf(0, 0)), Triple(11, false, byteArrayOf(0, 0)),
Triple(13, false, byteArrayOf(1, 0)), Triple(12, false, byteArrayOf(0, 0)),
Triple(14, true, byteArrayOf(7, 0x19, 6, 0, 0x30, 0x2e, 0x32, 0x20, 0x6d, 0x69)),
Triple(ZOOM_LEVEL_UPDATE, true, ZOOM_LABEL),
Triple(3, true, byteArrayOf()), Triple(17, true, byteArrayOf(0, 0, 0, 0, 3, 0x6d, 0x70, 0x68)),
Triple(13, false, byteArrayOf(1, 0)), Triple(12, false, byteArrayOf(1, 0)),
)
@@ -192,4 +200,12 @@ class NaviLiteTransport(context: Context, private val deviceAddress: String) : T
socket = null
runCatching { closing?.close() }
}
companion object {
/** Pillion docs/PROTOCOL.md: APP_MAP_ZOOM_IN/OUT_REQUEST; direction unverified on hardware. */
const val ZOOM_IN_REQUEST = 51
const val ZOOM_OUT_REQUEST = 52
private const val ZOOM_LEVEL_UPDATE = 14
private val ZOOM_LABEL = byteArrayOf(7, 0x19, 6, 0, 0x30, 0x2e, 0x32, 0x20, 0x6d, 0x69)
}
}