Files
NavFrame/docs/ROUTING.md
T

70 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Routing and guidance
Route calculation uses a configurable HTTPS Valhalla-compatible service. The default FOSSGIS endpoint is a public demo with fair-use/rate limits, not a production SLA. Valhalla asks applications published to end users to notify the project and include an identifying `X-Client-Id`; see the [official Valhalla documentation](https://valhalla.github.io/valhalla/). A route request sends the selected origin and destination to the configured service. Do not submit sensitive coordinates to a public endpoint.
NavFrame does not contain an offline routing graph. It can follow previously calculated route geometry with GPS, but calculating or recalculating a route requires network access. The `motorcycle` profile does not certify legal access, surface quality, or motorcycle suitability. ETA and GPS-based turn progression are estimates and require physical validation.
## Implementation contract
Research and contract dated 2026-09-29. NavFrame requests a route after explicit destination selection or Calculate, using a usable DEMO/GPS origin. Preview precedes guidance; these actions do not automatically replace an active route. GPS guidance may request recalculation after sustained deviation or a manual action. The Android service and UI own requests, cancellation, and preview. Phase 5 introduced preview; phase 6 adds basic pure guidance, route simulation, and a conservative deviation/recalculation policy. That phase does not include address search, voice, or advanced road map matching.
## Initial service and privacy
Initial configurable endpoint: `https://valhalla1.openstreetmap.de/route`, the FOSSGIS public demo; `valhalla.openstreetmap.de` is the frontend rather than the chosen API endpoint. The [official Valhalla README](https://github.com/valhalla/valhalla) documents the service and requires reasonable use; it asks applications published to users to identify themselves with `X-Client-Id` and notify its Discussions. No third parties have been contacted, and the app has not been published as a service for external users. Resolve that requirement or use a self-hosted server before public distribution.
The [official OpenAPI](https://github.com/valhalla/valhalla/blob/master/docs/docs/api/openapi.yaml) documents HTTP429 and a per-user limit of **one request per second**. The adapter must serialize requests, wait at least that interval, send an identifying User-Agent and `X-Client-Id`, and show errors. Phase 6 recalculation adds a minimum 30-second cooldown, one request in flight, and a pause after HTTP429; it does not create a continuous retry loop. The demo offers no availability guarantee; replacing it with a custom endpoint must not require changing rendering/transport.
Calculation sends origin/destination and options to the server, alongside IP and client identifier. Do not log JSON or coordinates. The [FOSSGIS routing policy](https://routing.openstreetmap.de/about.html) describes logging and OSM attribution for its OSRM service; Valhalla refers to that fair-use criterion, but identical retention across both implementations is not asserted. The full German terms page returned Anubis protection during research; it was not bypassed.
## Requests and profiles
`buildValhallaRequest(origin, destination, options)` generates POST JSON with two locations using `type=break`, `costing=motorcycle`, `shape_format=polyline6`, `units=kilometers`, language from the selected route language (`es-ES` by default), and `directions_type=instructions`. Valhalla marks `motorcycle` as beta. FASTEST means routing based on the model's time and costs; it does not certify a mathematical minimum, legal road access, or each segment's suitability for the MT-07.
Phase 0.8 adds combinable preferences in `RouteOptions(profile, avoidMotorways, avoidUnpaved, avoidTolls)`. Presets combine with explicit flags; changing a preference does not switch costing to auto:
| Profile/option | Motorcycle request | Meaning |
|---|---|---|
| FASTEST / Fast motorcycle | use_highways=0.5, use_tolls=0.5, use_trails=0.5 | Neutral preference; motorways and tolls allowed |
| AVOID_MOTORWAYS / Avoid motorways | use_highways=0 | Penalizes motorways; not an absolute prohibition |
| AVOID_UNPAVED / Prefer paved roads | use_trails=0 | Penalizes poor surfaces and trails; no pavement certification |
| TOURING | use_highways=0.2, use_tolls=0 | Reduces motorways and tolls; no scenic-route guarantee |
| avoidTolls | use_tolls=0 | Toll-avoidance preference, combinable with the above |
`use_tracks=0` retains a track penalty in all profiles. The paved-road preference has an effect: it reduces `use_trails` from the neutral 0.5 to 0.0; earlier phases fixed it at 0.0. No selection permits ignoring restrictions, access, or one-way roads.
The [official motorcycle/exclusion documentation](https://valhalla.github.io/valhalla/api/route/api-reference/#motorcycle-costing-options-beta) describes soft costs and experimental exclusions. [MotorcycleCost](https://github.com/valhalla/valhalla/blob/master/src/sif/motorcyclecost.cc), [DynamicCost](https://github.com/valhalla/valhalla/blob/master/valhalla/sif/dynamiccost.h), and [AutoCost](https://github.com/valhalla/valhalla/blob/master/src/sif/autocost.cc) were also checked on 2026-09-29: motorcycle reads base options, but Allowed/AllowedReverse do not apply `exclude_unpaved`; AutoCost does. Therefore that flag is not sent as a motorcycle guarantee. `exclude_highways`/`exclude_tolls` depend on `service_limits.allow_hard_exclusions`; the server may ignore them with a warning. `exclude_highways=true` was removed from the old preset to avoid that false expectation. There is no silent fallback to auto or another profile.
`RouteResult.hasUnpaved` is optional evidence, not independent validation: it derives from the boolean `maneuver.rough` emitted by the [official serializer](https://github.com/valhalla/valhalla/blob/master/src/tyr/route_serializer_valhalla.cc) when `portions_unpaved` is true. `true` permits a warning that the result includes unpaved sections despite the preference. Missing fields mean `null`, never “verified paved” through absence. Only a response with complete explicit information and all values false produces false; the usual backend omits rough=false. No summary.has_unpaved field is invented.
Android retains the options used with the route so recalculations preserve the profile. Changing controls prepares future requests and does not retroactively transform an active route. Serialization tests cover independent/combined preferences, motorcycle costing, and absence of unverified exclusions; metadata tests distinguish absence, positive evidence, and invalid booleans. No HTTP smoke test for every new combination or physical preference test has been performed.
## Pure JVM result
`parseValhallaRoute(json, destination=null)` returns `RouteResult`. It preserves the requested destination separately from the road-snapped endpoint, geometry, total length, and duration. `Maneuver` preserves instruction, type, begin/endShapeIndex, duration, road names, and **its segment's length**. That length is not the rider's current distance to the next turn.
The parser accepts strict JSON, successful status, and explicit kilometre/mile units; it converts to metres and rounded integer seconds. It decodes polyline6, validates geographic ranges, finite/nonnegative measurements, and index bounds. It joins legs at their shared point and rebases indices onto the final geometry. It rejects disconnected legs, responses over 2 Mi characters, geometries over 100,000 points, or more than 128 legs. The HTTP adapter must also limit received bytes before constructing the String. Local error messages include neither remote bodies nor coordinates.
JSON uses Gson 2.11.0 with `Strictness.STRICT`, documented in its [official release](https://github.com/google/gson/releases/tag/gson-parent-2.11.0). The adapter and decoder are original project code; no Valhalla engine code is embedded. Gson uses [Apache 2.0](https://github.com/google/gson/blob/gson-parent-2.11.0/LICENSE); Valhalla uses [MIT](https://github.com/valhalla/valhalla/blob/master/COPYING). Maps/routes must retain [© OpenStreetMap contributors](https://www.openstreetmap.org/copyright).
## Verification
`ValhallaRouteTest` uses an original realistically structured fixture, not user GPS recordings or an invented response presented as a real route. It covers an independent polyline6 vector, kilometres/miles, zero-length arrival maneuvers, leg joining/indices, non-strict JSON, backend errors, overflow, out-of-range coordinates, truncated shapes, and request options. Tests do not certify public availability, motorcycle restrictions, geocoding, or turn guidance.
Authorized HTTP smoke test: one synthetic demonstration POST in Asturias (43.36,-5.85 → 43.365,-5.845), without user coordinates, with an identifying User-Agent and X-Client-Id, returned HTTP200/status0 on 2026-09-29. Motorcycle, units kilometers, and language es-ES were accepted; the response contained one leg and ten Spanish maneuvers, including a zero-length arrival. This validates that query's contract, not continuous availability or road restrictions. HTTP checks and native Android rendering must be reported separately from the JVM parser. Phase 5 preview and phase 6 basic guidance are verified separately; thresholds are not calibrated through a physical road test. Physical TFT testing depends on the user's availability.
## Basic guidance and limits — phase 6
`RouteGuidanceTracker(route).update(fix, nowMs, epochMs, fixAgeMs)` separates monotonic time, wall-clock time for ETA, and actual fix age. The caller must pass age from the provider and never assume a new tick means a new fix. Age up to 15 seconds and finite horizontal accuracy from 0 to 25 m are accepted. An unusable fix produces GPS_LOST without turn/countdown/ETA and breaks deviation/arrival evidence. The fix timestamp identifies distinct observations; repeated ticks do not advance state or confirm thresholds. An observation gap over 15 seconds also breaks evidence. Recovery after GPS_LOST or that gap requires two new fixes: the first establishes a baseline without progress, and the second stable fix allows reacquisition; absence does not enlarge the movement window.
First acquisition uses the nearest valid projection over the entire route. Subsequent candidates are restricted to a local speed/time-dependent window, with 20 m backward tolerance and accumulated progress that does not retreat due to jitter. Distance to that candidate is checked before advancing. Position jumps incompatible with observed movement temporarily produce GPS_LOST; a later stable fix restores evaluation. These filters do not replace map matching: crossings, parallel branches, bridges, wrong-way travel, and prolonged GPS loss remain ambiguous. An isolated jump still temporarily produces GPS_LOST. If later fixes are stable but outside the reachable section, progress freezes and sustained evidence confirms OFF_ROUTE, allowing automatic recalculation; that deviation is not presented as GPS loss. Candidates are clipped to local-window endpoints to avoid artificial gaps near its boundaries. Do not infer a different road merely because other geometry is nearby.
The next turn uses geometric distance to `beginShapeIndex` and advances after passing it by more than 5 m. Official types 1/2/3 are Start/StartRight/StartLeft, departure instructions omitted from the next turn; regular Right/Left turns are 10/15. `maneuverDirection(type)` selects an icon without parsing translations. Arrival requires a road-snapped endpoint within 25 m, geometric remaining distance within 30 m, three distinct fixes, and at least two seconds; it then remains confirmed until the tracker is replaced. The [official maneuver types](https://valhalla.github.io/valhalla/api/route/api-reference/#trip-legs-and-maneuvers) support these IDs.
Deviation means distance from the geometrically reachable section based on previous progress greater than `max(40m, 2 × accuracy)` for at least five seconds and three distinct fixes. This includes reversing along the same road or reaching a distant later section even when near another part of the route. Recovery breaks the sequence. Turn estimates are hidden while position exceeds the threshold; OFF_ROUTE confirms the state after that evidence. OFF_ROUTE retains the route for the map but shows neither countdown nor ETA calculated as though still following it. All thresholds are configurable and await real-world calibration.
Remaining distance is pending geometric length. Real ETA is **approximate**: initial Valhalla duration multiplied by the remaining geometric fraction; it does not account for traffic, stops, or future speed. `RouteDemo(route).stateAt(elapsedMs, epochMs)` interpolates positions at 12 m/s and produces complete deterministic guidance up to ARRIVED; its ETA uses that speed. Android must continuously display DEMO and never use it to trigger HTTP recalculation.
`ReroutePolicy` separates decision from IO: `shouldRequest`, `markRequested` before launching, and `markFinished` in finally, including errors/cancellation. An active request blocks another; cooldown after completion is at least 30 seconds and may extend with Retry-After. `reset` is only for a new session/manual action. Android additionally applies failure limits and HTTP429 blocking; route replacement must be atomic and retain the previous route on failure.
`RouteGuidanceTest` covers projection/countdown/ETA, jitter/passed turns, intermediate acquisition, duplicate ticks/time gaps, three deviation/arrival observations, accuracy margins, invalid/stale fixes, jumps/return, geometry crossings, the antimeridian, single-flight/cooldown/Retry-After, and demo interpolation. `TftServiceRerouteTest` simulates Android GPS while reversing along the previous road and verifies one request from the current position with the same profile, one request in flight, and guidance recovery with the received route. These tests do not certify physical guidance or OSM data quality.