Compare commits

..
Author SHA1 Message Date
dasemu a9ff685bf0 Merge pull request #6 from Dasemu/feat/import-gpx-routes
Import GPX routes and start navigation automatically
2026-10-13 11:49:20 +02:00
Darío Sevilla 4ffd4d874e feat: require precise GPS for imported routes and release 0.13.4 2026-10-13 09:48:19 +00:00
Darío Sevilla 27bc1f6958 ci: retain manifest defaults when overriding production version code 2026-10-13 09:44:11 +00:00
Darío Sevilla 317f8cbfaa feat: import GPX traces and start navigation without destination search 2026-10-13 09:43:16 +00:00
dasemu cffdeb39c4 Merge pull request #5 from Dasemu/feat/persistent-tft-diagnostics
Feat/persistent tft diagnostics
2026-10-13 11:40:48 +02:00
dasemu 0ad42025b7 Merge branch 'main' into feat/persistent-tft-diagnostics 2026-10-13 11:40:39 +02:00
dasemu 9f5d3963db Merge pull request #4 from Dasemu/ci/automatic-android-releases
Publish signed main APK releases and development debug artifacts
2026-10-13 11:39:28 +02:00
Darío Sevilla e96e905b09 ci: publish signed main releases and development debug artifacts 2026-10-13 09:36:40 +00:00
dasemu b5a7c67512 Merge pull request #3 from Dasemu/feat/faster-location-compass
Improve location startup and add compass heading
2026-10-13 11:09:17 +02:00
dasemu 4b586cc3e2 Merge pull request #2 from Dasemu/feat/persistent-tft-diagnostics
Persist TFT map diagnostics across phone restarts
2026-10-13 11:09:09 +02:00
dasemu 470689573a Merge pull request #1 from Dasemu/docs/public-readiness-tft-investigation
Document TFT map incident and update English public guides
2026-10-13 11:08:53 +02:00
Darío Sevilla d335a084d4 feat: reuse native location fixes and add low-speed compass heading 2026-10-13 05:51:13 +00:00
Darío Sevilla 74b222a094 feat: persist and share TFT map failure history across restarts 2026-10-12 05:21:06 +00:00
Darío Sevilla f727149369 docs: prepare English public documentation and preserve license scope 2026-10-12 05:06:35 +00:00
Darío Sevilla 008e4e3d80 docs: investigate persistent TFT map failure in La Corredoria 2026-10-12 05:03:44 +00:00
dasemu 6fec09f20f Fix off-route detection and TFT network lifecycle 2026-10-01 13:57:29 +02:00
dasemu 823d5db5d7 Expand map area on motorcycle display 2026-10-01 12:35:12 +02:00
38 changed files with 2151 additions and 333 deletions

No files matched your search

