mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 15:26:05 +00:00
feat: road-route imported GPX stops and widen the TFT camera
- Route points, waypoints and sparse tracks are joined along roads with multi-location Valhalla requests (chunks of 20, merged legs); failures offer a retry instead of straight lines. - TFT camera: lower zoom, 45 degree pitch and rider lower in the frame; rider zoom offset from Settings and NaviLite zoom requests 51/52. - Online map failures fall back to an installed offline pack for 30 s. - Production-facing copy cleanup and docs; version 0.14.8 (25). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
694fefd98b
commit
b7bf2c2b43
22 files changed
+453
-116
No files matched your search
@@ -15,8 +15,8 @@ android {
|
||||
applicationId = "dev.navframe.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionName = "0.14.7"
|
||||
versionCode = 24
|
||||
versionName = "0.14.8"
|
||||
versionCode = 25
|
||||
}
|
||||
if (hasReleaseSigning) {
|
||||
signingConfigs.create("production") {
|
||||
|
||||
@@ -149,9 +149,9 @@ open class MainActivity : Activity() {
|
||||
})
|
||||
guidance = label("", 20f); progress = label("", 14f); routeInfo = label("", 14f)
|
||||
permissionInfo = label("", 12f)
|
||||
origin = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("GPS real", "DEMO · posición simulada")) }
|
||||
origin = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("Desde mi ubicación", "Simulación (sin GPS)")) }
|
||||
profileButton = button(profileLabel()) { chooseProfile() }
|
||||
stopButton = button("STOP · Detener ruta") { positionWait?.cancel(); service?.stopRoute(); routeDialog?.dismiss(); hint.text = ""; stopButton.visibility = View.GONE }.apply { visibility = View.GONE; setTextColor(Color.WHITE); background = rounded(0xEEA83939.toInt(), 18) }
|
||||
stopButton = button("Detener ruta") { positionWait?.cancel(); service?.stopRoute(); routeDialog?.dismiss(); hint.text = ""; stopButton.visibility = View.GONE }.apply { visibility = View.GONE; setTextColor(Color.WHITE); background = rounded(0xEEA83939.toInt(), 18) }
|
||||
root.addView(stopButton, FrameLayout.LayoutParams(-1, dp(56), android.view.Gravity.BOTTOM).apply { setMargins(dp(16), 0, dp(16), dp(28)) })
|
||||
root.addView(button("◎") { withPermissions(Action.POSITION) }.apply { contentDescription = "Centrar en mi posición y seguir el mapa"; background = rounded(0xFF50D5B6.toInt(), 28); setTextColor(0xFF0D191C.toInt()); elevation = dp(8).toFloat() }, FrameLayout.LayoutParams(dp(56), dp(56), android.view.Gravity.BOTTOM or android.view.Gravity.END).apply { setMargins(0, 0, dp(16), dp(104)) })
|
||||
positionNotice = label("", 13f).apply {
|
||||
@@ -214,8 +214,8 @@ open class MainActivity : Activity() {
|
||||
NavigationStatus.ARRIVED -> "Has llegado al destino"
|
||||
NavigationStatus.ROUTE_PREVIEW -> "Vista previa de ruta"
|
||||
NavigationStatus.IDLE -> "Listo para navegar"
|
||||
else -> state.nextManeuver?.instruction ?: if (state.route == null) "GPS listo · elige un destino" else if (state.route?.imported == true) "Sigue el trazado GPX · sin giros anunciados" else "Continúa por la ruta"
|
||||
}.let { if (demo) "DEMO · $it" else it }
|
||||
else -> state.nextManeuver?.instruction ?: if (state.route == null) "GPS listo · elige un destino" else if (state.route?.let { it.imported && it.maneuvers.isEmpty() } == true) "Sigue el trazado GPX" else "Continúa por la ruta"
|
||||
}.let { if (demo) "Simulación · $it" else it }
|
||||
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)) } ?: ""
|
||||
@@ -233,7 +233,7 @@ open class MainActivity : Activity() {
|
||||
if (needsLocation) required += Manifest.permission.ACCESS_FINE_LOCATION
|
||||
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
val blocked = missing.any { permissionsPreferences.getBoolean(it, false) && !shouldShowRequestPermissionRationale(it) }
|
||||
if (blocked) { AlertDialog.Builder(this).setTitle("Permiso necesario").setMessage("Activa ubicación precisa o dispositivos cercanos para esta función. Puedes seguir explorando mapas y usando la demo.").setPositiveButton("Abrir ajustes") { _, _ -> openAppSettings() }.setNegativeButton("Cancelar", null).show(); return }
|
||||
if (blocked) { AlertDialog.Builder(this).setTitle("Permiso necesario").setMessage("Activa ubicación precisa o dispositivos cercanos para esta función. Puedes seguir explorando mapas y usando la simulación.").setPositiveButton("Abrir ajustes") { _, _ -> openAppSettings() }.setNegativeButton("Cancelar", null).show(); return }
|
||||
val request = missing.toMutableList()
|
||||
if (missing.contains(Manifest.permission.ACCESS_FINE_LOCATION)) request += Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
if ((action == Action.CONNECT || action == Action.CHANGE_CONNECT || ((action == Action.ROUTE || action == Action.IMPORT_ROUTE) && service?.routeUsesGps() == true)) && Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED && !permissionsPreferences.getBoolean(Manifest.permission.POST_NOTIFICATIONS, false)) request += Manifest.permission.POST_NOTIFICATIONS
|
||||
@@ -252,7 +252,7 @@ open class MainActivity : Activity() {
|
||||
refreshPermissions()
|
||||
val needsFine = action == Action.IMPORT_ROUTE || action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
|
||||
val allowed = (!needsFine || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && ((action != Action.CONNECT && action != Action.CHANGE_CONNECT) || Build.VERSION.SDK_INT < 31 || checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED)
|
||||
if (action != null && allowed) perform(action) else hint.text = "Permiso denegado · puedes usar la demo. Toca el aviso de permisos para abrir ajustes."
|
||||
if (action != null && allowed) perform(action) else hint.text = "Permiso denegado · puedes usar la simulación o concederlo en los ajustes de la app."
|
||||
}
|
||||
private fun refreshPermissions() {
|
||||
if (!::permissionInfo.isInitialized) return
|
||||
@@ -356,12 +356,11 @@ open class MainActivity : Activity() {
|
||||
ensureActive()
|
||||
val current = service ?: run { hint.text = "Servicio no disponible · vuelve a cargar el GPX"; return@launch }
|
||||
cancelSearch(); routeDialog?.dismiss()
|
||||
current.prepareImportedRoute(imported)
|
||||
lastImportedRoute = imported
|
||||
destination = null; destinationName = ""
|
||||
hint.text = "Ruta GPX cargada"
|
||||
hint.text = ""
|
||||
showImportedRouteSheet(imported.name)
|
||||
withPermissions(Action.IMPORT_ROUTE)
|
||||
prepareImported(current, imported)
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (error: Exception) {
|
||||
// Parser messages contain no coordinates, file paths or document contents.
|
||||
@@ -369,20 +368,24 @@ open class MainActivity : Activity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Road-routes GPX stops first; navigation starts automatically once a route is ready. */
|
||||
private fun prepareImported(current: TftService, imported: ImportedRoute) {
|
||||
current.calculateImportedStops(imported) { if (lastImportedRoute === imported && routeDialog?.isShowing == true) withPermissions(Action.IMPORT_ROUTE) }
|
||||
}
|
||||
private fun showImportedRouteSheet(name: String?) {
|
||||
routeDialog?.dismiss()
|
||||
(routeInfo.parent as? android.view.ViewGroup)?.removeView(routeInfo)
|
||||
val box = column().apply { setPadding(dp(20), dp(16), dp(20), dp(16)) }
|
||||
box.addView(label(name ?: "Ruta GPX", 20f))
|
||||
box.addView(routeInfo)
|
||||
lastImportedRoute?.takeIf { !it.isTrack && it.route.geometry.size in 2..50 }?.let { imported ->
|
||||
box.addView(button("Calcular por carreteras · evitar autopistas") {
|
||||
service?.calculateImportedStops(imported)
|
||||
})
|
||||
}
|
||||
routeLoading = ProgressBar(this).apply { visibility = View.GONE }
|
||||
box.addView(routeLoading)
|
||||
retryRouteButton = null
|
||||
retryRouteButton = button("Reintentar") {
|
||||
val current = service ?: return@button
|
||||
// A GPS-wait timeout keeps the calculated route: only restart navigation.
|
||||
if (current.hasPreparedRoute()) withPermissions(Action.IMPORT_ROUTE) else lastImportedRoute?.let { prepareImported(current, it) }
|
||||
}.apply { visibility = View.GONE }
|
||||
box.addView(retryRouteButton)
|
||||
startButton = button("Iniciar navegación") { withPermissions(Action.IMPORT_ROUTE) }
|
||||
box.addView(startButton)
|
||||
val dialog = AlertDialog.Builder(this).setView(box).setNegativeButton("Cerrar", null).create()
|
||||
@@ -620,6 +623,16 @@ open class MainActivity : Activity() {
|
||||
try { startActivity(Intent("com.android.settings.TTS_SETTINGS")) }
|
||||
catch (_: ActivityNotFoundException) { openAppSettings() }
|
||||
})
|
||||
content.addView(label("Zoom del mapa en la pantalla de la moto", 14f))
|
||||
val zoomLabel = label("", 13f)
|
||||
fun showZoom(message: String = "") { zoomLabel.text = message.ifEmpty { if (current.tftZoomOffset == 0.0) "Automático según velocidad" else "Automático %+.1f".format(java.util.Locale("es", "ES"), current.tftZoomOffset) } }
|
||||
content.addView(row().apply {
|
||||
addView(button("−") { current.adjustTftZoom(-1); showZoom(current.tftZoomInfo.value.takeIf { it.endsWith("mínimo") }.orEmpty()) }.apply { contentDescription = "Alejar mapa TFT" }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
addView(button("Auto") { current.adjustTftZoom(-(current.tftZoomOffset / TftCameraPolicy.ZOOM_STEP).toInt()); showZoom() }.apply { contentDescription = "Restablecer zoom TFT" }, LinearLayout.LayoutParams(0, dp(48), 1f).apply { setMargins(dp(8), 0, dp(8), 0) })
|
||||
addView(button("+") { current.adjustTftZoom(1); showZoom(current.tftZoomInfo.value.takeIf { it.endsWith("máximo") }.orEmpty()) }.apply { contentDescription = "Acercar mapa TFT" }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
})
|
||||
showZoom()
|
||||
content.addView(zoomLabel)
|
||||
val routeEndpoint = entry("Servidor Valhalla HTTPS", current.routingEndpoint())
|
||||
val geocoderEndpoint = entry("Servidor búsqueda HTTPS", getSharedPreferences("geocoder", MODE_PRIVATE).getString("endpoint", NominatimGeocoder.DEFAULT_ENDPOINT) ?: NominatimGeocoder.DEFAULT_ENDPOINT)
|
||||
val catalogPreferences = getSharedPreferences("regional_downloads", MODE_PRIVATE)
|
||||
@@ -685,7 +698,7 @@ open class MainActivity : Activity() {
|
||||
}.setNegativeButton("Cancelar", null).show()
|
||||
}
|
||||
private fun showInfo() {
|
||||
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 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\nLa simulación usa posiciones ficticias. Calcular rutas y buscar direcciones necesita conexión; los mapas y lugares incluidos de Asturias funcionan sin conexión.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No escribas información personal o confidencial. Las peticiones se limitan a 1 por segundo y se guardan en 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()
|
||||
}
|
||||
@@ -746,6 +759,7 @@ open class MainActivity : Activity() {
|
||||
check(selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)))
|
||||
rebuildPhoneMap() // Release native readers before removing an active private archive.
|
||||
}
|
||||
service?.releaseMapFallback()
|
||||
offlineManager.delete(pack.id)
|
||||
hint.text = "Paquete offline borrado"
|
||||
} catch (_: Exception) { hint.text = "No se pudo borrar el paquete" }
|
||||
@@ -768,6 +782,7 @@ open class MainActivity : Activity() {
|
||||
check(selectMapSource(TileSource("asset://map/tft-style.json", ConfiguredMapDataSource.DEFAULT_ATTRIBUTION)))
|
||||
rebuildPhoneMap()
|
||||
}
|
||||
service?.releaseMapFallback()
|
||||
regionalManager.delete(region.folderId)
|
||||
displayedPlaces = emptyList(); phoneMap?.setPlaces(emptyList())
|
||||
hint.text = "Región borrada"
|
||||
|
||||
@@ -61,7 +61,7 @@ class MapFrameComposer {
|
||||
if (warning != null) {
|
||||
text(fitted(warning, 16f, 460f), 10f, 39f, 16f, if (state.navigationStatus == NavigationStatus.ARRIVED) accent else Color.YELLOW)
|
||||
} else {
|
||||
val imported = state.route?.imported == true
|
||||
val imported = state.route?.let { it.imported && it.maneuvers.isEmpty() } == true
|
||||
val maneuver = state.nextManeuver
|
||||
val direction = maneuverDirection(maneuver?.type).name
|
||||
canvas.save()
|
||||
@@ -85,7 +85,7 @@ class MapFrameComposer {
|
||||
}
|
||||
} else if (preview) {
|
||||
val route = requireNotNull(state.route)
|
||||
val summary = if (route.imported) "GPX · %.1f km · seguir trazado".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0) else "PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60)
|
||||
val summary = if (route.imported && route.maneuvers.isEmpty()) "GPX · %.1f km · seguir trazado".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0) else "PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60)
|
||||
text(fitted(summary, 13f, 460f), 8f, 31f, 13f)
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/** The service owns this dedicated 480×240 GPU snapshot target, not a phone MapView or Activity. */
|
||||
class MapLibreTftRenderer(context: Context, private val source: MapDataSource, private val reportStage: (MapRenderStage) -> Unit = {}) : TftRenderer {
|
||||
class MapLibreTftRenderer(context: Context, private val source: MapDataSource, private val zoomOffset: () -> Double = { 0.0 }, private val reportStage: (MapRenderStage) -> Unit = {}) : TftRenderer {
|
||||
private val context = context.applicationContext
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val composer = MapFrameComposer()
|
||||
@@ -71,9 +71,11 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
|
||||
// (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 camera = TftCameraPolicy(zoomOffset()).parameters(state)
|
||||
// Top padding moves the focal point (the rider) down to riderAnchorY of the frame height.
|
||||
val cameraPosition = CameraPosition.Builder().target(position).zoom(camera.zoom)
|
||||
.bearing(camera.bearingDegrees.toDouble()).padding(0.0, 50.0, 0.0, 0.0).build()
|
||||
.bearing(camera.bearingDegrees.toDouble()).tilt(camera.pitchDegrees)
|
||||
.padding(0.0, ((2 * camera.riderAnchorY - 1) * 240.0).coerceAtLeast(0.0), 0.0, 0.0).build()
|
||||
val current = snapshotter ?: run {
|
||||
val tile = source.tileSource()
|
||||
val builder = if (tile.uri.startsWith("asset://")) Style.Builder().fromJson(context.assets.open(tile.uri.removePrefix("asset://")).bufferedReader().use { it.readText() })
|
||||
|
||||
@@ -12,7 +12,7 @@ import java.util.concurrent.atomic.AtomicReference
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/** Button-triggered prototype search only: no autocomplete, GPS, viewbox or persisted query history. */
|
||||
/** Button-triggered search only: no autocomplete, GPS, viewbox or persisted query history. */
|
||||
class NominatimGeocoder(
|
||||
private val endpoint: String = DEFAULT_ENDPOINT,
|
||||
private val openConnection: (String) -> HttpURLConnection = { URI(it).toURL().openConnection() as HttpURLConnection },
|
||||
@@ -54,7 +54,7 @@ class NominatimGeocoder(
|
||||
http.requestMethod = "GET"
|
||||
http.connectTimeout = 8_000; http.readTimeout = 12_000
|
||||
http.instanceFollowRedirects = false
|
||||
http.setRequestProperty("User-Agent", "NavFrame/0.6 (Android navigation prototype)")
|
||||
http.setRequestProperty("User-Agent", "NavFrame/${BuildConfig.VERSION_NAME} (Android navigation)")
|
||||
http.setRequestProperty("Accept", "application/json")
|
||||
val status = http.responseCode
|
||||
if (status != 200) {
|
||||
|
||||
@@ -19,7 +19,7 @@ class TftService : Service() {
|
||||
private var routeJob: Job? = null
|
||||
private var routeGeneration = 0L
|
||||
private var preparedGeneration = 0L
|
||||
internal var routingEngineFactory: (String) -> RoutingEngine = { ValhallaRoutingEngine(it, "dev.navframe.app/0.6-prototype", language = { NavigationVoicePreferences.language(this).tag }) }
|
||||
internal var routingEngineFactory: (String) -> RoutingEngine = { ValhallaRoutingEngine(it, "dev.navframe.app/${BuildConfig.VERSION_NAME}", language = { NavigationVoicePreferences.language(this).tag }) }
|
||||
internal var mapRenderOverride: (suspend (NavigationState, NavigationMode) -> TftFrame)? = null
|
||||
private var routePlan: RoutePlan? = null
|
||||
private var preparedDestinationDirty = false
|
||||
@@ -52,7 +52,7 @@ class TftService : Service() {
|
||||
private var latestNavigationState = NavigationState()
|
||||
set(value) {
|
||||
field = value; mutableNavigationState.value = value
|
||||
if (shownRoute?.demo == false && !routePreview && value.route?.imported != true) voice?.update(value)
|
||||
if (shownRoute?.demo == false && !routePreview && value.route?.let { !it.imported || it.maneuvers.isNotEmpty() } != false) voice?.update(value)
|
||||
else voice?.reset()
|
||||
}
|
||||
private var voice: NavigationVoiceController? = null
|
||||
@@ -77,6 +77,19 @@ class TftService : Service() {
|
||||
private var mapRenderStarted = 0L
|
||||
private var mapRenderStage = MapRenderStage.INITIALIZE
|
||||
private var mapRetryAt = 0L
|
||||
/** Rider zoom adjustment on top of the speed-based TFT camera; persisted across sessions. */
|
||||
var tftZoomOffset: Double = 0.0
|
||||
private set
|
||||
private var forceMapRedraw = false
|
||||
/** Installed offline map used for the TFT while the online source keeps failing. */
|
||||
private var fallbackRenderer: MapLibreTftRenderer? = null
|
||||
private var fallbackUri: String? = null
|
||||
private var onlineRetryAt = 0L
|
||||
private var offlineSources: List<Pair<RegionalBounds, TileSource>> = emptyList()
|
||||
private var offlineSourcesAt = 0L
|
||||
private val mutableTftZoomInfo = MutableStateFlow("")
|
||||
val tftZoomInfo = mutableTftZoomInfo.asStateFlow()
|
||||
private var dashboardRequests = sortedMapOf<Int, Int>()
|
||||
private var mapFailures = 0
|
||||
private var unavailableMapFrame: TftFrame? = null
|
||||
private val mutableMode = MutableStateFlow(NavigationMode.IDLE)
|
||||
@@ -91,7 +104,7 @@ class TftService : Service() {
|
||||
val connectionState = mutableState.asStateFlow()
|
||||
private val mutableFrame = MutableStateFlow<TftFrame?>(null)
|
||||
val lastFrame = mutableFrame.asStateFlow()
|
||||
private val mutableMessage = MutableStateFlow("Listo para prueba TFT")
|
||||
private val mutableMessage = MutableStateFlow("Listo")
|
||||
val message = mutableMessage.asStateFlow()
|
||||
private val mutableInterval = MutableStateFlow(1_000L)
|
||||
val intervalMs = mutableInterval.asStateFlow()
|
||||
@@ -100,6 +113,7 @@ class TftService : Service() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
mutableInterval.value = getSharedPreferences("tft", MODE_PRIVATE).getLong("interval_ms", 1_000).coerceIn(500, 3_000)
|
||||
tftZoomOffset = TftCameraPolicy.stepOffset(getSharedPreferences("tft_camera", MODE_PRIVATE).getFloat("zoom_offset", 0f).toDouble(), 0)
|
||||
voice = NavigationVoiceController(this).also { controller ->
|
||||
mutableVoiceEnabled.value = controller.enabled.value
|
||||
scope.launch { controller.status.collect { mutableVoiceStatus.value = it } }
|
||||
@@ -223,7 +237,7 @@ class TftService : Service() {
|
||||
while (isActive) { delay(30_000); lock.acquire(120_000) }
|
||||
}
|
||||
TftSessionRunner(
|
||||
transportFactory = { NaviLiteTransport(applicationContext, address) },
|
||||
transportFactory = { NaviLiteTransport(applicationContext, address, ::onDashboardRequest) },
|
||||
latestFrame = { requireNotNull(mutableFrame.value) },
|
||||
policy = { TftSessionPolicy(effectiveInterval()) },
|
||||
clockMs = { SystemClock.elapsedRealtime() },
|
||||
@@ -369,7 +383,7 @@ class TftService : Service() {
|
||||
else DemoNavigation.stateAt(now - start, startEpoch)
|
||||
latestNavigationState = if (map) withRoute(simulated, true) else simulated
|
||||
scheduler.offer(latestNavigationState)
|
||||
val ready = scheduler.takeIfDue(now) ?: if (map && mapRetryAt > 0 && now >= mapRetryAt) latestNavigationState else null
|
||||
val ready = scheduler.takeIfDue(now) ?: if (map && ((mapRetryAt > 0 && now >= mapRetryAt) || consumeForcedRedraw())) latestNavigationState else null
|
||||
if (ready != null) {
|
||||
publishFrame(renderNavigationFrame(ready, mode))
|
||||
scheduler.markRendered(ready, SystemClock.elapsedRealtime())
|
||||
@@ -451,7 +465,7 @@ class TftService : Service() {
|
||||
checkSpeedCameras(state, now)
|
||||
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && reroutePolicy.shouldRequest(state, now)) requestReroute(false)
|
||||
scheduler.offer(state)
|
||||
val ready = scheduler.takeIfDue(now) ?: if (map && mapRetryAt > 0 && now >= mapRetryAt) latestNavigationState else null
|
||||
val ready = scheduler.takeIfDue(now) ?: if (map && ((mapRetryAt > 0 && now >= mapRetryAt) || consumeForcedRedraw())) latestNavigationState else null
|
||||
if (ready != null) {
|
||||
publishFrame(renderNavigationFrame(ready, mode))
|
||||
scheduler.markRendered(ready, SystemClock.elapsedRealtime())
|
||||
@@ -576,54 +590,62 @@ class TftService : Service() {
|
||||
if (generation == preparedGeneration && routePreview) publishFrame(frame)
|
||||
}
|
||||
}
|
||||
/** Import never contacts a routing server or replaces active guidance before Start. */
|
||||
/** Import never replaces active guidance before Start; a raw trace never contacts a routing server. */
|
||||
fun prepareImportedRoute(imported: ImportedRoute) {
|
||||
require(imported.route.imported && imported.route.maneuvers.isEmpty())
|
||||
require(imported.route.imported && !imported.needsRoadRouting)
|
||||
RouteGuidanceTracker(imported.route) // Validate before invalidating an existing plan.
|
||||
invalidateRoutePlan()
|
||||
routePlan = RoutePlan(imported.route, imported.route.geometry.first(), false)
|
||||
preparedDestinationDirty = false
|
||||
mutableRouteInfo.value = "GPX · %.1f km · %d puntos\nSigue el trazado: sin instrucciones de giro, ETA ni recálculo automático. Revisa el recorrido antes de iniciar.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, imported.route.geometry.size)
|
||||
mutableRouteInfo.value = if (imported.route.maneuvers.isNotEmpty())
|
||||
"GPX por carreteras · %.1f km · %d min\nIndicaciones de giro activas. Si te desvías, vuelve a la ruta: no se recalcula para respetar tus puntos.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, (imported.route.durationSeconds + 59) / 60)
|
||||
else "Traza GPX · %.1f km · %d puntos\nSigue el trazado: sin indicaciones de giro ni ETA. Revisa el recorrido antes de iniciar.".format(java.util.Locale.ROOT, imported.route.distanceMeters / 1000.0, imported.route.geometry.size)
|
||||
if (!hasActiveGuidance()) showPreparedPreview()
|
||||
}
|
||||
/** Resolve GPX route stops against Valhalla; never alter a detailed imported track. */
|
||||
fun calculateImportedStops(imported: ImportedRoute) {
|
||||
if (imported.isTrack || imported.route.geometry.size !in 2..50) {
|
||||
mutableRouteInfo.value = "Solo se pueden calcular rutas GPX con entre 2 y 50 puntos de paso."
|
||||
return
|
||||
}
|
||||
val stops = imported.route.geometry
|
||||
/** Join GPX route points, waypoints or a sparse track along roads; a detailed track is followed as is. */
|
||||
fun calculateImportedStops(imported: ImportedRoute, onReady: () -> Unit = {}) {
|
||||
if (!imported.needsRoadRouting) { prepareImportedRoute(imported); onReady(); return }
|
||||
invalidateRoutePlan() // Never offer the straight lines between stops as a route.
|
||||
val generation = preparedGeneration
|
||||
val options = RouteOptions(profile = RouteProfile.AVOID_MOTORWAYS, avoidMotorways = true, avoidUnpaved = true)
|
||||
mutableRouteInfo.value = "Calculando sobre carreteras · evitando autopistas y pistas sin asfaltar…"
|
||||
// A sparse recorded track may follow motorways; planned stops keep the scenic default.
|
||||
val options = if (imported.isTrack) RouteOptions(profile = RouteProfile.FASTEST, avoidUnpaved = true) else RouteOptions(profile = RouteProfile.AVOID_MOTORWAYS, avoidMotorways = true, avoidUnpaved = true)
|
||||
mutableRouteInfo.value = "Calculando la ruta por carreteras · ${imported.stops.size} puntos…"
|
||||
routeJob?.cancel()
|
||||
routeJob = scope.launch {
|
||||
try {
|
||||
val engine = routingEngineFactory(routingEndpoint())
|
||||
val geometry = mutableListOf<GeoPoint>()
|
||||
var metres = 0L
|
||||
for (i in 0 until stops.lastIndex) {
|
||||
val part = engine.calculateRoute(stops[i], stops[i + 1], options)
|
||||
ensureActive()
|
||||
if (part.geometry.size < 2) throw java.io.IOException("Segmento sin geometría")
|
||||
geometry.addAll(if (i == 0) part.geometry else part.geometry.drop(1))
|
||||
metres += part.distanceMeters
|
||||
if (geometry.size > 10_000) throw IllegalArgumentException("La ruta supera 10000 puntos")
|
||||
if (generation != preparedGeneration) return@launch
|
||||
mutableRouteInfo.value = "Calculando carreteras · tramo ${i + 1}/${stops.lastIndex}"
|
||||
}
|
||||
val result = routingEngineFactory(routingEndpoint()).calculateRouteThrough(imported.stops, options)
|
||||
ensureActive()
|
||||
if (generation != preparedGeneration) return@launch
|
||||
val result = RouteResult(geometry = geometry, maneuvers = emptyList(),
|
||||
distanceMeters = metres.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(),
|
||||
durationSeconds = 0, destination = geometry.last(), imported = true)
|
||||
prepareImportedRoute(ImportedRoute(imported.name, result, isTrack = true))
|
||||
mutableRouteInfo.value = "GPX ajustado a carreteras · %.1f km · %d puntos\nComprueba que no haya autovías ni tramos inadecuados antes de salir. No hay avisos de giro ni recálculo.".format(java.util.Locale.ROOT, metres / 1000.0, geometry.size)
|
||||
if (result.geometry.size !in 2..100_000) throw IllegalArgumentException("Geometría de ruta inválida")
|
||||
prepareImportedRoute(ImportedRoute(imported.name, result.copy(imported = true), isTrack = imported.isTrack))
|
||||
onReady()
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: Exception) {
|
||||
if (generation == preparedGeneration)
|
||||
mutableRouteInfo.value = "No se pudo calcular sobre carreteras. Se conserva el GPX original; comprueba conexión y endpoint Valhalla."
|
||||
mutableRouteInfo.value = if (error is RoutingHttpException && error.status == 429) "No se pudo calcular: servidor de rutas ocupado. Espera un minuto y pulsa Reintentar."
|
||||
else "No se pudo calcular la ruta por carreteras. Comprueba la conexión a Internet y pulsa Reintentar."
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Positive steps zoom in. Called from the phone and from handlebar requests. */
|
||||
fun adjustTftZoom(steps: Int) {
|
||||
val next = TftCameraPolicy.stepOffset(tftZoomOffset, steps)
|
||||
if (next == tftZoomOffset) { mutableTftZoomInfo.value = if (steps > 0) "Zoom máximo" else "Zoom mínimo"; return }
|
||||
tftZoomOffset = next
|
||||
getSharedPreferences("tft_camera", MODE_PRIVATE).edit().putFloat("zoom_offset", next.toFloat()).apply()
|
||||
mutableTftZoomInfo.value = "Zoom TFT %+.1f".format(java.util.Locale("es", "ES"), next)
|
||||
forceMapRedraw = true
|
||||
if (routePreview && shownRoute != null && navigationJob?.isActive != true) showPreparedPreview()
|
||||
}
|
||||
private fun consumeForcedRedraw(): Boolean = forceMapRedraw.also { forceMapRedraw = false }
|
||||
private fun onDashboardRequest(service: Int, payloadSize: Int) {
|
||||
android.util.Log.i("NavFrame", "NAVILITE_REQUEST service=$service bytes=$payloadSize")
|
||||
scope.launch {
|
||||
dashboardRequests[service] = (dashboardRequests[service] ?: 0) + 1
|
||||
when (service) {
|
||||
NaviLiteTransport.ZOOM_IN_REQUEST -> adjustTftZoom(1)
|
||||
NaviLiteTransport.ZOOM_OUT_REQUEST -> adjustTftZoom(-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -649,7 +671,8 @@ class TftService : Service() {
|
||||
reroutePaused = false
|
||||
if (plan.demo) startDemo(true, preserveRoute = true) else startGps(true, preserveRoute = true)
|
||||
if (plan.route.imported) {
|
||||
mutableRouteInfo.value = "GPX iniciado · GPS real · %.1f km\nSigue el trazado · sin giros anunciados, ETA ni recálculo automático.".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
|
||||
mutableRouteInfo.value = if (plan.route.maneuvers.isNotEmpty()) "Ruta GPX iniciada · %.1f km · indicaciones de giro activas".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
|
||||
else "Traza GPX iniciada · %.1f km · sigue el trazado".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
|
||||
return
|
||||
}
|
||||
mutableRouteInfo.value = "${if (preview) "Vista previa" else "Guiado iniciado"} · ${if (plan.demo) "posición DEMO simulada" else "GPS real"} · %.1f km · %d min planificados\nGuiado por geometría · ETA estimada. ${if (plan.demo) "Recorrido DEMO ficticio, sin GPS real ni recálculo automático." else "Recálculo por desvío sostenido; no sustituye señales viales."}".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0, (plan.route.durationSeconds + 59) / 60)
|
||||
@@ -758,7 +781,7 @@ class TftService : Service() {
|
||||
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" }
|
||||
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"
|
||||
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}\nZoom TFT: ${"%+.1f".format(java.util.Locale.ROOT, tftZoomOffset)} · peticiones de la moto: ${dashboardRequests.entries.joinToString { "${it.key}×${it.value}" }.ifEmpty { "ninguna" }}\nSin coordenadas, consultas, direcciones ni URLs.$historyWarning"
|
||||
}
|
||||
fun isRealSessionRequested(): Boolean = realRequested
|
||||
fun isGpsSessionActive(): Boolean = gpsRequested
|
||||
@@ -818,6 +841,7 @@ class TftService : Service() {
|
||||
if (next == previous) return
|
||||
// Release the previous local archive even if restarting GPS fails permission/provider checks.
|
||||
mapRenderer?.close(); mapRenderer = null
|
||||
releaseMapFallback(); onlineRetryAt = 0
|
||||
when (mutableMode.value) {
|
||||
NavigationMode.MAP_DEMO -> if (routePreview && shownRoute != null) showPreparedPreview() else startDemo(true, preserveRoute = true)
|
||||
NavigationMode.MAP_GPS -> if (routePreview && !gpsRequested && shownRoute != null) showPreparedPreview() else startGps(true, preserveRoute = true)
|
||||
@@ -832,16 +856,20 @@ class TftService : Service() {
|
||||
}
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (mapRetryAt > now) return MapFrameComposer().compose(null, null, state, mode, source.attribution, unavailable = true, failureCode = mutableMapDiagnostic.value.split(" · ").getOrNull(1)).also { unavailableMapFrame = it }
|
||||
val online = !source.uri.startsWith("file:")
|
||||
if (online && now < onlineRetryAt) offlineFallbackFrame(state, mode)?.let { return it }
|
||||
mapRenderStarted = SystemClock.elapsedRealtime()
|
||||
mapRenderStage = MapRenderStage.INITIALIZE
|
||||
try {
|
||||
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 ->
|
||||
val current = mapRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(if (source.uri.startsWith("asset://")) "" else source.uri, source.attribution, applicationContext), { tftZoomOffset }) { stage ->
|
||||
mapRenderStage = stage
|
||||
mutableMapDiagnostic.value = "TFT MAP · ${stage.name} · ${if (source.uri.startsWith("file:")) "LOCAL" else "ONLINE"}"
|
||||
}.also { mapRenderer = it }
|
||||
current.render(state, mode)
|
||||
}
|
||||
onlineRetryAt = 0
|
||||
releaseMapFallback()
|
||||
if (mapFailures > 0) recordMapEvent(MapDiagnosticKind.RECOVERED, state, mode, source, retryMs = 0)
|
||||
mutableMapDiagnostic.value = "TFT MAP · OK · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · 480×240"
|
||||
mapFailures = 0
|
||||
@@ -851,11 +879,62 @@ class TftService : Service() {
|
||||
return frame
|
||||
} catch (cancelled: CancellationException) {
|
||||
currentCoroutineContext().ensureActive() // A local map timeout is recoverable; STOP is not.
|
||||
return mapUnavailable(state, mode, source, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage))
|
||||
return onlineFailed(state, mode, source, MapRenderException(MapRenderFailure.TIMEOUT, mapRenderStage))
|
||||
} catch (error: Exception) {
|
||||
return mapUnavailable(state, mode, source, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName)))
|
||||
return onlineFailed(state, mode, source, error as? MapRenderException ?: MapRenderException(classifyMapRenderFailure(error.message), mapRenderStage, mapErrorDetail(error.message, error.javaClass.simpleName)))
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A still snapshot fails as a whole when any tile request fails, which is common with
|
||||
* patchy mobile coverage. Prefer an installed offline map over an error frame.
|
||||
*/
|
||||
private suspend fun onlineFailed(state: NavigationState, mode: NavigationMode, source: TileSource, error: MapRenderException): TftFrame {
|
||||
if (source.uri.startsWith("file:")) return mapUnavailable(state, mode, source, error)
|
||||
android.util.Log.w("NavFrame", "MAP_ONLINE_FAILED code=${error.failure.name} stage=${error.stage.name} detail=${error.detail.safeText()}")
|
||||
mapRenderer?.close(); mapRenderer = null
|
||||
onlineRetryAt = SystemClock.elapsedRealtime() + ONLINE_RETRY_MS
|
||||
lastMapFailureDiagnostic = "TFT MAP · ${error.failure.name} · ${error.stage.name} · ${error.detail.safeText()} · ONLINE"
|
||||
val frame = offlineFallbackFrame(state, mode)
|
||||
if (frame != null) return frame
|
||||
onlineRetryAt = 0
|
||||
return mapUnavailable(state, mode, source, error)
|
||||
}
|
||||
private suspend fun offlineFallbackFrame(state: NavigationState, mode: NavigationMode): TftFrame? {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (offlineSourcesAt == 0L || now - offlineSourcesAt > 60_000) {
|
||||
offlineSourcesAt = now
|
||||
offlineSources = try {
|
||||
val packs = OfflineMapManager(applicationContext).let { it.refresh(); it.packs.value }
|
||||
.filter { it.state == OfflinePackState.READY }
|
||||
.map { RegionalBounds(it.bounds.south, it.bounds.west, it.bounds.north, it.bounds.east) to it.source }
|
||||
val regions = RegionalPackManager(applicationContext).let { it.refresh(); RegionalPackManager.latest(it.regions.value) }
|
||||
.map { it.manifest.bounds to it.source }
|
||||
packs + regions
|
||||
} catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { emptyList() }
|
||||
}
|
||||
val position = state.position
|
||||
val source = offlineSources.firstOrNull { (bounds, _) -> position.latitude in bounds.south..bounds.north && position.longitude in bounds.west..bounds.east }?.second
|
||||
?: return null
|
||||
if (fallbackUri != source.uri) releaseMapFallback()
|
||||
mapRenderStarted = SystemClock.elapsedRealtime()
|
||||
return try {
|
||||
val renderer = fallbackRenderer ?: MapLibreTftRenderer(applicationContext, ConfiguredMapDataSource(source.uri, source.attribution, applicationContext), { tftZoomOffset })
|
||||
.also { fallbackRenderer = it; fallbackUri = source.uri }
|
||||
renderer.render(state, mode).also {
|
||||
mutableMapDiagnostic.value = "TFT MAP · OFFLINE DE RESPALDO · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · reintento online en ${ONLINE_RETRY_MS / 1000} s"
|
||||
mapFailures = 0; mapRetryAt = 0; unavailableMapFrame = null
|
||||
}
|
||||
} catch (cancelled: CancellationException) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
releaseMapFallback(); null
|
||||
} catch (_: Exception) { releaseMapFallback(); null }
|
||||
}
|
||||
/** Closes the offline fallback renderer, for example before deleting its archive. */
|
||||
fun releaseMapFallback() {
|
||||
fallbackRenderer?.close(); fallbackRenderer = null; fallbackUri = null
|
||||
// Do not rescan (and reopen) packs that may be in the middle of being deleted.
|
||||
offlineSources = emptyList(); offlineSourcesAt = SystemClock.elapsedRealtime()
|
||||
}
|
||||
private suspend fun mapUnavailable(state: NavigationState, mode: NavigationMode, source: TileSource, error: MapRenderException): TftFrame {
|
||||
lastMapNetworkConnected = mapRenderer?.networkConnected ?: lastMapNetworkConnected
|
||||
mapRenderer?.close()
|
||||
@@ -911,7 +990,7 @@ class TftService : Service() {
|
||||
return Notification.Builder(this, "tft")
|
||||
.setSmallIcon(android.R.drawable.ic_menu_compass)
|
||||
.setContentTitle("NavFrame · Yamaha TFT")
|
||||
.setContentText(if (realRequested) "$notificationText · ${mutableMode.value}" else "GPS activo · sin conexión TFT")
|
||||
.setContentText(if (realRequested) notificationText + when (mutableMode.value) { NavigationMode.GPS, NavigationMode.MAP_GPS -> " · navegando"; NavigationMode.DEMO, NavigationMode.MAP_DEMO -> " · simulación"; NavigationMode.IDLE -> "" } else "GPS activo · sin conexión TFT")
|
||||
.setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true)
|
||||
.addAction(Notification.Action.Builder(null, "Detener todo", stop).build()).build()
|
||||
}
|
||||
@@ -926,6 +1005,7 @@ class TftService : Service() {
|
||||
navigationJob?.cancel()
|
||||
mapRenderer?.close()
|
||||
mapRenderer = null
|
||||
releaseMapFallback()
|
||||
try { locationProvider?.close() } catch (_: SecurityException) { }
|
||||
locationProvider = null
|
||||
scope.cancel() // Cancelling runner closes its socket in NonCancellable cleanup.
|
||||
@@ -934,6 +1014,7 @@ class TftService : Service() {
|
||||
super.onDestroy()
|
||||
}
|
||||
companion object {
|
||||
private const val ONLINE_RETRY_MS = 30_000L
|
||||
const val ACTION_REAL = "dev.navframe.CONNECT_REAL"
|
||||
const val ACTION_GPS = "dev.navframe.START_GPS"
|
||||
const val ACTION_MAP_GPS = "dev.navframe.START_MAP_GPS"
|
||||
|
||||
@@ -13,13 +13,29 @@ import kotlin.coroutines.resumeWithException
|
||||
|
||||
class RoutingHttpException(val status: Int, val retryAfterMs: Long) : IOException("Servidor de rutas: HTTP $status")
|
||||
|
||||
/** Explicit prototype requests only. No automatic recalc, request retry or location history. */
|
||||
/** Explicit requests only. No automatic recalc, request retry or location history. */
|
||||
class ValhallaRoutingEngine(private val endpoint: String, private val clientId: String, private val language: () -> String = { "es-ES" }, private val openConnection: (String) -> HttpURLConnection = { URI(it).toURL().openConnection() as HttpURLConnection }) : RoutingEngine {
|
||||
init { validateEndpoint(endpoint) }
|
||||
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
|
||||
validatePoint(origin); validatePoint(destination)
|
||||
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult =
|
||||
calculateChunk(listOf(origin, destination), options)
|
||||
|
||||
/** Consecutive requests of at most [MAX_REQUEST_LOCATIONS] stops, sharing their boundary stop. */
|
||||
override suspend fun calculateRouteThrough(stops: List<GeoPoint>, options: RouteOptions): RouteResult {
|
||||
require(stops.size >= 2) { "Se necesitan al menos dos puntos" }
|
||||
val parts = ArrayList<RouteResult>()
|
||||
var start = 0
|
||||
while (start < stops.lastIndex) {
|
||||
val end = minOf(start + MAX_REQUEST_LOCATIONS - 1, stops.lastIndex)
|
||||
parts += calculateChunk(stops.subList(start, end + 1), options)
|
||||
start = end
|
||||
}
|
||||
return mergeRouteLegs(parts).copy(destination = stops.last())
|
||||
}
|
||||
private suspend fun calculateChunk(stops: List<GeoPoint>, options: RouteOptions): RouteResult {
|
||||
stops.forEach(::validatePoint)
|
||||
val destination = stops.last()
|
||||
val locale = GuidanceLanguage.resolve(language()).tag
|
||||
val body = buildValhallaRequest(origin, destination, options, locale)
|
||||
val body = buildValhallaRequest(stops, options, locale)
|
||||
val response = withTimeout(25_000) {
|
||||
rateGate.withLock {
|
||||
val wait = 1_000 - (System.nanoTime() / 1_000_000 - lastRequestMs)
|
||||
@@ -46,7 +62,7 @@ class ValhallaRoutingEngine(private val endpoint: String, private val clientId:
|
||||
http.connectTimeout = 10_000; http.readTimeout = 15_000
|
||||
http.instanceFollowRedirects = false
|
||||
http.setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||
http.setRequestProperty("User-Agent", "NavFrame/0.5 (Android prototype)")
|
||||
http.setRequestProperty("User-Agent", "NavFrame/${BuildConfig.VERSION_NAME} (Android)")
|
||||
http.setRequestProperty("X-Client-Id", clientId)
|
||||
http.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
|
||||
val status = http.responseCode
|
||||
|
||||
@@ -25,7 +25,22 @@ import java.time.Duration
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class ImportedRouteTest {
|
||||
class PhoneWithoutGpu : MainActivity() { override fun createPhoneMap(savedState: Bundle?): PhoneMapView? = null }
|
||||
private fun imported() = GpxRouteImporter.parse("""<gpx><rte><name>Weekend</name><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/></rte></gpx>""".byteInputStream())
|
||||
/** A detailed trace (about 11 m between points) is followed as is, without a routing server. */
|
||||
private fun imported() = GpxRouteImporter.parse(("<gpx><trk><name>Weekend</name><trkseg>" +
|
||||
(0..90).joinToString("") { "<trkpt lat=\"${43.36 + it * 0.0001}\" lon=\"-5.85\"/>" } + "</trkseg></trk></gpx>").byteInputStream())
|
||||
private class RoadEngine(val fail: Boolean = false) : RoutingEngine {
|
||||
val requests = mutableListOf<Pair<GeoPoint, GeoPoint>>()
|
||||
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
|
||||
requests += origin to destination
|
||||
if (fail) throw java.io.IOException("offline")
|
||||
val bend = GeoPoint((origin.latitude + destination.latitude) / 2, origin.longitude + 0.002)
|
||||
return RouteResult(listOf(origin, bend, destination), listOf(
|
||||
Maneuver("Gire a la derecha", 600, type = 10, beginShapeIndex = 1, endShapeIndex = 2),
|
||||
Maneuver("Ha llegado", 0, type = 4, beginShapeIndex = 2, endShapeIndex = 2),
|
||||
), 1_200, 120, destination)
|
||||
}
|
||||
override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = error("unused")
|
||||
}
|
||||
private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
|
||||
private fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true }
|
||||
|
||||
@@ -127,8 +142,17 @@ class ImportedRouteTest {
|
||||
try {
|
||||
shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
field("service").set(activity, service)
|
||||
importDocument("""<gpx><rte><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/></rte></gpx>""")
|
||||
val engine = RoadEngine()
|
||||
service.routingEngineFactory = { engine }
|
||||
importDocument("""<gpx><rte><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/><rtept lat="43.38" lon="-5.85"/></rte></gpx>""")
|
||||
tick()
|
||||
// Route points are joined along roads, keeping turn instructions, never by straight lines.
|
||||
assertEquals(2, engine.requests.size)
|
||||
assertTrue(service.preparedRouteIsImported())
|
||||
val routed = requireNotNull(service.navigationState.value.route)
|
||||
assertEquals(5, routed.geometry.size)
|
||||
assertEquals(listOf(10, 10, 4), routed.maneuvers.map { it.type })
|
||||
assertEquals(GeoPoint(43.38, -5.85), routed.destination)
|
||||
assertEquals("IMPORT_ROUTE", (field("pendingAction").get(activity) as Enum<*>).name)
|
||||
assertFalse(service.hasActiveGuidance())
|
||||
val oldRoute = service.navigationState.value.route
|
||||
@@ -197,4 +221,24 @@ class ImportedRouteTest {
|
||||
} finally { activityController.destroy(); serviceController.destroy() }
|
||||
}
|
||||
|
||||
@Test fun failedRoadCalculationNeverOffersStraightLinesAndCanBeRetried() {
|
||||
val controller = Robolectric.buildService(TftService::class.java).create()
|
||||
val service = controller.get()
|
||||
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
|
||||
try {
|
||||
val stops = GpxRouteImporter.parse("""<gpx><rte><rtept lat="43.36" lon="-5.85"/><rtept lat="43.37" lon="-5.85"/></rte></gpx>""".byteInputStream())
|
||||
assertTrue(stops.needsRoadRouting)
|
||||
service.routingEngineFactory = { RoadEngine(fail = true) }
|
||||
var ready = false
|
||||
service.calculateImportedStops(stops) { ready = true }; tick()
|
||||
assertFalse(ready)
|
||||
assertFalse(service.hasPreparedRoute())
|
||||
assertTrue(service.routeInfo.value.startsWith("No se pudo"))
|
||||
service.routingEngineFactory = { RoadEngine() }
|
||||
service.calculateImportedStops(stops) { ready = true }; tick()
|
||||
assertTrue(ready)
|
||||
assertTrue(service.preparedRouteIsImported())
|
||||
assertEquals(3, service.navigationState.value.route?.geometry?.size)
|
||||
} finally { controller.destroy() }
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ class NominatimGeocoderTest {
|
||||
assertFalse(url.contains("viewbox")); assertFalse(url.contains("lat=")); assertFalse(url.contains("lon="))
|
||||
assertTrue(result.name.contains("Asturias"))
|
||||
assertTrue(result.attribution.contains("OpenStreetMap"))
|
||||
assertTrue(http.getRequestProperty("User-Agent").startsWith("NavFrame/0.6"))
|
||||
assertTrue(http.getRequestProperty("User-Agent").startsWith("NavFrame/${BuildConfig.VERSION_NAME} "))
|
||||
}
|
||||
@Test fun cancellingSearchClosesItsConnectionAndBlockingRead() = runBlocking {
|
||||
val http = Connection(block = true)
|
||||
|
||||
Reference in new issue
Block a user