diff --git a/README.md b/README.md index e93f03d..86a6237 100644 --- a/README.md +++ b/README.md @@ -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. +## 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. + ## Documentation - [Documentation index](docs/README.md) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6dafa0b..39cba92 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -2,12 +2,13 @@ plugins { id("com.android.application"); kotlin("android") } android { namespace = "dev.navframe.app" compileSdk = 36 + buildFeatures { buildConfig = true } defaultConfig { applicationId = "dev.navframe.app" minSdk = 26 targetSdk = 35 - versionCode = 17 - versionName = "0.13.1" + versionCode = 18 + versionName = "0.13.2" } testOptions { unitTests.isIncludeAndroidResources = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } diff --git a/app/src/main/java/dev/navframe/app/MainActivity.kt b/app/src/main/java/dev/navframe/app/MainActivity.kt index 83c2038..7ea1b3a 100644 --- a/app/src/main/java/dev/navframe/app/MainActivity.kt +++ b/app/src/main/java/dev/navframe/app/MainActivity.kt @@ -600,14 +600,28 @@ open class MainActivity : Activity() { }.setNegativeButton("Cancelar", null).show() } private fun showInfo() { - 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 text = "NavFrame ${BuildConfig.VERSION_NAME} · 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() } private fun showMapDiagnostic() { - val report = service?.diagnosticReport() ?: "Servicio no disponible" - AlertDialog.Builder(this).setTitle("Diagnóstico TFT").setMessage(report).setPositiveButton("Cerrar", null) - .setNeutralButton("Compartir") { _, _ -> startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, report), "Compartir diagnóstico")) }.show() + scope.launch { + val current = service?.diagnosticReport() ?: "Servicio no disponible · el historial guardado sigue accesible." + val history = withContext(Dispatchers.IO) { MapDiagnosticHistory(applicationContext).report() } + val report = "$current\n\n$history" + AlertDialog.Builder(this@MainActivity).setTitle("Diagnóstico TFT").setMessage(report).setPositiveButton("Cerrar", null) + .setNeutralButton("Compartir") { _, _ -> startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, report), "Compartir diagnóstico")) } + .setNegativeButton("Borrar historial") { _, _ -> + AlertDialog.Builder(this@MainActivity).setTitle("Borrar historial TFT") + .setMessage("Se borrarán los fallos y recuperaciones guardados en este dispositivo.") + .setNegativeButton("Cancelar", null).setPositiveButton("Borrar") { _, _ -> + scope.launch { + val cleared = withContext(Dispatchers.IO) { MapDiagnosticHistory(applicationContext).clear() } + Toast.makeText(this@MainActivity, if (cleared) "Historial borrado" else "No se pudo borrar el historial", Toast.LENGTH_SHORT).show() + } + }.show() + }.show() + } } private fun showLicenses() { val files = arrayOf("PILLION_LICENSE.md", "MAPLIBRE_LICENSE.md", "GSON_LICENSE.md", "OFFLINE_FONT_LICENSE.md", "OFFLINE_DATA_LICENSE.md") diff --git a/app/src/main/java/dev/navframe/app/MapDiagnosticHistory.kt b/app/src/main/java/dev/navframe/app/MapDiagnosticHistory.kt new file mode 100644 index 0000000..97a2da7 --- /dev/null +++ b/app/src/main/java/dev/navframe/app/MapDiagnosticHistory.kt @@ -0,0 +1,133 @@ +package dev.navframe.app + +import android.content.Context +import android.util.AtomicFile +import dev.navframe.core.ConnectionState +import dev.navframe.core.NavigationStatus +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.time.Instant + +internal enum class MapDiagnosticKind { FAILURE, RECOVERED } +internal enum class MapDiagnosticSource { LOCAL, ONLINE } +internal enum class MapDiagnosticNetwork { CONNECTED, DISCONNECTED, UNKNOWN } + +/** Only structured labels and numbers are persisted, never native messages or navigation payloads. */ +internal data class MapDiagnosticEvent( + val kind: MapDiagnosticKind, + val timestampMs: Long, + val source: MapDiagnosticSource, + val network: MapDiagnosticNetwork, + val stage: MapRenderStage, + val failure: MapRenderFailure? = null, + val resource: MapResourceKind = MapResourceKind.UNKNOWN, + val reason: MapFailureReason = MapFailureReason.UNKNOWN, + val httpStatus: Int? = null, + val durationMs: Long, + val attempts: Int, + val retryMs: Long, + val mode: NavigationMode, + val navigation: NavigationStatus, + val connection: ConnectionState, + val androidApi: Int, + val appVersion: String = BuildConfig.VERSION_NAME, +) { + init { + require(timestampMs >= 0 && durationMs >= 0 && retryMs >= 0 && attempts in 1..4) + require(androidApi > 0 && appVersion.matches(Regex("[0-9]+(?:\\.[0-9]+){1,3}"))) + require(httpStatus == null || httpStatus in 400..599) + require((kind == MapDiagnosticKind.FAILURE) == (failure != null)) + } + + fun reportLine(): String = "${Instant.ofEpochMilli(timestampMs)} · ${kind.name} · NavFrame $appVersion · Android $androidApi · MapLibre 13.5.2\n" + + "${source.name} · red ${network.name} · ${failure?.name ?: "OK"}/${stage.name} · ${resource.name}/${reason.name}${httpStatus?.let { "/HTTP_$it" } ?: ""}\n" + + "$durationMs ms · intento $attempts · reintento $retryMs ms · ${mode.name} · ${navigation.name} · TFT ${connection.name}" + + fun toJson(): JSONObject = JSONObject().put("kind", kind.name).put("timestampMs", timestampMs) + .put("source", source.name).put("network", network.name).put("stage", stage.name) + .put("failure", failure?.name ?: JSONObject.NULL).put("resource", resource.name).put("reason", reason.name) + .put("httpStatus", httpStatus ?: JSONObject.NULL).put("durationMs", durationMs).put("attempts", attempts) + .put("retryMs", retryMs).put("mode", mode.name).put("navigation", navigation.name) + .put("connection", connection.name).put("androidApi", androidApi).put("appVersion", appVersion) + + companion object { + fun fromJson(value: JSONObject) = MapDiagnosticEvent( + kind = MapDiagnosticKind.valueOf(value.getString("kind")), timestampMs = value.getLong("timestampMs"), + source = MapDiagnosticSource.valueOf(value.getString("source")), network = MapDiagnosticNetwork.valueOf(value.getString("network")), + stage = MapRenderStage.valueOf(value.getString("stage")), + failure = if (value.isNull("failure")) null else MapRenderFailure.valueOf(value.getString("failure")), + resource = MapResourceKind.valueOf(value.getString("resource")), reason = MapFailureReason.valueOf(value.getString("reason")), + httpStatus = if (value.isNull("httpStatus")) null else value.getInt("httpStatus"), + durationMs = value.getLong("durationMs"), attempts = value.getInt("attempts"), retryMs = value.getLong("retryMs"), + mode = NavigationMode.valueOf(value.getString("mode")), navigation = NavigationStatus.valueOf(value.getString("navigation")), + connection = ConnectionState.valueOf(value.getString("connection")), androidApi = value.getInt("androidApi"), + appVersion = value.getString("appVersion"), + ) + } +} + +/** Bounded, private history; call on IO. AtomicFile syncs completed writes before replacing the old file. */ +internal class MapDiagnosticHistory(private val directory: File) { + constructor(context: Context) : this(context.applicationContext.noBackupFilesDir) + internal val file = File(directory, "tft-map-diagnostics.json") + private val atomic = AtomicFile(file) + + fun record(event: MapDiagnosticEvent): Boolean = synchronized(gate) { + try { + // An unreadable history cannot supply diagnostic text; the next event starts a clean history. + val previous = try { readEvents() } catch (_: Exception) { emptyList() } + val events = (previous + event).takeLast(MAX_EVENTS) + val bytes = JSONArray(events.map { it.toJson() }).toString().toByteArray(Charsets.UTF_8) + check(bytes.size <= MAX_BYTES) + val output = atomic.startWrite() + try { output.write(bytes); output.fd.sync(); atomic.finishWrite(output) } + catch (error: Exception) { atomic.failWrite(output); throw error } + readEvents() == events + } catch (_: Exception) { false } + } + + fun report(): String = synchronized(gate) { + try { + val events = readEvents() + "Historial persistente TFT (${events.size}/$MAX_EVENTS)\n" + + "Fechas UTC · Sin coordenadas, URLs, consultas, rutas ni identificadores Bluetooth.\n\n" + + if (events.isEmpty()) "Sin eventos guardados." else events.joinToString("\n\n") { it.reportLine() } + } catch (_: Exception) { "Historial persistente TFT no disponible: no se pudo leer el archivo." } + } + + fun clear(): Boolean = synchronized(gate) { + try { + atomic.delete() + !file.exists() && !File(file.path + ".bak").exists() && !File(file.path + ".new").exists() + } catch (_: Exception) { false } + } + + private fun readEvents(): List { + val input = try { atomic.openRead() } catch (error: java.io.FileNotFoundException) { + if (!file.exists() && (!directory.exists() || directory.isDirectory)) return emptyList() else throw error + } + val bytes = input.use { + val buffer = ByteArray(MAX_BYTES + 1) + var count = 0 + while (count < buffer.size) { + val read = it.read(buffer, count, buffer.size - count) + if (read < 0) break + count += read + } + if (count > MAX_BYTES) throw IOException("Diagnostic history too large") + buffer.copyOf(count) + } + val array = JSONArray(bytes.toString(Charsets.UTF_8)) + if (array.length() > MAX_EVENTS) throw IOException("Too many diagnostic events") + return (0 until array.length()).map { MapDiagnosticEvent.fromJson(array.getJSONObject(it)) } + } + + companion object { + const val MAX_EVENTS = 100 + const val MAX_BYTES = 128 * 1024 + // Serializes service writes and activity export/clear across separate store instances. + private val gate = Any() + } +} diff --git a/app/src/main/java/dev/navframe/app/TftService.kt b/app/src/main/java/dev/navframe/app/TftService.kt index 78223ce..b2ab1f2 100644 --- a/app/src/main/java/dev/navframe/app/TftService.kt +++ b/app/src/main/java/dev/navframe/app/TftService.kt @@ -72,6 +72,8 @@ class TftService : Service() { private val mutableMapDiagnostic = MutableStateFlow("TFT MAP · sin captura") val mapDiagnostic = mutableMapDiagnostic.asStateFlow() private var lastMapFailureDiagnostic = "sin fallo registrado" + private val mapDiagnosticHistory by lazy { MapDiagnosticHistory(applicationContext) } + private var mapHistoryWriteFailed = false private var mapRenderStarted = 0L private var mapRenderStage = MapRenderStage.INITIALIZE private var mapRetryAt = 0L @@ -695,7 +697,8 @@ class TftService : Service() { 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" 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." + val historyWarning = if (mapHistoryWriteFailed) "\nHistorial persistente: último evento no guardado (TFT_MAP_HISTORY_WRITE_FAILED)." else "" + return "NavFrame ${BuildConfig.VERSION_NAME} · 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.$historyWarning" } fun isRealSessionRequested(): Boolean = realRequested fun isGpsSessionActive(): Boolean = gpsRequested @@ -765,12 +768,14 @@ class TftService : Service() { mapRenderStarted = SystemClock.elapsedRealtime() mapRenderStage = MapRenderStage.INITIALIZE try { - mapRenderOverride?.let { return it(state, mode) } - val current = mapRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution, applicationContext)) { stage -> - mapRenderStage = stage - mutableMapDiagnostic.value = "TFT MAP · ${stage.name} · ${if (source.uri.startsWith("file:")) "LOCAL" else "ONLINE"}" - }.also { mapRenderer = it } - val frame = current.render(state, mode) + val frame = mapRenderOverride?.invoke(state, mode) ?: run { + val current = mapRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution, applicationContext)) { stage -> + mapRenderStage = stage + mutableMapDiagnostic.value = "TFT MAP · ${stage.name} · ${if (source.uri.startsWith("file:")) "LOCAL" else "ONLINE"}" + }.also { mapRenderer = it } + current.render(state, mode) + } + if (mapFailures > 0) recordMapEvent(MapDiagnosticKind.RECOVERED, state, mode, source, retryMs = 0) mutableMapDiagnostic.value = "TFT MAP · OK · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · 480×240" mapFailures = 0 mapRetryAt = 0 @@ -779,12 +784,12 @@ class TftService : Service() { return frame } catch (cancelled: CancellationException) { currentCoroutineContext().ensureActive() // A local map timeout is recoverable; STOP is not. - return mapUnavailable(state, mode, source.attribution, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage)) + return mapUnavailable(state, mode, source, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage)) } catch (error: Exception) { - return mapUnavailable(state, mode, source.attribution, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName))) + return mapUnavailable(state, mode, source, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName))) } } - private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, attribution: String, error: MapRenderException): TftFrame { + private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, source: TileSource, error: MapRenderException): TftFrame { lastMapNetworkConnected = mapRenderer?.networkConnected ?: lastMapNetworkConnected mapRenderer?.close() mapRenderer = null @@ -795,7 +800,28 @@ class TftService : Service() { lastMapFailureDiagnostic = mutableMapDiagnostic.value + " · " + if (mapSource().uri.startsWith("file:")) "LOCAL" else "ONLINE" mutableNavigationInfo.value = "MAPA TFT NO DISPONIBLE · ${error.failure.name} · reintento ${retryMs / 1000} s" android.util.Log.w("NavFrame", "MAP_UNAVAILABLE code=${error.failure.name} stage=${error.stage.name} retryMs=$retryMs") // No URLs, API tokens or coordinates. - return MapFrameComposer().compose(null, null, state, mode, attribution, unavailable = true, failureCode = error.failure.name).also { unavailableMapFrame = it } + recordMapEvent(MapDiagnosticKind.FAILURE, state, mode, source, retryMs, error) + return MapFrameComposer().compose(null, null, state, mode, source.attribution, unavailable = true, failureCode = error.failure.name).also { unavailableMapFrame = it } + } + + private suspend fun recordMapEvent(kind: MapDiagnosticKind, state: NavigationState, mode: NavigationMode, source: TileSource, retryMs: Long, error: MapRenderException? = null) { + val network = mapRenderer?.networkConnected ?: lastMapNetworkConnected + val event = MapDiagnosticEvent( + kind = kind, timestampMs = System.currentTimeMillis(), + source = if (source.uri.startsWith("file:")) MapDiagnosticSource.LOCAL else MapDiagnosticSource.ONLINE, + network = when (network) { true -> MapDiagnosticNetwork.CONNECTED; false -> MapDiagnosticNetwork.DISCONNECTED; null -> MapDiagnosticNetwork.UNKNOWN }, + stage = error?.stage ?: MapRenderStage.COMPOSE, failure = error?.failure, + resource = error?.detail?.resource ?: MapResourceKind.UNKNOWN, reason = error?.detail?.reason ?: MapFailureReason.UNKNOWN, + httpStatus = error?.detail?.httpStatus?.takeIf { it in 400..599 }, + durationMs = (SystemClock.elapsedRealtime() - mapRenderStarted).coerceAtLeast(0), attempts = mapFailures, + retryMs = retryMs, mode = mode, navigation = state.navigationStatus, connection = mutableState.value, + androidApi = Build.VERSION.SDK_INT, + ) + val saved = withContext(Dispatchers.IO) { + try { mapDiagnosticHistory.record(event) } catch (_: Exception) { false } + } + mapHistoryWriteFailed = !saved + if (!saved) android.util.Log.w("NavFrame", "TFT_MAP_HISTORY_WRITE_FAILED") } private fun updateNotification(text: String) { diff --git a/app/src/test/java/dev/navframe/app/MapDiagnosticHistoryTest.kt b/app/src/test/java/dev/navframe/app/MapDiagnosticHistoryTest.kt new file mode 100644 index 0000000..5901d67 --- /dev/null +++ b/app/src/test/java/dev/navframe/app/MapDiagnosticHistoryTest.kt @@ -0,0 +1,190 @@ +package dev.navframe.app + +import android.app.AlertDialog +import android.content.Intent +import android.os.Bundle +import android.os.Looper +import android.util.AtomicFile +import dev.navframe.core.* +import org.junit.After +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.ShadowAlertDialog +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +@LooperMode(LooperMode.Mode.PAUSED) +class MapDiagnosticHistoryTest { + private val context get() = RuntimeEnvironment.getApplication() + private val store get() = MapDiagnosticHistory(context) + class PhoneWithoutGpu : MainActivity() { override fun createPhoneMap(savedState: Bundle?): PhoneMapView? = null } + + @Before fun cleanHistory() { assertTrue(store.clear()) } + @After fun removeHistory() { store.file.deleteRecursively(); java.io.File(store.file.path + ".new").deleteRecursively(); store.clear() } + + private fun event(timestamp: Long = 1_792_000_000_000, kind: MapDiagnosticKind = MapDiagnosticKind.FAILURE) = MapDiagnosticEvent( + kind = kind, timestampMs = timestamp, source = MapDiagnosticSource.LOCAL, + network = MapDiagnosticNetwork.DISCONNECTED, stage = MapRenderStage.STYLE_READY, + failure = if (kind == MapDiagnosticKind.FAILURE) MapRenderFailure.TIMEOUT else null, + durationMs = 10_001, attempts = 1, retryMs = if (kind == MapDiagnosticKind.FAILURE) 2_000 else 0, + mode = NavigationMode.MAP_GPS, navigation = NavigationStatus.NAVIGATING, + connection = ConnectionState.CONNECTED, androidApi = 34, + ) + + @Test fun committedFailuresAndRecoverySurviveNewStoreInstancesWithoutNativeMessages() { + val raw = "Failed to load glyph https://private.example/fonts?token=secret HTTP status 403 at 43.361234,-5.856789" + val detail = mapErrorDetail(raw) + val failure = event().copy(failure = classifyMapRenderFailure(raw), resource = detail.resource, reason = detail.reason, httpStatus = detail.httpStatus) + assertTrue(store.record(failure)) + assertTrue(store.record(event(kind = MapDiagnosticKind.RECOVERED))) + val reopened = MapDiagnosticHistory(context) + assertTrue(reopened.file.canonicalPath.startsWith(context.noBackupFilesDir.canonicalPath + "/")) + val report = reopened.report() + assertTrue(report.contains("(2/100)")) + assertTrue(report.contains("NETWORK/STYLE_READY")) + assertTrue(report.contains("GLYPH/FORBIDDEN/HTTP_403")) + assertTrue(report.contains("RECOVERED")) + assertTrue(report.contains("LOCAL · red DISCONNECTED")) + for (text in listOf("secret", "private.example", "43.361234", "-5.856789", "https://")) { + assertFalse(report.contains(text)) + assertFalse(reopened.file.readText().contains(text)) + } + } + + @Test fun retentionKeepsNewestHundredEventsInOrderAndExplicitClearPersists() { + for (index in 0..104) assertTrue(store.record(event(timestamp = index.toLong()))) + val report = MapDiagnosticHistory(context).report() + assertTrue(report.contains("(100/100)")) + assertFalse(report.contains("1970-01-01T00:00:00.004Z")) + assertTrue(report.indexOf("1970-01-01T00:00:00.005Z") < report.indexOf("1970-01-01T00:00:00.104Z")) + assertTrue(store.file.length() <= MapDiagnosticHistory.MAX_BYTES) + assertTrue(store.clear()) + assertTrue(MapDiagnosticHistory(context).report().contains("Sin eventos guardados")) + assertFalse(store.file.exists()) + } + + @Test fun interruptedAtomicReplacementLeavesTheLastCommittedHistoryReadable() { + assertTrue(store.record(event())) + val previous = store.report() + val interrupted = AtomicFile(store.file).startWrite() + interrupted.write("incomplete private URL https://private.example".toByteArray()) + interrupted.fd.sync() + interrupted.close() // Simulate process loss before finishWrite; do not commit the replacement. + assertEquals(previous, MapDiagnosticHistory(context).report()) + } + + @Test fun corruptAndOversizedFilesAreNotExportedAndNextEventRepairsTheHistory() { + store.file.parentFile!!.mkdirs() + store.file.writeText("private URL https://private.example?token=secret") + assertTrue(store.report().contains("no se pudo leer")) + assertFalse(store.report().contains("secret")) + assertTrue(store.record(event())) + assertTrue(store.report().contains("(1/100)")) + store.file.writeBytes(ByteArray(MapDiagnosticHistory.MAX_BYTES + 1) { 'x'.code.toByte() }) + assertTrue(store.report().contains("no se pudo leer")) + assertTrue(store.record(event())) + assertTrue(store.report().contains("(1/100)")) + } + + @Test fun unavailableStorageReturnsFailureWithoutExportingExceptions() { + store.file.writeText("not a directory") + val blocked = MapDiagnosticHistory(store.file) + assertFalse(blocked.record(event())) + assertTrue(blocked.report().contains("no se pudo leer")) + assertFalse(blocked.report().contains(context.noBackupFilesDir.path)) + } + + @Test fun servicePersistsFailureThenRecoveryBeforeRecreation() { + val controller = Robolectric.buildService(TftService::class.java).create() + val service = controller.get() + var renders = 0 + service.mapRenderOverride = { _, _ -> + if (renders++ == 0) throw MapRenderException(MapRenderFailure.GPU, MapRenderStage.STYLE_READY, MapErrorDetail(reason = MapFailureReason.EGL)) + TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) + } + try { + service.startDemo(true) + await { store.report().contains("RECOVERED") } + val report = store.report() + assertTrue(report.contains("FAILURE")) + assertTrue(report.contains("GPU/STYLE_READY")) + assertTrue(report.contains("UNKNOWN/EGL")) + assertTrue(report.contains("RECOVERED")) + assertTrue(report.indexOf("FAILURE") < report.indexOf("RECOVERED")) + } finally { controller.destroy() } + val recreated = Robolectric.buildService(TftService::class.java).create() + try { + assertTrue(MapDiagnosticHistory(recreated.get()).report().contains("GPU/STYLE_READY")) + } finally { recreated.destroy() } + } + + @Test fun serviceStillPublishesErrorFrameAndReportsWhenHistoryCannotBeWritten() { + assertTrue(store.record(event())) + val blockedReplacement = java.io.File(store.file.path + ".new") + assertTrue(blockedReplacement.mkdir()) + java.io.File(blockedReplacement, "blocker").writeText("not removable as a file") + val controller = Robolectric.buildService(TftService::class.java).create() + val service = controller.get() + service.mapRenderOverride = { _, _ -> throw MapRenderException(MapRenderFailure.GPU, MapRenderStage.STYLE_READY) } + try { + service.startDemo(true) + await { service.lastFrame.value != null } + assertTrue(service.diagnosticReport().contains("TFT_MAP_HISTORY_WRITE_FAILED")) + assertEquals(NavigationMode.MAP_DEMO, service.navigationMode.value) + assertTrue(store.report().contains("(1/100)")) + } finally { controller.destroy(); blockedReplacement.deleteRecursively() } + } + + @Test fun diagnosisWithoutBoundServiceSharesSavedHistoryAndClearRequiresConfirmation() { + assertTrue(store.record(event())) + val controller = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create() + val activity = controller.get() + fun open() { + MainActivity::class.java.getDeclaredMethod("showMapDiagnostic").apply { isAccessible = true }.invoke(activity) + await { ShadowAlertDialog.getLatestAlertDialog()?.isShowing == true } + } + try { + open() + val dialog = ShadowAlertDialog.getLatestAlertDialog() + assertTrue(shadowOf(dialog).message.toString().contains("TIMEOUT/STYLE_READY")) + dialog.getButton(AlertDialog.BUTTON_NEUTRAL).performClick() + shadowOf(Looper.getMainLooper()).idle() + val chooser = shadowOf(activity).nextStartedActivity + assertEquals(Intent.ACTION_CHOOSER, chooser.action) + @Suppress("DEPRECATION") + val share = chooser.getParcelableExtra(Intent.EXTRA_INTENT)!! + assertEquals(Intent.ACTION_SEND, share.action) + assertTrue(share.getStringExtra(Intent.EXTRA_TEXT)!!.contains("TIMEOUT/STYLE_READY")) + open() + ShadowAlertDialog.getLatestAlertDialog().getButton(AlertDialog.BUTTON_NEGATIVE).performClick() + shadowOf(Looper.getMainLooper()).idle() + ShadowAlertDialog.getLatestAlertDialog().getButton(AlertDialog.BUTTON_NEGATIVE).performClick() + shadowOf(Looper.getMainLooper()).idle() + assertTrue(store.report().contains("(1/100)")) + open() + ShadowAlertDialog.getLatestAlertDialog().getButton(AlertDialog.BUTTON_NEGATIVE).performClick() + shadowOf(Looper.getMainLooper()).idle() + ShadowAlertDialog.getLatestAlertDialog().getButton(AlertDialog.BUTTON_POSITIVE).performClick() + await { store.report().contains("Sin eventos guardados") } + } finally { controller.destroy() } + } + + private fun await(condition: () -> Boolean) { + val deadline = System.nanoTime() + 5_000_000_000 + do { + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) + if (condition()) return + Thread.sleep(10) + } while (System.nanoTime() < deadline) + fail("Timed out waiting for diagnostic IO/UI completion") + } +} diff --git a/docs/TFT_DIAGNOSTICS.md b/docs/TFT_DIAGNOSTICS.md new file mode 100644 index 0000000..1363954 --- /dev/null +++ b/docs/TFT_DIAGNOSTICS.md @@ -0,0 +1,31 @@ +# Persistent TFT map diagnostics + +Starting with NavFrame 0.13.2, map-render failures and the first successful render after a failure are saved automatically on the phone. The history does not depend on Logcat or on keeping the service alive. Completed writes are retained across app/service restarts and a phone reboot, including a shutdown caused by an empty battery. + +## Export after an incident + +When stationary, open **Menu → Information and licenses → TFT map diagnosis → Share**. In the Spanish UI this is **☰ → Información y licencias → Diagnóstico del mapa TFT → Compartir**. + +The shared text includes the current service diagnostic, when available, and the saved history. History remains available when no service is bound. Save it before reinstalling the app or clearing app data. **Clear history** removes saved events after confirmation; it does not stop navigation or erase the current in-memory service diagnostic. + +## Recorded information + +Each event contains its UTC timestamp, app version, Android API level, MapLibre version, failure/recovery type, failure category and render stage, classified resource/reason and HTTP error status if available, render duration, retry delay/backoff attempt, active source type (`LOCAL` or `ONLINE`), observed connectivity, navigation mode/status, and TFT connection state. + +The backoff attempt is capped at four, like the renderer's existing retry policy. Repeated failures continue to create separate timestamped records after that limit. Only the first successful render following failures creates a recovery record; normal successful frames are not logged. + +Raw SDK messages, stack traces, URLs, tokens, coordinates, route geometry, destinations, search text, and Bluetooth identifiers are excluded. The history contains fixed labels and numbers, not a copy of Logcat. Network state is diagnostic context: a disconnected network does not itself explain a failure of a selected local map. + +## Storage and limits + +The history is a private app file named `tft-map-diagnostics.json` in Android's `noBackupFilesDir`. No storage permission is required; the app does not upload it automatically, and it is excluded from backup/device transfer. The file retains the latest 100 failure/recovery events and is bounded at 128 KiB. Older events are discarded when the limit is reached. + +File operations run on an IO dispatcher. Writes are synced and replaced atomically, so an interrupted replacement preserves the previous completed history. A failure that occurs while a shutdown interrupts its write may not be retained. Clearing app data or uninstalling NavFrame deletes the history. + +If reading fails, the diagnostic dialog reports that the history is unavailable and never exports the unreadable file as text. The next record replaces an unreadable history with a valid event. If storage cannot be written, navigation/error-frame handling continues; the current service diagnostic and Logcat report `TFT_MAP_HISTORY_WRITE_FAILED`. + +## What this cannot recover + +Events from before installing 0.13.2 cannot be reconstructed. This is a record of failures handled by NavFrame's TFT rendering path, not a system-wide crash recorder: abrupt native process crashes and power loss before a failure is recorded may leave no new event. A recovery record means image generation succeeded, not that delivery to the physical TFT was verified. The history helps investigate incidents; it does not establish their root cause by itself. + +Tests cover reopening persisted events, retention, interrupted replacement, malformed/oversized input, unavailable storage, service failure followed by recovery/recreation, and sharing/clearing saved history without a bound service. Physical power-loss behavior and MapLibre OpenGL/TFT rendering still need device validation.