Initial public NavFrame release with global regional package pipeline

This commit is contained in:
dasemu committed 2026-09-30 17:34:58 +02:00
commit d863f2b940
143 files changed
+17906

No files matched your search

@@ -0,0 +1,83 @@
package dev.navframe.core
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
enum class ConnectionState { DISCONNECTED, CONNECTING, HANDSHAKING, CONNECTED, ERROR }
data class TftFrame(
val width: Int = 480,
val height: Int = 240,
val encodedBytes: ByteArray,
val timestampMs: Long,
) {
init { require(width == 480 && height == 240) { "M1 requires a native 480×240 frame" } }
}
interface TftTransport {
val connectionState: StateFlow<ConnectionState>
suspend fun connect()
suspend fun disconnect()
suspend fun sendFrame(frame: TftFrame)
}
interface TftRenderer { suspend fun render(state: NavigationState): TftFrame }
data class GeoPoint(val latitude: Double, val longitude: Double)
data class Maneuver(
val instruction: String,
/** Length of this maneuver's segment, not the rider's distance to the next turn. */
val distanceMeters: Int,
val type: Int? = null,
val beginShapeIndex: Int? = null,
val endShapeIndex: Int? = null,
val durationSeconds: Int = 0,
val streetNames: List<String> = emptyList(),
)
data class RouteResult(
val geometry: List<GeoPoint>,
val maneuvers: List<Maneuver>,
val distanceMeters: Int,
val durationSeconds: Int,
/** Requested destination; may differ from the endpoint snapped to a road. */
val destination: GeoPoint? = null,
/** Valhalla maneuver.rough evidence; null when response does not establish the surface. */
val hasUnpaved: Boolean? = null,
/** Locale of the server-provided maneuver text; retained until this route is replaced. */
val guidanceLanguage: String = "es-ES",
)
enum class RouteProfile { FASTEST, AVOID_MOTORWAYS, TOURING, AVOID_UNPAVED }
/** Preferences, not guarantees or legal/surface certification. Presets combine with explicit flags. */
data class RouteOptions(
val profile: RouteProfile = RouteProfile.FASTEST,
val avoidMotorways: Boolean = false,
val avoidUnpaved: Boolean = false,
val avoidTolls: Boolean = false,
)
interface RoutingEngine {
suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult
suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions): RouteResult
}
data class SearchResult(
val name: String,
val position: GeoPoint,
val attribution: String = "© OpenStreetMap contributors",
)
interface Geocoder { suspend fun search(query: String): List<SearchResult> }
data class MapRegion(val name: String, val southWest: GeoPoint, val northEast: GeoPoint)
data class TileSource(val uri: String, val attribution: String)
interface MapDataSource { suspend fun prepareRegion(region: MapRegion); fun tileSource(): TileSource }
data class LocationFix(val position: GeoPoint, val bearing: Float, val speedMetersPerSecond: Float, val accuracyMeters: Float, val timestampMs: Long)
interface LocationProvider { val locations: Flow<LocationFix>; suspend fun start(); suspend fun stop() }
enum class NavigationStatus { IDLE, SEARCHING, ROUTE_PREVIEW, NAVIGATING, OFF_ROUTE, REROUTING, ARRIVED, GPS_LOST, TFT_DISCONNECTED, ERROR }
data class NavigationState(
val position: GeoPoint = GeoPoint(0.0, 0.0),
val bearing: Float = 0f,
val speed: Float = 0f,
val route: RouteResult? = null,
val nextManeuver: Maneuver? = null,
val distanceToNextManeuverMeters: Int? = null,
val remainingDistanceMeters: Int? = null,
val etaEpochMillis: Long? = null,
val navigationStatus: NavigationStatus = NavigationStatus.IDLE,
val accuracyMeters: Float? = null,
)
@@ -0,0 +1,25 @@
package dev.navframe.core
import kotlin.math.sin
/** Deterministic synthetic demonstration. These are invented positions and maneuvers, never a GPS fix. */
object DemoNavigation {
fun stateAt(elapsedMs: Long, startEpochMillis: Long = 1_800_000_000_000L): NavigationState {
require(elapsedMs >= 0)
val seconds = elapsedMs / 1000.0
val progressSeconds = (elapsedMs % 300_000) / 1000.0
val turnCycle = (elapsedMs / 30_000) % 2
val turnDistance = (350 - (elapsedMs % 30_000) * 350 / 30_000).toInt()
val speed = (8 + 2 * sin(seconds / 12)).toFloat()
return NavigationState(
position = GeoPoint(43.36 + progressSeconds * 0.00004, -5.85 + 0.0002 * sin(seconds / 10)),
bearing = normalizeBearing((35 + 30 * sin(seconds / 8)).toFloat()),
speed = speed,
nextManeuver = Maneuver(if (turnCycle == 0L) "DEMO · giro derecha" else "DEMO · giro izquierda", turnDistance),
distanceToNextManeuverMeters = turnDistance,
remainingDistanceMeters = (23_000 - progressSeconds * 8).toInt(),
etaEpochMillis = startEpochMillis + 18 * 60_000,
navigationStatus = NavigationStatus.NAVIGATING,
)
}
}
@@ -0,0 +1,60 @@
package dev.navframe.core
import java.util.Locale
/** App-owned speech templates; Valhalla provides maneuver instructions in the same locale. */
enum class GuidanceLanguage(val tag: String, val nativeName: String) {
SPANISH("es-ES", "Español"), ENGLISH("en-US", "English"),
GERMAN("de-DE", "Deutsch"), FRENCH("fr-FR", "Français"), ITALIAN("it-IT", "Italiano");
fun status(status: NavigationStatus): String = when (this) {
SPANISH -> when (status) {
NavigationStatus.ARRIVED -> "Has llegado a tu destino."
NavigationStatus.REROUTING -> "Recalculando ruta."
NavigationStatus.OFF_ROUTE -> "Te has desviado de la ruta."
else -> "Señal GPS insuficiente. Espera nuevas indicaciones."
}
GERMAN -> when (status) {
NavigationStatus.ARRIVED -> "Du hast dein Ziel erreicht."
NavigationStatus.REROUTING -> "Route wird neu berechnet."
NavigationStatus.OFF_ROUTE -> "Du bist von der Route abgewichen."
else -> "GPS-Signal unzureichend. Warte auf neue Anweisungen."
}
FRENCH -> when (status) {
NavigationStatus.ARRIVED -> "Vous êtes arrivé à destination."
NavigationStatus.REROUTING -> "Recalcul de l'itinéraire."
NavigationStatus.OFF_ROUTE -> "Vous avez quitté l'itinéraire."
else -> "Signal GPS insuffisant. Attendez de nouvelles instructions."
}
ITALIAN -> when (status) {
NavigationStatus.ARRIVED -> "Hai raggiunto la destinazione."
NavigationStatus.REROUTING -> "Ricalcolo del percorso."
NavigationStatus.OFF_ROUTE -> "Hai lasciato il percorso."
else -> "Segnale GPS insufficiente. Attendi nuove indicazioni."
}
ENGLISH -> when (status) {
NavigationStatus.ARRIVED -> "You have arrived at your destination."
NavigationStatus.REROUTING -> "Recalculating route."
NavigationStatus.OFF_ROUTE -> "You have left the route."
else -> "GPS signal is insufficient. Wait for new directions."
}
}
fun maneuver(instruction: String, distance: Int, now: Boolean): String = when (this) {
SPANISH -> if (now) "Ahora, $instruction" else "En $distance metros, $instruction"
ENGLISH -> if (now) "Now, $instruction" else "In $distance meters, $instruction"
GERMAN -> if (now) "Jetzt, $instruction" else "In $distance Metern, $instruction"
FRENCH -> if (now) "Maintenant, $instruction" else "Dans $distance mètres, $instruction"
ITALIAN -> if (now) "Ora, $instruction" else "Tra $distance metri, $instruction"
}
fun camera(distance: Int): String = when (this) {
SPANISH -> "Posible radar fijo cerca, a unos $distance metros."
ENGLISH -> "Possible fixed speed camera nearby, about $distance meters away."
GERMAN -> "Möglicher stationärer Blitzer in etwa $distance Metern."
FRENCH -> "Radar fixe possible à environ $distance mètres."
ITALIAN -> "Possibile autovelox fisso a circa $distance metri."
}
companion object {
/** Unsupported system locales consistently use English for TTS, templates and routing. */
fun resolve(tag: String): GuidanceLanguage = entries.firstOrNull { Locale.forLanguageTag(it.tag).language == Locale.forLanguageTag(tag.replace('_', '-')).language } ?: ENGLISH
}
}
@@ -0,0 +1,61 @@
package dev.navframe.core
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.Strictness
private const val MAX_GEOCODING_RESPONSE_CHARS = 512 * 1024
private val geocodingJson = GsonBuilder().setStrictness(Strictness.STRICT).create()
private val coordinatePattern = Regex("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?")
/** Error messages deliberately omit addresses, queries, response JSON and coordinates. */
class GeocodingResponseException(message: String) : IllegalArgumentException(message)
/** Encode these parameters using the HTTP client's query encoder, never concatenate user text. */
fun nominatimSearchParameters(query: String): Map<String, String> {
require(query.length <= 200 && query.none { it.isISOControl() && !it.isWhitespace() }) { "Invalid destination query" }
val normalized = query.trim().replace(Regex("\\s+"), " ")
require(normalized.length in 2..200) { "Destination query must contain 2 to 200 characters" }
return linkedMapOf("q" to normalized, "format" to "jsonv2", "limit" to "5",
"accept-language" to "es", "addressdetails" to "0")
}
/** Strict jsonv2 response adapter. No provider implementation code or live fixture is embedded. */
fun parseNominatimResults(json: String): List<SearchResult> {
if (json.isBlank() || json.length > MAX_GEOCODING_RESPONSE_CHARS) invalidGeocoding("Invalid geocoding response size")
try {
val root = geocodingJson.fromJson(json, JsonElement::class.java)
if (root == null || !root.isJsonArray) invalidGeocoding("Invalid geocoding result list")
val list = root.asJsonArray
if (list.size() > 40) invalidGeocoding("Too many geocoding results")
return list.map { element ->
if (!element.isJsonObject) invalidGeocoding("Invalid geocoding result")
val item = element.asJsonObject
val name = cleanLabel(item.get("display_name").requiredText(), 2_048)
if (name.isEmpty()) invalidGeocoding("Missing destination label")
val latitude = item.get("lat").coordinate(-90.0, 90.0)
val longitude = item.get("lon").coordinate(-180.0, 180.0)
val attribution = item.get("licence")?.let { cleanLabel(it.requiredText(), 2_048) }
?.takeIf { it.isNotEmpty() } ?: "© OpenStreetMap contributors"
SearchResult(name, GeoPoint(latitude, longitude), attribution)
}.distinctBy { Triple(it.name, it.position.latitude, it.position.longitude) }.take(5)
} catch (error: GeocodingResponseException) {
throw error
} catch (_: RuntimeException) {
invalidGeocoding("Malformed geocoding response")
}
}
private fun invalidGeocoding(message: String): Nothing = throw GeocodingResponseException(message)
private fun JsonElement?.requiredText(): String =
if (this != null && isJsonPrimitive && asJsonPrimitive.isString) asString else invalidGeocoding("Invalid geocoding text")
private fun JsonElement?.coordinate(min: Double, max: Double): Double {
val text = requiredText()
if (text.length > 64 || !coordinatePattern.matches(text)) invalidGeocoding("Invalid geocoding coordinate")
return text.toDoubleOrNull()?.takeIf { it.isFinite() && it in min..max }
?: invalidGeocoding("Geocoding coordinate outside valid range")
}
private fun cleanLabel(text: String, maxLength: Int): String {
if (text.length > maxLength) invalidGeocoding("Geocoding label too long")
return text.map { if (it.isISOControl()) ' ' else it }.joinToString("").trim().replace(Regex("\\s+"), " ")
}
@@ -0,0 +1,32 @@
package dev.navframe.core
import java.text.Normalizer
import java.util.Locale
/** Original local-POI contract. Categories describe OSM tags, not verified services/open status. */
enum class PlaceCategory(val labelSpanish: String) {
FUEL("Gasolina"), WORKSHOP("Talleres"), FOOD("Comer"), LODGING("Dormir"), SHOPPING("Compras")
}
data class OfflinePlace(
val id: String,
val name: String,
val category: PlaceCategory,
val position: GeoPoint,
val address: String? = null,
val openingHours: String? = null,
val website: String? = null,
val phone: String? = null,
/** Straight-line distance from the explicitly selected search origin, never route distance. */
val distanceMeters: Double? = null,
)
/** Same algorithm as tools/offline/build-pois.py, including whitespace and combining marks. */
fun normalizePlaceSearch(value: String): String = Normalizer.normalize(value, Normalizer.Form.NFD)
.replace(Regex("\\p{M}+"), "")
.lowercase(Locale.ROOT)
.replace(Regex("[\\s\\p{Z}\\p{Cc}\\p{Cf}]+"), " ")
.trim()
/** For a parameterized LIKE query using ESCAPE '\\'; parameterization alone does not escape wildcards. */
fun escapePlaceLike(value: String): String = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
@@ -0,0 +1,218 @@
package dev.navframe.core
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.Strictness
import java.time.Instant
import kotlin.math.abs
private val regionalJson = GsonBuilder().setStrictness(Strictness.STRICT).create()
private const val MAX_REGIONAL_JSON = 32 * 1024 * 1024
private const val MAX_REGION_FILE = 500L * 1024 * 1024
/** Local package metadata only: it cannot enable networking or provide an offline routing engine. */
data class RegionalBounds(val south: Double, val west: Double, val north: Double, val east: Double) {
init {
require(listOf(south, west, north, east).all { it.isFinite() })
require(south >= -85.051129 && north <= 85.051129 && south < north && west >= -180 && east <= 180 && west < east)
// Region packs may represent any Geofabrik country or continental extract.
// Keep Web Mercator latitude bounds and reject antimeridian-spanning boxes.
}
fun contains(point: GeoPoint) = point.latitude in south..north && point.longitude in west..east
}
data class RegionalFile(val path: String, val bytes: Long, val sha256: String)
data class RegionalSource(
val provider: String, val extractUrl: String, val pbfSha256: String,
val coverageUrl: String, val coverageSha256: String, val license: String,
val recipe: String, val planetiler: String, val poiBuilder: String,
)
data class RegionalCoverage(val polygons: List<List<List<GeoPoint>>>) {
/** GeoJSON outer rings include their edges; holes exclude their interiors and edges. No antimeridian packs. */
fun contains(point: GeoPoint): Boolean = polygons.any { polygon ->
insideRing(point, polygon.first()) && polygon.drop(1).none { insideRing(point, it) }
}
}
data class RegionalManifest(
val schemaVersion: Int, val id: String, val name: String, val version: String, val osmTimestamp: String,
val bounds: RegionalBounds, val minZoom: Int, val maxZoom: Int, val attribution: String,
val mapSchema: String, val poiSchema: Int, val glyphs: String, val source: RegionalSource,
val map: RegionalFile, val pois: RegionalFile, val coverage: RegionalCoverage? = null,
) {
val totalBytes: Long get() = map.bytes + pois.bytes
fun covers(point: GeoPoint): Boolean = bounds.contains(point) && (coverage?.contains(point) ?: true)
}
data class RegionalArchive(val path: String, val bytes: Long, val sha256: String, val url: String? = null)
data class RegionalCatalogEntry(
val manifest: RegionalManifest,
val archive: RegionalArchive,
val countryCode: String? = null,
val country: String? = null,
val region: String? = null,
val cameraCount: Int? = null,
)
data class RegionalCatalog(val schemaVersion: Int, val regions: List<RegionalCatalogEntry>)
/** Strict original parser; errors never include untrusted JSON, coordinates, paths or URLs. */
fun parseRegionalManifest(json: String): RegionalManifest = regionalDecode { parseManifest(regionalObject(json)) }
fun parseRegionalCatalog(json: String): RegionalCatalog = regionalDecode {
val root = regionalObject(json)
require(root.int("schemaVersion") == 1)
val entries = root.required("regions").arrayValue()
require(entries.size() in 1..4096)
val seen = HashSet<String>()
val seenPaths = HashSet<String>()
RegionalCatalog(1, entries.map { item ->
val entry = item.objectValue()
val manifest = parseManifest(entry.required("manifest").objectValue())
require(seen.add(manifest.id))
val archive = entry.required("archive").objectValue()
val path = archive.text("path")
require(path.length <= 120 && path.matches(Regex("[a-z0-9][a-z0-9._-]*\\.navframe")) && !path.contains("..") && seenPaths.add(path))
val size = archive.long("bytes")
require(size in 127..(2 * MAX_REGION_FILE + MAX_REGIONAL_JSON))
val hash = archive.hash()
val url = archive.optionalText("url")?.also {
validateHttpsUrl(it)
require(java.net.URI(it).path.substringAfterLast('/') == path)
}
val countryCode = entry.optionalText("countryCode")?.also { require(it.matches(Regex("[A-Z]{2}"))) }
val country = entry.optionalText("country")?.humanText(100)
val region = entry.optionalText("region")?.also {
require(it.length in 1..160 && it.matches(Regex("[a-z0-9]+(?:[a-z0-9._/-]*[a-z0-9])?")) &&
!it.contains("..") && !it.contains("//"))
}
val cameraCount = entry.optionalInt("cameraCount")?.also { require(it >= 0) }
RegionalCatalogEntry(manifest, RegionalArchive(path, size, hash, url), countryCode, country, region, cameraCount)
})
}
private fun parseManifest(root: JsonObject): RegionalManifest {
require(root.int("schemaVersion") == 1)
val id = root.text("id")
require(id.length in 3..64 && id.matches(Regex("[a-z0-9]+(?:-[a-z0-9]+)*")))
val name = root.text("name").humanText(100)
val version = root.text("version")
require(version.length in 1..40 && version.matches(Regex("[A-Za-z0-9][A-Za-z0-9._-]*")) && !version.contains(".."))
val timestamp = root.text("osmTimestamp")
require(timestamp.matches(Regex("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")))
Instant.parse(timestamp)
val area = root.required("bounds").objectValue()
val bounds = RegionalBounds(area.number("south"), area.number("west"), area.number("north"), area.number("east"))
val minZoom = root.int("minZoom")
val maxZoom = root.int("maxZoom")
require(minZoom in 0..16 && maxZoom in minZoom..16)
val attribution = root.text("attribution").humanText(100)
require(attribution.contains("OpenStreetMap"))
val mapSchema = root.text("mapSchema")
val poiSchema = root.int("poiSchema")
val glyphs = root.text("glyphs")
require(mapSchema == "NavFrame Offline/1.0.0" && poiSchema == 1 && glyphs == "noto-sans-regular-0-2047")
val capabilities = root.required("capabilities").arrayValue().map { it.textValue() }
require(capabilities.size == 2 && capabilities.toSet() == setOf("map", "poi"))
val sourceObject = root.required("source").objectValue()
val source = RegionalSource(
sourceObject.text("provider"), sourceObject.text("extractUrl"), sourceObject.hash("pbfSha256"),
sourceObject.text("coverageUrl"), sourceObject.hash("coverageSha256"),
sourceObject.text("license"), sourceObject.text("recipe"), sourceObject.text("planetiler"), sourceObject.text("poiBuilder"),
)
require(source.provider == "Geofabrik" && source.license == "ODbL-1.0")
requireGeofabrikUrl(source.extractUrl, ".osm.pbf")
requireGeofabrikUrl(source.coverageUrl, ".poly")
require(source.recipe in setOf("NavFrame regional pack 1.0.0", "NavFrame regional pack 1.1.0") &&
source.planetiler == "0.10.2" && source.poiBuilder in setOf("NavFrame POI 1.0.0", "NavFrame POI 1.1.0"))
// Unknown routing/network capabilities are not silently adopted by this local-only format.
val map = parseFile(root.required("map").objectValue(), "map.pmtiles", 127)
val pois = parseFile(root.required("pois").objectValue(), "pois.sqlite", 4096)
val coverage = parseCoverage(root.required("coverage").objectValue(), bounds)
return RegionalManifest(1, id, name, version, timestamp, bounds, minZoom, maxZoom, attribution, mapSchema, poiSchema, glyphs, source, map, pois, coverage)
}
private fun requireGeofabrikUrl(value: String, suffix: String) {
val path = value.removePrefix("https://download.geofabrik.de/")
require(value.length <= 512 && value.startsWith("https://download.geofabrik.de/") &&
value.endsWith(suffix) && !value.contains("..") && !path.contains("//") &&
path.matches(Regex("[a-z0-9._/-]+")))
}
private fun validateHttpsUrl(value: String) {
try {
val uri = java.net.URI(value)
require(value.length <= 2048 && uri.scheme == "https" && !uri.host.isNullOrBlank() &&
uri.userInfo == null && uri.fragment == null)
} catch (_: Exception) {
throw IllegalArgumentException("Invalid regional archive URL")
}
}
private fun parseFile(root: JsonObject, expectedPath: String, minimum: Long): RegionalFile {
val path = root.text("path")
require(path == expectedPath)
val bytes = root.long("bytes")
require(bytes in minimum..MAX_REGION_FILE)
return RegionalFile(path, bytes, root.hash())
}
private fun parseCoverage(root: JsonObject, bounds: RegionalBounds): RegionalCoverage {
val coordinates = root.required("coordinates").arrayValue()
val polygons = when (root.text("type")) {
"Polygon" -> listOf(coordinates)
"MultiPolygon" -> coordinates.map { it.arrayValue() }
else -> error("Unsupported coverage")
}
require(polygons.size in 1..64)
var count = 0
return RegionalCoverage(polygons.map { polygon ->
require(polygon.size() in 1..64)
polygon.map { ring ->
val points = ring.arrayValue()
require(points.size() in 4..8192)
count += points.size()
require(count <= 8192)
points.map { item ->
val pair = item.arrayValue()
require(pair.size() == 2)
val point = GeoPoint(pair[1].finiteNumber(), pair[0].finiteNumber())
require(bounds.contains(point))
point
}.also { require(it.first() == it.last() && it.toSet().size >= 3) }
}
})
}
private fun insideRing(point: GeoPoint, ring: List<GeoPoint>): Boolean {
var inside = false
for (index in 0 until ring.lastIndex) {
val a = ring[index]; val b = ring[index + 1]
val cross = (point.longitude - a.longitude) * (b.latitude - a.latitude) - (point.latitude - a.latitude) * (b.longitude - a.longitude)
if (abs(cross) < 1e-10 && point.longitude in minOf(a.longitude, b.longitude)..maxOf(a.longitude, b.longitude) &&
point.latitude in minOf(a.latitude, b.latitude)..maxOf(a.latitude, b.latitude)) return true
if ((a.latitude > point.latitude) != (b.latitude > point.latitude) &&
point.longitude < (b.longitude - a.longitude) * (point.latitude - a.latitude) / (b.latitude - a.latitude) + a.longitude) inside = !inside
}
return inside
}
private inline fun <T> regionalDecode(block: () -> T): T = try { block() } catch (_: RuntimeException) {
throw IllegalArgumentException("Paquete regional inválido o incompatible")
}
private fun regionalObject(json: String): JsonObject {
require(json.length in 2..MAX_REGIONAL_JSON)
return (regionalJson.fromJson(json, JsonElement::class.java) ?: error("Missing JSON")).objectValue()
}
private fun JsonObject.required(name: String): JsonElement = get(name) ?: error("Missing field")
private fun JsonElement.objectValue() = if (isJsonObject) asJsonObject else error("Invalid object")
private fun JsonElement.arrayValue() = if (isJsonArray) asJsonArray else error("Invalid array")
private fun JsonElement.textValue(): String = if (isJsonPrimitive && asJsonPrimitive.isString) asString else error("Invalid text")
private fun JsonObject.text(name: String) = required(name).textValue()
private fun JsonObject.optionalText(name: String): String? = if (!has(name) || get(name).isJsonNull) null else text(name)
private fun JsonObject.optionalInt(name: String): Int? = if (!has(name) || get(name).isJsonNull) null else int(name)
private fun JsonElement.finiteNumber(): Double {
require(isJsonPrimitive && asJsonPrimitive.isNumber)
return asDouble.also { require(it.isFinite()) }
}
private fun JsonObject.number(name: String) = required(name).finiteNumber()
private fun JsonObject.long(name: String): Long {
val value = required(name)
require(value.isJsonPrimitive && value.asJsonPrimitive.isNumber)
val decimal = value.asBigDecimal
return decimal.longValueExact()
}
private fun JsonObject.int(name: String): Int = long(name).also { require(it in Int.MIN_VALUE..Int.MAX_VALUE) }.toInt()
private fun JsonObject.hash(): String = text("sha256").also { require(it.matches(Regex("[0-9a-f]{64}"))) }
private fun JsonObject.hash(name: String): String = text(name).also { require(it.matches(Regex("[0-9a-f]{64}"))) }
private fun String.humanText(limit: Int): String = also { require(length in 1..limit && isNotBlank() && none { it.isISOControl() }) }
@@ -0,0 +1,108 @@
package dev.navframe.core
import kotlin.math.*
/** Visual redraw policy. TFT keepalive retransmits a cached JPEG independently of this class. */
data class RenderScheduleConfig(
val stoppedMaxFps: Double = 1.0,
val movingMaxFps: Double = 5.0,
val turningMaxFps: Double = 10.0,
val movingSpeedMetersPerSecond: Float = 0.7f,
val positionDeltaMeters: Double = 2.0,
val bearingDeltaDegrees: Float = 3f,
val turningDeltaDegrees: Float = 15f,
val speedDeltaMetersPerSecond: Float = 0.5f,
val distanceLabelStepMeters: Int = 10,
) {
init {
require(listOf(stoppedMaxFps, movingMaxFps, turningMaxFps).all { it.isFinite() && it > 0 })
require(movingSpeedMetersPerSecond.isFinite() && movingSpeedMetersPerSecond >= 0)
require(positionDeltaMeters.isFinite() && positionDeltaMeters > 0)
require(bearingDeltaDegrees.isFinite() && bearingDeltaDegrees > 0)
require(turningDeltaDegrees.isFinite() && turningDeltaDegrees >= bearingDeltaDegrees)
require(speedDeltaMetersPerSecond.isFinite() && speedDeltaMetersPerSecond > 0)
require(distanceLabelStepMeters > 0)
}
}
/** Single-owner policy; callers use elapsed monotonic milliseconds and offer their freshest state. */
class RenderScheduler(private val config: RenderScheduleConfig = RenderScheduleConfig()) {
private var pending: NavigationState? = null
private var rendered: NavigationState? = null
private var renderedAtMs: Long? = null
fun offer(state: NavigationState) { pending = state }
/** Retains only the freshest offered state during a throttle interval; no queue of old fixes. */
fun takeIfDue(nowMs: Long): NavigationState? {
require(nowMs >= 0)
val latest = pending ?: return null
val previous = rendered
val previousTime = renderedAtMs
val clockReset = previousTime != null && nowMs < previousTime
if (previous != null && !clockReset) {
if (!changed(previous, latest)) return null
val moving = max(previous.speed, latest.speed) >= config.movingSpeedMetersPerSecond
val turning = moving && bearingDistance(previous.bearing, latest.bearing) >= config.turningDeltaDegrees
val fps = when { turning -> config.turningMaxFps; moving -> config.movingMaxFps; else -> config.stoppedMaxFps }
if (previousTime != null && nowMs - previousTime < ceil(1000.0 / fps).toLong()) return null
}
return latest
}
/** Commit only after successful rendering/encoding; a failed render must not advance this baseline. */
fun markRendered(state: NavigationState, nowMs: Long) {
require(nowMs >= 0)
rendered = state
renderedAtMs = nowMs
if (pending == state) pending = null
}
/** Query for a loop that supplies current state each tick. Call markRendered after success. */
fun shouldRender(state: NavigationState, nowMs: Long): Boolean {
offer(state)
return takeIfDue(nowMs) != null
}
/** Call on renderer/source replacement, so its first frame renders immediately. */
fun reset() { pending = null; rendered = null; renderedAtMs = null }
private fun changed(old: NavigationState, fresh: NavigationState): Boolean =
old.navigationStatus != fresh.navigationStatus || old.route != fresh.route ||
old.bearing.isFinite() != fresh.bearing.isFinite() || old.speed.isFinite() != fresh.speed.isFinite() ||
accuracyChanged(old.accuracyMeters, fresh.accuracyMeters) ||
old.nextManeuver?.instruction != fresh.nextManeuver?.instruction ||
label(old.distanceToNextManeuverMeters) != label(fresh.distanceToNextManeuverMeters) ||
label(old.remainingDistanceMeters) != label(fresh.remainingDistanceMeters) ||
old.etaEpochMillis?.div(60_000) != fresh.etaEpochMillis?.div(60_000) ||
abs(old.speed - fresh.speed) >= config.speedDeltaMetersPerSecond ||
distanceMeters(old.position, fresh.position) >= config.positionDeltaMeters ||
(max(old.speed, fresh.speed) >= config.movingSpeedMetersPerSecond &&
bearingDistance(old.bearing, fresh.bearing) >= config.bearingDeltaDegrees)
private fun label(distance: Int?): Int? = distance?.div(config.distanceLabelStepMeters)
private fun accuracyChanged(old: Float?, fresh: Float?): Boolean {
val first = old?.takeIf { it.isFinite() && it >= 0 }
val second = fresh?.takeIf { it.isFinite() && it >= 0 }
return if (first == null || second == null) first != second else abs(first - second) >= 2f
}
}
/** Heading is circular: 359° → 1° is a two-degree change. */
internal fun bearingDistance(first: Float, second: Float): Float {
val delta = abs(normalizeBearing(first) - normalizeBearing(second))
return min(delta, 360f - delta)
}
fun normalizeBearing(bearing: Float): Float =
if (!bearing.isFinite()) 0f else ((bearing % 360f) + 360f) % 360f
private fun distanceMeters(first: GeoPoint, second: GeoPoint): Double {
val lat1 = Math.toRadians(first.latitude)
val lat2 = Math.toRadians(second.latitude)
val dLat = lat2 - lat1
val dLon = Math.toRadians(second.longitude - first.longitude)
val a = sin(dLat / 2).pow(2) + cos(lat1) * cos(lat2) * sin(dLon / 2).pow(2)
return 6_371_000.0 * 2 * asin(sqrt(a.coerceIn(0.0, 1.0)))
}
@@ -0,0 +1,249 @@
package dev.navframe.core
import kotlin.math.*
/** Initial conservative thresholds, pending physical validation. Times use a monotonic clock. */
data class GuidanceConfig(
val maxFixAgeMs: Long = 15_000,
val maxAccuracyMeters: Float = 25f,
val offRouteMeters: Double = 40.0,
val offRouteDurationMs: Long = 5_000,
val offRouteFixes: Int = 3,
val arrivalRadiusMeters: Double = 25.0,
val arrivalRemainingMeters: Double = 30.0,
val arrivalDurationMs: Long = 2_000,
val arrivalFixes: Int = 3,
) {
init {
require(maxFixAgeMs > 0 && maxAccuracyMeters.isFinite() && maxAccuracyMeters > 0)
require(offRouteMeters.isFinite() && offRouteMeters > 0 && offRouteDurationMs >= 0 && offRouteFixes >= 2)
require(arrivalRadiusMeters.isFinite() && arrivalRadiusMeters > 0 && arrivalRemainingMeters.isFinite() && arrivalRemainingMeters > 0)
require(arrivalDurationMs >= 0 && arrivalFixes >= 2)
}
}
/** 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)
private var progress = 0.0
private var acquired = false
private var lastPoint: GeoPoint? = null
private var lastNow: Long? = null
private var lastTimestamp: Long? = null
private val outside = SustainedFixes()
private val arrival = SustainedFixes()
private var arrived = false
private var needsRecovery = false
private var lastState: NavigationState? = null
private fun remember(state: NavigationState): NavigationState { lastState = state; return state }
fun update(fix: LocationFix, nowMs: Long, epochMs: Long, fixAgeMs: Long = 0): NavigationState {
val base = NavigationState(position = fix.position, bearing = fix.bearing,
speed = fix.speedMetersPerSecond.takeIf { it.isFinite() && it >= 0 } ?: 0f,
route = route, accuracyMeters = fix.accuracyMeters)
val usable = validPoint(fix.position) && fixAgeMs in 0..config.maxFixAgeMs &&
fix.accuracyMeters.isFinite() && fix.accuracyMeters in 0f..config.maxAccuracyMeters &&
(lastNow == null || nowMs >= lastNow!!)
if (!usable) {
outside.reset(); arrival.reset()
needsRecovery = lastPoint != null
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
}
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))
if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) {
outside.reset(); arrival.reset()
needsRecovery = false
acquired = false
lastPoint = fix.position
lastNow = nowMs
lastTimestamp = fix.timestampMs
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
}
val elapsed = lastNow?.let { (nowMs - it).coerceAtMost(config.maxFixAgeMs) / 1000.0 } ?: 0.0
val movementAllowance = 60.0 + base.speed * elapsed * 3 + fix.accuracyMeters * 2
val forwardAllowance = if (!acquired) line.total else movementAllowance
val jumped = lastPoint?.let { earthDistance(it, fix.position) > movementAllowance } ?: false
// Remember an isolated jump so a subsequently stable, genuine off-route position can recover.
lastPoint = fix.position
lastNow = nowMs
lastTimestamp = fix.timestampMs
if (jumped) {
outside.reset(); arrival.reset()
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
}
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,
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) {
progress = max(progress, projection.local)
acquired = true
}
if (offRoute) {
arrival.reset()
return remember(base.copy(navigationStatus = NavigationStatus.OFF_ROUTE))
}
if (projection.distance > 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
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))
return remember(line.guidedState(base, progress, epochMs))
}
}
/** HTTP remains outside core. A request must be marked before launching IO and finished on all exits. */
class ReroutePolicy(private val cooldownMs: Long = 30_000) {
init { require(cooldownMs >= 1_000) }
private var inFlight = false
private var nextAllowedMs = Long.MIN_VALUE
fun shouldRequest(state: NavigationState, nowMs: Long): Boolean =
state.navigationStatus == NavigationStatus.OFF_ROUTE && !inFlight && nowMs >= nextAllowedMs
fun markRequested(nowMs: Long) {
check(!inFlight && nowMs >= nextAllowedMs) { "Reroute request already active or cooling down" }
inFlight = true
nextAllowedMs = saturatedAdd(nowMs, cooldownMs)
}
fun markFinished(nowMs: Long, retryAfterMs: Long = 0) {
require(retryAfterMs >= 0)
inFlight = false
nextAllowedMs = max(nextAllowedMs, saturatedAdd(nowMs, max(cooldownMs, retryAfterMs)))
}
fun reset() { inFlight = false; nextAllowedMs = Long.MIN_VALUE }
}
/** Deterministic simulation along a calculated route; caller must visibly label it DEMO. */
class RouteDemo(private val route: RouteResult, private val speedMetersPerSecond: Float = 12f) {
init { require(speedMetersPerSecond.isFinite() && speedMetersPerSecond > 0) }
private val line = RouteLine(route)
fun stateAt(elapsedMs: Long, epochMs: Long): NavigationState {
val progress = (elapsedMs.coerceAtLeast(0) / 1000.0 * speedMetersPerSecond).coerceAtMost(line.total)
val (position, bearing) = line.pointAt(progress)
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)
val state = line.guidedState(base, progress, epochMs)
return state.copy(etaEpochMillis = saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
}
}
enum class ManeuverDirection { LEFT, RIGHT, STRAIGHT, UTURN, ROUNDABOUT, ARRIVAL, UNKNOWN }
/** Valhalla's stable maneuver type IDs, independent of instruction language. */
fun maneuverDirection(type: Int?): ManeuverDirection = when (type) {
2, 9, 10, 11, 18, 20, 23, 37 -> ManeuverDirection.RIGHT
3, 14, 15, 16, 19, 21, 24, 38 -> ManeuverDirection.LEFT
12, 13 -> ManeuverDirection.UTURN
26, 27 -> ManeuverDirection.ROUNDABOUT
4, 5, 6 -> ManeuverDirection.ARRIVAL
1, 7, 8, 17, 22, 25 -> ManeuverDirection.STRAIGHT
else -> ManeuverDirection.UNKNOWN
}
private class SustainedFixes {
private var since: Long? = null
private var count = 0
private var confirmed = false
fun observe(condition: Boolean, distinct: Boolean, now: Long, needed: Int, duration: Long): Boolean {
if (!condition) { reset(); return false }
if (distinct) {
if (since == null) since = now
count = min(count + 1, needed)
confirmed = count >= needed && since?.let { now - it >= duration } == true
}
return confirmed
}
fun reset() { since = null; count = 0; confirmed = false }
}
private class RouteLine(private val route: RouteResult) {
val cumulative: DoubleArray
val total: Double
private val indexed: List<Pair<Maneuver, Double>>
init {
require(route.geometry.size >= 2 && route.geometry.all(::validPoint)) { "Invalid guidance geometry" }
cumulative = DoubleArray(route.geometry.size)
for (i in 1 until route.geometry.size) cumulative[i] = cumulative[i - 1] + earthDistance(route.geometry[i - 1], route.geometry[i])
total = cumulative.last()
require(total.isFinite() && total > 0) { "Empty guidance geometry" }
require(route.durationSeconds >= 0 && route.distanceMeters >= 0)
indexed = route.maneuvers.mapNotNull { maneuver ->
val begin = maneuver.beginShapeIndex ?: return@mapNotNull null
val end = maneuver.endShapeIndex ?: return@mapNotNull null
require(begin in route.geometry.indices && end in begin until route.geometry.size) { "Invalid guidance maneuver index" }
if (maneuver.type != null && maneuver.type in 1..3) null else maneuver to cumulative[begin]
}.sortedBy { it.second }
}
data class Projection(val distance: Double, val local: Double?, val localDistance: Double)
fun project(point: GeoPoint, previous: Double, forwardAllowance: Double): Projection {
var nearestDistance = Double.POSITIVE_INFINITY
var localDistance = Double.POSITIVE_INFINITY
var localProgress: Double? = null
for (i in 1 until route.geometry.size) {
val a = route.geometry[i - 1]; val b = route.geometry[i]
val scale = cos(Math.toRadians((a.latitude + b.latitude) / 2)).coerceAtLeast(0.000001)
val dx = wrappedLongitude(b.longitude - a.longitude) * scale
val dy = b.latitude - a.latitude
val px = wrappedLongitude(point.longitude - a.longitude) * scale
val py = point.latitude - a.latitude
val norm = dx * dx + dy * dy
val fraction = if (norm == 0.0) 0.0 else ((px * dx + py * dy) / norm).coerceIn(0.0, 1.0)
val projected = GeoPoint(a.latitude + dy * fraction, wrappedLongitude(a.longitude + wrappedLongitude(b.longitude - a.longitude) * fraction))
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
}
}
return Projection(nearestDistance, localProgress, localDistance)
}
fun guidedState(base: NavigationState, progress: Double, epochMs: Long): NavigationState {
val next = indexed.firstOrNull { (_, at) -> at + 5 >= progress }
val remaining = (total - progress).coerceAtLeast(0.0)
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),
navigationStatus = NavigationStatus.NAVIGATING)
}
fun pointAt(progress: Double): Pair<GeoPoint, Float> {
val end = (1 until cumulative.size).firstOrNull { cumulative[it] >= progress } ?: cumulative.lastIndex
val a = route.geometry[end - 1]; val b = route.geometry[end]
val segment = cumulative[end] - cumulative[end - 1]
val fraction = if (segment <= 0) 0.0 else ((progress - cumulative[end - 1]) / segment).coerceIn(0.0, 1.0)
val position = when {
fraction <= 0.0 -> a
fraction >= 1.0 -> b
else -> GeoPoint(a.latitude + (b.latitude - a.latitude) * fraction,
wrappedLongitude(a.longitude + wrappedLongitude(b.longitude - a.longitude) * fraction))
}
val lat1 = Math.toRadians(a.latitude); val lat2 = Math.toRadians(b.latitude)
val lon = Math.toRadians(wrappedLongitude(b.longitude - a.longitude))
val bearing = ((Math.toDegrees(atan2(sin(lon) * cos(lat2), cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lon))) + 360) % 360).toFloat()
return position to bearing
}
}
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
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))
val square = sin(dlat / 2).pow(2) + cos(lat1) * cos(lat2) * sin(dlon / 2).pow(2)
return 6_371_000.0 * 2 * asin(sqrt(square.coerceIn(0.0, 1.0)))
}
private fun saturatedAdd(a: Long, nonnegative: Long): Long = if (a > Long.MAX_VALUE - nonnegative) Long.MAX_VALUE else a + nonnegative
@@ -0,0 +1,57 @@
package dev.navframe.core
import kotlin.math.*
/** Community mapped fixed camera; raw OSM direction is evidence, not a certified traffic direction. */
data class SpeedCamera(val id: String, val position: GeoPoint, val direction: String? = null)
data class SpeedCameraAlert(val cameraId: String, val distanceMeters: Int) {
val label: String get() = "Posible radar fijo cerca · ≈$distanceMeters m"
}
/** Conservative proximity advisory. Distance is straight-line, never a route or lane guarantee. */
class SpeedCameraAlertEngine {
private val previous = mutableMapOf<String, Double>()
private val notified = mutableMapOf<String, Long>()
fun reset() { previous.clear(); notified.clear() }
fun update(fix: LocationFix, cameras: List<SpeedCamera>, nowMs: Long, fixAgeMs: Long = 0, route: RouteResult? = null): SpeedCameraAlert? {
if (route == null || route.geometry.size < 2 || fixAgeMs !in 0..5_000 || !fix.accuracyMeters.isFinite() || fix.accuracyMeters !in 0f..25f ||
!fix.speedMetersPerSecond.isFinite() || fix.speedMetersPerSecond < 3f || !fix.bearing.isFinite() ||
!valid(fix.position)) { previous.clear(); return null }
notified.entries.removeAll { nowMs - it.value > 600_000 }
val candidates = cameras.distinctBy { it.id }.filter { valid(it.position) && onRoute(it.position, route.geometry) }.mapNotNull { camera ->
val distance = cameraDistance(fix.position, camera.position)
val before = previous.put(camera.id, distance)
val heading = cameraBearing(fix.position, camera.position)
val delta = abs(((heading - fix.bearing + 540) % 360) - 180)
// Require a second fix establishing approach; bearing alone can be stale or noisy.
if (distance !in 35.0..500.0 || before == null || before - distance < 3 || delta > 25 ||
distance * sin(Math.toRadians(delta)) > 35 || notified.containsKey(camera.id)) null
else camera to distance
}
val visibleIds = cameras.map { it.id }.toSet()
previous.keys.retainAll(visibleIds)
val closest = candidates.minByOrNull { it.second } ?: return null
notified[closest.first.id] = nowMs
return SpeedCameraAlert(closest.first.id, (closest.second / 25).roundToInt() * 25)
}
private fun onRoute(camera: GeoPoint, geometry: List<GeoPoint>): Boolean = geometry.zipWithNext().any { (a, b) ->
val scale = cos(Math.toRadians(camera.latitude))
val ax = (a.longitude-camera.longitude)*scale*111_195; val ay = (a.latitude-camera.latitude)*111_195
val bx = (b.longitude-camera.longitude)*scale*111_195; val by = (b.latitude-camera.latitude)*111_195
val dx = bx-ax; val dy = by-ay
val length = dx*dx+dy*dy
val t = if (length == 0.0) 0.0 else ((-ax*dx-ay*dy)/length).coerceIn(0.0,1.0)
hypot(ax+t*dx, ay+t*dy) <= 12
}
private fun valid(p: GeoPoint) = p.latitude.isFinite() && p.longitude.isFinite() && p.latitude in -90.0..90.0 && p.longitude in -180.0..180.0
}
fun cameraDistance(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_008.8 * 2 * asin(sqrt(h.coerceIn(0.0, 1.0)))
}
private fun cameraBearing(a: GeoPoint, b: GeoPoint): Double {
val lon = Math.toRadians(b.longitude - a.longitude)
val latA = Math.toRadians(a.latitude); val latB = Math.toRadians(b.latitude)
return (Math.toDegrees(atan2(sin(lon) * cos(latB), cos(latA) * sin(latB) - sin(latA) * cos(latB) * cos(lon))) + 360) % 360
}
@@ -0,0 +1,23 @@
package dev.navframe.core
/** Parameters for a bearing-up, rider-following TFT renderer, independent of any map SDK. */
data class TftCameraParameters(
val bearingDegrees: Float,
val zoom: Double,
val riderAnchorY: Float = 0.72f,
)
class TftCameraPolicy {
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
}
return TftCameraParameters(normalizeBearing(state.bearing), zoom)
}
}
@@ -0,0 +1,68 @@
package dev.navframe.core
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import kotlin.coroutines.coroutineContext
/** Start-to-start cadence: supports movement rendering up to 10 FPS and slower cached keepalive. */
data class TftSessionPolicy(val intervalMs: Long = 1_000) {
init { require(intervalMs in 100..3_000) }
fun framePauseMs(sendElapsedMs: Long): Long = (intervalMs - sendElapsedMs.coerceAtLeast(0)).coerceAtLeast(50)
fun retryDelayMs(consecutiveFailures: Int): Long {
require(consecutiveFailures > 0)
return when (consecutiveFailures) { 1 -> 1_000; 2 -> 2_000; 3 -> 4_000; 4 -> 8_000; else -> 15_000 }
}
}
/** One connection and one acknowledged JPEG at a time; retry preserves the caller's framebuffer. */
class TftSessionRunner(
private val transportFactory: () -> TftTransport,
private val latestFrame: () -> TftFrame,
private val policy: () -> TftSessionPolicy,
private val clockMs: () -> Long,
private val pause: suspend (Long) -> Unit = { delay(it) },
private val onState: (ConnectionState) -> Unit = {},
private val onSent: (TftFrame, Long) -> Unit = { _, _ -> },
private val onRetry: (Exception, Long) -> Unit = { _, _ -> },
) {
suspend fun run(): Nothing {
var failures = 0
while (true) {
coroutineContext.ensureActive()
var current: TftTransport? = null
var failure: Exception? = null
try {
coroutineScope {
val connection = transportFactory().also { current = it }
val observer = launch { connection.connectionState.collect(onState) }
try {
connection.connect()
while (true) {
ensureActive()
val frame = latestFrame()
val start = clockMs()
connection.sendFrame(frame) // Includes the CCU acknowledgement.
val elapsed = (clockMs() - start).coerceAtLeast(0)
failures = 0 // A full handshake plus accepted frame restores a healthy session.
onSent(frame, elapsed)
pause(policy().framePauseMs(elapsed))
}
} finally { observer.cancelAndJoin() }
}
} catch (cancelled: CancellationException) {
// A transport-local withTimeout expires without cancelling this outer session.
// STOP/process teardown cancels our context and must never trigger reconnect.
coroutineContext.ensureActive()
failure = cancelled
}
catch (error: Exception) { failure = error }
finally { withContext(NonCancellable) { runCatching { current?.disconnect() } } }
coroutineContext.ensureActive()
failures = (failures + 1).coerceAtMost(5)
val wait = policy().retryDelayMs(failures)
onState(ConnectionState.ERROR)
onRetry(requireNotNull(failure), wait)
pause(wait)
}
}
}
@@ -0,0 +1,181 @@
package dev.navframe.core
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.Strictness
import kotlin.math.roundToInt
private const val MAX_RESPONSE_CHARS = 2 * 1024 * 1024
private const val MAX_SHAPE_POINTS = 100_000
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)
val request = JsonObject()
request.add("locations", JsonArray().apply {
listOf(origin, destination).forEach { point ->
add(JsonObject().apply {
addProperty("lat", point.latitude)
addProperty("lon", point.longitude)
addProperty("type", "break")
})
}
})
request.addProperty("costing", "motorcycle")
request.addProperty("units", "kilometers")
request.addProperty("language", GuidanceLanguage.resolve(language).tag)
request.addProperty("directions_type", "instructions")
request.addProperty("shape_format", "polyline6")
request.add("costing_options", JsonObject().apply {
add("motorcycle", JsonObject().apply {
val avoidMotorways = options.avoidMotorways || options.profile == RouteProfile.AVOID_MOTORWAYS
val preferAsphalt = options.avoidUnpaved || options.profile == RouteProfile.AVOID_UNPAVED
val avoidTolls = options.avoidTolls || options.profile == RouteProfile.TOURING
addProperty("use_tracks", 0)
addProperty("use_trails", if (preferAsphalt) 0.0 else 0.5)
addProperty("use_highways", when {
avoidMotorways -> 0.0
options.profile == RouteProfile.TOURING -> 0.2
else -> 0.5
})
addProperty("use_tolls", if (avoidTolls) 0.0 else 0.5)
// No exclude_*: experimental highway exclusions may be ignored by the server;
// motorcycle currently does not apply exclude_unpaved in Allowed/AllowedReverse.
})
})
return routeJson.toJson(request)
}
/** Decode the requested precision-6 shape, rejecting malformed, oversized and invalid coordinates. */
fun decodePolyline6(encoded: String): List<GeoPoint> {
if (encoded.isEmpty() || encoded.length > MAX_RESPONSE_CHARS) invalid("Invalid route shape size")
var cursor = 0
var latitude = 0L
var longitude = 0L
fun component(): Long {
var bits = 0L
var shift = 0
while (true) {
if (cursor >= encoded.length) invalid("Truncated route shape")
val value = encoded[cursor++].code - 63
if (value !in 0..63 || shift > 30) invalid("Invalid route shape encoding")
bits = bits or ((value and 31).toLong() shl shift)
if (value < 32) break
shift += 5
}
if (bits > 0xffffffffL) invalid("Route shape component overflow")
return if ((bits and 1L) != 0L) -(bits shr 1) - 1 else bits shr 1
}
val points = ArrayList<GeoPoint>()
while (cursor < encoded.length) {
if (points.size >= MAX_SHAPE_POINTS) invalid("Too many route shape points")
latitude += component()
longitude += component()
if (latitude !in -90_000_000L..90_000_000L || longitude !in -180_000_000L..180_000_000L) {
invalid("Route shape coordinate outside valid range")
}
points.add(GeoPoint(latitude / 1_000_000.0, longitude / 1_000_000.0))
}
return points
}
/**
* Parse a Valhalla /route response to road-snapped geometry and segment maneuvers.
* Multi-leg indices are rebased onto the merged geometry. No navigation progress is inferred.
*/
fun parseValhallaRoute(json: String, destination: GeoPoint? = null): RouteResult {
if (json.length > MAX_RESPONSE_CHARS || json.isBlank()) invalid("Invalid route response size")
destination?.let(::validatePoint)
try {
val root = routeJson.fromJson(json, JsonElement::class.java).objectValue()
val trip = root.required("trip").objectValue()
if (trip.required("status").nonNegativeInt() != 0) invalid("Routing service returned an unsuccessful status")
val metersPerUnit = when (trip.required("units").stringValue()) {
"kilometers" -> 1000.0
"miles" -> 1609.344
else -> invalid("Unsupported routing distance units")
}
val summary = trip.required("summary").objectValue()
val totalMeters = summary.required("length").scaledInt(metersPerUnit)
val totalSeconds = summary.required("time").scaledInt(1.0)
val legs = trip.required("legs").arrayValue()
if (legs.size() !in 1..128) invalid("Invalid route leg count")
val geometry = ArrayList<GeoPoint>()
val maneuvers = ArrayList<Maneuver>()
var anyUnpaved = false
var allSurfacesKnown = true
for (element in legs) {
val leg = element.objectValue()
val shape = decodePolyline6(leg.required("shape").stringValue())
if (shape.size < 2) invalid("Route leg has insufficient geometry")
val offset = if (geometry.isEmpty()) 0 else {
if (geometry.last() != shape.first()) invalid("Disconnected route legs")
geometry.size - 1
}
if (geometry.size + shape.size > MAX_SHAPE_POINTS + 1) invalid("Too many route shape points")
geometry.addAll(if (geometry.isEmpty()) shape else shape.drop(1))
val legManeuvers = leg.required("maneuvers").arrayValue()
if (legManeuvers.size() > MAX_SHAPE_POINTS - maneuvers.size) invalid("Too many route maneuvers")
for (item in legManeuvers) {
val maneuver = item.objectValue()
val rough = maneuver.get("rough")?.booleanValue()
if (rough == null) allSurfacesKnown = false else if (rough) anyUnpaved = true
val begin = maneuver.required("begin_shape_index").nonNegativeInt()
val end = maneuver.required("end_shape_index").nonNegativeInt()
if (begin > end || end >= shape.size) invalid("Maneuver indices outside route shape")
val names = maneuver.get("street_names")?.arrayValue()?.map { it.stringValue() } ?: emptyList()
maneuvers.add(Maneuver(
instruction = maneuver.required("instruction").stringValue(),
distanceMeters = maneuver.required("length").scaledInt(metersPerUnit),
type = maneuver.required("type").nonNegativeInt(),
beginShapeIndex = begin + offset,
endShapeIndex = end + offset,
durationSeconds = maneuver.required("time").scaledInt(1.0),
streetNames = names,
))
}
}
if (maneuvers.isEmpty()) invalid("Route has no maneuvers")
return RouteResult(geometry, maneuvers, totalMeters, totalSeconds, destination,
hasUnpaved = if (anyUnpaved) true else if (allSurfacesKnown) false else null)
} catch (error: ValhallaRouteException) {
throw error
} catch (_: RuntimeException) {
// Do not leak backend messages, response JSON or coordinates into logs/UI.
invalid("Malformed routing response")
}
}
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")
}
private fun invalid(message: String): Nothing = throw ValhallaRouteException(message)
private fun JsonObject.required(name: String): JsonElement = get(name) ?: invalid("Missing routing field")
private fun JsonElement.objectValue(): JsonObject = if (isJsonObject) asJsonObject else invalid("Invalid routing object")
private fun JsonElement.arrayValue(): JsonArray = if (isJsonArray) asJsonArray else invalid("Invalid routing array")
private fun JsonElement.stringValue(): String = if (isJsonPrimitive && asJsonPrimitive.isString) asString else invalid("Invalid routing text")
private fun JsonElement.numberValue(): Double {
if (!isJsonPrimitive || !asJsonPrimitive.isNumber) invalid("Invalid routing number")
return asDouble.also { if (!it.isFinite() || it < 0) invalid("Invalid routing number range") }
}
private fun JsonElement.nonNegativeInt(): Int {
val number = numberValue()
if (number > Int.MAX_VALUE || number % 1 != 0.0) invalid("Invalid routing integer")
return number.toInt()
}
private fun JsonElement.scaledInt(factor: Double): Int {
val result = numberValue() * factor
if (!result.isFinite() || result > Int.MAX_VALUE) invalid("Routing measurement overflow")
return result.roundToInt()
}
private fun JsonElement.booleanValue(): Boolean =
if (isJsonPrimitive && asJsonPrimitive.isBoolean) asBoolean else invalid("Invalid routing boolean")
@@ -0,0 +1,31 @@
package dev.navframe.core
/** Spoken checkpoints are consumed once per maneuver, including noisy distance oscillations. */
class VoiceGuidancePolicy(private val language: GuidanceLanguage = GuidanceLanguage.SPANISH) {
private var route: RouteResult? = null
private val checkpoints = mutableMapOf<Maneuver, Int>()
private val statuses = mutableSetOf<NavigationStatus>()
fun reset() { route = null; checkpoints.clear(); statuses.clear() }
fun announcement(state: NavigationState): String? {
val current = state.route ?: run { reset(); return null }
if (route !== current) { reset(); route = current }
when (state.navigationStatus) {
NavigationStatus.ARRIVED -> return once(state.navigationStatus, language.status(state.navigationStatus))
NavigationStatus.REROUTING -> return once(state.navigationStatus, language.status(state.navigationStatus))
NavigationStatus.OFF_ROUTE -> return once(state.navigationStatus, language.status(state.navigationStatus))
NavigationStatus.GPS_LOST -> return once(state.navigationStatus, language.status(state.navigationStatus))
NavigationStatus.NAVIGATING -> Unit
else -> return null
}
val maneuver = state.nextManeuver ?: return null
val distance = state.distanceToNextManeuverMeters?.takeIf { it >= 0 } ?: return null
val stage = when { distance <= 30 -> 3; distance <= 100 -> 2; distance <= 300 -> 1; else -> return null }
if ((checkpoints[maneuver] ?: 0) >= stage) return null
checkpoints[maneuver] = stage
val instruction = maneuver.instruction.trim().takeIf { it.isNotEmpty() } ?: return null
return language.maneuver(instruction, distance, stage == 3)
}
private fun once(status: NavigationStatus, text: String): String? = if (statuses.add(status)) text else null
}
@@ -0,0 +1,41 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class DemoNavigationTest {
@Test fun demoIsDeterministicAndAdvancesMotionAndManeuver() {
val first = DemoNavigation.stateAt(0)
assertEquals(DemoNavigation.stateAt(5_000), DemoNavigation.stateAt(5_000))
val later = DemoNavigation.stateAt(5_000)
assertNotEquals(first.position, later.position)
assertNotEquals(first.bearing, later.bearing)
assertTrue(later.distanceToNextManeuverMeters!! < first.distanceToNextManeuverMeters!!)
assertTrue(later.remainingDistanceMeters!! < first.remainingDistanceMeters!!)
assertNotEquals(first.nextManeuver?.instruction, DemoNavigation.stateAt(30_000).nextManeuver?.instruction)
assertTrue(later.nextManeuver!!.instruction.startsWith("DEMO"))
assertNull(later.route) // Synthetic road is not represented as a calculated route.
}
@Test fun demoCountdownRestartsCleanlyAndKeepsHeadingInRange() {
assertEquals(350, DemoNavigation.stateAt(30_000).distanceToNextManeuverMeters)
assertTrue(DemoNavigation.stateAt(29_999).distanceToNextManeuverMeters!! in 0..1)
for (elapsed in 0L..300_000L step 500L) {
val state = DemoNavigation.stateAt(elapsed)
assertTrue(state.bearing >= 0 && state.bearing < 360)
assertTrue(state.speed > 0)
}
}
@Test fun cameraWidensWithSpeedAndZoomsForUpcomingManeuver() {
val policy = TftCameraPolicy()
val slow = policy.parameters(NavigationState(speed = 5f, bearing = -1f))
val fast = policy.parameters(NavigationState(speed = 25f, bearing = 361f))
assertTrue(fast.zoom < slow.zoom)
assertEquals(359f, slow.bearingDegrees)
assertEquals(1f, fast.bearingDegrees)
assertTrue(fast.riderAnchorY in 0.66f..0.8f)
val approaching = policy.parameters(NavigationState(speed = 25f, nextManeuver = Maneuver("derecha", 100), distanceToNextManeuverMeters = 100))
assertTrue(approaching.zoom > slow.zoom)
}
}
@@ -0,0 +1,39 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class GuidanceLanguageTest {
@Test fun regionalAndUnsupportedLocalesUseConsistentSupportedLanguage() {
assertEquals(GuidanceLanguage.SPANISH, GuidanceLanguage.resolve("es-MX"))
assertEquals(GuidanceLanguage.ENGLISH, GuidanceLanguage.resolve("en-GB"))
assertEquals(GuidanceLanguage.GERMAN, GuidanceLanguage.resolve("de_AT"))
assertEquals(GuidanceLanguage.ENGLISH, GuidanceLanguage.resolve("ja-JP"))
}
@Test fun requestUsesSelectedLocaleAndDefaultsRemainSpanish() {
val origin = GeoPoint(43.3, -5.8); val destination = GeoPoint(43.4, -5.9)
assertTrue(buildValhallaRequest(origin, destination).contains("es-ES"))
assertTrue(buildValhallaRequest(origin, destination, language = "fr-CA").contains("fr-FR"))
assertTrue(buildValhallaRequest(origin, destination, language = "unsupported").contains("en-US"))
}
@Test fun englishCheckpointsStatusesAndCameraAlertsDoNotUseSpanish() {
val maneuver = Maneuver("Turn left", 100, 15, 1, 2)
val route = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), listOf(maneuver), 1000, 100, guidanceLanguage = "en-US")
val state = NavigationState(route = route, nextManeuver = maneuver, distanceToNextManeuverMeters = 250, navigationStatus = NavigationStatus.NAVIGATING)
assertEquals("En 250 metros, Turn left", VoiceGuidancePolicy().announcement(state))
val policy = VoiceGuidancePolicy(GuidanceLanguage.ENGLISH)
assertEquals("In 250 meters, Turn left", policy.announcement(state))
assertNull(policy.announcement(state))
assertEquals("Now, Turn left", policy.announcement(state.copy(distanceToNextManeuverMeters = 20)))
assertEquals("You have arrived at your destination.", policy.announcement(state.copy(navigationStatus = NavigationStatus.ARRIVED)))
assertTrue(GuidanceLanguage.ENGLISH.camera(200).contains("200 meters"))
assertTrue(GuidanceLanguage.SPANISH.camera(200).contains("200 metros"))
}
@Test fun everySelectableLanguageProvidesLocalizedSpeech() {
GuidanceLanguage.entries.forEach { language ->
assertTrue(language.maneuver("instruction", 250, false).contains("250"))
assertTrue(language.camera(200).contains("200"))
assertTrue(language.status(NavigationStatus.GPS_LOST).isNotBlank())
}
}
}
@@ -0,0 +1,84 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class NominatimGeocodingTest {
// Original synthetic fixture following jsonv2's documented numeric strings.
private val fixture = """[
{"place_id":123,"lat":"43.36","lon":"-5.85","display_name":"Destino de prueba, Asturias, España","licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"},
{"lat":"0","lon":"180","display_name":"Punto de prueba"}
]"""
@Test fun `jsonv2 preserves display label coordinates and attribution`() {
val results = parseNominatimResults(fixture)
assertEquals(2, results.size)
assertEquals("Destino de prueba, Asturias, España", results[0].name)
assertEquals(GeoPoint(43.36, -5.85), results[0].position)
assertTrue(results[0].attribution.contains("ODbL 1.0"))
assertEquals("© OpenStreetMap contributors", results[1].attribution)
}
@Test fun `empty list is a successful no match result`() {
assertTrue(parseNominatimResults("[]").isEmpty())
}
@Test fun `result count and duplicate labels are bounded`() {
val item = """{"lat":"43.36","lon":"-5.85","display_name":"Test"}"""
assertEquals(1, parseNominatimResults("[$item,$item]").size)
val distinct = (0..5).joinToString(",") { """{"lat":"$it","lon":"0","display_name":"Test $it"}""" }
assertEquals(5, parseNominatimResults("[$distinct]").size)
rejects { parseNominatimResults("[" + List(41) { item }.joinToString(",") + "]") }
}
@Test fun `strict malformed and backend errors omit private data`() {
listOf("", "null", "{}", "[null]", fixture + "{}", "//comment\n$fixture",
"""{"error":"private search text"}""").forEach { value -> rejects { parseNominatimResults(value) } }
try {
parseNominatimResults("""{"error":"private search text"}""")
fail("Expected rejection")
} catch (error: GeocodingResponseException) {
assertFalse(error.message!!.contains("private search text"))
}
}
@Test fun `coordinates are strict finite numeric strings within geographic range`() {
listOf("NaN", "Infinity", "91", "-91", "1e999", "0x1p0", "", " 43.36").forEach { latitude ->
rejects { parseNominatimResults(fixture.replace("43.36", latitude)) }
}
rejects { parseNominatimResults(fixture.replace("-5.85", "181")) }
rejects { parseNominatimResults(fixture.replace("\"lat\":\"43.36\"", "\"lat\":43.36")) }
rejects { parseNominatimResults(fixture.replace("\"lon\":\"-5.85\"", "\"lon\":null")) }
}
@Test fun `required names and response sizes are validated`() {
rejects { parseNominatimResults("""[{"lat":"0","lon":"0","display_name":" "}]""") }
rejects { parseNominatimResults(fixture.replace("Destino de prueba, Asturias, España", "x".repeat(2_049))) }
rejects { parseNominatimResults(" ".repeat(512 * 1024 + 1)) }
val label = parseNominatimResults("""[{"lat":"0","lon":"0","display_name":"Test\nplace"}]""")[0].name
assertEquals("Test place", label)
}
@Test fun `parameters normalize whitespace preserve Unicode and do not carry GPS`() {
val params = nominatimSearchParameters(" Peña de prueba ")
assertEquals("Peña de prueba", params["q"])
assertEquals("jsonv2", params["format"])
assertEquals("5", params["limit"])
assertEquals("es", params["accept-language"])
assertFalse(params.containsKey("viewbox"))
assertFalse(params.containsKey("lat"))
assertEquals("A&B? q=other", nominatimSearchParameters("A&B? q=other")["q"])
}
@Test fun `invalid explicit query rejected before HTTP`() {
listOf("", " ", "x", "x".repeat(201), "Test\u0000place").forEach { query ->
try { nominatimSearchParameters(query); fail("Expected query rejection") }
catch (_: IllegalArgumentException) { /* expected */ }
}
}
private fun rejects(block: () -> Unit) {
try { block(); fail("Expected response rejection") }
catch (_: GeocodingResponseException) { /* expected */ }
}
}
@@ -0,0 +1,31 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class OfflinePlaceTest {
@Test fun `search matches accents combining forms and irregular spaces`() {
assertEquals("cafe alvaro", normalizePlaceSearch(" CAFÉ\u00a0ÁLVARO\n"))
assertEquals(normalizePlaceSearch("José"), normalizePlaceSearch("Jose\u0301"))
assertEquals("penaflor", normalizePlaceSearch("Peñaflor"))
assertEquals("καφες", normalizePlaceSearch("Καφές"))
assertEquals("россия", normalizePlaceSearch("Россия"))
assertEquals("a b", normalizePlaceSearch("A\u200bB"))
assertEquals("", normalizePlaceSearch(" \n\t"))
}
@Test fun `LIKE literal escaping preserves apostrophes and never treats input as SQL`() {
assertEquals("100\\% moto\\_x\\\\y", escapePlaceLike("100% moto_x\\y"))
assertEquals("o'connor", escapePlaceLike("o'connor"))
assertEquals("' or 1=1 --", escapePlaceLike("' or 1=1 --"))
}
@Test fun `business carries raw opening hours and distinct OSM identity without invented details`() {
val place = OfflinePlace("w/123", "Taller test", PlaceCategory.WORKSHOP, GeoPoint(43.36, -5.85))
assertNull(place.openingHours)
assertNull(place.distanceMeters)
assertEquals("Talleres", place.category.labelSpanish)
assertNotEquals(place, place.copy(id = "n/123"))
assertEquals(5, PlaceCategory.entries.size)
}
}
@@ -0,0 +1,125 @@
package dev.navframe.core
import com.google.gson.JsonParser
import org.junit.Assert.*
import org.junit.Test
class RegionalPackTest {
private val fixture = """{"schemaVersion":1,"id":"es-test","name":"Region test","version":"2026-09-28.1",
"osmTimestamp":"2026-09-28T20:23:05Z","bounds":{"south":42.7,"west":-4.9,"north":43.9,"east":-3.1},
"minZoom":6,"maxZoom":14,"attribution":"© OpenStreetMap contributors","mapSchema":"NavFrame Offline/1.0.0",
"poiSchema":1,"glyphs":"noto-sans-regular-0-2047","capabilities":["map","poi"],
"source":{"provider":"Geofabrik","extractUrl":"https://download.geofabrik.de/europe/spain/cantabria-latest.osm.pbf",
"pbfSha256":"${"d".repeat(64)}","coverageUrl":"https://download.geofabrik.de/europe/spain/cantabria.poly",
"coverageSha256":"${"e".repeat(64)}","license":"ODbL-1.0","recipe":"NavFrame regional pack 1.0.0","planetiler":"0.10.2","poiBuilder":"NavFrame POI 1.0.0"},
"coverage":{"type":"Polygon","coordinates":[[[-4.9,42.7],[-3.1,42.7],[-3.1,43.9],[-4.9,43.9],[-4.9,42.7]]]},
"map":{"path":"map.pmtiles","bytes":10000,"sha256":"${"a".repeat(64)}"},
"pois":{"path":"pois.sqlite","bytes":4096,"sha256":"${"b".repeat(64)}"}}"""
private fun rejects(value: String) {
try { parseRegionalManifest(value); fail("Expected rejection") } catch (error: IllegalArgumentException) {
assertEquals("Paquete regional inválido o incompatible", error.message)
}
}
@Test fun `manifest has two original schemas local components and bounded sizes`() {
val pack = parseRegionalManifest(fixture)
assertEquals(14096L, pack.totalBytes)
assertEquals("map.pmtiles", pack.map.path)
assertEquals("pois.sqlite", pack.pois.path)
assertTrue(pack.covers(GeoPoint(43.4, -3.8)))
assertFalse(pack.covers(GeoPoint(43.36, -5.85)))
}
@Test fun `unsupported routing schemas missing attribution and unsafe paths are rejected`() {
listOf(
fixture.replace("\"schemaVersion\":1", "\"schemaVersion\":2"),
fixture.replace("\"poiSchema\":1", "\"poiSchema\":2"),
fixture.replace("NavFrame Offline/1.0.0", "OpenMapTiles"),
fixture.replace("\"map\",\"poi\"", "\"map\",\"routing\""),
fixture.replace("map.pmtiles", "../map.pmtiles"),
fixture.replace("© OpenStreetMap contributors", "unknown"),
fixture.replace("noto-sans-regular-0-2047", "https://font.invalid"),
fixture.replace("es-test", "../../private"),
fixture.replace("Geofabrik", "Unknown"),
fixture.replace("download.geofabrik.de/europe/spain/cantabria-latest", "attacker.invalid/cantabria-latest"),
fixture.replace("ODbL-1.0", "Proprietary"),
fixture.replace("NavFrame regional pack 1.0.0", "unknown recipe"),
).forEach(::rejects)
}
@Test fun `numbers hashes dates and JSON must be strict rather than coerced`() {
listOf(
fixture.replace("10000", "1.5"), fixture.replace("10000", "9223372036854775808"),
fixture.replace("10000", "524288001"), fixture.replace("10000", "\"10000\""),
fixture.replace("4096", "-1"), fixture.replace("\"maxZoom\":14", "\"maxZoom\":19"),
fixture.replace("43.9", "1e309"), fixture.replace("42.7", "44.0"),
fixture.replace("2026-09-28T20:23:05Z", "2026-02-30T20:23:05Z"),
fixture.replace("a".repeat(64), "G".repeat(64)), fixture + "{}", "// comment\n$fixture",
).forEach(::rejects)
}
@Test fun `actual coverage differentiates irregular regions holes and edge points`() {
val root = JsonParser.parseString(fixture).asJsonObject
root.add("coverage", JsonParser.parseString("""{"type":"Polygon","coordinates":[
[[-4.8,42.8],[-3.2,42.8],[-4.8,43.8],[-4.8,42.8]],
[[-4.7,42.9],[-4.6,42.9],[-4.6,43.0],[-4.7,43.0],[-4.7,42.9]]]}"""))
val pack = parseRegionalManifest(root.toString())
assertTrue(pack.covers(GeoPoint(43.3, -4.7)))
assertFalse(pack.covers(GeoPoint(43.7, -3.3))) // Inside bbox, outside triangle.
assertFalse(pack.covers(GeoPoint(42.95, -4.65))) // Hole.
assertTrue(pack.covers(GeoPoint(42.8, -4.8))) // Outer boundary.
assertFalse(pack.covers(GeoPoint(42.9, -4.7))) // Hole boundary.
}
@Test fun `malformed coverage rings and unbounded coordinates fail closed`() {
val root = JsonParser.parseString(fixture).asJsonObject
listOf("""{"type":"Polygon","coordinates":[[[-4,43],[-3.5,43],[-4,43.5]]]}""",
"""{"type":"Polygon","coordinates":[[[-20,43],[-3.5,43],[-4,43.5],[-20,43]]]}""",
"""{"type":"LineString","coordinates":[]}""").forEach {
root.add("coverage", JsonParser.parseString(it)); rejects(root.toString())
}
}
@Test fun `worldwide Geofabrik paths and multipolygon coverage parse`() {
val root = JsonParser.parseString(fixture).asJsonObject
root.add("bounds", JsonParser.parseString("""{"south":-50,"west":-130,"north":75,"east":-30}"""))
val source = root.getAsJsonObject("source")
source.addProperty("extractUrl", "https://download.geofabrik.de/north-america/us/texas-latest.osm.pbf")
source.addProperty("coverageUrl", "https://download.geofabrik.de/north-america/us/texas.poly")
root.add("coverage", JsonParser.parseString("""{"type":"MultiPolygon","coordinates":[
[[[ -100,30],[-99,30],[-99,31],[-100,31],[-100,30]]],
[[[-98,32],[-97,32],[-97,33],[-98,33],[-98,32]]]]}"""))
val manifest = parseRegionalManifest(root.toString())
assertTrue(manifest.covers(GeoPoint(30.5, -99.5)))
assertTrue(manifest.covers(GeoPoint(32.5, -97.5)))
assertFalse(manifest.covers(GeoPoint(31.5, -98.5)))
}
@Test fun `worldwide recipe accepts camera-enabled catalogs without breaking legacy packs`() {
val updated = fixture.replace("NavFrame regional pack 1.0.0", "NavFrame regional pack 1.1.0")
.replace("NavFrame POI 1.0.0", "NavFrame POI 1.1.0")
assertEquals("NavFrame regional pack 1.1.0", parseRegionalManifest(updated).source.recipe)
assertEquals("NavFrame regional pack 1.0.0", parseRegionalManifest(fixture).source.recipe)
}
@Test fun `local catalog validates original entries without fabricated remote endpoints`() {
val item = """{"manifest":$fixture,"archive":{"path":"es-test-20260928.navframe","bytes":20000,"sha256":"${"c".repeat(64)}"}}"""
val json = """{"schemaVersion":1,"regions":[$item]}"""
val catalog = parseRegionalCatalog(json)
assertEquals("es-test-20260928.navframe", catalog.regions.single().archive.path)
listOf(json.replace("es-test-20260928.navframe", "../../private.navframe"),
json.replace("es-test-20260928.navframe", "https://endpoint.invalid/file.navframe"),
"""{"schemaVersion":1,"regions":[$item,$item]}""").forEach {
try { parseRegionalCatalog(it); fail("Expected rejection") } catch (_: IllegalArgumentException) { }
}
}
@Test fun `global catalog optional release URL and region metadata preserve local entries`() {
val item = """{"manifest":$fixture,"archive":{"path":"es-test-20260928.navframe","bytes":20000,
"sha256":"${"c".repeat(64)}","url":"https://github.com/example/navframe/releases/download/v1/es-test-20260928.navframe"},
"countryCode":"ES","country":"Spain","region":"spain/cantabria","cameraCount":22}"""
val entry = parseRegionalCatalog("""{"schemaVersion":1,"regions":[$item]}""").regions.single()
assertEquals("https://github.com/example/navframe/releases/download/v1/es-test-20260928.navframe", entry.archive.url)
assertEquals("ES", entry.countryCode)
assertEquals("Spain", entry.country)
assertEquals("spain/cantabria", entry.region)
assertEquals(22, entry.cameraCount)
val old = """{"manifest":$fixture,"archive":{"path":"es-test-20260928.navframe","bytes":20000,"sha256":"${"c".repeat(64)}"}}"""
assertNull(parseRegionalCatalog("""{"schemaVersion":1,"regions":[$old]}""").regions.single().archive.url)
listOf(item.replace("https://github.com", "http://github.com"), item.replace("\"ES\"", "\"Spain\""), item.replace("\"cameraCount\":22", "\"cameraCount\":-1")).forEach {
try { parseRegionalCatalog("""{"schemaVersion":1,"regions":[$it]}"""); fail("Expected rejection") } catch (_: IllegalArgumentException) { }
}
}
}
@@ -0,0 +1,133 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class RenderSchedulerTest {
private fun state(speed: Float = 0f, bearing: Float = 0f, lat: Double = 43.0) =
NavigationState(position = GeoPoint(lat, -5.0), speed = speed, bearing = bearing)
@Test fun stationaryUnchangedDoesNotRedrawEvenAfterLongWait() {
val scheduler = RenderScheduler()
assertTrue(scheduler.renderIfDue(state(), 0))
assertFalse(scheduler.renderIfDue(state(), 60_000))
}
@Test fun stationaryPositionAndHeadingJitterDoesNotRedraw() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(), 0)
assertFalse(scheduler.renderIfDue(state(bearing = 90f, lat = 43.000005), 5_000))
}
@Test fun stationaryUiChangesRespectOneFpsMaximum() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(), 0)
val changed = state().copy(navigationStatus = NavigationStatus.GPS_LOST)
assertFalse(scheduler.renderIfDue(changed, 999))
assertTrue(scheduler.renderIfDue(changed, 1_000))
}
@Test fun movingPositionUpdatesRespectFiveFpsMaximum() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(speed = 8f), 0)
val moved = state(speed = 8f, lat = 43.0001)
assertFalse(scheduler.renderIfDue(moved, 199))
assertTrue(scheduler.renderIfDue(moved, 200))
}
@Test fun rapidTurnCanRenderAtTenFps() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(speed = 8f), 0)
val turned = state(speed = 8f, bearing = 20f)
assertFalse(scheduler.renderIfDue(turned, 99))
assertTrue(scheduler.renderIfDue(turned, 100))
}
@Test fun compassNorthWrapIsSmallChangeRatherThanRapidTurn() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(speed = 8f, bearing = 359f), 0)
assertFalse(scheduler.renderIfDue(state(speed = 8f, bearing = 1f), 50))
assertFalse(scheduler.renderIfDue(state(speed = 8f, bearing = 4f), 100))
assertTrue(scheduler.renderIfDue(state(speed = 8f, bearing = 4f), 200))
}
@Test fun queuedStateIsReplacedWithLatestWhileThrottled() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(speed = 8f), 0)
scheduler.offer(state(speed = 8f, lat = 43.0001))
assertNull(scheduler.takeIfDue(100))
val newest = state(speed = 8f, lat = 43.0002)
scheduler.offer(newest)
assertEquals(newest, scheduler.takeIfDue(200))
scheduler.markRendered(newest, 200)
assertNull(scheduler.takeIfDue(400))
}
@Test fun newManeuverAndLabelChangeRenderWithoutPositionChange() {
val scheduler = RenderScheduler()
val first = state().copy(nextManeuver = Maneuver("derecha", 350), distanceToNextManeuverMeters = 350)
scheduler.renderIfDue(first, 0)
assertTrue(scheduler.renderIfDue(first.copy(nextManeuver = Maneuver("izquierda", 350)), 1_000))
assertTrue(scheduler.renderIfDue(first.copy(nextManeuver = Maneuver("izquierda", 350), distanceToNextManeuverMeters = 330), 2_000))
}
@Test fun etaOnlyChangesRenderedMinuteRatherThanEverySecond() {
val scheduler = RenderScheduler()
val first = state().copy(etaEpochMillis = 120_000)
scheduler.renderIfDue(first, 0)
assertFalse(scheduler.renderIfDue(first.copy(etaEpochMillis = 121_000), 1_000))
assertTrue(scheduler.renderIfDue(first.copy(etaEpochMillis = 180_000), 2_000))
}
@Test fun configurablePolicyChangesMovementThresholdAndRate() {
val scheduler = RenderScheduler(RenderScheduleConfig(movingMaxFps = 2.0, positionDeltaMeters = 20.0))
scheduler.renderIfDue(state(speed = 8f), 0)
assertFalse(scheduler.renderIfDue(state(speed = 8f, lat = 43.0001), 100))
val moved = state(speed = 8f, lat = 43.0003)
assertFalse(scheduler.renderIfDue(moved, 499))
assertTrue(scheduler.renderIfDue(moved, 500))
}
@Test fun resetAndRestartedMonotonicClockAllowFirstFrameImmediately() {
val scheduler = RenderScheduler()
scheduler.renderIfDue(state(), 10_000)
assertTrue(scheduler.renderIfDue(state(), 100))
scheduler.reset()
assertTrue(scheduler.renderIfDue(state(), 101))
}
@Test fun failedRenderDoesNotCommitAndNewerFixSurvivesOlderRenderCompletion() {
val scheduler = RenderScheduler()
val first = state(speed = 8f)
scheduler.offer(first)
assertEquals(first, scheduler.takeIfDue(0))
// Encoding failed: querying again still yields the first frame, without waiting.
assertEquals(first, scheduler.takeIfDue(1))
val newest = first.copy(position = GeoPoint(43.0002, -5.0))
scheduler.offer(newest)
scheduler.markRendered(first, 2)
assertNull(scheduler.takeIfDue(100))
assertEquals(newest, scheduler.takeIfDue(202))
}
private fun RenderScheduler.renderIfDue(state: NavigationState, nowMs: Long): Boolean {
val due = shouldRender(state, nowMs)
if (due) markRendered(state, nowMs)
return due
}
@Test fun stationaryAccuracyAndBearingAvailabilityChangesAreVisible() {
val scheduler = RenderScheduler()
val first = state().copy(accuracyMeters = 5f)
scheduler.renderIfDue(first, 0)
assertFalse(scheduler.renderIfDue(first.copy(accuracyMeters = 6f), 1_000))
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = 10f), 2_000))
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = null), 3_000))
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = null, bearing = Float.NaN), 4_000))
}
@Test fun invalidConfigurationIsRejected() {
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(movingMaxFps = Double.NaN) }
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(distanceLabelStepMeters = 0) }
}
}
@@ -0,0 +1,204 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class RouteGuidanceTest {
// Equatorial segments are ~111.2m each; original route duration is 30 seconds.
private val route = RouteResult(
listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.001), GeoPoint(0.001, 0.001)),
listOf(Maneuver("Start", 111, 1, 0, 1, 15), Maneuver("Left", 111, 15, 1, 2, 15), Maneuver("Arrive", 0, 4, 2, 2)),
222, 30,
)
private fun fix(lat: Double = 0.0, lon: Double = 0.0, time: Long = 1, accuracy: Float = 5f, speed: Float = 12f) =
LocationFix(GeoPoint(lat, lon), 90f, speed, accuracy, time)
@Test fun `projection yields next turn countdown remaining and estimated ETA`() {
val state = RouteGuidanceTracker(route).update(fix(lon = 0.0005), 0, 100_000)
assertEquals(NavigationStatus.NAVIGATING, state.navigationStatus)
assertEquals("Left", state.nextManeuver!!.instruction)
assertEquals(56, state.distanceToNextManeuverMeters!!)
assertEquals(167, state.remainingDistanceMeters!!)
assertEquals(122_500L, state.etaEpochMillis!!)
}
@Test fun `jitter never moves countdown backwards and crossed turn advances with margin`() {
val tracker = RouteGuidanceTracker(route)
val a = tracker.update(fix(lon = 0.0008), 0, 0)
val jitter = tracker.update(fix(lon = 0.00075, time = 2), 1_000, 1_000)
assertEquals(a.remainingDistanceMeters, jitter.remainingDistanceMeters)
assertEquals("Left", jitter.nextManeuver!!.instruction)
val crossed = tracker.update(fix(lat = 0.0001, lon = 0.001, time = 3), 2_000, 2_000)
assertEquals("Arrive", crossed.nextManeuver!!.instruction)
assertEquals(100, crossed.distanceToNextManeuverMeters!!)
}
@Test fun `off route requires distinct fresh fixes time and resets after jitter recovery`() {
val tracker = RouteGuidanceTracker(route)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005), 0, 0).navigationStatus)
// Ticks on the same fix do not satisfy either count or sustained-duration confirmation.
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005), 8_000, 8_000).navigationStatus)
tracker.update(fix(lat = -0.0005, time = 2), 9_000, 9_000)
val outside = tracker.update(fix(lat = -0.0005, time = 3), 10_000, 10_000)
assertEquals(NavigationStatus.OFF_ROUTE, outside.navigationStatus)
assertNull(outside.nextManeuver)
assertNull(outside.distanceToNextManeuverMeters)
assertNull(outside.etaEpochMillis)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(time = 4), 11_000, 11_000).navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005, time = 5), 12_000, 12_000).navigationStatus)
}
@Test fun `a long gap breaks consecutive deviation evidence`() {
val tracker = RouteGuidanceTracker(route)
tracker.update(fix(lat = -0.0005), 0, 0)
tracker.update(fix(lat = -0.0005, time = 2), 3_000, 0)
val resumed = tracker.update(fix(lat = -0.0005, time = 3), 30_000, 0)
assertEquals(NavigationStatus.GPS_LOST, resumed.navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(lat = -0.0005, time = 4), 31_000, 0).navigationStatus)
}
@Test fun `accuracy margin rejects jitter at forty five meters with twenty five meter accuracy`() {
val tracker = RouteGuidanceTracker(route)
for (i in 1..5) {
val state = tracker.update(fix(lat = -0.0004, time = i.toLong(), accuracy = 25f), i * 3_000L, 0)
assertEquals(NavigationStatus.NAVIGATING, state.navigationStatus)
}
}
@Test fun `poor stale invalid fixes cannot confirm deviation or arrival`() {
listOf(Float.NaN, Float.POSITIVE_INFINITY, 26f, -1f).forEach { accuracy ->
val state = RouteGuidanceTracker(route).update(fix(accuracy = accuracy), 0, 0)
assertEquals(NavigationStatus.GPS_LOST, state.navigationStatus)
assertNull(state.nextManeuver)
assertNull(state.etaEpochMillis)
}
val tracker = RouteGuidanceTracker(route)
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(), 0, 0, 15_001).navigationStatus)
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(lat = Double.NaN), 1_000, 0).navigationStatus)
}
@Test fun `arrival requires endpoint geometry repeated fixes and time then stays arrived`() {
val tracker = RouteGuidanceTracker(route)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.001, 0.001), 0, 0).navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.001, 0.001), 5_000, 0).navigationStatus)
tracker.update(fix(0.001, 0.001, time = 2), 6_000, 0)
val arrived = tracker.update(fix(0.001, 0.001, time = 3), 7_000, 0)
assertEquals(NavigationStatus.ARRIVED, arrived.navigationStatus)
assertNull(arrived.nextManeuver)
assertEquals(0, arrived.remainingDistanceMeters!!)
assertEquals(NavigationStatus.ARRIVED, tracker.update(fix(0.0009, 0.001, time = 4), 8_000, 0).navigationStatus)
}
@Test fun `isolated jump and return cannot advance route or cause reroute`() {
val tracker = RouteGuidanceTracker(route)
val start = tracker.update(fix(), 0, 0)
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(0.001, 0.001, time = 2), 100, 0).navigationStatus)
assertEquals(NavigationStatus.GPS_LOST, tracker.update(fix(time = 3), 200, 0).navigationStatus)
val recovered = tracker.update(fix(time = 4), 300, 0)
assertEquals(start.remainingDistanceMeters, recovered.remainingDistanceMeters)
assertEquals(NavigationStatus.NAVIGATING, recovered.navigationStatus)
}
@Test fun `crossing route does not jump forward to distant later branch`() {
val crossing = route.copy(geometry = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.002),
GeoPoint(0.002, 0.002), GeoPoint(0.002, 0.0), GeoPoint(0.0, 0.0), GeoPoint(0.0, -0.002)), maneuvers = emptyList())
val tracker = RouteGuidanceTracker(crossing)
val initial = tracker.update(fix(), 0, 0)
val next = tracker.update(fix(lon = -0.00005, time = 2), 1_000, 0)
assertEquals(initial.remainingDistanceMeters, next.remainingDistanceMeters)
assertEquals(NavigationStatus.NAVIGATING, next.navigationStatus)
}
@Test fun `dateline projection follows short segment`() {
val crossing = RouteResult(listOf(GeoPoint(0.0, 179.999), GeoPoint(0.0, -179.999)), emptyList(), 222, 30)
val state = RouteGuidanceTracker(crossing).update(fix(lon = 180.0), 0, 0)
assertEquals(111, state.remainingDistanceMeters!!)
}
@Test fun `reroute policy single flight cooldown and retry after suppress loops`() {
val policy = ReroutePolicy()
val off = NavigationState(navigationStatus = NavigationStatus.OFF_ROUTE)
assertTrue(policy.shouldRequest(off, 0))
policy.markRequested(0)
assertFalse(policy.shouldRequest(off, 100_000))
policy.markFinished(1_000, retryAfterMs = 60_000)
assertFalse(policy.shouldRequest(off, 60_999))
assertTrue(policy.shouldRequest(off, 61_000))
assertFalse(policy.shouldRequest(off.copy(navigationStatus = NavigationStatus.GPS_LOST), 61_000))
policy.reset()
assertTrue(policy.shouldRequest(off, 0))
}
@Test fun `demo is deterministic interpolated and includes guidance then arrival`() {
val demo = RouteDemo(route)
val state = demo.stateAt(5_000, 100_000)
assertEquals(state, demo.stateAt(5_000, 100_000))
assertEquals("Left", state.nextManeuver!!.instruction)
assertEquals(51, state.distanceToNextManeuverMeters!!)
assertEquals(12f, state.speed, 0f)
assertEquals(0.0005396, state.position.longitude, 0.000001)
assertEquals(90f, state.bearing, 0.1f)
val arrived = demo.stateAt(30_000, 130_000)
assertEquals(NavigationStatus.ARRIVED, arrived.navigationStatus)
assertEquals(route.geometry.last(), arrived.position)
assertNull(arrived.nextManeuver)
}
@Test fun `repeated ticks preserve movement baseline until new fix`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), emptyList(), 1112, 100)
val tracker = RouteGuidanceTracker(longRoute)
val original = fix(speed = 30f)
tracker.update(original, 0, 0)
for (tick in 1..49) tracker.update(original, tick * 100L, 0)
val moved = tracker.update(fix(lon = 0.0015, time = 2, speed = 30f), 5_000, 0)
assertEquals(NavigationStatus.NAVIGATING, moved.navigationStatus)
assertEquals(945, moved.remainingDistanceMeters!!)
}
@Test fun `first acquisition can begin far inside calculated route`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), emptyList(), 1112, 100)
val tracker = RouteGuidanceTracker(longRoute)
val midway = tracker.update(fix(lon = 0.005), 0, 0)
assertEquals(556, midway.remainingDistanceMeters!!)
assertEquals(534, tracker.update(fix(lon = 0.0052, time = 2), 2_000, 0).remainingDistanceMeters!!)
}
@Test fun `start right and start left are departure instructions not upcoming turns`() {
for (startType in 1..3) {
val withDeparture = route.copy(maneuvers = listOf(route.maneuvers.first().copy(type = startType)) + route.maneuvers.drop(1))
assertEquals("Left", RouteGuidanceTracker(withDeparture).update(fix(), 0, 0).nextManeuver!!.instruction)
}
}
@Test fun `GPS recovery needs two new stable fixes and ignores absent time for movement`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 100)
val tracker = RouteGuidanceTracker(longRoute)
tracker.update(fix(speed = 25f), 0, 0)
val first = tracker.update(fix(lon = 0.01, time = 2, speed = 25f), 60_000, 0)
assertEquals(NavigationStatus.GPS_LOST, first.navigationStatus)
assertNull(first.nextManeuver)
val second = tracker.update(fix(lon = 0.0101, time = 3, speed = 25f), 61_000, 0)
assertEquals(NavigationStatus.NAVIGATING, second.navigationStatus)
assertEquals(1101, second.remainingDistanceMeters!!)
}
@Test fun `ambiguous distant on route jump does not show old turn guidance`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), emptyList(), 1112, 100)
val tracker = RouteGuidanceTracker(longRoute)
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)
assertNull(stableButDistant.remainingDistanceMeters)
assertNull(stableButDistant.nextManeuver)
}
@Test fun `maneuver arrows use type rather than translated prose`() {
assertEquals(ManeuverDirection.LEFT, maneuverDirection(15))
assertEquals(ManeuverDirection.RIGHT, maneuverDirection(10))
assertEquals(ManeuverDirection.UTURN, maneuverDirection(12))
assertEquals(ManeuverDirection.ROUNDABOUT, maneuverDirection(26))
assertEquals(ManeuverDirection.ARRIVAL, maneuverDirection(6))
assertEquals(ManeuverDirection.UNKNOWN, maneuverDirection(null))
}
}
@@ -0,0 +1,33 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class SpeedCameraTest {
private val camera = SpeedCamera("n/1", GeoPoint(43.004, -5.0))
private val route = RouteResult(listOf(GeoPoint(43.0,-5.0), GeoPoint(43.01,-5.0)), emptyList(), 1100, 100)
private fun fix(lat: Double, accuracy: Float = 5f, bearing: Float = 0f) = LocationFix(GeoPoint(lat,-5.0),bearing,15f,accuracy,0)
@Test fun approachAlertsOnce() {
val engine = SpeedCameraAlertEngine()
assertNull(engine.update(fix(43.0),listOf(camera),0,route=route))
val alert = engine.update(fix(43.0001),listOf(camera),1000,route=route)
assertNotNull(alert)
assertNull(engine.update(fix(43.0002),listOf(camera),2000,route=route))
}
@Test fun uncertainOrStaleGpsAndRecedingDoNotAlert() {
for (bad in listOf(fix(43.0001,50f), fix(43.0001,bearing=180f))) {
val engine = SpeedCameraAlertEngine()
engine.update(fix(43.0),listOf(camera),0,route=route)
assertNull(engine.update(bad,listOf(camera),1000,route=route))
}
val engine = SpeedCameraAlertEngine()
engine.update(fix(43.0002),listOf(camera),0,route=route)
assertNull(engine.update(fix(43.0001),listOf(camera),1000,route=route))
assertNull(engine.update(fix(43.0003),listOf(camera),2000,6000,route))
}
@Test fun absentRouteAndParallelRoadDoNotAlert() {
val engine = SpeedCameraAlertEngine()
assertNull(engine.update(fix(43.0),listOf(camera),0))
val offRoute = camera.copy(position=GeoPoint(43.004,-5.001))
engine.update(fix(43.0),listOf(offRoute),0,route=route)
assertNull(engine.update(fix(43.0001),listOf(offRoute),1000,route=route))
}
}
@@ -0,0 +1,197 @@
package dev.navframe.core
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Assert.*
import org.junit.Test
class TftSessionRunnerTest {
private fun frame(value: Byte) = TftFrame(encodedBytes = byteArrayOf(value), timestampMs = value.toLong())
private class Transport : TftTransport {
override val connectionState = MutableStateFlow(ConnectionState.DISCONNECTED)
var connects = 0
var disconnects = 0
val sent = mutableListOf<TftFrame>()
var connectAction: suspend () -> Unit = {}
var sendAction: suspend () -> Unit = {}
override suspend fun connect() { connects++; connectAction(); connectionState.value = ConnectionState.CONNECTED }
override suspend fun disconnect() { disconnects++; connectionState.value = ConnectionState.DISCONNECTED }
override suspend fun sendFrame(frame: TftFrame) { sent += frame; sendAction() }
}
@Test fun slowAckNeverCausesBacklogOrBusyLoop() {
val policy = TftSessionPolicy()
assertEquals(900L, policy.framePauseMs(100))
assertEquals(50L, policy.framePauseMs(2_000))
assertEquals(1_000L, policy.framePauseMs(-20))
}
@Test fun movementCadenceSupportsFiveAndTenFpsWithAckBackpressure() {
assertEquals(120L, TftSessionPolicy(200).framePauseMs(80))
assertEquals(80L, TftSessionPolicy(100).framePauseMs(20))
assertEquals(50L, TftSessionPolicy(100).framePauseMs(120))
}
@Test fun changesFromIdleToMovementCadenceWithoutSecondWriter() = runBlocking {
val current = Transport()
val started = Channel<Unit>(Channel.UNLIMITED)
val ack = Channel<Unit>(Channel.UNLIMITED)
val waiting = Channel<Long>(Channel.UNLIMITED)
val tick = Channel<Unit>(Channel.UNLIMITED)
var cadence = 1_000L
var now = 0L
var cached = frame(1)
current.sendAction = { started.send(Unit); ack.receive() }
val runner = TftSessionRunner({ current }, { cached }, { TftSessionPolicy(cadence) }, { now },
pause = { waiting.send(it); tick.receive() })
val job = launch { runner.run() }
try {
withTimeout(3_000) {
started.receive()
now = 100
ack.send(Unit)
assertEquals(900L, waiting.receive())
cadence = 200
cached = frame(2)
tick.send(Unit)
started.receive()
assertSame(cached, current.sent[1])
now = 180
ack.send(Unit)
assertEquals(120L, waiting.receive())
assertEquals(1, current.connects)
assertEquals(2, current.sent.size)
}
} finally { job.cancelAndJoin() }
assertEquals(1, current.disconnects)
}
@Test fun invalidCadenceFailsRatherThanCreatingTightLoop() {
for (interval in listOf(0L, 99L, 3_001L)) {
assertThrows(IllegalArgumentException::class.java) { TftSessionPolicy(interval) }
}
}
@Test fun cachedImageUpdatesOnlyAfterPendingAckAndCadence() = runBlocking {
val current = Transport()
val sendStarted = Channel<Unit>(Channel.UNLIMITED)
val ack = Channel<Unit>(Channel.UNLIMITED)
val waiting = Channel<Long>(Channel.UNLIMITED)
val tick = Channel<Unit>(Channel.UNLIMITED)
current.sendAction = { sendStarted.send(Unit); ack.receive() }
var cached = frame(1)
val runner = TftSessionRunner({ current }, { cached }, { TftSessionPolicy() }, { 0 },
pause = { waiting.send(it); tick.receive() })
val job = launch { runner.run() }
try {
withTimeout(3_000) {
sendStarted.receive()
cached = frame(2)
yield()
assertEquals(1, current.sent.size) // No overlapping send while CCU ACK is outstanding.
ack.send(Unit)
assertEquals(1_000L, waiting.receive())
assertEquals(1, current.sent.size) // ACK alone does not bypass cadence.
tick.send(Unit)
sendStarted.receive()
assertSame(cached, current.sent[1])
assertEquals(1, current.connects)
}
} finally { job.cancelAndJoin() }
assertEquals(1, current.disconnects)
}
@Test fun failedConnectionsBackOffAndReuseFrameAfterRecovery() = runBlocking {
val transports = mutableListOf<Transport>()
val retries = mutableListOf<Long>()
val reachedSend = CompletableDeferred<Unit>()
val hold = CompletableDeferred<Unit>()
val cached = frame(7)
val runner = TftSessionRunner(
transportFactory = {
Transport().also {
if (transports.size < 5) it.connectAction = { error("CCU unavailable") }
else it.sendAction = { reachedSend.complete(Unit); hold.await() }
transports += it
}
}, latestFrame = { cached }, policy = { TftSessionPolicy() }, clockMs = { 0 },
pause = { retries += it },
)
val job = launch { runner.run() }
try {
withTimeout(3_000) { reachedSend.await() }
assertEquals(listOf(1_000L, 2_000L, 4_000L, 8_000L, 15_000L), retries)
assertTrue(transports.take(5).all { it.disconnects == 1 })
assertSame(cached, transports.last().sent.single())
} finally { job.cancelAndJoin() }
assertEquals(1, transports.last().disconnects)
}
@Test fun stopDuringRetryPreventsAnotherConnection() = runBlocking {
val current = Transport().apply { connectAction = { error("Disconnected") } }
val waiting = CompletableDeferred<Unit>()
val hold = CompletableDeferred<Unit>()
val runner = TftSessionRunner({ current }, { frame(1) }, { TftSessionPolicy() }, { 0 },
pause = { waiting.complete(Unit); hold.await() })
val job = launch { runner.run() }
withTimeout(3_000) { waiting.await() }
job.cancelAndJoin()
assertEquals(1, current.connects)
assertEquals(1, current.disconnects)
assertTrue(current.sent.isEmpty())
}
@Test fun successfulFrameResetsBackoffBeforeLaterDrop() = runBlocking {
var attempt = 0
val retries = mutableListOf<Long>()
val stopAtThird = CompletableDeferred<Unit>()
val hold = CompletableDeferred<Unit>()
val runner = TftSessionRunner(
transportFactory = {
val number = ++attempt
Transport().apply {
if (number == 1) connectAction = { error("First handshake failed") }
if (number == 2) {
var sends = 0
sendAction = { if (++sends > 1) error("Link dropped after ACK") }
}
if (number == 3) connectAction = { stopAtThird.complete(Unit); hold.await() }
}
}, latestFrame = { frame(1) }, policy = { TftSessionPolicy() }, clockMs = { 0 },
pause = {}, onRetry = { _, millis -> retries += millis },
)
val job = launch { runner.run() }
try {
withTimeout(3_000) { stopAtThird.await() }
assertEquals(listOf(1_000L, 1_000L), retries)
} finally { job.cancelAndJoin() }
}
@Test fun transportLocalAckTimeoutRetriesRatherThanCancellingSession() = runBlocking {
var attempt = 0
val recovered = CompletableDeferred<Unit>()
val hold = CompletableDeferred<Unit>()
val retryWaits = mutableListOf<Long>()
val runner = TftSessionRunner(
transportFactory = {
val number = ++attempt
Transport().apply {
sendAction = {
if (number == 1) withTimeout(5) { awaitCancellation() }
else { recovered.complete(Unit); hold.await() }
}
}
}, latestFrame = { frame(1) }, policy = { TftSessionPolicy() }, clockMs = { 0 },
pause = {}, onRetry = { _, millis -> retryWaits += millis },
)
val job = launch { runner.run() }
try {
withTimeout(3_000) { recovered.await() }
assertTrue(job.isActive)
assertEquals(2, attempt)
assertEquals(listOf(1_000L), retryWaits)
} finally { job.cancelAndJoin() }
assertEquals(2, attempt)
}
}
@@ -0,0 +1,166 @@
package dev.navframe.core
import com.google.gson.JsonParser
import org.junit.Assert.*
import org.junit.Test
class ValhallaRouteTest {
private val fixture get() = javaClass.getResource("/valhalla-route.json")!!.readText()
@Test fun `precision six preserves known coordinates`() {
val decoded = decodePolyline6("_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI")
assertEquals(listOf(GeoPoint(38.5, -120.2), GeoPoint(40.7, -120.95), GeoPoint(43.252, -126.453)), decoded)
}
@Test fun `parse route converts kilometers and preserves segment indices and destination`() {
val destination = GeoPoint(43.36031, -5.85012)
val route = parseValhallaRoute(fixture, destination)
assertEquals(listOf(GeoPoint(43.36, -5.85), GeoPoint(43.3601, -5.8502), GeoPoint(43.3603, -5.8501)), route.geometry)
assertEquals(52, route.distanceMeters)
assertEquals(17, route.durationSeconds)
assertEquals(destination, route.destination)
assertEquals(31, route.maneuvers[0].distanceMeters)
assertEquals(listOf("Calle de prueba"), route.maneuvers[0].streetNames)
assertEquals(10, route.maneuvers[1].type)
assertEquals(1, route.maneuvers[1].beginShapeIndex)
assertEquals(2, route.maneuvers[1].endShapeIndex)
assertEquals(0, route.maneuvers.last().distanceMeters)
}
@Test fun `miles conversion is explicit`() {
val route = parseValhallaRoute(fixture.replace("kilometers", "miles").replace("0.052", "1.0"))
assertEquals(1609, route.distanceMeters)
assertEquals(50, route.maneuvers.first().distanceMeters)
}
@Test fun `multiple legs deduplicate join and rebase indices`() {
val root = JsonParser.parseString(fixture).asJsonObject
val trip = root.getAsJsonObject("trip")
val legs = trip.getAsJsonArray("legs")
val next = legs[0].asJsonObject.deepCopy()
next.addProperty("shape", "waouqAf~`dJgEoK")
val nextManeuvers = next.getAsJsonArray("maneuvers")
nextManeuvers.remove(2)
nextManeuvers[1].asJsonObject.addProperty("begin_shape_index", 1)
nextManeuvers[1].asJsonObject.addProperty("end_shape_index", 1)
legs.add(next)
val route = parseValhallaRoute(root.toString())
assertEquals(4, route.geometry.size)
assertEquals(GeoPoint(43.3604, -5.8499), route.geometry.last())
assertEquals(2, route.maneuvers[3].beginShapeIndex)
assertEquals(3, route.maneuvers[3].endShapeIndex)
assertEquals(3, route.maneuvers[4].beginShapeIndex)
}
@Test fun `malformed shape rejected without hanging`() {
listOf("", "_", "??_", "!!", "~~~~~~~~~~~~??", "_keqlD???").forEach { shape ->
rejects { decodePolyline6(shape) }
}
}
@Test fun `malformed JSON measurements status and indices rejected`() {
listOf(
"{\"trip\":{}", fixture + "{}", "// comment\n$fixture",
fixture.replace("\"status\": 0", "\"status\": 442"),
fixture.replace("\"length\": 0.052", "\"length\": -1"),
fixture.replace("\"length\": 0.052", "\"length\": 1e100"),
fixture.replace("\"time\": 17.4", "\"time\": \"17.4\""),
fixture.replace("\"end_shape_index\": 2", "\"end_shape_index\": 3"),
fixture.replace("\"begin_shape_index\": 1", "\"begin_shape_index\": 3"),
fixture.replace("\"type\": 10", "\"type\": 1.5"),
fixture.replace("kilometers", "meters"),
" ".repeat(2 * 1024 * 1024 + 1),
).forEach { json -> rejects { parseValhallaRoute(json) } }
}
@Test fun `disconnected legs rejected`() {
val root = JsonParser.parseString(fixture).asJsonObject
val legs = root.getAsJsonObject("trip").getAsJsonArray("legs")
legs.add(legs[0].deepCopy())
rejects { parseValhallaRoute(root.toString()) }
}
@Test fun `coordinate request fixes format language and explicit profile options`() {
val origin = GeoPoint(43.36, -5.85)
val destination = GeoPoint(43.37, -5.84)
val root = JsonParser.parseString(buildValhallaRequest(origin, destination)).asJsonObject
assertEquals("motorcycle", root["costing"].asString)
assertEquals(0, root.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_tracks"].asInt)
assertEquals(0.5, root.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_trails"].asDouble, 0.0)
assertEquals("polyline6", root["shape_format"].asString)
assertEquals("es-ES", root["language"].asString)
assertEquals("kilometers", root["units"].asString)
assertEquals(2, root.getAsJsonArray("locations").size())
assertEquals("break", root.getAsJsonArray("locations")[0].asJsonObject["type"].asString)
val avoid = JsonParser.parseString(buildValhallaRequest(origin, destination, RouteOptions(RouteProfile.AVOID_MOTORWAYS))).asJsonObject
assertEquals(0.0, avoid.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_highways"].asDouble, 0.0)
val touring = JsonParser.parseString(buildValhallaRequest(origin, destination, RouteOptions(RouteProfile.TOURING))).asJsonObject
assertEquals(0.2, touring.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")["use_highways"].asDouble, 0.0)
rejects { buildValhallaRequest(GeoPoint(Double.NaN, 0.0), destination) }
rejects { buildValhallaRequest(origin, GeoPoint(0.0, 181.0)) }
}
private fun motorcycleOptions(options: RouteOptions) = JsonParser.parseString(
buildValhallaRequest(GeoPoint(43.36, -5.85), GeoPoint(43.37, -5.84), options)
).asJsonObject.getAsJsonObject("costing_options").getAsJsonObject("motorcycle")
@Test fun `asphalt preset applies motorcycle surface preference without unsupported hard exclusion`() {
val fast = motorcycleOptions(RouteOptions())
val asphalt = motorcycleOptions(RouteOptions(RouteProfile.AVOID_UNPAVED))
assertEquals(0.5, fast["use_highways"].asDouble, 0.0)
assertEquals(0.5, fast["use_trails"].asDouble, 0.0)
assertEquals(0.0, asphalt["use_trails"].asDouble, 0.0)
assertEquals(fast["use_highways"], asphalt["use_highways"])
assertFalse(asphalt.has("exclude_unpaved"))
assertFalse(asphalt.has("exclude_highways"))
assertFalse(asphalt.has("shortest"))
}
@Test fun `combinable flags persist on presets without changing motorcycle mode`() {
val options = RouteOptions(RouteProfile.TOURING, avoidMotorways = true, avoidUnpaved = true, avoidTolls = true)
val cost = motorcycleOptions(options)
assertEquals(0.0, cost["use_highways"].asDouble, 0.0)
assertEquals(0.0, cost["use_trails"].asDouble, 0.0)
assertEquals(0.0, cost["use_tolls"].asDouble, 0.0)
assertEquals(0, cost["use_tracks"].asInt)
val request = JsonParser.parseString(buildValhallaRequest(GeoPoint(0.0, 0.0), GeoPoint(0.1, 0.1), options)).asJsonObject
assertEquals("motorcycle", request["costing"].asString)
assertFalse(cost.keySet().any { it.startsWith("exclude_") })
assertEquals(cost, motorcycleOptions(options.copy()))
}
@Test fun `optional rough maneuver evidence never certifies asphalt from absence`() {
assertNull(parseValhallaRoute(fixture).hasUnpaved)
val root = JsonParser.parseString(fixture).asJsonObject
val maneuvers = root.getAsJsonObject("trip").getAsJsonArray("legs")[0].asJsonObject.getAsJsonArray("maneuvers")
maneuvers[0].asJsonObject.addProperty("rough", true)
assertEquals(true, parseValhallaRoute(root.toString()).hasUnpaved)
maneuvers[0].asJsonObject.addProperty("rough", false)
assertNull(parseValhallaRoute(root.toString()).hasUnpaved)
maneuvers.forEach { it.asJsonObject.addProperty("rough", false) }
assertEquals(false, parseValhallaRoute(root.toString()).hasUnpaved)
}
@Test fun `optional surface evidence rejects coercion instead of trusting backend strings`() {
val root = JsonParser.parseString(fixture).asJsonObject
val maneuver = root.getAsJsonObject("trip").getAsJsonArray("legs")[0].asJsonObject.getAsJsonArray("maneuvers")[0].asJsonObject
listOf("false", "true", "1").forEach {
maneuver.addProperty("rough", it)
rejects { parseValhallaRoute(root.toString()) }
}
}
@Test fun `backend error is sanitized`() {
try {
parseValhallaRoute("{\"error\":\"private-coordinate-details\",\"error_code\":442}")
fail("Expected error")
} catch (error: ValhallaRouteException) {
assertFalse(error.message!!.contains("private-coordinate-details"))
}
}
private fun rejects(block: () -> Unit) {
try { block(); fail("Expected invalid routing data to be rejected") }
catch (_: ValhallaRouteException) { /* expected */ }
}
}
@@ -0,0 +1,35 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
class VoiceGuidancePolicyTest {
private val turn = Maneuver("Gira a la izquierda", 100, 15, 1, 2)
private val route = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.01)), listOf(turn), 1000, 100)
private fun state(distance: Int = 250, status: NavigationStatus = NavigationStatus.NAVIGATING) =
NavigationState(route = route, nextManeuver = turn, distanceToNextManeuverMeters = distance, navigationStatus = status)
@Test fun `distance checkpoints do not repeat or replay skipped stages`() {
val policy = VoiceGuidancePolicy()
assertNotNull(policy.announcement(state()))
repeat(100) { assertNull(policy.announcement(state(260))) }
assertNotNull(policy.announcement(state(25)))
assertNull(policy.announcement(state(90)))
assertNull(policy.announcement(state(25)))
}
@Test fun `preview and no route never speak and replacement resets checkpoint`() {
val policy = VoiceGuidancePolicy()
assertNull(policy.announcement(state(status = NavigationStatus.ROUTE_PREVIEW)))
assertNotNull(policy.announcement(state()))
assertNotNull(policy.announcement(state().copy(route = route.copy())))
assertNull(policy.announcement(NavigationState()))
assertNotNull(policy.announcement(state()))
}
@Test fun `arrival rerouting and poor GPS speak once per route and suppress turns`() {
val policy = VoiceGuidancePolicy()
for (status in listOf(NavigationStatus.REROUTING, NavigationStatus.GPS_LOST, NavigationStatus.ARRIVED)) {
assertNotNull(policy.announcement(state(status = status)))
repeat(10) { assertNull(policy.announcement(state(status = status))) }
}
}
}
@@ -0,0 +1,18 @@
{
"trip": {
"status_message": "Found route between points",
"status": 0,
"units": "kilometers",
"language": "es-ES",
"summary": {"length": 0.052, "time": 17.4},
"legs": [{
"shape": "_onuqA~w`dJgEnKoKgE",
"summary": {"length": 0.052, "time": 17.4},
"maneuvers": [
{"type": 1, "instruction": "Dirígete hacia el norte.", "street_names": ["Calle de prueba"], "length": 0.031, "time": 10.4, "begin_shape_index": 0, "end_shape_index": 1},
{"type": 10, "instruction": "Gira a la derecha.", "length": 0.021, "time": 7, "begin_shape_index": 1, "end_shape_index": 2},
{"type": 4, "instruction": "Has llegado a tu destino.", "length": 0, "time": 0, "begin_shape_index": 2, "end_shape_index": 2}
]
}]
}
}