feat: reuse native location fixes and add low-speed compass heading

This commit is contained in:
Darío Sevilla committed 2026-10-13 05:51:13 +00:00
1 parent 74b222a094
commit d335a084d4
11 files changed
+354 -36

No files matched your search

@@ -0,0 +1,71 @@
package dev.navframe.app
import android.content.Context
import android.hardware.GeomagneticField
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.SystemClock
import android.view.Surface
import android.view.WindowManager
import dev.navframe.core.GeoPoint
import dev.navframe.core.normalizeBearing
/** Absolute orientation of the screen's top edge; coordinates are only used in memory for declination. */
internal class AndroidCompass(context: Context, private val changed: () -> Unit) : SensorEventListener {
private val manager = context.getSystemService(SensorManager::class.java)
private val windows = context.getSystemService(WindowManager::class.java)
private var sensor: Sensor? = null
private var degrees = Float.NaN
private var measuredAt = 0L
private var declination = 0f
private var accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE
private val matrix = FloatArray(9)
private val remapped = FloatArray(9)
private val angles = FloatArray(3)
fun start() {
sensor = manager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
?: manager.getDefaultSensor(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR)
sensor?.let { manager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI) }
}
fun updatePosition(point: GeoPoint) {
declination = GeomagneticField(point.latitude.toFloat(), point.longitude.toFloat(), 0f, System.currentTimeMillis()).declination
}
fun heading(): Float = if (degrees.isFinite() && accuracy != SensorManager.SENSOR_STATUS_UNRELIABLE && SystemClock.elapsedRealtime() - measuredAt in 0..5_000) normalizeBearing(degrees + declination) else Float.NaN
fun close() {
manager.unregisterListener(this)
sensor = null; degrees = Float.NaN; measuredAt = 0
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { this.accuracy = accuracy; changed() }
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor != sensor) return
accuracy = event.accuracy
if (accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { degrees = Float.NaN; changed(); return }
SensorManager.getRotationMatrixFromVector(matrix, event.values)
@Suppress("DEPRECATION")
val axes = when (windows.defaultDisplay.rotation) {
Surface.ROTATION_90 -> SensorManager.AXIS_Y to SensorManager.AXIS_MINUS_X
Surface.ROTATION_180 -> SensorManager.AXIS_MINUS_X to SensorManager.AXIS_MINUS_Y
Surface.ROTATION_270 -> SensorManager.AXIS_MINUS_Y to SensorManager.AXIS_X
else -> SensorManager.AXIS_X to SensorManager.AXIS_Y
}
SensorManager.remapCoordinateSystem(matrix, axes.first, axes.second, remapped)
SensorManager.getOrientation(remapped, angles)
val next = normalizeBearing(Math.toDegrees(angles[0].toDouble()).toFloat())
degrees = smoothHeading(degrees, next)
measuredAt = SystemClock.elapsedRealtime()
changed()
}
}
internal fun smoothHeading(previous: Float, next: Float): Float = if (!previous.isFinite()) normalizeBearing(next) else
normalizeBearing(previous + (((next - previous + 540f) % 360f) - 180f) * .2f)
internal fun selectHeading(course: Float, speed: Float, compass: Float): Float = when {
speed >= 2f && course.isFinite() -> normalizeBearing(course)
compass.isFinite() -> normalizeBearing(compass)
speed >= .7f && course.isFinite() -> normalizeBearing(course)
else -> Float.NaN
}
@@ -15,7 +15,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
/** Android GPS only. Locations stay in memory and are never written to logs. */
/** Native Android location sources and compass. Positions stay in memory and are never logged. */
class AndroidLocationProvider(context: Context) : LocationProvider {
private val context = context.applicationContext
private val manager = this.context.getSystemService(LocationManager::class.java)
@@ -23,44 +23,92 @@ class AndroidLocationProvider(context: Context) : LocationProvider {
override val locations = fixes.asSharedFlow()
private val enabled = MutableStateFlow(false)
val providerEnabled = enabled.asStateFlow()
private val headings = MutableStateFlow(Float.NaN)
val bearings = headings.asStateFlow()
private val compass = AndroidCompass(this.context) { updateBearing() }
private val registered = mutableSetOf<String>()
private var lastLocation: Location? = null
val currentBearing: Float get() { updateBearing(); return headings.value }
var lastFixElapsedMs: Long = 0
private set
internal var headingFromCompass = false
private set
private var listening = false
private val listener = object : LocationListener {
override fun onLocationChanged(location: Location) {
val ageMs = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000
if (ageMs !in 0..15_000 || !location.latitude.isFinite() || !location.longitude.isFinite()) return
lastFixElapsedMs = location.elapsedRealtimeNanos / 1_000_000
enabled.value = true
fixes.tryEmit(LocationFix(
GeoPoint(location.latitude, location.longitude),
if (location.hasBearing()) location.bearing else Float.NaN,
if (location.hasSpeed() && location.speed.isFinite()) location.speed.coerceAtLeast(0f) else 0f,
if (location.hasAccuracy()) location.accuracy else Float.POSITIVE_INFINITY,
location.time,
))
private fun updateBearing() {
val fix = lastLocation
val course = if (fix?.hasBearing() == true && (!fix.hasBearingAccuracy() || fix.bearingAccuracyDegrees <= 45f)) fix.bearing else Float.NaN
val recent = fix != null && locationAgeMs(fix) in 0..MAX_FIX_AGE_MS
val compassHeading = compass.heading()
val speed = if (recent && fix!!.hasSpeed()) fix.speed else 0f
headingFromCompass = compassHeading.isFinite() && !(speed >= 2f && recent && course.isFinite())
headings.value = selectHeading(if (recent) course else Float.NaN, speed, compassHeading)
}
private fun accept(location: Location) {
if (!validLocation(location)) return
val previous = lastLocation
if (previous != null && validLocation(previous)) {
val newerMs = (location.elapsedRealtimeNanos - previous.elapsedRealtimeNanos) / 1_000_000
if (location.accuracy > MAP_ACCURACY_METERS && previous.accuracy <= MAP_ACCURACY_METERS) return
if (newerMs < 0 || (newerMs < 5_000 && location.accuracy > previous.accuracy * 2 + 20)) return
}
override fun onProviderEnabled(provider: String) { enabled.value = true }
override fun onProviderDisabled(provider: String) { enabled.value = false; lastFixElapsedMs = 0 }
lastLocation = Location(location)
lastFixElapsedMs = location.elapsedRealtimeNanos / 1_000_000
refreshEnabled()
compass.updatePosition(GeoPoint(location.latitude, location.longitude))
fixes.tryEmit(LocationFix(
GeoPoint(location.latitude, location.longitude), currentBearing,
if (location.hasSpeed() && location.speed.isFinite()) location.speed.coerceAtLeast(0f) else 0f,
location.accuracy, location.time,
))
}
private fun refreshEnabled() { enabled.value = registered.any { it != LocationManager.PASSIVE_PROVIDER && manager.isProviderEnabled(it) } }
private val listener = object : LocationListener {
override fun onLocationChanged(location: Location) { if (listening) accept(location) }
override fun onProviderEnabled(provider: String) { refreshEnabled() }
override fun onProviderDisabled(provider: String) { refreshEnabled(); if (!enabled.value) lastFixElapsedMs = 0 }
@Deprecated("Legacy Android callback")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { }
}
override suspend fun start() {
check(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
"Autoriza ubicación precisa para usar el GPS"
"Autoriza ubicación precisa para usar la ubicación"
}
check(LocationManager.GPS_PROVIDER in manager.allProviders) { "GPS no disponible en este dispositivo" }
if (listening) return
lastFixElapsedMs = 0
enabled.value = manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
lastLocation = null
val available = manager.allProviders.filter { it in setOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER, "fused", LocationManager.PASSIVE_PROVIDER) }
check(available.any { it != LocationManager.PASSIVE_PROVIDER }) { "Ubicación no disponible en este dispositivo" }
listening = true
try {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500L, 0f, listener, Looper.getMainLooper())
listening = true
} catch (error: Exception) { manager.removeUpdates(listener); throw error }
for (provider in available) {
try {
manager.requestLocationUpdates(provider, 500L, 0f, listener, Looper.getMainLooper())
registered += provider
} catch (_: IllegalArgumentException) { /* An optional provider can disappear during registration. */ }
}
check(registered.any { it != LocationManager.PASSIVE_PROVIDER }) { "No se pudo activar la ubicación" }
refreshEnabled()
compass.start()
// Seed promptly from a recent fix Android already has, instead of waiting for a new satellite fix.
registered.filter { manager.isProviderEnabled(it) }.mapNotNull { try { manager.getLastKnownLocation(it) } catch (_: IllegalArgumentException) { null } }
.filter(::validLocation).minByOrNull { it.accuracy + locationAgeMs(it) / 100f }?.let(::accept)
} catch (error: Exception) { close(); throw error }
}
override suspend fun stop() { close() }
fun close() {
try { if (listening) manager.removeUpdates(listener) }
finally { listening = false; enabled.value = false; lastFixElapsedMs = 0 }
finally {
compass.close(); registered.clear(); listening = false; enabled.value = false
lastFixElapsedMs = 0; lastLocation = null; headings.value = Float.NaN; headingFromCompass = false
}
}
companion object {
const val MAX_FIX_AGE_MS = 15_000L
const val MAP_ACCURACY_METERS = 100f
const val GUIDANCE_ACCURACY_METERS = 25f
internal fun locationAgeMs(location: Location) = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000
internal fun validLocation(location: Location): Boolean = locationAgeMs(location) in 0..MAX_FIX_AGE_MS &&
location.latitude.isFinite() && location.latitude in -90.0..90.0 && location.longitude.isFinite() && location.longitude in -180.0..180.0 &&
location.hasAccuracy() && location.accuracy.isFinite() && location.accuracy >= 0
}
}
@@ -204,7 +204,7 @@ open class MainActivity : Activity() {
val demo = current.navigationMode.value == NavigationMode.MAP_DEMO || current.navigationMode.value == NavigationMode.DEMO
guidance.text = when (state.navigationStatus) {
NavigationStatus.GPS_LOST -> "Sin GPS reciente y preciso"
NavigationStatus.GPS_LOST -> if (current.hasFreshGpsFix()) "Posición aproximada · esperando precisión para guiar" else "Sin ubicación reciente"
NavigationStatus.REROUTING -> "Recalculando ruta…"
NavigationStatus.OFF_ROUTE -> "Fuera de ruta"
NavigationStatus.ARRIVED -> "Has llegado al destino"
@@ -215,8 +215,9 @@ open class MainActivity : Activity() {
val next = state.distanceToNextManeuverMeters?.let { "$it m" } ?: ""
val remaining = state.remainingDistanceMeters?.let { "%.1f km restantes".format(java.util.Locale.ROOT, it / 1000.0) } ?: ""
val eta = state.etaEpochMillis?.let { "ETA " + java.text.SimpleDateFormat("HH:mm", java.util.Locale.ROOT).format(java.util.Date(it)) } ?: ""
val accuracy = state.accuracyMeters?.takeIf { it.isFinite() }?.let { "GPS ±${it.toInt()} m" } ?: ""
progress.text = listOf(next, remaining, eta, accuracy).filter { it.isNotEmpty() }.joinToString(" · ")
val accuracy = state.accuracyMeters?.takeIf { it.isFinite() }?.let { "${if (it > AndroidLocationProvider.GUIDANCE_ACCURACY_METERS) "Ubicación aproximada" else "Ubicación"} ±${it.toInt()} m" } ?: ""
val heading = if (!demo) state.bearing.takeIf { it.isFinite() }?.let { "${if (current.usesCompassHeading()) "Brújula" else "Rumbo GPS"} ${it.toInt()}°" } ?: "" else ""
progress.text = listOf(next, remaining, eta, accuracy, heading).filter { it.isNotEmpty() }.joinToString(" · ")
} }
}
}
@@ -267,7 +268,7 @@ open class MainActivity : Activity() {
if (hasReliablePosition()) { hidePositionNotice(); recenterPhoneMap() }
else showPositionNotice(when {
current == null || !current.isGpsSessionActive() && current.navigationState.value.accuracyMeters == null -> "Buscando señal GPS…"
current.navigationState.value.accuracyMeters?.let { !it.isFinite() || it > 25f } == true -> "Señal GPS poco precisa"
current.navigationState.value.accuracyMeters?.let { !it.isFinite() || it > AndroidLocationProvider.MAP_ACCURACY_METERS } == true -> "Señal GPS poco precisa"
else -> "Esperando una posición GPS reciente"
})
}
@@ -29,6 +29,7 @@ class MapFrameComposer {
}
val lost = state.navigationStatus == NavigationStatus.GPS_LOST
val approximate = lost && state.accuracyMeters?.let { it.isFinite() && it > AndroidLocationProvider.GUIDANCE_ACCURACY_METERS && it <= AndroidLocationProvider.MAP_ACCURACY_METERS } == true
val accent = Color.rgb(80, 227, 194)
val guidanceVisible = state.route != null && state.navigationStatus != NavigationStatus.ROUTE_PREVIEW
val preview = state.route != null && !guidanceVisible
@@ -39,6 +40,7 @@ class MapFrameComposer {
canvas.drawRect(0f, 0f, WIDTH.toFloat(), topHeight.toFloat(), paint)
val modeText = if (mode == NavigationMode.MAP_DEMO) "DEMO" else "GPS"
val routeText = when {
approximate -> "POSICIÓN APROXIMADA"
lost -> "SIN SEÑAL GPS"
unavailable || map == null -> "MAPA NO DISPONIBLE"
state.route != null -> "RUTA"
@@ -49,6 +51,7 @@ class MapFrameComposer {
if (guidanceVisible) {
val warning = when {
unavailable || map == null -> "GUIADO EN ESPERA · SIN MAPA"
approximate -> "PRECISIÓN BAJA · guiado en espera"
lost -> "SIN GPS · esperando posición precisa"
state.navigationStatus == NavigationStatus.REROUTING -> "RECALCULANDO · espera nueva ruta"
state.navigationStatus == NavigationStatus.OFF_ROUTE -> "FUERA DE RUTA · revisa el recorrido"
@@ -446,7 +446,7 @@ class TftService : Service() {
if (lost && state.navigationStatus != NavigationStatus.GPS_LOST) {
state = state.copy(speed = 0f, bearing = Float.NaN, navigationStatus = NavigationStatus.GPS_LOST, accuracyMeters = null)
}
state = withRoute(state, false)
state = withRoute(state, false).copy(bearing = provider.currentBearing)
latestNavigationState = state
checkSpeedCameras(state, now)
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && reroutePolicy.shouldRequest(state, now)) requestReroute(false)
@@ -586,7 +586,7 @@ class TftService : Service() {
}
if (preparedDestinationDirty) { mutableRouteInfo.value = "Destino cambiado · calcula una nueva ruta primero."; return }
val plan = routePlan ?: run { mutableRouteInfo.value = "Calcula una ruta primero."; return }
if (!preview && !plan.demo && !hasFreshGpsFix()) { mutableRouteInfo.value = "Espera GPS reciente y preciso antes de iniciar guiado"; return }
if (!preview && !plan.demo && !hasGuidanceGpsFix()) { mutableRouteInfo.value = "Espera GPS reciente y preciso antes de iniciar guiado"; return }
shownRoute = plan
routePreview = preview
guidance = RouteGuidanceTracker(plan.route)
@@ -679,7 +679,7 @@ class TftService : Service() {
}
private fun isMapMode(mode: NavigationMode) = mode == NavigationMode.MAP_DEMO || mode == NavigationMode.MAP_GPS
private fun createScheduler(mode: NavigationMode) = if (isMapMode(mode)) RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, movingMaxFps = 1.0, turningMaxFps = 1.0, positionDeltaMeters = 5.0, bearingDeltaDegrees = 5f)) else RenderScheduler()
private fun createScheduler(mode: NavigationMode) = if (isMapMode(mode)) RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, movingMaxFps = 1.0, turningMaxFps = 1.0, positionDeltaMeters = 5.0, bearingDeltaDegrees = 5f, redrawStationaryBearing = true)) else RenderScheduler()
fun mapSource(): TileSource {
val preferences = getSharedPreferences("map", MODE_PRIVATE)
@@ -702,7 +702,10 @@ class TftService : Service() {
}
fun isRealSessionRequested(): Boolean = realRequested
fun isGpsSessionActive(): Boolean = gpsRequested
fun hasFreshGpsFix(): Boolean = lastGpsFix?.let { it.accuracyMeters.isFinite() && it.accuracyMeters <= 25 && SystemClock.elapsedRealtime() - lastGpsElapsed in 0..15_000 && (locationProvider?.providerEnabled?.value == true || (phoneVisible && visibleGpsProvider?.providerEnabled?.value == true)) } == true
fun hasFreshGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.MAP_ACCURACY_METERS)
fun usesCompassHeading(): Boolean = (locationProvider ?: visibleGpsProvider)?.headingFromCompass == true
private fun hasGuidanceGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.GUIDANCE_ACCURACY_METERS)
private fun usableGpsFix(maxAccuracy: Float): Boolean = lastGpsFix?.let { it.accuracyMeters.isFinite() && it.accuracyMeters in 0f..maxAccuracy && SystemClock.elapsedRealtime() - lastGpsElapsed in 0..15_000 && (locationProvider?.providerEnabled?.value == true || (phoneVisible && visibleGpsProvider?.providerEnabled?.value == true)) } == true
private fun stopVisibleGps() {
visibleGpsJob?.cancel(); visibleGpsJob = null
try { visibleGpsProvider?.close() } catch (_: SecurityException) { }
@@ -725,13 +728,17 @@ class TftService : Service() {
lastGpsFix = fix; lastGpsElapsed = provider.lastFixElapsedMs
mutableGpsReady.value = hasFreshGpsFix()
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) {
latestNavigationState = latestNavigationState.copy(position = fix.position, bearing = fix.bearing, speed = fix.speedMetersPerSecond, accuracyMeters = fix.accuracyMeters, navigationStatus = if (routePreview && shownRoute != null) NavigationStatus.ROUTE_PREVIEW else if (fix.accuracyMeters <= 25) NavigationStatus.NAVIGATING else NavigationStatus.GPS_LOST)
latestNavigationState = latestNavigationState.copy(position = fix.position, bearing = fix.bearing, speed = fix.speedMetersPerSecond, accuracyMeters = fix.accuracyMeters, navigationStatus = if (routePreview && shownRoute != null) NavigationStatus.ROUTE_PREVIEW else if (fix.accuracyMeters <= AndroidLocationProvider.MAP_ACCURACY_METERS) NavigationStatus.NAVIGATING else NavigationStatus.GPS_LOST)
}
} }
launch { provider.bearings.collect { bearing ->
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(bearing = bearing)
} }
provider.start()
while (isActive) {
mutableGpsReady.value = hasFreshGpsFix()
if (!gpsRequested && (!provider.providerEnabled.value || SystemClock.elapsedRealtime() - provider.lastFixElapsedMs > 15_000) && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(speed = 0f, bearing = Float.NaN, navigationStatus = NavigationStatus.GPS_LOST)
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(bearing = provider.currentBearing)
if (!gpsRequested && (!provider.providerEnabled.value || SystemClock.elapsedRealtime() - provider.lastFixElapsedMs > 15_000) && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(speed = 0f, bearing = Float.NaN, accuracyMeters = null, navigationStatus = NavigationStatus.GPS_LOST)
delay(1_000)
}
}