diff --git a/README.md b/README.md index 83fb4bc..44ce2fa 100644 --- a/README.md +++ b/README.md @@ -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.7. 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. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 5e26d3f..eab2ddb 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "dev.navframe.app" minSdk = 26 targetSdk = 35 - versionName = "0.14.7" - versionCode = 24 + versionName = "0.14.8" + versionCode = 25 } if (hasReleaseSigning) { signingConfigs.create("production") { diff --git a/app/src/main/java/dev/navframe/app/MainActivity.kt b/app/src/main/java/dev/navframe/app/MainActivity.kt index 026083d..ceff613 100644 --- a/app/src/main/java/dev/navframe/app/MainActivity.kt +++ b/app/src/main/java/dev/navframe/app/MainActivity.kt @@ -149,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 { @@ -214,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)) } ?: "" @@ -233,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 @@ -252,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 @@ -356,12 +356,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. @@ -369,20 +368,24 @@ 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) val box = column().apply { setPadding(dp(20), dp(16), dp(20), dp(16)) } box.addView(label(name ?: "Ruta GPX", 20f)) box.addView(routeInfo) - lastImportedRoute?.takeIf { !it.isTrack && it.route.geometry.size in 2..50 }?.let { imported -> - box.addView(button("Calcular por carreteras · evitar autopistas") { - service?.calculateImportedStops(imported) - }) - } 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() @@ -620,6 +623,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) @@ -685,7 +698,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() } @@ -746,6 +759,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" } @@ -768,6 +782,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" diff --git a/app/src/main/java/dev/navframe/app/MapFrameComposer.kt b/app/src/main/java/dev/navframe/app/MapFrameComposer.kt index 7e1ae5e..b317672 100644 --- a/app/src/main/java/dev/navframe/app/MapFrameComposer.kt +++ b/app/src/main/java/dev/navframe/app/MapFrameComposer.kt @@ -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) } diff --git a/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt b/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt index 59c9802..7278a80 100644 --- a/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt +++ b/app/src/main/java/dev/navframe/app/MapLibreTftRenderer.kt @@ -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() }) diff --git a/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt b/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt index e5f7c9f..2742278 100644 --- a/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt +++ b/app/src/main/java/dev/navframe/app/NominatimGeocoder.kt @@ -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) { diff --git a/app/src/main/java/dev/navframe/app/TftService.kt b/app/src/main/java/dev/navframe/app/TftService.kt index 24de837..e4d9b95 100644 --- a/app/src/main/java/dev/navframe/app/TftService.kt +++ b/app/src/main/java/dev/navframe/app/TftService.kt @@ -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 @@ -52,7 +52,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 +77,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> = emptyList() + private var offlineSourcesAt = 0L + private val mutableTftZoomInfo = MutableStateFlow("") + val tftZoomInfo = mutableTftZoomInfo.asStateFlow() + private var dashboardRequests = sortedMapOf() private var mapFailures = 0 private var unavailableMapFrame: TftFrame? = null private val mutableMode = MutableStateFlow(NavigationMode.IDLE) @@ -91,7 +104,7 @@ class TftService : Service() { val connectionState = mutableState.asStateFlow() private val mutableFrame = MutableStateFlow(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 +113,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 +237,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 +383,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 +465,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,54 +590,62 @@ 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() } - /** Resolve GPX route stops against Valhalla; never alter a detailed imported track. */ - fun calculateImportedStops(imported: ImportedRoute) { - if (imported.isTrack || imported.route.geometry.size !in 2..50) { - mutableRouteInfo.value = "Solo se pueden calcular rutas GPX con entre 2 y 50 puntos de paso." - return - } - val stops = imported.route.geometry + /** 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 - val options = RouteOptions(profile = RouteProfile.AVOID_MOTORWAYS, avoidMotorways = true, avoidUnpaved = true) - mutableRouteInfo.value = "Calculando sobre carreteras · evitando autopistas y pistas sin asfaltar…" + // 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 engine = routingEngineFactory(routingEndpoint()) - val geometry = mutableListOf() - var metres = 0L - for (i in 0 until stops.lastIndex) { - val part = engine.calculateRoute(stops[i], stops[i + 1], options) - ensureActive() - if (part.geometry.size < 2) throw java.io.IOException("Segmento sin geometría") - geometry.addAll(if (i == 0) part.geometry else part.geometry.drop(1)) - metres += part.distanceMeters - if (geometry.size > 10_000) throw IllegalArgumentException("La ruta supera 10000 puntos") - if (generation != preparedGeneration) return@launch - mutableRouteInfo.value = "Calculando carreteras · tramo ${i + 1}/${stops.lastIndex}" - } + val result = routingEngineFactory(routingEndpoint()).calculateRouteThrough(imported.stops, options) ensureActive() if (generation != preparedGeneration) return@launch - val result = RouteResult(geometry = geometry, maneuvers = emptyList(), - distanceMeters = metres.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(), - durationSeconds = 0, destination = geometry.last(), imported = true) - prepareImportedRoute(ImportedRoute(imported.name, result, isTrack = true)) - mutableRouteInfo.value = "GPX ajustado a carreteras · %.1f km · %d puntos\nComprueba que no haya autovías ni tramos inadecuados antes de salir. No hay avisos de giro ni recálculo.".format(java.util.Locale.ROOT, metres / 1000.0, geometry.size) + 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 = "No se pudo calcular sobre carreteras. Se conserva el GPX original; comprueba conexión y endpoint Valhalla." + 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." + } + } + } + /** 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) } } } @@ -649,7 +671,8 @@ class TftService : Service() { reroutePaused = false 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) @@ -758,7 +781,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 @@ -818,6 +841,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) @@ -832,16 +856,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 @@ -851,11 +879,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() @@ -911,7 +990,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() } @@ -926,6 +1005,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. @@ -934,6 +1014,7 @@ 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" diff --git a/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt b/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt index 6edd671..18c2761 100644 --- a/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt +++ b/app/src/main/java/dev/navframe/app/ValhallaRoutingEngine.kt @@ -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, options: RouteOptions): RouteResult { + require(stops.size >= 2) { "Se necesitan al menos dos puntos" } + val parts = ArrayList() + 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, 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 diff --git a/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt b/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt index 037f9f3..f33a303 100644 --- a/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt +++ b/app/src/test/java/dev/navframe/app/ImportedRouteTest.kt @@ -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("""Weekend""".byteInputStream()) + /** A detailed trace (about 11 m between points) is followed as is, without a routing server. */ + private fun imported() = GpxRouteImporter.parse(("Weekend" + + (0..90).joinToString("") { "" } + "").byteInputStream()) + private class RoadEngine(val fail: Boolean = false) : RoutingEngine { + val requests = mutableListOf>() + 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 } @@ -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("""""") + val engine = RoadEngine() + service.routingEngineFactory = { engine } + importDocument("""""") + 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 @@ -197,4 +221,24 @@ 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("""""".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() } + } } diff --git a/app/src/test/java/dev/navframe/app/NominatimGeocoderTest.kt b/app/src/test/java/dev/navframe/app/NominatimGeocoderTest.kt index 13d69ac..17551a6 100644 --- a/app/src/test/java/dev/navframe/app/NominatimGeocoderTest.kt +++ b/app/src/test/java/dev/navframe/app/NominatimGeocoderTest.kt @@ -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) diff --git a/core/src/main/kotlin/dev/navframe/core/Contracts.kt b/core/src/main/kotlin/dev/navframe/core/Contracts.kt index 759f0df..1ca0b67 100644 --- a/core/src/main/kotlin/dev/navframe/core/Contracts.kt +++ b/core/src/main/kotlin/dev/navframe/core/Contracts.kt @@ -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, 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, diff --git a/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt b/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt index 8803901..427456e 100644 --- a/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt +++ b/core/src/main/kotlin/dev/navframe/core/GpxRouteImporter.kt @@ -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, val isTrack: Boolean = false) +/** + * [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 = 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,30 @@ 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) + ), handler.isTrack, stops) + } + + private fun isSparse(points: List): 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): List { + 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() private val trackPoints = mutableListOf() + private val waypoints = mutableListOf() private var routeName: String? = null private var trackName: String? = null - val points: List get() = if (tracks > 0) trackPoints else routePoints + val points: List 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() @@ -88,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) { diff --git a/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt b/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt index 14122e9..eb24ece 100644 --- a/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt +++ b/core/src/main/kotlin/dev/navframe/core/RouteGuidance.kt @@ -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 { diff --git a/core/src/main/kotlin/dev/navframe/core/TftCameraPolicy.kt b/core/src/main/kotlin/dev/navframe/core/TftCameraPolicy.kt index db5873e..5b11b6a 100644 --- a/core/src/main/kotlin/dev/navframe/core/TftCameraPolicy.kt +++ b/core/src/main/kotlin/dev/navframe/core/TftCameraPolicy.kt @@ -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) } } diff --git a/core/src/main/kotlin/dev/navframe/core/ValhallaRoute.kt b/core/src/main/kotlin/dev/navframe/core/ValhallaRoute.kt index 4e5bc36..bcdfba4 100644 --- a/core/src/main/kotlin/dev/navframe/core/ValhallaRoute.kt +++ b/core/src/main/kotlin/dev/navframe/core/ValhallaRoute.kt @@ -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, 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,39 @@ 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 { + require(parts.isNotEmpty()) { "No route parts" } + if (parts.size == 1) return parts.single() + val geometry = ArrayList() + val maneuvers = ArrayList() + 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) +} + 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") diff --git a/core/src/test/kotlin/dev/navframe/core/DemoNavigationTest.kt b/core/src/test/kotlin/dev/navframe/core/DemoNavigationTest.kt index e78a3da..c204217 100644 --- a/core/src/test/kotlin/dev/navframe/core/DemoNavigationTest.kt +++ b/core/src/test/kotlin/dev/navframe/core/DemoNavigationTest.kt @@ -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) } } diff --git a/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt b/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt index 6342540..e8f6825 100644 --- a/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt +++ b/core/src/test/kotlin/dev/navframe/core/GpxRouteImporterTest.kt @@ -103,4 +103,27 @@ class GpxRouteImporterTest { assertNull(outside.etaEpochMillis) } + @Test fun `route points and waypoints are stops to join along roads`() { + val route = parse("$points") + 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("") + 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("" + + (0 until count).joinToString("") { "" } + "") + 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()) + } } diff --git a/core/src/test/kotlin/dev/navframe/core/ValhallaRouteTest.kt b/core/src/test/kotlin/dev/navframe/core/ValhallaRouteTest.kt index 092f4f2..f1e9f71 100644 --- a/core/src/test/kotlin/dev/navframe/core/ValhallaRouteTest.kt +++ b/core/src/test/kotlin/dev/navframe/core/ValhallaRouteTest.kt @@ -163,4 +163,30 @@ 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) + } } diff --git a/docs/IMPORTED_ROUTES.md b/docs/IMPORTED_ROUTES.md index b8bd52e..7d36db7 100644 --- a/docs/IMPORTED_ROUTES.md +++ b/docs/IMPORTED_ROUTES.md @@ -1,18 +1,24 @@ # 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. ## 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. It is not recalculated automatically during navigation so that the planned points are respected. 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. + ## 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 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. 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. @@ -20,4 +26,4 @@ The imported route is not persisted across process death or device reboot: reloa ## 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, 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 and prevention of online recalculation with the renderer replaced to avoid device-only JNI. diff --git a/docs/NAVILITE.md b/docs/NAVILITE.md index b0ef437..2bf082c 100644 --- a/docs/NAVILITE.md +++ b/docs/NAVILITE.md @@ -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. diff --git a/docs/TFT_RENDERING.md b/docs/TFT_RENDERING.md index 414dd7a..62b978d 100644 --- a/docs/TFT_RENDERING.md +++ b/docs/TFT_RENDERING.md @@ -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. + diff --git a/navilite/src/main/kotlin/dev/navframe/navilite/NaviLiteTransport.kt b/navilite/src/main/kotlin/dev/navframe/navilite/NaviLiteTransport.kt index 00c7e04..a22890b 100644 --- a/navilite/src/main/kotlin/dev/navframe/navilite/NaviLiteTransport.kt +++ b/navilite/src/main/kotlin/dev/navframe/navilite/NaviLiteTransport.kt @@ -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 = 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) + } }