mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 07:16:06 +00:00
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:
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() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +275,10 @@ private class RouteLine(private val route: RouteResult) {
|
||||
private fun validPoint(point: GeoPoint) = point.latitude.isFinite() && point.longitude.isFinite() &&
|
||||
point.latitude in -90.0..90.0 && point.longitude in -180.0..180.0
|
||||
private fun wrappedLongitude(value: Double): Double = ((value + 180) % 360 + 360) % 360 - 180
|
||||
/** Farther than this from an imported route's first point, a road leg to it is prepended on start. */
|
||||
const val IMPORTED_APPROACH_MIN_METERS = 150.0
|
||||
fun needsApproach(position: GeoPoint, route: RouteResult): Boolean =
|
||||
route.geometry.isNotEmpty() && earthDistance(position, route.geometry.first()) > IMPORTED_APPROACH_MIN_METERS
|
||||
private fun earthDistance(a: GeoPoint, b: GeoPoint): Double {
|
||||
val lat1 = Math.toRadians(a.latitude); val lat2 = Math.toRadians(b.latitude)
|
||||
val dlat = lat2 - lat1; val dlon = Math.toRadians(wrappedLongitude(b.longitude - a.longitude))
|
||||
|
||||
@@ -192,6 +192,15 @@ fun mergeRouteLegs(parts: List<RouteResult>): RouteResult {
|
||||
guidanceLanguage = parts.first().guidanceLanguage)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefix [route] with a road leg from the rider's position to its first point. A trace stays a
|
||||
* trace: no turn instructions or ETA, the leg only extends the line to follow.
|
||||
*/
|
||||
fun prependApproach(approach: RouteResult, route: RouteResult): RouteResult {
|
||||
val merged = mergeRouteLegs(listOf(approach, route))
|
||||
return if (route.imported && route.maneuvers.isEmpty()) merged.copy(maneuvers = emptyList(), durationSeconds = 0) else merged
|
||||
}
|
||||
|
||||
private fun validatePoint(point: GeoPoint) {
|
||||
if (!point.latitude.isFinite() || !point.longitude.isFinite() ||
|
||||
point.latitude !in -90.0..90.0 || point.longitude !in -180.0..180.0) invalid("Invalid routing coordinate")
|
||||
|
||||
@@ -189,4 +189,23 @@ class ValhallaRouteTest {
|
||||
// Independently snapped endpoints that do not coincide keep both points.
|
||||
assertEquals(6, mergeRouteLegs(listOf(part(a, b, c, true), part(GeoPoint(43.0201, -5.0), GeoPoint(43.025, -5.0), d, false))).geometry.size)
|
||||
}
|
||||
|
||||
@Test fun `imported routes get a road leg from a distant rider position`() {
|
||||
val start = GeoPoint(43.0, -5.0)
|
||||
val trace = RouteResult(listOf(start, GeoPoint(43.01, -5.0)), emptyList(), 1_100, 0, GeoPoint(43.01, -5.0), imported = true)
|
||||
assertFalse(needsApproach(GeoPoint(43.0005, -5.0), trace)) // About 55 m away.
|
||||
assertTrue(needsApproach(GeoPoint(42.99, -5.0), trace))
|
||||
val approach = RouteResult(listOf(GeoPoint(42.99, -5.0), start), listOf(
|
||||
Maneuver("start", 1_100, type = 1, beginShapeIndex = 0, endShapeIndex = 1),
|
||||
Maneuver("arrive", 0, type = 4, beginShapeIndex = 1, endShapeIndex = 1),
|
||||
), 1_100, 90, start)
|
||||
val merged = prependApproach(approach, trace)
|
||||
assertEquals(3, merged.geometry.size)
|
||||
assertTrue(merged.maneuvers.isEmpty()) // Still a trace to follow.
|
||||
assertEquals(2_200, merged.distanceMeters)
|
||||
assertTrue(merged.imported)
|
||||
assertEquals(trace.destination, merged.destination)
|
||||
assertEquals(0, merged.durationSeconds) // A trace never shows an ETA.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Open **☰ → Cargar ruta GPX**, then choose a `.gpx` file using Android's document picker. The app displays the name and distance and previews the route when no other navigation session is active. Files made of route points, waypoints or sparse tracks are first joined along roads (see below). After a valid file is selected and any road calculation succeeds, navigation starts automatically with real GPS as soon as location permission and a recent accurate fix are available. No destination search is needed. A pending import leaves existing navigation running until the new trace can start. The **Iniciar navegación** button retries after a timeout or permission denial.
|
||||
|
||||
Precise location permission is required to start navigation. If a recent fix with accuracy of 25 metres or better is unavailable, the app waits up to 60 seconds. Close the import panel or stop the route to cancel that wait. When the wait expires, enable location and tap **Iniciar navegación** to retry. Denying permission leaves the trace available for review.
|
||||
Precise location permission is required to start navigation. If a recent fix with accuracy of 25 metres or better is unavailable, the app waits up to 60 seconds (searched destinations wait the same way instead of refusing to start). Close the import panel or stop the route to cancel that wait. When the wait expires, enable location and tap **Iniciar navegación** to retry. Denying permission leaves the trace available for review.
|
||||
|
||||
## Supported files
|
||||
|
||||
@@ -16,9 +16,13 @@ Route points (`rtept`), waypoints and sparse tracks (median gap between points a
|
||||
|
||||
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.
|
||||
|
||||
## Starting away from the first point
|
||||
|
||||
On start, if the rider is more than 150 m from the route's first point, the app calculates a road leg from the current position to that point (fastest motorcycle route, avoiding unpaved roads) and prepends it, so guidance begins where the rider actually is. A dense trace stays a trace: the leg extends the line to follow, without turn instructions or ETA. The leg is not recalculated if you leave it. If the leg cannot be calculated, navigation starts on the imported route alone and the app asks the rider to head to the first point. Pressing start again later recalculates the leg from the new position.
|
||||
|
||||
## Following a trace
|
||||
|
||||
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.
|
||||
Dense tracks keep their original coordinates in memory and are drawn on the phone and TFT. Following such a trace sends no GPX coordinates to a routing server; only the optional leg from your position to its first point is calculated online. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time.
|
||||
|
||||
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace. After a confirmed deviation, three fresh, stable GPS fixes spanning at least two seconds automatically resume progress at the nearest point of the original trace, whether you rejoin ahead of or behind the previous position. GPS jumps and inaccurate fixes cannot confirm a rejoin.
|
||||
|
||||
|
||||
Reference in new issue
Block a user