Initial public NavFrame release with global regional package pipeline

This commit is contained in:
dasemu committed 2026-09-30 17:34:58 +02:00
commit d863f2b940
143 files changed
+17906

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
# Architecture
NavFrame separates navigation state, Android services, rendering, local map data, and the experimental Yamaha display protocol.
```mermaid
flowchart LR
UI[Android activity] --> S[Navigation service and state]
S --> GPS[Android location]
S --> R[Configured Valhalla HTTP routing]
UI --> G[Explicit Nominatim search]
UI --> M[Phone MapLibre renderer]
S --> T[TFT frame composer]
T --> B[NaviLite Bluetooth transport]
B --> Y[Yamaha TFT]
M --> O[Online style or local PMTiles]
T --> O
UI --> P[Regional package manager]
P --> D[HTTPS catalog and archive downloader]
P --> Q[SQLite POI and camera catalogs]
```
## Modules
- `app` contains the Android activity, foreground navigation service, location and voice controllers, phone/TFT renderers, online routing/geocoding adapters, offline map/package managers, and user interface.
- `core` contains platform-independent route, map-frame, guidance, camera-alert, and regional-package models and parsers.
- `navilite` contains the adapted Yamaha TFT protocol and transport support. It includes code adapted from Pillion and is subject to the noncommercial terms documented in [Licensing](LICENSING.md).
## Main flows
The activity owns map exploration and explicit search/route actions. GPS guidance moves into a foreground service so it can continue when the activity is not visible. The service combines location fixes with a previously calculated route, creates navigation state, and composes a 480×240 frame. The frame is rendered locally and, when connected, sent through NaviLite over Bluetooth. Demo mode uses synthetic data and must remain visibly identified as demo.
Routing sends an explicit origin/destination request to the configured HTTPS Valhalla-compatible endpoint. Address search sends text only after the user requests an online search. Neither public service is an availability commitment. Previously calculated route geometry may be followed without a fresh routing request, but offline route calculation and recalculation are not implemented.
Offline map packages contain `manifest.json`, `map.pmtiles`, and `pois.sqlite`. The manifest records schema, geographic bounds and polygon coverage, source provenance, attribution, and component checksums. On import or download, the package is staged, checked, and committed to private app storage only after validation. POI and optional camera records are queried from local SQLite databases. Regional maps are selectable individually; seamless rendering of multiple adjacent regional maps is not yet provided.
Worldwide region discovery/building is a separate publishing pipeline. Geofabrik extracts are transformed into NavFrame packages and distributed as GitHub Release assets; the Android app fetches a catalog and verifies the selected package before installing it. The workflow builds regions on demand, so discovery does not imply that every region is published or suitable for every device. See [GLOBAL_OFFLINE.md](GLOBAL_OFFLINE.md).
## Trust and limitations
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).
+41
View File
@@ -0,0 +1,41 @@
# Explicit destination search (English summary)
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.
# Detailed geocoding notes (Spanish)
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.
## Política del servidor público
**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.
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 y HTTP Android
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)` 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.
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.
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.
## Parser y selección
`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/).
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.
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.
## Privacidad, créditos y pruebas
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` 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.
+79
View File
@@ -0,0 +1,79 @@
# Worldwide offline package pipeline
The app installs individual `.navframe` packages containing a PMTiles map, a SQLite POI/camera database and a manifest with source timestamp, coverage, attribution and SHA-256 hashes. Worldwide means regions discoverable in the official Geofabrik index, with publication on demand. It does not mean every region has already been generated or that OSM has complete camera data.
## Generate and publish
In `Dasemu/NavFrame`, open **Actions → Build worldwide offline regions → Run workflow**. Enter Geofabrik IDs such as `andorra,act,cantabria,us/california`. First run with **publish = false** to inspect artifacts; run with **publish = true** to publish packages. Each run builds at most 32 independent regions, with two concurrent builders and a 330-minute timeout per builder. No planet download or full-world local build is performed.
One-time bootstrap with SSH push access (no local GitHub CLI/token required): after pushing the project to the default branch, create and push the exact tag below. Only this tag triggers an automatic **Andorra** build with publication enabled; other tag or branch pushes do not trigger the offline builder. The catalog becomes available after that workflow succeeds.
```sh
git tag offline-bootstrap-andorra
git push origin offline-bootstrap-andorra
```
Discover valid IDs without downloading extracts:
```sh
python3 tools/offline/global-regions.py discover --output build/offline/worldwide-sources.json
```
The discovery output describes source availability. The app catalog contains only successfully built packages. Standard hosted runners accept extracts up to 1 GiB and packages below 500 MiB, consistent with the app's archive budget. Choose smaller Geofabrik subregions when an extract exceeds the budget; a future dedicated larger runner can increase the input budget, but the package must remain within the Android installer limit. Input budgets do not guarantee that a runner has enough memory or disk for every extract.
Local build (Python dependencies and Java 21 required):
```sh
pip install -r tools/offline/poi-requirements.txt
curl --fail --location --output planetiler.jar https://github.com/onthegomap/planetiler/releases/download/v0.10.2/planetiler.jar
python3 tools/offline/global-regions.py build --region andorra --version 20260930.1 --planetiler-jar planetiler.jar --output build/offline/andorra
```
`build-region.py` also accepts existing PBF/.poly/PMTiles inputs for network-free builds. Planetiler and POI dependencies are pinned by version. Build provenance records the recipe, upstream PBF SHA-256, coverage SHA-256, Planetiler binary SHA-256 and PBF replication timestamp. Geofabrik's `latest` source URL rotates daily; the downloaded PBF is checked against its official MD5 sidecar, and its actual bytes are identified by SHA-256. A daily rotation during download fails rather than accepting a mismatch. OSM's replication timestamp identifies data freshness, while the package version identifies a publication.
## Catalog and publication contract
Every package publishes a release `offline-gf-REGION-RUNID.ATTEMPT` with the package and `regional-catalog.json`. The workflow creates a draft, uploads assets, then publishes it; it never replaces package assets. Published region releases should be treated as immutable. Package manifests retain schema version 1 and stable IDs `gf-REGION` (slashes in upstream IDs become hyphens, e.g. `us/california` → `gf-us-california`).
The serialized catalog job reads **all** published region releases, merges their fragments and selects the latest publication per region. The merged index uses compact JSON and is checked against a 32 MiB / 4,096-entry Android discovery budget before publication.
The mutable discovery index is:
`https://github.com/Dasemu/NavFrame/releases/download/offline-catalog/regional-catalog.json`
This index release must remain mutable so its asset can be updated; do not enable repository-wide release immutability without moving the index to another host. The individual package URLs remain versioned. Historical package releases remain available. Catalog rebuilding is safe across concurrent region batches because the index job is serialized. A failed region does not prevent catalog rebuilding for successful releases.
Catalog format:
```json
{
"schemaVersion": 1,
"regions": [{
"manifest": {"id": "gf-andorra", "name": "Andorra", "version": "12345.1"},
"archive": {
"path": "gf-andorra-12345.1.navframe",
"url": "https://github.com/Dasemu/NavFrame/releases/download/offline-gf-andorra-12345.1/gf-andorra-12345.1.navframe",
"bytes": 123456,
"sha256": "64 lowercase hexadecimal characters"
},
"countryCode": "AD",
"country": "Andorra",
"region": "andorra",
"cameraCount": 4
}]
}
```
The example abbreviates the manifest: real entries include the full map/POI hashes, geographic bounds and Polygon/MultiPolygon coverage. Metadata is optional; multi-country extracts may have no country code. Downloaders use `archive.url` when present and verify archive length/hash before installation. `path` remains a flat filename for older local catalogs. `global-regions.py merge` rejects conflicting entries for the same immutable ID/version.
## Coverage and cameras
Geofabrik `.poly` parsing preserves multiple islands and holes. Camera extraction accepts globally used `highway=speed_camera` nodes and explicitly speed-enforcing traffic-surveillance camera nodes. Generic CCTV, speed displays and abandoned objects are excluded. Raw direction evidence is retained without inventing enforcement direction. Average-speed relations, mobile enforcement and untagged cameras are not inferred. Missing camera entries cannot be interpreted as an absence of enforcement.
Maps use the existing NavFrame schema and bundled fonts. Worldwide coordinates and extraction support do not guarantee complete typography for every writing system; the existing limited offline glyph bundle remains a rendering limitation.
All package manifests retain **© OpenStreetMap contributors** and **ODbL-1.0**, with Geofabrik provenance. Keep attribution visible in the app and when redistributing packages. Generated large data assets belong in Releases/artifacts, not Git history.
## Verified upstream constraints
Geofabrik documents its [machine-readable worldwide index](https://download.geofabrik.de/technical.html). GitHub allows [up to 1,000 release assets, each under 2 GiB](https://docs.github.com/en/repositories/releasing-projects-on-github/about-releases). Actions has [matrix/runtime limits](https://docs.github.com/en/actions/reference/limits); this workflow deliberately uses smaller batches and packages. Artifact storage is temporary and may consume account quotas; only preview runs upload package artifacts, while publication runs distribute packages directly through Releases.
+33
View File
@@ -0,0 +1,33 @@
# Licenses, attribution, and service terms
This document summarizes the project's current third-party materials and service dependencies. It is not legal advice. Data licenses, software licenses, and public-service policies are separate obligations; review the full notices included with the relevant component before redistribution or commercial use.
## Project and third-party software
| 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. |
| 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`. |
| Planetiler 0.10.2 | Apache License 2.0 | Build-time tool; it is not an Android runtime dependency. |
| 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. |
## 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.
ODbL applies to the database/data and derivative database obligations; it does not automatically place all NavFrame application code under ODbL. Geofabrik provides regional extracts as a source; its `latest` links change, so package provenance records the exact source bytes used.
## Online services
- **Valhalla routing:** The default endpoint is the public FOSSGIS demo service at `valhalla1.openstreetmap.de`. The [Valhalla project documents fair-use/rate limiting](https://valhalla.github.io/valhalla/) and asks apps published to end users to notify it through GitHub Discussions and send an identifying `X-Client-Id`. This endpoint is for development and testing, not a production availability guarantee. For a public release, arrange an appropriate provider or operate a service under explicit terms.
- **Nominatim search:** The public OSMF service's [usage policy](https://operations.osmfoundation.org/policies/nominatim/) applies to aggregate traffic. It limits use to at most one request per second, requires an identifying User-Agent or Referer and attribution, and prohibits autocomplete and systematic bulk use. Do not assume a per-device limiter is sufficient for a multi-user release. Use a suitably provisioned provider or proxy before scaling.
- **Online map styles:** The default online style uses OpenFreeMap/OpenMapTiles/OSM data. Its public service is provided under its own [terms](https://openfreemap.org/tos/) and does not constitute an SLA. Style providers may receive map-resource requests for the visible area. Keep attribution supplied by the style visible. NavFrame does not use `tile.openstreetmap.org` for bulk tile downloads or offline map generation.
Online search sends the submitted text and network metadata to the configured geocoder. Routing sends origin and destination coordinates to the configured routing endpoint. A remotely hosted map style receives resource requests that reveal the viewed area and network metadata. Avoid sending personal or sensitive destinations to public services.
## Notices
The APK contains license/attribution notices under `app/src/main/assets/`; NaviLite retains the Pillion notice under `third_party/pillion/`. When redistributing a binary, preserve the notices applicable to the components and datasets it contains. Review all transitive dependency licenses for a changed dependency set.
+78
View File
@@ -0,0 +1,78 @@
# MapLibre Native: direct TFT rendering
Research dated 2026-09-29 for phase 4. Goal: render real cartography and GPS position into an original 480×240 JPEG without an Activity-bound MapView or screen capture. This phase does not calculate routes or maneuvers.
## Selected dependency and compatibility
Pinned recommendation: `org.maplibre.gl:android-sdk-opengl:13.5.2`, published on Maven Central. Its [POM](https://repo.maven.apache.org/maven2/org/maplibre/gl/android-sdk-opengl/13.5.2/android-sdk-opengl-13.5.2.pom) and sources at tag `android-v13.5.2` were checked. The POM declares Kotlin stdlib 2.2.10, compatible with the project's 2.2.21, and coroutines 1.10.2; align dependencies to avoid mixing runtime expectations in tests.
Version 13.6.1 also exists, but 13.5.2 received later texture/snapshotter synchronization and Adreno GPU fixes. Pin a checked version without a dynamic range or prerelease. [Release 13.5.2](https://github.com/maplibre/maplibre-native/releases/tag/android-v13.5.2), [release 13.6.1](https://github.com/maplibre/maplibre-native/releases/tag/android-v13.6.1).
The current `android-sdk` artifact uses Vulkan; `android-sdk-opengl` explicitly selects OpenGL ES. This avoids initially packaging two backends. It does not guarantee compatibility with every GPU: test on the Xiaomi and an emulator. See [official rendering engines](https://maplibre.org/maplibre-native/android/examples/data/rendering-engine/).
## Offscreen API and resource ownership
`MapSnapshotter` accepts applicationContext, dimensions, style, and camera without requiring a MapView. Its renderer is **native and GPU-backed** and returns a `Bitmap`; do not describe the map itself as CPU-only rendering. The Canvas overlay and JPEG are additional NavFrame-owned steps.
API checked in [MapSnapshotter.kt at the selected tag](https://github.com/maplibre/maplibre-native/blob/android-v13.5.2/platform/android/MapLibreAndroid/src/main/java/org/maplibre/android/snapshotter/MapSnapshotter.kt):
```kotlin
MapLibre.getInstance(applicationContext)
val options = MapSnapshotter.Options(480, 240)
.withPixelRatio(1f)
.withStyleBuilder(Style.Builder().fromUri(styleUrl))
.withCameraPosition(CameraPosition.Builder()
.target(LatLng(latitude, longitude))
.zoom(zoom).bearing(bearingDegrees).tilt(0.0).build())
val snapshotter = MapSnapshotter(applicationContext, options)
```
Create and operate the snapshotter on Main; the class is annotated `@UiThread`. `start(readyCallback, errorHandler)` is asynchronous. Reuse `setCameraPosition` between successful captures, with only one capture pending. New fixes replace pending state; do not queue snapshots. On stop/cancel/timeout, call `cancel()` on Main and discard the instance. There is no public `close()`/`destroy()`; cancellation and dropping references are the exposed mechanism. Measure memory during long sessions.
Important detail in the pinned code: `onSnapshotReady` calls the callback and then `reset()`. Resuming a continuation immediately inside the callback and calling `start()` again can produce `Snapshotter was already started`. Posting the continuation with `Handler(Main).post` avoids reentry. Apply the same deferred dispatch after an error callback. A cancelled capture must not publish a frame or update the scheduler baseline; use request identity/generation to reject stale callbacks. After cancellation/error, create a fresh snapshotter so late completion cannot leak into a new capture.
The camera supports bearing and zoom. `Options.withPadding` is documented to take effect only when `region != null`; do not assume cameraPosition alone places GPS at 72% height. For the first map, project the GPS marker with `snapshot.pixelForLatLng(position)` and draw it at that point. Tune the camera/anchor only after verifying the projection. The same API can project a future polyline; for long routes, GeoJSON Source + LineLayer is preferable without adding routing to this phase.
[Official snapshot examples](https://maplibre.org/maplibre-native/android/examples/snapshotter/), [MapSnapshot API](https://maplibre.org/maplibre-native/android/api/-map-libre%20-native%20-android/org.maplibre.android.snapshotter/-map-snapshot/index.html).
## Service pipeline
The service owns GPS, state, snapshotter, and latest JPEG. Request a 480×240 / pixelRatio 1 snapshot, verify actual dimensions, draw the marker and original overlay without hiding attribution, encode on Default, then publish the JPEG. Call `RenderScheduler.markRendered` only after the complete frame exists. Bluetooth keepalive may continue sending the cached JPEG while the map loads; never create a second NaviLite reader/writer.
Start with at most **one snapshot per second** while moving and none for unchanged state. This is an initial power policy, not a measured SDK capacity. Rendering may take longer than a second over network/GPU: keep it serial and use the latest state. Separate `snapshotMs`, `encodeMs`, `frameAgeMs`, and ACK metrics without logging coordinates. On network/style failure, show an explicit unavailable/stale map state; do not draw decorative roads as real cartography. GPS loss must invalidate current measurements even if a cached image remains.
## Configurable vector source
Initial provider: OpenFreeMap. The `https://tiles.openfreemap.org/styles/dark` style was studied; integration ultimately chose an **original minimal NavFrame style**, `app/src/main/assets/map/tft-style.json`, with a vector source at `https://tiles.openfreemap.org/planet` and provider-hosted glyphs. The Dark JSON is not incorporated. Settings accepts another HTTPS style URL for a provider or self-host. The `MapDataSource` abstraction should keep source selection/configuration separate from the renderer and not turn the initial endpoint into a required backend. The [provider quick start](https://openfreemap.org/quick_start/) allows its styles in mobile apps using MapLibre Native and documents self-hosting. Its [style repository](https://github.com/hyperknot/openfreemap-styles) documents the Dark endpoint and origin.
OpenFreeMap advertises access without accounts/API keys, no view/request limits, and commercial use; it provides no SLA. These statements are not availability guarantees or authorization for mass regional downloads: distinguish documented SDK map use from unauthorized automated collection. Do not implement bulk prefetch in this phase. [Provider information](https://openfreemap.org/), [terms, updated 2026-09-09](https://openfreemap.org/tos/).
While investigating the unused Dark alternative, a Python request to `/styles/dark` with its default User-Agent returned HTTP 403. Repeating from the same machine with a browser User-Agent and a descriptive app User-Agent (`NavFrame/0.3 MapLibre/13.5.2 (Android 14)`) both returned HTTP 200 and 20,959 bytes of JSON. This is representative, not the exact User-Agent emitted by the SDK. Resources for the selected original style, `/planet` and glyphs, were checked separately with curl and returned HTTP 200. `/planet` returned TileJSON with vector PBF tiles, zoom 0–14, and OpenFreeMap/OpenMapTiles/OpenStreetMap attribution. This confirms HTTP availability under those conditions, pending native Android loading. Handle errors and allow source changes; never conceal failures with invented data.
A style may reference sprites/glyphs/TileJSON and additional tiles; a configurable HTTPS URL must also serve those resources. The local original style uses `Style.Builder.fromJson` and absolute HTTPS URLs. A configurable remote style uses `fromUri`, avoiding broken relative URLs caused by manually downloading/transforming JSON. To improve TFT legibility, hide unnecessary building/layers using a style observer or implement a compatible transformation after checking IDs and licenses. The fetched Dark JSON has no POI layers; it contains `building`, `highway_name_other`, `highway_name_motorway`, boundaries, and `place_*`. Its sources are `openmaptiles` vector and `ne2_shaded` Natural Earth raster; shading is not needed on TFT and may be removed if active. Its sprite/glyph/TileJSON references are absolute HTTPS URLs.
Do not use `tile.openstreetmap.org` as a production backend or capture another app's screen. Online tile requests disclose the viewed map area to the provider even if the app does not send GPS history; document that in settings. OpenFreeMap may use a CDN and security logs: [provider privacy policy](https://openfreemap.org/privacy/). Offline PMTiles/MBTiles and regional downloads belong to a later phase; a cached map does not imply offline coverage.
The footer retains `OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors`, including error/GPS-loss frames. For custom styles, check all attribution in MapLibre style metadata and add provider-required credits. Keep credits legible in the 480×240 footer and link terms from the phone's license screen. The SDK is BSD-2-Clause; NavFrame's TFT style does not copy the Dark theme. See [MapLibre research](MAPLIBRE_RESEARCH.md) and [Licensing](LICENSING.md).
An invalid style or connection should show `MAPA NO DISPONIBLE` and remove stale speed/bearing values; do not replace the real map with an illustrated road or fabricated position. Snapshot requests are asynchronous: create, start, and cancel `MapSnapshotter` from Main; its callback runs on the calling thread, and restart must wait for the SDK reset. Old/cancelled callbacks must not publish frames after STOP or a mode change.
## Phase limits
Phase 4 added cartography and position; phase 5 adds an explicit route plan. Neither screen is suitable for driving guidance. Robolectric can test composition/overlay but does not run JNI/OpenGL or load tiles on a device. Runtime Android and physical TFT map/route tests are still required. Demo routes must never be confused with real routes. See the [product brief](../yamaha_tft_native_navigator_codex.md) for later phases.
## Phase 5: coordinate route plan without guidance
The screen offers origin **DEMO Oviedo · simulated** or **GPS real · last position**, destination latitude/longitude, and an HTTPS `/route` endpoint. There is no geocoder. A GPS origin is accepted only if the provider is enabled and the fix is younger than 15 seconds. On explicit calculation, it sends a Valhalla `costing=motorcycle` request (beta profile); result text identifies origin, distance, estimated duration, and maneuver count. It retains response geometry for drawing a line; the received shape is not progress tracking or turn-by-turn navigation.
The polyline is shown as **PREVIEW** or **PLAN … no guidance**. The marker continues to show current GPS or demo position; movement does not imply map matching, route adherence detection, turn distance, or dynamically calculated ETA. Switching ordinary sources clears route/overlay; showing a plan explicitly selects the source appropriate to its origin. **Stop route · keep GPS/TFT** removes the plan/overlay without itself stopping GPS/map or transport.
Coordinates are sent to the chosen endpoint only when the user explicitly calculates a route. The endpoint receives origin/destination and connection metadata; the request body and coordinates are not written to local logs. The implementation limits requests to one per second and does not retry automatically. The public Valhalla/FOSSGIS server is for development/fair use and has no SLA. See [ROUTING.md](ROUTING.md) and [Licensing](LICENSING.md); check terms and data retention before switching endpoints.
This phase has no turn-by-turn, active route progress, live turns, off-route detection, rerouting, voice, geocoding, or verification that roads are safe for motorcycles. Do not use the line or route data to ride. A successful synthetic service request does not validate user GPS origin, MapLibre rendering on the phone, or route transmission to the TFT. Those physical tests remain pending.
## Phase 6: active route guidance
**Start guidance for calculated route** activates the GPS tracker or DEMO simulation over the geometry. The HUD displays icon, distance to maneuver, remaining distance, and approximate ETA. NO GPS, OFF ROUTE, and RECALCULATING hide stale estimates. Arrival requires distinct position evidence. The service preserves continuous transport and its stop controls.
Native composition is checked with `guidance.png` over a test background. This does not certify MapLibre GPU or physical navigation. See [testing](TESTING.md) and [thresholds/limits](ROUTING.md).
+74
View File
@@ -0,0 +1,74 @@
# NavFrame NaviLite protocol contract
Based on Pillion commit `6647af22f035ad74dc98f0e2a29e0c8a769a1caa`; attribution and scope are documented in [NAVILITE_RESEARCH.md](NAVILITE_RESEARCH.md) and `third_party/pillion/`. This is an experimental interoperability adaptation, unaffiliated with Yamaha or Garmin. The owner confirmed both NavFrame test and synthetic images on a 2026 MT-07 using a Xiaomi 11 Lite 5G NE / Android 14. Long-duration stability remains unverified.
## RFCOMM stream packet
| Offset | Bytes | Field |
|---:|---:|---|
| 0 | 4 | ASCII `nAl@` = `6E 41 6C 40` |
| 4 | 1 | version `01` |
| 5 | 1 | frameType, outgoing `06` |
| 6 | 1 | serviceType |
| 7 | 4 | payload length, UInt32 little endian |
| 11 | 1 | payloadDataType: value=0, pointer=1 |
| 12 | 4 | CRC UInt32 little endian |
| 16 | n | payload |
CRC-32/MPEG-2 is calculated over header bytes 0–11 concatenated with the payload, excluding the CRC itself. Polynomial `04C11DB7`, init `FFFFFFFF`, no reflection, xor-out 0. Standard vector `123456789` → `0376E6E7`. The implementation validates packet size (1 MiB), CRC, and version. The size limit is a defensive implementation bound, not a demonstrated protocol maximum. RFCOMM is a byte stream: one read may contain part of a packet or multiple packets.
## Handshake
1. Connect an insecure RFCOMM socket to the selected already-paired device, UUID `00007220-0000-1000-8000-00805F9B34FB`.
2. Wait for ESN_UPDATE service 66.
3. Send ESN_ACK service 81, value, `01 00`.
4. Send AUTH_REQUEST service 33, pointer, `1C 07 00 01 00 00 00 00`.
5. Wait for SEC_DATA service 83. Payload is an ASCII part number followed by a 4-byte nonce; each byte is obfuscated with XOR `0A`.
6. Send SEC_DATA_ACK service 84, pointer, the last 4 bytes XOR `0A`. Require at least 4 bytes before extracting them.
7. Send the following setup. Outgoing frameType is 6 for every packet.
| Order | Service | PDT | Payload hex |
|---:|---:|---:|---|
| 1 | 2 NAV_STATUS | 0 | `00 00` |
| 2 | 31 DAY_NIGHT | 0 | `01 00` |
| 3 | 10 HOME | 0 | `00 00` |
| 4 | 11 OFFICE | 0 | `00 00` |
| 5 | 13 GPS | 0 | `01 00` |
| 6 | 12 APP_SETTING | 0 | `00 00` |
| 7 | 14 ZOOM | 1 | `07 19 06 00 30 2E 32 20 6D 69` |
| 8 | 3 ROAD | 1 | empty |
| 9 | 17 SPEED_LIMIT | 1 | `00 00 00 00 03 6D 70 68` |
| 10 | 13 GPS | 0 | `01 00` |
| 11 | 12 APP_SETTING | 0 | `01 00` |
These values reproduce the observed upstream session, including scale/unit labels in miles. NavFrame's own image may show metric values; the detailed semantics of these metadata are unverified.
## Image and send cycle
Service 0, frameType 6, pointer 1, payload `03 | seq UInt16LE | JPEG`. Sequence starts at 1 and wraps to 0 after 65535. The JPEG is generated by NavFrame at baseline 480×240; it is not a phone-screen capture. Only one frame may be in flight: `sendFrame` writes the packet and waits for IMAGE_ACK service 80 before the next frame. ACK payload format/correlation is not demonstrated; as in Pillion, the implementation filters on service 80. Other services are consumed without executing commands. An ACK confirms protocol exchange acceptance, not that an image was visibly drawn on the TFT.
Connection, handshake, and ACK timeouts and cancellation close the socket, unblock I/O, and set ERROR; `disconnect` closes directly without waiting for a held mutex. The initial version required an explicit reconnect; after ERROR, transport can call `connect()` again with a new socket, full handshake, and reset sequence. Automatic pairing and additional commands are not implemented. The transport has no continuously running reader while no sends occur; it detects a remote close on the next send. Therefore the session keepalive policy needs periodic checks; without them, CONNECTED may remain visible until another send.
## Android API
`NaviLiteTransport(context, deviceAddress)` implements `dev.navframe.core.TftTransport`: `connect`, `disconnect`, `sendFrame`, and `connectionState`. Android 12+ requires runtime `BLUETOOTH_CONNECT`; legacy Bluetooth permissions apply through Android 11. The app selects from paired devices. CONNECTED means setup was sent; only observing the TFT confirms M1.
## Local verification
JVM codec tests cover standard and captured CRC, captured/independent framing, fragmentation, concatenation, resynchronization, UInt32 limits, truncation, version, nonce, and image sequence. The complete handshake and setup were manually compared with the pinned `core/Handshake.kt`; an automated end-to-end session/stream test is still missing. The owner physically confirmed the handshake and test/synthetic images on the specified MT-07 2026. Timeout and cancellation paths were reviewed by control-flow analysis and still need real Bluetooth close/recovery validation.
## Static session, keepalive, and recovery
The owner reported connection drops after long intervals without sends; duration and cause have not been measured. Pillion repeatedly sends the latest JPEG without image deduplication; no separate ping/heartbeat is documented. The initial conservative policy is to resend the cached latest JPEG every 1 second, with a new sequence and normal ACK. This does not change the wire format or require a redraw. This provisional interval requires testing with the target motorcycle.
`connect()` closes any prior socket, increments a generation, and performs full authentication. `disconnect()` invalidates the generation and closes immediately, including during connect/read. Android recovery should use a single session job to serialize connect/send/retry, retain the latest frame, use bounded retry backoff, and stop on STOP; stale callbacks must not reopen sockets. Permission failures and Bluetooth-off state need user intervention/configuration rather than rapid retries. Backoff policy is not a NaviLite protocol property.
## Screen-off behavior: Android requirements
Continuous Bluetooth sending belongs in a `connectedDevice` foreground service with `FOREGROUND_SERVICE`, the foreground-service type permission, and the runtime Bluetooth permission. GPS adds the `location` type. MediaProjection is not part of this architecture. This follows Android's [foreground-service type](https://developer.android.com/develop/background-work/services/fgs/service-types) and [background start restrictions](https://developer.android.com/develop/background-work/services/fgs/restrictions-bg-start); start from visible user interaction.
A foreground service does not keep the CPU awake. If suspension interrupts timers/keepalive, use a `PARTIAL_WAKE_LOCK` only during the user-requested active session, without turning on the display. Renew a protective timeout only while the session remains active and release on STOP, destroy, cancellation, or terminal failure. Keep acquisition/release under one owner. Android recommends choosing the lightest mechanism and reserving wake locks for work that cannot be suspended: [keep-device-awake guidance](https://developer.android.com/develop/background-work/background-tasks/awake) and [wake-lock release](https://developer.android.com/develop/background-work/background-tasks/awake/wakelock/release).
A wake lock addresses ordinary suspension; it does **not** guarantee execution during Doze. Android documents that Doze ignores wake locks for apps that are not exempt. Test screen-off and Doze behavior, and distinguish Xiaomi policy from CCU behavior. Do not assume a battery exemption or request one automatically. See [Doze and App Standby](https://developer.android.com/training/monitoring-device-state/doze-standby).
Keepalive stability, automatic reconnect, and wake-lock behavior need further integration/screen-off tests. Codec tests do not verify them. M1 confirms initial image transport, not GPS navigation or battery behavior.
+58
View File
@@ -0,0 +1,58 @@
# Pillion / NaviLite research
Date: 2026-09-29. Source inspected: [Pillion](https://github.com/alexandrevega/pillion), `main`, commit `6647af22f035ad74dc98f0e2a29e0c8a769a1caa`. The upstream repository was downloaded to `/tmp/navframe-pillion`; code was read only after checking `LICENSE.md`.
## License and reuse
The [pinned upstream license](https://github.com/alexandrevega/pillion/blob/6647af22f035ad74dc98f0e2a29e0c8a769a1caa/LICENSE.md) is PolyForm Noncommercial 1.0.0. It permits modification, use, and distribution for noncommercial purposes and describes personal hobby projects without anticipated commercial application. It is not a permissive license for commercial exploitation. Recipients of any part of the software must receive the terms or their URL and the required notice: `Required Notice: Copyright 2026 the Pillion authors`.
The full license is retained in `third_party/pillion/LICENSE.md`. The `navilite` module adapts Pillion algorithms and sequencing; its files identify their origin. Pillion's license is not presented as automatically licensing the rest of the project. Commercial use requires a separate license from the rightsholder.
## Structure and examined components
Pillion uses Kotlin Multiplatform and Compose Multiplatform, with module `composeApp`, Android code in `src/androidMain`, and shared protocol in `src/commonMain`. It uses JDK 17 and the Android SDK. Relevant files at the inspected commit:
| Source | NavFrame reuse |
|---|---|
| `protocol/NaviLiteCodec.kt` | Packet format and little endian handling; NavFrame adds version, CRC, and size checks |
| `protocol/Crc32Mpeg2.kt` | Checksum algorithm |
| `protocol/Auth.kt` | XOR and nonce; NavFrame adds a minimum length check |
| `protocol/ServiceType.kt` | IDs needed for initialization and images |
| `core/Handshake.kt` | AUTH payload and setup order/values |
| `core/FrameReader.kt` | Fragmented stream reading, reimplemented with bounds and CRC |
| `core/MirrorEngine.kt` | Stop-and-wait image sending and UInt16 sequence |
| `android/RfcommByteChannel.kt` | Insecure RFCOMM socket and UUID |
NavFrame does not reuse `CaptureService`, `MediaProjectionScreenSource`, ADB, mirroring, the GitHub updater, or UI components. The sender accepts a NavFrame-generated JPEG at 480×240.
## Transport and image
Bluetooth Classic RFCOMM, with the phone as client and the motorcycle already paired. UUID `00007220-0000-1000-8000-00805F9B34FB`; socket created with `createInsecureRfcommSocketToServiceRecord`. This is not BLE/GATT. Only one projection app should occupy the link; close StreetCross/Pillion before testing.
NaviLite on this path sends a baseline JPEG: service 0, pointer payload, imageType 3, UInt16 LE sequence, then JPEG. Pillion uses 480×240 and also documents 480×236. Do not assume every CCU accepts the same height: its documentation also distinguishes 480×234 for family `006-B3952` and 480×240 for `006-B4160` / `006-B4920`. NavFrame's initial target remains 480×240.
An ACK service 80 is expected after each image. Effective rate depends on JPEG size, encoding, and transport. Upstream-reported 14–15 FPS at approximately quality 40 is not a guarantee for the user's phone or motorcycle. Even an unchanged image may need periodic retransmission to keep the session active; see the real observation below. There is no need to render or encode an unchanged JPEG again.
## Compatibility: evidence and assumptions
The [upstream specification](https://github.com/alexandrevega/pillion/blob/6647af22f035ad74dc98f0e2a29e0c8a769a1caa/docs/PROTOCOL.md) attributes the original observation to an MT-07 2025, CCU `006-B4160-00`. The [compatibility table](https://github.com/alexandrevega/pillion/blob/6647af22f035ad74dc98f0e2a29e0c8a769a1caa/docs/COMPATIBILITY.md) contains reports for MT-07 2025, R9 2026, MT-09 2024/2025, MT-09 SP 2026, and XSR900 2025. These are upstream reports, separate from NavFrame tests below.
MT-07 2026 is not listed as confirmed in that upstream table. The owner first confirmed Garmin StreetCross works on the MT-07 2026 with a Xiaomi 11 Lite 5G NE / Android 14. The owner later confirmed **both NavFrame-generated images** (test and synthetic) appeared on the TFT: RFCOMM connection, handshake, and 480×240 images are verified by the owner for that combination; **M1-TFT achieved**. This has not been extrapolated to other motorcycles/phones, and long-term stability, power use, and latency have not been measured.
During that test, the owner observed the connection drop after a long interval between sends. No reproducible duration, disconnect log, or controlled screen/Doze condition is available yet. The behavior is consistent with CCU inactivity, but Android suspension must also be separated as a cause. No specific timeout or exclusive cause is asserted.
## Inactivity and recommendations after M1
At the inspected commit, `core/MirrorEngine.kt` always requests `latestFrame()` and sends the available JPEG after each ACK, even if its content is unchanged. It has no separate heartbeat/ping and does not deduplicate static images. `docs/PROTOCOL.md` lists service 16 `BT_THROUGHPUT_TIMEOUT_UPDATE` with unknown payload, so it cannot provide a documented keepalive. Service 80 acknowledges images but does not by itself establish how long a link can remain idle.
The initial recommendation is to resend the latest cached JPEG every **1 second**, with a new sequence, one frame in flight, and normal ACK wait. This is a provisional policy to measure, not a discovered CCU timeout or a universally guaranteed value. When navigation updates, send the new frame and reset the keepalive timer instead of sending an extra redundant packet. Reuse a static JPEG without rendering/encoding it again. A send failure starts conservative reconnection while the user keeps the session active; STOP must cancel sending/retries and release resources.
A stationary visual rate of zero FPS and a transport rate of zero packets are not equivalent. The scheduler may avoid redraws while retaining retransmissions if the CCU needs them. To find a suitable interval, compare screen on/off, stable connection at 1 s, then longer intervals. Record monotonic send/ACK times and failure cause, without location data. Stable measured durations are test evidence, not automatically protocol limits.
## Differences between upstream documentation and code
The PROTOCOL text describes NAV_STATUS `01 00` in setup, but `core/Handshake.kt` currently sends `00 00`. The pinned code was used as the smoke-test reference. The exact meaning of several setup values remains uncertain. StreetCross documentation contains services not needed by the smoke test; dashboard commands and navigation metadata are not implemented without a specific test.
The upstream reader does not validate CRC on receive or limit payload before reserving memory; NavFrame does. The upstream engine ignores non-ACK packets during transmission; NavFrame does not interpret navigation commands and documents this limitation. NavFrame adds timeouts and socket closure to unblock reads/connects.
The exact implementable contract is in [NAVILITE.md](NAVILITE.md).
+33
View File
@@ -0,0 +1,33 @@
# Offline maps and regional packages
NavFrame offline packages provide map display and local place/camera lookup. They do not include an offline routing graph or offline address geocoder.
## Included and regional data
The APK includes an Asturias PMTiles map and SQLite place database derived from OpenStreetMap data obtained from Geofabrik. The data timestamp is `2026-09-28T20:23:05Z`; the map covers zoom levels 6–14. The app also supports regional `.navframe` packages containing `manifest.json`, `map.pmtiles`, and `pois.sqlite`. Cantabria packages are available under `dist/` for manual import and as part of the on-demand worldwide region publishing workflow.
Regional downloads use the HTTPS catalog configured in **Settings → Offline maps**. Each catalog entry describes a region, package URL, exact byte count, SHA-256, geographic coverage, source date, and attribution. The downloader checks the package length and SHA-256, then the importer validates the package manifest, PMTiles metadata, and SQLite schema before committing it to private app storage. A malformed or incomplete package is rejected. Manual file import remains available.
The default catalog is hosted as a GitHub Release asset. Catalog URLs can be changed in settings; only use a catalog from a source you trust. SHA-256 protects against a package differing from the catalog, but the catalog is not currently signed or authenticated with a pinned key.
The app supports individual regional maps. It does not merge adjacent map sources into a continuous multi-region map view. Local place/camera searches can use installed regional catalogs, filtered by each region's coverage. The practical package limits are 600 MiB per archive, 1 GiB total offline storage, and up to twelve installed versions. Actual device storage and memory may impose lower practical limits.
## Worldwide region generation
The [worldwide package workflow](GLOBAL_OFFLINE.md) discovers source regions from Geofabrik's machine-readable index, builds selected regions on demand, and publishes packages and a catalog through GitHub Releases. “Worldwide” describes where a region may be sourced from; it does not mean every region has been generated, published, or tested. Choose smaller subdivisions for extracts or generated packages that exceed the current build or app limits. Do not infer global package size or performance from the Asturias or Cantabria examples.
Each generated package preserves OSM attribution and ODbL provenance. Geofabrik `latest` URLs change over time; retain the actual source checksums and timestamps to reproduce a package. See [Licensing](LICENSING.md) for data and redistribution terms.
## Offline use and limitations
Maps and installed places can be viewed without a network connection. Search for local places does not query Nominatim. Address search and route calculation need the configured online services. Following a previously calculated route can continue from its saved geometry, but route calculation and recalculation still need a network connection.
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.
## Package format and validation
The current package manifest uses schema version 1 and identifies `NavFrame Offline/1.0.0` map data and POI schema 1. Geographic coverage supports GeoJSON Polygon and MultiPolygon geometry, including multiple islands and holes. Package IDs and immutable versions are retained when publishing. Do not substitute a generic PMTiles archive: compatible data layers, style, glyph source, coverage, and POI schema are required.
OpenStreetMap-derived map and database products are distributed under ODbL 1.0. Preserve the manifest and attribution with packages. The app includes the full ODbL notice in its license information.
+29
View File
@@ -0,0 +1,29 @@
# OsmAnd reuse and UX research
Official research dated 2026-09-29, on the requested [osmandapp/OsmAnd](https://github.com/osmandapp/OsmAnd) repository, commit **2c0061842370920aad3c25e3748a625c0df0d7e6**. Licenses and file headers were read before considering reuse. **No OsmAnd code, layout, or artwork has been incorporated.**
## What it contributes as a reference
Its [official README](https://github.com/osmandapp/OsmAnd/blob/2c0061842370920aad3c25e3748a625c0df0d7e6/README.md) highlights maps, position/orientation, destinations, profiles, route preview, starting guidance, rerouting, and local maps. NavFrame adopts common navigation functionality with its own implementation and interface: map as the main content, visible destination, preparing a route before starting, profile controls, and motorcycle preferences. It does not reproduce a concrete layout, iconography, extensive text, brand, or protected visual themes.
## License by component
The [license at the examined commit](https://github.com/osmandapp/OsmAnd/blob/2c0061842370920aad3c25e3748a625c0df0d7e6/LICENSE) distinguishes several groups:
| Component | License/evidence | Current decision |
|---|---|---|
| OsmAnd Android, OsmAnd-java, OsmAnd-core, its own engine/routing/rendering | GPLv3, with specific stated exceptions | Do not integrate into the current APK |
| Custom layouts, UI/UX design, icons, and artwork | CC-BY-NC-ND 4.0; proprietary resources and store-specific terms also exist | Use original UI and drawings; do not copy these assets |
| Google's Java Protobuf, e.g. CodedInputStream | [Three-clause BSD header](https://github.com/osmandapp/OsmAnd/blob/2c0061842370920aad3c25e3748a625c0df0d7e6/OsmAnd-java/src/main/java/com/google/protobuf/CodedInputStream.java), exception noted in the root license | Could be isolated with notices and an audit of changes/dependencies; not needed by current features |
| Third-party fonts and icons | Root license lists Apache 2.0, public domain, and other terms; no single license covers every directory | If needed, use the original source and verify each file individually |
| Code received through pull requests | PULL_REQUEST.MIT.LICENSE and MIT contribution declaration | Does not imply MIT relicensing for files mixed with GPL code |
The presence of a library inside OsmAnd does not make it GPL, and an exception does not make every file permissive. For example, `com/wdtinc/mapbox_vector_tile` is listed as a modified library, but the examined JtsAdapter lacks a sufficient independent license and depends on OsmAnd and JTS types. It is not treated as a clean authorized copy without more research. `com/jwetherell/openmap/common/LatLonPoint.java` retains BBN copyright; that header alone does not grant broad permission. NavFrame incorporates none of these pieces.
## Relationship to Pillion
The current NaviLite module retains Pillion-derived material under **PolyForm Noncommercial 1.0.0**, with the license and Required Notice distributed. GPLv3 requires a combined distributed work to retain freedoms of use/distribution without additional restrictions; a commercial-use restriction on that material cannot simply be added to a GPL work as a whole. Therefore directly combining OsmAnd's GPL engine/UI with NaviLite in one distributed work is not a matter of copying a few classes and adding attribution. This assessment is grounded in the [PolyForm license](https://polyformproject.org/licenses/noncommercial/1.0.0/) and [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html), especially sections 5 and 10. It does not claim that consulting functional ideas, using separate programs, or every private use is prohibited.
Viable future reuse would need to be specific: a permissively licensed library with verified terms/notices, alternative authorization from the rightsholders, or a separately evaluated app integration. Embedding OsmAnd-core/OBF/offline routing is outside the current increment. The existing PMTiles map is not an OsmAnd/Valhalla routing graph.
NavFrame already uses components suited to its contracts—MapLibre, Gson, OSM data, and NaviLite derived from Pillion—and keeps its own profile/guidance engine. The app is not rewritten to copy OsmAnd, and the new UX is not presented as a port of its code.
+61
View File
@@ -0,0 +1,61 @@
# Offline places / POIs for Asturias — 0.9
Catalog derived from the same OpenStreetMap/Geofabrik PBF as the Asturias map. Nominatim and Overpass are not queried to generate it; Google Places or a new backend are not integrated.
## Data and provenance
Source: [Geofabrik Asturias](https://download.geofabrik.de/europe/spain/asturias.html), `asturias-latest.osm.pbf` downloaded for this project, timestamp **2026-09-28T20:23:05Z**. PBF SHA-256: `1ab5967cc162027f0d05b2b603b65ad3f5d3b5466551613054cf5e6b28b9eb5d`.
Artifact: `app/src/main/assets/offline/asturias-pois.sqlite`, **2,347,008 bytes**, SHA-256 **c5d8413f260b0b3e5bdc3da4c9b5e33f8e66f5acd80cc284a7e8668f039798f9**, SQLite `user_version=1`, recipe **NavFrame POI 1.0.0**. Timestamp, schema, source hash, attribution, bounds, and counts are stored in `metadata`. The rectangle south/west/north/east is 42.9/−7.2/43.75/−4.45; objects are clipped to the regional extract polygon, not guaranteed to cover every neighboring region within the rectangle.
**11,457 places**, from OSM nodes, ways, and relation areas:
| Group | Count | Selection |
|---|---:|---|
| Fuel | 259 | `amenity=fuel` |
| Workshops | 196 | `shop=motorcycle_repair/car_repair/tyres`; explicit motorcycle repair `motorcycle:repair=yes/only`, or `repair=yes/only` on `shop=motorcycle` |
| Food | 4,393 | `amenity=restaurant/fast_food/cafe/food_court/pub/bar` |
| Lodging | 1,383 | `tourism=hotel/motel/hostel/guest_house/camp_site/caravan_site/chalet/apartment` |
| Shopping | 5,226 | Other valid `shop` values, including motorcycle/parts stores without explicit repair tagging |
Classification follows [amenity](https://wiki.openstreetmap.org/wiki/Key:amenity), [shop](https://wiki.openstreetmap.org/wiki/Key:shop), [tourism](https://wiki.openstreetmap.org/wiki/Key:tourism), and [motorcycle](https://wiki.openstreetmap.org/wiki/Tag:shop%3Dmotorcycle). A general workshop is not verified as offering motorcycle repair, and a fuel station does not guarantee stock. OSM may be incomplete or stale; names/hours/contact details are shown as source data, not as commercial verification.
Nodes use their own position. Assembled areas use an interior `representative_point` instead of a centroid that might fall outside a concave polygon; compatible open ways use their midpoint. These are object positions, not guaranteed entrances or road access. **Zero geometry failures** were reported in this extraction. IDs `n/<id>`, `w/<id>`, and `r/<id>` distinguish object types and avoid ID collisions; records are not merged just because names match. OSM can represent one business as different objects, so duplicate physical businesses are not perfectly removed.
Relevant inactive markers are excluded (`disused`/`abandoned` and prefixes for shop/amenity/tourism), as are `shop=no/vacant/disused/abandoned/closed`. The generator does not invent names or addresses: names use existing `name`/`name:es`/`brand`/`operator`, with a category “unnamed” label only as a last resort.
## Contract and SQLite
The original core `OfflinePlace` retains ID, name, `PlaceCategory`, position, optional address/openingHours/website/phone, and optional straight-line distance. `normalizePlaceSearch` uses NFD, removes combining marks, lowercases independently of locale, compacts whitespace/control/format characters, and preserves non-Latin alphabets. Python generates `search_name` with the same algorithm. Map glyphs remain limited to Unicode 0–2047; native list text does not depend on these PBF glyphs.
Schema: `places(id TEXT PRIMARY KEY, name TEXT, search_name TEXT, category TEXT, latitude REAL, longitude REAL, address TEXT, opening_hours TEXT, website TEXT, phone TEXT)`. Name/search/category/position are required and categories are checked. Indexes: `(category,latitude,longitude)`, `(latitude,longitude)`, `search_name`. `metadata(key TEXT PRIMARY KEY,value TEXT)` identifies version/coverage. Android queries are parameterized and escape `%`, `_`, and backslash via `escapePlaceLike` with `ESCAPE '\'`; an apostrophe remains data. Bounded substring search does not make the name index a full-text-search guarantee for millions of places.
The Android repository opens the catalog as read-only SQLite. Local text/category and region/selected-position search returns a bounded number of places; selecting one enters the existing destination/preview flow. Displayed distance is straight line, not road distance. Without a usable GPS fix, users can search from the map center or explore installed catalogs; NavFrame does not invent a phone location or automatically query a geocoder for POIs.
Address fields preserve existing `addr:*` tags. `opening_hours` remains raw text; the app does not evaluate “open now”. Website accepts only HTTP/HTTPS with a host and no credentials/whitespace/control or dangerous characters. Phone retains only simple telephone characters. Both are optional and are not opened automatically; external links require explicit user action. The phone map displays catalog markers; this increment does not add a POI layer to PMTiles.
## Compatibility and license
The catalog installs independently from the cartographic file: PMTiles/`NavFrame Offline 1.0.0` style are unchanged, as are user-imported regions. Old maps are not deleted or regenerated to enable businesses. Catalog schema 1 can be copied/updated as a whole after size/checksum/schema validation and before activation; incompatible versions must be rejected without destroying the previous database. Map manager 0.8 does not interpret this catalog as new PMTiles.
The complete derived SQLite database is distributed inside the APK ZIP at `assets/offline/asturias-pois.sqlite` under [ODbL 1.0](https://opendatacommons.org/licenses/odbl/1-0/). `OFFLINE_DATA_LICENSE.md` adds source/hash/recipe to the full license; preserve `© OpenStreetMap contributors` in the UI. Build-time Pyosmium 4.3.1 ([BSD 2-Clause](https://github.com/osmcode/pyosmium/blob/v4.3.1/LICENSE.TXT)) and Shapely 2.1.2 ([BSD 3-Clause](https://github.com/shapely/shapely/blob/2.1.2/LICENSE.txt)) are not packaged in Android. The script/models are original, not OsmAnd code.
## Reproduction and tests
```sh
python3 -m venv build/offline/poi-venv
build/offline/poi-venv/bin/pip install -r tools/offline/poi-requirements.txt
build/offline/poi-venv/bin/python tools/offline/build-pois.py \
--pbf build/offline/asturias.osm.pbf \
--output app/src/main/assets/offline/asturias-pois.sqlite \
--osm-date 2026-09-28T20:23:05Z
build/offline/poi-venv/bin/python -m unittest discover -s tools/offline -p 'test_build_pois.py' -v
```
The command takes an explicit date that must match the PBF; `latest` changes, and another source changes the counts/hash. It builds in staging and activates the file after `integrity_check`; the script does not download data onto the phone. Extraction does not calculate routes or use network access.
Four Python tests passed: an original OSM fixture with node/way/relation cases, categories/lifecycle, optional metadata and sanitization, plus integrity/coordinates/normalization/identity checks for the **complete real catalog**. Three core JVM tests check Unicode/diacritics, LIKE escaping, and optional fields; Android runs the final repository/UI build tests. These checks do not certify businesses remain open or have road access. Physical 0.9 POI search/selection still needs testing on the phone; the owner's earlier confirmation of Asturias offline map is separate evidence and does not validate this new catalog.
## Local Cantabria (0.10)
The search center must lie in Asturias or an installed region. The app then queries available catalogs, filters each result to its region's polygon and the search radius, and deduplicates by OSM identity. The Cantabria file contains **8,448 POIs** (fuel 171, workshops 205, food 2,690, lodging 1,000, shopping 4,382), SQLite `user_version=1`, derived from the Geofabrik PBF timestamped 2026-09-28T20:23:05Z. Source, hash, coverage, recipe, and component hashes are in the manifest within `dist/es-cantabria-20260928.1.navframe` and in [OFFLINE.md](OFFLINE.md). Importing it does not remove the Asturias map or catalog. Local search can work in airplane mode; route calculation and address search still require Internet. Cantabria is one additional region, not a Europe-wide catalog.
+29
View File
@@ -0,0 +1,29 @@
# 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.
## Product goal
Build an Android navigation app for compatible Yamaha motorcycle TFT displays. The initial target is a Yamaha MT-07 2026, 480×240 TFT, connected through the Yamaha/Garmin CCU using a NaviLite-compatible Bluetooth transport. NavFrame renders its own navigation image at the TFT's target dimensions. It does not capture or crop another app's screen with MediaProjection.
The intended data flow is Android GPS plus map data and route results into shared navigation state, then a native 480×240 renderer, a TFT-specific overlay, JPEG/frame encoding, and Bluetooth transmission. The design does not aim to reproduce all of Google Maps or Waze.
## Planned user capabilities
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.
## Engineering principles retained
- Keep demo data visibly distinct from GPS/route data.
- Make route start, online search, and other network requests explicit user actions.
- Preserve attribution and licenses for OSM data, map styles, fonts, and software.
- Keep location out of logs and avoid sending sensitive coordinates/search terms to public services.
- Separate rendering cadence from Bluetooth keepalive/ACK flow; do not queue stale frames.
- Treat GPS loss, service errors, stale map data, and failed route requests as explicit states.
- Verify simulation, JVM/Android tests, and physical-device behavior as separate evidence.
## Provenance and limitations
The source brief is a planning document, not a current API contract or report of completed features. Later technical references document what was implemented and tested. Consult [NaviLite protocol notes](NAVILITE.md), [TFT rendering](TFT_RENDERING.md), [MapLibre research](MAPLIBRE_RESEARCH.md), and [offline regional packages](GLOBAL_OFFLINE.md) for current details.
+19
View File
@@ -0,0 +1,19 @@
# Fixed speed-camera advisories
Camera advisories are opt-in and default to off. They are available only during live GPS route guidance, never in demo playback. The alert text says “Possible fixed speed camera nearby.” It is informational; it is not a speed-limit warning, a guarantee of camera presence or absence, or a substitute for posted signs and safe riding.
## Data and matching
The offline POI database can include an indexed `speed_cameras` table generated from a regional OSM extract. The current generator accepts active `highway=speed_camera` nodes and selected traffic-surveillance nodes explicitly tagged for speed enforcement. Existing regional packages without this optional table remain usable. OSM coverage is community maintained and can be incomplete, stale, or incorrectly positioned. The database does not infer cameras from unrelated CCTV or speed display tags.
An alert is considered only when a route exists and a camera is close to its geometry. The runtime requires successive GPS fixes showing approach, an acceptable bearing, lateral distance, fix accuracy/age, and minimum speed. It announces at roughly 35–500 m and suppresses repeat alerts for the same OSM object for ten minutes. Distances are approximate, straight-line estimates rounded for display.
Direction tags are preserved as source evidence, but the app does not certify enforcement direction, lane, lens orientation, or relation topology. Parallel roads, route geometry, missing camera data, changes since the extract, mobile cameras, and average-speed enforcement are not reliably handled. Never treat silence as evidence that a road has no enforcement.
## Legal and regional availability
Rules vary by jurisdiction. Check local law before enabling or using camera-location alerts. For example, France's [Code de la route Article R413-15](https://www.legifrance.gouv.fr/loda/article_lc/LEGIARTI000025111528/2026-05-23) covers devices or products that warn or inform users about the location of enforcement equipment. This project does not provide a jurisdiction-by-jurisdiction legal determination. Global package availability does not mean camera alerts are lawful or enabled everywhere; distribution should apply an appropriate regional policy before broad release.
Camera locations are derived from OSM and distributed with ODbL attribution. Source extracts, timestamps, and checksums are recorded in package manifests. Do not combine another provider's camera data without checking its license, terms, completeness, and local restrictions.
Automated extraction and policy tests do not validate real-road timing, GPS quality, legal status, or audible behavior. Physical audio and riding-condition validation remain pending.
+36
View File
@@ -0,0 +1,36 @@
# Documentation index
## Project and development
- [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)
- [Contributing](../CONTRIBUTING.md)
- [Security reporting](../SECURITY.md)
## Maps, data, and services
- [Offline maps and regional packages](OFFLINE.md)
- [On-demand worldwide region build and publication](GLOBAL_OFFLINE.md)
- [Offline POI catalogs](POIS.md)
- [Historical regional maps/POI rollout plan](REGIONAL_MAPS_PLAN.md)
- [Routing and guidance limits](ROUTING.md)
- [Explicit geocoding and Nominatim policy](GEOCODING.md)
- [MapLibre Native research](MAPLIBRE_RESEARCH.md)
- [OsmAnd licensing and UX research](OSMAND_RESEARCH.md)
## Yamaha TFT and navigation output
- [NaviLite protocol contract](NAVILITE.md)
- [Pillion/NaviLite source and license research](NAVILITE_RESEARCH.md)
- [TFT rendering and navigation data](TFT_RENDERING.md)
- [Voice directions](VOICE.md)
- [Fixed speed-camera advisories](RADARS.md)
- [Testing and physical-device status](TESTING.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).
+100
View File
@@ -0,0 +1,100 @@
# Offline places and regional maps: status and next steps
Initial proposal dated 2026-09-29, updated 2026-09-30. NavFrame 0.10 introduced the Asturias POI catalog and local regional-package format/import, with Cantabria as a second region. A later increment added an on-demand worldwide source/build/publication workflow and app catalog downloads; its current behavior is described in [GLOBAL_OFFLINE.md](GLOBAL_OFFLINE.md). The catalog is not complete worldwide coverage. Offline routing is not implemented. This document preserves the original data/product rationale and distinguishes it from later implementation.
## Current data
Asturias has a 34,617,483-byte PMTiles map containing roads, places/towns, inland water, land cover, and buildings at zoom 6–14, plus an SQLite catalog of 11,457 POIs. Cantabria is a separate `.navframe` map/POI package. Both retain separate source extracts and hashes. Maps are selected as individual regional sources; place search combines installed catalogs using the chosen location's coverage. The APK includes Noto Sans Regular glyphs for Unicode 0–2047. Current app limits are 1 GiB total, 600 MiB per compressed regional package, and up to twelve installed versions. These are prototype limits, not demonstrated capacity for all regions.
## Offline places for Asturias
The appropriate source is **the same OSM extract**, not repeated geocoder queries. OSM documents [amenity](https://wiki.openstreetmap.org/wiki/Key:amenity), [shop](https://wiki.openstreetmap.org/wiki/Key:shop), and [tourism](https://wiki.openstreetmap.org/wiki/Key:tourism); objects can be nodes, areas, or relations. Names and metadata remain OSM data under ODbL, with no promise of completeness, current opening hours, or the commercial coverage of another provider.
Initial visible categories:
| Visible category | Input OSM tags |
|---|---|
| Fuel | `amenity=fuel` |
| Motorcycles and repair | `shop=motorcycle/motorcycle_repair`; `motorcycle:repair=yes` or `repair=yes` on a motorcycle shop identifies repair; `shop=car_repair` remains a separate general workshop category |
| Food | `amenity=restaurant/fast_food/cafe` |
| Lodging | `tourism=hotel/motel/hostel/guest_house/camp_site` |
| Shopping | Compatible `shop=*` objects in their own category; do not treat `abandoned`/`disused` as active businesses |
Motorcycle workshop semantics are documented at [shop=motorcycle](https://wiki.openstreetmap.org/wiki/Tag:shop%3Dmotorcycle). Do not claim every car repair shop works on motorcycles.
Generate two products from the same PBF date/schema:
1. **PMTiles** with an additional `poi` layer for icons/names at close zoom, simplified geometry for display, category-specific appearance zoom, and density handling. Use original drawings; TFT shows a small useful selection while the phone can explore/tap.
2. **`pois.sqlite`** for complete offline search, independent of zoom and currently loaded tiles. Columns include internal ID, OSM type/ID, category, name/brand/operator, lat/lon, existing address, and optionally opening hours. Retain OSM identity for cross-region de-duplication and references. For unnamed entries, use the category as a label; do not invent a business name.
For areas, use an interior point/known entrance rather than an arbitrary center that may fall outside the geometry. A map point does not certify access or motorcycle entrance; routing currently snaps the destination to a road. Preserve provenance/date and remove disused/abandoned objects during build. Do not blindly merge nearby branches just because names match.
The proposed local query `PoiCatalog.search(query, categories, bounds, limit)` returns results and position. SQLite supports [R*Tree](https://www.sqlite.org/rtree.html) for spatial lookup; verify Android SQLite support in implementation and retain category/lat/lon indexes as fallback. Use text search compatible with the minimum Android SQLite version (verify FTS4), normalize diacritics explicitly, and parameterize queries. “Near me” requires usable position; allow map-region exploration without inventing GPS. Sort by actual distance to the selected location and distinguish straight-line from road distance. Do not imply coverage outside installed regions.
Selecting a business sets the existing destination, prepares route preview, and allows an explicit start. It must not replace active guidance or launch remote searches for every map movement. Offline catalog tests should cover coordinates/areas, duplicates, categories, Unicode, empty searches, overlapping regions, and no-network selection.
The [official Nominatim policy](https://operations.osmfoundation.org/policies/nominatim/) prohibits systematic queries to download all POIs and autocomplete on the public instance. Nominatim remains an explicit remote destination search; it **does not build this catalog**. Extracting categories from downloadable PBF files does not query that API. Any future business-data provider needs its own license/contract and attribution.
## Regional packages and global rollout
[Geofabrik provides downloadable Europe, country, and subregion extracts](https://download.geofabrik.de/europe.html) under ODbL. Offer regional packages, not all of Europe in the APK. Users may select regions for a trip and may eventually install all compatible packages if storage permits. For Spain/France/Germany and other large countries, use subdivisions when a package exceeds build or app limits. See [GLOBAL_OFFLINE.md](GLOBAL_OFFLINE.md) for the implemented on-demand workflow, inputs, release/catalog contract, and current constraints.
The original proposed build pipeline, outside the phone, was:
`Geofabrik regional PBF → pinned Planetiler + NavFrame profile → map.pmtiles + pois.sqlite → validation → immutable manifest → import files or HTTP server`
Maintain a versioned shared schema, explicit migrations, and a compatible renderer. A POI map layer needs a map schema version the original 1.0.0 importer did not accept. Do not accept arbitrary PMTiles schemas. Phone and TFT use the same styles/glyphs/attribution.
Each manifest should contain stable region ID, label, coverage polygon/bounds, parent region, OSM date, schema/style version, min/max zoom, URLs, exact sizes and SHA-256 per artifact, license/attribution, and minimum compatible app version. A catalog signed by a pinned publication key would provide authenticity; a hash alone detects corruption but does not authenticate a manifest served by an attacker. Versioned packages retain immutable URLs and allow atomic updates.
Select by **actual coverage**, not only rectangles: countries/subregions have irregular boundaries, islands, and overlap. Before a trip, install regions intersecting the route with edge overlap. Do not present a bbox as continuous coverage. A multi-region renderer must mount the required sources and avoid duplicate features; SQLite search combines indexes and deduplicates by OSM identity. The current map selector still selects an individual regional map, so combining adjacent regions requires new work.
For European/global use, add shared, versioned glyph coverage by writing system. Latin/Greek/Cyrillic are broadly covered by current ranges, but Georgian and many other business-name characters are not. Do not promise full names with glyphs 0–2047. New packages should declare needed ranges; generate/distribute font derivatives under their OFL terms without hidden remote font fetches.
### Download and install design
Users select regions, see sizes/date/required space, then download or import via SAF. Keep file/USB import available for personal use without hosting. Neither approach requires downloading every country or harvesting public map tiles.
For first-party packages, use HTTPS, content length/ETag, HTTP Range + If-Range resume, persistent staging with progress/checksum, cancel/pause, free-space checks for both new and old versions, activation only after every component validates, and coordinated deletion with readers. If ETag changes or server rejects Range, restart safely; never combine different versions. Keep work off the UI thread. Replace a whole region; [PMTiles is not updated in place](https://docs.protomaps.com/pmtiles/).
A server needs no dynamic GIS; static HTTPS files/manifests with practical transfer limits and Range support are enough. [PMTiles cloud-storage guidance](https://docs.protomaps.com/pmtiles/cloud-storage) describes object storage and partial requests. For personal use, generating on a PC and importing may be enough; CDN/managed storage is a future distribution choice with storage, transfer, and request costs. No price estimate or hosting commitment is made here.
### Size and capacity
The Geofabrik page consulted advertised **32.7 GB for the raw Europe PBF** and showed a specific `europe-260928.osm.pbf` version at **35,069,743,863 bytes** (page and bytes use different rounding units). This is **not** the final NavFrame package size or phone download. Output depends on zoom, layers/attributes, simplification, density, and POI/index choices. Do not extrapolate Asturias's ratio to the continent.
Useful size estimates require first building Asturias with POIs and a second border region, measuring final bytes/build time/RAM/temporary disk, and summing exact sizes from published manifests. Separate PC/server build cost, bytes downloaded, and storage needed for installation/update. Do not promise “Europe fits in X GB” without those measurements.
## Offline cartography/POIs versus offline routing
Maps and local places can work offline. **Calculating or recalculating routes** still depends on configured Valhalla; following an already calculated geometry is different. PMTiles and SQLite POIs do not contain the routing graph/access/restriction indexes needed to calculate routes.
Offline routing later requires evaluating a routing engine and building compatible regional data. [Valhalla uses dedicated graph tiles](https://valhalla.github.io/valhalla/concepts/why-tiles/); Android/NDK compilation, footprint, timings, and cross-region routing need evaluation. MapLibre SDK does not provide this. OsmAnd has a different engine/OBF format, but embedding it requires the GPL/PolyForm/license assessment in `OSMAND_RESEARCH.md`; do not treat its packages or engine as interchangeable with PMTiles.
## Original recommended increments
After closing 0.8, first deliver **Asturias offline POIs** for fuel/motorcycles/food/lodging, local search, and selecting a destination from real data. Regenerate map schema, add the SQLite catalog, migration, and package importer together; verify phone/TFT map and airplane-mode search. Then build a second region with the same pipeline and validate continuity/de-duplication. Only then expand to a downloadable Europe catalog and implement update/resume. This describes the original plan, not a claim that those steps are all complete.
## Local Cantabria package (2026-09-30)
The first local package was generated to validate the format and file import. It is [`dist/es-cantabria-20260928.1.navframe`](../dist/es-cantabria-20260928.1.navframe); the verifiable local catalog is [`dist/regional-catalog.json`](../dist/regional-catalog.json). Those local artifacts had no associated endpoint, server, or HTTP download. Copy the `.navframe` file to the device and import it with the file picker. Current network catalog downloads and worldwide package publication are separate later features; see [GLOBAL_OFFLINE.md](GLOBAL_OFFLINE.md).
The package is **27,782,594 bytes** (SHA-256 `b4f8e8075301a645e33511642119997dc27b1fb8e52ae0caa14519ebd3b79ce9`). It contains only `manifest.json`, `map.pmtiles`, and `pois.sqlite`. The source PBF was timestamped `2026-09-28T20:23:05Z`, size **35,537,700 bytes**, SHA-256 `0036ed2762d2ef7833362f15b5e09904dacbea47d0a2381bbc1fab80a92d0731`. The manifest records source/component hashes, PBF URL, official Cantabria `.poly` URL and SHA-256, OSM/ODbL attribution, and Planetiler/NavFrame build versions.
The map uses NavFrame Offline 1.0.0 style, zoom 6–14, and the actual Cantabria polygon; manifest rectangle validates extent, while the polygon determines whether a coordinate is covered. Local catalog has **8,448 POIs**: 171 fuel, 205 workshops, 2,690 food, 1,000 lodging, 4,382 shopping. Extraction reported zero geometry failures. The package has no offline routing graph. Asturias remains another bundled data pack; this initial Cantabria package did not publish or create a Europe catalog.
To reproduce the package on a build machine, install dependencies from `tools/offline/poi-requirements.txt`, place matching PBF and `.poly` inputs locally, and provide Planetiler 0.10.2:
```sh
python3 tools/offline/build-region.py \
--id es-cantabria --name Cantabria --version 20260928.1 \
--pbf build/offline/cantabria/source.osm.pbf \
--coverage-poly build/offline/cantabria/coverage.poly \
--coverage-url https://download.geofabrik.de/europe/spain/cantabria.poly \
--planetiler-jar build/offline/planetiler-0.10.2.jar \
--source-url https://download.geofabrik.de/europe/spain/cantabria-latest.osm.pbf \
--python build/offline/poi-venv/bin/python \
--output dist/es-cantabria-20260928.1.navframe
```
To package already generated components, replace `--planetiler-jar` with `--map-pmtiles ... --pois-sqlite ...`; the packager rereads the PBF timestamp and recalculates hashes. Geofabrik's `latest` endpoint can change; retain the local PBF identified by SHA-256 to reproduce this exact version. The 27.8 MB figure applies to this package and must not be extrapolated to other regions.
+70
View File
@@ -0,0 +1,70 @@
# Routing and guidance (English summary)
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.
# Detailed routing notes (Spanish)
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.
## Servicio inicial y privacidad
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.
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.
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ó.
## Petición y perfiles
`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.
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:
| Perfil/opción | Petición motorcycle | Semántica |
|---|---|---|
| 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 |
`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.
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.
`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.
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.
## Resultado puro JVM
`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.
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.
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).
## Verificación
`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.
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.
## Guiado básico y límites — fase 6
`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.
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.
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.
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.
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` 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.
+184
View File
@@ -0,0 +1,184 @@
# Testing and physical validation status (English summary)
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`.
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.
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.
# Historical test procedures (Spanish)
## M1-TFT: preparación y humo
**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.
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.
### Comprobación local (sin moto)
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.
### Procedimiento M1 (ya completado; repetir solo tras cambios de protocolo)
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.
É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.
### Prueba de pantalla apagada y recuperación (pendiente)
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.
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.
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.
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.
### Fase 2: demo animada (datos ficticios)
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.
### Fase 3: GPS real sin mapa ni ruta
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.
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.
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.
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.
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.
### Fase 4: mapa real MapLibre
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.
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.
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**.
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.
### Fase 5: cálculo y visualización de un plan (sin guiado)
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.
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.
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.
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.
### Fase 6: guiado y recálculo
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.
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).
### Fase 7: búsqueda explícita de destino
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.
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.
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/).
### Fase 8: paquete vectorial offline de Asturias
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.
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.
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.
**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.
### Fase 9: flujo de navegación en moto y preferencias Yamaha
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.
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.
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.
### Fase 10: catálogo local de lugares de Asturias (0.9)
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.
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.
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.
### Permisos y recuperación
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.
## Entorno de desarrollo observado
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.
## Registro de verificación local
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.
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.
### Fase 11: paquete regional local de Cantabria (0.10)
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.
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.
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`.
### Fase 12: pantalla principal de mapa y búsqueda unificada (0.11)
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.
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.
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.
### Aviso de GPS al centrar (0.11.1)
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.
### Voz y radares fijos opcionales (0.12.0)
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.
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.
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.
+57
View File
@@ -0,0 +1,57 @@
# TFT rendering and navigation data
This document distinguishes visual demo data from real GPS data. Output for the Yamaha is an original **480 × 240** image rendered directly; the phone preview should show the same JPEG bytes before they are sent.
## Phase 2: synthetic demo
Start the demo with **Start animated demo**. It supports TFT layout iteration and transport tests. Position, motion, road segment, route, maneuver, and distances are invented by the app. The UI says `DEMO · carretera y maniobras ficticias`; the TFT says `DEMO · RUTA FICTICIA` and `ETA … · DEMO`. These values do not come from the phone, OSM, route calculation, or motorcycle. Demo values are not riding directions.
Drawing uses a logical 480 × 240 `Canvas`, prioritizing the maneuver, route shape, and position marker. `RenderScheduler` keeps only the latest state and avoids repaints for small changes: initial thresholds are 2 m position, 3° bearing, 0.5 m/s speed, and 10 m for visible distance changes. Initial maximum redraw rates are 1 FPS stopped, 5 FPS moving, and 10 FPS turning. These limit redraws; NaviLite keepalive sending is a separate configurable cadence (0.5/1/2 s) that waits for ACK and never queues frames. An ACK delay must not build a frame queue or block the demo.
The accompanying camera policy keeps the marker near 72% screen height and changes simulated zoom by speed/turn distance: 17 below 30 km/h, 16 through 70 km/h, 15 above, and 17.5 within 150 m of a turn. In this phase the renderer draws an illustrative road directly on Canvas; it does not project tiles or a map. These parameters only support future map integration.
Check by starting the simulated demo and watching the preview for at least one minute. Position/bearing should change, frames should remain 480 × 240, and `DEMO` should remain visible. Stopping the demo should halt its animation and update source. This check does not test GPS or real navigation.
## Phase 3: GPS position
The real source uses Android `LocationManager` with `GPS_PROVIDER` from the navigation service. On **Start real GPS (no map/route)**, Android requests precise location (`ACCESS_FINE_LOCATION`) if it is not already granted. The foreground service uses type `location`, or `location|connectedDevice` when TFT Bluetooth is also active. The app does not request permanent/background location: the service starts from the visible Activity. Revisit this policy if the start flow changes.
Platform references: [location permissions](https://developer.android.com/develop/sensors-and-location/location/permissions), [foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types), and [restrictions on starting a service from the background](https://developer.android.com/develop/background-work/services/fgs/restrictions-bg-start).
When switching from demo to GPS, the image stops identifying itself as demo. A local grid moves with real position, and the marker rotates to the real bearing if Android provides one; speed and accuracy also come from the fix. This is a schematic visual aid without cartography, not a scaled map or route. Fixes older than 15 seconds are discarded. If GPS is lost, the TFT shows `SIN SEÑAL`, `--`, and `Esperando una posición GPS reciente`. Do not replace missing measurements with invented values. Do not persist exact coordinates in logs.
The GPS phase has no map, destination search, calculated route, or real turn-by-turn instructions. A decorative line that follows position is not a navigable route. Do not use this screen as riding guidance.
To check it, grant precise location and test while parked in an open area; validate loss/recovery states without sharing coordinates in screenshots or logs. **Stop navigation · keep TFT** must cancel GPS listening without ending an existing TFT session; **Disconnect TFT** also ends Bluetooth. This phase has not yet had runtime visual verification; review the exported Canvas image and physical test separately. Emulator location simulation can aid development but does not replace testing on the Xiaomi.
## Phase 4: MapLibre in a 480 × 240 frame
The app includes MapLibre Native OpenGL and `MapSnapshotter` to request a GPU snapshot at **480 × 240** from the service; it then draws its own marker/state, attribution, and text and encodes the NaviLite JPEG. It does not use an Activity `MapView` or capture StreetCross. The default style is a reduced dark vector JSON in NavFrame assets, using OpenFreeMap tile/vector sources and glyphs. An HTTPS URL setting can replace the remote style; attribution is configured alongside the URL. The MapLibre layer is reused and cancelled on stop/mode change. Snapshots are serial and limited to about 1 Hz moving and 0.5 Hz at rest to avoid a queue; Bluetooth send/ACK cadence is independent. According to the [MapSnapshotter API](https://maplibre.org/maplibre-native/android/api/-map-libre%20-native%20-android/org.maplibre.android.snapshotter/-map-snapshotter/index.html), the object is used on the UI thread, draws off-thread, calls back on the caller thread, and `cancel()` must be called from its creation thread. The implementation defers continuation resumption until the callback's internal reset finishes.
**Start demo map (simulated position)** places synthetic position on real cartography and displays `MAPA · POSICIÓN SIMULADA`, without invented turn/route instructions. **Start GPS map (no route)** uses granted GPS permission and centers on real fixes, displaying `MAPA GPS · SIN RUTA`. Earlier GPS-only and demo-only modes remain separate. This phase draws position on a map; it does not search destinations, calculate routes, geocode, or provide navigation instructions.
Remote styles request resources for the visible map area. This reveals the viewed area and network metadata to the configured source even though NavFrame does not store GPS history or log coordinates. OpenFreeMap states that it does not retain IPs in routine logs but may use a CDN and temporarily log IPs during incidents; see its [privacy policy](https://openfreemap.org/privacy/) and [terms](https://openfreemap.org/tos/). At the time this phase was implemented, offline use required an authorized source and later implementation; it did not download regions or promise offline coverage. Regional package downloads are now documented in [OFFLINE.md](OFFLINE.md) and [GLOBAL_OFFLINE.md](GLOBAL_OFFLINE.md). Do not substitute raster tiles from `tile.openstreetmap.org`; its separate rules prohibit preloading/offline use.
The footer retains `OpenFreeMap · © OpenMapTiles · © OpenStreetMap contributors`, including error/GPS-loss frames. For custom styles, check all attribution in MapLibre metadata and add provider-required credits; the configuration stores attribution with the URL. Credits must remain legible in the 480 × 240 footer and the phone license screen must link to terms. The SDK is BSD-2-Clause; NavFrame's TFT style does not copy Dark. See [MapLibre research](MAPLIBRE_RESEARCH.md) and [Licensing](LICENSING.md).
A connection/style error should show `MAPA NO DISPONIBLE` and remove speed/bearing figures that are no longer current; do not replace the real map with an illustrative road or fabricate a position. Snapshots are asynchronous: create, start, and cancel `MapSnapshotter` on Main; its callback runs on the caller thread, and restarting must wait for the SDK reset. Old/cancelled callbacks must not publish frames after STOP or a mode change.
## Phase limits
Phase 4 added map and position; phase 5 added an explicit route plan. Neither screen is suitable for riding guidance. Robolectric can check composition/overlay but does not run JNI/OpenGL or tiles on a device. Runtime Android and physical map/route tests on the TFT are required. Demo routes must never be confused with real routes. Later phases are in the [product brief](../yamaha_tft_native_navigator_codex.md).
## Phase 5: coordinate route plan without guidance
The screen offers origin **DEMO Oviedo · simulated** or **GPS real · last position**, destination latitude/longitude, and HTTPS `/route` endpoint. There is no geocoder. A GPS origin is accepted only when the provider is enabled and the fix is younger than 15 seconds. Calculation is user initiated and uses Valhalla `costing=motorcycle` (beta profile); the result identifies origin, distance, estimated duration, and maneuver count. Response geometry is retained to draw a line; it is not progress tracking or turn-by-turn navigation.
The polyline is shown as **PREVIEW** or **PLAN … no guidance**. The marker continues to show current GPS or demo position; movement does not mean NavFrame performs map matching, detects route adherence, measures turn distance, or dynamically calculates ETA. Switching ordinary sources clears the route/overlay; showing a plan explicitly selects the source appropriate to its origin. **Stop route · keep GPS/TFT** removes the plan and overlay without stopping GPS/map or transport by itself.
Coordinates are sent to the chosen endpoint only on explicit route calculation. The endpoint receives origin/destination and connection metadata; request body and coordinates are not written to local logs. The implementation limits requests to one per second and does not retry automatically. The public Valhalla/FOSSGIS server is for development/fair use, with no SLA. See [ROUTING.md](ROUTING.md) and [Licensing](LICENSING.md); review terms and data retention before changing endpoint.
This phase has no turn-by-turn, active progress, live turns, off-route detection, rerouting, voice, geocoding, or motorcycle road-safety verification. Do not ride using the line or route data. A successful synthetic service request does not validate user GPS origin, MapLibre rendering on the phone, or a route sent to the TFT. Those physical tests remain pending.
## Phase 6: guidance on an active route
**Start guidance for calculated route** activates the GPS tracker or DEMO simulation over route geometry. The HUD shows icon, distance to maneuver, remaining distance, and approximate ETA. NO GPS, OFF ROUTE, and RECALCULATING hide stale estimates. Arrival requires distinct position observations. The service retains continuous transport and stop controls.
Native composition is checked using `guidance.png` on a test base. This does not certify MapLibre GPU or physical navigation. See [testing](TESTING.md) and [thresholds and limitations](ROUTING.md).
+13
View File
@@ -0,0 +1,13 @@
# Voice directions
NavFrame supports spoken guidance templates and routing-language requests for Spanish, English, German, French, and Italian. Settings also offers the Android system language; unsupported system locales resolve to English. The selected route language controls maneuver text and voice templates. Route preview and demo mode are silent. Speech is owned by the navigation foreground service, so it does not depend on the activity remaining open. Android power-management policy may still stop or restrict background work.
In Settings, the voice toggle enables or mutes announcements, and the language selector chooses a route/voice language or the system language. **Configure Android voice** opens system TextToSpeech settings so a user can install or select voice data. NavFrame prefers an installed voice for the selected language that does not require a network connection when the Android engine exposes one. It does not download voice data automatically. Template/routing-language support does not guarantee that a matching Android voice is installed or that it works offline; availability depends on the engine and installed data, and a device may lack the locale or require a connection.
Each maneuver can be announced at approximately 300 m, 100 m, and 30 m. Starting near a turn announces only the current threshold. GPS jitter does not replay earlier thresholds. Arrival, off-route state, reroute, and inadequate GPS are announced once per route state. Muting consumes passed checkpoints, so enabling voice later does not replay old directions.
Speech requests Android's navigation-guidance audio usage and transient audio focus, allowing other audio to duck. The output follows Android's selected audio route, including a compatible Bluetooth intercom; NavFrame does not force a Yamaha TFT audio route or Bluetooth SCO connection. Camera alerts have a separate setting, respect mute, and do not interrupt an active maneuver announcement.
`VoiceGuidancePolicyTest` covers thresholds, GPS changes, route replacement, previews, and one-time events. These automated checks do not prove that sound is audible through a particular phone, helmet, intercom, or motorcycle. Physical validation of voice playback, audio mixing, intercom routing, and screen-off behavior remains pending.
References: [Android TextToSpeech API](https://developer.android.com/reference/android/speech/tts/TextToSpeech) and [audio focus](https://developer.android.com/media/optimize/audio-focus).
+25
View File
@@ -0,0 +1,25 @@
# Navigation voice languages
Settings offers Spanish (the existing default), English, German, French, Italian,
and a system-language option. Regional language variants map to the supported
Valhalla locale. An unsupported system language uses English consistently for
routing instructions, speech templates and Android TTS.
The preference applies to newly calculated routes. An active route retains the
language of its server-provided maneuver text until it is replaced, so existing
instructions are not spoken with a newly selected language's voice. Status
announcements and optional speed-camera speech use that route's language too.
Android's configured TTS engine must provide the selected language. NavFrame
prefers an installed voice that works offline and reports whether the selected
voice needs Internet. If language data is missing or unsupported, speech is
unavailable; install voice data using the Android voice settings button. Map
rendering and navigation remain available. Valhalla routing itself still needs
Internet.
Tests cover preserved Spanish defaults, locale mapping, English checkpoints,
localized alerts, selected request language, and system-language fallback.
API references: [Valhalla locale files](https://github.com/valhalla/valhalla/tree/master/locales),
[Android TextToSpeech](https://developer.android.com/reference/android/speech/tts/TextToSpeech),
and [Android Voice](https://developer.android.com/reference/android/speech/tts/Voice).