mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 15:26:05 +00:00
feat: persist and share TFT map failure history across restarts
This commit is contained in:
1 parent
6fec09f20f
commit
74b222a094
7 files changed
+416
-17
No files matched your search
@@ -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")
|
||||
|
||||
@@ -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<MapDiagnosticEvent> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user