Fix off-route detection and TFT network lifecycle

This commit is contained in:
dasemu committed 2026-10-01 13:57:29 +02:00
1 parent 823d5db5d7
commit 6fec09f20f
11 files changed
+267 -18

No files matched your search

+2 -2
View File
@@ -6,8 +6,8 @@ android {
applicationId = "dev.navframe.app"
minSdk = 26
targetSdk = 35
versionCode = 16
versionName = "0.13.0"
versionCode = 17
versionName = "0.13.1"
}
testOptions { unitTests.isIncludeAndroidResources = true }
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
@@ -600,7 +600,7 @@ open class MainActivity : Activity() {
}.setNegativeButton("Cancelar", null).show()
}
private fun showInfo() {
val text = "NavFrame 0.11.0 · 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 0.13.1 · 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 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()
}
@@ -9,6 +9,7 @@ import android.text.Html
import dev.navframe.core.*
import kotlinx.coroutines.*
import org.maplibre.android.MapLibre
import org.maplibre.android.net.ConnectivityReceiver
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.Style
@@ -32,6 +33,21 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
private var closed = false
private var stage = MapRenderStage.INITIALIZE
private var capturedOnce = false
private var lastNetworkState: Boolean? = null
internal val networkConnected: Boolean? get() = lastNetworkState
private val connectivity = TftMapConnectivity(
acquire = { ConnectivityReceiver.instance(this.context).activate() },
refresh = {
val receiver = ConnectivityReceiver.instance(this.context)
receiver.setConnected(null)
val connected = receiver.isConnected
if (lastNetworkState != connected) {
lastNetworkState = connected
android.util.Log.d("NavFrame", "TFT_MAP_NETWORK connected=$connected")
}
},
release = { ConnectivityReceiver.instance(this.context).deactivate() },
)
private fun phase(value: MapRenderStage) { stage = value; reportStage(value) }
private data class Raster(val bitmap: Bitmap, val marker: PointF, val attribution: String)
override suspend fun render(state: NavigationState) = render(state, NavigationMode.MAP_GPS)
@@ -50,6 +66,10 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
private suspend fun capture(state: NavigationState): Raster = suspendCancellableCoroutine { continuation ->
phase(MapRenderStage.INITIALIZE)
MapLibre.getInstance(context)
// MapSnapshotter owns FileSource activation, but unlike MapView it does not own
// ConnectivityReceiver. Keep network notifications alive when the phone map stops
// (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 cameraPosition = CameraPosition.Builder().target(position).zoom(camera.zoom)
@@ -117,8 +137,12 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
/** Must be called on Main, just as the snapshotter was created there. */
fun close() {
check(Looper.myLooper() == Looper.getMainLooper())
if (closed) return
closed = true
snapshotter?.cancel()
snapshotter = null
try { snapshotter?.cancel() }
finally {
snapshotter = null
connectivity.close()
}
}
}
@@ -0,0 +1,29 @@
package dev.navframe.app
/** An independent SDK network lease: stopping the phone MapView must not stop TFT updates. */
internal class TftMapConnectivity(
private val acquire: () -> Unit,
private val refresh: () -> Unit,
private val release: () -> Unit,
) : AutoCloseable {
private var active = false
private var closed = false
fun refresh() {
check(!closed)
if (!active) {
acquire()
active = true
}
refresh.invoke()
}
override fun close() {
if (closed) return
closed = true
if (active) {
active = false
release()
}
}
}
@@ -68,6 +68,7 @@ class TftService : Service() {
private val mutableVoiceStatus = MutableStateFlow("Voz: preparando motor español")
val voiceStatus = mutableVoiceStatus.asStateFlow()
private var mapRenderer: MapLibreTftRenderer? = null
private var lastMapNetworkConnected: Boolean? = null
private val mutableMapDiagnostic = MutableStateFlow("TFT MAP · sin captura")
val mapDiagnostic = mutableMapDiagnostic.asStateFlow()
private var lastMapFailureDiagnostic = "sin fallo registrado"
@@ -693,7 +694,8 @@ class TftService : Service() {
val fix = lastGpsFix
val accuracy = when { fix == null -> "SIN FIX"; !fix.accuracyMeters.isFinite() -> "DESCONOCIDA"; fix.accuracyMeters <= 5 -> "0–5 m"; fix.accuracyMeters <= 15 -> "6–15 m"; fix.accuracyMeters <= 25 -> "16–25 m"; else -> ">25 m" }
val age = if (fix == null) "SIN FIX" else if (SystemClock.elapsedRealtime() - lastGpsElapsed <= 15_000) "RECIENTE" else "CADUCADO"
return "NavFrame 0.13.0 · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\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."
val network = when (mapRenderer?.networkConnected ?: lastMapNetworkConnected) { true -> "CONECTADA"; false -> "SIN CONEXIÓN"; null -> "SIN COMPROBAR" }
return "NavFrame 0.13.1 · 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."
}
fun isRealSessionRequested(): Boolean = realRequested
fun isGpsSessionActive(): Boolean = gpsRequested
@@ -783,6 +785,7 @@ class TftService : Service() {
}
}
private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, attribution: String, error: MapRenderException): TftFrame {
lastMapNetworkConnected = mapRenderer?.networkConnected ?: lastMapNetworkConnected
mapRenderer?.close()
mapRenderer = null
mapFailures = (mapFailures + 1).coerceAtMost(4)
@@ -0,0 +1,39 @@
package dev.navframe.app
import org.junit.Assert.*
import org.junit.Test
class TftMapConnectivityTest {
@Test fun phoneStoppingLeavesTftNetworkLeaseActiveAndRefreshesCurrentNetwork() {
var sdkReferences = 1 // The visible phone MapView already owns a lease.
var actualNetwork = false
var observedNetwork: Boolean? = null
val lease = TftMapConnectivity({ sdkReferences++ }, { observedNetwork = actualNetwork }, { sdkReferences-- })
lease.refresh()
assertEquals(false, observedNetwork)
sdkReferences-- // Screen turns off: MapView.onStop releases the phone lease.
actualNetwork = true // Mobile data recovers while the phone map is stopped.
lease.refresh()
assertEquals(true, observedNetwork)
assertEquals(1, sdkReferences)
lease.close()
lease.close()
assertEquals(0, sdkReferences)
}
@Test fun failedRefreshStillReleasesAcquiredSdkLease() {
var references = 0
val lease = TftMapConnectivity({ references++ }, { error("network service unavailable") }, { references-- })
try { lease.refresh(); fail("Expected refresh failure") } catch (_: IllegalStateException) { }
assertEquals(1, references)
lease.close()
assertEquals(0, references)
}
@Test fun closingUnusedRendererDoesNotReleasePhoneLease() {
var references = 1
val lease = TftMapConnectivity({ references++ }, { }, { references-- })
lease.close()
assertEquals(1, references)
}
}
@@ -0,0 +1,106 @@
package dev.navframe.app
import android.Manifest
import android.location.Location
import android.location.LocationManager
import android.os.Looper
import android.os.SystemClock
import dev.navframe.core.*
import kotlinx.coroutines.CompletableDeferred
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@LooperMode(LooperMode.Mode.PAUSED)
class TftServiceRerouteTest {
@Test fun reliableFixesMovingBackAlongOldRoadRequestRouteFromCurrentPositionAndResumeGuidance() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
val manager = service.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
val destination = GeoPoint(0.0, 0.02)
val original = RouteResult(listOf(GeoPoint(0.0, 0.0), destination), emptyList(), 2224, 180)
val pendingReroute = CompletableDeferred<RouteResult>()
val options = RouteOptions(RouteProfile.AVOID_UNPAVED, avoidMotorways = true)
var calculations = 0
var rerouteOrigin: GeoPoint? = null
var rerouteOptions: RouteOptions? = null
service.routingEngineFactory = { object : RoutingEngine {
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
calculations++
if (calculations == 1) return original
rerouteOrigin = origin
rerouteOptions = options
return pendingReroute.await()
}
override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = error("Unexpected routing API")
} }
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
fun tick(millis: Long = 100) { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis)) }
fun awaitNavigationStatus(expected: NavigationStatus) {
// The initial no-fix frame is encoded on Dispatchers.Default; draining only the
// Android looper does not wait for that worker to resume the service loop.
val deadline = System.nanoTime() + 3_000_000_000L
while (service.navigationState.value.navigationStatus != expected && System.nanoTime() < deadline) {
Thread.sleep(10)
tick(10)
}
assertEquals(service.diagnosticReport() + "\n" + service.routeInfo.value,
expected, service.navigationState.value.navigationStatus)
}
var timestamp = 0L
fun position(longitude: Double, accuracy: Float = 5f) {
timestamp += 1000
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 0.0; this.longitude = longitude; this.accuracy = accuracy
speed = 12f; bearing = 270f; time = timestamp
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
})
tick()
val deadline = System.nanoTime() + 3_000_000_000L
while (service.navigationState.value.position.longitude != longitude && System.nanoTime() < deadline) {
Thread.sleep(10)
tick(10)
}
assertEquals(service.diagnosticReport(), longitude, service.navigationState.value.position.longitude, 0.0)
}
try {
service.setPhoneVisible(true); tick()
position(0.01)
service.calculateRoute(destination, false, "https://example.test/route", options); tick()
service.startRoute(); tick(600)
position(0.01)
tick(1000)
position(0.01)
awaitNavigationStatus(NavigationStatus.NAVIGATING)
for (longitude in listOf(0.0098, 0.0095, 0.0092, 0.0089, 0.0086, 0.0083, 0.0080)) {
tick(1500)
position(longitude)
}
awaitNavigationStatus(NavigationStatus.REROUTING)
assertEquals(2, calculations)
assertEquals(options, rerouteOptions)
assertTrue(requireNotNull(rerouteOrigin).longitude < 0.0095)
assertEquals(NavigationStatus.REROUTING, service.navigationState.value.navigationStatus)
assertEquals(GeoPoint(0.0, 0.0080), service.navigationState.value.position)
val replacement = RouteResult(listOf(requireNotNull(rerouteOrigin), GeoPoint(0.0, 0.007), destination),
listOf(Maneuver("Arrive", 0, 4, 2, 2)), 1300, 120)
pendingReroute.complete(replacement); tick(1000)
position(0.0079)
assertSame(replacement, service.navigationState.value.route)
assertEquals(NavigationStatus.NAVIGATING, service.navigationState.value.navigationStatus)
assertNotNull(service.navigationState.value.nextManeuver)
assertEquals(2, calculations)
} finally { controller.destroy() }
}
}
@@ -76,7 +76,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
}
val projection = line.project(fix.position, progress, forwardAllowance)
val outsideThreshold = max(config.offRouteMeters, fix.accuracyMeters * 2.0)
val offRoute = outside.observe(projection.distance > outsideThreshold, distinct, nowMs,
val offRoute = outside.observe(projection.localDistance > outsideThreshold, distinct, nowMs,
config.offRouteFixes, config.offRouteDurationMs)
// Freeze progress during inaccurate projection, so driving parallel to the road does not advance turns.
if (projection.distance <= outsideThreshold && projection.localDistance <= outsideThreshold && projection.local != null) {
@@ -87,14 +87,10 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
arrival.reset()
return remember(base.copy(navigationStatus = NavigationStatus.OFF_ROUTE))
}
if (projection.distance > outsideThreshold) {
if (projection.localDistance > outsideThreshold) {
arrival.reset()
return remember(base.copy(navigationStatus = NavigationStatus.NAVIGATING))
}
if (projection.local == null || projection.localDistance > outsideThreshold) {
arrival.reset()
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
}
val remaining = line.total - progress
val close = projection.distance <= outsideThreshold && remaining <= config.arrivalRemainingMeters &&
earthDistance(fix.position, route.geometry.last()) <= config.arrivalRadiusMeters
@@ -205,8 +201,21 @@ private class RouteLine(private val route: RouteResult) {
val distance = earthDistance(point, projected)
val along = cumulative[i - 1] + (cumulative[i] - cumulative[i - 1]) * fraction
nearestDistance = min(nearestDistance, distance)
if (along >= previous - 20 && along <= previous + forwardAllowance && distance < localDistance - 0.01) {
localDistance = distance; localProgress = along
// Compare against the reachable section, including its boundary points. A reliable
// position behind progress or on a distant later branch is a deviation, not GPS loss.
// Clamping the projection also avoids artificial gaps at the progress-window edges.
val start = max(cumulative[i - 1], previous - 20)
val end = min(cumulative[i], previous + forwardAllowance)
if (start <= end) {
val reachableAlong = along.coerceIn(start, end)
val length = cumulative[i] - cumulative[i - 1]
val reachableFraction = if (length == 0.0) 0.0 else (reachableAlong - cumulative[i - 1]) / length
val reachablePoint = GeoPoint(a.latitude + dy * reachableFraction,
wrappedLongitude(a.longitude + wrappedLongitude(b.longitude - a.longitude) * reachableFraction))
val reachableDistance = earthDistance(point, reachablePoint)
if (reachableDistance < localDistance - 0.01) {
localDistance = reachableDistance; localProgress = reachableAlong
}
}
}
return Projection(nearestDistance, localProgress, localDistance)
@@ -188,9 +188,36 @@ class RouteGuidanceTest {
tracker.update(fix(), 0, 0)
tracker.update(fix(lon = 0.005, time = 2), 1_000, 0)
val stableButDistant = tracker.update(fix(lon = 0.005, time = 3), 2_000, 0)
assertEquals(NavigationStatus.GPS_LOST, stableButDistant.navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, stableButDistant.navigationStatus)
assertNull(stableButDistant.remainingDistanceMeters)
assertNull(stableButDistant.nextManeuver)
tracker.update(fix(lon = 0.005, time = 4), 5_000, 0)
val offRoute = tracker.update(fix(lon = 0.005, time = 5), 7_000, 0)
assertEquals(NavigationStatus.OFF_ROUTE, offRoute.navigationStatus)
assertTrue(ReroutePolicy().shouldRequest(offRoute, 7_000))
}
@Test fun `turning back on the same road confirms deviation rather than GPS loss`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 180)
val tracker = RouteGuidanceTracker(longRoute)
tracker.update(fix(lon = 0.01), 0, 0)
tracker.update(fix(lon = 0.0097, time = 2), 1_000, 0)
tracker.update(fix(lon = 0.0094, time = 3), 2_000, 0)
tracker.update(fix(lon = 0.0091, time = 4), 4_000, 0)
val reversed = tracker.update(fix(lon = 0.0088, time = 5), 7_000, 0)
assertEquals(NavigationStatus.OFF_ROUTE, reversed.navigationStatus)
assertTrue(ReroutePolicy().shouldRequest(reversed, 7_000))
assertNull(reversed.nextManeuver)
assertEquals(GeoPoint(0.0, 0.0088), reversed.position)
}
@Test fun `small movement past progress window uses boundary instead of false GPS loss`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 180)
val tracker = RouteGuidanceTracker(longRoute)
val initial = tracker.update(fix(lon = 0.01), 0, 0)
val reversed = tracker.update(fix(lon = 0.00975, time = 2), 1_000, 0)
assertEquals(NavigationStatus.NAVIGATING, reversed.navigationStatus)
assertEquals(initial.remainingDistanceMeters, reversed.remainingDistanceMeters)
}
@Test fun `maneuver arrows use type rather than translated prose`() {
+3 -3
View File
@@ -57,14 +57,14 @@ Smoke HTTP autorizado: una única petición POST de demostración en Asturias (4
`RouteGuidanceTracker(route).update(fix, nowMs, epochMs, fixAgeMs)` separa reloj monotónico, hora civil para ETA y edad real del fix. El caller debe pasar la edad desde el proveedor, nunca asumir que un tick nuevo implica un fix nuevo. Se acepta edad hasta 15s y precisión horizontal finita entre 0 y 25m. Un fix no utilizable produce GPS_LOST sin giro/countdown/ETA y rompe evidencia de desvío/llegada. El timestamp del fix identifica observaciones distintas; ticks repetidos no avanzan estado ni confirman umbrales. Un intervalo entre observaciones de más de 15s también rompe evidencia. Recuperar tras GPS_LOST o ese intervalo requiere dos fixes nuevos: el primero establece baseline sin avanzar y el segundo estable permite adquirir de nuevo; la ausencia no amplía la ventana de movimiento.
La primera adquisición usa la proyección más cercana válida sobre toda la ruta. Después se limita el candidato a una ventana local dependiente de velocidad/tiempo, con tolerancia hacia atrás de 20m y progreso acumulado que no retrocede por jitter. Se verifica distancia a ese candidato antes de avanzar. Saltos de posición incompatibles con movimiento observado producen temporalmente GPS_LOST; un fix posterior estable recupera evaluación. Estos filtros no sustituyen map matching: cruces, ramales paralelos, puentes, conducción en sentido contrario y pérdidas prolongadas de GPS siguen siendo ambiguos. La política conservadora puede congelar progreso y ocultar guiado como GPS_LOST ante un salto grande hacia una sección posterior con proyección local ambigua; detener/iniciar o recalcular permite una adquisición nueva. No inferir una carretera distinta solo porque otra geometría está cerca.
La primera adquisición usa la proyección más cercana válida sobre toda la ruta. Después se limita el candidato a una ventana local dependiente de velocidad/tiempo, con tolerancia hacia atrás de 20m y progreso acumulado que no retrocede por jitter. Se verifica distancia a ese candidato antes de avanzar. Saltos de posición incompatibles con movimiento observado producen temporalmente GPS_LOST; un fix posterior estable recupera evaluación. Estos filtros no sustituyen map matching: cruces, ramales paralelos, puentes, conducción en sentido contrario y pérdidas prolongadas de GPS siguen siendo ambiguos. Un salto aislado sigue produciendo GPS_LOST temporalmente. Si los fixes posteriores son estables pero quedan fuera de la sección alcanzable, se congela el progreso y se confirma OFF_ROUTE tras evidencia sostenida, permitiendo el recálculo automático; no se presenta esa desviación como pérdida de GPS. Los candidatos se recortan a los extremos de la ventana local para evitar huecos artificiales cerca de sus límites. No inferir una carretera distinta solo porque otra geometría está cerca.
El próximo giro usa la distancia geométrica al `beginShapeIndex` y avanza después de pasarlo por más de 5m. Los tipos oficiales 1/2/3 son Start/StartRight/StartLeft, instrucciones de salida, y se omiten del próximo giro; los giros normales Right/Left son 10/15. `maneuverDirection(type)` elige icono sin analizar traducciones. Llegada exige extremo ajustado a carretera a ≤25m, restante geométrico ≤30m, tres fixes distintos y ≥2s; luego permanece confirmada hasta sustituir el tracker. Los [tipos oficiales de maniobra](https://valhalla.github.io/valhalla/api/route/api-reference/#trip-legs-and-maneuvers) sustentan esos IDs.
Desvío: separación de toda la geometría mayor que `max(40m, 2 × accuracy)` durante ≥5s y ≥3 fixes distintos. Una recuperación rompe la secuencia. Mientras la posición excede el umbral se ocultan estimaciones de giro; OFF_ROUTE confirma el estado después de esa evidencia. OFF_ROUTE conserva la ruta para el mapa, pero no muestra countdown ni ETA calculados como si se siguiera sobre ella. Todos esos umbrales son configurables y están pendientes de calibración real.
Desvío: separación de la sección geométrica alcanzable desde el progreso previo mayor que `max(40m, 2 × accuracy)` durante ≥5s y ≥3 fixes distintos. Esto incluye volver hacia atrás por la misma carretera o alcanzar una sección posterior distante aunque la posición esté cerca de otra parte de la ruta. Una recuperación rompe la secuencia. Mientras la posición excede el umbral se ocultan estimaciones de giro; OFF_ROUTE confirma el estado después de esa evidencia. OFF_ROUTE conserva la ruta para el mapa, pero no muestra countdown ni ETA calculados como si se siguiera sobre ella. Todos esos umbrales son configurables y están pendientes de calibración real.
El restante es longitud geométrica pendiente. ETA real es **aproximada**: duración inicial Valhalla multiplicada por fracción geométrica pendiente; no contempla tráfico, paradas ni velocidad futura. `RouteDemo(route).stateAt(elapsedMs, epochMs)` interpola posiciones a 12m/s y produce guiado completo determinista hasta ARRIVED; su ETA usa esa velocidad. Android debe mostrar DEMO continuamente y jamás utilizarlo para lanzar recálculo HTTP.
`ReroutePolicy` separa decisión de IO: `shouldRequest`, `markRequested` antes de lanzar y `markFinished` en finally, incluidos errores/cancelación. Un request activo bloquea otro; el cooldown tras finalización es al menos 30s, ampliable con Retry-After. `reset` solo para nueva sesión/acción manual. Android aplica además el límite de fallos y bloqueo HTTP429; una sustitución de ruta debe ser atómica y conservar la ruta anterior si falla.
`RouteGuidanceTest` cubre proyección/countdown/ETA, jitter y giro pasado, adquisición intermedia, ticks duplicados y separación temporal, tres observaciones de desvío/llegada, margen de precisión, fixes inválidos/stale, saltos y retorno, cruce de geometría, antimeridiano, single-flight/cooldown/Retry-After e interpolación demo. Son pruebas geométricas; no certifican guiado físico ni calidad de datos OSM.
`RouteGuidanceTest` cubre proyección/countdown/ETA, jitter y giro pasado, adquisición intermedia, ticks duplicados y separación temporal, tres observaciones de desvío/llegada, margen de precisión, fixes inválidos/stale, saltos y retorno, cruce de geometría, antimeridiano, single-flight/cooldown/Retry-After e interpolación demo. `TftServiceRerouteTest` simula GPS Android al retroceder sobre la carretera anterior y verifica una solicitud desde la posición actual con el mismo perfil, una sola solicitud en vuelo y recuperación del guiado con la ruta recibida. Estas pruebas no certifican guiado físico ni calidad de datos OSM.
+12
View File
@@ -147,6 +147,18 @@ La pantalla principal funciona sin GPS ni Bluetooth: mapa online, búsqueda, opc
## Entorno de desarrollo observado
### Ride feedback and regression checks (0.13.1)
The rider confirmed downloaded regional maps display on both the phone and the Yamaha TFT, and voice instructions work during a real ride. Online maps worked on the phone but failed on the TFT. Deviating from the route could incorrectly report GPS loss while the map still followed the rider, with instructions resuming only after returning to the previous route progress.
Route regressions now distinguish a reliable position outside the reachable route section from an unusable GPS fix. Validate automatic recalculation from the current position after a sustained deviation, including a reversal on the same road. The destination and selected routing profile must remain unchanged, and a successful replacement route must resume instructions.
The TFT snapshot renderer now owns its connectivity lifecycle independently of the phone map. This closes a confirmed lifecycle gap; the reported online-map failure still needs device validation. Test the default online map with no offline source selected, then background the phone, lock the screen, and change between Wi-Fi and mobile data. If rendering fails, use **Info → TFT map diagnostics** to collect the sanitized failure stage and reason.
Horizontal GPS uncertainty remains visible as small marker movement. Guidance still rejects fixes older than 15 seconds or with accuracy worse than 25 metres; deviation handling must not hide genuine loss of usable positioning.
Local verification for 0.13.1 passed 159 unit tests (60 app, 89 core, 10 NaviLite), Android APK assembly, and lint with zero errors. The online TFT lifecycle tests do not exercise the native GPU renderer or prove online rendering on the motorcycle.
El shell inicial tenía OpenJDK 25 y `adb` 35.0.2; no definía `ANDROID_HOME`/`ANDROID_SDK_ROOT` ni encontraba `gradle` en PATH. Se encontró un SDK Android bajo `/home/dasemu/.bubblewrap/android_sdk` y JDK 17 bajo `/home/dasemu/.bubblewrap/jdk/jdk-17.0.11+9`; la ejecución de Gradle se realizó con este JDK y `local.properties` apuntando al SDK. No hay un teléfono conectado validado por ADB.
## Registro de verificación local