fix: wait for a precise fix on start and route GPX from the rider

- Start no longer fails when the first fix is coarser than 25 m: both
  searched and imported routes wait up to 60 s for guidance accuracy.
- Starting an imported route more than 150 m from its first point
  prepends a road leg from the current position; traces stay traces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:43:41 +01:00
1 parent b7bf2c2b43
commit 646a4a2a2a
7 files changed
+128 -9

No files matched your search

@@ -282,6 +282,7 @@ open class MainActivity : Activity() {
Action.IMPORT_ROUTE -> startImportedRoute()
Action.ROUTE, Action.PREVIEW -> {
if (action == Action.ROUTE && service?.hasPreparedRoute() != true) return
if (action == Action.ROUTE && service?.routeUsesGps() == true && service?.hasGuidanceGpsFix() != true) { startWhenGuidanceReady("Esperando GPS preciso para iniciar la ruta…") { perform(Action.ROUTE) }; return }
if (action == Action.ROUTE) startRequested = true
if (action == Action.PREVIEW) service?.previewPreparedRoute()
else if (service?.routeUsesGps() == true) try { startForegroundService(Intent(this, TftService::class.java).setAction(TftService.ACTION_ROUTE_GPS).putExtra(TftService.EXTRA_PREVIEW, action == Action.PREVIEW)) } catch (_: RuntimeException) { hint.text = "No se pudo iniciar · revisa permisos de ubicación" }
@@ -396,10 +397,24 @@ open class MainActivity : Activity() {
private fun startImportedRoute() {
val current = service ?: return
if (!current.preparedRouteIsImported()) { hint.text = "Vuelve a cargar la ruta GPX"; return }
startWhenGuidanceReady("Esperando GPS preciso para iniciar el GPX…") {
if (!current.preparedRouteIsImported()) return@startWhenGuidanceReady
routeLoading?.visibility = View.VISIBLE
current.prepareImportedApproach { approached ->
routeLoading?.visibility = View.GONE
if (!approached) hint.text = "No se pudo calcular el camino hasta el inicio del GPX · dirígete al primer punto"
// The sheet may have been closed while the leg was calculated: then do not start.
if (routeDialog?.isShowing == true && current.preparedRouteIsImported()) perform(Action.ROUTE)
}
}
}
/** Coarse first fixes are common: wait for guidance accuracy instead of refusing to start. */
private fun startWhenGuidanceReady(message: String, start: () -> Unit) {
val current = service ?: return
positionWait?.cancel()
if (current.hasGuidanceGpsFix()) { perform(Action.ROUTE); return }
if (current.hasGuidanceGpsFix()) { start(); return }
current.setPhoneVisible(true)
hint.text = "Esperando GPS preciso para iniciar el GPX…"
hint.text = message
routeLoading?.visibility = View.VISIBLE
startButton?.isEnabled = false
positionWait = scope.launch {
@@ -408,10 +423,13 @@ open class MainActivity : Activity() {
// Map readiness stays true while accuracy improves from 100 m to 25 m.
while (!current.hasGuidanceGpsFix()) delay(200)
}
ensureActive()
if (current.preparedRouteIsImported()) perform(Action.ROUTE)
} catch (_: TimeoutCancellationException) { hint.text = "Sin GPS preciso · activa ubicación y pulsa Iniciar navegación de nuevo" }
finally { routeLoading?.visibility = View.GONE; startButton?.isEnabled = current.hasPreparedRoute() }
} catch (_: TimeoutCancellationException) {
hint.text = "Sin GPS preciso · activa ubicación y pulsa Iniciar de nuevo"
return@launch
} finally { routeLoading?.visibility = View.GONE; startButton?.isEnabled = current.hasPreparedRoute() }
ensureActive()
hint.text = ""
start()
}
}
private fun cancelSearch() { searchGeneration++; searchJob?.cancel(); searchJob = null }
@@ -36,7 +36,7 @@ class TftService : Service() {
private var lastGpsElapsed = 0L
private val mutableRouteInfo = MutableStateFlow("Sin ruta calculada")
val routeInfo = mutableRouteInfo.asStateFlow()
private data class RoutePlan(val route: RouteResult, val origin: GeoPoint, val demo: Boolean, val options: RouteOptions = RouteOptions())
private data class RoutePlan(val route: RouteResult, val origin: GeoPoint, val demo: Boolean, val options: RouteOptions = RouteOptions(), val importedBase: RouteResult? = null)
private var navigationJob: Job? = null
private var locationProvider: AndroidLocationProvider? = null
private var gpsRequested = false
@@ -628,6 +628,35 @@ class TftService : Service() {
}
}
}
/**
* Before starting an imported route away from its first point, prepend a road leg from the
* current position. [onReady] receives false when that leg could not be calculated.
*/
fun prepareImportedApproach(onReady: (Boolean) -> Unit) {
val plan = routePlan?.takeIf { !preparedDestinationDirty && it.route.imported } ?: return onReady(true)
val base = plan.importedBase ?: plan.route
val position = lastGpsFix?.position?.takeIf { hasGuidanceGpsFix() } ?: return onReady(false)
if (!needsApproach(position, base)) { if (plan.importedBase != null) routePlan = plan.copy(route = base, origin = base.geometry.first(), importedBase = null); return onReady(true) }
val generation = preparedGeneration
mutableRouteInfo.value = "Calculando el camino hasta el inicio del GPX…"
routeJob?.cancel()
routeJob = scope.launch {
try {
val approach = routingEngineFactory(routingEndpoint()).calculateRoute(position, base.geometry.first(), RouteOptions(profile = RouteProfile.FASTEST, avoidUnpaved = true))
ensureActive()
if (generation != preparedGeneration || routePlan !== plan) return@launch
val route = prependApproach(approach, base)
RouteGuidanceTracker(route) // Validate before replacing the plan.
routePlan = plan.copy(route = route, origin = position, importedBase = base)
mutableRouteInfo.value = "Camino hasta el inicio del GPX calculado · %.1f km".format(java.util.Locale.ROOT, approach.distanceMeters / 1000.0)
onReady(true)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Exception) {
if (generation == preparedGeneration && routePlan === plan) { routePlan = plan.copy(route = base, origin = base.geometry.first(), importedBase = null); mutableRouteInfo.value = "Sin camino hasta el inicio del GPX · dirígete al primer punto"; onReady(false) }
}
}
}
/** Positive steps zoom in. Called from the phone and from handlebar requests. */
fun adjustTftZoom(steps: Int) {
val next = TftCameraPolicy.stepOffset(tftZoomOffset, steps)
@@ -206,6 +206,7 @@ class ImportedRouteTest {
assertTrue(service.gpsReady.value)
assertTrue(service.hasFreshGpsFix())
assertFalse(service.hasGuidanceGpsFix())
MainActivity::class.java.getDeclaredMethod("showImportedRouteSheet", String::class.java).apply { isAccessible = true }.invoke(activity, "Weekend")
MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity)
val pending = field("positionWait").get(activity) as kotlinx.coroutines.Job
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
@@ -241,4 +242,39 @@ class ImportedRouteTest {
assertEquals(3, service.navigationState.value.route?.geometry?.size)
} finally { controller.destroy() }
}
@Test fun importedStartAwayFromTheFirstPointRoutesThereFirst() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
val application = RuntimeEnvironment.getApplication()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
field("service").set(activity, service)
val manager = application.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
val route = imported()
service.prepareImportedRoute(route); tick()
service.setPhoneVisible(true); tick()
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 43.35; longitude = -5.85; accuracy = 5f // About 1.1 km before the first point.
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
val engine = RoadEngine()
service.routingEngineFactory = { engine }
MainActivity::class.java.getDeclaredMethod("showImportedRouteSheet", String::class.java).apply { isAccessible = true }.invoke(activity, "Weekend")
MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity); tick()
assertEquals(listOf(GeoPoint(43.35, -5.85) to route.route.geometry.first()), engine.requests)
assertEquals(TftService.ACTION_ROUTE_GPS, shadowOf(activity).nextStartedService.action)
service.startRoute(); tick()
val started = service.navigationState.value.route!!
assertEquals(GeoPoint(43.35, -5.85), started.geometry.first())
assertEquals(route.route.geometry.last(), started.geometry.last())
assertTrue(started.maneuvers.isEmpty())
assertNull(service.navigationState.value.etaEpochMillis)
} finally { activityController.destroy(); serviceController.destroy() }
}
}