mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 15:26:05 +00:00
Fix off-route detection and TFT network lifecycle
This commit is contained in:
1 parent
823d5db5d7
commit
6fec09f20f
11 files changed
+267
-18
No files matched your search
@@ -600,7 +600,7 @@ open class MainActivity : Activity() {
|
||||
}.setNegativeButton("Cancelar", null).show()
|
||||
}
|
||||
private fun showInfo() {
|
||||
val text = "NavFrame 0.11.0 · mapas OpenStreetMap. Móvil y Yamaha comparten estado; el TFT se renderiza directamente a 480 × 240, sin captura de pantalla.\n\nDEMO es ficticia. GPS/ETA/guiado deben probarse en condiciones reales. Rutas y búsqueda necesitan conexión; los mapas y lugares incluidos de Asturias se consultan offline. Calcular rutas sigue necesitando Internet.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No envíes información personal/confidencial. Prototipo con máximo 1 petición/s agregado y caché.\n\nNaviLite adaptado de Pillion · PolyForm Noncommercial 1.0.0\nRequired Notice: Copyright 2026 the Pillion authors\n\nFuente online predeterminada incluida: OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors.\n\nAsturias offline: datos © OpenStreetMap contributors, extracto Geofabrik 28/09/2026, licencia ODbL. Límites 42,9–43,75 N / 7,2–4,45 O; zoom 6–14. Tipografía Noto Sans, SIL OFL 1.1."
|
||||
val text = "NavFrame 0.13.1 · mapas OpenStreetMap. Móvil y Yamaha comparten estado; el TFT se renderiza directamente a 480 × 240, sin captura de pantalla.\n\nDEMO es ficticia. GPS/ETA/guiado deben probarse en condiciones reales. Rutas y búsqueda necesitan conexión; los mapas y lugares incluidos de Asturias se consultan offline. Calcular rutas sigue necesitando Internet.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No envíes información personal/confidencial. Prototipo con máximo 1 petición/s agregado y caché.\n\nNaviLite adaptado de Pillion · PolyForm Noncommercial 1.0.0\nRequired Notice: Copyright 2026 the Pillion authors\n\nFuente online predeterminada incluida: OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors.\n\nAsturias offline: datos © OpenStreetMap contributors, extracto Geofabrik 28/09/2026, licencia ODbL. Límites 42,9–43,75 N / 7,2–4,45 O; zoom 6–14. Tipografía Noto Sans, SIL OFL 1.1."
|
||||
val box = column().apply { setPadding(dp(16), 0, dp(16), 0); addView(label(text + "\n\nFuente activa: ${service?.mapSource()?.attribution ?: ConfiguredMapDataSource.DEFAULT_ATTRIBUTION}\nSi una fuente personalizada no declara atribución, corrige el estilo en Ajustes.", 14f)); addView(button("Diagnóstico del mapa TFT") { showMapDiagnostic() }) }
|
||||
AlertDialog.Builder(this).setTitle("Información y licencias").setView(ScrollView(this).apply { addView(box) }).setPositiveButton("Cerrar", null).setNeutralButton("Licencias") { _, _ -> showLicenses() }.setNegativeButton("Política búsqueda") { _, _ -> openUrl("https://operations.osmfoundation.org/policies/nominatim/") }.show()
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.text.Html
|
||||
import dev.navframe.core.*
|
||||
import kotlinx.coroutines.*
|
||||
import org.maplibre.android.MapLibre
|
||||
import org.maplibre.android.net.ConnectivityReceiver
|
||||
import org.maplibre.android.camera.CameraPosition
|
||||
import org.maplibre.android.geometry.LatLng
|
||||
import org.maplibre.android.maps.Style
|
||||
@@ -32,6 +33,21 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
|
||||
private var closed = false
|
||||
private var stage = MapRenderStage.INITIALIZE
|
||||
private var capturedOnce = false
|
||||
private var lastNetworkState: Boolean? = null
|
||||
internal val networkConnected: Boolean? get() = lastNetworkState
|
||||
private val connectivity = TftMapConnectivity(
|
||||
acquire = { ConnectivityReceiver.instance(this.context).activate() },
|
||||
refresh = {
|
||||
val receiver = ConnectivityReceiver.instance(this.context)
|
||||
receiver.setConnected(null)
|
||||
val connected = receiver.isConnected
|
||||
if (lastNetworkState != connected) {
|
||||
lastNetworkState = connected
|
||||
android.util.Log.d("NavFrame", "TFT_MAP_NETWORK connected=$connected")
|
||||
}
|
||||
},
|
||||
release = { ConnectivityReceiver.instance(this.context).deactivate() },
|
||||
)
|
||||
private fun phase(value: MapRenderStage) { stage = value; reportStage(value) }
|
||||
private data class Raster(val bitmap: Bitmap, val marker: PointF, val attribution: String)
|
||||
override suspend fun render(state: NavigationState) = render(state, NavigationMode.MAP_GPS)
|
||||
@@ -50,6 +66,10 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
|
||||
private suspend fun capture(state: NavigationState): Raster = suspendCancellableCoroutine { continuation ->
|
||||
phase(MapRenderStage.INITIALIZE)
|
||||
MapLibre.getInstance(context)
|
||||
// MapSnapshotter owns FileSource activation, but unlike MapView it does not own
|
||||
// ConnectivityReceiver. Keep network notifications alive when the phone map stops
|
||||
// (including screen off) and initialize from the current network, not a stale event.
|
||||
connectivity.refresh()
|
||||
val position = LatLng(state.position.latitude, state.position.longitude)
|
||||
val camera = TftCameraPolicy().parameters(state)
|
||||
val cameraPosition = CameraPosition.Builder().target(position).zoom(camera.zoom)
|
||||
@@ -117,8 +137,12 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
|
||||
/** Must be called on Main, just as the snapshotter was created there. */
|
||||
fun close() {
|
||||
check(Looper.myLooper() == Looper.getMainLooper())
|
||||
if (closed) return
|
||||
closed = true
|
||||
snapshotter?.cancel()
|
||||
snapshotter = null
|
||||
try { snapshotter?.cancel() }
|
||||
finally {
|
||||
snapshotter = null
|
||||
connectivity.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package dev.navframe.app
|
||||
|
||||
/** An independent SDK network lease: stopping the phone MapView must not stop TFT updates. */
|
||||
internal class TftMapConnectivity(
|
||||
private val acquire: () -> Unit,
|
||||
private val refresh: () -> Unit,
|
||||
private val release: () -> Unit,
|
||||
) : AutoCloseable {
|
||||
private var active = false
|
||||
private var closed = false
|
||||
|
||||
fun refresh() {
|
||||
check(!closed)
|
||||
if (!active) {
|
||||
acquire()
|
||||
active = true
|
||||
}
|
||||
refresh.invoke()
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
if (active) {
|
||||
active = false
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,7 @@ class TftService : Service() {
|
||||
private val mutableVoiceStatus = MutableStateFlow("Voz: preparando motor español")
|
||||
val voiceStatus = mutableVoiceStatus.asStateFlow()
|
||||
private var mapRenderer: MapLibreTftRenderer? = null
|
||||
private var lastMapNetworkConnected: Boolean? = null
|
||||
private val mutableMapDiagnostic = MutableStateFlow("TFT MAP · sin captura")
|
||||
val mapDiagnostic = mutableMapDiagnostic.asStateFlow()
|
||||
private var lastMapFailureDiagnostic = "sin fallo registrado"
|
||||
@@ -693,7 +694,8 @@ class TftService : Service() {
|
||||
val fix = lastGpsFix
|
||||
val accuracy = when { fix == null -> "SIN FIX"; !fix.accuracyMeters.isFinite() -> "DESCONOCIDA"; fix.accuracyMeters <= 5 -> "0–5 m"; fix.accuracyMeters <= 15 -> "6–15 m"; fix.accuracyMeters <= 25 -> "16–25 m"; else -> ">25 m" }
|
||||
val age = if (fix == null) "SIN FIX" else if (SystemClock.elapsedRealtime() - lastGpsElapsed <= 15_000) "RECIENTE" else "CADUCADO"
|
||||
return "NavFrame 0.13.0 · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\n${mutableMapDiagnostic.value}\nÚltimo fallo: $lastMapFailureDiagnostic\nGPS: $age · precisión $accuracy · ${mutableNavigationState.value.navigationStatus}\nTFT: ${mutableState.value} · modo ${mutableMode.value}\nSin coordenadas, consultas, direcciones ni URLs."
|
||||
val network = when (mapRenderer?.networkConnected ?: lastMapNetworkConnected) { true -> "CONECTADA"; false -> "SIN CONEXIÓN"; null -> "SIN COMPROBAR" }
|
||||
return "NavFrame 0.13.1 · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\nRed TFT: $network\n${mutableMapDiagnostic.value}\nÚltimo fallo: $lastMapFailureDiagnostic\nGPS: $age · precisión $accuracy · ${mutableNavigationState.value.navigationStatus}\nTFT: ${mutableState.value} · modo ${mutableMode.value}\nSin coordenadas, consultas, direcciones ni URLs."
|
||||
}
|
||||
fun isRealSessionRequested(): Boolean = realRequested
|
||||
fun isGpsSessionActive(): Boolean = gpsRequested
|
||||
@@ -783,6 +785,7 @@ class TftService : Service() {
|
||||
}
|
||||
}
|
||||
private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, attribution: String, error: MapRenderException): TftFrame {
|
||||
lastMapNetworkConnected = mapRenderer?.networkConnected ?: lastMapNetworkConnected
|
||||
mapRenderer?.close()
|
||||
mapRenderer = null
|
||||
mapFailures = (mapFailures + 1).coerceAtMost(4)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.navframe.app
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class TftMapConnectivityTest {
|
||||
@Test fun phoneStoppingLeavesTftNetworkLeaseActiveAndRefreshesCurrentNetwork() {
|
||||
var sdkReferences = 1 // The visible phone MapView already owns a lease.
|
||||
var actualNetwork = false
|
||||
var observedNetwork: Boolean? = null
|
||||
val lease = TftMapConnectivity({ sdkReferences++ }, { observedNetwork = actualNetwork }, { sdkReferences-- })
|
||||
lease.refresh()
|
||||
assertEquals(false, observedNetwork)
|
||||
sdkReferences-- // Screen turns off: MapView.onStop releases the phone lease.
|
||||
actualNetwork = true // Mobile data recovers while the phone map is stopped.
|
||||
lease.refresh()
|
||||
assertEquals(true, observedNetwork)
|
||||
assertEquals(1, sdkReferences)
|
||||
lease.close()
|
||||
lease.close()
|
||||
assertEquals(0, sdkReferences)
|
||||
}
|
||||
|
||||
@Test fun failedRefreshStillReleasesAcquiredSdkLease() {
|
||||
var references = 0
|
||||
val lease = TftMapConnectivity({ references++ }, { error("network service unavailable") }, { references-- })
|
||||
try { lease.refresh(); fail("Expected refresh failure") } catch (_: IllegalStateException) { }
|
||||
assertEquals(1, references)
|
||||
lease.close()
|
||||
assertEquals(0, references)
|
||||
}
|
||||
|
||||
@Test fun closingUnusedRendererDoesNotReleasePhoneLease() {
|
||||
var references = 1
|
||||
val lease = TftMapConnectivity({ references++ }, { }, { references-- })
|
||||
lease.close()
|
||||
assertEquals(1, references)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package dev.navframe.app
|
||||
|
||||
import android.Manifest
|
||||
import android.location.Location
|
||||
import android.location.LocationManager
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import dev.navframe.core.*
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import org.junit.Assert.*
|
||||
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 java.time.Duration
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class TftServiceRerouteTest {
|
||||
@Test fun reliableFixesMovingBackAlongOldRoadRequestRouteFromCurrentPositionAndResumeGuidance() {
|
||||
val controller = Robolectric.buildService(TftService::class.java).create()
|
||||
val service = controller.get()
|
||||
shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
val manager = service.getSystemService(LocationManager::class.java)
|
||||
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
|
||||
val destination = GeoPoint(0.0, 0.02)
|
||||
val original = RouteResult(listOf(GeoPoint(0.0, 0.0), destination), emptyList(), 2224, 180)
|
||||
val pendingReroute = CompletableDeferred<RouteResult>()
|
||||
val options = RouteOptions(RouteProfile.AVOID_UNPAVED, avoidMotorways = true)
|
||||
var calculations = 0
|
||||
var rerouteOrigin: GeoPoint? = null
|
||||
var rerouteOptions: RouteOptions? = null
|
||||
service.routingEngineFactory = { object : RoutingEngine {
|
||||
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
|
||||
calculations++
|
||||
if (calculations == 1) return original
|
||||
rerouteOrigin = origin
|
||||
rerouteOptions = options
|
||||
return pendingReroute.await()
|
||||
}
|
||||
override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = error("Unexpected routing API")
|
||||
} }
|
||||
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
|
||||
fun tick(millis: Long = 100) { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis)) }
|
||||
fun awaitNavigationStatus(expected: NavigationStatus) {
|
||||
// The initial no-fix frame is encoded on Dispatchers.Default; draining only the
|
||||
// Android looper does not wait for that worker to resume the service loop.
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
while (service.navigationState.value.navigationStatus != expected && System.nanoTime() < deadline) {
|
||||
Thread.sleep(10)
|
||||
tick(10)
|
||||
}
|
||||
assertEquals(service.diagnosticReport() + "\n" + service.routeInfo.value,
|
||||
expected, service.navigationState.value.navigationStatus)
|
||||
}
|
||||
var timestamp = 0L
|
||||
fun position(longitude: Double, accuracy: Float = 5f) {
|
||||
timestamp += 1000
|
||||
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
|
||||
latitude = 0.0; this.longitude = longitude; this.accuracy = accuracy
|
||||
speed = 12f; bearing = 270f; time = timestamp
|
||||
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
|
||||
})
|
||||
tick()
|
||||
val deadline = System.nanoTime() + 3_000_000_000L
|
||||
while (service.navigationState.value.position.longitude != longitude && System.nanoTime() < deadline) {
|
||||
Thread.sleep(10)
|
||||
tick(10)
|
||||
}
|
||||
assertEquals(service.diagnosticReport(), longitude, service.navigationState.value.position.longitude, 0.0)
|
||||
}
|
||||
try {
|
||||
service.setPhoneVisible(true); tick()
|
||||
position(0.01)
|
||||
service.calculateRoute(destination, false, "https://example.test/route", options); tick()
|
||||
service.startRoute(); tick(600)
|
||||
position(0.01)
|
||||
tick(1000)
|
||||
position(0.01)
|
||||
awaitNavigationStatus(NavigationStatus.NAVIGATING)
|
||||
for (longitude in listOf(0.0098, 0.0095, 0.0092, 0.0089, 0.0086, 0.0083, 0.0080)) {
|
||||
tick(1500)
|
||||
position(longitude)
|
||||
}
|
||||
awaitNavigationStatus(NavigationStatus.REROUTING)
|
||||
assertEquals(2, calculations)
|
||||
assertEquals(options, rerouteOptions)
|
||||
assertTrue(requireNotNull(rerouteOrigin).longitude < 0.0095)
|
||||
assertEquals(NavigationStatus.REROUTING, service.navigationState.value.navigationStatus)
|
||||
assertEquals(GeoPoint(0.0, 0.0080), service.navigationState.value.position)
|
||||
val replacement = RouteResult(listOf(requireNotNull(rerouteOrigin), GeoPoint(0.0, 0.007), destination),
|
||||
listOf(Maneuver("Arrive", 0, 4, 2, 2)), 1300, 120)
|
||||
pendingReroute.complete(replacement); tick(1000)
|
||||
position(0.0079)
|
||||
assertSame(replacement, service.navigationState.value.route)
|
||||
assertEquals(NavigationStatus.NAVIGATING, service.navigationState.value.navigationStatus)
|
||||
assertNotNull(service.navigationState.value.nextManeuver)
|
||||
assertEquals(2, calculations)
|
||||
} finally { controller.destroy() }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user