feat: import GPX traces and start navigation without destination search

This commit is contained in:
Darío Sevilla committed 2026-10-13 09:43:16 +00:00
1 parent cffdeb39c4
commit 317f8cbfaa
9 files changed
+508 -19

No files matched your search

@@ -44,6 +44,8 @@ data class RouteResult(
val hasUnpaved: Boolean? = null,
/** Locale of the server-provided maneuver text; retained until this route is replaced. */
val guidanceLanguage: String = "es-ES",
/** Imported geometry has no verified road maneuvers or travel-time estimate. */
val imported: Boolean = false,
)
enum class RouteProfile { FASTEST, AVOID_MOTORWAYS, TOURING, AVOID_UNPAVED }
/** Preferences, not guarantees or legal/surface certification. Presets combine with explicit flags. */
@@ -0,0 +1,115 @@
package dev.navframe.core
import java.io.ByteArrayInputStream
import java.io.InputStream
import javax.xml.parsers.SAXParserFactory
import org.xml.sax.Attributes
import org.xml.sax.InputSource
import org.xml.sax.SAXException
import org.xml.sax.ext.DefaultHandler2
import kotlin.math.*
data class ImportedRoute(val name: String?, val route: RouteResult)
/** 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
const val MAX_DEPTH = 64
private val namespaces = setOf("", "http://www.topografix.com/GPX/1/0", "http://www.topografix.com/GPX/1/1")
fun parse(input: InputStream): ImportedRoute {
val bytes = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
if (bytes.size() + read > MAX_BYTES) fail("El archivo GPX supera los 5 MiB. Exporta una ruta más pequeña.")
bytes.write(buffer, 0, read)
}
val handler = Handler()
try {
val factory = SAXParserFactory.newInstance().apply { isNamespaceAware = true }
val reader = factory.newSAXParser().xmlReader
// Lexical handling is mandatory: reject DTD before any entity can be expanded.
reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler)
for (feature in listOf("http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://apache.org/xml/features/nonvalidating/load-external-dtd")) {
try { reader.setFeature(feature, false) } catch (_: SAXException) { /* The rejecting resolver remains active. */ }
}
reader.contentHandler = handler
reader.entityResolver = handler
reader.errorHandler = handler
reader.parse(InputSource(ByteArrayInputStream(bytes.toByteArray())))
} catch (error: IllegalArgumentException) {
throw error
} catch (_: Exception) {
fail("No se pudo leer el GPX. Comprueba que sea un archivo GPX válido sin DTD ni entidades externas.")
}
val points = handler.points
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.")
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,
))
}
private class Handler : DefaultHandler2() {
val points = mutableListOf<GeoPoint>()
var name: String? = null
private val path = mutableListOf<String>()
private var rootNamespace = ""
private var candidates = 0
private var nonemptySegments = 0
private var segmentPoints = 0
private var nameText: StringBuilder? = null
override fun startDTD(name: String?, publicId: String?, systemId: String?) = fail("El GPX contiene un DTD no permitido.")
override fun resolveEntity(publicId: String?, systemId: String?): InputSource = fail("El GPX contiene entidades externas no permitidas.")
override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
if (path.size >= MAX_DEPTH) fail("El GPX tiene demasiados niveles XML.")
if (path.isEmpty()) {
if (localName != "gpx" || uri !in namespaces) fail("Selecciona un archivo GPX 1.0 o 1.1 válido.")
rootNamespace = uri
}
path.add(if (uri == rootNamespace) localName else "#extension")
val route = path == listOf("gpx", "rte")
val track = path == listOf("gpx", "trk")
if (route || track) {
candidates++
if (candidates > 1) fail("El GPX contiene varias rutas o tracks. Exporta solo la ruta que quieras seguir.")
}
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 (points.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.")
points.add(GeoPoint(lat, lon))
if (path[1] == "trk") segmentPoints++
}
}
override fun characters(ch: CharArray, start: Int, length: Int) {
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) {
nameText?.let { if (it.length < 256) it.append(ch, start, minOf(length, 256 - it.length)) }
}
}
override fun endElement(uri: String, localName: String, qName: String) {
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) { name = nameText?.toString(); nameText = null }
if (path == listOf("gpx", "trk", "trkseg") && segmentPoints > 0) {
nonemptySegments++
if (nonemptySegments > 1) fail("El GPX contiene varios segmentos separados. Exporta un solo segmento continuo.")
}
path.removeAt(path.lastIndex)
}
}
private fun distance(a: GeoPoint, b: GeoPoint): Double {
val lat = Math.toRadians(b.latitude - a.latitude)
val lon = Math.toRadians(b.longitude - a.longitude)
val h = sin(lat / 2).pow(2) + cos(Math.toRadians(a.latitude)) * cos(Math.toRadians(b.latitude)) * sin(lon / 2).pow(2)
return 6_371_000.0 * 2 * asin(sqrt(h.coerceIn(0.0, 1.0)))
}
private fun fail(message: String): Nothing = throw IllegalArgumentException(message)
}
@@ -52,7 +52,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 = epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) {
outside.reset(); arrival.reset()
needsRecovery = false
@@ -96,7 +96,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 = epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
return remember(line.guidedState(base, progress, epochMs))
}
}
@@ -131,9 +131,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 = epochMs, navigationStatus = NavigationStatus.ARRIVED)
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)
val state = line.guidedState(base, progress, epochMs)
return state.copy(etaEpochMillis = saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
return state.copy(etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
}
}
@@ -226,7 +226,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 = saturatedAdd(epochMs, etaMs),
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, etaMs),
navigationStatus = NavigationStatus.NAVIGATING)
}
fun pointAt(progress: Double): Pair<GeoPoint, Float> {
@@ -0,0 +1,91 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
import java.io.ByteArrayInputStream
class GpxRouteImporterTest {
private val points = "<rtept lat=\"43\" lon=\"-5\"/><rtept lat=\"43.001\" lon=\"-5\"/>"
private fun parse(xml: String) = GpxRouteImporter.parse(ByteArrayInputStream(xml.toByteArray()))
private fun rejected(xml: String, expected: String? = null) {
try { parse(xml); fail("Expected rejected GPX") } catch (error: IllegalArgumentException) {
expected?.let { assertTrue(error.message.orEmpty(), error.message.orEmpty().contains(it)) }
}
}
@Test fun `imports route geometry without invented guidance`() {
val result = parse("<gpx><rte><name> Asturias &amp; Costa </name>$points</rte></gpx>")
assertEquals("Asturias & Costa", result.name)
assertEquals(2, result.route.geometry.size)
assertEquals(111, result.route.distanceMeters)
assertEquals(0, result.route.durationSeconds)
assertTrue(result.route.maneuvers.isEmpty())
assertTrue(result.route.imported)
assertEquals(result.route.geometry.last(), result.route.destination)
}
@Test fun `supports standard namespaces and prefixed GPX`() {
for (version in listOf("1/0", "1/1")) {
assertEquals(2, parse("<gpx xmlns=\"http://www.topografix.com/GPX/$version\"><rte>$points</rte></gpx>").route.geometry.size)
}
assertEquals(2, parse("<p:gpx xmlns:p=\"http://www.topografix.com/GPX/1/1\"><p:rte><p:rtept lat=\"0\" lon=\"0\"/><p:rtept lat=\"1\" lon=\"1\"/></p:rte></p:gpx>").route.geometry.size)
}
@Test fun `imports track and ignores empty segments and waypoints`() {
val trackPoints = points.replace("rtept", "trkpt")
val result = parse("<gpx><wpt lat=\"90\" lon=\"180\"/><trk><name>Track</name><trkseg/><trkseg>$trackPoints</trkseg><trkseg/></trk></gpx>")
assertEquals("Track", result.name)
assertEquals(2, result.route.geometry.size)
}
@Test fun `rejects multiple candidates and disconnected segments`() {
rejected("<gpx><rte>$points</rte><rte>$points</rte></gpx>", "varias")
rejected("<gpx><rte>$points</rte><trk/></gpx>", "varias")
val segment = "<trkseg>${points.replace("rtept", "trkpt")}</trkseg>"
rejected("<gpx><trk>$segment$segment</trk></gpx>", "segmentos")
}
@Test fun `rejects DTD internal and external entities`() {
rejected("<!DOCTYPE gpx [<!ENTITY name 'expanded'>]><gpx><rte><name>&name;</name>$points</rte></gpx>")
rejected("<!DOCTYPE gpx SYSTEM 'file:///etc/passwd'><gpx><rte>$points</rte></gpx>")
rejected("<!DOCTYPE gpx [<!ENTITY x SYSTEM 'https://example.com/secret'>]><gpx><rte><name>&x;</name>$points</rte></gpx>")
}
@Test fun `rejects invalid empty and stationary geometry`() {
for (value in listOf("NaN", "Infinity", "91", "nope")) rejected("<gpx><rte><rtept lat=\"$value\" lon=\"0\"/>$points</rte></gpx>")
rejected("<gpx><rte><rtept lat=\"0\" lon=\"181\"/>$points</rte></gpx>")
rejected("<gpx/>")
rejected("<gpx><rte><rtept lat=\"0\" lon=\"0\"/><rtept lat=\"0\" lon=\"0\"/></rte></gpx>", "distintos")
rejected("<other><rte>$points</rte></other>")
rejected("<gpx xmlns=\"https://example.com\"><rte>$points</rte></gpx>")
rejected("<gpx><rte>$points")
}
@Test fun `does not import points from extensions`() {
rejected("<gpx><extensions><rte>$points</rte></extensions></gpx>")
rejected("<gpx xmlns:x=\"https://example.com\"><rte><x:rtept lat=\"0\" lon=\"0\"/><x:rtept lat=\"1\" lon=\"1\"/></rte></gpx>")
}
@Test fun `bounds bytes points and nesting`() {
rejected(" ".repeat(GpxRouteImporter.MAX_BYTES + 1), "5 MiB")
rejected("<gpx><rte>" + "<rtept lat=\"1\" lon=\"1\"/>".repeat(GpxRouteImporter.MAX_POINTS + 1) + "</rte></gpx>", "10000")
rejected("<gpx>" + "<extensions>".repeat(GpxRouteImporter.MAX_DEPTH) + "</extensions>".repeat(GpxRouteImporter.MAX_DEPTH) + "</gpx>", "niveles")
}
@Test fun `bounded name and submeter route remain usable`() {
val result = parse("<gpx><rte><name>${"x".repeat(1000)}</name><rtept lat=\"0\" lon=\"0\"/><rtept lat=\"0.000001\" lon=\"0\"/></rte></gpx>")
assertEquals(256, result.name!!.length)
assertEquals(1, result.route.distanceMeters)
}
@Test fun `imported route tracks progress without turns or ETA and confirms deviation`() {
val route = parse("<gpx><rte><rtept lat=\"0\" lon=\"0\"/><rtept lat=\"0\" lon=\"0.01\"/></rte></gpx>").route
val tracker = RouteGuidanceTracker(route)
fun fix(lat: Double, time: Long) = LocationFix(GeoPoint(lat, 0.005), 90f, 5f, 5f, time)
val onLine = tracker.update(fix(0.0, 1), 0, 100_000)
assertEquals(NavigationStatus.NAVIGATING, onLine.navigationStatus)
assertEquals(556, onLine.remainingDistanceMeters!!)
assertNull(onLine.etaEpochMillis)
assertNull(onLine.nextManeuver)
assertNull(onLine.distanceToNextManeuverMeters)
// A 56m displacement is believable movement, but clearly outside the route corridor.
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.0005, 2), 1_000, 101_000).navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.0005, 3), 4_000, 104_000).navigationStatus)
val outside = tracker.update(fix(0.0005, 4), 6_000, 106_000)
assertEquals(NavigationStatus.OFF_ROUTE, outside.navigationStatus)
assertNull(outside.nextManeuver)
assertNull(outside.distanceToNextManeuverMeters)
assertNull(outside.etaEpochMillis)
}
}