+125 -5
View File
@@ -1,13 +1,15 @@
name: Android build and checks
on:
push:
branches: [main]
branches: [main, development]
pull_request:
workflow_dispatch:
permissions:
contents: read
# Grouping by branch would drop pending builds during rapid pushes.
concurrency:
group: android-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
group: android-${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
jobs:
verify:
runs-on: ubuntu-latest
@@ -23,15 +25,133 @@ jobs:
run: sdkmanager "platforms;android-36" "build-tools;35.0.0"
- uses: gradle/actions/setup-gradle@v4
- name: Build, unit tests and lint
run: ./gradlew --no-daemon :app:assembleDebug :app:testDebugUnitTest :app:lintDebug :core:test :navilite:testDebugUnitTest
run: ./gradlew --no-daemon --max-workers=4 :app:assembleDebug :app:testDebugUnitTest :app:lintDebug :core:test :navilite:testDebugUnitTest
- name: Preserve check reports
if: always()
uses: actions/upload-artifact@v4
with:
name: android-check-reports
name: android-check-reports-${{ github.run_id }}
path: |
app/build/reports/
core/build/reports/
navilite/build/reports/
if-no-files-found: ignore
retention-days: 7
- name: Upload development debug APK
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/development'
uses: actions/upload-artifact@v4
with:
name: navframe-debug-${{ github.sha }}
path: app/build/outputs/apk/debug/app-debug.apk
if-no-files-found: error
retention-days: 14
release:
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- uses: android-actions/setup-android@v4
- name: Install Android compile SDK
run: sdkmanager "platforms;android-36" "build-tools;35.0.0"
- uses: gradle/actions/setup-gradle@v4
- name: Restore production signing key
env:
ANDROID_RELEASE_KEYSTORE_BASE64: ${{ secrets.ANDROID_RELEASE_KEYSTORE_BASE64 }}
ANDROID_RELEASE_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEYSTORE_PASSWORD }}
ANDROID_RELEASE_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }}
ANDROID_RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }}
run: |
set -euo pipefail
for name in ANDROID_RELEASE_KEYSTORE_BASE64 ANDROID_RELEASE_KEYSTORE_PASSWORD ANDROID_RELEASE_KEY_ALIAS ANDROID_RELEASE_KEY_PASSWORD; do
if [[ -z "${!name}" ]]; then
echo "::error::Missing production signing secret: $name (see docs/ANDROID_RELEASES.md)"
exit 1
fi
done
umask 077
printf '%s' "$ANDROID_RELEASE_KEYSTORE_BASE64" | base64 --decode > "$RUNNER_TEMP/navframe-release.p12"
echo "NAVFRAME_KEYSTORE_PATH=$RUNNER_TEMP/navframe-release.p12" >> "$GITHUB_ENV"
- name: Build signed production APK and lint
env:
NAVFRAME_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEYSTORE_PASSWORD }}
NAVFRAME_KEY_ALIAS: ${{ secrets.ANDROID_RELEASE_KEY_ALIAS }}
NAVFRAME_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }}
run: |
set -euo pipefail
# Preserve numeric versionName for the diagnostic history schema.
VERSION_CODE=$((1000000 + GITHUB_RUN_NUMBER))
./gradlew --no-daemon --max-workers=4 :app:assembleRelease :app:lintRelease -PnavframeVersionCode="$VERSION_CODE"
- name: Verify signature and prepare release files
id: package
run: |
set -euo pipefail
SDK_ROOT="${ANDROID_SDK_ROOT:-$ANDROID_HOME}"
"$SDK_ROOT/build-tools/35.0.0/apksigner" verify --verbose app/build/outputs/apk/release/app-release.apk
python3 - <<'PY'
import json, os, pathlib, re, shutil, hashlib
metadata = json.loads(pathlib.Path('app/build/outputs/apk/release/output-metadata.json').read_text())
item = metadata['elements'][0]
version = item['versionName']
if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){1,3}', version):
raise SystemExit('Unexpected versionName')
if item['versionCode'] != 1000000 + int(os.environ['GITHUB_RUN_NUMBER']):
raise SystemExit('Unexpected production versionCode')
tag = f"app-v{version}-build-{os.environ['GITHUB_RUN_NUMBER']}-{os.environ['GITHUB_SHA'][:12]}"
folder = pathlib.Path(os.environ['RUNNER_TEMP']) / 'navframe-release-output'; folder.mkdir()
apk = folder / f'navframe-{tag}.apk'
shutil.copyfile('app/build/outputs/apk/release/app-release.apk', apk)
(folder / 'SHA256SUMS.txt').write_text(f'{hashlib.sha256(apk.read_bytes()).hexdigest()} {apk.name}\n')
(folder / 'build-info.json').write_text(json.dumps({'versionName': version, 'versionCode': item['versionCode'], 'commit': os.environ['GITHUB_SHA'], 'runNumber': int(os.environ['GITHUB_RUN_NUMBER'])}, indent=2) + '\n')
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
out.write(f'tag={tag}\nversion={version}\ndirectory={folder}\n')
PY
- name: Publish production release
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ steps.package.outputs.tag }}
VERSION_NAME: ${{ steps.package.outputs.version }}
RELEASE_DIRECTORY: ${{ steps.package.outputs.directory }}
run: |
set -euo pipefail
# A rerun may finish its own draft but cannot replace published assets.
if gh release view "$RELEASE_TAG" --json isDraft,targetCommitish > "$RUNNER_TEMP/existing-release.json" 2>/dev/null; then
python3 - <<'PY'
import json, os, pathlib
release = json.loads(pathlib.Path(os.environ['RUNNER_TEMP'], 'existing-release.json').read_text())
if release['targetCommitish'] != os.environ['GITHUB_SHA']:
raise SystemExit('Existing release targets another commit')
PY
if [[ "$(python3 -c 'import json,os,pathlib; print(str(json.loads(pathlib.Path(os.environ["RUNNER_TEMP"], "existing-release.json").read_text())["isDraft"]).lower())')" == false ]]; then
echo "Production release already published; preserving its assets."
exit 0
fi
gh release upload "$RELEASE_TAG" "$RELEASE_DIRECTORY"/* --clobber
else
printf 'Signed production APK for commit %s.\n\nVersion code: %s. Checksums and build metadata are attached.\n' "$GITHUB_SHA" "$((1000000 + GITHUB_RUN_NUMBER))" > "$RUNNER_TEMP/release-notes.md"
gh release create "$RELEASE_TAG" "$RELEASE_DIRECTORY"/* --draft --target "$GITHUB_SHA" --title "NavFrame $VERSION_NAME · build $GITHUB_RUN_NUMBER" --notes-file "$RUNNER_TEMP/release-notes.md"
fi
# An older build finishing late cannot replace the current main release as latest.
LATEST=false
if [[ "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" == "$GITHUB_SHA" ]]; then
LATEST=true
fi
gh release edit "$RELEASE_TAG" --draft=false --latest="$LATEST"
- name: Preserve production lint report
if: always()
uses: actions/upload-artifact@v4
with:
name: android-release-lint-${{ github.run_id }}
path: app/build/reports/lint-results-release.*
if-no-files-found: ignore
retention-days: 7
- name: Remove temporary signing key
if: always()
run: rm -f "$RUNNER_TEMP/navframe-release.p12"
+4
View File
@@ -10,6 +10,10 @@ Contributions are welcome. NavFrame is experimental software for motorcycle navi
- Preserve OSM attribution and source dates/hashes for derived data. Check third-party licenses before adding code, fonts, images, or data.
- Keep endpoints configurable where appropriate. Never commit API keys, signing keys, personal coordinates, Bluetooth identifiers, or local machine configuration.
## Licensing contributions
The project currently has no global license grant for original code and documentation. Discuss contribution and redistribution terms with the maintainers before submitting substantial work. Identify any third-party origin and license explicitly. Changes to the Pillion-derived `navilite` module must preserve its PolyForm Noncommercial provenance and required notices; do not assume a license for original project material overrides third-party terms.
## Build and checks
Use JDK 17 and an Android SDK with API 36. The Gradle wrapper pins the Gradle version.
+22 -4
View File
@@ -4,11 +4,11 @@ NavFrame is an experimental Android navigation app that renders its own 480×240
## Current status
The owner has confirmed static and synthetic NavFrame frames on a Xiaomi 11 Lite 5G NE running Android 14 and a 2026 Yamaha MT-07. The owner has also confirmed that the bundled Asturias map works offline on the phone. These results do not validate the current MapLibre map renderer on the motorcycle TFT: the last reported TFT map attempt showed `MAPA NO DISPONIBLE`, and no later physical map-render result is recorded.
The owner has confirmed static and synthetic NavFrame frames on a Xiaomi 11 Lite 5G NE running Android 14 and a 2026 Yamaha MT-07, and the bundled Asturias map working offline on the phone. On 2026-10-12, the owner reported that the latest version displayed the map on the TFT for about 20 minutes, then showed `Mapa no disponible` in La Corredoria (Oviedo) for the rest of the trip while the phone map continued working. An offline map was installed. The exact installed build, diagnostic code and background state were not recorded; the cause is under investigation. This establishes a successful map display followed by a persistent failure, not sustained TFT reliability.
Version 0.13.0 adds voice/routing language selection for Spanish, English, German, French, and Italian, plus a system-language option; unsupported system locales resolve to English. Speech still depends on the Android TextToSpeech engine and its installed voice data. The app includes offline map and place data for Asturias, plus installable regional packages. Worldwide regions can be discovered and built on demand through the [regional package workflow](docs/GLOBAL_OFFLINE.md); this is not complete worldwide coverage. Installed packages currently provide map and local place/camera data. Offline route calculation, global camera completeness, and complete worldwide font coverage are not provided.
The current checkout is version 0.13.4. The 0.13 series adds voice/routing language selection for Spanish, English, German, French, and Italian, plus a system-language option; unsupported system locales resolve to English. Speech still depends on the Android TextToSpeech engine and its installed voice data. The app includes offline map and place data for Asturias, plus installable regional packages. Worldwide regions can be discovered and built on demand through the [regional package workflow](docs/GLOBAL_OFFLINE.md); this is not complete worldwide coverage. Installed packages currently provide map and local place/camera data. Offline route calculation, global camera completeness, and complete worldwide font coverage are not provided.
Route calculation and address search use configurable online services. Spoken output uses the selected language when Android provides voice data; voice availability and offline behavior depend on the device's TextToSpeech engine. Physical validation of route guidance, voice playback, camera alerts, TFT map rendering, and a 30-minute screen-off session remains pending unless a newer test report says otherwise.
Route calculation and address search use configurable online services. Spoken output uses the selected language when Android provides voice data; voice availability and offline behavior depend on the device's TextToSpeech engine. Physical validation of route guidance, voice playback, camera alerts, sustained TFT map rendering, and a 30-minute screen-off session remains pending unless a newer test report says otherwise.
## Build
@@ -27,6 +27,22 @@ 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.
## Location and compass
Version 0.13.3 uses available native Android location sources and recent cached fixes to avoid waiting exclusively for a new satellite fix. The map can recenter on a recent approximate position with accuracy up to 100 metres; starting route guidance still requires 25 metres. A compass heading orients the map at low speed, while usable movement course takes priority when riding. See [Location and compass](docs/LOCATION_AND_COMPASS.md) for behavior and device-validation limits.
## 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.
## Automated builds
GitHub Actions uploads a debug APK artifact for pushes to `development`. Pushes to `main` publish a signed production APK release after build, tests, lint and signature checks pass. Production signing requires the repository secrets described in [Android builds and releases](docs/ANDROID_RELEASES.md). Pull requests run checks without publishing releases.
## Imported routes
Choose **☰ → Cargar ruta GPX** to load a standard GPX route or track and start following it once precise GPS is available. Imported traces retain their geometry without online recalculation or invented turn announcements. See [GPX import](docs/IMPORTED_ROUTES.md).
## Documentation
- [Documentation index](docs/README.md)
@@ -42,4 +58,6 @@ Set up `local.properties` for your own Android SDK when needed. It is excluded f
## License notes
There is no single permissive license covering every part of this repository. In particular, NaviLite contains code adapted from Pillion under PolyForm Noncommercial 1.0.0, which restricts commercial use. Other code, datasets, fonts, and dependencies have their own terms and notices. Review [Licensing](docs/LICENSING.md) and the included notices before copying, redistributing, or using any part of this project. OpenStreetMap-derived offline data is distributed under ODbL 1.0 with attribution.
No project-wide license is granted for original NavFrame code or documentation. Public repository visibility alone does not grant permission to copy, modify or redistribute that material. The Pillion-derived `navilite` module retains **PolyForm Noncommercial 1.0.0** and its required notices; its commercial-use restrictions must be respected.
Map data, fonts, dependencies and other third-party material retain their respective terms. OpenStreetMap-derived offline data is distributed under ODbL 1.0 with attribution. Review [Licensing](docs/LICENSING.md) and the included notices before copying, redistributing or using project material. Before redistributing a release, verify the terms for original material and every included component.
+26 -2
View File
@@ -1,17 +1,41 @@
plugins { id("com.android.application"); kotlin("android") }
val releaseSigningNames = listOf("NAVFRAME_KEYSTORE_PATH", "NAVFRAME_KEYSTORE_PASSWORD", "NAVFRAME_KEY_ALIAS", "NAVFRAME_KEY_PASSWORD")
val releaseSigning = releaseSigningNames.associateWith { System.getenv(it).orEmpty() }
val hasReleaseSigning = releaseSigning.values.all { it.isNotBlank() }
if (releaseSigning.values.any { it.isNotBlank() } && !hasReleaseSigning) {
throw GradleException("Incomplete release signing configuration. Required variables: ${releaseSigningNames.joinToString()}")
}
val navframeVersionCode = providers.gradleProperty("navframeVersionCode").orNull?.toInt()
require(navframeVersionCode == null || navframeVersionCode in 1..2_100_000_000) { "Android versionCode must be between 1 and 2100000000" }
android {
namespace = "dev.navframe.app"
compileSdk = 36
buildFeatures { buildConfig = true }
defaultConfig {
applicationId = "dev.navframe.app"
minSdk = 26
targetSdk = 35
versionCode = 16
versionName = "0.13.0"
versionName = "0.13.4"
versionCode = 20
}
if (hasReleaseSigning) {
signingConfigs.create("production") {
storeFile = file(releaseSigning.getValue("NAVFRAME_KEYSTORE_PATH"))
storePassword = releaseSigning.getValue("NAVFRAME_KEYSTORE_PASSWORD")
keyAlias = releaseSigning.getValue("NAVFRAME_KEY_ALIAS")
keyPassword = releaseSigning.getValue("NAVFRAME_KEY_PASSWORD")
}
buildTypes.getByName("release").signingConfig = signingConfigs.getByName("production")
}
testOptions { unitTests.isIncludeAndroidResources = true }
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
}
navframeVersionCode?.let { android.defaultConfig.versionCode = it }
gradle.taskGraph.whenReady {
if (!hasReleaseSigning && allTasks.any { it.path in setOf(":app:assembleRelease", ":app:bundleRelease", ":app:packageRelease") }) {
throw GradleException("Production builds require release signing. Configure ${releaseSigningNames.joinToString()}.")
}
}
kotlin { jvmToolchain(17) }
dependencies {
implementation(project(":core"))
@@ -0,0 +1,71 @@
package dev.navframe.app
import android.content.Context
import android.hardware.GeomagneticField
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.SystemClock
import android.view.Surface
import android.view.WindowManager
import dev.navframe.core.GeoPoint
import dev.navframe.core.normalizeBearing
/** Absolute orientation of the screen's top edge; coordinates are only used in memory for declination. */
internal class AndroidCompass(context: Context, private val changed: () -> Unit) : SensorEventListener {
private val manager = context.getSystemService(SensorManager::class.java)
private val windows = context.getSystemService(WindowManager::class.java)
private var sensor: Sensor? = null
private var degrees = Float.NaN
private var measuredAt = 0L
private var declination = 0f
private var accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE
private val matrix = FloatArray(9)
private val remapped = FloatArray(9)
private val angles = FloatArray(3)
fun start() {
sensor = manager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
?: manager.getDefaultSensor(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR)
sensor?.let { manager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI) }
}
fun updatePosition(point: GeoPoint) {
declination = GeomagneticField(point.latitude.toFloat(), point.longitude.toFloat(), 0f, System.currentTimeMillis()).declination
}
fun heading(): Float = if (degrees.isFinite() && accuracy != SensorManager.SENSOR_STATUS_UNRELIABLE && SystemClock.elapsedRealtime() - measuredAt in 0..5_000) normalizeBearing(degrees + declination) else Float.NaN
fun close() {
manager.unregisterListener(this)
sensor = null; degrees = Float.NaN; measuredAt = 0
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { this.accuracy = accuracy; changed() }
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor != sensor) return
accuracy = event.accuracy
if (accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { degrees = Float.NaN; changed(); return }
SensorManager.getRotationMatrixFromVector(matrix, event.values)
@Suppress("DEPRECATION")
val axes = when (windows.defaultDisplay.rotation) {
Surface.ROTATION_90 -> SensorManager.AXIS_Y to SensorManager.AXIS_MINUS_X
Surface.ROTATION_180 -> SensorManager.AXIS_MINUS_X to SensorManager.AXIS_MINUS_Y
Surface.ROTATION_270 -> SensorManager.AXIS_MINUS_Y to SensorManager.AXIS_X
else -> SensorManager.AXIS_X to SensorManager.AXIS_Y
}
SensorManager.remapCoordinateSystem(matrix, axes.first, axes.second, remapped)
SensorManager.getOrientation(remapped, angles)
val next = normalizeBearing(Math.toDegrees(angles[0].toDouble()).toFloat())
degrees = smoothHeading(degrees, next)
measuredAt = SystemClock.elapsedRealtime()
changed()
}
}
internal fun smoothHeading(previous: Float, next: Float): Float = if (!previous.isFinite()) normalizeBearing(next) else
normalizeBearing(previous + (((next - previous + 540f) % 360f) - 180f) * .2f)
internal fun selectHeading(course: Float, speed: Float, compass: Float): Float = when {
speed >= 2f && course.isFinite() -> normalizeBearing(course)
compass.isFinite() -> normalizeBearing(compass)
speed >= .7f && course.isFinite() -> normalizeBearing(course)
else -> Float.NaN
}
@@ -15,7 +15,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
/** Android GPS only. Locations stay in memory and are never written to logs. */
/** Native Android location sources and compass. Positions stay in memory and are never logged. */
class AndroidLocationProvider(context: Context) : LocationProvider {
private val context = context.applicationContext
private val manager = this.context.getSystemService(LocationManager::class.java)
@@ -23,44 +23,92 @@ class AndroidLocationProvider(context: Context) : LocationProvider {
override val locations = fixes.asSharedFlow()
private val enabled = MutableStateFlow(false)
val providerEnabled = enabled.asStateFlow()
private val headings = MutableStateFlow(Float.NaN)
val bearings = headings.asStateFlow()
private val compass = AndroidCompass(this.context) { updateBearing() }
private val registered = mutableSetOf<String>()
private var lastLocation: Location? = null
val currentBearing: Float get() { updateBearing(); return headings.value }
var lastFixElapsedMs: Long = 0
private set
internal var headingFromCompass = false
private set
private var listening = false
private val listener = object : LocationListener {
override fun onLocationChanged(location: Location) {
val ageMs = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000
if (ageMs !in 0..15_000 || !location.latitude.isFinite() || !location.longitude.isFinite()) return
lastFixElapsedMs = location.elapsedRealtimeNanos / 1_000_000
enabled.value = true
fixes.tryEmit(LocationFix(
GeoPoint(location.latitude, location.longitude),
if (location.hasBearing()) location.bearing else Float.NaN,
if (location.hasSpeed() && location.speed.isFinite()) location.speed.coerceAtLeast(0f) else 0f,
if (location.hasAccuracy()) location.accuracy else Float.POSITIVE_INFINITY,
location.time,
))
private fun updateBearing() {
val fix = lastLocation
val course = if (fix?.hasBearing() == true && (!fix.hasBearingAccuracy() || fix.bearingAccuracyDegrees <= 45f)) fix.bearing else Float.NaN
val recent = fix != null && locationAgeMs(fix) in 0..MAX_FIX_AGE_MS
val compassHeading = compass.heading()
val speed = if (recent && fix!!.hasSpeed()) fix.speed else 0f
headingFromCompass = compassHeading.isFinite() && !(speed >= 2f && recent && course.isFinite())
headings.value = selectHeading(if (recent) course else Float.NaN, speed, compassHeading)
}
private fun accept(location: Location) {
if (!validLocation(location)) return
val previous = lastLocation
if (previous != null && validLocation(previous)) {
val newerMs = (location.elapsedRealtimeNanos - previous.elapsedRealtimeNanos) / 1_000_000
if (location.accuracy > MAP_ACCURACY_METERS && previous.accuracy <= MAP_ACCURACY_METERS) return
if (newerMs < 0 || (newerMs < 5_000 && location.accuracy > previous.accuracy * 2 + 20)) return
}
override fun onProviderEnabled(provider: String) { enabled.value = true }
override fun onProviderDisabled(provider: String) { enabled.value = false; lastFixElapsedMs = 0 }
lastLocation = Location(location)
lastFixElapsedMs = location.elapsedRealtimeNanos / 1_000_000
refreshEnabled()
compass.updatePosition(GeoPoint(location.latitude, location.longitude))
fixes.tryEmit(LocationFix(
GeoPoint(location.latitude, location.longitude), currentBearing,
if (location.hasSpeed() && location.speed.isFinite()) location.speed.coerceAtLeast(0f) else 0f,
location.accuracy, location.time,
))
}
private fun refreshEnabled() { enabled.value = registered.any { it != LocationManager.PASSIVE_PROVIDER && manager.isProviderEnabled(it) } }
private val listener = object : LocationListener {
override fun onLocationChanged(location: Location) { if (listening) accept(location) }
override fun onProviderEnabled(provider: String) { refreshEnabled() }
override fun onProviderDisabled(provider: String) { refreshEnabled(); if (!enabled.value) lastFixElapsedMs = 0 }
@Deprecated("Legacy Android callback")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { }
}
override suspend fun start() {
check(context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
"Autoriza ubicación precisa para usar el GPS"
"Autoriza ubicación precisa para usar la ubicación"
}
check(LocationManager.GPS_PROVIDER in manager.allProviders) { "GPS no disponible en este dispositivo" }
if (listening) return
lastFixElapsedMs = 0
enabled.value = manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
lastLocation = null
val available = manager.allProviders.filter { it in setOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER, "fused", LocationManager.PASSIVE_PROVIDER) }
check(available.any { it != LocationManager.PASSIVE_PROVIDER }) { "Ubicación no disponible en este dispositivo" }
listening = true
try {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500L, 0f, listener, Looper.getMainLooper())
listening = true
} catch (error: Exception) { manager.removeUpdates(listener); throw error }
for (provider in available) {
try {
manager.requestLocationUpdates(provider, 500L, 0f, listener, Looper.getMainLooper())
registered += provider
} catch (_: IllegalArgumentException) { /* An optional provider can disappear during registration. */ }
}
check(registered.any { it != LocationManager.PASSIVE_PROVIDER }) { "No se pudo activar la ubicación" }
refreshEnabled()
compass.start()
// Seed promptly from a recent fix Android already has, instead of waiting for a new satellite fix.
registered.filter { manager.isProviderEnabled(it) }.mapNotNull { try { manager.getLastKnownLocation(it) } catch (_: IllegalArgumentException) { null } }
.filter(::validLocation).minByOrNull { it.accuracy + locationAgeMs(it) / 100f }?.let(::accept)
} catch (error: Exception) { close(); throw error }
}
override suspend fun stop() { close() }
fun close() {
try { if (listening) manager.removeUpdates(listener) }
finally { listening = false; enabled.value = false; lastFixElapsedMs = 0 }
finally {
compass.close(); registered.clear(); listening = false; enabled.value = false
lastFixElapsedMs = 0; lastLocation = null; headings.value = Float.NaN; headingFromCompass = false
}
}
companion object {
const val MAX_FIX_AGE_MS = 15_000L
const val MAP_ACCURACY_METERS = 100f
const val GUIDANCE_ACCURACY_METERS = 25f
internal fun locationAgeMs(location: Location) = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000
internal fun validLocation(location: Location): Boolean = locationAgeMs(location) in 0..MAX_FIX_AGE_MS &&
location.latitude.isFinite() && location.latitude in -90.0..90.0 && location.longitude.isFinite() && location.longitude in -180.0..180.0 &&
location.hasAccuracy() && location.accuracy.isFinite() && location.accuracy >= 0
}
}
@@ -22,6 +22,8 @@ open class MainActivity : Activity() {
private var observers: Job? = null
private var searchJob: Job? = null
private var positionWait: Job? = null
private var importJob: Job? = null
private var pendingImportUri: Uri? = null
private var searchGeneration = 0L
private var updatingDestination = false
private val placeRepository by lazy { OfflinePlaceRepository(applicationContext) }
@@ -69,7 +71,7 @@ open class MainActivity : Activity() {
private val visibleProfiles = listOf(RouteProfile.FASTEST, RouteProfile.AVOID_MOTORWAYS, RouteProfile.AVOID_UNPAVED)
private var destination: GeoPoint? = null
private var destinationName = ""
private enum class Action { POSITION, CALCULATE, ROUTE, PREVIEW, CONNECT, CHANGE_CONNECT }
private enum class Action { POSITION, CALCULATE, ROUTE, PREVIEW, CONNECT, CHANGE_CONNECT, IMPORT_ROUTE }
private var pendingAction: Action? = null
private val permissionsPreferences by lazy { getSharedPreferences("permissions", MODE_PRIVATE) }
private val connection = object : ServiceConnection {
@@ -78,6 +80,7 @@ open class MainActivity : Activity() {
observeService()
refreshPermissions()
tryAutoConnect()
pendingImportUri?.let { pendingImportUri = null; importRoute(it) }
}
override fun onServiceDisconnected(name: ComponentName?) { service = null; connectionInfo.text = "● Yamaha · conectar" }
}
@@ -102,7 +105,7 @@ open class MainActivity : Activity() {
setOnClickListener { withPermissions(Action.CONNECT) }; contentDescription = "Estado Yamaha. Tocar para conectar"
}
toolbar.addView(connectionInfo, LinearLayout.LayoutParams(0, dp(48), 1f))
toolbar.addView(button("☰") { AlertDialog.Builder(this).setTitle("NavFrame").setItems(arrayOf("Ajustes", "Mapas offline", "Lugares cercanos", "Información y licencias")) { _, item -> when(item) { 0 -> showSettings(); 1 -> showOfflineMaps(); 2 -> showPlaces(); 3 -> showInfo() } }.show() }.apply { contentDescription = "Abrir menú" }, LinearLayout.LayoutParams(dp(56), dp(48)))
toolbar.addView(button("☰") { AlertDialog.Builder(this).setTitle("NavFrame").setItems(arrayOf("Ajustes", "Mapas offline", "Lugares cercanos", "Cargar ruta GPX", "Información y licencias")) { _, item -> when(item) { 0 -> showSettings(); 1 -> showOfflineMaps(); 2 -> showPlaces(); 3 -> chooseRouteFile(); 4 -> showInfo() } }.show() }.apply { contentDescription = "Abrir menú" }, LinearLayout.LayoutParams(dp(56), dp(48)))
top.addView(toolbar, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = dp(8) })
val searchRow = row().apply { background = rounded(0xF217212D.toInt(), 18); elevation = dp(6).toFloat(); setPadding(dp(8), 0, dp(4), 0) }
searchQuery = edit("Buscar calles y lugares").apply {
@@ -136,7 +139,7 @@ open class MainActivity : Activity() {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (updatingDestination) return
cancelSearch(); positionWait?.cancel(); destination = null; destinationName = ""; routeDialog?.dismiss(); startButton?.isEnabled = false
cancelSearch(); importJob?.cancel(); positionWait?.cancel(); destination = null; destinationName = ""; routeDialog?.dismiss(); startButton?.isEnabled = false
if (service?.hasActiveGuidance() != true) service?.selectSearchDestination()
results.removeAllViews(); resultScroll.visibility = View.GONE; hint.text = ""
searchOfflineSuggestions(s?.toString().orEmpty())
@@ -204,25 +207,26 @@ open class MainActivity : Activity() {
val demo = current.navigationMode.value == NavigationMode.MAP_DEMO || current.navigationMode.value == NavigationMode.DEMO
guidance.text = when (state.navigationStatus) {
NavigationStatus.GPS_LOST -> "Sin GPS reciente y preciso"
NavigationStatus.GPS_LOST -> if (current.hasFreshGpsFix()) "Posición aproximada · esperando precisión para guiar" else "Sin ubicación reciente"
NavigationStatus.REROUTING -> "Recalculando ruta…"
NavigationStatus.OFF_ROUTE -> "Fuera de ruta"
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 "Continúa por la ruta"
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 }
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)) } ?: ""
val accuracy = state.accuracyMeters?.takeIf { it.isFinite() }?.let { "GPS ±${it.toInt()} m" } ?: ""
progress.text = listOf(next, remaining, eta, accuracy).filter { it.isNotEmpty() }.joinToString(" · ")
val accuracy = state.accuracyMeters?.takeIf { it.isFinite() }?.let { "${if (it > AndroidLocationProvider.GUIDANCE_ACCURACY_METERS) "Ubicación aproximada" else "Ubicación"} ±${it.toInt()} m" } ?: ""
val heading = if (!demo) state.bearing.takeIf { it.isFinite() }?.let { "${if (current.usesCompassHeading()) "Brújula" else "Rumbo GPS"} ${it.toInt()}°" } ?: "" else ""
progress.text = listOf(next, remaining, eta, accuracy, heading).filter { it.isNotEmpty() }.joinToString(" · ")
} }
}
}
private fun withPermissions(action: Action) {
if (service == null) { hint.text = "Espera la conexión con el servicio"; return }
val needsLocation = action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
val needsLocation = action == Action.IMPORT_ROUTE || action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
val required = mutableListOf<String>()
if ((action == Action.CONNECT || action == Action.CHANGE_CONNECT) && Build.VERSION.SDK_INT >= 31) required += Manifest.permission.BLUETOOTH_CONNECT
if (needsLocation) required += Manifest.permission.ACCESS_FINE_LOCATION
@@ -231,7 +235,7 @@ open class MainActivity : Activity() {
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 }
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 && 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
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
if (request.isEmpty()) { perform(action); return }
val ask = {
pendingAction = action
@@ -245,7 +249,7 @@ open class MainActivity : Activity() {
if (requestCode != 42) return
val action = pendingAction; pendingAction = null
refreshPermissions()
val needsFine = action == Action.POSITION || (action == Action.CALCULATE && origin.selectedItemPosition == 0) || (action == Action.ROUTE && service?.routeUsesGps() == true)
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."
}
@@ -267,13 +271,14 @@ open class MainActivity : Activity() {
if (hasReliablePosition()) { hidePositionNotice(); recenterPhoneMap() }
else showPositionNotice(when {
current == null || !current.isGpsSessionActive() && current.navigationState.value.accuracyMeters == null -> "Buscando señal GPS…"
current.navigationState.value.accuracyMeters?.let { !it.isFinite() || it > 25f } == true -> "Señal GPS poco precisa"
current.navigationState.value.accuracyMeters?.let { !it.isFinite() || it > AndroidLocationProvider.MAP_ACCURACY_METERS } == true -> "Señal GPS poco precisa"
else -> "Esperando una posición GPS reciente"
})
}
Action.CONNECT -> if (!connectRemembered(false)) chooseMotorcycle()
Action.CHANGE_CONNECT -> chooseMotorcycle()
Action.CALCULATE -> calculateRoute()
Action.IMPORT_ROUTE -> startImportedRoute()
Action.ROUTE, Action.PREVIEW -> {
if (action == Action.ROUTE && service?.hasPreparedRoute() != true) return
if (action == Action.ROUTE) startRequested = true
@@ -327,8 +332,81 @@ open class MainActivity : Activity() {
} catch (cancelled: CancellationException) { currentCoroutineContext().ensureActive(); hint.text = "Sin GPS · activa ubicación y prueba de nuevo"; routeInfo.text = hint.text; routeLoading?.visibility = View.GONE; retryRouteButton?.visibility = View.VISIBLE }
}
}
private fun chooseRouteFile() {
importJob?.cancel(); positionWait?.cancel()
try {
startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
// GPX providers use several MIME types, including application/octet-stream.
type = "*/*"
}, 76)
} catch (_: ActivityNotFoundException) { hint.text = "No hay selector de archivos disponible" }
}
private fun importRoute(uri: Uri) {
importJob?.cancel()
positionWait?.cancel()
hint.text = "Leyendo ruta GPX…"
importJob = scope.launch {
try {
val imported = withContext(Dispatchers.IO) {
contentResolver.openInputStream(uri)?.use(GpxRouteImporter::parse)
?: throw java.io.IOException("No se puede abrir el archivo")
}
ensureActive()
val current = service ?: run { hint.text = "Servicio no disponible · vuelve a cargar el GPX"; return@launch }
cancelSearch(); routeDialog?.dismiss()
current.prepareImportedRoute(imported)
destination = null; destinationName = ""
hint.text = "Ruta GPX cargada"
showImportedRouteSheet(imported.name)
withPermissions(Action.IMPORT_ROUTE)
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) {
// Parser messages contain no coordinates, file paths or document contents.
hint.text = if (error is IllegalArgumentException) error.message ?: "GPX no válido" else "No se pudo leer el GPX · revisa el archivo y su acceso"
}
}
}
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)
routeLoading = ProgressBar(this).apply { visibility = View.GONE }
box.addView(routeLoading)
retryRouteButton = null
startButton = button("Iniciar navegación") { withPermissions(Action.IMPORT_ROUTE) }
box.addView(startButton)
val dialog = AlertDialog.Builder(this).setView(box).setNegativeButton("Cerrar", null).create()
dialog.setOnDismissListener { positionWait?.cancel(); startRequested = false }
routeDialog = dialog
dialog.show()
}
private fun startImportedRoute() {
val current = service ?: return
if (!current.preparedRouteIsImported()) { hint.text = "Vuelve a cargar la ruta GPX"; return }
positionWait?.cancel()
if (current.hasGuidanceGpsFix()) { perform(Action.ROUTE); return }
current.setPhoneVisible(true)
hint.text = "Esperando GPS preciso para iniciar el GPX…"
routeLoading?.visibility = View.VISIBLE
startButton?.isEnabled = false
positionWait = scope.launch {
try {
withTimeout(60_000) {
// Map readiness stays true while accuracy improves from 100 m to 25 m.
while (!current.hasGuidanceGpsFix()) delay(200)
}
ensureActive()
if (current.preparedRouteIsImported()) perform(Action.ROUTE)
} catch (_: TimeoutCancellationException) { hint.text = "Sin GPS preciso · activa ubicación y pulsa Iniciar navegación de nuevo" }
finally { routeLoading?.visibility = View.GONE; startButton?.isEnabled = current.hasPreparedRoute() }
}
}
private fun cancelSearch() { searchGeneration++; searchJob?.cancel(); searchJob = null }
private fun searchDestination() {
positionWait?.cancel()
cancelSearch(); results.removeAllViews(); resultScroll.visibility = View.GONE
val query = searchQuery.text.toString(); val generation = searchGeneration
val endpoint = getSharedPreferences("geocoder", MODE_PRIVATE).getString("endpoint", NominatimGeocoder.DEFAULT_ENDPOINT) ?: NominatimGeocoder.DEFAULT_ENDPOINT
@@ -394,7 +472,7 @@ open class MainActivity : Activity() {
}
private fun chooseDestination(point: GeoPoint, name: String, attribution: String) {
val current = service ?: run { hint.text = "Espera la conexión con el servicio"; return }
cancelSearch(); positionWait?.cancel()
cancelSearch(); importJob?.cancel(); positionWait?.cancel()
updatingDestination = true
try { searchQuery.setText(name.take(200)) } finally { updatingDestination = false }
startRequested = false
@@ -600,14 +678,28 @@ open class MainActivity : Activity() {
}.setNegativeButton("Cancelar", null).show()
}
private fun showInfo() {
val text = "NavFrame 0.11.0 · mapas OpenStreetMap. Móvil y Yamaha comparten estado; el TFT se renderiza directamente a 480 × 240, sin captura de pantalla.\n\nDEMO es ficticia. GPS/ETA/guiado deben probarse en condiciones reales. Rutas y búsqueda necesitan conexión; los mapas y lugares incluidos de Asturias se consultan offline. Calcular rutas sigue necesitando Internet.\n\nNominatim recibe el texto de búsqueda, no tu GPS. No envíes información personal/confidencial. Prototipo con máximo 1 petición/s agregado y caché.\n\nNaviLite adaptado de Pillion · PolyForm Noncommercial 1.0.0\nRequired Notice: Copyright 2026 the Pillion authors\n\nFuente online predeterminada incluida: OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors.\n\nAsturias offline: datos © OpenStreetMap contributors, extracto Geofabrik 28/09/2026, licencia ODbL. Límites 42,9–43,75 N / 7,2–4,45 O; zoom 6–14. Tipografía Noto Sans, SIL OFL 1.1."
val text = "NavFrame ${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")
@@ -769,8 +861,12 @@ open class MainActivity : Activity() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode !in listOf(73, 74) || resultCode != RESULT_OK) return
if (requestCode !in listOf(73, 74, 76) || resultCode != RESULT_OK) return
val uri = data?.data ?: return
if (requestCode == 76) {
if (service == null) pendingImportUri = uri else importRoute(uri)
return
}
showOfflineMaps()
if (requestCode == 74) {
if (offlineTask?.isActive == true) { hint.text = "Ya hay una importación en curso"; return }
@@ -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()
}
}
@@ -5,109 +5,153 @@ import dev.navframe.core.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import kotlin.math.roundToInt
/** Native JPEG overlay, independent of a map SDK so its layout can be verified without GPU access. */
class MapFrameComposer {
suspend fun compose(map: Bitmap?, marker: PointF?, state: NavigationState, mode: NavigationMode, attribution: String, unavailable: Boolean = false, failureCode: String? = null): TftFrame = withContext(Dispatchers.Default) {
require(map == null || (map.width == 480 && map.height == 240)) { "Bitmap dimensions invalid" }
val bitmap = Bitmap.createBitmap(480, 240, Bitmap.Config.ARGB_8888)
require(map == null || (map.width == WIDTH && map.height == HEIGHT)) { "Bitmap dimensions invalid" }
val bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888)
try {
val canvas = Canvas(bitmap)
canvas.drawColor(Color.rgb(13, 19, 25))
map?.let { canvas.drawBitmap(it, 0f, 0f, null) } // Same dimensions: no phone-resolution render or downscale.
map?.let { canvas.drawBitmap(it, 0f, 0f, null) }
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
fun text(value: String, x: Float, y: Float, size: Float, color: Int = Color.WHITE) {
paint.apply { this.color = color; textSize = size; style = Paint.Style.FILL; typeface = Typeface.create("sans-serif", Typeface.BOLD) }
canvas.drawText(value, x, y, paint)
}
fun fitted(value: String, size: Float, width: Float): String {
paint.textSize = size
if (paint.measureText(value) <= width) return value
var result = value
while (result.isNotEmpty() && paint.measureText("$result…") > width) result = result.dropLast(1)
return if (result.isEmpty()) "" else "$result…"
}
val lost = state.navigationStatus == NavigationStatus.GPS_LOST
val approximate = lost && state.accuracyMeters?.let { it.isFinite() && it > AndroidLocationProvider.GUIDANCE_ACCURACY_METERS && it <= AndroidLocationProvider.MAP_ACCURACY_METERS } == true
val accent = Color.rgb(80, 227, 194)
val guidanceVisible = state.route != null && state.navigationStatus != NavigationStatus.ROUTE_PREVIEW
val preview = state.route != null && !guidanceVisible
val topHeight = when { guidanceVisible -> GUIDANCE_HEIGHT; preview -> PREVIEW_HEIGHT; else -> STATUS_HEIGHT }
// Keep navigation cues in one shallow band; let the map occupy the whole center.
paint.color = Color.rgb(7, 12, 17)
canvas.drawRect(0f, 0f, 480f, 27f, paint)
text(if (mode == NavigationMode.MAP_DEMO) "MAPA · DEMO${if (state.route != null) " · RUTA" else " SIMULADO"}" else if (lost) "MAPA GPS · SIN SEÑAL" else if (state.route != null) "MAPA GPS · RUTA CALCULADA" else "MAPA GPS · SIN RUTA", 9f, 20f, 17f, if (lost) Color.YELLOW else accent)
canvas.drawRect(0f, 0f, WIDTH.toFloat(), topHeight.toFloat(), paint)
val modeText = if (mode == NavigationMode.MAP_DEMO) "DEMO" else "GPS"
val routeText = when {
approximate -> "POSICIÓN APROXIMADA"
lost -> "SIN SEÑAL GPS"
unavailable || map == null -> "MAPA NO DISPONIBLE"
state.route != null -> "RUTA"
else -> "MAPA"
}
text("$modeText · $routeText", 8f, 13f, 10f, if (lost || unavailable) Color.YELLOW else accent)
if (guidanceVisible) {
val warning = when {
unavailable || map == null -> "GUIADO EN ESPERA · SIN MAPA"
approximate -> "PRECISIÓN BAJA · guiado en espera"
lost -> "SIN GPS · esperando posición precisa"
state.navigationStatus == NavigationStatus.REROUTING -> "RECALCULANDO · espera nueva ruta"
state.navigationStatus == NavigationStatus.OFF_ROUTE -> "FUERA DE RUTA · revisa el recorrido"
state.navigationStatus == NavigationStatus.ARRIVED -> "HAS LLEGADO AL DESTINO"
else -> null
}
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 maneuver = state.nextManeuver
val direction = maneuverDirection(maneuver?.type).name
canvas.save()
canvas.translate(27f, 33f)
canvas.rotate(if (direction.contains("LEFT")) -90f else if (direction.contains("RIGHT")) 90f else 0f)
paint.apply { style = Paint.Style.STROKE; color = accent; strokeWidth = 6f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
val icon = Path().apply { moveTo(0f, 14f); lineTo(0f, -13f); moveTo(-10f, -3f); lineTo(0f, -13f); lineTo(10f, -3f) }
if (direction == "ARRIVAL") {
canvas.drawLine(-8f, 15f, -8f, -15f, paint)
canvas.drawPath(Path().apply { moveTo(-8f, -15f); lineTo(13f, -9f); lineTo(-8f, -2f) }, paint)
} else if (direction.contains("ROUNDABOUT")) canvas.drawCircle(0f, 0f, 13f, paint)
else if (direction.contains("UTURN") || direction.contains("U_TURN")) {
canvas.drawArc(-12f, -14f, 12f, 11f, 180f, 180f, false, paint)
canvas.drawLine(-12f, -2f, -12f, 15f, paint); canvas.drawLine(12f, -2f, 12f, 15f, paint)
} else if (!imported) canvas.drawPath(icon, paint)
canvas.restore()
paint.strokeCap = Paint.Cap.BUTT
text(fitted(maneuver?.instruction ?: if (imported) "Sigue el trazado GPX" else "Continúa por la ruta", 15f, 392f), 48f, 30f, 15f)
val next = state.distanceToNextManeuverMeters?.let { if (it >= 1000) "%.1f km".format(java.util.Locale.ROOT, it / 1000.0) else "$it m" } ?: "-- m"
text(if (imported) "Sin indicaciones de giro" else next, 48f, 49f, if (imported) 12f else 19f, accent)
}
} 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)
text(fitted(summary, 13f, 460f), 8f, 31f, 13f)
}
if (map != null && marker != null) {
val x = marker.x
val y = marker.y
val arrow = Path().apply { moveTo(x, y - 19); lineTo(x + 14, y + 16); lineTo(x, y + 8); lineTo(x - 14, y + 16); close() }
val x = marker.x; val y = marker.y
val arrow = Path().apply { moveTo(x, y - 16); lineTo(x + 12, y + 13); lineTo(x, y + 7); lineTo(x - 12, y + 13); close() }
paint.apply { color = if (lost) Color.GRAY else Color.WHITE; style = Paint.Style.FILL }
canvas.drawPath(arrow, paint)
paint.apply { color = if (lost) Color.YELLOW else accent; style = Paint.Style.STROKE; strokeWidth = 3f }
paint.apply { color = if (lost) Color.YELLOW else accent; style = Paint.Style.STROKE; strokeWidth = 2.5f }
canvas.drawPath(arrow, paint)
}
if (unavailable || map == null) {
text(if (unavailable) "MAPA NO DISPONIBLE" else "ESPERANDO GPS", 60f, 109f, 27f)
text(if (unavailable) "TFT: ${failureCode ?: "SDK"} · ${if (lost) "SIN GPS" else "Info"}" else "No se usa una posición ficticia", 52f, 149f, 20f)
}
val guidanceVisible = state.route != null && state.navigationStatus != NavigationStatus.ROUTE_PREVIEW
state.route?.let { route ->
paint.style = Paint.Style.FILL
}
if (unavailable || map == null) {
paint.color = Color.rgb(7, 12, 17)
canvas.drawRect(0f, 28f, 480f, if (guidanceVisible) 88f else 51f, paint)
if (!guidanceVisible) text("PREVIA · %.1f km · %d min".format(java.util.Locale.ROOT, route.distanceMeters / 1000.0, (route.durationSeconds + 59) / 60), 9f, 45f, 16f)
else {
val statusText = when {
unavailable || map == null -> "GUIADO EN ESPERA · SIN MAPA"
lost -> "SIN GPS · esperando posición precisa"
state.navigationStatus == NavigationStatus.REROUTING -> "RECALCULANDO · espera nueva ruta"
state.navigationStatus == NavigationStatus.OFF_ROUTE -> "FUERA DE RUTA · revisa el recorrido"
state.navigationStatus == NavigationStatus.ARRIVED -> "HAS LLEGADO AL DESTINO"
else -> null
}
if (statusText != null) text(statusText, 9f, 64f, 20f, if (state.navigationStatus == NavigationStatus.ARRIVED) accent else Color.YELLOW)
else {
val maneuver = state.nextManeuver
val direction = maneuverDirection(maneuver?.type).name
canvas.save()
canvas.translate(40f, 61f)
canvas.rotate(if (direction.contains("LEFT")) -90f else if (direction.contains("RIGHT")) 90f else 0f)
paint.apply { style = Paint.Style.STROKE; color = accent; strokeWidth = 7f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
val icon = Path().apply { moveTo(0f, 19f); lineTo(0f, -18f); moveTo(-13f, -5f); lineTo(0f, -18f); lineTo(13f, -5f) }
if (direction == "ARRIVAL") { canvas.drawLine(-10f, 20f, -10f, -20f, paint); val flag = Path().apply { moveTo(-10f, -20f); lineTo(17f, -12f); lineTo(-10f, -3f) }; canvas.drawPath(flag, paint) }
else if (direction.contains("ROUNDABOUT")) canvas.drawCircle(0f, 1f, 16f, paint)
else if (direction.contains("UTURN") || direction.contains("U_TURN")) { canvas.drawArc(-15f, -17f, 15f, 13f, 180f, 180f, false, paint); canvas.drawLine(-15f, -2f, -15f, 19f, paint); canvas.drawLine(15f, -2f, 15f, 19f, paint) }
else canvas.drawPath(icon, paint)
canvas.restore()
paint.strokeCap = Paint.Cap.BUTT
var instruction = maneuver?.instruction ?: "Continúa por la ruta"
paint.textSize = 18f
while (instruction.isNotEmpty() && paint.measureText(instruction) > 384f) instruction = instruction.dropLast(1)
text(instruction, 81f, 49f, 18f)
val next = state.distanceToNextManeuverMeters?.let { if (it >= 1000) "%.1f km".format(java.util.Locale.ROOT, it / 1000.0) else "$it m" } ?: "-- m"
text(next, 81f, 79f, 28f, accent)
}
}
canvas.drawRect(36f, 78f, 444f, 132f, paint)
text(if (unavailable) "MAPA NO DISPONIBLE" else "ESPERANDO GPS", 50f, 101f, 21f)
text(if (unavailable) "TFT: ${failureCode ?: "SDK"} · ${if (lost) "SIN GPS" else "Comprueba fuente"}" else "No se usa una posición ficticia", 50f, 121f, 13f)
}
// Wrap rather than clipping a custom provider's mandatory credits.
paint.typeface = Typeface.DEFAULT
paint.textSize = 12f
val lines = mutableListOf<String>()
var line = ""
for (character in attribution.trim().replace(Regex("\\s+"), " ")) {
val next = line + character
if (line.isNotEmpty() && paint.measureText(next) > 464f) { lines += line.trim(); line = character.toString() }
else line = next
}
if (line.isNotEmpty()) lines += line
val footer = (240f - lines.size * 15f - if (guidanceVisible) 55f else 34f).coerceAtLeast(27f)
// Credits stay visible, but consume only their actual wrapped lines.
val creditPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE; textSize = CREDIT_SIZE; typeface = Typeface.DEFAULT }
val credits = wrap(attribution, creditPaint, WIDTH - 16f)
val footerDataHeight = if (guidanceVisible) FOOTER_DATA_HEIGHT else 0
val footerHeight = footerDataHeight + credits.size * CREDIT_LINE_HEIGHT
val footer = (HEIGHT - footerHeight).coerceAtLeast(topHeight + MIN_MAP_HEIGHT)
paint.apply { color = Color.rgb(7, 12, 17); style = Paint.Style.FILL }
canvas.drawRect(0f, footer, 480f, 240f, paint)
val speed = if (lost || unavailable || map == null) "-- km/h" else "${(state.speed * 3.6f).roundToInt()} km/h"
text(speed, 9f, footer + 24f, 23f)
val heading = if (lost || unavailable || map == null || !state.bearing.isFinite()) "--" else state.bearing.roundToInt().toString()
text("Rumbo $heading°", 182f, footer + 24f, 20f)
text(if (mode == NavigationMode.MAP_DEMO) "DEMO" else "GPS", 393f, footer + 24f, 19f, accent)
canvas.drawRect(0f, footer.toFloat(), WIDTH.toFloat(), HEIGHT.toFloat(), paint)
if (guidanceVisible) {
val valid = !lost && !unavailable && map != null && state.navigationStatus in setOf(NavigationStatus.NAVIGATING, NavigationStatus.ARRIVED)
val remaining = if (valid) state.remainingDistanceMeters?.let { "%.1f km restantes".format(java.util.Locale.ROOT, it / 1000.0) } ?: "Restante --" else "Restante --"
val eta = if (valid) state.etaEpochMillis?.let { java.text.SimpleDateFormat("HH:mm", java.util.Locale.ROOT).format(java.util.Date(it)) } ?: "--:--" else "--:--"
text(remaining, 9f, footer + 44f, 17f)
text("ETA $eta", 285f, footer + 44f, 17f)
// Speed and heading already occupy the Yamaha instrument panel; keep only trip data here.
text(fitted(remaining, 12f, 340f), 8f, footer + 14f, 12f)
text("ETA $eta", 397f, footer + 14f, 12f)
}
credits.forEachIndexed { index, credit ->
canvas.drawText(credit, 8f, footer + footerDataHeight + (index + 1) * CREDIT_LINE_HEIGHT.toFloat() - 2f, creditPaint)
}
paint.apply { textSize = 12f; typeface = Typeface.DEFAULT; color = Color.WHITE }
lines.forEachIndexed { index, credit -> canvas.drawText(credit, 8f, footer + (if (guidanceVisible) 67f else 46f) + index * 15f, paint) }
val bytes = ByteArrayOutputStream().use { out -> check(bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out)); out.toByteArray() }
TftFrame(encodedBytes = bytes, timestampMs = System.currentTimeMillis())
} finally { bitmap.recycle() }
}
private fun wrap(value: String, paint: Paint, maxWidth: Float): List<String> {
val lines = mutableListOf<String>()
var line = ""
for (character in value.trim().replace(Regex("\\s+"), " ")) {
val next = line + character
if (line.isNotEmpty() && paint.measureText(next) > maxWidth) { lines += line.trim(); line = character.toString() }
else line = next
}
if (line.isNotEmpty()) lines += line
return lines.ifEmpty { listOf("") }
}
companion object {
const val WIDTH = 480
const val HEIGHT = 240
const val GUIDANCE_HEIGHT = 50
const val PREVIEW_HEIGHT = 36
const val STATUS_HEIGHT = 20
const val MIN_MAP_HEIGHT = 88
private const val FOOTER_DATA_HEIGHT = 18
private const val CREDIT_SIZE = 8.5f
private const val CREDIT_LINE_HEIGHT = 10
}
}
@@ -9,6 +9,7 @@ import android.text.Html
import dev.navframe.core.*
import kotlinx.coroutines.*
import org.maplibre.android.MapLibre
import org.maplibre.android.net.ConnectivityReceiver
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.Style
@@ -32,6 +33,21 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
private var closed = false
private var stage = MapRenderStage.INITIALIZE
private var capturedOnce = false
private var lastNetworkState: Boolean? = null
internal val networkConnected: Boolean? get() = lastNetworkState
private val connectivity = TftMapConnectivity(
acquire = { ConnectivityReceiver.instance(this.context).activate() },
refresh = {
val receiver = ConnectivityReceiver.instance(this.context)
receiver.setConnected(null)
val connected = receiver.isConnected
if (lastNetworkState != connected) {
lastNetworkState = connected
android.util.Log.d("NavFrame", "TFT_MAP_NETWORK connected=$connected")
}
},
release = { ConnectivityReceiver.instance(this.context).deactivate() },
)
private fun phase(value: MapRenderStage) { stage = value; reportStage(value) }
private data class Raster(val bitmap: Bitmap, val marker: PointF, val attribution: String)
override suspend fun render(state: NavigationState) = render(state, NavigationMode.MAP_GPS)
@@ -50,10 +66,14 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
private suspend fun capture(state: NavigationState): Raster = suspendCancellableCoroutine { continuation ->
phase(MapRenderStage.INITIALIZE)
MapLibre.getInstance(context)
// MapSnapshotter owns FileSource activation, but unlike MapView it does not own
// ConnectivityReceiver. Keep network notifications alive when the phone map stops
// (including screen off) and initialize from the current network, not a stale event.
connectivity.refresh()
val position = LatLng(state.position.latitude, state.position.longitude)
val camera = TftCameraPolicy().parameters(state)
val cameraPosition = CameraPosition.Builder().target(position).zoom(camera.zoom)
.bearing(camera.bearingDegrees.toDouble()).padding(0.0, 70.0, 0.0, 0.0).build()
.bearing(camera.bearingDegrees.toDouble()).padding(0.0, 50.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() })
@@ -117,8 +137,12 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
/** Must be called on Main, just as the snapshotter was created there. */
fun close() {
check(Looper.myLooper() == Looper.getMainLooper())
if (closed) return
closed = true
snapshotter?.cancel()
snapshotter = null
try { snapshotter?.cancel() }
finally {
snapshotter = null
connectivity.close()
}
}
}
@@ -0,0 +1,29 @@
package dev.navframe.app
/** An independent SDK network lease: stopping the phone MapView must not stop TFT updates. */
internal class TftMapConnectivity(
private val acquire: () -> Unit,
private val refresh: () -> Unit,
private val release: () -> Unit,
) : AutoCloseable {
private var active = false
private var closed = false
fun refresh() {
check(!closed)
if (!active) {
acquire()
active = true
}
refresh.invoke()
}
override fun close() {
if (closed) return
closed = true
if (active) {
active = false
release()
}
}
}
@@ -52,7 +52,7 @@ class TftService : Service() {
private var latestNavigationState = NavigationState()
set(value) {
field = value; mutableNavigationState.value = value
if (shownRoute?.demo == false && !routePreview) voice?.update(value)
if (shownRoute?.demo == false && !routePreview && value.route?.imported != true) voice?.update(value)
else voice?.reset()
}
private var voice: NavigationVoiceController? = null
@@ -68,9 +68,12 @@ class TftService : Service() {
private val mutableVoiceStatus = MutableStateFlow("Voz: preparando motor español")
val voiceStatus = mutableVoiceStatus.asStateFlow()
private var mapRenderer: MapLibreTftRenderer? = null
private var lastMapNetworkConnected: Boolean? = null
private val mutableMapDiagnostic = MutableStateFlow("TFT MAP · sin captura")
val mapDiagnostic = mutableMapDiagnostic.asStateFlow()
private var lastMapFailureDiagnostic = "sin fallo registrado"
private val mapDiagnosticHistory by lazy { MapDiagnosticHistory(applicationContext) }
private var mapHistoryWriteFailed = false
private var mapRenderStarted = 0L
private var mapRenderStage = MapRenderStage.INITIALIZE
private var mapRetryAt = 0L
@@ -443,7 +446,7 @@ class TftService : Service() {
if (lost && state.navigationStatus != NavigationStatus.GPS_LOST) {
state = state.copy(speed = 0f, bearing = Float.NaN, navigationStatus = NavigationStatus.GPS_LOST, accuracyMeters = null)
}
state = withRoute(state, false)
state = withRoute(state, false).copy(bearing = provider.currentBearing)
latestNavigationState = state
checkSpeedCameras(state, now)
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && reroutePolicy.shouldRequest(state, now)) requestReroute(false)
@@ -573,6 +576,17 @@ class TftService : Service() {
if (generation == preparedGeneration && routePreview) publishFrame(frame)
}
}
/** Import never contacts a routing server or replaces active guidance before Start. */
fun prepareImportedRoute(imported: ImportedRoute) {
require(imported.route.imported && imported.route.maneuvers.isEmpty())
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)
if (!hasActiveGuidance()) showPreparedPreview()
}
fun preparedRouteIsImported() = hasPreparedRoute() && routePlan?.route?.imported == true
fun hasPreparedRoute() = !preparedDestinationDirty && routePlan != null
fun routeUsesGps() = !preparedDestinationDirty && routePlan?.demo == false
fun startRoute(preview: Boolean = false) {
@@ -583,7 +597,7 @@ class TftService : Service() {
}
if (preparedDestinationDirty) { mutableRouteInfo.value = "Destino cambiado · calcula una nueva ruta primero."; return }
val plan = routePlan ?: run { mutableRouteInfo.value = "Calcula una ruta primero."; return }
if (!preview && !plan.demo && !hasFreshGpsFix()) { mutableRouteInfo.value = "Espera GPS reciente y preciso antes de iniciar guiado"; return }
if (!preview && !plan.demo && !hasGuidanceGpsFix()) { mutableRouteInfo.value = "Espera GPS reciente y preciso antes de iniciar guiado"; return }
shownRoute = plan
routePreview = preview
guidance = RouteGuidanceTracker(plan.route)
@@ -593,6 +607,10 @@ class TftService : Service() {
rerouteFailures = 0
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)
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)
}
fun stopRoute() {
@@ -631,6 +649,10 @@ class TftService : Service() {
fun requestReroute(manual: Boolean = true) {
val plan = shownRoute ?: return
if (plan.route.imported) {
if (manual) mutableRouteInfo.value = "Ruta GPX · vuelve al trazado; no se modifica ni recalcula la ruta importada."
return
}
if (plan.demo || routePreview || rerouteJob?.isActive == true) return
val now = SystemClock.elapsedRealtime()
val fix = lastGpsFix
@@ -676,7 +698,7 @@ class TftService : Service() {
}
private fun isMapMode(mode: NavigationMode) = mode == NavigationMode.MAP_DEMO || mode == NavigationMode.MAP_GPS
private fun createScheduler(mode: NavigationMode) = if (isMapMode(mode)) RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, movingMaxFps = 1.0, turningMaxFps = 1.0, positionDeltaMeters = 5.0, bearingDeltaDegrees = 5f)) else RenderScheduler()
private fun createScheduler(mode: NavigationMode) = if (isMapMode(mode)) RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, movingMaxFps = 1.0, turningMaxFps = 1.0, positionDeltaMeters = 5.0, bearingDeltaDegrees = 5f, redrawStationaryBearing = true)) else RenderScheduler()
fun mapSource(): TileSource {
val preferences = getSharedPreferences("map", MODE_PRIVATE)
@@ -693,11 +715,16 @@ class TftService : Service() {
val fix = lastGpsFix
val accuracy = when { fix == null -> "SIN FIX"; !fix.accuracyMeters.isFinite() -> "DESCONOCIDA"; fix.accuracyMeters <= 5 -> "0–5 m"; fix.accuracyMeters <= 15 -> "6–15 m"; fix.accuracyMeters <= 25 -> "16–25 m"; else -> ">25 m" }
val age = if (fix == null) "SIN FIX" else if (SystemClock.elapsedRealtime() - lastGpsElapsed <= 15_000) "RECIENTE" else "CADUCADO"
return "NavFrame 0.13.0 · Android ${Build.VERSION.SDK_INT} · ${Build.MANUFACTURER} ${Build.MODEL}\nMapLibre OpenGL 13.5.2 · TFT nativo 480×240\nOrigen del mapa: $origin\n${mutableMapDiagnostic.value}\nÚltimo fallo: $lastMapFailureDiagnostic\nGPS: $age · precisión $accuracy · ${mutableNavigationState.value.navigationStatus}\nTFT: ${mutableState.value} · modo ${mutableMode.value}\nSin coordenadas, consultas, direcciones ni URLs."
val network = when (mapRenderer?.networkConnected ?: lastMapNetworkConnected) { true -> "CONECTADA"; false -> "SIN CONEXIÓN"; null -> "SIN COMPROBAR" }
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
fun hasFreshGpsFix(): Boolean = lastGpsFix?.let { it.accuracyMeters.isFinite() && it.accuracyMeters <= 25 && SystemClock.elapsedRealtime() - lastGpsElapsed in 0..15_000 && (locationProvider?.providerEnabled?.value == true || (phoneVisible && visibleGpsProvider?.providerEnabled?.value == true)) } == true
fun hasFreshGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.MAP_ACCURACY_METERS)
fun usesCompassHeading(): Boolean = (locationProvider ?: visibleGpsProvider)?.headingFromCompass == true
fun hasGuidanceGpsFix(): Boolean = usableGpsFix(AndroidLocationProvider.GUIDANCE_ACCURACY_METERS)
private fun usableGpsFix(maxAccuracy: Float): Boolean = lastGpsFix?.let { it.accuracyMeters.isFinite() && it.accuracyMeters in 0f..maxAccuracy && SystemClock.elapsedRealtime() - lastGpsElapsed in 0..15_000 && (locationProvider?.providerEnabled?.value == true || (phoneVisible && visibleGpsProvider?.providerEnabled?.value == true)) } == true
private fun stopVisibleGps() {
visibleGpsJob?.cancel(); visibleGpsJob = null
try { visibleGpsProvider?.close() } catch (_: SecurityException) { }
@@ -720,13 +747,17 @@ class TftService : Service() {
lastGpsFix = fix; lastGpsElapsed = provider.lastFixElapsedMs
mutableGpsReady.value = hasFreshGpsFix()
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) {
latestNavigationState = latestNavigationState.copy(position = fix.position, bearing = fix.bearing, speed = fix.speedMetersPerSecond, accuracyMeters = fix.accuracyMeters, navigationStatus = if (routePreview && shownRoute != null) NavigationStatus.ROUTE_PREVIEW else if (fix.accuracyMeters <= 25) NavigationStatus.NAVIGATING else NavigationStatus.GPS_LOST)
latestNavigationState = latestNavigationState.copy(position = fix.position, bearing = fix.bearing, speed = fix.speedMetersPerSecond, accuracyMeters = fix.accuracyMeters, navigationStatus = if (routePreview && shownRoute != null) NavigationStatus.ROUTE_PREVIEW else if (fix.accuracyMeters <= AndroidLocationProvider.MAP_ACCURACY_METERS) NavigationStatus.NAVIGATING else NavigationStatus.GPS_LOST)
}
} }
launch { provider.bearings.collect { bearing ->
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(bearing = bearing)
} }
provider.start()
while (isActive) {
mutableGpsReady.value = hasFreshGpsFix()
if (!gpsRequested && (!provider.providerEnabled.value || SystemClock.elapsedRealtime() - provider.lastFixElapsedMs > 15_000) && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(speed = 0f, bearing = Float.NaN, navigationStatus = NavigationStatus.GPS_LOST)
if (!gpsRequested && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(bearing = provider.currentBearing)
if (!gpsRequested && (!provider.providerEnabled.value || SystemClock.elapsedRealtime() - provider.lastFixElapsedMs > 15_000) && mutableMode.value !in listOf(NavigationMode.MAP_DEMO, NavigationMode.DEMO)) latestNavigationState = latestNavigationState.copy(speed = 0f, bearing = Float.NaN, accuracyMeters = null, navigationStatus = NavigationStatus.GPS_LOST)
delay(1_000)
}
}
@@ -763,12 +794,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
@@ -777,12 +810,13 @@ 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
mapFailures = (mapFailures + 1).coerceAtMost(4)
@@ -792,7 +826,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) {
@@ -0,0 +1,145 @@
package dev.navframe.app
import android.Manifest
import android.hardware.Sensor
import android.hardware.SensorManager
import android.location.Location
import android.location.LocationManager
import android.os.Looper
import android.os.SystemClock
import dev.navframe.core.*
import kotlinx.coroutines.runBlocking
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.ShadowSensor
import org.robolectric.shadows.ShadowSensorManager
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@LooperMode(LooperMode.Mode.PAUSED)
class AndroidLocationProviderTest {
private val context get() = RuntimeEnvironment.getApplication()
private val manager get() = context.getSystemService(LocationManager::class.java)
@Before fun permissions() {
shadowOf(context).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
shadowOf(manager).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)
}
private fun fix(provider: String = LocationManager.GPS_PROVIDER, accuracy: Float = 7f, ageMs: Long = 0) = Location(provider).apply {
latitude = 43.36; longitude = -5.85; this.accuracy = accuracy; time = 1000
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos() - ageMs * 1_000_000
}
private fun tick() { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) }
@Test fun recentNetworkCacheIsAvailableImmediatelyAndAllListenersAreReleased() = runBlocking {
shadowOf(manager).setLastKnownLocation(LocationManager.NETWORK_PROVIDER, fix(LocationManager.NETWORK_PROVIDER, 60f))
val provider = AndroidLocationProvider(context)
try {
provider.start()
assertEquals(60f, provider.locations.replayCache.single().accuracyMeters)
assertTrue(shadowOf(manager).getLocationUpdateListeners(LocationManager.GPS_PROVIDER).isNotEmpty())
assertTrue(shadowOf(manager).getLocationUpdateListeners(LocationManager.NETWORK_PROVIDER).isNotEmpty())
} finally { provider.close() }
assertTrue(shadowOf(manager).locationUpdateListeners.isEmpty())
assertFalse(provider.providerEnabled.value)
}
@Test fun staleInvalidAndFutureCachedFixesAreRejected() = runBlocking {
for (location in listOf(fix(ageMs = 15_001), fix(ageMs = -1000), fix().apply { latitude = 91.0 }, fix().apply { accuracy = Float.NaN })) {
shadowOf(manager).setLastKnownLocation(LocationManager.GPS_PROVIDER, location)
val provider = AndroidLocationProvider(context)
try { provider.start(); assertTrue(provider.locations.replayCache.isEmpty()) }
finally { provider.close() }
}
}
@Test fun coarseNetworkUpdatesCannotReplaceARecentAccurateFix() = runBlocking {
val provider = AndroidLocationProvider(context)
try {
provider.start()
shadowOf(manager).simulateLocation(fix()); tick()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(6))
shadowOf(manager).simulateLocation(fix(LocationManager.NETWORK_PROVIDER, 500f).apply { latitude = 43.4 }); tick()
assertEquals(7f, provider.locations.replayCache.single().accuracyMeters)
assertEquals(43.36, provider.locations.replayCache.single().position.latitude, 0.000001)
} finally { provider.close() }
}
@Test fun disablingOneProviderDoesNotInvalidateTheOtherAndPassiveAloneIsNotReady() = runBlocking {
val provider = AndroidLocationProvider(context)
try {
provider.start()
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, false); tick()
assertTrue(provider.providerEnabled.value)
shadowOf(manager).setProviderEnabled(LocationManager.NETWORK_PROVIDER, false); tick()
if ("fused" in manager.allProviders) { shadowOf(manager).setProviderEnabled("fused", false); tick() }
assertFalse(provider.providerEnabled.value)
} finally { provider.close() }
}
@Test fun serviceAllowsApproximateRecentPositionForMapWithoutClaimingPreciseGuidance() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
try {
service.setPhoneVisible(true); tick()
shadowOf(manager).simulateLocation(fix(LocationManager.NETWORK_PROVIDER, 80f)); tick()
assertTrue(service.hasFreshGpsFix())
assertTrue(service.gpsReady.value)
assertEquals(80f, service.navigationState.value.accuracyMeters)
assertEquals(NavigationStatus.NAVIGATING, service.navigationState.value.navigationStatus)
val route = RouteResult(listOf(GeoPoint(43.36, -5.85), GeoPoint(43.37, -5.85)), emptyList(), 1100, 100)
assertEquals(NavigationStatus.GPS_LOST, RouteGuidanceTracker(route).update(LocationFix(GeoPoint(43.36, -5.85), Float.NaN, 0f, 80f, 1000), 0, 0).navigationStatus)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(16))
assertFalse(service.hasFreshGpsFix())
assertEquals(NavigationStatus.GPS_LOST, service.navigationState.value.navigationStatus)
assertNull(service.navigationState.value.accuracyMeters)
service.setPhoneVisible(false); tick()
assertFalse(service.hasFreshGpsFix())
} finally { controller.destroy() }
}
@Test fun compassDrivesStationaryHeadingButMovingGpsWinsAndSensorsStopOnClose() = runBlocking {
val sensors = context.getSystemService(SensorManager::class.java)
val sensor = ShadowSensor.newInstance(Sensor.TYPE_ROTATION_VECTOR)
shadowOf(sensors).addSensor(sensor)
val provider = AndroidLocationProvider(context)
try {
provider.start()
val event = ShadowSensorManager.createSensorEvent(4).apply {
this.sensor = sensor; accuracy = SensorManager.SENSOR_STATUS_ACCURACY_HIGH
values[0] = 0f; values[1] = 0f; values[2] = 0f; values[3] = 1f
}
shadowOf(sensors).sendSensorEventToListeners(event); tick()
assertTrue(provider.currentBearing.isFinite())
assertTrue(provider.headingFromCompass)
shadowOf(manager).simulateLocation(fix().apply { speed = 12f; bearing = 90f }); tick()
assertEquals(90f, provider.currentBearing)
assertFalse(provider.headingFromCompass)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
shadowOf(manager).simulateLocation(fix().apply { speed = 0f; bearing = 90f }); tick()
assertTrue(provider.headingFromCompass)
event.accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE
shadowOf(sensors).sendSensorEventToListeners(event); tick()
assertTrue(provider.currentBearing.isNaN())
} finally { provider.close() }
assertTrue(shadowOf(sensors).listeners.isEmpty())
}
@Test fun headingSelectionAndSmoothingRespectNorthWrapAndMissingSensors() {
assertEquals(90f, selectHeading(90f, 12f, 180f))
assertEquals(180f, selectHeading(90f, 0f, 180f))
assertTrue(selectHeading(90f, 0f, Float.NaN).isNaN())
assertTrue(selectHeading(Float.NaN, 12f, Float.NaN).isNaN())
assertEquals(354f, smoothHeading(350f, 10f))
assertEquals(6f, smoothHeading(10f, 350f))
}
}
@@ -0,0 +1,200 @@
package dev.navframe.app
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
import android.os.SystemClock
import dev.navframe.core.*
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@LooperMode(LooperMode.Mode.PAUSED)
class 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())
private fun tick() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
private fun field(name: String) = MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true }
@Test fun importedPreviewRequiresGpsAndStartsWithoutRoutingOrRerouting() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
service.routingEngineFactory = { error("Imported routes must not use a server") }
try {
val route = imported()
service.prepareImportedRoute(route); tick()
assertTrue(service.preparedRouteIsImported())
assertTrue(service.routeUsesGps())
assertEquals(NavigationStatus.ROUTE_PREVIEW, service.navigationState.value.navigationStatus)
assertSame(route.route, service.navigationState.value.route)
service.startRoute(); tick()
assertFalse(service.hasActiveGuidance())
assertTrue(service.routeInfo.value.contains("GPS reciente"))
val application = RuntimeEnvironment.getApplication()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
val manager = application.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
service.setPhoneVisible(true); tick()
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 43.36; longitude = -5.85; accuracy = 3f
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
assertTrue(service.hasFreshGpsFix())
service.startRoute(); tick()
assertTrue(service.hasActiveGuidance())
assertSame(route.route, service.navigationState.value.route)
service.requestReroute(); tick()
assertTrue(service.routeInfo.value.contains("no se modifica"))
assertSame(route.route, service.navigationState.value.route)
assertNull(service.navigationState.value.nextManeuver)
assertNull(service.navigationState.value.etaEpochMillis)
service.stopRoute(); tick()
assertFalse(service.hasActiveGuidance())
assertFalse(service.hasPreparedRoute())
assertNull(service.navigationState.value.route)
} finally { controller.destroy() }
}
@Test fun filePickerUsesSafAndCancelKeepsThePreparedRoute() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
field("service").set(activity, service)
service.prepareImportedRoute(imported()); tick()
MainActivity::class.java.getDeclaredMethod("chooseRouteFile").apply { isAccessible = true }.invoke(activity)
val request = shadowOf(activity).nextStartedActivityForResult
assertEquals(Intent.ACTION_OPEN_DOCUMENT, request.intent.action)
assertTrue(request.intent.hasCategory(Intent.CATEGORY_OPENABLE))
MainActivity::class.java.getDeclaredMethod("onActivityResult", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Intent::class.java)
.apply { isAccessible = true }.invoke(activity, 76, Activity.RESULT_CANCELED, null)
assertTrue(service.preparedRouteIsImported())
assertFalse(service.hasActiveGuidance())
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun importedStartRequestsFineLocationAndDenialNeverStartsNavigation() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
shadowOf(RuntimeEnvironment.getApplication()).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
field("service").set(activity, service)
service.prepareImportedRoute(imported()); tick()
val actionClass = Class.forName("dev.navframe.app.MainActivity\$Action")
val action = actionClass.enumConstants.first { (it as Enum<*>).name == "IMPORT_ROUTE" }
MainActivity::class.java.getDeclaredMethod("withPermissions", actionClass).apply { isAccessible = true }.invoke(activity, action)
assertNotNull(field("pendingAction").get(activity))
activity.onRequestPermissionsResult(42, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), intArrayOf(android.content.pm.PackageManager.PERMISSION_DENIED))
tick()
assertFalse(service.hasActiveGuidance())
assertTrue(service.preparedRouteIsImported())
assertTrue((field("hint").get(activity) as android.widget.TextView).text.contains("Permiso denegado"))
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun validDocumentAutomaticallyRequestsNavigationPermissionAndInvalidDocumentPreservesTrace() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
fun importDocument(xml: String) {
val uri = android.net.Uri.parse("content://test/route.gpx")
shadowOf(activity.contentResolver).registerInputStream(uri, xml.byteInputStream())
MainActivity::class.java.getDeclaredMethod("onActivityResult", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Intent::class.java)
.apply { isAccessible = true }.invoke(activity, 76, Activity.RESULT_OK, Intent().setData(uri))
val job = field("importJob").get(activity) as kotlinx.coroutines.Job
for (attempt in 0..200) { if (job.isCompleted) break; Thread.sleep(5); tick() }
assertTrue("Document import should finish", job.isCompleted)
}
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>""")
assertTrue(service.preparedRouteIsImported())
assertEquals("IMPORT_ROUTE", (field("pendingAction").get(activity) as Enum<*>).name)
assertFalse(service.hasActiveGuidance())
val oldRoute = service.navigationState.value.route
importDocument("<gpx><rte><rtept lat=\"NaN\" lon=\"0\"/></rte></gpx>")
assertSame(oldRoute, service.navigationState.value.route)
assertTrue((field("hint").get(activity) as android.widget.TextView).text.contains("coordenadas inválidas"))
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun closingImportedPanelCancelsThePendingGpsStart() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
field("service").set(activity, service)
service.prepareImportedRoute(imported()); tick()
MainActivity::class.java.getDeclaredMethod("showImportedRouteSheet", String::class.java).apply { isAccessible = true }.invoke(activity, "Test")
MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity)
val pending = field("positionWait").get(activity) as kotlinx.coroutines.Job
assertTrue(pending.isActive)
org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog().dismiss(); tick()
assertTrue(pending.isCancelled)
assertFalse(service.hasActiveGuidance())
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun importedStartWaitsForGuidanceAccuracyEvenWhenMapReadinessStaysTrue() {
val activityController = Robolectric.buildActivity(PhoneWithoutGpu::class.java).create()
val serviceController = Robolectric.buildService(TftService::class.java).create()
val activity = activityController.get()
val service = serviceController.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
val application = RuntimeEnvironment.getApplication()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
field("service").set(activity, service)
val manager = application.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
service.prepareImportedRoute(imported()); tick()
service.setPhoneVisible(true); tick()
fun fix(accuracy: Float) {
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 43.36; longitude = -5.85; this.accuracy = accuracy
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
})
tick()
}
fix(80f)
assertTrue(service.gpsReady.value)
assertTrue(service.hasFreshGpsFix())
assertFalse(service.hasGuidanceGpsFix())
MainActivity::class.java.getDeclaredMethod("startImportedRoute").apply { isAccessible = true }.invoke(activity)
val pending = field("positionWait").get(activity) as kotlinx.coroutines.Job
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(600))
assertTrue(pending.isActive)
assertNull(shadowOf(activity).nextStartedService)
assertFalse(service.hasActiveGuidance())
fix(20f)
assertTrue(service.gpsReady.value)
assertTrue(service.hasGuidanceGpsFix())
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(400))
assertTrue(pending.isCompleted)
assertEquals(TftService.ACTION_ROUTE_GPS, shadowOf(activity).nextStartedService.action)
} finally { activityController.destroy(); serviceController.destroy() }
}
}
@@ -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>(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")
}
}
@@ -37,6 +37,21 @@ class MapFrameComposerTest {
try { assertEquals(480, decoded.width); assertTrue(Color.red(decoded.getPixel(20, 50)) < 25) }
finally { decoded.recycle() }
}
@Test fun guidedLayoutReservesMoreOfTheTftForTheMap() = runBlocking {
val map = Bitmap.createBitmap(480, 240, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.rgb(44, 60, 76)) }
try {
val route = RouteResult(listOf(GeoPoint(43.36, -5.85), GeoPoint(43.365, -5.845)), emptyList(), 12000, 900)
val state = NavigationState(route = route, nextManeuver = Maneuver("Gira a la derecha", 400, 10, 0, 1, 20),
distanceToNextManeuverMeters = 400, navigationStatus = NavigationStatus.NAVIGATING)
val decoded = decode(MapFrameComposer().compose(map, PointF(240f, 145f), state, NavigationMode.MAP_GPS, ConfiguredMapDataSource.DEFAULT_ATTRIBUTION))
try {
assertEquals(480, decoded.width); assertEquals(240, decoded.height)
assertTrue("Map should begin immediately below the compact maneuver band", Color.red(decoded.getPixel(10, 56)) > 35)
assertTrue("Map should remain visible almost to the compact footer", Color.red(decoded.getPixel(10, 205)) > 35)
assertTrue("Footer should start below the enlarged map viewport", Color.red(decoded.getPixel(250, 225)) < 25)
} finally { decoded.recycle() }
} finally { map.recycle() }
}
@Test fun longAttributionRemainsInsideFrameAndUsesMultipleLines() = runBlocking {
val frame = MapFrameComposer().compose(null, null, NavigationState(), NavigationMode.MAP_GPS, "© Example map provider and its contributors · OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors")
val decoded = decode(frame)
@@ -0,0 +1,39 @@
package dev.navframe.app
import org.junit.Assert.*
import org.junit.Test
class TftMapConnectivityTest {
@Test fun phoneStoppingLeavesTftNetworkLeaseActiveAndRefreshesCurrentNetwork() {
var sdkReferences = 1 // The visible phone MapView already owns a lease.
var actualNetwork = false
var observedNetwork: Boolean? = null
val lease = TftMapConnectivity({ sdkReferences++ }, { observedNetwork = actualNetwork }, { sdkReferences-- })
lease.refresh()
assertEquals(false, observedNetwork)
sdkReferences-- // Screen turns off: MapView.onStop releases the phone lease.
actualNetwork = true // Mobile data recovers while the phone map is stopped.
lease.refresh()
assertEquals(true, observedNetwork)
assertEquals(1, sdkReferences)
lease.close()
lease.close()
assertEquals(0, sdkReferences)
}
@Test fun failedRefreshStillReleasesAcquiredSdkLease() {
var references = 0
val lease = TftMapConnectivity({ references++ }, { error("network service unavailable") }, { references-- })
try { lease.refresh(); fail("Expected refresh failure") } catch (_: IllegalStateException) { }
assertEquals(1, references)
lease.close()
assertEquals(0, references)
}
@Test fun closingUnusedRendererDoesNotReleasePhoneLease() {
var references = 1
val lease = TftMapConnectivity({ references++ }, { }, { references-- })
lease.close()
assertEquals(1, references)
}
}
@@ -0,0 +1,106 @@
package dev.navframe.app
import android.Manifest
import android.location.Location
import android.location.LocationManager
import android.os.Looper
import android.os.SystemClock
import dev.navframe.core.*
import kotlinx.coroutines.CompletableDeferred
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@LooperMode(LooperMode.Mode.PAUSED)
class TftServiceRerouteTest {
@Test fun reliableFixesMovingBackAlongOldRoadRequestRouteFromCurrentPositionAndResumeGuidance() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
val manager = service.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
val destination = GeoPoint(0.0, 0.02)
val original = RouteResult(listOf(GeoPoint(0.0, 0.0), destination), emptyList(), 2224, 180)
val pendingReroute = CompletableDeferred<RouteResult>()
val options = RouteOptions(RouteProfile.AVOID_UNPAVED, avoidMotorways = true)
var calculations = 0
var rerouteOrigin: GeoPoint? = null
var rerouteOptions: RouteOptions? = null
service.routingEngineFactory = { object : RoutingEngine {
override suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult {
calculations++
if (calculations == 1) return original
rerouteOrigin = origin
rerouteOptions = options
return pendingReroute.await()
}
override suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions) = error("Unexpected routing API")
} }
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
fun tick(millis: Long = 100) { shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(millis)) }
fun awaitNavigationStatus(expected: NavigationStatus) {
// The initial no-fix frame is encoded on Dispatchers.Default; draining only the
// Android looper does not wait for that worker to resume the service loop.
val deadline = System.nanoTime() + 3_000_000_000L
while (service.navigationState.value.navigationStatus != expected && System.nanoTime() < deadline) {
Thread.sleep(10)
tick(10)
}
assertEquals(service.diagnosticReport() + "\n" + service.routeInfo.value,
expected, service.navigationState.value.navigationStatus)
}
var timestamp = 0L
fun position(longitude: Double, accuracy: Float = 5f) {
timestamp += 1000
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
latitude = 0.0; this.longitude = longitude; this.accuracy = accuracy
speed = 12f; bearing = 270f; time = timestamp
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
})
tick()
val deadline = System.nanoTime() + 3_000_000_000L
while (service.navigationState.value.position.longitude != longitude && System.nanoTime() < deadline) {
Thread.sleep(10)
tick(10)
}
assertEquals(service.diagnosticReport(), longitude, service.navigationState.value.position.longitude, 0.0)
}
try {
service.setPhoneVisible(true); tick()
position(0.01)
service.calculateRoute(destination, false, "https://example.test/route", options); tick()
service.startRoute(); tick(600)
position(0.01)
tick(1000)
position(0.01)
awaitNavigationStatus(NavigationStatus.NAVIGATING)
for (longitude in listOf(0.0098, 0.0095, 0.0092, 0.0089, 0.0086, 0.0083, 0.0080)) {
tick(1500)
position(longitude)
}
awaitNavigationStatus(NavigationStatus.REROUTING)
assertEquals(2, calculations)
assertEquals(options, rerouteOptions)
assertTrue(requireNotNull(rerouteOrigin).longitude < 0.0095)
assertEquals(NavigationStatus.REROUTING, service.navigationState.value.navigationStatus)
assertEquals(GeoPoint(0.0, 0.0080), service.navigationState.value.position)
val replacement = RouteResult(listOf(requireNotNull(rerouteOrigin), GeoPoint(0.0, 0.007), destination),
listOf(Maneuver("Arrive", 0, 4, 2, 2)), 1300, 120)
pendingReroute.complete(replacement); tick(1000)
position(0.0079)
assertSame(replacement, service.navigationState.value.route)
assertEquals(NavigationStatus.NAVIGATING, service.navigationState.value.navigationStatus)
assertNotNull(service.navigationState.value.nextManeuver)
assertEquals(2, calculations)
} finally { controller.destroy() }
}
}
@@ -44,6 +44,8 @@ data class RouteResult(
val hasUnpaved: Boolean? = null,
/** Locale of the server-provided maneuver text; retained until this route is replaced. */
val guidanceLanguage: String = "es-ES",
/** Imported geometry has no verified road maneuvers or travel-time estimate. */
val imported: Boolean = false,
)
enum class RouteProfile { FASTEST, AVOID_MOTORWAYS, TOURING, AVOID_UNPAVED }
/** Preferences, not guarantees or legal/surface certification. Presets combine with explicit flags. */
@@ -0,0 +1,115 @@
package dev.navframe.core
import java.io.ByteArrayInputStream
import java.io.InputStream
import javax.xml.parsers.SAXParserFactory
import org.xml.sax.Attributes
import org.xml.sax.InputSource
import org.xml.sax.SAXException
import org.xml.sax.ext.DefaultHandler2
import kotlin.math.*
data class ImportedRoute(val name: String?, val route: RouteResult)
/** Imports geometry only: GPX points do not establish road turns, speeds or travel time. */
object GpxRouteImporter {
const val MAX_BYTES = 5 * 1024 * 1024
const val MAX_POINTS = 10_000
const val MAX_DEPTH = 64
private val namespaces = setOf("", "http://www.topografix.com/GPX/1/0", "http://www.topografix.com/GPX/1/1")
fun parse(input: InputStream): ImportedRoute {
val bytes = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
if (bytes.size() + read > MAX_BYTES) fail("El archivo GPX supera los 5 MiB. Exporta una ruta más pequeña.")
bytes.write(buffer, 0, read)
}
val handler = Handler()
try {
val factory = SAXParserFactory.newInstance().apply { isNamespaceAware = true }
val reader = factory.newSAXParser().xmlReader
// Lexical handling is mandatory: reject DTD before any entity can be expanded.
reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler)
for (feature in listOf("http://xml.org/sax/features/external-general-entities", "http://xml.org/sax/features/external-parameter-entities", "http://apache.org/xml/features/nonvalidating/load-external-dtd")) {
try { reader.setFeature(feature, false) } catch (_: SAXException) { /* The rejecting resolver remains active. */ }
}
reader.contentHandler = handler
reader.entityResolver = handler
reader.errorHandler = handler
reader.parse(InputSource(ByteArrayInputStream(bytes.toByteArray())))
} catch (error: IllegalArgumentException) {
throw error
} catch (_: Exception) {
fail("No se pudo leer el GPX. Comprueba que sea un archivo GPX válido sin DTD ni entidades externas.")
}
val points = handler.points
if (points.size < 2) fail("El GPX necesita al menos dos puntos de ruta o track.")
val distance = points.zipWithNext().sumOf { (a, b) -> distance(a, b) }
if (!distance.isFinite() || distance <= 0.0) fail("El GPX necesita al menos dos puntos distintos.")
return ImportedRoute(handler.name?.trim()?.takeIf { it.isNotEmpty() }, RouteResult(
geometry = points.toList(), maneuvers = emptyList(), distanceMeters = distance.roundToInt().coerceAtLeast(1),
durationSeconds = 0, destination = points.last(), imported = true,
))
}
private class Handler : DefaultHandler2() {
val points = mutableListOf<GeoPoint>()
var name: String? = null
private val path = mutableListOf<String>()
private var rootNamespace = ""
private var candidates = 0
private var nonemptySegments = 0
private var segmentPoints = 0
private var nameText: StringBuilder? = null
override fun startDTD(name: String?, publicId: String?, systemId: String?) = fail("El GPX contiene un DTD no permitido.")
override fun resolveEntity(publicId: String?, systemId: String?): InputSource = fail("El GPX contiene entidades externas no permitidas.")
override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
if (path.size >= MAX_DEPTH) fail("El GPX tiene demasiados niveles XML.")
if (path.isEmpty()) {
if (localName != "gpx" || uri !in namespaces) fail("Selecciona un archivo GPX 1.0 o 1.1 válido.")
rootNamespace = uri
}
path.add(if (uri == rootNamespace) localName else "#extension")
val route = path == listOf("gpx", "rte")
val track = path == listOf("gpx", "trk")
if (route || track) {
candidates++
if (candidates > 1) fail("El GPX contiene varias rutas o tracks. Exporta solo la ruta que quieras seguir.")
}
if (path == listOf("gpx", "trk", "trkseg")) segmentPoints = 0
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) nameText = StringBuilder()
if (path == listOf("gpx", "rte", "rtept") || path == listOf("gpx", "trk", "trkseg", "trkpt")) {
if (points.size >= MAX_POINTS) fail("El GPX supera los 10000 puntos. Simplifica la ruta antes de importarla.")
val lat = attributes.getValue("lat")?.toDoubleOrNull()
val lon = attributes.getValue("lon")?.toDoubleOrNull()
if (lat == null || lon == null || !lat.isFinite() || !lon.isFinite() || lat !in -90.0..90.0 || lon !in -180.0..180.0) fail("El GPX contiene coordenadas inválidas.")
points.add(GeoPoint(lat, lon))
if (path[1] == "trk") segmentPoints++
}
}
override fun characters(ch: CharArray, start: Int, length: Int) {
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) {
nameText?.let { if (it.length < 256) it.append(ch, start, minOf(length, 256 - it.length)) }
}
}
override fun endElement(uri: String, localName: String, qName: String) {
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) { name = nameText?.toString(); nameText = null }
if (path == listOf("gpx", "trk", "trkseg") && segmentPoints > 0) {
nonemptySegments++
if (nonemptySegments > 1) fail("El GPX contiene varios segmentos separados. Exporta un solo segmento continuo.")
}
path.removeAt(path.lastIndex)
}
}
private fun distance(a: GeoPoint, b: GeoPoint): Double {
val lat = Math.toRadians(b.latitude - a.latitude)
val lon = Math.toRadians(b.longitude - a.longitude)
val h = sin(lat / 2).pow(2) + cos(Math.toRadians(a.latitude)) * cos(Math.toRadians(b.latitude)) * sin(lon / 2).pow(2)
return 6_371_000.0 * 2 * asin(sqrt(h.coerceIn(0.0, 1.0)))
}
private fun fail(message: String): Nothing = throw IllegalArgumentException(message)
}
@@ -13,6 +13,7 @@ data class RenderScheduleConfig(
val turningDeltaDegrees: Float = 15f,
val speedDeltaMetersPerSecond: Float = 0.5f,
val distanceLabelStepMeters: Int = 10,
val redrawStationaryBearing: Boolean = false,
) {
init {
require(listOf(stoppedMaxFps, movingMaxFps, turningMaxFps).all { it.isFinite() && it > 0 })
@@ -77,7 +78,7 @@ class RenderScheduler(private val config: RenderScheduleConfig = RenderScheduleC
old.etaEpochMillis?.div(60_000) != fresh.etaEpochMillis?.div(60_000) ||
abs(old.speed - fresh.speed) >= config.speedDeltaMetersPerSecond ||
distanceMeters(old.position, fresh.position) >= config.positionDeltaMeters ||
(max(old.speed, fresh.speed) >= config.movingSpeedMetersPerSecond &&
((config.redrawStationaryBearing || max(old.speed, fresh.speed) >= config.movingSpeedMetersPerSecond) &&
bearingDistance(old.bearing, fresh.bearing) >= config.bearingDeltaDegrees)
private fun label(distance: Int?): Int? = distance?.div(config.distanceLabelStepMeters)
@@ -52,7 +52,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
val distinct = lastTimestamp != fix.timestampMs
if (!distinct) return lastState ?: base.copy(navigationStatus = NavigationStatus.GPS_LOST)
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) {
outside.reset(); arrival.reset()
needsRecovery = false
@@ -76,7 +76,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
}
val projection = line.project(fix.position, progress, forwardAllowance)
val outsideThreshold = max(config.offRouteMeters, fix.accuracyMeters * 2.0)
val offRoute = outside.observe(projection.distance > outsideThreshold, distinct, nowMs,
val offRoute = outside.observe(projection.localDistance > outsideThreshold, distinct, nowMs,
config.offRouteFixes, config.offRouteDurationMs)
// Freeze progress during inaccurate projection, so driving parallel to the road does not advance turns.
if (projection.distance <= outsideThreshold && projection.localDistance <= outsideThreshold && projection.local != null) {
@@ -87,20 +87,16 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
arrival.reset()
return remember(base.copy(navigationStatus = NavigationStatus.OFF_ROUTE))
}
if (projection.distance > outsideThreshold) {
if (projection.localDistance > outsideThreshold) {
arrival.reset()
return remember(base.copy(navigationStatus = NavigationStatus.NAVIGATING))
}
if (projection.local == null || projection.localDistance > outsideThreshold) {
arrival.reset()
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
}
val remaining = line.total - progress
val close = projection.distance <= outsideThreshold && remaining <= config.arrivalRemainingMeters &&
earthDistance(fix.position, route.geometry.last()) <= config.arrivalRadiusMeters
arrived = arrival.observe(close, distinct, nowMs, config.arrivalFixes, config.arrivalDurationMs)
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
return remember(line.guidedState(base, progress, epochMs))
}
}
@@ -135,9 +131,9 @@ class RouteDemo(private val route: RouteResult, private val speedMetersPerSecond
val base = NavigationState(position = position, bearing = bearing, speed = speedMetersPerSecond,
route = route, accuracyMeters = 3f)
if (progress >= line.total) return base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = epochMs, navigationStatus = NavigationStatus.ARRIVED)
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)
val state = line.guidedState(base, progress, epochMs)
return state.copy(etaEpochMillis = saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
return state.copy(etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
}
}
@@ -205,8 +201,21 @@ private class RouteLine(private val route: RouteResult) {
val distance = earthDistance(point, projected)
val along = cumulative[i - 1] + (cumulative[i] - cumulative[i - 1]) * fraction
nearestDistance = min(nearestDistance, distance)
if (along >= previous - 20 && along <= previous + forwardAllowance && distance < localDistance - 0.01) {
localDistance = distance; localProgress = along
// Compare against the reachable section, including its boundary points. A reliable
// position behind progress or on a distant later branch is a deviation, not GPS loss.
// Clamping the projection also avoids artificial gaps at the progress-window edges.
val start = max(cumulative[i - 1], previous - 20)
val end = min(cumulative[i], previous + forwardAllowance)
if (start <= end) {
val reachableAlong = along.coerceIn(start, end)
val length = cumulative[i] - cumulative[i - 1]
val reachableFraction = if (length == 0.0) 0.0 else (reachableAlong - cumulative[i - 1]) / length
val reachablePoint = GeoPoint(a.latitude + dy * reachableFraction,
wrappedLongitude(a.longitude + wrappedLongitude(b.longitude - a.longitude) * reachableFraction))
val reachableDistance = earthDistance(point, reachablePoint)
if (reachableDistance < localDistance - 0.01) {
localDistance = reachableDistance; localProgress = reachableAlong
}
}
}
return Projection(nearestDistance, localProgress, localDistance)
@@ -217,7 +226,7 @@ private class RouteLine(private val route: RouteResult) {
val etaMs = (route.durationSeconds * 1000.0 * remaining / total).roundToLong()
return base.copy(nextManeuver = next?.first,
distanceToNextManeuverMeters = next?.let { (it.second - progress).coerceAtLeast(0.0).roundToInt() },
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = saturatedAdd(epochMs, etaMs),
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, etaMs),
navigationStatus = NavigationStatus.NAVIGATING)
}
fun pointAt(progress: Double): Pair<GeoPoint, Float> {
@@ -0,0 +1,91 @@
package dev.navframe.core
import org.junit.Assert.*
import org.junit.Test
import java.io.ByteArrayInputStream
class GpxRouteImporterTest {
private val points = "<rtept lat=\"43\" lon=\"-5\"/><rtept lat=\"43.001\" lon=\"-5\"/>"
private fun parse(xml: String) = GpxRouteImporter.parse(ByteArrayInputStream(xml.toByteArray()))
private fun rejected(xml: String, expected: String? = null) {
try { parse(xml); fail("Expected rejected GPX") } catch (error: IllegalArgumentException) {
expected?.let { assertTrue(error.message.orEmpty(), error.message.orEmpty().contains(it)) }
}
}
@Test fun `imports route geometry without invented guidance`() {
val result = parse("<gpx><rte><name> Asturias &amp; Costa </name>$points</rte></gpx>")
assertEquals("Asturias & Costa", result.name)
assertEquals(2, result.route.geometry.size)
assertEquals(111, result.route.distanceMeters)
assertEquals(0, result.route.durationSeconds)
assertTrue(result.route.maneuvers.isEmpty())
assertTrue(result.route.imported)
assertEquals(result.route.geometry.last(), result.route.destination)
}
@Test fun `supports standard namespaces and prefixed GPX`() {
for (version in listOf("1/0", "1/1")) {
assertEquals(2, parse("<gpx xmlns=\"http://www.topografix.com/GPX/$version\"><rte>$points</rte></gpx>").route.geometry.size)
}
assertEquals(2, parse("<p:gpx xmlns:p=\"http://www.topografix.com/GPX/1/1\"><p:rte><p:rtept lat=\"0\" lon=\"0\"/><p:rtept lat=\"1\" lon=\"1\"/></p:rte></p:gpx>").route.geometry.size)
}
@Test fun `imports track and ignores empty segments and waypoints`() {
val trackPoints = points.replace("rtept", "trkpt")
val result = parse("<gpx><wpt lat=\"90\" lon=\"180\"/><trk><name>Track</name><trkseg/><trkseg>$trackPoints</trkseg><trkseg/></trk></gpx>")
assertEquals("Track", result.name)
assertEquals(2, result.route.geometry.size)
}
@Test fun `rejects multiple candidates and disconnected segments`() {
rejected("<gpx><rte>$points</rte><rte>$points</rte></gpx>", "varias")
rejected("<gpx><rte>$points</rte><trk/></gpx>", "varias")
val segment = "<trkseg>${points.replace("rtept", "trkpt")}</trkseg>"
rejected("<gpx><trk>$segment$segment</trk></gpx>", "segmentos")
}
@Test fun `rejects DTD internal and external entities`() {
rejected("<!DOCTYPE gpx [<!ENTITY name 'expanded'>]><gpx><rte><name>&name;</name>$points</rte></gpx>")
rejected("<!DOCTYPE gpx SYSTEM 'file:///etc/passwd'><gpx><rte>$points</rte></gpx>")
rejected("<!DOCTYPE gpx [<!ENTITY x SYSTEM 'https://example.com/secret'>]><gpx><rte><name>&x;</name>$points</rte></gpx>")
}
@Test fun `rejects invalid empty and stationary geometry`() {
for (value in listOf("NaN", "Infinity", "91", "nope")) rejected("<gpx><rte><rtept lat=\"$value\" lon=\"0\"/>$points</rte></gpx>")
rejected("<gpx><rte><rtept lat=\"0\" lon=\"181\"/>$points</rte></gpx>")
rejected("<gpx/>")
rejected("<gpx><rte><rtept lat=\"0\" lon=\"0\"/><rtept lat=\"0\" lon=\"0\"/></rte></gpx>", "distintos")
rejected("<other><rte>$points</rte></other>")
rejected("<gpx xmlns=\"https://example.com\"><rte>$points</rte></gpx>")
rejected("<gpx><rte>$points")
}
@Test fun `does not import points from extensions`() {
rejected("<gpx><extensions><rte>$points</rte></extensions></gpx>")
rejected("<gpx xmlns:x=\"https://example.com\"><rte><x:rtept lat=\"0\" lon=\"0\"/><x:rtept lat=\"1\" lon=\"1\"/></rte></gpx>")
}
@Test fun `bounds bytes points and nesting`() {
rejected(" ".repeat(GpxRouteImporter.MAX_BYTES + 1), "5 MiB")
rejected("<gpx><rte>" + "<rtept lat=\"1\" lon=\"1\"/>".repeat(GpxRouteImporter.MAX_POINTS + 1) + "</rte></gpx>", "10000")
rejected("<gpx>" + "<extensions>".repeat(GpxRouteImporter.MAX_DEPTH) + "</extensions>".repeat(GpxRouteImporter.MAX_DEPTH) + "</gpx>", "niveles")
}
@Test fun `bounded name and submeter route remain usable`() {
val result = parse("<gpx><rte><name>${"x".repeat(1000)}</name><rtept lat=\"0\" lon=\"0\"/><rtept lat=\"0.000001\" lon=\"0\"/></rte></gpx>")
assertEquals(256, result.name!!.length)
assertEquals(1, result.route.distanceMeters)
}
@Test fun `imported route tracks progress without turns or ETA and confirms deviation`() {
val route = parse("<gpx><rte><rtept lat=\"0\" lon=\"0\"/><rtept lat=\"0\" lon=\"0.01\"/></rte></gpx>").route
val tracker = RouteGuidanceTracker(route)
fun fix(lat: Double, time: Long) = LocationFix(GeoPoint(lat, 0.005), 90f, 5f, 5f, time)
val onLine = tracker.update(fix(0.0, 1), 0, 100_000)
assertEquals(NavigationStatus.NAVIGATING, onLine.navigationStatus)
assertEquals(556, onLine.remainingDistanceMeters!!)
assertNull(onLine.etaEpochMillis)
assertNull(onLine.nextManeuver)
assertNull(onLine.distanceToNextManeuverMeters)
// A 56m displacement is believable movement, but clearly outside the route corridor.
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.0005, 2), 1_000, 101_000).navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, tracker.update(fix(0.0005, 3), 4_000, 104_000).navigationStatus)
val outside = tracker.update(fix(0.0005, 4), 6_000, 106_000)
assertEquals(NavigationStatus.OFF_ROUTE, outside.navigationStatus)
assertNull(outside.nextManeuver)
assertNull(outside.distanceToNextManeuverMeters)
assertNull(outside.etaEpochMillis)
}
}
@@ -126,6 +126,17 @@ class RenderSchedulerTest {
assertTrue(scheduler.renderIfDue(first.copy(accuracyMeters = null, bearing = Float.NaN), 4_000))
}
@Test fun stationaryCompassRotationRedrawsOnlyWhenEnabledAndWithinItsRateLimit() {
val scheduler = RenderScheduler(RenderScheduleConfig(stoppedMaxFps = .5, redrawStationaryBearing = true))
val first = state().copy(speed = 0f, bearing = 10f)
assertTrue(scheduler.renderIfDue(first, 0))
assertFalse(scheduler.renderIfDue(first.copy(bearing = 40f), 1_000))
assertTrue(scheduler.renderIfDue(first.copy(bearing = 40f), 2_000))
val original = RenderScheduler()
original.renderIfDue(first, 0)
assertFalse(original.renderIfDue(first.copy(bearing = 40f), 2_000))
}
@Test fun invalidConfigurationIsRejected() {
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(movingMaxFps = Double.NaN) }
assertThrows(IllegalArgumentException::class.java) { RenderScheduleConfig(distanceLabelStepMeters = 0) }
@@ -188,9 +188,36 @@ class RouteGuidanceTest {
tracker.update(fix(), 0, 0)
tracker.update(fix(lon = 0.005, time = 2), 1_000, 0)
val stableButDistant = tracker.update(fix(lon = 0.005, time = 3), 2_000, 0)
assertEquals(NavigationStatus.GPS_LOST, stableButDistant.navigationStatus)
assertEquals(NavigationStatus.NAVIGATING, stableButDistant.navigationStatus)
assertNull(stableButDistant.remainingDistanceMeters)
assertNull(stableButDistant.nextManeuver)
tracker.update(fix(lon = 0.005, time = 4), 5_000, 0)
val offRoute = tracker.update(fix(lon = 0.005, time = 5), 7_000, 0)
assertEquals(NavigationStatus.OFF_ROUTE, offRoute.navigationStatus)
assertTrue(ReroutePolicy().shouldRequest(offRoute, 7_000))
}
@Test fun `turning back on the same road confirms deviation rather than GPS loss`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 180)
val tracker = RouteGuidanceTracker(longRoute)
tracker.update(fix(lon = 0.01), 0, 0)
tracker.update(fix(lon = 0.0097, time = 2), 1_000, 0)
tracker.update(fix(lon = 0.0094, time = 3), 2_000, 0)
tracker.update(fix(lon = 0.0091, time = 4), 4_000, 0)
val reversed = tracker.update(fix(lon = 0.0088, time = 5), 7_000, 0)
assertEquals(NavigationStatus.OFF_ROUTE, reversed.navigationStatus)
assertTrue(ReroutePolicy().shouldRequest(reversed, 7_000))
assertNull(reversed.nextManeuver)
assertEquals(GeoPoint(0.0, 0.0088), reversed.position)
}
@Test fun `small movement past progress window uses boundary instead of false GPS loss`() {
val longRoute = RouteResult(listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 180)
val tracker = RouteGuidanceTracker(longRoute)
val initial = tracker.update(fix(lon = 0.01), 0, 0)
val reversed = tracker.update(fix(lon = 0.00975, time = 2), 1_000, 0)
assertEquals(NavigationStatus.NAVIGATING, reversed.navigationStatus)
assertEquals(initial.remainingDistanceMeters, reversed.remainingDistanceMeters)
}
@Test fun `maneuver arrows use type rather than translated prose`() {
+53
View File
@@ -0,0 +1,53 @@
# Android builds and automatic releases
The Android workflow verifies the debug build, unit tests and lint for pull requests and pushes to `main` or `development`. A manual Actions run is also available. Pull requests never receive production signing secrets or publish releases.
## Branch outputs
| Event | Output after checks pass |
| --- | --- |
| Push to `development` | `app-debug.apk` uploaded as `navframe-debug-COMMIT_SHA`, retained for 14 days. |
| Push to `main` | Signed production/release APK, `SHA256SUMS.txt` and `build-info.json` published in a new GitHub Release. |
| Pull request | Build/test/lint reports only; no release publication. |
| Manual run | Same branch behavior as a push when run on `main` or `development`. |
Each push is a separate run, including rapid successive pushes; older builds are not cancelled or discarded. A push containing several commits builds its final commit. Release publication requires successful checks, release compilation/lint, and APK signature verification. Tags include versionName, workflow run number and commit SHA, for example `app-v0.13.2-build-42-0123456789ab`. APK versionCode is `1000000 + github.run_number`, so successive production builds can update each other without changing the human-readable versionName for every commit. Preserve the workflow's run-number history if reorganizing the workflow.
An older build finishing late does not replace the current main build as `latest`. Rerunning a run can finish its own draft release, but preserves an already published release and its assets. Offline-region release/catalog workflows are separate.
## Production signing secrets
Create these repository Actions secrets under **Settings → Secrets and variables → Actions**:
| Secret | Contents |
| --- | --- |
| `ANDROID_RELEASE_KEYSTORE_BASE64` | Base64-encoded production `.p12`/keystore file. |
| `ANDROID_RELEASE_KEYSTORE_PASSWORD` | Keystore password. |
| `ANDROID_RELEASE_KEY_ALIAS` | Alias of the production signing key. |
| `ANDROID_RELEASE_KEY_PASSWORD` | Key password; for a PKCS12 key it normally matches the keystore password. |
Use a permanent production key and keep a secure offline backup of the keystore and passwords. The newly prepared NavFrame key uses RSA-4096, PKCS12, alias `navframe-release`, and a 10,000-day certificate validity. Its private backup is supplied separately from the repository; neither keys nor password values belong in Git, Actions artifacts, release assets or this document. A replacement key normally cannot update an app signed by the old key. A production key also cannot update an earlier APK signed with a debug key; preserve/export app data before any uninstall required by a signature mismatch.
The workflow restores the keystore to a private temporary runner file, checks that all four secrets exist, builds with environment-only signing parameters, verifies the APK signature, and removes the temporary key even if the job fails. The verification job remains read-only; only the guarded main release job has `contents: write`. The normal repository `GITHUB_TOKEN` publishes releases, with no separate personal token required. Repository/org policies must permit the release job's requested permission.
Development artifacts use Android's default debug signing. Fresh GitHub runners can generate different debug keys, so debug artifacts are not a stable production update channel. They do not contain the production private key.
## Local production validation
Provide these values securely in the process environment (never commit a shell script containing their values):
- `NAVFRAME_KEYSTORE_PATH`
- `NAVFRAME_KEYSTORE_PASSWORD`
- `NAVFRAME_KEY_ALIAS`
- `NAVFRAME_KEY_PASSWORD`
From the repository root, using JDK 17 and Android SDK 36:
```sh
./gradlew --no-daemon --max-workers=4 :app:assembleRelease :app:lintRelease -PnavframeVersionCode=1000042
"$ANDROID_HOME/build-tools/35.0.0/apksigner" verify --verbose app/build/outputs/apk/release/app-release.apk
```
The version-code override is optional for local builds; ordinary debug builds retain the manifest's normal version code and need no signing variables. An unsigned production build is rejected instead of producing a publishable release. Partially specified signing configuration is rejected with variable names only.
Publication is active only after this workflow lands on the selected branch and the production secrets are configured. A successful local production build does not establish a GitHub Release was published.
+1 -1
View File
@@ -39,4 +39,4 @@ Worldwide region discovery/building is a separate publishing pipeline. Geofabrik
The regional catalog URL is configurable. HTTPS protects transport to the selected host; archive SHA-256 values detect mismatch with that catalog. The app does not currently pin a signing key for catalog authenticity. Only install catalogs from a source you trust.
OpenStreetMap-derived content can be incomplete or stale. Camera alerts are optional, jurisdiction-sensitive, and cannot establish enforcement direction or absence. Android TextToSpeech availability and offline voice data depend on the selected engine and installed voice. The current directions voice is Spanish. Detailed physical validation status is recorded in [TESTING.md](TESTING.md).
OpenStreetMap-derived content can be incomplete or stale. Camera alerts are optional, jurisdiction-sensitive, and cannot establish enforcement direction or absence. Android TextToSpeech availability and offline voice data depend on the selected engine and installed voice. Directions support Spanish, English, German, French and Italian, plus system-language selection with English fallback; actual speech depends on installed Android TTS voices. Detailed physical validation status is recorded in [TESTING.md](TESTING.md).
+19 -21
View File
@@ -1,41 +1,39 @@
# Explicit destination search (English summary)
# Explicit destination search
Typing in NavFrame searches installed local place catalogs. Online address search requires a separate user action; NavFrame sends the submitted search text to the configured geocoder and does not send GPS as part of that query. The default public Nominatim service is subject to the [OSMF usage policy](https://operations.osmfoundation.org/policies/nominatim/): one request per second aggregated across the application, no client-side autocomplete or systematic bulk queries, and an identifying User-Agent/Referer with attribution. A per-device delay does not satisfy a multi-user aggregate limit. Do not submit sensitive search text to a public service.
Detailed implementation and historical test notes follow in Spanish.
## Implementation contract
# Detailed geocoding notes (Spanish)
Research dated 2026-09-29. NavFrame retains the `Geocoder.search(query)` abstraction, and the user selects a `SearchResult` before route calculation. Typing does not initiate network requests: only Search or an equivalent explicit action does. Searching does not start guidance, replace an active route, or assume the first result is correct.
Investigación del 2026-09-29. NavFrame conserva la abstracción `Geocoder.search(query)` y el usuario selecciona un `SearchResult` antes de calcular ruta. Escribir no inicia red: solo el botón Buscar o acción explícita equivalente. Una búsqueda no inicia navegación, no sustituye una ruta activa y no presupone que el primer resultado sea correcto.
## Public server policy
## Política del servidor público
**Read the [official OSMF Nominatim policy](https://operations.osmfoundation.org/policies/nominatim/) before enabling the public service.** It permits explicit queries with moderate numbers of users; it requires an identifying User-Agent/Referer, attribution, and an absolute maximum of **one request per second aggregated across the entire application**, not per user or phone. Autocomplete, systematic queries, and personal/confidential data are prohibited. The application must be able to change backend without an APK update; a proxy/cache is recommended. Its LLM section requires a deliberate, informed developer decision and prohibits providing it as a generic geocoder for app-generation platforms.
**Leer la [política oficial Nominatim de OSMF](https://operations.osmfoundation.org/policies/nominatim/) antes de activar el servicio público.** Permite consultas explícitas con usuarios moderados; exige User-Agent/Referer identificativo, atribución y máximo absoluto **1 petición/s agregado de toda la aplicación**, no por usuario o teléfono. Prohíbe autocomplete, consultas sistemáticas y datos personales/confidenciales. La app debe poder cambiar backend sin actualizar APK; proxy/cache son recomendados. Su apartado LLM exige una decisión deliberada e informada del desarrollador y prohíbe ofrecerlo como geocoder genérico de plataformas de generación de apps.
The developer brief deliberately selects Nominatim as a possible provider, with explicit search and no abuse. The initial implementation is limited to the personal NavFrame prototype; it is not permission to distribute multiple installations with independent request budgets. Before expanding the user base, use a proxy that limits aggregate traffic or a self-hosted/commercial provider with suitable terms. The screen must show the policy and selected provider. Availability and results are not guaranteed; provider blocking must be respected.
El brief del desarrollador elige conscientemente Nominatim como proveedor posible, con búsqueda explícita y sin abuso. La implementación inicial se limita al prototipo personal NavFrame; no representa permiso para distribuir múltiples instalaciones con presupuestos independientes. Antes de ampliar usuarios, usar un proxy que limite el tráfico agregado o un proveedor propio/comercial con condiciones apropiadas. La pantalla debe mostrar la política y el proveedor seleccionado. No garantiza disponibilidad ni resultados; un bloqueo del proveedor debe respetarse.
## Endpoint and Android HTTP
## Endpoint y HTTP Android
Documented public endpoint: `https://nominatim.openstreetmap.org/search`. Another HTTPS URL **compatible with Nominatim jsonv2** can be selected in settings without recompilation. Removing the public provider must remain possible. The [official Search parameters](https://nominatim.org/release-docs/latest/api/Search/) allow free-form q, jsonv2, limit, and accept-language; the obsolete search.php endpoint is not used.
Endpoint público documentado: `https://nominatim.openstreetmap.org/search`. Otra URL HTTPS **compatible con Nominatim jsonv2** puede seleccionarse en ajustes sin recompilar. Debe ser posible retirar el público como proveedor. Los [parámetros oficiales Search](https://nominatim.org/release-docs/latest/api/Search/) permiten q libre, jsonv2, limit y accept-language; no se usa el endpoint obsoleto search.php.
`nominatimSearchParameters(query)` returns `q` with normalized whitespace, `format=jsonv2`, `limit=5`, `accept-language=es`, and `addressdetails=0`. Android encodes each parameter through the HTTP encoder; do not concatenate unescaped queries. Queries have 2–200 characters, a local UI restriction rather than a service limit. Do not send GPS, viewbox, user identity, or email. User-Agent must identify NavFrame/version rather than the generic HTTP client; the geocoder requires neither X-Client-Id nor UUID.
`nominatimSearchParameters(query)` devuelve `q` con espacios normalizados, `format=jsonv2`, `limit=5`, `accept-language=es`, `addressdetails=0`. Android codifica cada parámetro mediante encoder HTTP; no concatenar consultas sin escapar. La consulta tiene 2–200 caracteres; esto es una limitación UI propia, no del servicio. No enviar GPS, viewbox, identidad del usuario ni email. User-Agent debe identificar NavFrame/version y no el cliente HTTP genérico; el geocoder no requiere X-Client-Id ni UUID.
Allow one request in flight, at least one second between HTTP starts, a timeout, and cancellation when leaving or replacing a search. Do not retry errors or HTTP429 automatically: show a pause and respect Retry-After before a manual action. A search generation must prevent late callbacks from replacing newer results.
Una sola solicitud en vuelo, separación mínima de 1s entre inicios HTTP, timeout y cancelación al salir/sustituir búsqueda. No reintentar automáticamente errores ni HTTP429: mostrar pausa y respetar Retry-After antes de una acción manual. Una generación de búsqueda debe impedir que un callback tardío reemplace resultados más nuevos.
Use a bounded in-memory cache (target: 100 entries/24 hours), keyed by endpoint, normalized query, and language, including empty results. Different queries must not mix; changing endpoint must partition or clear the cache. Destination/address history is not persisted by default. This cache and rate limiter reduce traffic for one installation; they do not solve the global limit when distributed to multiple phones.
Cache de memoria acotada (objetivo 100 entradas/24h) por endpoint, consulta normalizada e idioma; incluir resultados vacíos. Consultas distintas no se mezclan y cambiar endpoint debe separar o limpiar cache. No persiste historial de destinos ni direcciones por defecto. En una instalación este cache y rate limiter reducen tráfico; no resuelven el límite global si se distribuye a múltiples teléfonos.
## Parsing and selection
## Parser y selección
`parseNominatimResults(json)` uses strict Gson and returns `SearchResult(name, position, attribution)`; previous constructors remain available with default attribution. `display_name` describes the destination; lat/lon are finite numeric strings within geographic ranges. The result's `licence` is preserved as text; a standard OSM credit is shown when missing. See the [official output format](https://nominatim.org/release-docs/latest/api/Output/).
`parseNominatimResults(json)` utiliza Gson estricto y devuelve `SearchResult(name, position, attribution)`; conserva constructors anteriores con attribution default. `display_name` describe el destino, lat/lon son strings numéricos finitos con rango geográfico. `licence` del resultado se conserva como texto; si falta se muestra crédito OSM estándar. [Formato de resultados oficial](https://nominatim.org/release-docs/latest/api/Output/).
Responses are limited to 512 Ki characters, at most 40 remote objects, up to five UI results, and labels of 2,048 characters. Android must also limit bytes before loading a String. Exact name/coordinate duplicates and label control characters are removed without interpreting HTML. Invalid JSON/error/status/body produces local messages without the query or coordinates. An empty list means no matches, not failure.
Respuesta limitada a 512Ki caracteres, máximo remoto 40 objetos, hasta cinco resultados para UI y labels de 2048 caracteres. Android debe limitar bytes también antes de cargar String. Se eliminan duplicados exactos nombre/coordenadas y controles del label, sin reinterpretar HTML. JSON/error/status/body incorrectos generan mensajes propios sin consulta ni coordenadas. Una lista vacía significa sin coincidencias, no fallo.
Do not retain place_id as a permanent identity or infer motorcycle access from a city/POI centroid. Show the full name and selected coordinates before calculation; Valhalla may snap the destination to another road position. Search does not guarantee access, parking availability, or site restrictions.
No se guarda place_id como identidad permanente ni se inferirá una entrada apta para moto a partir de un centroide de ciudad/POI. Mostrar el nombre completo y coordenadas de la selección antes de calcular; Valhalla puede ajustar el destino a otra posición de carretera. Búsqueda no garantiza acceso, existencia de aparcamiento ni restricciones del lugar.
## Privacy, attribution, and tests
## Privacidad, créditos y pruebas
The provider receives search text, IP, and HTTP metadata; do not enter private/confidential addresses into the public service. Show `© OpenStreetMap contributors` and a [copyright/ODbL](https://www.openstreetmap.org/copyright) link in results, preserving map credits and remote attribution where appropriate. No Nominatim code is embedded: the adapter/parser are original and consume HTTP. Gson/notices are already distributed in the APK.
El proveedor recibe el texto buscado, IP y metadata HTTP; no escribir direcciones privadas/confidenciales en el servicio público. Mostrar `© OpenStreetMap contributors` y enlace a [copyright/ODbL](https://www.openstreetmap.org/copyright) en resultados, manteniendo crédito de mapas y attribution remoto cuando proceda. No se incorpora código Nominatim: adapter/parser son originales y se consume HTTP. Gson/avisos ya están distribuidos en el APK.
`NominatimGeocodingTest` covers an original jsonv2 fixture, Unicode/antimeridian coordinates, attribution, empty results, duplicates/limits, invalid/non-strict JSON and backend errors, finite string coordinates/ranges, labels, Unicode/escaping parameters, and validation before HTTP. Tests do not run automated public queries. Adapter checks cover caching, rate limits, and cancellation; public availability and actual search quality require independent verification.
`NominatimGeocodingTest` cubre fixture original jsonv2, coordenadas Unicode/antimeridiano, attribution, vacíos, duplicados/límites, JSON inválido/no estricto y errores backend, coordenadas string finitas/rangos, labels, parámetros Unicode/escape y validación antes de HTTP. No se ejecutan consultas públicas automáticas en tests. Las comprobaciones del adapter prueban cache, rate limit y cancelación; disponibilidad pública y calidad real de búsquedas requieren verificaciones independientes.
La fase 6 incluye además un ajuste de recuperación GPS: dos fixes nuevos estables tras pérdida/gap antes de adquirir progreso, sin interpretar el tiempo sin señal como movimiento demostrado. Se valida junto al incremento 0.6, sin alterar el APK 0.5 ya entregado.
Phase 6 also includes a GPS recovery adjustment: two new stable fixes after loss/a gap before acquiring progress, without interpreting time without signal as demonstrated movement. It is validated with increment 0.6, without changing the previously delivered 0.5 APK.
+23
View File
@@ -0,0 +1,23 @@
# Importing a GPX route
Open **☰ → Cargar ruta GPX**, then choose a `.gpx` file using Android's document picker. The app displays the name, distance and point count and previews the trace when no other navigation session is active. After a valid file is selected, navigation starts automatically with real GPS as soon as location permission and a recent accurate fix are available. No destination search is needed. A pending import leaves existing navigation running until the new trace can start. The **Iniciar navegación** button retries after a timeout or permission denial.
Precise location permission is required to start navigation. If a recent fix with accuracy of 25 metres or better is unavailable, the app waits up to 60 seconds. Close the import panel or stop the route to cancel that wait. When the wait expires, enable location and tap **Iniciar navegación** to retry. Denying permission leaves the trace available for review.
## Supported files
GPX 1.0 and 1.1 routes (`rte/rtept`) and tracks (`trk/trkseg/trkpt`) are supported, including GPX files without a namespace. Export exactly one route or one track containing a single nonempty continuous segment. Multiple routes, tracks or nonempty segments are rejected: the app must not create a fictitious connection between separate tracks. Waypoints alone do not define a route.
Files are limited to 5 MiB, 10,000 trace points and 64 XML nesting levels. Coordinates must be finite and within latitude/longitude bounds, with at least two distinct points. DTD declarations and external entities are rejected. Route names are capped at 256 characters. An invalid or inaccessible file leaves any running navigation untouched.
## Following a trace
The original coordinates are retained locally in memory and drawn on the phone and TFT. GPX import does not send the file or its coordinates to a routing server. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time.
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace.
The imported route is not persisted across process death or device reboot: reload the original document to resume. The document remains in its selected provider; the app does not request long-term file access or copy the GPX into its own storage. Map diagnostics do not include route coordinates, document paths or route names.
## Validation
Core tests exercise standard GPX routes/tracks, namespaces, malicious XML, resource limits and trace guidance without invented turns or ETA. Android unit tests exercise the document picker, cancellation, precise-location permission denial, preview/start/stop and prevention of online recalculation with the renderer replaced to avoid device-only JNI.
+5 -1
View File
@@ -6,7 +6,7 @@ This document summarizes the project's current third-party materials and service
| Component | Terms or status | Practical note |
| --- | --- | --- |
| NavFrame application | No single permissive license is declared for the whole repository | Check the individual code and data notices. Do not assume every file is available under the same terms. |
| Original NavFrame code and documentation | No project-wide license is granted | Public visibility does not itself grant reuse or redistribution rights. Third-party material retains its own terms. |
| NaviLite / Pillion-derived code | PolyForm Noncommercial 1.0.0; see `third_party/pillion/LICENSE.md` and `NOTICE.md` | The license restricts commercial use. Preserve the required notice and license. Separate permission is needed for uses outside its terms. |
| MapLibre Native Android | BSD 2-Clause | Preserve required copyright, license, and disclaimer notices for distributed binaries and source. |
| Gson | Apache License 2.0 | The app bundles Gson; its license and notice are in `app/src/main/assets/GSON_LICENSE.md`. |
@@ -14,6 +14,10 @@ This document summarizes the project's current third-party materials and service
| PMTiles format | Specification is CC0 | This does not change the license of the map data stored in a PMTiles file. |
| Noto Sans glyph assets | SIL Open Font License 1.1 | Bundled glyph files and the full font notice are included in the APK assets. |
## Public source and application releases
The app links `navilite`, which contains Pillion-derived PolyForm Noncommercial code. Its license restricts commercial use. Preserve its required notice and license when distributing derived material, and obtain separate permission from the rightsholders for uses outside those terms. Original NavFrame code and documentation currently have no project-wide license grant; a public source repository does not itself provide reuse rights. A redistribution must respect the rights in original material as well as all included component, data and font licenses.
## OpenStreetMap-derived data
Offline maps, places, and camera catalogs are derived from OpenStreetMap data and are distributed under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/). Attribute the data to **© OpenStreetMap contributors** and link to [openstreetmap.org/copyright](https://www.openstreetmap.org/copyright). Regional package manifests retain source URLs, timestamps, checksums, build recipe, and attribution. Keep these details with redistributed packages.
+27
View File
@@ -0,0 +1,27 @@
# Location acquisition and compass (0.13.3)
NavFrame now listens to the Android location sources available on the device: GNSS/GPS, network, native fused location, and passive updates. It also seeds the position from a recent, validated Android last-known location rather than always waiting for another satellite fix. The native fused provider is used only when present; this does not introduce a Google Play services dependency or guarantee the same acquisition behavior as Google Maps or Waze.
## Approximate position versus route guidance
The previous 25-metre gate applied even to recentering the map. A recent position with reported accuracy up to 100 metres can now recenter the map, supply a route-preview origin, and show the rider's approximate position. The phone displays the estimated accuracy and labels positions worse than 25 metres as approximate. Stale, future-dated, invalid, or accuracy-free fixes are rejected. A very coarse network update cannot replace a recent usable precise fix.
Starting guidance and automatic recalculation still require a recent fix with accuracy at most 25 metres. The route tracker retains its existing precision, freshness, and sustained-deviation rules. Approximate position is not presented as confirmed road-level route progress. If guidance pauses for low precision while a recent approximate position remains available, the phone/TFT explain that distinction instead of simply claiming there is no GPS signal.
All freshness checks use Android's monotonic elapsed time and a 15-second limit, including cached fixes. Location services must be enabled and precise location permission remains required by the current app workflow. Enabled providers are tracked independently; disabling one does not invalidate another active provider. Location subscriptions are removed when their visible-map or navigation session ends.
## Compass and course
When the position workflow is active, the app uses an absolute rotation-vector sensor (or a geomagnetic rotation-vector sensor when available) to determine the direction of the top edge of the screen. Display rotation is accounted for, and the latest in-memory location supplies magnetic declination for a true-north heading. No extra sensor permission is needed.
At speeds of at least 2 m/s, a usable GPS course takes priority. At lower speeds, an available compass heading drives the map orientation and the phone shows **Brújula** (Compass). The phone labels movement course **Rumbo GPS** (GPS course). The compass is smoothed across the north/360-degree boundary, expires after five seconds without a measurement, and rejects sensor status UNRELIABLE. Without a suitable sensor or trustworthy heading, direction remains unavailable rather than inventing north as a measured heading.
Stationary TFT compass changes can redraw the map, limited to the existing stopped-map cadence (at most once every two seconds). Sensor listeners are released with the location workflow. Magnetic mounts, vehicle metal, and device calibration can affect compass accuracy; test with the phone in its actual mounting position. The sensor describes phone orientation, not inherently motorcycle orientation.
Coordinates are used only in memory; this change does not add coordinate logs or uploads. It retains the existing explicit online-route/search behavior and the persistent sanitized TFT diagnostics from 0.13.2.
## Validation
Robolectric tests cover fresh network-cache startup, stale/invalid/future fixes, coarse updates competing with precise fixes, independent provider availability and cleanup, approximate-map readiness versus strict route guidance, expiration of stale visible positions, stationary compass versus movement course, sensor reliability/cleanup, and north-wrap smoothing. A core scheduling test verifies stationary compass redraws respect the configured rate limit without changing the default policy for other renderers.
Native GNSS acquisition time, device-specific provider availability, compass accuracy on a motorcycle mount, and physical TFT rendering require device validation.
+1 -1
View File
@@ -24,7 +24,7 @@ Maps and installed places can be viewed without a network connection. Search for
Map detail is bounded by package coverage and maximum zoom. POI data can be absent or outdated. Glyph coverage is limited to the bundled font ranges, so some writing systems or characters may not render. OSM data does not certify business status, road access, motorcycle suitability, speed limits, or camera completeness.
The owner confirmed that the bundled Asturias map works offline on a Xiaomi 11 Lite 5G NE running Android 14. This confirms phone use only. The last reported physical map-render attempt on the Yamaha TFT displayed `MAPA NO DISPONIBLE`; a successful TFT map render has not been confirmed.
The owner confirmed that the bundled Asturias map works offline on a Xiaomi 11 Lite 5G NE running Android 14. On 2026-10-12, the owner reported about 20 minutes of working TFT map display followed by persistent `Mapa no disponible` while the phone map continued working, with an offline map installed. This confirms some successful TFT rendering, but not sustained reliability or the exact source selected by the TFT at failure. See [Testing](TESTING.md).
## Package format and validation
+2 -2
View File
@@ -1,6 +1,6 @@
# Yamaha TFT Native Navigator: English brief summary
This is an English summary of the original project brief, [`yamaha_tft_native_navigator_codex.md`](../yamaha_tft_native_navigator_codex.md). That source document is preserved in its original Spanish-language form for provenance; this summary is not a line-by-line translation and may not include every original requirement.
This is an English summary of the original project brief, [`yamaha_tft_native_navigator_codex.md`](../yamaha_tft_native_navigator_codex.md). The source document is in English; this summary is not a line-by-line translation and may not include every original requirement.
## Product goal
@@ -12,7 +12,7 @@ The intended data flow is Android GPS plus map data and route results into share
The original brief describes GPS position, destination search, route calculation, map/position/route display, next maneuver, remaining distance and estimated arrival, turn-based rerouting, direct TFT rendering, and screen-off operation. It proposes an Android Kotlin app, MapLibre for maps, a routing backend, configurable geocoding, local regional maps in a later phase, and a phone UI for setup/control.
The implementation is experimental and incomplete. Current verified status is documented in the main [README](../README.md), [Architecture](ARCHITECTURE.md), and [Testing/physical validation record](TESTING.md). In particular, physical confirmation of basic images on one Yamaha/phone combination does not establish a working map renderer, safe route guidance, or long-duration screen-off operation.
The implementation is experimental and incomplete. Current verified status is documented in the main [README](../README.md), [Architecture](ARCHITECTURE.md), and [Testing/physical validation record](TESTING.md). In particular, physical confirmation of basic images on one Yamaha/phone combination does not establish sustained map-rendering reliability, safe route guidance, or long-duration screen-off operation. A later owner report confirms that map display worked for about 20 minutes before a persistent failure; see the testing record.
## Engineering principles retained
+3 -2
View File
@@ -5,7 +5,7 @@
- [Project overview, build, current status, and license summary](../README.md)
- [Architecture and data flow](ARCHITECTURE.md)
- [English summary of the original product brief](PRODUCT_BRIEF_EN.md)
- [Original product brief (Spanish)](../yamaha_tft_native_navigator_codex.md)
- [Original product brief (English)](../yamaha_tft_native_navigator_codex.md)
- [Contributing](../CONTRIBUTING.md)
- [Security reporting](../SECURITY.md)
@@ -28,9 +28,10 @@
- [Voice directions](VOICE.md)
- [Fixed speed-camera advisories](RADARS.md)
- [Testing and physical-device status](TESTING.md)
- [2026-10-12 TFT map incident investigation](TFT_MAP_INCIDENT_2026-10-12.md)
## Licensing
- [Licenses, attribution, and service terms](LICENSING.md)
Most current public-facing guides are in English. `ROUTING.md` and `GEOCODING.md` begin with English summaries but retain detailed historical implementation notes in Spanish. `TESTING.md` retains detailed historical test procedures and per-version records in Spanish, with an English current-status summary at the top. The original product brief remains Spanish and is accompanied by [PRODUCT_BRIEF_EN.md](PRODUCT_BRIEF_EN.md).
The guides and original product brief are in English. Quoted app labels and error messages retain the language displayed by the app. Historical procedures describe the version that introduced a feature; the current status in [Testing](TESTING.md) distinguishes later reports from those historical records.
+36 -37
View File
@@ -1,70 +1,69 @@
# Routing and guidance (English summary)
# Routing and guidance
Route calculation uses a configurable HTTPS Valhalla-compatible service. The default FOSSGIS endpoint is a public demo with fair-use/rate limits, not a production SLA. Valhalla asks applications published to end users to notify the project and include an identifying `X-Client-Id`; see the [official Valhalla documentation](https://valhalla.github.io/valhalla/). A route request sends the selected origin and destination to the configured service. Do not submit sensitive coordinates to a public endpoint.
NavFrame does not contain an offline routing graph. It can follow previously calculated route geometry with GPS, but calculating or recalculating a route requires network access. The `motorcycle` profile does not certify legal access, surface quality, or motorcycle suitability. ETA and GPS-based turn progression are estimates and require physical validation. Detailed implementation and historical test notes follow in Spanish.
NavFrame does not contain an offline routing graph. It can follow previously calculated route geometry with GPS, but calculating or recalculating a route requires network access. The `motorcycle` profile does not certify legal access, surface quality, or motorcycle suitability. ETA and GPS-based turn progression are estimates and require physical validation.
# Detailed routing notes (Spanish)
## Implementation contract
Investigación y contrato del 2026-09-29. NavFrame solicita una ruta al seleccionar un destino explícito o pulsar calcular, con origen DEMO/GPS utilizable. La vista previa precede al inicio del guiado; estas acciones no sustituyen automáticamente una ruta activa. El guiado GPS puede solicitar un recálculo tras desvío sostenido o una acción manual. El servicio y UI Android poseen la solicitud, cancelación y vista previa. La fase 5 incorporó vista previa; la fase 6 añade guiado básico puro, simulación sobre la ruta y política conservadora de desvío/recálculo. No incorpora búsqueda de direcciones, voz ni map matching vial avanzado.
Research and contract dated 2026-09-29. NavFrame requests a route after explicit destination selection or Calculate, using a usable DEMO/GPS origin. Preview precedes guidance; these actions do not automatically replace an active route. GPS guidance may request recalculation after sustained deviation or a manual action. The Android service and UI own requests, cancellation, and preview. Phase 5 introduced preview; phase 6 adds basic pure guidance, route simulation, and a conservative deviation/recalculation policy. That phase does not include address search, voice, or advanced road map matching.
## Servicio inicial y privacidad
## Initial service and privacy
Endpoint configurable inicial: `https://valhalla1.openstreetmap.de/route`, demo pública de FOSSGIS; `valhalla.openstreetmap.de` es el frontend, no el endpoint API elegido. El [README oficial Valhalla](https://github.com/valhalla/valhalla) documenta el servicio y exige uso razonable; pide identificar aplicaciones que se publiquen a usuarios mediante `X-Client-Id` y avisar en sus Discussions. No se ha contactado a terceros ni se publica esta app como servicio para usuarios externos. Antes de distribución pública, resolver ese requisito o usar un servidor propio.
Initial configurable endpoint: `https://valhalla1.openstreetmap.de/route`, the FOSSGIS public demo; `valhalla.openstreetmap.de` is the frontend rather than the chosen API endpoint. The [official Valhalla README](https://github.com/valhalla/valhalla) documents the service and requires reasonable use; it asks applications published to users to identify themselves with `X-Client-Id` and notify its Discussions. No third parties have been contacted, and the app has not been published as a service for external users. Resolve that requirement or use a self-hosted server before public distribution.
El [OpenAPI oficial](https://github.com/valhalla/valhalla/blob/master/docs/docs/api/openapi.yaml) documenta HTTP429 y límite por usuario de **una petición por segundo**. El adapter debe serializar solicitudes, esperar al menos ese intervalo, enviar User-Agent identificativo y `X-Client-Id`, y mostrar errores. El recálculo de fase 6 añade cooldown mínimo de 30 segundos, una sola solicitud en vuelo y pausa ante HTTP429; no crea un bucle continuo de reintentos. La demo no ofrece disponibilidad garantizada; el endpoint propio debe poder sustituirse sin cambiar renderer/transporte.
The [official OpenAPI](https://github.com/valhalla/valhalla/blob/master/docs/docs/api/openapi.yaml) documents HTTP429 and a per-user limit of **one request per second**. The adapter must serialize requests, wait at least that interval, send an identifying User-Agent and `X-Client-Id`, and show errors. Phase 6 recalculation adds a minimum 30-second cooldown, one request in flight, and a pause after HTTP429; it does not create a continuous retry loop. The demo offers no availability guarantee; replacing it with a custom endpoint must not require changing rendering/transport.
Calcular envía al servidor origen/destino y opciones, además de IP e identificador de cliente. No registrar JSON ni coordenadas en logs. La [política FOSSGIS de routing](https://routing.openstreetmap.de/about.html) describe registros y crédito OSM para su servicio OSRM; Valhalla remite a ese criterio de fair use, pero no se afirma que ambas implementaciones tengan idéntica retención. La página alemana completa de condiciones respondió protección Anubis durante investigación; no se eludió.
Calculation sends origin/destination and options to the server, alongside IP and client identifier. Do not log JSON or coordinates. The [FOSSGIS routing policy](https://routing.openstreetmap.de/about.html) describes logging and OSM attribution for its OSRM service; Valhalla refers to that fair-use criterion, but identical retention across both implementations is not asserted. The full German terms page returned Anubis protection during research; it was not bypassed.
## Petición y perfiles
## Requests and profiles
`buildValhallaRequest(origin, destination, options)` genera POST JSON con dos locations `type=break`, `costing=motorcycle`, `shape_format=polyline6`, `units=kilometers`, `language=es-ES` y `directions_type=instructions`. `motorcycle` está marcado beta por Valhalla. FASTEST significa una ruta basada en tiempo y costes del modelo; no certifica el mínimo matemático, legalidad vial ni idoneidad de cada tramo para la MT-07.
`buildValhallaRequest(origin, destination, options)` generates POST JSON with two locations using `type=break`, `costing=motorcycle`, `shape_format=polyline6`, `units=kilometers`, language from the selected route language (`es-ES` by default), and `directions_type=instructions`. Valhalla marks `motorcycle` as beta. FASTEST means routing based on the model's time and costs; it does not certify a mathematical minimum, legal road access, or each segment's suitability for the MT-07.
Fase0.8 añade preferencias combinables en `RouteOptions(profile, avoidMotorways, avoidUnpaved, avoidTolls)`. Los presets se combinan con los flags explícitos; cambiar una preferencia no modifica el costing a auto:
Phase 0.8 adds combinable preferences in `RouteOptions(profile, avoidMotorways, avoidUnpaved, avoidTolls)`. Presets combine with explicit flags; changing a preference does not switch costing to auto:
| Perfil/opción | Petición motorcycle | Semántica |
| Profile/option | Motorcycle request | Meaning |
|---|---|---|
| FASTEST / Moto rápido | use_highways=0.5, use_tolls=0.5, use_trails=0.5 | Preferencia neutral; autopistas y peajes permitidos |
| AVOID_MOTORWAYS / Evitar autopistas | use_highways=0 | Penaliza autopistas; no prohibición absoluta |
| AVOID_UNPAVED / Preferir asfalto | use_trails=0 | Penaliza superficies deficientes y caminos; no certificación de asfalto |
| TOURING | use_highways=0.2, use_tolls=0 | Reduce autopistas y peajes; no garantiza ruta panorámica |
| avoidTolls | use_tolls=0 | Preferencia por evitar peajes, combinable con las anteriores |
| FASTEST / Fast motorcycle | use_highways=0.5, use_tolls=0.5, use_trails=0.5 | Neutral preference; motorways and tolls allowed |
| AVOID_MOTORWAYS / Avoid motorways | use_highways=0 | Penalizes motorways; not an absolute prohibition |
| AVOID_UNPAVED / Prefer paved roads | use_trails=0 | Penalizes poor surfaces and trails; no pavement certification |
| TOURING | use_highways=0.2, use_tolls=0 | Reduces motorways and tolls; no scenic-route guarantee |
| avoidTolls | use_tolls=0 | Toll-avoidance preference, combinable with the above |
`use_tracks=0` conserva una penalización de pistas en todos los perfiles. La preferencia de asfalto tiene efecto: reduce `use_trails` de0.5 neutral a0.0; en fases previas era0.0 fijo. Ninguna selección habilita ignorar restricciones, acceso o sentidos únicos.
`use_tracks=0` retains a track penalty in all profiles. The paved-road preference has an effect: it reduces `use_trails` from the neutral 0.5 to 0.0; earlier phases fixed it at 0.0. No selection permits ignoring restrictions, access, or one-way roads.
La [documentación oficial motorcycle y exclusiones](https://valhalla.github.io/valhalla/api/route/api-reference/#motorcycle-costing-options-beta) describe costes blandos y exclusiones experimentales. Se comprobó también [MotorcycleCost](https://github.com/valhalla/valhalla/blob/master/src/sif/motorcyclecost.cc), [DynamicCost](https://github.com/valhalla/valhalla/blob/master/valhalla/sif/dynamiccost.h) y [AutoCost](https://github.com/valhalla/valhalla/blob/master/src/sif/autocost.cc) el2026-09-29: motorcycle lee opciones base, pero Allowed/AllowedReverse no aplican `exclude_unpaved`; AutoCost sí lo aplica. Por eso no enviamos esa bandera como una garantía de moto. `exclude_highways`/`exclude_tolls` dependen de `service_limits.allow_hard_exclusions`; el servidor puede ignorarlas con un warning. Se retiró `exclude_highways=true` del antiguo preset para evitar esa falsa expectativa. No hay fallback silencioso a auto ni a otro perfil.
The [official motorcycle/exclusion documentation](https://valhalla.github.io/valhalla/api/route/api-reference/#motorcycle-costing-options-beta) describes soft costs and experimental exclusions. [MotorcycleCost](https://github.com/valhalla/valhalla/blob/master/src/sif/motorcyclecost.cc), [DynamicCost](https://github.com/valhalla/valhalla/blob/master/valhalla/sif/dynamiccost.h), and [AutoCost](https://github.com/valhalla/valhalla/blob/master/src/sif/autocost.cc) were also checked on 2026-09-29: motorcycle reads base options, but Allowed/AllowedReverse do not apply `exclude_unpaved`; AutoCost does. Therefore that flag is not sent as a motorcycle guarantee. `exclude_highways`/`exclude_tolls` depend on `service_limits.allow_hard_exclusions`; the server may ignore them with a warning. `exclude_highways=true` was removed from the old preset to avoid that false expectation. There is no silent fallback to auto or another profile.
`RouteResult.hasUnpaved` es evidencia opcional, no una validación independiente: se deriva del campo booleano `maneuver.rough`, emitido por el [serializador oficial](https://github.com/valhalla/valhalla/blob/master/src/tyr/route_serializer_valhalla.cc) cuando `portions_unpaved` es verdadero. `true` permite avisar que el resultado incluye tierra pese a la preferencia. Si faltan campos, es `null`, nunca «asfalto verificado» por ausencia. Solo una respuesta con información explícita completa y todos false produce false; el backend habitual omite rough=false. No se inventa un campo summary.has_unpaved.
`RouteResult.hasUnpaved` is optional evidence, not independent validation: it derives from the boolean `maneuver.rough` emitted by the [official serializer](https://github.com/valhalla/valhalla/blob/master/src/tyr/route_serializer_valhalla.cc) when `portions_unpaved` is true. `true` permits a warning that the result includes unpaved sections despite the preference. Missing fields mean `null`, never “verified paved” through absence. Only a response with complete explicit information and all values false produces false; the usual backend omits rough=false. No summary.has_unpaved field is invented.
Android conserva las opciones usadas junto a la ruta para que los recálculos mantengan el perfil. Cambiar los controles prepara solicitudes futuras y no transforma retroactivamente una ruta activa. Las pruebas de serialización cubren independencia/combinación de preferencias, costing motorcycle y ausencia de exclusiones no verificadas; las pruebas de metadatos distinguen ausencia, evidencia positiva y booleanos inválidos. No se ha realizado un smoke HTTP para cada combinación nueva ni una prueba física de las preferencias.
Android retains the options used with the route so recalculations preserve the profile. Changing controls prepares future requests and does not retroactively transform an active route. Serialization tests cover independent/combined preferences, motorcycle costing, and absence of unverified exclusions; metadata tests distinguish absence, positive evidence, and invalid booleans. No HTTP smoke test for every new combination or physical preference test has been performed.
## Resultado puro JVM
## Pure JVM result
`parseValhallaRoute(json, destination=null)` devuelve `RouteResult`. Preserva el destino solicitado separado del extremo ajustado a carretera, geometría, longitud total y duración. `Maneuver` conserva instruction, type, begin/endShapeIndex, duración, nombres de vía y longitud **de su segmento**. Esta longitud no es la distancia actual del motorista hasta el próximo giro.
`parseValhallaRoute(json, destination=null)` returns `RouteResult`. It preserves the requested destination separately from the road-snapped endpoint, geometry, total length, and duration. `Maneuver` preserves instruction, type, begin/endShapeIndex, duration, road names, and **its segment's length**. That length is not the rider's current distance to the next turn.
El parser acepta JSON estricto, status exitoso y unidades explícitas kilómetros/millas; convierte a metros y segundos enteros redondeados. Decodifica polyline6, valida rangos geográficos, mediciones finitas/no negativas y límites de índices. Une legs por su punto común y rebasa índices sobre la geometría final. Rechaza legs desconectadas, respuestas de más de 2Mi caracteres, geometrías de más de 100.000 puntos o más de 128 legs. El HTTP adapter debe limitar también los bytes recibidos antes de construir el String. Mensajes de error propios no incluyen cuerpo remoto ni coordenadas.
The parser accepts strict JSON, successful status, and explicit kilometre/mile units; it converts to metres and rounded integer seconds. It decodes polyline6, validates geographic ranges, finite/nonnegative measurements, and index bounds. It joins legs at their shared point and rebases indices onto the final geometry. It rejects disconnected legs, responses over 2 Mi characters, geometries over 100,000 points, or more than 128 legs. The HTTP adapter must also limit received bytes before constructing the String. Local error messages include neither remote bodies nor coordinates.
JSON utiliza Gson 2.11.0 con `Strictness.STRICT`, API documentada en su [release oficial](https://github.com/google/gson/releases/tag/gson-parent-2.11.0). Adapter y decoder son código original del proyecto; no se incorpora código del motor Valhalla. Gson usa [Apache 2.0](https://github.com/google/gson/blob/gson-parent-2.11.0/LICENSE); Valhalla es [MIT](https://github.com/valhalla/valhalla/blob/master/COPYING). El mapa/ruta debe conservar crédito [© OpenStreetMap contributors](https://www.openstreetmap.org/copyright).
JSON uses Gson 2.11.0 with `Strictness.STRICT`, documented in its [official release](https://github.com/google/gson/releases/tag/gson-parent-2.11.0). The adapter and decoder are original project code; no Valhalla engine code is embedded. Gson uses [Apache 2.0](https://github.com/google/gson/blob/gson-parent-2.11.0/LICENSE); Valhalla uses [MIT](https://github.com/valhalla/valhalla/blob/master/COPYING). Maps/routes must retain [© OpenStreetMap contributors](https://www.openstreetmap.org/copyright).
## Verificación
## Verification
`ValhallaRouteTest` usa fixture original de estructura realista, no captura de GPS del usuario ni respuesta inventada presentada como ruta real. Cubre vector polyline6 independiente, kilómetros/millas, maniobras de llegada de longitud cero, unión de legs e índices, JSON no estricto, errores backend, overflow, coordenadas fuera de rango, formas truncadas y opciones de petición. Las pruebas no certifican disponibilidad pública, idoneidad de restricciones de moto, geocoder ni guía de giros.
`ValhallaRouteTest` uses an original realistically structured fixture, not user GPS recordings or an invented response presented as a real route. It covers an independent polyline6 vector, kilometres/miles, zero-length arrival maneuvers, leg joining/indices, non-strict JSON, backend errors, overflow, out-of-range coordinates, truncated shapes, and request options. Tests do not certify public availability, motorcycle restrictions, geocoding, or turn guidance.
Smoke HTTP autorizado: una única petición POST de demostración en Asturias (43.36,-5.85 → 43.365,-5.845), sin coordenadas del usuario, con User-Agent identificativo y X-Client-Id, devolvió HTTP200/status0 el 2026-09-29. Se aceptó motorcycle, units kilometers y language es-ES; la respuesta contenía un leg y diez maniobras en español, incluida llegada de longitud cero. Esto verifica el contrato de esta consulta, no disponibilidad continua ni restricciones de carretera. La comprobación HTTP y el render nativo Android deben reportarse por separado del parser JVM. La vista previa de fase 5 y el guiado básico de fase 6 se verifican por separado; sus umbrales no están calibrados con una prueba física de carretera. La prueba física TFT se realizará cuando el usuario esté disponible.
Authorized HTTP smoke test: one synthetic demonstration POST in Asturias (43.36,-5.85 → 43.365,-5.845), without user coordinates, with an identifying User-Agent and X-Client-Id, returned HTTP200/status0 on 2026-09-29. Motorcycle, units kilometers, and language es-ES were accepted; the response contained one leg and ten Spanish maneuvers, including a zero-length arrival. This validates that query's contract, not continuous availability or road restrictions. HTTP checks and native Android rendering must be reported separately from the JVM parser. Phase 5 preview and phase 6 basic guidance are verified separately; thresholds are not calibrated through a physical road test. Physical TFT testing depends on the user's availability.
## Basic guidance and limits — phase 6
## Guiado básico y límites — fase 6
`RouteGuidanceTracker(route).update(fix, nowMs, epochMs, fixAgeMs)` separates monotonic time, wall-clock time for ETA, and actual fix age. The caller must pass age from the provider and never assume a new tick means a new fix. Age up to 15 seconds and finite horizontal accuracy from 0 to 25 m are accepted. An unusable fix produces GPS_LOST without turn/countdown/ETA and breaks deviation/arrival evidence. The fix timestamp identifies distinct observations; repeated ticks do not advance state or confirm thresholds. An observation gap over 15 seconds also breaks evidence. Recovery after GPS_LOST or that gap requires two new fixes: the first establishes a baseline without progress, and the second stable fix allows reacquisition; absence does not enlarge the movement window.
`RouteGuidanceTracker(route).update(fix, nowMs, epochMs, fixAgeMs)` separa reloj monotónico, hora civil para ETA y edad real del fix. El caller debe pasar la edad desde el proveedor, nunca asumir que un tick nuevo implica un fix nuevo. Se acepta edad hasta 15s y precisión horizontal finita entre 0 y 25m. Un fix no utilizable produce GPS_LOST sin giro/countdown/ETA y rompe evidencia de desvío/llegada. El timestamp del fix identifica observaciones distintas; ticks repetidos no avanzan estado ni confirman umbrales. Un intervalo entre observaciones de más de 15s también rompe evidencia. Recuperar tras GPS_LOST o ese intervalo requiere dos fixes nuevos: el primero establece baseline sin avanzar y el segundo estable permite adquirir de nuevo; la ausencia no amplía la ventana de movimiento.
First acquisition uses the nearest valid projection over the entire route. Subsequent candidates are restricted to a local speed/time-dependent window, with 20 m backward tolerance and accumulated progress that does not retreat due to jitter. Distance to that candidate is checked before advancing. Position jumps incompatible with observed movement temporarily produce GPS_LOST; a later stable fix restores evaluation. These filters do not replace map matching: crossings, parallel branches, bridges, wrong-way travel, and prolonged GPS loss remain ambiguous. An isolated jump still temporarily produces GPS_LOST. If later fixes are stable but outside the reachable section, progress freezes and sustained evidence confirms OFF_ROUTE, allowing automatic recalculation; that deviation is not presented as GPS loss. Candidates are clipped to local-window endpoints to avoid artificial gaps near its boundaries. Do not infer a different road merely because other geometry is nearby.
La primera adquisición usa la proyección más cercana válida sobre toda la ruta. Después se limita el candidato a una ventana local dependiente de velocidad/tiempo, con tolerancia hacia atrás de 20m y progreso acumulado que no retrocede por jitter. Se verifica distancia a ese candidato antes de avanzar. Saltos de posición incompatibles con movimiento observado producen temporalmente GPS_LOST; un fix posterior estable recupera evaluación. Estos filtros no sustituyen map matching: cruces, ramales paralelos, puentes, conducción en sentido contrario y pérdidas prolongadas de GPS siguen siendo ambiguos. La política conservadora puede congelar progreso y ocultar guiado como GPS_LOST ante un salto grande hacia una sección posterior con proyección local ambigua; detener/iniciar o recalcular permite una adquisición nueva. No inferir una carretera distinta solo porque otra geometría está cerca.
The next turn uses geometric distance to `beginShapeIndex` and advances after passing it by more than 5 m. Official types 1/2/3 are Start/StartRight/StartLeft, departure instructions omitted from the next turn; regular Right/Left turns are 10/15. `maneuverDirection(type)` selects an icon without parsing translations. Arrival requires a road-snapped endpoint within 25 m, geometric remaining distance within 30 m, three distinct fixes, and at least two seconds; it then remains confirmed until the tracker is replaced. The [official maneuver types](https://valhalla.github.io/valhalla/api/route/api-reference/#trip-legs-and-maneuvers) support these IDs.
El próximo giro usa la distancia geométrica al `beginShapeIndex` y avanza después de pasarlo por más de 5m. Los tipos oficiales 1/2/3 son Start/StartRight/StartLeft, instrucciones de salida, y se omiten del próximo giro; los giros normales Right/Left son 10/15. `maneuverDirection(type)` elige icono sin analizar traducciones. Llegada exige extremo ajustado a carretera a ≤25m, restante geométrico ≤30m, tres fixes distintos y ≥2s; luego permanece confirmada hasta sustituir el tracker. Los [tipos oficiales de maniobra](https://valhalla.github.io/valhalla/api/route/api-reference/#trip-legs-and-maneuvers) sustentan esos IDs.
Deviation means distance from the geometrically reachable section based on previous progress greater than `max(40m, 2 × accuracy)` for at least five seconds and three distinct fixes. This includes reversing along the same road or reaching a distant later section even when near another part of the route. Recovery breaks the sequence. Turn estimates are hidden while position exceeds the threshold; OFF_ROUTE confirms the state after that evidence. OFF_ROUTE retains the route for the map but shows neither countdown nor ETA calculated as though still following it. All thresholds are configurable and await real-world calibration.
Desvío: separación de toda la geometría mayor que `max(40m, 2 × accuracy)` durante ≥5s y ≥3 fixes distintos. Una recuperación rompe la secuencia. Mientras la posición excede el umbral se ocultan estimaciones de giro; OFF_ROUTE confirma el estado después de esa evidencia. OFF_ROUTE conserva la ruta para el mapa, pero no muestra countdown ni ETA calculados como si se siguiera sobre ella. Todos esos umbrales son configurables y están pendientes de calibración real.
Remaining distance is pending geometric length. Real ETA is **approximate**: initial Valhalla duration multiplied by the remaining geometric fraction; it does not account for traffic, stops, or future speed. `RouteDemo(route).stateAt(elapsedMs, epochMs)` interpolates positions at 12 m/s and produces complete deterministic guidance up to ARRIVED; its ETA uses that speed. Android must continuously display DEMO and never use it to trigger HTTP recalculation.
El restante es longitud geométrica pendiente. ETA real es **aproximada**: duración inicial Valhalla multiplicada por fracción geométrica pendiente; no contempla tráfico, paradas ni velocidad futura. `RouteDemo(route).stateAt(elapsedMs, epochMs)` interpola posiciones a 12m/s y produce guiado completo determinista hasta ARRIVED; su ETA usa esa velocidad. Android debe mostrar DEMO continuamente y jamás utilizarlo para lanzar recálculo HTTP.
`ReroutePolicy` separates decision from IO: `shouldRequest`, `markRequested` before launching, and `markFinished` in finally, including errors/cancellation. An active request blocks another; cooldown after completion is at least 30 seconds and may extend with Retry-After. `reset` is only for a new session/manual action. Android additionally applies failure limits and HTTP429 blocking; route replacement must be atomic and retain the previous route on failure.
`ReroutePolicy` separa decisión de IO: `shouldRequest`, `markRequested` antes de lanzar y `markFinished` en finally, incluidos errores/cancelación. Un request activo bloquea otro; el cooldown tras finalización es al menos 30s, ampliable con Retry-After. `reset` solo para nueva sesión/acción manual. Android aplica además el límite de fallos y bloqueo HTTP429; una sustitución de ruta debe ser atómica y conservar la ruta anterior si falla.
`RouteGuidanceTest` cubre proyección/countdown/ETA, jitter y giro pasado, adquisición intermedia, ticks duplicados y separación temporal, tres observaciones de desvío/llegada, margen de precisión, fixes inválidos/stale, saltos y retorno, cruce de geometría, antimeridiano, single-flight/cooldown/Retry-After e interpolación demo. Son pruebas geométricas; no certifican guiado físico ni calidad de datos OSM.
`RouteGuidanceTest` covers projection/countdown/ETA, jitter/passed turns, intermediate acquisition, duplicate ticks/time gaps, three deviation/arrival observations, accuracy margins, invalid/stale fixes, jumps/return, geometry crossings, the antimeridian, single-flight/cooldown/Retry-After, and demo interpolation. `TftServiceRerouteTest` simulates Android GPS while reversing along the previous road and verifies one request from the current position with the same profile, one request in flight, and guidance recovery with the received route. These tests do not certify physical guidance or OSM data quality.
+124 -108
View File
@@ -1,184 +1,200 @@
# Testing and physical validation status (English summary)
# Testing and physical validation status
Automated checks and physical-device checks are separate. The `0.13.0` / versionCode 16 build passed 152 automated JVM/Robolectric tests (55 app, 87 core, 10 NaviLite), plus 11 Python offline-builder tests. Android lint reported 0 errors and 75 warnings. The debug APK is 81,266,845 bytes, SHA-256 `4901f4fe846e606d3db64e74e1e6b27ad554e46fc01d45d2f7091d441cee8eff`.
**Latest physical report — 2026-10-12:** using the latest version (exact version number not supplied), the rider saw the map work correctly on the Yamaha TFT for approximately 20 minutes. In La Corredoria, Oviedo, the TFT then displayed **“Mapa no disponible”** (“Map unavailable”) and did not recover for the rest of the trip, while the map continued working on the phone with an offline map installed. Whether the phone was locked or the app was in the background, and any diagnostic error code, are unknown. This establishes successful TFT map rendering followed by a persistent failure; it does not establish the failure's cause or prove the TFT's active source was the installed offline map. See the [incident investigation](TFT_MAP_INCIDENT_2026-10-12.md) for findings and recovery checks.
The owner confirmed that static and synthetic NavFrame frames appeared on a Xiaomi 11 Lite 5G NE (Android 14) and a 2026 Yamaha MT-07. The owner also confirmed that the Asturias offline map works on the phone. The last reported MapLibre map attempt on the Yamaha TFT displayed `MAPA NO DISPONIBLE`; a successful physical map render on the TFT is not recorded. Offline regional POI search, route guidance, GPS quality, voice playback, camera alert timing, intercom audio, Bluetooth recovery, and a 30-minute screen-off session still need physical validation unless a newer report records them.
Offline POI behavior, GPS quality, voice instructions, camera-alert timing, intercom audio, Bluetooth recovery, and a controlled 30-minute screen-off session still require physical validation unless a newer report records them. Older statements below describe evidence available at the time and are superseded by the report above.
JVM/Robolectric tests do not run MapLibre JNI/OpenGL or exercise a physical Yamaha display, motorcycle, Bluetooth intercom, or Android TextToSpeech hardware. The detailed historical procedures and per-version records below are maintained in Spanish; the current status above is the English summary.
Automated checks and physical-device checks are separate. Local verification for `0.13.1` passed 159 unit tests (60 app, 89 core, 10 NaviLite), 17 Python offline-builder tests, Android APK assembly, and lint with zero errors and 76 warnings. The earlier `0.13.0` / versionCode 16 build passed 152 automated JVM/Robolectric tests (55 app, 87 core, 10 NaviLite), plus 11 Python offline-builder tests. Android lint reported 0 errors and 75 warnings. Its debug APK was 81,266,845 bytes, SHA-256 `4901f4fe846e606d3db64e74e1e6b27ad554e46fc01d45d2f7091d441cee8eff`.
# Historical test procedures (Spanish)
The owner confirmed static and synthetic NavFrame frames on a Xiaomi 11 Lite 5G NE (Android 14) and a 2026 Yamaha MT-07, and the Asturias offline map on the phone. JVM/Robolectric tests do not run MapLibre JNI/OpenGL or exercise a physical Yamaha display, motorcycle, Bluetooth intercom, or Android TextToSpeech hardware.
## M1-TFT: preparación y humo
UI labels below are translated for readability; the installed app may display their Spanish equivalents. Literal status strings and diagnostic messages are retained where useful.
**M1-TFT completado:** el usuario confirma que NavFrame mostró tanto la imagen fija como la imagen sintética de navegación en la TFT de su Yamaha MT-07 2026, con un Xiaomi 11 Lite 5G NE con Android 14. StreetCross también funciona con esa combinación. La vista previa local y el fake siguen siendo pruebas separadas de la compatibilidad física.
## Historical test procedures
Se observó que la sesión podía desconectarse cuando no llegaban frames nuevos. La versión `0.1.1-continuous` ya conserva y reenvía el último JPEG, mantiene un servicio de primer plano con wake lock parcial acotado y reintenta con pausas de 1, 2, 4, 8 y hasta 15 segundos. El intervalo seleccionable es 0,5, 1 o 2 segundos (1 segundo por defecto). Esta lógica pasó pruebas unitarias, pero el uso prolongado con la pantalla apagada y el cierre completo al pulsar **Desconectar** todavía requieren validación en el teléfono del usuario.
### M1-TFT: preparation and smoke test
### Comprobación local (sin moto)
**M1-TFT completed:** the user confirmed both the static image and synthetic navigation image on the TFT of a 2026 Yamaha MT-07, using a Xiaomi 11 Lite 5G NE with Android 14. StreetCross also works with that combination. Local preview and fake transport remain separate from physical compatibility tests.
1. Compilar e instalar con los comandos de la raíz descritos en `README.md`.
2. Abrir NavFrame. La vista previa aparece antes de conectar y muestra el JPEG generado por `TestTftRenderer` dentro de un visor de 480×240.
3. Pulsar **Conectar simulador**. El estado de conexión debe pasar a `CONNECTED` y el mensaje termina en «Simulador conectado · sin sesión Bluetooth continua». Pulsar **Enviar texto de navegación sintética**; el visor refleja los valores fijos (NEXT TURN 350 m, 23 km, ETA 17:42). Pulsar **Desconectar** al terminar.
4. Esta ruta usa `FakeTftTransport`, no abre Bluetooth ni requiere permiso, y el visor enseña los mismos bytes JPEG que el fake recibe. Verifica render y flujo local. No valida handshake, escritura Bluetooth ni imagen en la TFT física.
The session was observed disconnecting when no new frames arrived. Version `0.1.1-continuous` retains and resends the last JPEG, maintains a foreground service with a bounded partial wake lock, and retries after 1, 2, 4, 8, and up to 15 seconds. Selectable intervals are 0.5, 1, or 2 seconds (default: one second). This logic passed unit tests, but prolonged screen-off operation and complete shutdown after **Disconnect** still require validation on the user's phone.
### Procedimiento M1 (ya completado; repetir solo tras cambios de protocolo)
#### Local check (without a motorcycle)
Usar primero el Xiaomi 11 Lite 5G NE (Android 14) y la MT-07 2026 que ya funcionan con StreetCross. Preparar teléfono y motocicleta detenida en un lugar seguro. Cerrar completamente StreetCross antes de la prueba para que no compita por la sesión del CCU. Activar Bluetooth. En NavFrame, pulsar **Actualizar dispositivos emparejados** y conceder permiso de dispositivos cercanos / `BLUETOOTH_CONNECT`; si aún no hay vínculo, usar **Abrir ajustes Bluetooth / emparejar** y completar el emparejamiento según las instrucciones de la moto. Volver a NavFrame, actualizar, seleccionar la Yamaha en la lista y pulsar **Conectar Yamaha seleccionada**. Autorizar notificaciones si Android lo solicita para la sesión de primer plano. Al completar setup, el estado debe pasar a `CONNECTED` y la app intenta enviar automáticamente la imagen fija; el mensaje queda como «Imagen enviada: … bytes · … ms» si recibió el ACK de servicio. Después se pueden probar **Enviar imagen de prueba** y **Enviar texto de navegación sintética**. Mantener la app en primer plano para el primer diagnóstico. Registrar modelo/año de moto, modelo/versión Android, versión de app, estado de emparejamiento, resultado de conexión y handshake, y si la imagen aparece completa en la TFT. Evitar registrar ubicación precisa, identificadores Bluetooth o datos personales en logs compartidos.
1. Build and install using the root commands documented in `README.md`.
2. Open NavFrame. Preview appears before connection and shows the JPEG generated by `TestTftRenderer` in a 480×240 viewer.
3. Press **Connect simulator**. Connection state must become `CONNECTED`, and the message ends with “Simulator connected · no continuous Bluetooth session.” Press **Send synthetic navigation text**; the viewer reflects fixed values (NEXT TURN 350 m, 23 km, ETA 17:42). Press **Disconnect** afterward.
4. This path uses `FakeTftTransport`, opens no Bluetooth connection, requires no permission, and displays the same JPEG bytes received by the fake. It verifies local rendering/flow, not handshake, Bluetooth writes, or the physical TFT image.
Éxito observable ya reportado: ambas imágenes de NavFrame aparecen en la TFT, sin usar MediaProjection ni capturar otra aplicación. Esto acredita el humo de conexión/render M1 para ese teléfono y esa MT-07 2026; no demuestra todavía estabilidad durante periodos largos, navegación real, GPS ni compatibilidad con otros años Yamaha.
#### M1 procedure (completed; repeat only after protocol changes)
### Prueba de pantalla apagada y recuperación (pendiente)
Start with the Xiaomi 11 Lite 5G NE (Android 14) and 2026 MT-07 already working with StreetCross. Prepare the phone and stationary motorcycle in a safe location. Completely close StreetCross so it does not compete for the CCU session. Enable Bluetooth. In NavFrame, press **Refresh paired devices** and grant nearby-device permission / `BLUETOOTH_CONNECT`; if not paired, use **Open Bluetooth settings / pair** and follow the motorcycle's instructions. Return to NavFrame, refresh, select Yamaha, and press **Connect selected Yamaha**. Allow notifications if Android requests them for the foreground session. After setup, state must become `CONNECTED`; the app automatically attempts to send the static image. The message becomes “Image sent: … bytes · … ms” after the service ACK. Then test **Send test image** and **Send synthetic navigation text**. Keep the app foregrounded for initial diagnosis. Record motorcycle model/year, phone model/Android version, app version, pairing state, connection/handshake result, and whether the complete image appears on the TFT. Avoid precise location, Bluetooth identifiers, or personal data in shared logs.
Instalar la versión `0.2.0` (o posterior) en la Xiaomi 11 Lite 5G NE (Android 14) y usar la MT-07 2026. Cerrar StreetCross y las otras apps de navegación, conectar NavFrame y comprobar primero que se muestra una de las imágenes confirmadas en M1. Revisar en pantalla el estado de optimización de batería. Si Android/Xiaomi impide que la sesión continúe, abrir los ajustes con **Abrir ajustes de optimización de batería** y anotar el cambio que se haga; la app no cambia la política automáticamente. Dejar la moto estacionada de forma segura, con TFT/CCU encendidos, y apagar la pantalla del teléfono; no realizar la prueba mientras se conduce.
Reported observable success: both NavFrame images appear on the TFT without MediaProjection or capturing another application. This validates M1 connection/render smoke testing for that phone and MT-07; it does not establish long-term stability, real navigation, GPS, or compatibility with other Yamaha model years.
Dejar NavFrame en segundo plano y la pantalla apagada durante 30 minutos. Comprobar que la TFT conserva y refresca el último frame, y que al volver a abrir NavFrame el estado aparece conectado y el mensaje muestra «Sesión continua · … ACK … ms». Anotar si Android detuvo el servicio, si hubo cortes visibles, el tiempo hasta la recuperación y cualquier aviso de batería/permisos. En una prueba separada y con la moto parada, desactivar el Bluetooth del teléfono durante unos 10 segundos y volverlo a activar; comprobar que NavFrame muestra el estado de reintento y vuelve a enviar el frame sin iniciar StreetCross ni pulsar conectar. No registrar ubicación ni identificadores Bluetooth.
#### Screen-off and recovery test (pending)
Al terminar, volver a NavFrame y pulsar **Desconectar**. Comprobar que desaparece la notificación de navegación, el estado cambia a `DISCONNECTED`, el mensaje indica «Desconectado · envío y reconexión detenidos» y no hay nuevos reintentos. La última imagen puede quedar estática en la TFT; eso no significa que el servicio siga enviando. La pantalla de la app muestra el estado de la optimización Android, no el estado del wake lock.
Install `0.2.0` or later on the Xiaomi 11 Lite 5G NE (Android 14) and use the 2026 MT-07. Close StreetCross and other navigation apps, connect NavFrame, and first confirm an M1 image. Check the displayed battery-optimization state. If Android/Xiaomi prevents the session continuing, use **Open battery optimization settings** and record any change; the app does not change policy automatically. Leave the motorcycle safely parked with TFT/CCU powered and turn off the phone screen; do not conduct this test while riding.
Para comprobar de forma técnica que el wake lock se libera, con depuración USB autorizada puede consultarse el teléfono antes y después de desconectar: `adb shell dumpsys power | grep -F 'NavFrame:TftSession'`. Debe aparecer durante la sesión real activa y dejar de aparecer después de **Desconectar**. Esta comprobación es opcional y no sustituye la prueba de 30 minutos en el teléfono.
Leave NavFrame backgrounded with the screen off for 30 minutes. Check that the TFT retains and refreshes the last frame and that reopening NavFrame shows a connected state and “Continuous session · … ACK … ms.” Record service termination by Android, visible interruptions, recovery time, and battery/permission warnings. In a separate stationary test, disable phone Bluetooth for approximately ten seconds and re-enable it; verify retry state and frame transmission resume without opening StreetCross or pressing Connect. Do not record location or Bluetooth identifiers.
### Fase 2: demo animada (datos ficticios)
Finally press **Disconnect**. Verify the navigation notification disappears, state becomes `DISCONNECTED`, the message says “Disconnected · sending and reconnection stopped,” and no further retries occur. The last TFT image may remain static; that does not mean the service keeps transmitting. The app shows Android optimization state, not wake-lock state.
1. Abrir NavFrame y, opcionalmente, pulsar **Conectar simulador** o conectar la Yamaha. La demo también puede comprobarse solo en la vista previa.
2. Pulsar **Iniciar demo animada**. No requiere permiso de ubicación. Confirmar que el estado indica `DEMO · carretera, ruta y maniobras ficticias`, que la vista previa cambia y que el JPEG es 480×240.
3. La imagen debe llevar `DEMO · RUTA FICTICIA` y `ETA … · DEMO`; posición, velocidad, carretera, ruta y maniobras son datos inventados. Si está conectada la TFT, confirmar visualmente allí los frames dinámicos. El simulador local solo verifica la vista previa/flujo local, no Bluetooth físico.
4. Pulsar **Detener navegación · mantener TFT**. Debe detener la demo y dejar la conexión TFT disponible; **Desconectar TFT** detiene la sesión Bluetooth también.
For a technical wake-lock release check with authorized USB debugging, inspect before and after disconnecting: `adb shell dumpsys power | grep -F 'NavFrame:TftSession'`. It should appear during the active real session and disappear after **Disconnect**. This optional check does not replace the 30-minute phone test.
### Fase 3: GPS real sin mapa ni ruta
### Phase 2: animated demo (fictional data)
Prueba inicial aparcado y en un lugar seguro; no manipular el teléfono durante la conducción. En el Xiaomi 11 Lite 5G NE con Android 14, cerrar StreetCross antes de conectar la moto para evitar competencia por el canal. Activar ubicación del teléfono. Pulsar **Iniciar GPS real (sin mapa/ruta)** y conceder ubicación precisa cuando Android la solicite. La app necesita `ACCESS_FINE_LOCATION`; si se concede solo ubicación aproximada, explicar que GPS real no puede arrancar y que la demo sigue disponible. Android puede pedir notificaciones para mostrar el servicio en primer plano. La aplicación inicia GPS desde una pantalla visible y no pide permiso de ubicación permanente/en segundo plano.
1. Open NavFrame and optionally press **Connect simulator** or connect Yamaha. Preview alone can also test the demo.
2. Press **Start animated demo**. No location permission is required. Confirm `DEMO · carretera, ruta y maniobras ficticias`, changing preview, and a 480×240 JPEG.
3. The image must display `DEMO · RUTA FICTICIA` and `ETA … · DEMO`; position, speed, road, route, and maneuvers are invented. If TFT is connected, visually confirm dynamic frames there. The local simulator validates preview/local flow, not physical Bluetooth.
4. Press **Stop navigation · keep TFT**. The demo stops while TFT connection remains available; **Disconnect TFT** also stops Bluetooth.
Si el proveedor GPS está apagado, NavFrame indica que hay que activarlo en **Abrir ajustes de ubicación** y volver a pulsar GPS. En un lugar con recepción, esperar un fix: la UI y la TFT deben indicar `GPS · SIN MAPA/RUTA`; se muestran velocidad, rumbo si Android lo entrega, precisión y una cuadrícula de prueba, nunca una ruta real. GPS puede ejecutarse sin TFT para probar la vista previa; con una Yamaha conectada, el mismo frame se transmite a la pantalla. La posición exacta se mantiene en memoria y no debe aparecer en logs ni capturas compartidas.
### Phase 3: real GPS without a map or route
Comprobar el estado sin fix: al superar 15 segundos desde la última posición válida, la pantalla indica `SIN SEÑAL` / `GPS_LOST`, velocidad/rumbo/precisión aparecen como no disponibles y el texto espera una posición reciente. Al volver la señal, los datos deben actualizarse. Se puede revocar el permiso desde **Abrir permisos de NavFrame** para comprobar que la app ofrece la demo como alternativa.
Start parked in a safe location; do not operate the phone while riding. On the Xiaomi 11 Lite 5G NE with Android 14, close StreetCross before connecting the motorcycle to avoid channel competition. Enable phone location. Press **Start real GPS (no map/route)** and grant precise location when Android requests it. The app needs `ACCESS_FINE_LOCATION`; approximate-only permission must explain that real GPS cannot start while the demo remains available. Android may request notifications for the foreground service. GPS starts from a visible screen and requests no permanent/background-location permission.
Pulsar **Detener navegación · mantener TFT**. Debe cesar la fuente GPS y aparecer `NAVEGACIÓN DETENIDA`, conservando la sesión de la TFT si estaba conectada. **Desconectar TFT** finaliza además la conexión; la acción de notificación **Detener todo** cancela navegación y conexión. No inferir liberación de wake lock o estabilidad de pantalla apagada de esta prueba.
If the GPS provider is off, NavFrame asks to enable it via **Open location settings**, then press GPS again. With reception, wait for a fix: UI/TFT must show `GPS · SIN MAPA/RUTA`; speed, heading when supplied by Android, accuracy, and a test grid appear, never a real route. GPS can run without TFT to test preview; with Yamaha connected, the same frame is transmitted. Exact position stays in memory and must not appear in shared logs or screenshots.
Esta fase comprueba posición y render local, no mapas, destino, geocodificación, ruta calculada ni indicaciones giro a giro. La demo nunca debe confundirse con una navegación real. Mantener separadas las evidencias: preview/fake, GPS real en teléfono y TFT física.
Check the no-fix state: more than 15 seconds after the last valid position, display `SIN SEÑAL` / `GPS_LOST`, mark speed/heading/accuracy unavailable, and wait for a recent position. Data should update when reception returns. Revoke permission through **Open NavFrame permissions** to verify the app offers the demo as an alternative.
### Fase 4: mapa real MapLibre
Press **Stop navigation · keep TFT**. GPS stops and `NAVEGACIÓN DETENIDA` appears, preserving any TFT session. **Disconnect TFT** also ends connection; notification action **Stop everything** cancels navigation and connection. Do not infer wake-lock release or screen-off stability from this test.
La fase añade botones **Iniciar Mapa demo (posición simulada)** y **Iniciar Mapa GPS (sin ruta)**, un campo opcional URL HTTPS de estilo vectorial, atribución y **Guardar fuente de mapa**. Con URL vacía usa el estilo oscuro reducido de NavFrame en assets y la fuente OpenFreeMap; el estilo personalizado debe ser un style JSON completo compatible con MapLibre y llevar todos sus créditos en el campo atribución. No introducir `tile.openstreetmap.org` como fuente. El endpoint público OpenFreeMap no requiere clave, pero el servicio no ofrece SLA.
This phase checks position and local rendering, not maps, destinations, geocoding, calculated routes, or turn-by-turn directions. The demo must never be mistaken for real navigation. Keep preview/fake, real phone GPS, and physical TFT evidence separate.
1. Probar primero solo con preview/fake y una conexión de red. Guardar la configuración por defecto (URL vacía y créditos predeterminados), iniciar **Mapa demo** y esperar la primera captura. Debe aparecer cartografía real alrededor de la posición inventada y el estado `MAPA · POSICIÓN SIMULADA · sin ruta`; el indicador móvil en TFT no incluye una línea de ruta ni maniobras. La primera petición online puede tardar; los siguientes snapshots deben actualizarse de forma serial, sin acumular frames.
2. Con GPS preciso autorizado, ubicación activa y teléfono aparcado en exterior, iniciar **Mapa GPS**. La vista previa debe mostrar calles reales alrededor del fix del teléfono y `MAPA GPS · SIN RUTA`. Si también se conecta la Yamaha, comprobar que el JPEG 480×240 recibido conserva la atribución y el indicador. Repetir con GPS sin señal; no deben mostrarse medidas actuales como si fueran válidas.
3. Comprobar una fuente inválida/desconexión de red; NavFrame debe mostrar `MAPA NO DISPONIBLE`, vaciar velocidad/rumbo actuales y reintentar con pausa. No debe sustituir el mapa por la carretera ilustrativa de la demo. Restaurar la red debe recuperar el mapa. Si falla el snapshot TFT, abrir **Ajustes → Información → Diagnóstico del mapa TFT** y revisar código, etapa, tiempo y origen ONLINE/LOCAL; el informe evita coordenadas, URLs y consultas. Sus categorías ayudan a orientar el diagnóstico, pero no identifican por sí solas una causa raíz. Cambiar estilo/fuente detiene la navegación en curso, conserva la configuración local y obliga a iniciar el modo de nuevo.
4. Usar **Detener navegación · mantener TFT** durante una captura: debe cancelar el MapSnapshotter, evitar que un callback atrasado publique un frame de navegación y conservar la sesión Bluetooth. **Desconectar TFT** detiene además la conexión.
### Phase 4: real MapLibre map
La app no registra coordenadas ni URL/tokens en logs; aun así, cargar un mapa remoto envía solicitudes de los recursos de la zona visible al origen configurado, revelando esa área junto con metadatos de red. OpenFreeMap declara que no guarda IP en logs regulares, pero puede usar CDN y hacer logging temporal ante incidentes; revisar su [política de privacidad](https://openfreemap.org/privacy/) y [términos](https://openfreemap.org/tos/). No hay modo de descarga offline en esta fase. La TFT debe mostrar como mínimo `© OpenStreetMap contributors · © OpenMapTiles` y los créditos adicionales que reporte el estilo/configuración; el teléfono expone licencia/créditos desde **Licencia MapLibre y créditos de mapas**.
This phase adds **Start demo map (simulated position)** and **Start GPS map (no route)**, an optional HTTPS vector-style URL, attribution, and **Save map source**. An empty URL uses NavFrame's reduced dark asset style and OpenFreeMap source; custom styles must be complete MapLibre-compatible style JSON with all credits in attribution. Do not use `tile.openstreetmap.org` as a source. Public OpenFreeMap requires no key but offers no SLA.
El mapa real requiere verificación en dispositivo Android con GPU y conectividad. Los tests Robolectric de composición no cargan JNI/OpenGL ni confirman que el endpoint sirva tiles; la compilación tampoco prueba render nativo. La prueba del mapa en Xiaomi/MT-07 queda pendiente hasta que el usuario pueda hacerla con la moto detenida.
1. Start with preview/fake and network access. Save defaults (empty URL and default credits), start **Demo map**, and wait for the first snapshot. Real cartography must appear around the invented position with `MAPA · POSICIÓN SIMULADA · sin ruta`; the TFT position indicator includes neither route line nor maneuvers. The initial online request may take time; subsequent snapshots must update serially without accumulating frames.
2. With precise GPS authorized, location enabled, and phone parked outdoors, start **GPS map**. Preview must show real streets around the phone fix and `MAPA GPS · SIN RUTA`. With Yamaha connected, verify the received 480×240 JPEG preserves attribution and indicator. Repeat without GPS signal; current measurements must not appear valid.
3. Test an invalid source/network disconnection. NavFrame must display `MAPA NO DISPONIBLE`, clear current speed/heading, and retry with pauses, without substituting the demo's illustrated road. Restoring the network should recover the map. If TFT snapshot fails, open **Settings → Info → TFT map diagnostics** and inspect code, stage, timing, and ONLINE/LOCAL source; reports omit coordinates, URLs, and queries. Categories guide diagnosis but do not independently identify a root cause. Changing style/source stops current navigation, preserves local configuration, and requires restarting the mode.
4. Use **Stop navigation · keep TFT** during capture: cancel MapSnapshotter, prevent a late callback publishing a navigation frame, and preserve Bluetooth. **Disconnect TFT** also stops connection.
### Fase 5: cálculo y visualización de un plan (sin guiado)
The app logs neither coordinates nor URLs/tokens. Loading a remote map nevertheless requests visible-area resources from the configured origin, revealing that area and network metadata. OpenFreeMap states that regular logs omit IPs, but may use a CDN and temporary incident logging; review its [privacy policy](https://openfreemap.org/privacy/) and [terms](https://openfreemap.org/tos/). This phase has no offline-download mode. TFT must show at least `© OpenStreetMap contributors · © OpenMapTiles` plus additional style/configuration credits; the phone exposes licenses/credits through **MapLibre license and map credits**.
Esta fase calcula una ruta solo tras una acción explícita y dos coordenadas. No hay geocodificador: introduce latitud/longitud del destino. En **Origen DEMO Oviedo · simulado**, el origen es una posición inventada de Oviedo. En **Origen GPS real · última posición**, se exige un proveedor GPS activo y un fix de menos de 15 segundos; inicia **Iniciar GPS real** o **Iniciar Mapa GPS** y espera una posición reciente antes de calcular. El resultado identifica cuál de los dos orígenes se utilizó. No uses la opción demo para desplazamientos reales.
Real maps require an Android device with GPU and connectivity. Robolectric composition tests load no JNI/OpenGL and do not confirm tile endpoint availability; compilation does not test native rendering. At this phase, the Xiaomi/MT-07 map test remained pending until the user could perform it with the motorcycle stationary.
Para una prueba de desarrollo, usa el servidor público `https://valhalla1.openstreetmap.de/route` solo con coordenadas no sensibles; también puedes configurar un endpoint HTTPS propio. Al calcular se envían el origen y destino al endpoint seleccionado, por lo que el servidor ve esas coordenadas y la solicitud llega desde la IP del teléfono. La aplicación limita solicitudes a una por segundo y envía `User-Agent` y `X-Client-Id`. El guiado GPS puede recalcular por desvío confirmado, con cooldown de al menos 30 segundos; HTTP429 pausa el automático. La instancia pública tiene fair-use y no ofrece SLA; consulta [ROUTING.md](ROUTING.md) antes de usar otro servicio o distribuir la app.
### Phase 5: calculate and display a plan (without guidance)
1. Selecciona el origen DEMO; introduce coordenadas de destino válidas; pulsa **Calcular ruta · vista previa**. Deben aparecer distancia, duración estimada, número de maniobras y el texto `origen DEMO`. Pulsa **Ver ruta en mapa** para ver la polilínea marcada como previa, La vista previa no activa guiado; **Iniciar guiado de ruta calculada** activa las indicaciones.
2. Para el origen GPS, concede ubicación precisa, inicia GPS y espera un fix reciente. Selecciónalo y calcula otra ruta con un destino no sensible. Debe aparecer `origen GPS`; si falta el permiso, el proveedor está apagado o el fix supera 15 segundos, la app debe pedir un fix reciente y no enviar una nueva solicitud. El resultado muestra el plan desde las coordenadas del fix usado al calcularlo.
3. Comprueba cancelación pulsando **Cancelar cálculo**. Calcula rutas sucesivas y cambia de destino: un resultado atrasado no debe sustituir un cálculo posterior. Cambiar entre demo y GPS debe retirar el plan anterior; también prueba un destino mal formado después de cargar una ruta para comprobar que no reaparece el plan previo. **Detener ruta · mantener GPS/TFT** elimina el plan mostrado y conserva la fuente GPS/mapa y la conexión TFT; **Detener navegación · mantener TFT** detiene además la fuente de navegación. Un error HTTP, 429 o falta de red debe poder repetirse manualmente y no debe recuperar una ruta vieja como si fuera nueva.
4. Comprueba el overlay con el mapa visible. La línea representa solo la geometría recibida de Valhalla; el marcador indica la posición actual/demo, pero no el progreso sobre la ruta. El tiempo es una estimación del backend. El perfil `motorcycle` está en beta y la ruta no certifica restricciones o seguridad para esta moto.
This phase calculates a route only after explicit action and two coordinates. There is no geocoder at this stage: enter destination latitude/longitude. **DEMO Oviedo origin · simulated** uses an invented Oviedo position. **Real GPS origin · latest position** requires an active GPS provider and a fix younger than 15 seconds; start **Start real GPS** or **Start GPS map** and wait for a recent position before calculating. The result identifies the origin used. Do not use the demo for real travel.
Esta función todavía no tiene validación física de una ruta renderizada en el Xiaomi/TFT. La fase 6 añade guiado básico y recálculo, descritos abajo. Siguen pendientes voz y comprobación de carreteras aptas para motocicleta. No usarla para guiar una conducción. Las pruebas de parser, HTTP simulado o una consulta sintética al servidor no sustituyen el render GPU en un teléfono ni el ensayo con la TFT; mantienen pendiente también la prueba GPS física y los 30 minutos en pantalla apagada.
For development, use `https://valhalla1.openstreetmap.de/route` only with nonsensitive coordinates, or configure a custom HTTPS endpoint. Calculation sends origin/destination to the selected endpoint, revealing those coordinates and phone IP. The app limits requests to one per second and sends `User-Agent` and `X-Client-Id`. GPS guidance may recalculate after confirmed deviation with at least 30 seconds cooldown; HTTP429 pauses automatic recalculation. The public instance has fair-use conditions and no SLA; read [ROUTING.md](ROUTING.md) before changing service or distributing the app.
### Fase 6: guiado y recálculo
1. Select DEMO origin, enter valid destination coordinates, and press **Calculate route · preview**. Distance, estimated duration, maneuver count, and `origen DEMO` must appear. **View route on map** shows the polyline marked as preview. Preview does not activate guidance; **Start calculated-route guidance** does.
2. For GPS origin, grant precise location, start GPS, wait for a recent fix, select it, and calculate another route to a nonsensitive destination. `origen GPS` must appear. Missing permission, disabled provider, or a fix older than 15 seconds must request a recent fix without sending another request. The result shows a plan from the fix used for calculation.
3. Press **Cancel calculation** to test cancellation. Calculate successive routes/change destination: late results must not replace later calculations. Switching DEMO/GPS must remove the earlier plan. Enter a malformed destination after loading a route to verify the previous plan does not reappear. **Stop route · keep GPS/TFT** removes the displayed plan while preserving GPS/map and TFT; **Stop navigation · keep TFT** also stops the navigation source. HTTP errors, 429, or missing network must permit manual retry without presenting an old route as new.
4. Check the visible map overlay. The line represents only Valhalla's returned geometry; the marker shows current/demo position, not route progress. Time is a backend estimate. The beta `motorcycle` profile does not certify restrictions or safety for this motorcycle.
1. En casa, calcula una ruta con origen DEMO y pulsa **Iniciar guiado de ruta calculada**. El marcador debe recorrerla, cambiar la próxima maniobra y reducir distancia restante hasta llegada. DEMO permanece visible; no lanza recálculos HTTP.
2. Para GPS, usa ubicación precisa y una posición reciente. El guiado exige precisión finita de hasta 25 m; con señal insuficiente oculta giro, distancia y ETA. ETA es aproximada, basada en la duración de Valhalla y la fracción geométrica restante.
3. El desvío requiere al menos tres posiciones distintas durante cinco segundos, separadas de la ruta más de max(40 m, dos veces la precisión). El recálculo conserva la ruta anterior hasta recibir otra válida. Un error no sustituye la ruta; HTTP429 y tres fallos pausan el automático. **Recalcular ahora (GPS)** permite reintentar respetando el cooldown y Retry-After.
4. **Cancelar cálculo** cancela también el recálculo activo y pausa el automático. Comprueba que detener o cambiar de modo impide que una respuesta atrasada restaure el guiado.
At this phase, a route rendered on Xiaomi/TFT had no physical validation. Phase 6 adds basic guidance and recalculation below. Voice and motorcycle-suitable roads remained unverified; the phase was not ready to guide a ride. Parser, mocked HTTP, and synthetic server queries do not replace phone GPU rendering or TFT testing, nor physical GPS and the 30-minute screen-off test.
La imagen `app/build/outputs/preview/guidance.png` se exporta con Canvas Android en Robolectric: comprueba el HUD sobre una base dibujada de prueba, no el render GPU de MapLibre. Las pruebas físicas de guiado, desvío, recálculo, GPS y pantalla apagada siguen pendientes. Los umbrales aún no están calibrados en carretera; los límites geométricos están en [ROUTING.md](ROUTING.md).
### Phase 6: guidance and recalculation
### Fase 7: búsqueda explícita de destino
1. At home, calculate a DEMO-origin route and press **Start calculated-route guidance**. The marker must follow the route, update the next maneuver, and reduce remaining distance until arrival. DEMO remains visible and triggers no HTTP recalculation.
2. For GPS, use precise location and a recent fix. Guidance requires finite accuracy up to 25 m; inadequate signal hides turn, distance, and ETA. ETA is approximate, based on Valhalla duration and remaining geometric fraction.
3. Deviation requires at least three distinct positions over five seconds, separated from the route by more than max(40 m, twice accuracy). Recalculation retains the previous route until another valid route arrives. Errors do not replace it; HTTP429 and three failures pause automatic requests. **Recalculate now (GPS)** permits retry while respecting cooldown and Retry-After.
4. **Cancel calculation** also cancels active recalculation and pauses automatic requests. Stopping/changing mode must prevent late responses restoring guidance.
La búsqueda se inicia solo al pulsar **Buscar**; escribir no emite solicitudes. Escribe un nombre/dirección con ciudad, revisa el endpoint HTTPS y pulsa Buscar. Para el servicio público usa solo consultas no sensibles: el proveedor recibe el texto y la IP de origen. La UI informa que no envía GPS; evita datos personales/confidenciales. No ofrece autocomplete ni consulta de resultados mientras se escribe. Puedes cambiar el endpoint Nominatim-compatible desde Ajustes sin actualizar la app.
`app/build/outputs/preview/guidance.png` is exported with Android Canvas in Robolectric: it checks HUD composition on a drawn test base, not MapLibre GPU rendering. At this stage physical guidance, deviation, recalculation, GPS, and screen-off tests remained pending. Thresholds were not road-calibrated; geometric limits are documented in [ROUTING.md](ROUTING.md).
1. Prueba primero una consulta sintética no privada (por ejemplo un sitio público conocido) y confirma que el resultado incluye nombre completo y atribución OSM/licencia. Sin resultados no es un error. Cambiar el texto o endpoint durante la búsqueda debe cancelar la petición anterior y borrar sus botones; una respuesta atrasada no puede reemplazar la consulta nueva.
2. Pulsa **Cancelar búsqueda** mientras se consulta; debe cerrarse la conexión y no quedar un resultado seleccionable. Repite una consulta idéntica para comprobar el cache de memoria, incluida la respuesta vacía; cambia endpoint/idioma/parámetro para comprobar que no se mezclan entradas. Cache y rate limit viven solo en memoria del proceso (100 entradas/24 h); no se persiste historial.
3. Al elegir un resultado, la app rellena el destino y empieza a calcular una vista previa. No inicia guiado: comprueba que no aparecen maniobras activas antes de pulsar Iniciar. Editar la consulta después debe borrar el destino anterior; pulsar Calcular sin elegir un resultado actual no debe reutilizar coordenadas anteriores. Con guiado en curso, elegir otro resultado y calcularlo debe mantener el guiado actual mientras espera o si falla la respuesta. Un plan nuevo tampoco sustituye al guiado hasta pulsar **Iniciar**. **Detener ruta** elimina la ruta activa a petición. No se selecciona automáticamente el primer resultado.
4. No hagas pruebas de fuerza contra el servicio público. La política OSMF limita todas las instalaciones de esta app juntas a un máximo absoluto de una petición por segundo. El adapter serializa solicitudes, cachea consultas, identifica la app con User-Agent y respeta Retry-After de 429; un 429 bloquea nuevas búsquedas hasta que pase el periodo y requiere acción manual, sin bucle de reintentos. Tests de adapter con servidor controlado cubren cancelación, query encoding, cache y 429; no generes tráfico de prueba automático hacia Nominatim público.
### Phase 7: explicit destination search
Esta búsqueda proporciona candidatos de lugar, no dirección validada ni accesibilidad para moto. El usuario confirma el resultado y cálculo; Valhalla puede ajustar el punto a una carretera cercana. Búsqueda/ruta y guiado aún no se han probado en teléfono/TFT ni en conducción. Consulta [GEOCODING.md](GEOCODING.md) y la [política oficial Nominatim](https://operations.osmfoundation.org/policies/nominatim/).
Search starts only after **Search**; typing issues no requests at this stage. Enter a name/address with city, check the HTTPS endpoint, and press Search. Use only nonsensitive queries on the public service: the provider receives text and source IP. The UI explains GPS is not sent; avoid personal/confidential data. No autocomplete or result fetching occurs while typing. Settings can change the Nominatim-compatible endpoint without updating the app.
### Fase 8: paquete vectorial offline de Asturias
1. Start with a synthetic nonprivate query, such as a known public site, and confirm full name and OSM/license attribution. No results is not an error. Changing text/endpoint while searching must cancel the previous request and remove its buttons; a late response must not replace the new query.
2. Press **Cancel search** during a query; the connection must close with no selectable result remaining. Repeat an identical query to check memory caching, including empty responses; change endpoint/language/parameter to verify entries do not mix. Cache and rate limiter exist only in process memory (100 entries/24 hours); no history is persisted.
3. Selecting a result fills the destination and starts preview calculation without guidance: no active maneuvers appear before **Start**. Editing the query clears the old destination; Calculate without a current selection must not reuse earlier coordinates. With guidance active, choosing/calculating another result preserves existing guidance while waiting or after failure. A new plan does not replace guidance until **Start**. **Stop route** explicitly removes the active route. The first result is not selected automatically.
4. Do not stress-test the public service. OSMF limits all installations of this app together to an absolute maximum of one request per second. The adapter serializes requests, caches queries, identifies the app with User-Agent, and honors Retry-After on 429; a 429 blocks new searches until the period expires and requires manual action without a retry loop. Controlled-server adapter tests cover cancellation, query encoding, caching, and 429; do not generate automatic test traffic to public Nominatim.
La versión `0.7.0` incorpora en el APK un archivo PMTiles generado a partir de un extracto de OpenStreetMap de Geofabrik. **Instalar Asturias incluido** copia el recurso empaquetado al almacenamiento privado de la app; no descarga cartografía de Internet. También se puede importar un PMTiles NavFrame compatible desde el selector de archivos. La copia/importación presenta bytes y puede cancelarse; al cancelar se elimina el staging parcial. El paquete persiste entre reinicios de la app. El límite actual es 3 paquetes, 500 MiB por archivo, 1 GiB en total, hasta 5° de latitud/10° de longitud; la app solo acepta el esquema y estilo NavFrame Offline 1.0.0.
Search provides place candidates, not validated addresses or motorcycle access. The user confirms the result/calculation; Valhalla may snap it to a nearby road. At this phase search/routes and guidance had not been tested on phone/TFT or while riding. See [GEOCODING.md](GEOCODING.md) and the [official Nominatim policy](https://operations.osmfoundation.org/policies/nominatim/).
1. En **Ajustes → Mapas offline**, pulsa **Instalar Asturias incluido**. Confirma que aparece progreso de copia y, al completarse, el paquete queda en estado listo con su tamaño. Pulsa **Usar Asturias · OSM 2026-09-28** (o el nombre equivalente mostrado) para activar la fuente. La misma fuente se usa en el mapa del teléfono y en el renderer 480×240 de la TFT; el crédito OSM debe seguir visible. La fuente actual puede conservar el guiado; borrar el paquete activo cambia primero a la fuente online y libera las vistas/lectores.
2. Cancela una instalación en curso y abre de nuevo el gestor: no debe aparecer ningún paquete incompleto seleccionable ni quedar archivos parciales. Repite la instalación completa, cierra/abre la app y confirma que el paquete listo persiste. Comprueba **Borrar** y vuelve a instalar si quieres seguir probando.
3. Para comprobar uso sin red, activa el paquete antes de desconectar datos y comienza **Mapa DEMO sin ruta** desde **Opciones avanzadas**; Oviedo queda dentro del área almacenada. Desactiva Wi‑Fi/datos (Bluetooth/GPS pueden permanecer activos) y verifica el mapa del teléfono; si tienes la TFT conectada, verifica por separado el frame enviado. El archivo contiene cartografía hasta zoom 14; a mayor zoom se amplía la tesela z14. La cobertura real sigue los datos del extracto y no se extiende automáticamente a las zonas vecinas.
4. Busca/calcula una ruta en otra prueba con red y selecciónala. Una vez calculada, GPS puede seguir su geometría almacenada sin volver a consultar Valhalla, pero búsqueda y cálculo/recálculo de ruta siguen dependiendo de Internet. El paquete **no** incluye un grafo de routing. Confirma que modo demo y datos simulados permanecen identificados como DEMO y que seleccionar o instalar un paquete no empieza una ruta por sí solo.
5. Usa **Importar PMTiles NavFrame** con un archivo del formato documentado en [OFFLINE.md](OFFLINE.md); un archivo genérico PMTiles/Protomaps/OpenMapTiles puede tener un esquema incompatible y debe rechazarse sin cambiar la fuente activa. Cancela una importación desde SAF y comprueba que la copia parcial desaparece. No se requiere permiso general de almacenamiento.
### Phase 8: Asturias offline vector package
El APK contiene el mapa de Asturias (34.617.483 bytes sin comprimir; hash y procedencia en [OFFLINE.md](OFFLINE.md)); el proceso puede aumentar de forma visible el tamaño instalado. El paquete se guarda en `filesDir`, fuera de la caché de teselas ambient de MapLibre. Las pruebas JVM/Robolectric pueden verificar cabecera, persistencia, límites, cancelación y selección de fuente, pero **no** ejecutan JNI/OpenGL.
Version `0.7.0` embeds a PMTiles file generated from a Geofabrik OpenStreetMap extract in the APK. **Install bundled Asturias** copies the bundled resource to app-private storage without downloading maps. A compatible NavFrame PMTiles file can also be imported through the file picker. Copy/import displays bytes and supports cancellation; cancellation removes partial staging. Packages persist across app restarts. Current limits: three packages, 500 MiB per file, 1 GiB total, up to 5° latitude/10° longitude; only the NavFrame Offline 1.0.0 schema/style is accepted.
**Resultado físico reportado por el usuario en la versión 0.7.0 (29 de septiembre de 2026):** en Xiaomi 11 Lite 5G NE / Android 14, el MapView del teléfono muestra correctamente el mapa online de OpenFreeMap. La conexión con la TFT de la Yamaha MT-07 2026 también funciona, pero al enviar el mapa el frame muestra `MAPA NO DISPONIBLE`. No hay diagnóstico del motivo en esa prueba: el mensaje genérico no permite concluir que sea red, estilo, GPU o GPS. **Después, el usuario confirmó que el mapa Asturias funciona offline en el teléfono**; esa confirmación no incluye el catálogo de POI nuevo ni demuestra el render 480×240 en la TFT. La versión 0.7.1 añade categorías/etapa diagnósticas sin coordenadas ni URLs; deben recogerse en una nueva prueba, y no equivalen a una causa confirmada. Para recopilar un primer informe sin moto ni GPS, reproducir en casa: **Ajustes → Opciones avanzadas → Mapa DEMO sin ruta**, esperar 30–40 segundos y abrir **Información → Diagnóstico del mapa TFT → Compartir**. Ese informe de teléfono ayuda a distinguir el fallo del snapshot; no valida que el frame llegue a la Yamaha. El test de pantalla apagada continúa pendiente. El estado M1 confirmado no demuestra estas funciones.
1. In **Settings → Offline maps**, press **Install bundled Asturias**. Check copy progress, then ready state/size. Press **Use Asturias · OSM 2026-09-28** or the equivalent displayed name. Phone map and 480×240 TFT renderer use the same source; OSM credit must remain visible. Changing the current source can preserve guidance; deleting an active package switches to online first and releases views/readers.
2. Cancel an installation and reopen the manager: no incomplete selectable package or partial files may remain. Complete installation, close/reopen the app, and verify the ready package persists. Check **Delete**, then reinstall for further testing.
3. Activate the package before disabling data and start **DEMO map without route** from **Advanced options**; Oviedo is inside the stored area. Disable Wi-Fi/data (Bluetooth/GPS may remain enabled) and check the phone map; with TFT connected, independently check the transmitted frame. Cartography extends to zoom 14; higher zoom enlarges the z14 tile. Actual coverage follows extract data and does not automatically extend into neighboring regions.
4. Search/calculate a route in a separate online test and select it. Once calculated, GPS can follow stored geometry without contacting Valhalla again, but search and route calculation/recalculation still require Internet. The package contains **no** routing graph. DEMO/simulated data must remain identified, and selecting/installing a package must not start a route.
5. Use **Import NavFrame PMTiles** with the format documented in [OFFLINE.md](OFFLINE.md); generic PMTiles/Protomaps/OpenMapTiles may have incompatible schemas and must be rejected without changing the active source. Cancel a SAF import and check partial-copy removal. No broad storage permission is required.
### Fase 9: flujo de navegación en moto y preferencias Yamaha
The APK includes Asturias cartography (34,617,483 uncompressed bytes; hash/provenance in [OFFLINE.md](OFFLINE.md)); installation can noticeably increase storage use. The package lives in `filesDir`, outside MapLibre's ambient tile cache. JVM/Robolectric tests verify headers, persistence, limits, cancellation, and source selection, but **do not** run JNI/OpenGL.
1. En la pantalla principal, confirma que el mapa ocupa el fondo y que la barra superior muestra el estado/conexión Yamaha y el menú. Toca **◎** para centrar y seguir tu ubicación después de desplazar el mapa; el lector de pantalla debe anunciar la acción. Sin permiso GPS, el mapa y la búsqueda deben seguir disponibles. Al dejar NavFrame, la escucha visible se cierra; solo el guiado GPS usa el servicio de ubicación en primer plano y su notificación.
2. Escribe un término no sensible en **Buscar calles y lugares**. Las sugerencias inmediatas deben venir solo de los catálogos POI locales instalados; no se debe enviar HTTP durante escritura, movimiento de mapa ni carga de marcadores. Pulsa el icono de búsqueda o la acción IME para consultar Nominatim explícitamente: los resultados online y offline se etiquetan por origen y se combinan sin duplicados. Comprueba una búsqueda local en modo avión y una búsqueda online con red. No generes solicitudes de carga contra Nominatim público; sus límites aplican al uso agregado de todas las instalaciones. Al escribir otra consulta o cerrar la lista, una respuesta antigua no debe reponer resultados obsoletos.
3. Desplaza el mapa a otra zona con cobertura instalada. Tras asentarse el movimiento, los marcadores locales deben actualizarse desde SQLite y el catálogo regional; no deben contactar a Nominatim, Overpass ni otro servicio. Haz desplazamientos rápidos consecutivos para comprobar que una consulta local cancelada no coloca marcadores de la vista previa anterior. Las etiquetas del mapa muestran clústeres al alejarse y lugares individuales al acercarse; el detalle conserva nombre/categoría y la distancia se identifica como línea recta.
4. Selecciona una sugerencia o resultado. Debe abrir la ficha inferior de ruta con destino, perfil, origen, resumen y **Iniciar**; calcular/preparar una ruta no empieza guiado. Cambia el perfil de moto y confirma que el resumen corresponde a la ruta preparada; son preferencias del backend, no garantías de evitar autopistas o caminos de tierra. Con otra ruta ya guiada, seleccionar un destino alternativo debe dejar accesible la ficha mientras el guiado existente continúa; solo **Iniciar** cambia al nuevo guiado. Ningún error o texto editado debe restaurar una selección anterior.
5. Empareja una moto desde los ajustes Bluetooth del teléfono. El indicador Yamaha superior debe anunciar el estado y permitir conectar/cambiar. Al volver a abrir NavFrame con reconexión automática activada, debe intentar la conexión en primer plano; el servicio reintenta una sesión interrumpida mientras continúe activa. **STOP · Detener ruta** aparece como única acción inferior durante guiado: debe borrar la ruta y parar el guiado, conservando mapa/GPS visible y la sesión Yamaha. **Desconectar Yamaha** pausa la reconexión automática; solo una conexión manual, reactivar la preferencia o elegir otra moto quita esa pausa. **Olvidar Yamaha** elimina la selección guardada sin cambiar ruta/destino.
6. El crédito compacto `© OpenStreetMap` permanece visible sobre el mapa; tocarlo lleva a Información y licencias. Confirma que se puede abrir el texto completo ODbL y el crédito/enlace de copyright OSM. El render TFT incorpora atribución de sus fuentes sobre el frame; la salida de diagnósticos del mapa TFT anterior sigue sin demostrar que el mapa llegue a la Yamaha. Con estilo HTTPS personalizado sin attribution metadata, NavFrame debe comunicar que no hay crédito declarado, sin inventar OpenFreeMap u OSM.
**Physical result reported for 0.7.0 on 2026-09-29:** the Xiaomi 11 Lite 5G NE / Android 14 phone MapView displayed OpenFreeMap online cartography correctly. Yamaha MT-07 2026 TFT connection worked, but its map frame displayed `MAPA NO DISPONIBLE`. No diagnostic cause was recorded; the generic message cannot establish network, style, GPU, or GPS failure. **The user subsequently confirmed Asturias offline maps on the phone**; that did not cover the new POI catalog or establish 480×240 TFT rendering. Version 0.7.1 added sanitized diagnostic categories/stages without coordinates or URLs, requiring a new report rather than representing a confirmed cause. For an initial report without motorcycle/GPS, reproduce at home: **Settings → Advanced options → DEMO map without route**, wait 30–40 seconds, then **Info → TFT map diagnostics → Share**. A phone report distinguishes snapshot failure but does not prove frame delivery to Yamaha. Screen-off testing remained pending; M1 did not establish these functions. Later physical evidence is recorded at the top of this document.
La previsualización de layout generada para `0.11.0` usa un mapa de marcador de posición y permite revisar controles en 360×720; no ejecuta MapLibre Android ni prueba una pantalla física. Repite esta fase en el Xiaomi 11 Lite 5G NE y en una moto detenida antes de considerar validada la navegación real.
### Phase 9: motorcycle navigation workflow and Yamaha preferences
La experiencia usa conceptos generales de navegación en moto como referencia funcional; no se integra ni copia UI, iconos o código de OsmAnd. Consulta [OSMAND_RESEARCH.md](OSMAND_RESEARCH.md). Ninguno de estos pasos sustituye la prueba física de mapa TFT que falló en 0.7.0, ni valida guiado sobre carretera. La estabilidad con pantalla apagada continúa pendiente.
1. On the main screen, confirm a background map and top Yamaha connection/status bar/menu. Tap **◎** to recenter/follow after panning; screen readers must announce the action. Map/search remain available without GPS permission. Leaving NavFrame stops visible-screen location listening; only GPS guidance uses a foreground location service and notification.
2. Type a nonsensitive term in **Search streets and places**. Immediate suggestions must use installed local POI catalogs only; typing, panning, and marker loading must send no HTTP. Press search/IME to explicitly query Nominatim: online/offline results are labeled by source and merged without duplicates. Check local search in airplane mode and online search with networking. Do not load-test public Nominatim; limits aggregate all installations. New queries/list closure must prevent old responses restoring outdated results.
3. Pan to another installed coverage area. After motion settles, markers update from SQLite/regional catalogs without contacting Nominatim, Overpass, or other services. Pan rapidly several times to check cancelled local queries cannot place previous-view markers. Labels show clusters when zoomed out and individual places when zoomed in; details retain name/category, and distance is labeled straight-line.
4. Select a suggestion/result. The route bottom sheet must show destination, profile, origin, summary, and **Start**; preparation/calculation does not start guidance. Change motorcycle profile and verify the prepared-route summary; backend preferences do not guarantee motorway/unpaved avoidance. With another route already guiding, an alternative destination leaves the sheet accessible while existing guidance continues; only **Start** switches guidance. Errors/edited text must not restore an earlier selection.
5. Pair the motorcycle in phone Bluetooth settings. The top Yamaha indicator announces state and allows connection/change. Reopening NavFrame with automatic reconnection enabled attempts foreground connection; the service retries an interrupted session while active. **STOP · Stop route** is the only bottom action during guidance: clear the route/stop guidance while keeping the visible GPS/map and Yamaha session. **Disconnect Yamaha** pauses automatic reconnection; manual connection, re-enabling the preference, or selecting another motorcycle lifts that pause. **Forget Yamaha** clears the saved selection without changing route/destination.
6. Compact `© OpenStreetMap` credit remains visible on the map; tapping opens Info/licenses. Verify full ODbL text and OSM copyright credit/link. TFT frames include source attribution; previous diagnostic output alone does not prove Yamaha map delivery. Custom HTTPS styles without attribution metadata must report undeclared credits rather than inventing OpenFreeMap/OSM attribution.
### Fase 10: catálogo local de lugares de Asturias (0.9)
The `0.11.0` layout preview uses placeholder cartography for 360×720 controls; it runs neither MapLibre Android nor a physical screen. Repeat this phase on the Xiaomi 11 Lite 5G NE and stationary motorcycle before treating real navigation as validated.
El APK incorpora el catálogo SQLite derivado del mismo extracto OSM que el PMTiles. La base se instala automáticamente, en almacenamiento privado e independiente del gestor PMTiles; no hace consultas Nominatim/Overpass para buscar estos lugares. Contiene 11.457 registros (gasolina 259, talleres 196, comida 4.393, alojamiento 1.383, compras 5.226), limitados por el extracto y no necesariamente completos o vigentes. La búsqueda es substring local con normalización de tildes; el marcador del mapa del teléfono se agrupa cuando hay muchos puntos. La distancia es en línea recta desde el centro de mapa usado al abrir **Lugares**, no distancia de carretera. El uso de resultados remotos de direcciones/Nominatim sigue siendo un flujo distinto.
The experience uses general motorcycle-navigation concepts as functional reference; it integrates/copies no OsmAnd UI, icons, or code. See [OSMAND_RESEARCH.md](OSMAND_RESEARCH.md). These steps did not replace the physical TFT test that failed in 0.7.0 or validate road guidance; screen-off stability remained pending at the time.
1. Con cartografía online y también en modo avión con Asturias offline ya activo, pulsa **Lugares**. Comprueba que abre el catálogo sin pedir permiso GPS, almacenamiento ni red. Busca «Oviedo», «Gijón» y una cadena con tildes (por ejemplo «Peñaflor» / «Penaflor»); selecciona categorías y confirma que una consulta nueva reemplaza los marcadores/resultados anteriores. Las categorías vacías o un centro fuera de Asturias deben mostrar un estado sin resultados claro, no coordenadas inventadas. Repite desde varios centros de mapa dentro de Asturias: la navegación de lista y el radio de exploración cambian según categoría/texto. Los clústeres deben separarse al acercar y los marcadores individuales deben distinguir las cinco categorías por color; la ficha/lista conserva siempre el nombre textual de categoría.
2. Selecciona un marcador o resultado y comprueba la ficha: nombre y categoría proceden de tags OSM, «sin nombre» es una etiqueta de fallback, dirección/teléfono/web/horario pueden faltar. El horario se presenta en bruto; no debe afirmar «abierto ahora». Distancia recta no equivale a ruta. Un vendedor de motos sin etiqueta de reparación explícita aparece en Compras, no se promete que cualquier taller atienda motos.
3. Prueba el botón **Abrir web** y el de teléfono solo desde una ficha, tras acción explícita del usuario. La web debe ser HTTP/HTTPS saneada; teléfono utiliza el marcador del sistema, no inicia una llamada. Si no hay aplicación externa disponible, NavFrame debe seguir operativa. No abras un marcador externo al tocar el mapa sin pasar por la ficha.
4. **Elegir destino** debe pedir cálculo de ruta online con ese punto. La consulta de POI continúa local; Valhalla recibe origen/destino al calcular. No se inicia guiado automáticamente: el guiado anterior, si lo había, debe seguir hasta que el usuario pulse **Iniciar**; cerrar o reemplazar una búsqueda y una respuesta local tardía no deben instalar marcadores de una consulta vieja. La ruta no pasa a ser offline: con red desconectada no se calcula ni recalcula.
5. Vuelve a abrir **Lugares** tras cerrar/reiniciar la app. La copia local debe quedar utilizable sin sustituir ni borrar el mapa PMTiles, importaciones o selección activa. Comprobar al menos gasolina, talleres y comercios por nombre en modo avión; buscar POI no debe producir solicitud de red ni añadir historial persistente propio. La atribución `© OpenStreetMap contributors` debe mantenerse visible en el mapa y accesible en la ficha. Prueba **Ocultar marcadores** con una consulta en vuelo: una respuesta vieja no debe volver a colocarlos.
### Phase 10: local Asturias place catalog (0.9)
El catálogo físico 0.9 aún no se ha validado con el usuario; la confirmación de mapa offline Asturias es evidencia de una versión anterior y función distinta. La base puede contener negocios desactualizados, duplicados o con acceso vial incorrecto. Consulta [POIS.md](POIS.md) para esquema, selección de tags, cobertura y hash. Las pruebas de parser/generador/SQLite no prueban el catálogo en una TFT ni aseguran disponibilidad comercial.
The APK embeds a SQLite catalog derived from the same OSM extract as PMTiles. It installs automatically into private storage independently of the PMTiles manager, without Nominatim/Overpass queries for these places. It contains 11,457 records (fuel 259, workshops 196, food 4,393, lodging 1,383, shopping 5,226), limited by the extract and not necessarily complete/current. Search is local substring matching with accent normalization; phone markers cluster when numerous. Distance is straight-line from the map center used when opening **Places**, not road distance. Remote address/Nominatim results remain a separate workflow.
### Permisos y recuperación
1. With online cartography and in airplane mode with Asturias offline active, press **Places**. Catalog opening requires no GPS, storage, or network permission. Search “Oviedo,” “Gijón,” and an accented string such as “Peñaflor” / “Penaflor”; select categories and verify new queries replace previous markers/results. Empty categories or a center outside Asturias show a clear no-results state, not invented coordinates. Repeat from multiple Asturias map centers: list navigation/exploration radius vary with category/text. Clusters separate when zooming in; five categories use distinct marker colors while cards/lists always retain category text.
2. Select a marker/result and inspect its card: name/category come from OSM tags, “unnamed” is a fallback, and address/phone/web/hours may be absent. Hours are raw text and must not claim “open now.” Straight-line distance is not a route. Motorcycle sellers without explicit repair tags appear in Shopping; no promise is made that all workshops service motorcycles.
3. Test **Open website**/phone only from a card after explicit action. Websites must be sanitized HTTP/HTTPS; phone opens the system dialer without starting a call. Missing external apps must not break NavFrame. A map tap must not launch an external dialer without the card step.
4. **Choose destination** requests online route calculation for that point. POI queries remain local; calculation sends origin/destination to Valhalla. Guidance does not start automatically: existing guidance continues until **Start**. Closing/replacing searches and late local responses must not install obsolete markers. Routes do not become offline: without networking they cannot calculate/recalculate.
5. Reopen **Places** after closing/restarting the app. The local copy must remain usable without replacing/deleting PMTiles, imports, or active selection. Check at least fuel, workshops, and shops by name in airplane mode; POI search sends no network request or persistent local history. `© OpenStreetMap contributors` remains visible on the map and accessible in cards. Test **Hide markers** with a query in flight: old responses must not restore them.
La pantalla principal funciona sin GPS ni Bluetooth: mapa online, búsqueda, opciones DEMO y ajustes no solicitan permisos de ubicación ni dispositivos cercanos. Conceder ubicación precisa habilita fixes mientras NavFrame está visible; salir de la app los detiene. Pulsa el botón **◎** o inicia una ruta GPS para centrar/obtener fixes; la sesión de guiado usa FGS de ubicación y notificación. **Yamaha** pide solo Bluetooth y notificaciones que requiera el sistema para el servicio conectado. Una denegación no debe volver a lanzar el diálogo en bucle; el aviso táctil abre los ajustes de NavFrame. Revocar ubicación durante guiado debe detener el seguimiento FGS; volver desde Ajustes no reanuda guiado por sí solo. No se solicita acceso permanente a la ubicación.
The physical 0.9 catalog was not yet user-validated; earlier Asturias offline-map confirmation covered a different version/function. The database may contain stale businesses, duplicates, or incorrect road access. See [POIS.md](POIS.md) for schema, tag selection, coverage, and hash. Parser/generator/SQLite tests do not validate a TFT catalog or business availability.
## Entorno de desarrollo observado
### Permissions and recovery
El shell inicial tenía OpenJDK 25 y `adb` 35.0.2; no definía `ANDROID_HOME`/`ANDROID_SDK_ROOT` ni encontraba `gradle` en PATH. Se encontró un SDK Android bajo `/home/dasemu/.bubblewrap/android_sdk` y JDK 17 bajo `/home/dasemu/.bubblewrap/jdk/jdk-17.0.11+9`; la ejecución de Gradle se realizó con este JDK y `local.properties` apuntando al SDK. No hay un teléfono conectado validado por ADB.
The main screen works without GPS/Bluetooth: online maps, search, DEMO options, and settings request neither location nor nearby-device permission. Precise location enables fixes while NavFrame is visible; leaving stops them. Press **◎** or start a GPS route to recenter/acquire fixes; guidance uses a location foreground service and notification. **Yamaha** requests only Bluetooth and notifications required by the system for the connected service. Denial must not cause repeated permission dialogs; the tappable notice opens NavFrame settings. Revoking location during guidance stops foreground tracking; returning from Settings does not resume guidance automatically. Permanent location access is not requested.
## Registro de verificación local
## Observed development environment
La versión `0.9.0` (versionCode 11) compiló con JDK 17: **120 pruebas aprobadas, 0 fallos** (42 app, 68 core y 10 NaviLite); lint terminó con **0 errores y 55 avisos**. APK `app/build/outputs/apk/debug/app-debug.apk`: 81.243.815 bytes; SHA-256 `37c0d2b573737449f6b4f910112dfa8c45a9f47d8e8b7f021012b3ad17cd0ab7`. Los 4 tests nuevos del repositorio usan la SQLite empaquetada real para integridad/hash/conteos y preservación del pack de mapa, normalización de tildes y escape de wildcards/SQL, categoría/radio/orden/límite y recuperación de copia privada corrupta; otro test de actividad comprueba que elegir un lugar desde su ficha pide cálculo/vista previa y no inicia guiado. Las pruebas automáticas no ejecutan JNI/OpenGL ni demuestran render de teselas/POI en TFT. El catálogo incluido mide 2.334.720 bytes (SHA-256 `153cbc6d71e5a51b16ddb125ee4e51e34982a34c6da5231b22c786764976fa3d`) y el PMTiles de Asturias 34.617.483 bytes (SHA-256 `f63f65f9c2bc7e169371d3da8c01125f15f3d6ae0caae0d7d7d47aad43f4df9e`). No se hicieron consultas de prueba contra Nominatim público. La consulta sintética de Valhalla documentada en [ROUTING.md](ROUTING.md) no valida cobertura o idoneidad vial.
### Ride feedback and regression checks (0.13.1)
Se intentó iniciar dos veces el AVD existente `sports_test` (Android 14 / API 34), pero el emulador terminó con salida 139 antes de completar el arranque; ADB nunca lo mostró como dispositivo disponible. No se instaló ni abrió el APK en un emulador. El usuario confirma M1 físico para las dos imágenes de prueba en Xiaomi 11 Lite 5G NE / Android 14 y MT-07 2026, y confirma cartografía Asturias offline en el teléfono. La versión 0.7.0 falló al mostrar el mapa en la TFT; no hay prueba física posterior que confirme render del mapa/POI en TFT. La búsqueda POI, GPS, rutas, guiado y perfiles en moto todavía requieren validación física. También sigue pendiente la prueba de 30 minutos en segundo plano, recuperación Bluetooth y liberación del wake lock tras STOP.
Previously recorded feedback for 0.13.1: the rider confirmed downloaded regional maps on the phone and Yamaha TFT and working voice instructions during a ride. Online maps worked on the phone but failed on the TFT. Deviating from the route could incorrectly report GPS loss while the map still followed the rider, with instructions resuming only after returning to the previous route progress. This feedback was already recorded before the 12 October incident; it does not identify the cause of the new failure.
### Fase 11: paquete regional local de Cantabria (0.10)
Route regressions now distinguish a reliable position outside the reachable route section from an unusable GPS fix. Validate automatic recalculation from the current position after a sustained deviation, including a reversal on the same road. The destination and selected routing profile must remain unchanged, and a successful replacement route must resume instructions.
El archivo `dist/es-cantabria-20260928.1.navframe` se entrega fuera del APK para importarlo con SAF. Copia el archivo al teléfono y abre **Ajustes → Mapas offline → Importar/actualizar región**. Comprueba progreso, nombre/versión y la acción **Usar**. Reinicia la app y confirma que el paquete persiste. Asturias incluido y su catálogo deben seguir disponibles. En Cantabria, centra el mapa en Santander y abre **Lugares**; comprueba resultados locales (por ejemplo gasolina) y repite en modo avión. Centra fuera del polígono Cantabria y Asturias: la app no debe atribuir el área a una región instalada. Importa un ZIP corrupto o con entrada adicional y confirma que se rechaza sin cambiar la fuente activa. Al borrar la región activa, el renderer TFT y el MapView deben soltar sus lectores antes de eliminarla.
The TFT snapshot renderer now owns its connectivity lifecycle independently of the phone map. The effect of that change on online TFT rendering still needs device validation. Test the default online map with no offline source selected, then background the phone, lock the screen, and change between Wi-Fi and mobile data. If rendering fails, use **Info → TFT map diagnostics** to collect the sanitized failure stage and reason.
Una prueba Robolectric importa el `.navframe` real desde `dist/`, comprueba cobertura POI en Santander y preservación de Asturias; otra comprueba hash incorrecto y entrada ZIP adicional con rollback. Las pruebas automatizadas no ejecutan MapLibre JNI/OpenGL ni validan el frame TFT. La prueba física nueva de Cantabria/POI y el mapa en TFT quedan pendientes.
Horizontal GPS uncertainty remains visible as small marker movement. Guidance still rejects fixes older than 15 seconds or with accuracy worse than 25 metres; deviation handling must not hide genuine loss of usable positioning.
La build final `0.10.0` (versionCode 12) pasó **129 pruebas, 0 fallos y 0 omitidas**: 45 app/Robolectric, 74 core y 10 NaviLite. `assembleDebug` y `lintDebug` pasaron; lint registró **0 errores y 62 avisos**. APK `app/build/outputs/apk/debug/app-debug.apk`: **81.324.605 bytes**, SHA-256 `0b1b4ff07153e9d794b1a26d621d8ad857e635d8b7e21d98b035139d2ed1c4df`.
Cloud verification on 2026-10-12 for 0.13.1 passed 159 unit tests (60 app, 89 core, 10 NaviLite), 17 Python offline-builder tests, Android APK assembly, and lint with zero errors and 76 warnings. The online TFT lifecycle tests do not exercise the native GPU renderer or prove online rendering on the motorcycle.
### Fase 12: pantalla principal de mapa y búsqueda unificada (0.11)
The original shell had OpenJDK 25 and `adb` 35.0.2, no `ANDROID_HOME`/`ANDROID_SDK_ROOT`, and no `gradle` in PATH. An Android SDK was found at `/home/dasemu/.bubblewrap/android_sdk` and JDK 17 at `/home/dasemu/.bubblewrap/jdk/jdk-17.0.11+9`; Gradle ran with that JDK and SDK configured in `local.properties`. No ADB-connected phone was validated. These are historical machine-specific paths, not required cloud paths.
En `0.11.0`, la pantalla de mapa coloca estado Yamaha y menú arriba, búsqueda de calles/lugares en una sola barra, atribución compacta sobre el mapa y botón de recentrado. La búsqueda en escritura solo consulta el catálogo instalado; las peticiones remotas requieren Buscar/IME. Mover el mapa actualiza POI mediante el catálogo local con debounce/cancelación. Seleccionar destino presenta perfil y preparación de ruta; **Iniciar** es una acción separada. Durante guiado, **STOP · Detener ruta** es el único control de acción inferior y conserva la conexión TFT/Yamaha.
## Historical local verification records
Revisa las previsualizaciones en `app/build/outputs/preview/phone-layout-placeholder.png` y `phone-route-sheet-placeholder.png`. Son composición de layout con mapa de muestra; no ejercitan MapLibre, GPU, IME del sistema ni el dispositivo físico. En las imágenes de 360×720, el indicador Yamaha/search quedan bajo las barras del sistema; el FAB de centrar queda arriba del crédito OSM y la tarjeta inferior ofrece origen/perfil/resumen/Iniciar. El crédito OSM y STOP ocupan bandas separadas.
Version `0.9.0` (versionCode 11) built with JDK 17: **120 tests passed, zero failures** (42 app, 68 core, 10 NaviLite); lint reported **zero errors and 55 warnings**. APK `app/build/outputs/apk/debug/app-debug.apk`: 81,243,815 bytes; SHA-256 `37c0d2b573737449f6b4f910112dfa8c45a9f47d8e8b7f021012b3ad17cd0ab7`. Four new repository tests use the actual packaged SQLite for integrity/hash/counts and map-pack preservation, accent normalization and wildcard/SQL escaping, category/radius/order/limit, and corrupt private-copy recovery; another activity test checks that choosing a place from its card requests calculation/preview without starting guidance. Automated tests run no JNI/OpenGL and do not establish TFT tile/POI rendering. Included catalog: 2,334,720 bytes (SHA-256 `153cbc6d71e5a51b16ddb125ee4e51e34982a34c6da5231b22c786764976fa3d`); Asturias PMTiles: 34,617,483 bytes (SHA-256 `f63f65f9c2bc7e169371d3da8c01125f15f3d6ae0caae0d7d7d47aad43f4df9e`). No public Nominatim test queries were made. The synthetic Valhalla query documented in [ROUTING.md](ROUTING.md) does not validate coverage or road suitability.
La validación final de `0.11.0` (versionCode 13) pasó **133 pruebas, 0 fallos y 0 omitidas**: 49 app/Robolectric, 74 core y 10 NaviLite. `assembleDebug`, `lintDebug`, `:navilite:testDebugUnitTest` y `:core:test` pasaron; lint registró **0 errores y 62 avisos**. El APK `app/build/outputs/apk/debug/app-debug.apk` mide **81.357.540 bytes**, SHA-256 `1f6850be7077b4a53e1d30a2095bf5458269b734b4d2c33beeeedfa4d90fe516`. Pruebas y preview no ejecutan MapLibre JNI/OpenGL en teléfono. No se realizó una nueva prueba física de mapa TFT, búsqueda/ruta/POI, guiado, compatibilidad de pantalla pequeña real ni pantalla apagada. El último resultado físico de mapa TFT sigue siendo `MAPA NO DISPONIBLE` de la versión 0.7.0; M1 solo confirma imagen fija/sintética y no demuestra el render actual.
The existing `sports_test` AVD (Android 14 / API 34) was started twice but exited with code 139 before boot completed; ADB never listed it as available. The APK was not installed/opened in an emulator. At this stage, the user had confirmed physical M1 for two test images on Xiaomi 11 Lite 5G NE / Android 14 and MT-07 2026, and Asturias offline cartography on the phone. Version 0.7.0 had failed to display the TFT map, with no later physical TFT map/POI success yet recorded. Physical POI search, GPS, routes, guidance, motorcycle profiles, 30-minute background operation, Bluetooth recovery, and wake-lock release after STOP remained pending. See the latest reports at the top for subsequent evidence.
### Aviso de GPS al centrar (0.11.1)
### Phase 11: local Cantabria regional package (0.10)
Con el mapa visible, pulsa centrar sin señal GPS reciente o con precisión insuficiente: aparece un aviso discreto en la parte inferior y la cámara no se mueve. Púlsalo varias veces: debe renovarse un solo aviso. Con un fix reciente y preciso, el botón vuelve a centrar. La prueba Robolectric comprueba ambos caminos; la calibración y el comportamiento físico en el Xiaomi siguen pendientes. `0.11.1` (code 14) compila con 50 pruebas Android aprobadas y lint sin errores (63 avisos). APK: 81.130.894 bytes, SHA-256 `d0c428e4ca67389484c45f65dbafd51cbc8101ae1c4d16ef80b8068a83b8f3e9`. Core/NaviLite permanecen sin cambios respecto a sus 74/10 pruebas previas.
`dist/es-cantabria-20260928.1.navframe` is delivered outside the APK for SAF import. Copy it to the phone and open **Settings → Offline maps → Import/update region**. Check progress, name/version, and **Use**. Restart and verify persistence; bundled Asturias and its catalog remain available. Center on Santander in Cantabria and open **Places**; check local results such as fuel, then repeat in airplane mode. Center outside Cantabria/Asturias polygons: the app must not claim installed-region coverage. Import a corrupt ZIP or one with an additional entry and verify rejection without active-source changes. Deleting an active region must release TFT/MapView readers first.
### Voz y radares fijos opcionales (0.12.0)
A Robolectric test imports the real `.navframe` from `dist/`, checks Santander POI coverage and Asturias preservation; another checks incorrect hashes/additional ZIP entries with rollback. Automated tests run no MapLibre JNI/OpenGL and do not validate TFT frames. New physical Cantabria/POI and TFT-map testing remained pending.
En Ajustes, deja activa la voz en español y comprueba que Android informa una voz instalada. Prepara e inicia una ruta GPS: escucha los anuncios antes de las maniobras; confirma que no se repiten en cada actualización de posición. Silencia la voz y vuelve a activarla. Prueba una ruta con el teléfono bloqueado y el intercomunicador enlazado; la reproducción y el comportamiento de audio son aún pendientes de validación física.
Final `0.10.0` build (versionCode 12): **129 tests passed, zero failed/skipped** (45 app/Robolectric, 74 core, 10 NaviLite). `assembleDebug` and `lintDebug` passed; lint: **zero errors, 62 warnings**. APK `app/build/outputs/apk/debug/app-debug.apk`: **81,324,605 bytes**, SHA-256 `0b1b4ff07153e9d794b1a26d621d8ad857e635d8b7e21d98b035139d2ed1c4df`.
Los avisos de posibles radares fijos empiezan desactivados. Tras activarlos en Ajustes, importa `dist/es-cantabria-20260928.2.navframe` si se va a probar Cantabria. Comprueba en una ruta real y legal que el aviso aparece brevemente en el teléfono y, con voz activa, se oye al aproximarse. No hagas una prueba deliberada de exceso de velocidad. Los 83 puntos de Asturias y 22 de Cantabria proceden de OSM, pueden estar incompletos o desactualizados y no certifican carril o sentido; véase [Radares](RADARS.md). Antes de circular, verifica si los avisos están permitidos en el lugar.
### Phase 12: map main screen and unified search (0.11)
La build final `0.12.0` (code 15) pasó **140 pruebas, 0 fallos**: 50 app/Robolectric, 80 core y 10 NaviLite. `assembleDebug` y `lintDebug` pasaron con **0 errores y 66 avisos**. APK: **81.150.850 bytes**, SHA-256 `26a03dc6f620e8fcdb55e261530f73e1835f499ef1c87b92e06496189f973a0b`. Las pruebas automatizadas no reproducen audio físico, Bluetooth/intercom ni MapLibre GPU/TFT.
In `0.11.0`, the map screen places Yamaha status/menu at the top, street/place search in one bar, compact map attribution, and a recenter button. Typing searches only installed catalogs; remote requests require Search/IME. Moving the map updates local POI with debounce/cancellation. Selecting a destination presents profile/route preparation; **Start** is separate. During guidance, **STOP · Stop route** is the only bottom action and preserves TFT/Yamaha connection.
Review `app/build/outputs/preview/phone-layout-placeholder.png` and `phone-route-sheet-placeholder.png`. These compose layout with a sample map; they exercise neither MapLibre, GPU, system IME, nor physical hardware. In 360×720 images, Yamaha/search sit below system bars; the recenter FAB sits above OSM credit; the bottom card offers origin/profile/summary/Start. OSM credit and STOP occupy separate bands.
Final `0.11.0` validation (versionCode 13): **133 tests passed, zero failed/skipped** (49 app/Robolectric, 74 core, 10 NaviLite). `assembleDebug`, `lintDebug`, `:navilite:testDebugUnitTest`, and `:core:test` passed; lint: **zero errors, 62 warnings**. APK `app/build/outputs/apk/debug/app-debug.apk`: **81,357,540 bytes**, SHA-256 `1f6850be7077b4a53e1d30a2095bf5458269b734b4d2c33beeeedfa4d90fe516`. Tests/previews run no MapLibre JNI/OpenGL on a phone. No new physical TFT map, search/route/POI, guidance, actual small-screen compatibility, or screen-off test was performed. At that time, the latest physical TFT map result remained `MAPA NO DISPONIBLE` in 0.7.0; M1 confirmed only static/synthetic images. This historical status is superseded by later reports above.
### GPS recenter warning (0.11.1)
With the map visible, press recenter without a recent GPS fix or with insufficient accuracy: a subtle bottom notice appears and the camera does not move. Repeated presses refresh one notice. A recent accurate fix allows recentering again. Robolectric checks both paths; Xiaomi physical behavior/calibration remained pending. `0.11.1` (code 14) built with 50 passing Android tests and lint with zero errors (63 warnings). APK: 81,130,894 bytes, SHA-256 `d0c428e4ca67389484c45f65dbafd51cbc8101ae1c4d16ef80b8068a83b8f3e9`. Core/NaviLite remained unchanged from 74/10 earlier tests.
### Voice and optional fixed-camera alerts (0.12.0)
In Settings, leave Spanish voice enabled and check Android reports an installed voice. Prepare/start a GPS route: listen for announcements before maneuvers and verify no repetition on every position update. Mute/unmute voice. Test a route with phone locked and intercom paired; physical playback/audio behavior remained pending at this stage.
Possible fixed-camera alerts default off. Enable them in Settings; import `dist/es-cantabria-20260928.2.navframe` when testing Cantabria. On a real legal route, check the phone briefly displays the alert and enabled voice announces the approach. Do not deliberately speed for testing. The 83 Asturias points and 22 Cantabria points come from OSM, may be incomplete/stale, and certify neither lane nor direction; see [Camera alerts](RADARS.md). Before riding, check whether alerts are permitted locally.
Final `0.12.0` build (code 15): **140 tests passed, zero failures** (50 app/Robolectric, 80 core, 10 NaviLite). `assembleDebug`/`lintDebug` passed with **zero errors, 66 warnings**. APK: **81,150,850 bytes**, SHA-256 `26a03dc6f620e8fcdb55e261530f73e1835f499ef1c87b92e06496189f973a0b`. Automated tests reproduce neither physical audio, Bluetooth/intercom, nor MapLibre GPU/TFT.
+31
View File
@@ -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.
+49
View File
@@ -0,0 +1,49 @@
# TFT map incident: La Corredoria, 12 October 2026
## Report and conclusion
The owner reported that the TFT map stopped working in La Corredoria (Oviedo) after approximately 20 minutes of successful operation. It displayed `MAPA NO DISPONIBLE` and did not recover for the rest of the journey, while the phone map continued working. An offline map was installed. The owner reported using the latest version, but the installed APK and error diagnostics were not available to verify the build or failure category.
**The root cause remains unknown.** The symptom is consistent with a failure in the independent TFT snapshot workflow. There is no device log or physical reproduction establishing a GPU, resource, network, or lifecycle cause. No runtime change is proposed on that basis.
This investigation reviewed commit `6fec09f20fff50c3ed94782b10c67998adce986f`, which declares version 0.13.1. Repository inspection does not establish which exact APK was installed.
## What the implementation establishes
- The phone uses `PhoneMapView`/MapLibre `MapView`; the service renders the TFT with a separate `MapSnapshotter` at 480×240. A working phone map does not establish that the snapshot renderer is healthy.
- `MapLibreTftRenderer.render` allows 30 seconds for the first snapshot and 10 seconds after its first success. Errors are classified as `TIMEOUT`, `NETWORK`, `STYLE`, `GPU`, `BITMAP`, or `SDK`. The display text alone does not identify the category or cause.
- `TftService.mapUnavailable` discards the failed renderer and schedules retries after 2, 4, 8, and at most 15 seconds. A replacement renderer receives the initial 30-second timeout again. Persistent failure can mean repeated errors; a retained error image can also remain visible if updates stop. An increasing attempt counter distinguishes active retries from a static last frame.
- The error image is composed by NavFrame. If it arrived as a new frame during the incident, at least that frame was transmitted. It does not by itself prove that Bluetooth later stayed connected.
- `OfflineMapStyle` uses local PMTiles and bundled font assets rather than network resource URLs. Loss of mobile coverage alone does not explain a failure when a valid offline source was actually selected and its resources remained usable.
- Installation and selection are separate actions. An installed package does not prove that the active source was offline: the user must select **Use** for that package. The diagnostic report distinguishes `LOCAL PMTiles` from `ONLINE`.
- The bundled Asturias archive has PMTiles v3 metadata, zoom levels 6–14, and bounds 42.9–43.75 N / −7.2–−4.45 E. La Corredoria lies inside these declared bounds. This rules out being outside that archive's declared coverage, but does not validate every tile or establish that this archive was selected.
- The TFT requests zoom 15–17.5 according to speed and maneuver proximity; the phone uses a zoom 0.8 levels lower. Overzoom beyond the stored maximum is not itself evidence of a defect, but the two views can request different resources.
- The real TFT session renews its 120-second partial wake lock every 30 seconds. No programmed 20-minute cutoff was found in this workflow. Device power management and native resource problems remain unverified.
- This commit already includes the 1 October TFT connectivity lifecycle correction: the snapshot renderer owns a connectivity receiver activation independently of the phone map. The older defect cannot be assumed to explain this incident if the installed build includes that correction.
## Open hypotheses
A snapshot timeout, graphics-context failure, or native resource problem can affect the TFT while its independent phone map keeps working. A local tile, style, or glyph resource failure is also possible. Alternatively, an online source may have remained selected despite an installed offline package. A static last error frame must be distinguished from repeated failing captures. None of these hypotheses is confirmed by the report.
## Capture evidence before restarting
While stationary, open **Menu → Information and licenses → TFT map diagnosis → Share** (Spanish UI: **☰ → Información y licencias → Diagnóstico del mapa TFT → Compartir**). Save the complete report before stopping the service or restarting the app. It includes the active source, failure code, stage, duration, attempts, and last failure without coordinates or URLs. The last failure is retained in service memory even after recovery, but is lost when that service instance is destroyed; it is not a persistent incident history.
For a stationary reproduction with an attached development device, collect logcat locally and inspect `MAP_UNAVAILABLE`, `TFT_MAP_NETWORK`, `GPS_FAILED`, and MapLibre/EGL output. A full logcat may include private information; review and redact it before sharing.
| Evidence | Next investigation |
| --- | --- |
| `TIMEOUT / STYLE_LOADING` | Determine which style/resource operation did not finish; do not infer an Internet outage solely from the timeout. |
| `TIMEOUT / STYLE_READY` | Inspect pending resources and native rendering after style loading completed. |
| `GPU`, `EGL`, or `CONTEXT_LOST` | Investigate OpenGL context and recovery on the actual device. |
| `NETWORK` with source `ONLINE` | Verify source selection and connectivity. |
| Increasing attempt counter | Retries are running and failing again. |
| Unchanging attempt counter and error frame | Investigate rendering/session progress and whether the TFT is showing a retained frame. |
After preserving evidence, restarting the map mode or app while stationary can test recovery. It is not a demonstrated fix for this incident.
## Automated validation and limits
The reviewed code built its debug APK and passed Android lint (zero errors, 76 warnings), 159 unit tests (60 app, 89 core, 10 NaviLite; zero failures or skips), and 17 offline Python tests. The cloud setup uses JDK 17 and Android SDK 36.
These checks do not execute physical MapLibre JNI/OpenGL rendering, Yamaha Bluetooth/TFT behavior, or device power management. They neither reproduce nor rule out this incident. Future fixes need evidence from the device and validation of the affected failure/recovery path.