Fix off-route detection and TFT network lifecycle

This commit is contained in:
dasemu committed 2026-10-01 13:57:29 +02:00
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)