mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 07:16:06 +00:00
Merge pull request #3 from Dasemu/feat/faster-location-compass
Improve location startup and add compass heading
This commit is contained in:
11 files changed
+354
-36
No files matched your search
@@ -27,6 +27,10 @@ python3 -m unittest discover -s tools/offline -p 'test_*.py'
|
||||
|
||||
Set up `local.properties` for your own Android SDK when needed. It is excluded from Git. See [Contributing](CONTRIBUTING.md) for the development and review process.
|
||||
|
||||
## Location and compass
|
||||
|
||||
Version 0.13.3 uses available native Android location sources and recent cached fixes to avoid waiting exclusively for a new satellite fix. The map can recenter on a recent approximate position with accuracy up to 100 metres; starting route guidance still requires 25 metres. A compass heading orients the map at low speed, while usable movement course takes priority when riding. See [Location and compass](docs/LOCATION_AND_COMPASS.md) for behavior and device-validation limits.
|
||||
|
||||
## TFT diagnostic history
|
||||
|
||||
Version 0.13.2 automatically saves the latest 100 TFT map failures and recoveries on the phone. After a reboot or empty battery, open **Information and licenses → TFT map diagnosis → Share** to export the saved history. It excludes coordinates, URLs, route/search text, and Bluetooth identifiers. See [Persistent TFT diagnostics](docs/TFT_DIAGNOSTICS.md) for retention and limitations.
|
||||
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId = "dev.navframe.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 18
|
||||
versionName = "0.13.2"
|
||||
versionCode = 19
|
||||
versionName = "0.13.3"
|
||||
}
|
||||
testOptions { unitTests.isIncludeAndroidResources = true }
|
||||
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package dev.navframe.app
|
||||
|
||||
import android.Manifest
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import dev.navframe.core.*
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.LooperMode
|
||||
import org.robolectric.shadows.ShadowSensor
|
||||
import org.robolectric.shadows.ShadowSensorManager
|
||||
import java.time.Duration
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class AndroidLocationProviderTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private val manager get() = context.getSystemService(LocationManager::class.java)
|
||||
@Before fun permissions() {
|
||||
shadowOf(context).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
|
||||
shadowOf(manager).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)
|
||||
}
|
||||
private fun fix(provider: String = LocationManager.GPS_PROVIDER, accuracy: Float = 7f, ageMs: Long = 0) = Location(provider).apply {
|
||||
latitude = 43.36; longitude = -5.85; this.accuracy = accuracy; time = 1000
|
||||
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos() - ageMs * 1_000_000
|
||||
}
|
||||
private fun tick() { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) }
|
||||
|
||||
@Test fun recentNetworkCacheIsAvailableImmediatelyAndAllListenersAreReleased() = runBlocking {
|
||||
shadowOf(manager).setLastKnownLocation(LocationManager.NETWORK_PROVIDER, fix(LocationManager.NETWORK_PROVIDER, 60f))
|
||||
val provider = AndroidLocationProvider(context)
|
||||
try {
|
||||
provider.start()
|
||||
assertEquals(60f, provider.locations.replayCache.single().accuracyMeters)
|
||||
assertTrue(shadowOf(manager).getLocationUpdateListeners(LocationManager.GPS_PROVIDER).isNotEmpty())
|
||||
assertTrue(shadowOf(manager).getLocationUpdateListeners(LocationManager.NETWORK_PROVIDER).isNotEmpty())
|
||||
} finally { provider.close() }
|
||||
assertTrue(shadowOf(manager).locationUpdateListeners.isEmpty())
|
||||
assertFalse(provider.providerEnabled.value)
|
||||
}
|
||||
|
||||
@Test fun staleInvalidAndFutureCachedFixesAreRejected() = runBlocking {
|
||||
for (location in listOf(fix(ageMs = 15_001), fix(ageMs = -1000), fix().apply { latitude = 91.0 }, fix().apply { accuracy = Float.NaN })) {
|
||||
shadowOf(manager).setLastKnownLocation(LocationManager.GPS_PROVIDER, location)
|
||||
val provider = AndroidLocationProvider(context)
|
||||
try { provider.start(); assertTrue(provider.locations.replayCache.isEmpty()) }
|
||||
finally { provider.close() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun coarseNetworkUpdatesCannotReplaceARecentAccurateFix() = runBlocking {
|
||||
val provider = AndroidLocationProvider(context)
|
||||
try {
|
||||
provider.start()
|
||||
shadowOf(manager).simulateLocation(fix()); tick()
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(6))
|
||||
shadowOf(manager).simulateLocation(fix(LocationManager.NETWORK_PROVIDER, 500f).apply { latitude = 43.4 }); tick()
|
||||
assertEquals(7f, provider.locations.replayCache.single().accuracyMeters)
|
||||
assertEquals(43.36, provider.locations.replayCache.single().position.latitude, 0.000001)
|
||||
} finally { provider.close() }
|
||||
}
|
||||
|
||||
@Test fun disablingOneProviderDoesNotInvalidateTheOtherAndPassiveAloneIsNotReady() = runBlocking {
|
||||
val provider = AndroidLocationProvider(context)
|
||||
try {
|
||||
provider.start()
|
||||
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, false); tick()
|
||||
assertTrue(provider.providerEnabled.value)
|
||||
shadowOf(manager).setProviderEnabled(LocationManager.NETWORK_PROVIDER, false); tick()
|
||||
if ("fused" in manager.allProviders) { shadowOf(manager).setProviderEnabled("fused", false); tick() }
|
||||
assertFalse(provider.providerEnabled.value)
|
||||
} finally { provider.close() }
|
||||
}
|
||||
|
||||
@Test fun serviceAllowsApproximateRecentPositionForMapWithoutClaimingPreciseGuidance() {
|
||||
val controller = Robolectric.buildService(TftService::class.java).create()
|
||||
val service = controller.get()
|
||||
try {
|
||||
service.setPhoneVisible(true); tick()
|
||||
shadowOf(manager).simulateLocation(fix(LocationManager.NETWORK_PROVIDER, 80f)); tick()
|
||||
assertTrue(service.hasFreshGpsFix())
|
||||
assertTrue(service.gpsReady.value)
|
||||
assertEquals(80f, service.navigationState.value.accuracyMeters)
|
||||
assertEquals(NavigationStatus.NAVIGATING, service.navigationState.value.navigationStatus)
|
||||
val route = RouteResult(listOf(GeoPoint(43.36, -5.85), GeoPoint(43.37, -5.85)), emptyList(), 1100, 100)
|
||||
assertEquals(NavigationStatus.GPS_LOST, RouteGuidanceTracker(route).update(LocationFix(GeoPoint(43.36, -5.85), Float.NaN, 0f, 80f, 1000), 0, 0).navigationStatus)
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(16))
|
||||
assertFalse(service.hasFreshGpsFix())
|
||||
assertEquals(NavigationStatus.GPS_LOST, service.navigationState.value.navigationStatus)
|
||||
assertNull(service.navigationState.value.accuracyMeters)
|
||||
service.setPhoneVisible(false); tick()
|
||||
assertFalse(service.hasFreshGpsFix())
|
||||
} finally { controller.destroy() }
|
||||
}
|
||||
|
||||
@Test fun compassDrivesStationaryHeadingButMovingGpsWinsAndSensorsStopOnClose() = runBlocking {
|
||||
val sensors = context.getSystemService(SensorManager::class.java)
|
||||
val sensor = ShadowSensor.newInstance(Sensor.TYPE_ROTATION_VECTOR)
|
||||
shadowOf(sensors).addSensor(sensor)
|
||||
val provider = AndroidLocationProvider(context)
|
||||
try {
|
||||
provider.start()
|
||||
val event = ShadowSensorManager.createSensorEvent(4).apply {
|
||||
this.sensor = sensor; accuracy = SensorManager.SENSOR_STATUS_ACCURACY_HIGH
|
||||
values[0] = 0f; values[1] = 0f; values[2] = 0f; values[3] = 1f
|
||||
}
|
||||
shadowOf(sensors).sendSensorEventToListeners(event); tick()
|
||||
assertTrue(provider.currentBearing.isFinite())
|
||||
assertTrue(provider.headingFromCompass)
|
||||
shadowOf(manager).simulateLocation(fix().apply { speed = 12f; bearing = 90f }); tick()
|
||||
assertEquals(90f, provider.currentBearing)
|
||||
assertFalse(provider.headingFromCompass)
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
|
||||
shadowOf(manager).simulateLocation(fix().apply { speed = 0f; bearing = 90f }); tick()
|
||||
assertTrue(provider.headingFromCompass)
|
||||
event.accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE
|
||||
shadowOf(sensors).sendSensorEventToListeners(event); tick()
|
||||
assertTrue(provider.currentBearing.isNaN())
|
||||
} finally { provider.close() }
|
||||
assertTrue(shadowOf(sensors).listeners.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun headingSelectionAndSmoothingRespectNorthWrapAndMissingSensors() {
|
||||
assertEquals(90f, selectHeading(90f, 12f, 180f))
|
||||
assertEquals(180f, selectHeading(90f, 0f, 180f))
|
||||
assertTrue(selectHeading(90f, 0f, Float.NaN).isNaN())
|
||||
assertTrue(selectHeading(Float.NaN, 12f, Float.NaN).isNaN())
|
||||
assertEquals(354f, smoothHeading(350f, 10f))
|
||||
assertEquals(6f, smoothHeading(10f, 350f))
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ data class RenderScheduleConfig(
|
||||
val turningDeltaDegrees: Float = 15f,
|
||||
val speedDeltaMetersPerSecond: Float = 0.5f,
|
||||
val distanceLabelStepMeters: Int = 10,
|
||||
val redrawStationaryBearing: Boolean = false,
|
||||
) {
|
||||
init {
|
||||
require(listOf(stoppedMaxFps, movingMaxFps, turningMaxFps).all { it.isFinite() && it > 0 })
|
||||
@@ -77,7 +78,7 @@ class RenderScheduler(private val config: RenderScheduleConfig = RenderScheduleC
|
||||
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 &&
|
||||
((config.redrawStationaryBearing || max(old.speed, fresh.speed) >= config.movingSpeedMetersPerSecond) &&
|
||||
bearingDistance(old.bearing, fresh.bearing) >= config.bearingDeltaDegrees)
|
||||
|
||||
private fun label(distance: Int?): Int? = distance?.div(config.distanceLabelStepMeters)
|
||||
|
||||
@@ -126,6 +126,17 @@ class RenderSchedulerTest {
|
||||
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = null, bearing = Float.NaN), 4_000))
|
||||
}
|
||||
|
||||
@Test fun stationaryCompassRotationRedrawsOnlyWhenEnabledAndWithinItsRateLimit() {
|
||||
val scheduler = RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, redrawStationaryBearing = true))
|
||||
val first = state().copy(speed = 0f, bearing = 10f)
|
||||
assertTrue(scheduler.renderIfDue(first, 0))
|
||||
assertFalse(scheduler.renderIfDue(first.copy(bearing = 40f), 1_000))
|
||||
assertTrue(scheduler.renderIfDue(first.copy(bearing = 40f), 2_000))
|
||||
val original = RenderScheduler()
|
||||
original.renderIfDue(first, 0)
|
||||
assertFalse(original.renderIfDue(first.copy(bearing = 40f), 2_000))
|
||||
}
|
||||
|
||||
@Test fun invalidConfigurationIsRejected() {
|
||||
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(movingMaxFps = Double.NaN) }
|
||||
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(distanceLabelStepMeters = 0) }
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Location acquisition and compass (0.13.3)
|
||||
|
||||
NavFrame now listens to the Android location sources available on the device: GNSS/GPS, network, native fused location, and passive updates. It also seeds the position from a recent, validated Android last-known location rather than always waiting for another satellite fix. The native fused provider is used only when present; this does not introduce a Google Play services dependency or guarantee the same acquisition behavior as Google Maps or Waze.
|
||||
|
||||
## Approximate position versus route guidance
|
||||
|
||||
The previous 25-metre gate applied even to recentering the map. A recent position with reported accuracy up to 100 metres can now recenter the map, supply a route-preview origin, and show the rider's approximate position. The phone displays the estimated accuracy and labels positions worse than 25 metres as approximate. Stale, future-dated, invalid, or accuracy-free fixes are rejected. A very coarse network update cannot replace a recent usable precise fix.
|
||||
|
||||
Starting guidance and automatic recalculation still require a recent fix with accuracy at most 25 metres. The route tracker retains its existing precision, freshness, and sustained-deviation rules. Approximate position is not presented as confirmed road-level route progress. If guidance pauses for low precision while a recent approximate position remains available, the phone/TFT explain that distinction instead of simply claiming there is no GPS signal.
|
||||
|
||||
All freshness checks use Android's monotonic elapsed time and a 15-second limit, including cached fixes. Location services must be enabled and precise location permission remains required by the current app workflow. Enabled providers are tracked independently; disabling one does not invalidate another active provider. Location subscriptions are removed when their visible-map or navigation session ends.
|
||||
|
||||
## Compass and course
|
||||
|
||||
When the position workflow is active, the app uses an absolute rotation-vector sensor (or a geomagnetic rotation-vector sensor when available) to determine the direction of the top edge of the screen. Display rotation is accounted for, and the latest in-memory location supplies magnetic declination for a true-north heading. No extra sensor permission is needed.
|
||||
|
||||
At speeds of at least 2 m/s, a usable GPS course takes priority. At lower speeds, an available compass heading drives the map orientation and the phone shows **Brújula** (Compass). The phone labels movement course **Rumbo GPS** (GPS course). The compass is smoothed across the north/360-degree boundary, expires after five seconds without a measurement, and rejects sensor status UNRELIABLE. Without a suitable sensor or trustworthy heading, direction remains unavailable rather than inventing north as a measured heading.
|
||||
|
||||
Stationary TFT compass changes can redraw the map, limited to the existing stopped-map cadence (at most once every two seconds). Sensor listeners are released with the location workflow. Magnetic mounts, vehicle metal, and device calibration can affect compass accuracy; test with the phone in its actual mounting position. The sensor describes phone orientation, not inherently motorcycle orientation.
|
||||
|
||||
Coordinates are used only in memory; this change does not add coordinate logs or uploads. It retains the existing explicit online-route/search behavior and the persistent sanitized TFT diagnostics from 0.13.2.
|
||||
|
||||
## Validation
|
||||
|
||||
Robolectric tests cover fresh network-cache startup, stale/invalid/future fixes, coarse updates competing with precise fixes, independent provider availability and cleanup, approximate-map readiness versus strict route guidance, expiration of stale visible positions, stationary compass versus movement course, sensor reliability/cleanup, and north-wrap smoothing. A core scheduling test verifies stationary compass redraws respect the configured rate limit without changing the default policy for other renderers.
|
||||
|
||||
Native GNSS acquisition time, device-specific provider availability, compass accuracy on a motorcycle mount, and physical TFT rendering require device validation.
|
||||
Reference in new issue
Block a user