Skip to content

RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.

Release 2.20.0: turn-by-turn navigation, alert cards on the map, route-aware Waze alerts, no-Vulkan phone fix

CIS-C05a89e728d99c
diff --git a/README.md b/README.md
index d28eb62..16766b2 100644
--- a/README.md
+++ b/README.md
@@ -93,7 +93,7 @@
| **Camera glasses** | Ray-Ban / Oakley Meta, Snap Spectacles, Vuzix, HeyCyan-based glasses such as Nilox Smart AI Glasses | Company IDs `0x0D53`, `0x03C2`, `0x060C`, Meta UUIDs, the HeyCyan SDK UUID, name tokens |
| **Fake cell towers** | IMSI catchers / cell-site simulators | Test network codes, sudden 4G→2G, cloned or reserved cell identities, unexpected networks |
| **Police aircraft** *(online, off by default)* | Police, sheriff, state patrol, federal and RCMP / provincial police aircraft, and unlisted aircraft circling low overhead | Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries |
-| **Waze reports** *(online, off by default)* | Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), each with its own level: sound and voice, notification only, or silent. Shows what Waze says it is (hiding, mobile speed camera...) | Two sources: your own OpenWeb Ninja API key, or *Waze direct* (opt-in: no key, free, sends Waze your IP address and a position rounded to a 1 km grid). You set the alert range (100 m to 10 km), the map range, and how often Waze is asked (15 s to 5 min direct, 2 to 10 min OpenWeb Ninja), slower when parked and faster on fast roads. Scored by distance, age and driver confirmations and re-scored every second as you move, so an alert fires the moment a report comes into range, not at the next check. Optional: only alert for reports on the road you're on, ahead of you (checked against the map's roads: a parallel road, a cross street, an overpass or a report behind you stays quiet), and spoken call-outs at 1 km, 500 m and 200 m. Third-party service, at your own risk |
+| **Waze reports** *(online, off by default)* | Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), each with its own level: sound and voice, notification only, or silent. Shows what Waze says it is (hiding, mobile speed camera...) | Two sources: your own OpenWeb Ninja API key, or *Waze direct* (opt-in: no key, free, sends Waze your IP address and a position rounded to a 1 km grid). You set the alert range (100 m to 10 km), the map range, and how often Waze is asked (15 s to 5 min direct, 2 to 10 min OpenWeb Ninja), slower when parked and faster on fast roads. Scored by distance, age and driver confirmations and re-scored every second as you move, so an alert fires the moment a report comes into range, not at the next check. Optional: only alert for reports on the road you're on, ahead of you (checked against the map's roads: a parallel road, a cross street, an overpass or a report behind you stays quiet; while you are guided to a destination the route decides: only reports on the part still ahead of you count, corners included; the ones that aren't on your way are left off the list unless you turn that off, and stay on the map), and spoken call-outs at 1 km, 500 m and 200 m. Third-party service, at your own risk |
| **Card skimmers** | Bluetooth modules inside gas-pump and ATM skimmers | HC-05 / HC-06 / HC-03 / RN42 / BT04-A names, serial-port service |
| **Hacking tools** *(off by default)* | Flipper Zero, Pwnagotchi, WiFi Pineapple, ESP deauthers, evil twin WiFi networks, Bluetooth spam floods, **WiFi deauth attacks** | Flipper UUIDs / company ID `0x0E29` / IEEE block, Pwnagotchi beacon JSON, default SSIDs, same network name from two makers with mismatched security, bursts of new pairing pop-ups; with a USB WiFi adapter, floods of unprotected deauthentication frames knocking devices off a network |
| **Emergency vehicles (V2X, Europe)** | Police, fire, ambulance and safety cars that broadcast European car-to-car radio (ITS-G5) | Needs an ESP32-C5 with the [V2X2MAP](https://github.com/pit711/V2X2MAP) firmware: the vehicle's own role, light bar and siren state and position (CAM), and its "emergency vehicle approaching" warnings (DENM). Ordinary cars are counted, not listed. Not in North America, which uses C-V2X |
@@ -134,6 +134,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- **Voice loudness** boost up to +15 dB (without distorting) for when music drowns the voice, in the car too, and an option to **pause music** while an alert is spoken
- Discreet mode, adjustable alert threshold, mute from the app or the car
- **Floating threat bubble** over Waze, Google Maps or any app, with a pop-up card saying what was just detected
+- **Alert card on the full screen map:** each alert (a flagged device, a known camera, a Waze report, a cell warning) pops up as a card under the turn banner - what it is, how far, how sure, "on your route" when it is - and goes by itself after a few seconds (longer for a strong match or something following you) or when dismissed; tap it to look at the place. Silent, honours Discreet mode and the alert snooze
- **Floating mini map** over other apps: the devices and known cameras around you, like the app's map (pinch to zoom, drag, resize)
- Android Auto alert cards say what it is, how sure, about how far and how many more are flagged ("BODY CAM · strong · ~40 m · near (-58 dBm) · +2 more flagged")
- Notification, Quick Settings tile and home-screen widget
@@ -289,6 +290,48 @@ the raw advertisement.
phone (never sent automatically); it offers to send it next time, or Settings →
*Lists, tools & about* → *Export crash log*.
+### Navigation
+
+Turn-by-turn directions on the map, with your scanner running alongside.
+
+- **Where to?** The magnifier button on the map searches places and addresses as you type: your own
+ places that fit show first, results say what kind of place they are ("Park · Munich"), the best name match
+ comes before one that merely mentions the words, and a pair of coordinates works too. Pressing the keyboard's
+ search key (or the *Search for* row) looks in more places at once. Empty, it lists **Home**, **Work**, starred and recent places (all kept on the phone) and kinds of
+ place to look for - petrol, charging, food, parking, shops, pharmacy, hospital, cash, toilets, rest stops -
+ **near you**, and **along your route** while you are guided (a stop to add, in the order you reach them).
+ A **long press** on the map drops a pin: it names what's there, offers *Directions*, and can be starred.
+- **Routes:** up to three, each with its time and the main roads it takes, drawn on the map.
+ *Avoid tolls / highways / ferries* ticked while you plan (or on the trip menu) is remembered for the next
+ destination, and is the same setting as Settings → *Navigation*.
+ **Start** begins guidance - and the scan too, unless you turn that off (Settings → *Navigation*);
+ a scan already running is left as it is, and it keeps going after you arrive.
+- **Guidance:** a banner with the next turn, its distance and street, the **lane arrows** where the map
+ has them, and the turn after it when it follows closely; an arrival bar with your arrival
+ time, time and distance left; *whole route* view; mute; *add a stop*. It follows your north-up /
+ heading-up / 3D choice, zooms in as a turn comes up, keeps the screen on, and carries on with the
+ screen off (a notification shows the next turn). Roundabouts name the exit ("2nd exit"). On the main
+ screen's small map pane there is a slim one-line banner; tap it for the full screen map.
+- **Arrival time** starts from the route's usual driving time and then follows how you really drive
+ (stops at lights, a slow road), so it is closer than a fixed figure without any traffic service.
+- **Night map:** after sunset, worked out on the phone from your position and the time, the map turns to its
+ night look while you are guided (Settings → *Navigation*; the sun / moon button keeps the look you choose).
+- **Spoken directions** ("In 500 meters, keep right", then "Keep right") come as navigation audio, so music
+ dips under them as in Maps, in the voice, speed and loudness chosen under Alerts. A "something is following you"
+ alert cuts in on a direction; the last prompt before a turn cuts in on other alerts; otherwise they take turns.
+ Miles or kilometres by your region, or your choice.
+- **Re-routes** by itself when you leave the route or turn round, and ends when you arrive. *Open in...*
+ hands the destination to Google Maps, Waze or any map app.
+- Not included: live traffic (the arrival time is the route's usual driving time), speed limits and offline routes.
+- Routes come from [Valhalla](https://valhalla.github.io/valhalla/) on the OpenStreetMap Germany server and
+ places from [Photon](https://photon.komoot.io) as you type, and from OpenStreetMap's own
+ [Nominatim](https://nominatim.org) as well when you submit a search (the keyboard's search key, or the
+ *Search for* row) - whichever answers first is shown at once. They see what you search for, where you start,
+ stop and finish, and your IP address - never what you scan - and only when you search, long-press the map
+ or start a route. Search sends your position rounded to about 1 km. Looking for petrol, food and the like asks OpenStreetMap's
+ Overpass servers (the same ones as the camera downloads) for that kind of place around you - your position
+ rounded to about 1 km, or the road ahead as points rounded to about 200 m.
+
### Export
Menu → **Export...** (or Settings → Data → Export all devices):
@@ -345,9 +388,9 @@ A driver-safe, template-based Android Auto app:
devices, known plate / speed / red-light cameras and your position. Drag,
pinch or **+ / −**; **◎** follows the car again. Needs car API level 7; older
Android Auto gets car-drawn maps with device and camera lists.
-- **Navigation:** *Navigate to...* searches with [Nominatim](https://nominatim.org)
- (on submit only), keeps recent destinations on the phone, routes with
- [OSRM](https://project-osrm.org), speaks turns and re-routes.
+- **Navigation:** *Navigate to...* searches with [Photon](https://photon.komoot.io) and
+ [Nominatim](https://nominatim.org) (on submit only), starts from Home, Work, starred and recent places kept on the phone,
+ routes with [Valhalla](https://valhalla.github.io/valhalla/), speaks turns and re-routes.
- **Alerts** appear as heads-up cards with **Mute 30 min** and **Ignore**
buttons, and play through the car speakers as navigation audio, briefly
lowering your music.
@@ -563,8 +606,10 @@ Pick a theme in the setup wizard or under **Settings → Appearance**.
overpass.kumi.systems and overpass.private.coffee). Camera downloads also
fetch DeFlock's region files from cdn.deflock.me. These servers see your IP
address and the area, never your scans. Turn off *Show known cameras
- automatically* to fetch only when you tap a download. In Android Auto,
- navigation uses Nominatim and OSRM only when you search or start a route.
+ automatically* to fetch only when you tap a download. Navigation, on the phone
+ or in Android Auto, uses Photon and Nominatim (place search) and Valhalla (routes) only when you
+ search, long-press the map or start a route; they see the search, your start and
+ destination, and your IP address.
Map data © OpenStreetMap contributors (ODbL), © OpenMapTiles, © Mapbox when chosen.
- **Two optional online sources, off by default:** *Police / government
aircraft* sends a position rounded to about 1 km to the community ADS-B
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index d24b98d..d510373 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -7,8 +7,8 @@ plugins {
}
// Bump both for every release. versionName ends up in the APK file name.
-val appVersionCode = 43
-val appVersionName = "2.19.0"
+val appVersionCode = 44
+val appVersionName = "2.20.0"
// Release signing credentials live in keystore.properties (git-ignored).
// Without that file, release builds are produced unsigned.
@@ -119,8 +119,10 @@ dependencies {
// OpenStreetMap map view (Apache-2.0, no API key). Tiles are the only network use.
implementation("org.osmdroid:osmdroid-android:6.1.20")
- // Preview of the new map engine (3D driving view): vector maps with a real 3D camera.
- implementation("org.maplibre.gl:android-sdk:13.6.1")
+ // The map engine (3D driving view): vector maps with a real 3D camera. The Vulkan + OpenGL build picks Vulkan only
+ // where the phone has it and OpenGL ES everywhere else (the plain build is Vulkan-only and crashes the app on phones
+ // without Vulkan, e.g. Android 9 phones with a PowerVR GE8320).
+ implementation("org.maplibre.gl:android-sdk-vulkan-opengl:13.6.1")
// Optional Mapbox map (Settings > Map > Map provider); needs MAPBOX_ACCESS_TOKEN in local.properties.
implementation("com.mapbox.maps:android-ndk27:11.32.0")
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 2bb6611..15c80a6 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -86,6 +86,10 @@
android:name=".ui.MapActivity"
android:exported="false"
android:parentActivityName=".MainActivity" />
+ <activity
+ android:name=".nav.NavSearchActivity"
+ android:exported="false"
+ android:windowSoftInputMode="stateVisible|adjustResize" />
<activity
android:name=".ui.TripsActivity"
android:exported="false"
@@ -146,6 +150,12 @@
android:exported="false"
android:foregroundServiceType="connectedDevice|location" />
+ <!-- Turn-by-turn guidance: keeps the GPS running with the screen off while a route is followed. -->
+ <service
+ android:name=".nav.NavigationService"
+ android:exported="false"
+ android:foregroundServiceType="location" />
+
<service
android:name=".service.ScanTileService"
android:exported="true"
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 35cabaa..c8ea982 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -119,7 +119,10 @@ class MainActivity : AppCompatActivity() {
// crossfade would make the whole list flicker and fight the match flash.
(binding.recyclerView.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
binding.radarView.onBlipClick = { DeviceActions.openDetails(this, it) }
+ // The app closed while the map was starting last time: switch it to OpenGL, or leave it off the main screen (and say so).
+ val mapRecovery = com.rfsentinel.app.ui.MapSafety.recover(this)
panes = com.rfsentinel.app.ui.MainPanes(this, binding)
+ if (mapRecovery != com.rfsentinel.app.ui.MapSafety.Recovery.NONE) binding.root.post { if (!isFinishing && !isDestroyed) com.rfsentinel.app.ui.MapSafetyUi.tell(this, mapRecovery) }
binding.startStopButton.addOnLayoutChangeListener { _, l, _, r, _, ol, _, or, _ -> if (r - l != or - ol) fitStartButton() }
binding.startStopButton.setOnClickListener {
@@ -181,6 +184,10 @@ class MainActivity : AppCompatActivity() {
com.rfsentinel.app.ui.DemoData.seedAlerts(this@MainActivity, anchor)
anchor?.let { com.rfsentinel.app.ui.DemoData.seedHistory(this@MainActivity, it) }
}
+ // --ez demo_alert true: a made-up alert every 12 s, for the alert card on the full screen map.
+ if (intent.getBooleanExtra("demo_alert", false)) lifecycleScope.launch {
+ while (true) { kotlinx.coroutines.delay(12_000L); com.rfsentinel.app.ui.DemoData.publishSampleAlert(com.rfsentinel.app.ui.DemoData.fakeLocation?.let { it.latitude to it.longitude }) }
+ }
}
applyViewMode()
observeDevices()
@@ -316,26 +323,39 @@ class MainActivity : AppCompatActivity() {
}
/**
- * Start / Stop with its icon when both fit; with large text the icon goes first, then the
- * word (the colour and the icon still tell them apart), so the label is never cut off.
+ * "Start" / "Stop" with its icon when both fit; with less room the icon goes and the word stays. When
+ * even the word would be cut off (large text, a narrow window, the view buttons beside it) the word goes
+ * and the icon stays on its own: a play triangle to start, a stop square to stop (the colour and the
+ * description say the same), centred in the button with no side padding so the icon is never clipped.
*/
private var startIconPadding = -1
+ private var startPadStart = 0
+ private var startPadEnd = 0
+ private var startMinWidth = 0
private fun fitStartButton() {
val b = binding.startStopButton
+ val d = resources.displayMetrics.density
val running = shownRunning == true
val label = if (running) "Stop" else "Start"
val icon = if (running) R.drawable.ic_car_stop else R.drawable.ic_car_play
- if (b.width == 0) { b.text = label; b.setIconResource(icon); return }
- val room = b.width - b.paddingStart - b.paddingEnd
+ if (startIconPadding < 0) { // the button as the layout made it
+ startIconPadding = b.iconPadding; startPadStart = b.paddingStart; startPadEnd = b.paddingEnd; startMinWidth = b.minWidth
+ }
+ fun withWord() {
+ b.text = label; b.setIconResource(icon); b.iconPadding = startIconPadding
+ b.setPaddingRelative(startPadStart, b.paddingTop, startPadEnd, b.paddingBottom); b.minWidth = startMinWidth
+ }
+ if (b.width == 0) { withWord(); return }
+ val room = b.width - startPadStart - startPadEnd
val drawn = b.transformationMethod?.getTransformation(label, b)?.toString() ?: label
- val textW = b.paint.measureText(drawn) + 2 * resources.displayMetrics.density
- if (startIconPadding < 0) startIconPadding = b.iconPadding
- val iconW = (b.iconSize.takeIf { it > 0 } ?: (24 * resources.displayMetrics.density).toInt()) + startIconPadding
- when {
- textW + iconW <= room -> { b.text = label; b.setIconResource(icon); b.iconPadding = startIconPadding }
- textW <= room -> { b.text = label; b.icon = null }
- else -> { b.text = ""; b.setIconResource(icon); b.iconPadding = 0 }
+ val textW = b.paint.measureText(drawn) + 2 * d
+ val iconW = (b.iconSize.takeIf { it > 0 } ?: (24 * d).toInt()) + startIconPadding
+ if (textW + iconW <= room) withWord()
+ else if (textW <= room) { withWord(); b.icon = null }
+ else {
+ b.text = ""; b.setIconResource(icon); b.iconPadding = 0
+ b.setPaddingRelative(0, b.paddingTop, 0, b.paddingBottom); b.minWidth = (48 * d).toInt()
}
}
@@ -516,7 +536,8 @@ class MainActivity : AppCompatActivity() {
private fun currentWaze(now: Long): List<com.rfsentinel.app.online.WazePolice.Shown> {
if (!ScanForegroundService.isRunning) return emptyList()
val alertM = Prefs.wazeAlertM(this).toDouble()
- return com.rfsentinel.app.online.WazePolice.latest.filter { it.distanceM <= alertM }
+ return com.rfsentinel.app.online.WazePolice.forList(com.rfsentinel.app.online.WazePolice.latest, alertM,
+ Prefs.wazeAheadOnly(this), Prefs.wazeHideOffWay(this))
}
/**
@@ -528,16 +549,18 @@ class MainActivity : AppCompatActivity() {
if (filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.WAZE) return emptyList()
val aheadOnly = Prefs.wazeAheadOnly(this)
return currentWaze(now)
- .sortedBy { it.distanceM }
+ // With "only ahead" on, the ones on your way come first; the others stay listed, quiet, below them.
+ .sortedWith(compareBy<com.rfsentinel.app.online.WazePolice.Shown> { aheadOnly && !it.onMyWay }.thenBy { it.distanceM })
.filter { query.isBlank() || it.hit.label.contains(query.trim(), ignoreCase = true) }
.map { w ->
+ val off = aheadOnly && !w.onMyWay // behind you, another street, off your route
val urgent = w.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&
- w.hit.confidence >= threshold && !(aheadOnly && w.where.isBehind)
+ w.hit.confidence >= threshold && !off
val ago = w.report.publishedMs?.let { "${((now - it) / 60_000).coerceAtLeast(0)} min ago" } ?: "just now"
DeviceRow(
mac = WAZE_ROW + w.report.id,
title = w.hit.label,
- subtitle = com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend),
+ subtitle = com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend) + if (off) " · not on your way" else "",
meta = "Reported $ago" + listOfNotNull(w.report.street, w.report.city).joinToString(", ").takeIf { it.isNotEmpty() }?.let { " · $it" }.orEmpty() +
(if (w.report.thumbsUp > 0) " · ${w.report.thumbsUp} confirmed" else ""),
tag = "WAZE · ${w.hit.tier.label.lowercase()} ${w.hit.confidence}%",
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
index fa791c1..328b026 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
@@ -295,7 +295,7 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
private data class DeviceDot(val lat: Double, val lon: Double, val color: Int, val sizeDp: Int)
- private var drawnRoute: com.rfsentinel.app.nav.OsmRouting.Route? = null
+ private var drawnRoute: com.rfsentinel.app.nav.Route? = null
/** Swaps in a new route line when the route changes (osmdroid lines are rebuilt, not edited). */
private fun syncRoute(m: MapView) {
@@ -304,11 +304,11 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
drawnRoute = r
route?.let { m.overlays.remove(it) }
route = null
- if (r == null || r.points.size < 2) return
+ if (r == null || r.size < 2) return
route = Polyline(m).apply {
outlinePaint.color = 0xFF1A73E8.toInt()
outlinePaint.strokeWidth = 10f * m.context.resources.displayMetrics.density
- setPoints(r.points.map { GeoPoint(it.first, it.second) })
+ setPoints(r.points().map { GeoPoint(it.first, it.second) })
setInfoWindow(null)
}
m.overlays.add(0, route) // under the markers
diff --git a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
index 601a974..2bb0870 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
@@ -10,21 +10,20 @@ import androidx.car.app.model.Template
import androidx.lifecycle.lifecycleScope
import com.rfsentinel.app.BuildConfig
import com.rfsentinel.app.nav.Navigator
-import com.rfsentinel.app.nav.OsmRouting
+import com.rfsentinel.app.nav.PlaceRank
+import com.rfsentinel.app.nav.Place
+import com.rfsentinel.app.nav.Places
import com.rfsentinel.app.service.DeviceRegistry
import com.rfsentinel.app.util.Prefs
-import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
/**
- * Pick a destination: recent ones, or a search in OpenStreetMap (Nominatim),
- * sent only when you submit it - Nominatim's usage policy forbids
- * search-as-you-type, and it keeps requests to a minimum.
+ * Pick a destination: Home, Work, starred and recent ones, or a search in OpenStreetMap (Photon and
+ * Nominatim together), sent only when you submit it - a car keyboard is slow, and the screen redraws on every letter.
*/
class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen) : SafeScreen(carContext) {
- private var results: List<OsmRouting.Destination>? = null
+ private var results: List<Place>? = null
private var loading = false
private var query = ""
/** What's typed so far (searched only when submitted or tapped - no search-as-you-type). */
@@ -32,7 +31,7 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
override fun buildTemplate(): Template {
val list = ItemList.Builder()
- val shown = results ?: Prefs.recentDestinations(carContext)
+ val shown = results ?: savedPlaces()
val me = CarUi.currentLocation(carContext)
// Some cars' keyboards don't send "submit": offer the search as a row too.
if (typed.isNotBlank() && typed != query) {
@@ -42,7 +41,9 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
.setOnClickListener { search(typed) }
.build())
}
- shown.forEach { d ->
+ // The car shows a few rows at a time (and the "Search" row above takes one): the best matches come first.
+ val room = CarUi.listLimit(carContext) - if (typed.isNotBlank() && typed != query) 1 else 0
+ shown.take(room.coerceAtLeast(1)).forEach { d ->
val row = Row.Builder().setTitle(d.name)
// Short for a car screen (older saved entries may hold the full address).
val where = d.address.split(", ").filter { it.isNotBlank() }.take(2).joinToString(", ").ifBlank { "OpenStreetMap" }
@@ -68,7 +69,7 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
.setInitialSearchText(typed)
.setHeaderAction(Action.BACK)
.setSearchHint("Destination (searched in OpenStreetMap)")
- .setShowKeyboardByDefault(results == null && Prefs.recentDestinations(carContext).isEmpty())
+ .setShowKeyboardByDefault(results == null && savedPlaces().isEmpty())
.setLoading(loading)
.apply { if (!loading) setItemList(list.build()) }
.build()
@@ -78,28 +79,42 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
val q = text.trim()
if (q.isEmpty()) return
query = q
+ // "48.137, 11.575" is a place already.
+ PlaceRank.coordinates(q)?.let { results = listOf(it); invalidate(); return }
loading = true
invalidate()
val me = CarUi.currentLocation(carContext)
+ // Your own places that fit come first, then the answers: Photon and Nominatim are asked together
+ // (a submitted search, which is what Nominatim's rules allow) and the first to answer is on the
+ // screen at once.
+ val own = PlaceRank.mine(q, Prefs.navHome(carContext), Prefs.navWork(carContext), Prefs.navFavorites(carContext),
+ Prefs.recentDestinations(carContext), limit = 2)
lifecycleScope.launch {
val found = runCatching {
- withContext(Dispatchers.IO) {
- OsmRouting.search(q, me?.latitude, me?.longitude, "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")
+ Places.searchSubmitted(q, me?.latitude, me?.longitude, "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}",
+ graceMs = 4_000L) { list ->
+ results = own + list.filter { r -> own.none { it.lat == r.lat && it.lon == r.lon } }
+ loading = false
+ invalidate()
}
}
loading = false
- found.onSuccess { list ->
- // Closest first: in the car the nearby match is almost always the one meant.
- results = if (me == null) list else list.sortedBy { DeviceRegistry.metersBetween(me.latitude, me.longitude, it.lat, it.lon) }
- }.onFailure {
- results = emptyList()
+ found.onFailure {
+ if (it is kotlinx.coroutines.CancellationException) throw it
+ results = own
CarToast.makeText(carContext, "Search failed - no connection?", CarToast.LENGTH_LONG).show()
}
invalidate()
}
}
- private fun go(d: OsmRouting.Destination) {
+ /** Home and Work when set, then starred places, then recent ones (each place once). */
+ private fun savedPlaces(): List<Place> = (listOfNotNull(
+ Prefs.navHome(carContext)?.let { it.copy(name = "Home") }, Prefs.navWork(carContext)?.let { it.copy(name = "Work") }
+ ) + Prefs.navFavorites(carContext) + Prefs.recentDestinations(carContext))
+ .distinctBy { "%.4f,%.4f".format(java.util.Locale.US, it.lat, it.lon) }.take(10)
+
+ private fun go(d: Place) {
val from = CarUi.currentLocation(carContext)
if (from == null) {
CarToast.makeText(carContext, "Waiting for your location...", CarToast.LENGTH_SHORT).show(); return
@@ -107,9 +122,8 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
loading = true
invalidate()
lifecycleScope.launch {
- runCatching { Navigator.start(carContext, d, from) }
+ com.rfsentinel.app.nav.attempt { Navigator.start(carContext, d, from) }
.onSuccess {
- Prefs.addRecentDestination(carContext, d)
screenManager.pop()
map.onNavigationStarted()
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
index 13feae4..3e1cfc6 100644
--- a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
@@ -28,18 +28,19 @@ import java.util.Date
class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 3_000L, preciseLocation = true) {
private val renderer = CarMapRenderer(carContext, lifecycleScope)
+ private var removeNavListener: (() -> Unit)? = null
init {
renderer.onFollowingChanged = { invalidate() }
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
carContext.getCarService(AppManager::class.java).setSurfaceCallback(renderer)
- Navigator.onUpdate = { renderer.redraw(); invalidate() }
+ removeNavListener = Navigator.addListener { renderer.redraw(); invalidate() }
}
override fun onDestroy(owner: LifecycleOwner) {
carContext.getCarService(AppManager::class.java).setSurfaceCallback(null)
renderer.release()
- Navigator.onUpdate = null
+ removeNavListener?.invoke(); removeNavListener = null
}
})
}
@@ -51,9 +52,9 @@ class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =
}
override fun contentKey(): Any {
- val p = Navigator.progress
- return if (Navigator.active) listOf("nav", Navigator.status, p?.nextStep?.instruction,
- p?.toNextStepM?.let { (it / 10).toInt() }, p?.remainingM?.let { (it / 100).toInt() })
+ val s = Navigator.state
+ return if (Navigator.active) listOf("nav", Navigator.status, s?.stepIndex,
+ s?.toManeuverM?.let { (it / 10).toInt() }, s?.remainingM?.let { (it / 100).toInt() })
else listOf(ScanForegroundService.isRunning, renderer.counts(), renderer.following)
}
@@ -92,7 +93,7 @@ class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =
.build())
list.addItem(Row.Builder()
.setTitle("Navigate to...")
- .addText("Search a destination (OpenStreetMap)")
+ .addText("Search a destination (OpenStreetMap data)")
.setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
.setBrowsable(true)
.setOnClickListener { screenManager.push(DestinationScreen(carContext, this)) }
@@ -112,21 +113,23 @@ class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =
}
private fun guidanceRows(list: ItemList.Builder) {
- val p = Navigator.progress
- val step = p?.nextStep
+ val s = Navigator.state
+ val r = Navigator.route
+ // The banner's own wording for the coming turn ("Rue Principale"), else Valhalla's sentence for the next step.
+ val banner = if (r != null && s != null) com.rfsentinel.app.nav.Prompts.banner(r, s.stepIndex, s.toManeuverM) else null
+ val next = r?.steps?.getOrNull((s?.stepIndex ?: 0) + 1)
+ val turn = banner?.text?.takeIf { it.isNotBlank() } ?: next?.instruction?.removeSuffix(".")
list.addItem(Row.Builder()
- .setTitle(Navigator.status ?: step?.instruction ?: "Follow the route")
- .addText(if (p != null) "in ${NearbyMapScreen.distanceText(p.toNextStepM)}" else "Waiting for GPS...")
+ .setTitle(Navigator.status ?: turn ?: "Follow the route")
+ .addText(if (s != null) "in ${NearbyMapScreen.distanceText(s.toManeuverM)}" else "Waiting for GPS...")
.setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
.build())
- val r = Navigator.route
- if (p != null && r != null && r.distanceM > 0) {
- // Time left scales with distance left (the route's own average speed).
- val leftS = r.durationS * (p.remainingM / r.distanceM)
- val eta = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(System.currentTimeMillis() + (leftS * 1000).toLong()))
+ if (s != null) {
+ val left = Navigator.remainingS ?: s.remainingS
+ val eta = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(System.currentTimeMillis() + (left * 1000).toLong()))
list.addItem(Row.Builder()
.setTitle("Arrive $eta")
- .addText("${NearbyMapScreen.distanceText(p.remainingM)} · ${(leftS / 60).toInt().coerceAtLeast(1)} min")
+ .addText("${NearbyMapScreen.distanceText(s.remainingM)} · ${com.rfsentinel.app.nav.NavFormat.duration(left)}")
.build())
}
list.addItem(Row.Builder()
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Attempt.kt b/app/src/main/java/com/rfsentinel/app/nav/Attempt.kt
new file mode 100644
index 0000000..be4fd06
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Attempt.kt
@@ -0,0 +1,18 @@
+package com.rfsentinel.app.nav
+
+import kotlinx.coroutines.CancellationException
+
+/**
+ * Like [runCatching] for code that may suspend: a failure is returned, but a cancelled coroutine stays
+ * cancelled (the [CancellationException] is thrown on). With plain runCatching a request replaced by a
+ * newer one - or abandoned when its card was closed - would land in the failure branch and show a
+ * "no connection" message over the newer request's state.
+ */
+internal inline fun <T> attempt(block: () -> T): Result<T> =
+ try {
+ Result.success(block())
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ Result.failure(e)
+ }
diff --git a/app/src/main/java/com/rfsentinel/app/nav/HandOff.kt b/app/src/main/java/com/rfsentinel/app/nav/HandOff.kt
new file mode 100644
index 0000000..7fdaa37
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/HandOff.kt
@@ -0,0 +1,35 @@
+package com.rfsentinel.app.nav
+
+import android.content.ActivityNotFoundException
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.widget.Toast
+import java.util.Locale
+
+/** Opens a destination in another navigation app (Google Maps, Waze, or any app that takes a map link). */
+object HandOff {
+
+ const val GOOGLE_MAPS = "com.google.android.apps.maps"
+ const val WAZE = "com.waze"
+
+ fun googleMapsUri(lat: Double, lon: Double): String = String.format(Locale.US, "google.navigation:q=%.6f,%.6f&mode=d", lat, lon)
+ fun wazeUri(lat: Double, lon: Double): String = String.format(Locale.US, "waze://?ll=%.6f,%.6f&navigate=yes", lat, lon)
+ fun geoUri(lat: Double, lon: Double, name: String): String =
+ String.format(Locale.US, "geo:%.6f,%.6f?q=%.6f,%.6f(%s)", lat, lon, lat, lon,
+ java.net.URLEncoder.encode(name.ifBlank { "Destination" }, "UTF-8").replace("+", "%20"))
+
+ /** Opens [place] in the app named by [target] ("google", "waze" or anything else for the phone's choice). */
+ fun open(context: Context, place: Place, target: String) {
+ val intent = when (target) {
+ "google" -> Intent(Intent.ACTION_VIEW, Uri.parse(googleMapsUri(place.lat, place.lon))).setPackage(GOOGLE_MAPS)
+ "waze" -> Intent(Intent.ACTION_VIEW, Uri.parse(wazeUri(place.lat, place.lon))).setPackage(WAZE)
+ else -> Intent(Intent.ACTION_VIEW, Uri.parse(geoUri(place.lat, place.lon, place.name)))
+ }.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ try {
+ context.startActivity(intent)
+ } catch (e: ActivityNotFoundException) {
+ Toast.makeText(context, if (target == "google") "Google Maps isn't installed" else if (target == "waze") "Waze isn't installed" else "No map app found", Toast.LENGTH_LONG).show()
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/NavCamera.kt b/app/src/main/java/com/rfsentinel/app/nav/NavCamera.kt
new file mode 100644
index 0000000..0691c8e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/NavCamera.kt
@@ -0,0 +1,27 @@
+package com.rfsentinel.app.nav
+
+/** How the map camera helps while you are guided (pure; unit-tested). */
+object NavCamera {
+
+ /** The turn starts to matter this far out... */
+ private const val FROM_M = 350.0
+ /** ...and is as close up as it gets this near. */
+ private const val FULL_M = 60.0
+ /** The most the map zooms in for a turn (levels). */
+ const val MAX_BOOST = 0.9
+ /** Above this speed (km/h) the junction comes too fast to zoom for. */
+ private const val NO_BOOST_KMH = 90f
+ private const val FULL_BOOST_KMH = 50f
+
+ /**
+ * Extra zoom levels for a turn [toTurnM] ahead at [kmh]: none while it is far off, rising to
+ * [MAX_BOOST] as you reach it, so a junction fills the screen as in navigation apps. Less on fast
+ * roads (the turn is a ramp you see coming), none above 90 km/h.
+ */
+ fun turnBoost(toTurnM: Double, kmh: Float): Double {
+ if (toTurnM >= FROM_M || kmh >= NO_BOOST_KMH) return 0.0
+ val near = ((FROM_M - toTurnM) / (FROM_M - FULL_M)).coerceIn(0.0, 1.0)
+ val speed = if (kmh <= FULL_BOOST_KMH) 1.0 else 1.0 - (kmh - FULL_BOOST_KMH) / (NO_BOOST_KMH - FULL_BOOST_KMH)
+ return MAX_BOOST * near * speed
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt b/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt
new file mode 100644
index 0000000..23ec799
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt
@@ -0,0 +1,104 @@
+package com.rfsentinel.app.nav
+
+import android.content.Context
+import com.rfsentinel.app.util.Prefs
+import java.util.Locale
+
+/** Distances, times and icons as navigation shows them (pure apart from [miles]; unit-tested). */
+object NavFormat {
+
+ private const val M_PER_MILE = 1609.344
+ private const val FT_PER_M = 3.28084
+
+ /** Regions that drive by miles. */
+ private val MILE_REGIONS = setOf("US", "GB", "LR", "MM")
+
+ /** Whether guidance counts in miles: the Settings choice, or by the phone's region. */
+ fun miles(context: Context, locale: Locale = Locale.getDefault()): Boolean = when (Prefs.navUnits(context)) {
+ "mi" -> true
+ "km" -> false
+ else -> locale.country.uppercase(Locale.ROOT) in MILE_REGIONS
+ }
+
+ /** "300 m", "1.2 km"; "400 ft", "0.3 mi". Rounded the way a driver reads it. */
+ fun distance(meters: Double, miles: Boolean): String {
+ val m = meters.coerceAtLeast(0.0)
+ return if (!miles) when {
+ m < 100 -> "${(Math.round(m / 10.0) * 10).toInt()} m"
+ m < 1000 -> "${(Math.round(m / 50.0) * 50).toInt()} m"
+ m < 10_000 -> String.format(Locale.US, "%.1f km", m / 1000)
+ else -> "${Math.round(m / 1000.0)} km"
+ } else {
+ val ft = m * FT_PER_M
+ when {
+ ft < 1000 -> "${(Math.round(ft / 50.0) * 50).toInt().coerceAtLeast(0)} ft"
+ m < 10 * M_PER_MILE -> String.format(Locale.US, "%.1f mi", m / M_PER_MILE)
+ else -> "${Math.round(m / M_PER_MILE)} mi"
+ }
+ }
+ }
+
+ /** "18 min", "1 h 05 min". */
+ fun duration(seconds: Double): String {
+ val min = Math.round(seconds.coerceAtLeast(0.0) / 60.0).toInt().coerceAtLeast(1)
+ return if (min < 60) "$min min" else String.format(Locale.US, "%d h %02d min", min / 60, min % 60)
+ }
+
+ /** Your speed as the speedometer shows it. */
+ fun speed(metersPerSecond: Double, miles: Boolean): String =
+ if (miles) "${Math.round(metersPerSecond * 2.236936).toInt()} mph" else "${Math.round(metersPerSecond * 3.6).toInt()} km/h"
+
+ /** Which arrow stands for a manoeuvre (the screens map these to drawables). */
+ enum class Icon { STRAIGHT, LEFT, RIGHT, SLIGHT_LEFT, SLIGHT_RIGHT, SHARP_LEFT, SHARP_RIGHT, U_TURN_LEFT, U_TURN_RIGHT,
+ ROUNDABOUT, ROUNDABOUT_LEFT, MERGE, FORK_LEFT, FORK_RIGHT, RAMP_LEFT, RAMP_RIGHT, ARRIVE }
+
+ /** "1st", "2nd", "3rd", "4th", "11th", "21st"... for a roundabout exit. */
+ fun ordinal(n: Int): String {
+ val suffix = if (n % 100 in 11..13) "th" else when (n % 10) { 1 -> "st"; 2 -> "nd"; 3 -> "rd"; else -> "th" }
+ return "$n$suffix"
+ }
+
+ /**
+ * The arrow for an OSRM manoeuvre [type] and [modifier], on a road where they drive on [drivingSide]
+ * ("left" turns the roundabout the other way and puts a U-turn on the other side).
+ */
+ fun iconFor(type: String?, modifier: String?, drivingSide: String? = null): Icon {
+ val leftHand = drivingSide == "left"
+ val left = modifier?.contains("left") == true
+ val right = modifier?.contains("right") == true
+ return when (type) {
+ "arrive" -> Icon.ARRIVE
+ "roundabout", "rotary", "roundabout turn", "exit roundabout", "exit rotary" -> if (leftHand) Icon.ROUNDABOUT_LEFT else Icon.ROUNDABOUT
+ "merge" -> Icon.MERGE
+ "fork" -> if (left) Icon.FORK_LEFT else Icon.FORK_RIGHT
+ "on ramp", "off ramp" -> if (left) Icon.RAMP_LEFT else if (right) Icon.RAMP_RIGHT else Icon.STRAIGHT
+ else -> if (modifier == "uturn" && leftHand) Icon.U_TURN_RIGHT else byModifier(modifier)
+ }
+ }
+
+ private fun byModifier(modifier: String?): Icon = when (modifier) {
+ "left" -> Icon.LEFT
+ "right" -> Icon.RIGHT
+ "slight left" -> Icon.SLIGHT_LEFT
+ "slight right" -> Icon.SLIGHT_RIGHT
+ "sharp left" -> Icon.SHARP_LEFT
+ "sharp right" -> Icon.SHARP_RIGHT
+ "uturn" -> Icon.U_TURN_LEFT
+ else -> Icon.STRAIGHT
+ }
+
+ /** The arrow for one lane direction ("straight", "slight right"...). */
+ fun laneIcon(direction: String?): Icon = when (direction) {
+ "left" -> Icon.LEFT
+ "right" -> Icon.RIGHT
+ "slight left" -> Icon.SLIGHT_LEFT
+ "slight right" -> Icon.SLIGHT_RIGHT
+ "sharp left" -> Icon.SHARP_LEFT
+ "sharp right" -> Icon.SHARP_RIGHT
+ "uturn" -> Icon.U_TURN_LEFT
+ else -> Icon.STRAIGHT
+ }
+
+ /** The direction to draw for a lane: the one to take when it is the lane to be in, else its first. */
+ fun laneDirection(lane: Step.Lane): String? = if (lane.active) lane.activeDirection ?: lane.directions.firstOrNull() else lane.directions.firstOrNull()
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.kt b/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.kt
new file mode 100644
index 0000000..5ee2937
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/NavSearchActivity.kt
@@ -0,0 +1,411 @@
+package com.rfsentinel.app.nav
+
+import android.content.Context
+import android.content.Intent
+import android.location.Location
+import android.location.LocationManager
+import android.os.Bundle
+import android.text.Editable
+import android.text.TextWatcher
+import android.view.Gravity
+import android.view.View
+import android.view.inputmethod.EditorInfo
+import android.widget.EditText
+import android.widget.ImageButton
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.lifecycleScope
+import com.rfsentinel.app.BuildConfig
+import com.rfsentinel.app.R
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.service.ScanForegroundService
+import com.rfsentinel.app.ui.ChipStyle
+import com.rfsentinel.app.util.Permissions
+import com.rfsentinel.app.util.Prefs
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.Dispatchers
+
+/**
+ * Where to? A search with suggestions as you type, Home and Work, starred places and recent
+ * destinations. Returns the chosen [Place] to whoever opened it ([EXTRA_NAME] ... as the result).
+ *
+ * Your own places that fit what you type are there at once. Network use: what you type (after a short pause,
+ * from 3 characters) goes to Photon with your position rounded to about 1 km; a search you submit (the
+ * keyboard's search key, or the "Search for" row) also asks OpenStreetMap's Nominatim, and whichever answers
+ * first is shown while the other is merged in. Only while this screen is open; a newer search stops the
+ * older one's request.
+ */
+class NavSearchActivity : AppCompatActivity() {
+
+ companion object {
+ /** What the choice is for: "go" (a destination), "stop" (a stop on the way), "home" or "work" (save it there). */
+ const val EXTRA_MODE = "mode"
+ const val MODE_GO = "go"
+ const val MODE_STOP = "stop"
+ const val MODE_HOME = "home"
+ const val MODE_WORK = "work"
+ const val EXTRA_NAME = "name"
+ const val EXTRA_ADDRESS = "address"
+ const val EXTRA_LAT = "lat"
+ const val EXTRA_LON = "lon"
+ private const val DEBOUNCE_MS = 250L
+ /** Once one of the two servers has answered a submitted search, the other gets this long. */
+ private const val SUBMIT_GRACE_MS = 6_000L
+
+ fun intent(context: Context, mode: String = MODE_GO) =
+ Intent(context, NavSearchActivity::class.java).putExtra(EXTRA_MODE, mode)
+
+ /** The place a search result carries, or null. */
+ fun placeOf(data: Intent?): Place? {
+ val d = data ?: return null
+ if (!d.hasExtra(EXTRA_LAT) || !d.hasExtra(EXTRA_LON)) return null
+ return Place(d.getStringExtra(EXTRA_NAME).orEmpty(), d.getStringExtra(EXTRA_ADDRESS).orEmpty(),
+ d.getDoubleExtra(EXTRA_LAT, 0.0), d.getDoubleExtra(EXTRA_LON, 0.0))
+ }
+ }
+
+ private val mode get() = intent.getStringExtra(EXTRA_MODE) ?: MODE_GO
+ private lateinit var input: EditText
+ private lateinit var list: LinearLayout
+ private lateinit var note: TextView
+ private var searchJob: Job? = null
+ private var me: Location? = null
+ private val dp get() = resources.displayMetrics.density
+ private fun px(v: Int) = (v * dp).toInt()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ title = when (mode) {
+ MODE_STOP -> "Add a stop"; MODE_HOME -> "Set Home"; MODE_WORK -> "Set Work"; else -> "Where to?"
+ }
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ me = currentFix()
+ if (me == null) askForFix()
+
+ input = EditText(this).apply {
+ hint = when (mode) { MODE_HOME -> "Home address"; MODE_WORK -> "Work address"; else -> "Search a place or address" }
+ setSingleLine()
+ imeOptions = EditorInfo.IME_ACTION_SEARCH
+ inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
+ setPadding(px(14), px(12), px(14), px(12))
+ setOnEditorActionListener { _, id, _ -> if (id == EditorInfo.IME_ACTION_SEARCH) { search(text.toString(), submit = true); true } else false }
+ addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
+ override fun afterTextChanged(s: Editable?) = search(s?.toString().orEmpty(), submit = false)
+ })
+ }
+ note = TextView(this).apply { textSize = 13f; setPadding(px(16), px(8), px(16), px(8)); visibility = View.GONE }
+ list = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ val column = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(input, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
+ .apply { setMargins(px(12), px(8), px(12), px(4)) })
+ addView(note)
+ addView(ScrollView(this@NavSearchActivity).apply { isFillViewport = true; addView(list) },
+ LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
+ }
+ setContentView(column)
+ column.applySystemBarInsets()
+ showStart()
+ }
+
+ override fun onSupportNavigateUp(): Boolean { finish(); return true }
+
+ // ---- what to show ------------------------------------------------------------------------------
+
+ /** Nothing typed: Home and Work, starred places, recent destinations. */
+ private fun showStart() {
+ list.removeAllViews()
+ note.visibility = View.GONE
+ if (mode == MODE_GO || mode == MODE_STOP) {
+ val home = Prefs.navHome(this); val work = Prefs.navWork(this)
+ list.addView(row(R.drawable.ic_nav_home, "Home", home?.let { it.address.ifBlank { it.name } } ?: "Tap to set your home address",
+ home, star = false, onTap = { if (home != null) choose(home) else startActivityForResult(intent(this, MODE_HOME), REQ_HOME) },
+ onMore = { startActivityForResult(intent(this, MODE_HOME), REQ_HOME) }))
+ list.addView(row(R.drawable.ic_nav_work, "Work", work?.let { it.address.ifBlank { it.name } } ?: "Tap to set your work address",
+ work, star = false, onTap = { if (work != null) choose(work) else startActivityForResult(intent(this, MODE_WORK), REQ_WORK) },
+ onMore = { startActivityForResult(intent(this, MODE_WORK), REQ_WORK) }))
+ categories("Nearby") { categorySearch(it, along = false) }
+ if (Navigator.active && Navigator.state != null) categories("Along your route") { categorySearch(it, along = true) }
+ section("Starred", Prefs.navFavorites(this), R.drawable.ic_nav_star)
+ section("Recent", Prefs.recentDestinations(this), R.drawable.ic_nav_history)
+ }
+ if (list.childCount == 0) setNote("Type at least ${Places.MIN_QUERY} letters to search.")
+ }
+
+ private fun header(title: String) = list.addView(TextView(this).apply {
+ text = title; textSize = 12f; setTypeface(typeface, android.graphics.Typeface.BOLD)
+ setPadding(px(16), px(14), px(16), px(4)); alpha = 0.7f
+ })
+
+ private fun section(title: String, places: List<Place>, icon: Int) {
+ if (places.isEmpty()) return
+ header(title)
+ places.forEach { p -> list.addView(placeRow(p, icon)) }
+ }
+
+ /** A row of kinds of place to look for (petrol, food, charging...). */
+ private fun categories(title: String, onPick: (PlaceCategories.Category) -> Unit) {
+ header(title)
+ val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ for (c in PlaceCategories.Category.entries) {
+ row.addView(com.google.android.material.chip.Chip(this).apply {
+ text = c.label
+ setEnsureMinTouchTargetSize(false)
+ ChipStyle.apply(this)
+ setOnClickListener { onPick(c) }
+ }, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { marginEnd = px(6) })
+ }
+ list.addView(android.widget.HorizontalScrollView(this).apply {
+ isHorizontalScrollBarEnabled = false
+ setPadding(px(12), 0, px(12), 0)
+ addView(row)
+ })
+ }
+
+ /** Places of one kind near you, or ahead along the route you are following. */
+ private fun categorySearch(c: PlaceCategories.Category, along: Boolean) {
+ val route = Navigator.route
+ val from = Navigator.state?.alongM
+ if (along && (route == null || from == null)) return
+ searchJob?.cancel()
+ list.removeAllViews()
+ setNote(if (along) "Looking for ${c.label.lowercase()} along your route..." else "Looking for ${c.label.lowercase()} near you...")
+ searchJob = lifecycleScope.launch {
+ // Near you needs your position: give a fix just asked for a few seconds to arrive.
+ var waited = 0
+ while (!along && me == null && waited < 10_000) { delay(250); waited += 250 }
+ val here = me
+ if (!along && here == null) { setNote("Can't tell where you are yet - is location on?"); return@launch }
+ val found = attempt {
+ withContext(Dispatchers.IO) {
+ // The public servers are sometimes overloaded: after half a minute say so, rather than wait on.
+ kotlinx.coroutines.withTimeoutOrNull(30_000L) {
+ val query = if (along) PlaceCategories.alongQuery(c, PlaceCategories.routeSample(route!!, from!!))
+ else PlaceCategories.nearQuery(c, here!!.latitude, here.longitude)
+ val json = com.rfsentinel.app.alpr.AlprStore.fetchFirst("data=" + java.net.URLEncoder.encode(query, "UTF-8")) { }
+ val places = PlaceCategories.parse(json, c)
+ if (along) PlaceCategories.rankAlong(places, c, route!!, from!!) else PlaceCategories.rankNear(places, c, here!!.latitude, here.longitude)
+ } ?: throw ServersBusy()
+ }
+ }
+ list.removeAllViews()
+ found.onSuccess { hits ->
+ if (hits.isEmpty()) setNote("No ${c.label.lowercase()} found ${if (along) "along your route" else "within ${NavFormat.distance(PlaceCategories.NEAR_RADIUS_M.toDouble(), NavFormat.miles(this@NavSearchActivity))} of you"}.")
+ else { note.visibility = View.GONE; hits.take(25).forEach { list.addView(hitRow(it)) } }
+ }.onFailure {
+ setNote(if (it is ServersBusy || it.message?.contains("busy") == true)
+ "OpenStreetMap's servers are busy right now - try again in a moment." else "Search failed - ${it.message ?: "no connection?"}")
+ }
+ }
+ }
+
+ /** No answer from the public servers within the time allowed. */
+ private class ServersBusy : Exception("busy")
+
+ private fun hitRow(h: PlaceCategories.Hit): View {
+ val miles = NavFormat.miles(this)
+ val how = if (h.aheadM != null) "${NavFormat.distance(h.aheadM, miles)} ahead · ${NavFormat.distance(h.offM ?: 0.0, miles)} off the road"
+ else h.distanceM?.let { NavFormat.distance(it, miles) }.orEmpty()
+ return row(R.drawable.ic_nav_place, h.place.name, listOf(how, h.place.address).filter { it.isNotBlank() }.joinToString(" · "), h.place,
+ star = true, onTap = { choose(h.place) }, onMore = null)
+ }
+
+ private fun placeRow(p: Place, icon: Int) = row(icon, p.name, listOf(distanceFrom(p), p.address).filter { it.isNotBlank() }.joinToString(" · "), p,
+ star = true, onTap = { choose(p) }, onMore = null)
+
+ private fun distanceFrom(p: Place): String {
+ val here = me ?: return ""
+ return NavFormat.distance(DeviceRegistry.metersBetween(here.latitude, here.longitude, p.lat, p.lon), NavFormat.miles(this))
+ }
+
+ /** One line: an icon, two lines of text, and (for a place) a star to keep it. */
+ private fun row(icon: Int, title: String, sub: String, place: Place?, star: Boolean, onTap: () -> Unit, onMore: (() -> Unit)?): View {
+ val (accent, _) = ChipStyle.accent(this)
+ val v = LinearLayout(this).apply {
+ orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL
+ setPadding(px(16), px(10), px(8), px(10))
+ isClickable = true; isFocusable = true
+ val out = android.util.TypedValue()
+ if (theme.resolveAttribute(android.R.attr.selectableItemBackground, out, true)) setBackgroundResource(out.resourceId)
+ setOnClickListener { onTap() }
+ }
+ v.addView(ImageView(this).apply { setImageResource(icon); setColorFilter(accent) }, LinearLayout.LayoutParams(px(24), px(24)).apply { marginEnd = px(16) })
+ val texts = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ texts.addView(TextView(this).apply { text = title; textSize = 16f; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END })
+ if (sub.isNotBlank()) texts.addView(TextView(this).apply { text = sub; textSize = 13f; alpha = 0.7f; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END })
+ v.addView(texts, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
+ if (star && place != null) {
+ v.addView(starButton(place), LinearLayout.LayoutParams(px(44), px(44)))
+ } else if (onMore != null && place != null) {
+ v.addView(ImageButton(this).apply {
+ setImageResource(R.drawable.ic_settings); setColorFilter(ChipStyle.onSurface(this@NavSearchActivity)); alpha = 0.6f
+ background = null; contentDescription = "Change"
+ setOnClickListener { onMore() }
+ }, LinearLayout.LayoutParams(px(44), px(44)))
+ }
+ return v
+ }
+
+ private fun starButton(p: Place) = ImageButton(this).apply {
+ val (accent, _) = ChipStyle.accent(this@NavSearchActivity)
+ fun style() {
+ val on = Prefs.isNavFavorite(this@NavSearchActivity, p)
+ setImageResource(if (on) R.drawable.ic_nav_star else R.drawable.ic_nav_star_border)
+ setColorFilter(if (on) accent else ChipStyle.onSurface(this@NavSearchActivity))
+ alpha = if (on) 1f else 0.6f
+ contentDescription = if (on) "Starred - tap to remove" else "Star this place"
+ }
+ background = null
+ style()
+ setOnClickListener { Prefs.toggleNavFavorite(this@NavSearchActivity, p); style() }
+ }
+
+ private fun setNote(text: String) { note.text = text; note.visibility = View.VISIBLE }
+
+ // ---- searching ---------------------------------------------------------------------------------
+
+ private val userAgent get() = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}"
+
+ /** Answers already fetched (this screen only): backing over a word you typed costs nothing. */
+ private val cache = object : LinkedHashMap<String, List<Place>>(32, 0.75f, true) {
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, List<Place>>?) = size > 40
+ }
+
+ /** What the servers last answered: a longer query starts from what of it still fits, while its own answer comes. */
+ private var lastResults: List<Place> = emptyList()
+
+ /** Your own places that fit the words - there at once, before any server answers. */
+ private fun mine(q: String): List<Place> =
+ if (mode != MODE_GO && mode != MODE_STOP) emptyList()
+ else PlaceRank.mine(q, Prefs.navHome(this), Prefs.navWork(this), Prefs.navFavorites(this), Prefs.recentDestinations(this))
+
+ private fun search(text: String, submit: Boolean) {
+ val q = text.trim()
+ searchJob?.cancel()
+ if (q.isEmpty()) { lastResults = emptyList(); showStart(); return }
+ // "48.137, 11.575" is a place already.
+ PlaceRank.coordinates(q)?.let { showPlaces(q, emptyList(), listOf(it), null, canSubmit = false); return }
+
+ val here = me
+ val la = here?.latitude; val lo = here?.longitude
+ val key = PlaceRank.cacheKey(q, la, lo)
+ val submitted = cache["s|$key"]
+ val done = submitted ?: if (!submit) cache[key] else null
+ val own = mine(q)
+ // On screen at once: this search's earlier answer, else what an earlier (shorter) search found that still fits.
+ val carry = done ?: PlaceRank.rank(q, PlaceRank.stillMatching(q, lastResults), la, lo)
+ val ask = done == null && (submit || q.length >= Places.MIN_QUERY)
+ val canSubmit = submitted == null && q.length >= Places.MIN_QUERY
+ showPlaces(q, own, carry, if (ask) "Searching..." else null, canSubmit)
+ if (done != null) lastResults = done
+ if (!ask) return
+
+ searchJob = lifecycleScope.launch {
+ if (!submit) delay(DEBOUNCE_MS)
+ try {
+ if (submit) {
+ var latest = carry
+ Places.searchSubmitted(q, la, lo, userAgent, SUBMIT_GRACE_MS) { merged ->
+ latest = merged
+ // Nothing yet from the first answer: keep saying so while the other one is awaited.
+ showPlaces(q, own, merged, if (merged.isEmpty()) "Searching..." else null, canSubmit = false)
+ }
+ cache["s|$key"] = latest; lastResults = latest
+ showPlaces(q, own, latest, null, canSubmit = false)
+ } else {
+ val ranked = PlaceRank.rank(q, PlaceRank.dedupe(Places.searchPhoton(q, la, lo, userAgent)), la, lo)
+ cache[key] = ranked; lastResults = ranked
+ showPlaces(q, own, ranked, null, canSubmit = true)
+ }
+ } catch (e: kotlinx.coroutines.CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ showPlaces(q, own, carry, "Search failed - no connection? The search key tries again.", canSubmit = true)
+ }
+ }
+ }
+
+ /** The list for [q]: your own places, then [results] (each place once), then the "Search for" row; [status] on top when given. */
+ private fun showPlaces(q: String, own: List<Place>, results: List<Place>, status: String?, canSubmit: Boolean) {
+ list.removeAllViews()
+ own.forEach { list.addView(placeRow(it, iconOf(it))) }
+ val others = results.filter { r -> own.none { it.lat == r.lat && it.lon == r.lon } }
+ others.forEach { list.addView(placeRow(it, R.drawable.ic_nav_place)) }
+ val shown = own.size + others.size
+ if (canSubmit) {
+ list.addView(row(R.drawable.ic_search, "Search for \u201c$q\u201d", "Look in more places", null, star = false,
+ onTap = { search(input.text.toString(), submit = true) }, onMore = null))
+ }
+ when {
+ status != null -> setNote(status)
+ shown == 0 && q.length < Places.MIN_QUERY -> setNote("Type at least ${Places.MIN_QUERY} letters to search.")
+ shown == 0 -> setNote("Nothing found for \"$q\".")
+ else -> note.visibility = View.GONE
+ }
+ }
+
+ private fun iconOf(p: Place) = when {
+ p.name == "Home" -> R.drawable.ic_nav_home
+ p.name == "Work" -> R.drawable.ic_nav_work
+ Prefs.isNavFavorite(this, p) -> R.drawable.ic_nav_star
+ else -> R.drawable.ic_nav_history
+ }
+
+ // ---- choosing ----------------------------------------------------------------------------------
+
+ private val REQ_HOME = 11
+ private val REQ_WORK = 12
+
+ private fun choose(p: Place) {
+ when (mode) {
+ MODE_HOME -> { Prefs.setNavHome(this, p); Toast.makeText(this, "Home saved", Toast.LENGTH_SHORT).show() }
+ MODE_WORK -> { Prefs.setNavWork(this, p); Toast.makeText(this, "Work saved", Toast.LENGTH_SHORT).show() }
+ }
+ setResult(RESULT_OK, Intent().putExtra(EXTRA_MODE, mode).putExtra(EXTRA_NAME, p.name).putExtra(EXTRA_ADDRESS, p.address)
+ .putExtra(EXTRA_LAT, p.lat).putExtra(EXTRA_LON, p.lon))
+ finish()
+ }
+
+ @Deprecated("Deprecated in Java")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ @Suppress("DEPRECATION")
+ super.onActivityResult(requestCode, resultCode, data)
+ // Home / Work was just set from here: show it, or go there when this search is for a destination.
+ if (resultCode != RESULT_OK || requestCode !in listOf(REQ_HOME, REQ_WORK)) return
+ val p = placeOf(data) ?: return
+ if (mode == MODE_GO || mode == MODE_STOP) choose(p) else showStart()
+ }
+
+ /** No position known yet (the phone has not used GPS lately): ask for one now, so a "near me" search has something to go on. */
+ @android.annotation.SuppressLint("MissingPermission")
+ private fun askForFix() {
+ if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION) &&
+ !Permissions.granted(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return
+ val lm = getSystemService(LocationManager::class.java) ?: return
+ val provider = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER).firstOrNull { runCatching { lm.isProviderEnabled(it) }.getOrDefault(false) } ?: return
+ val noCancel: android.os.CancellationSignal? = null
+ runCatching {
+ androidx.core.location.LocationManagerCompat.getCurrentLocation(lm, provider, noCancel, androidx.core.content.ContextCompat.getMainExecutor(this),
+ androidx.core.util.Consumer<Location?> { l -> if (l != null && me == null) me = l })
+ }
+ }
+
+ @android.annotation.SuppressLint("MissingPermission")
+ private fun currentFix(): Location? {
+ ScanForegroundService.lastFix?.let { return it }
+ if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION) &&
+ !Permissions.granted(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return null
+ val lm = getSystemService(LocationManager::class.java) ?: return null
+ return runCatching { lm.getProviders(true).mapNotNull { runCatching { lm.getLastKnownLocation(it) }.getOrNull() }.maxByOrNull { it.time } }.getOrNull()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/NavigationService.kt b/app/src/main/java/com/rfsentinel/app/nav/NavigationService.kt
new file mode 100644
index 0000000..c5e085b
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/NavigationService.kt
@@ -0,0 +1,124 @@
+package com.rfsentinel.app.nav
+
+import android.app.Notification
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.IBinder
+import androidx.core.app.NotificationCompat
+import androidx.core.content.ContextCompat
+import com.rfsentinel.app.R
+import com.rfsentinel.app.ui.MapActivity
+import com.rfsentinel.app.util.NotificationHelper
+import java.text.DateFormat
+import java.util.Date
+
+/**
+ * Keeps guidance alive with the screen off or the app in the background (Android otherwise stops a
+ * background app's GPS), and shows the next turn and the arrival time in an ongoing notification.
+ * Runs only while a route is being followed; [Navigator] starts and stops it.
+ */
+class NavigationService : Service() {
+
+ companion object {
+ private const val ACTION_STOP = "com.rfsentinel.app.NAV_STOP"
+ const val NOTIFICATION_ID = 7
+
+ fun start(context: Context) {
+ // Not allowed to start from the background on newer Android: guidance still runs, just without the notification.
+ runCatching { ContextCompat.startForegroundService(context, Intent(context, NavigationService::class.java)) }
+ }
+
+ /** True from the moment the service has called startForeground until it is destroyed. */
+ @Volatile internal var up = false
+
+ fun stop(context: Context) {
+ // A service just asked to start has not called startForeground yet, and stopping it now crashes the
+ // app (Android: "did not then call startForeground") - guidance that ends at once, arriving on the very
+ // first fix, is exactly that. It finds out for itself that guidance is over when it starts, and ends.
+ if (up) runCatching { context.stopService(Intent(context, NavigationService::class.java)) }
+ }
+ }
+
+ private var removeListener: (() -> Unit)? = null
+ private var shown = ""
+ private var foreground = false
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ if (intent?.action == ACTION_STOP) {
+ Navigator.stop()
+ stopSelf()
+ return START_NOT_STICKY
+ }
+ // Started with startForegroundService, so it must call startForeground at once - even if the route
+ // ended in the meantime (arriving on the very first fix): Android crashes the app otherwise.
+ val n = build()
+ runCatching {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
+ else startForeground(NOTIFICATION_ID, n)
+ foreground = true
+ up = true
+ }
+ if (!Navigator.active) { stopSelf(); return START_NOT_STICKY }
+ if (removeListener == null) removeListener = Navigator.addListener { refresh() }
+ return START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ up = false
+ removeListener?.invoke(); removeListener = null
+ super.onDestroy()
+ }
+
+ private fun refresh() {
+ if (!Navigator.active) { stopSelf(); return }
+ val key = lines().joinToString("|")
+ if (key == shown) return // only when the words change, not at every fix
+ runCatching { getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, build()) }
+ }
+
+ /** The notification's two lines: the next turn, and the arrival. */
+ private fun lines(): List<String> {
+ // Discreet mode: nothing about the trip on the notification.
+ if (com.rfsentinel.app.util.Prefs.discreetMode(this)) return listOf("Navigation active", "Tap to open")
+ val r = Navigator.route ?: return listOf("Navigating", "")
+ val s = Navigator.state ?: return listOf("Navigating to ${Navigator.destination?.name.orEmpty()}", Navigator.status.orEmpty())
+ val miles = NavFormat.miles(this)
+ val banner = Prompts.banner(r, s.stepIndex, s.toManeuverM)
+ val turn = banner?.text?.ifBlank { null } ?: r.steps.getOrNull(s.stepIndex + 1)?.instruction?.removeSuffix(".").orEmpty()
+ val title = if (Navigator.status != null) Navigator.status!! else NavFormat.distance(s.toManeuverM, miles) + (if (turn.isBlank()) "" else " · $turn")
+ val left = Navigator.remainingS ?: s.remainingS
+ val eta = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(System.currentTimeMillis() + (left * 1000).toLong()))
+ return listOf(title, "Arrive $eta · ${NavFormat.duration(left)} · ${NavFormat.distance(s.remainingM, miles)}")
+ }
+
+ private fun build(): Notification {
+ val l = lines()
+ shown = l.joinToString("|")
+ val open = PendingIntent.getActivity(
+ this, 0,
+ Intent(this, MapActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ val stop = PendingIntent.getService(
+ this, 2, Intent(this, NavigationService::class.java).setAction(ACTION_STOP),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ return NotificationCompat.Builder(this, NotificationHelper.CHANNEL_NAV)
+ .setSmallIcon(R.drawable.ic_nav_navigation)
+ .setContentTitle(l[0])
+ .setContentText(l.getOrElse(1) { "" })
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setShowWhen(false)
+ .setCategory(NotificationCompat.CATEGORY_NAVIGATION)
+ .setPriority(NotificationCompat.PRIORITY_LOW)
+ .setContentIntent(open)
+ .addAction(0, "End navigation", stop)
+ .build()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt b/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
index 52b6b32..34fe4e5 100644
--- a/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
+++ b/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
@@ -3,88 +3,264 @@ package com.rfsentinel.app.nav
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
-import android.location.LocationListener
+import androidx.core.location.LocationListenerCompat
import android.location.LocationManager
import android.os.Build
import android.os.Looper
import com.rfsentinel.app.BuildConfig
-import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.AlertPlayer
import com.rfsentinel.app.util.Permissions
+import com.rfsentinel.app.util.Prefs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import java.util.concurrent.CopyOnWriteArrayList
/**
- * Turn-by-turn guidance along an [OsmRouting.Route]: follows your GPS position,
- * tells the next manoeuvre and what's left, re-routes when you leave the route
- * and stops on arrival. Runs on its own GPS updates, so it works with or
- * without a scan running.
+ * Turn-by-turn guidance along a [Route] on its own GPS updates (so it works with or without a scan
+ * running): where you are on the route, the next turn and what is left, spoken directions, a new route
+ * when you leave this one, stops on the way, and the end. [NavigationService] keeps it running with the
+ * screen off.
+ *
+ * Planning a route ([plan]) changes nothing; [begin] starts guiding on one of the planned routes.
*/
object Navigator {
- /** Where you are along the route (pure; unit-tested). */
- data class Progress(
- val nextStep: OsmRouting.Step?,
- val toNextStepM: Double,
- val remainingM: Double,
- /** Distance from the route line; large = off route. */
- val offRouteM: Double,
- val arrived: Boolean
- )
-
- const val OFF_ROUTE_M = 60.0
+ /** Within this of the end, you have arrived. */
const val ARRIVED_M = 35.0
+ /** Further than this from the route's line, you are off it. */
+ const val OFF_ROUTE_M = 60.0
+ private const val OFF_ROUTE_AFTER_MS = 5_000L
+ private const val REROUTE_GAP_MS = 15_000L
+ /** Turned round (heading against the route) for this long also means a new route. */
+ private const val WRONG_WAY_AFTER_MS = 8_000L
+ /** Stopped this close to the end for this long: you have arrived (a car park 50 m off the line, a GPS fix that won't settle). */
+ private const val NEAR_END_M = 120.0
+ private const val STOPPED_AT_END_MS = 8_000L
+ private const val STOPPED_MS = 0.8f
+ /** A stop at the lights is part of the trip; one longer than this (you parked) is not counted in the pace. */
+ private const val PARK_AFTER_MS = 45_000L
- @Volatile var destination: OsmRouting.Destination? = null
+ @Volatile var destination: Place? = null
private set
- @Volatile var route: OsmRouting.Route? = null
+ @Volatile var route: Route? = null
private set
- @Volatile var progress: Progress? = null
+ /** Where you are on [route]; null before the first fix. */
+ @Volatile var state: RouteProgress.State? = null
private set
@Volatile var lastFix: Location? = null
private set
+ /** "Re-routing...", or a problem; null when all is well. */
@Volatile var status: String? = null
private set
+ /** Stops still to make on the way to [destination]. */
+ @Volatile var stops: List<Place> = emptyList()
+ private set
+ @Volatile var options: Valhalla.Options = Valhalla.Options()
+ private set
+ @Volatile var arrived: Boolean = false
+ private set
+
+ val active: Boolean get() = destination != null && route != null
+
+ /**
+ * How fast you are really going compared with the route's plan (1 = as planned, 1.2 = a fifth slower),
+ * learned from the drive so far: stops at lights, a slow road. It scales the time left, which is the
+ * nearest thing to traffic-aware timing without a traffic service.
+ */
+ @Volatile var pace: Double = 1.0
+ private set
+
+ /** Seconds left to the end at your pace. */
+ val remainingS: Double? get() = state?.let { it.remainingS * pace }
+
+ /** When you will arrive (epoch ms), from the time left on the route at your pace. */
+ val etaMillis: Long? get() = remainingS?.let { System.currentTimeMillis() + (it * 1000).toLong() }
+
+ // Tests replace these: the time, the route service and the voice.
+ internal var clock: () -> Long = { System.currentTimeMillis() }
+ internal var planner: (suspend (Context, Place, Location, Valhalla.Options, List<Place>) -> List<Route>)? = null
+ internal var speaker: ((String, Boolean) -> Unit)? = null
+ internal var scanStarter: ((Context) -> Unit)? = null
- val active: Boolean get() = destination != null
+ /** Bumped at every begin and stop, so an answer to a question asked of an earlier trip is ignored. */
+ @Volatile internal var generation = 0
+ private set
+
+ private val listeners = CopyOnWriteArrayList<() -> Unit>()
+
+ /** Calls [onChange] (on the main thread) at every fix and change; returns the function that removes it. */
+ fun addListener(onChange: () -> Unit): () -> Unit {
+ listeners.add(onChange)
+ return { listeners.remove(onChange) }
+ }
- /** Called on every change (main thread). */
- var onUpdate: (() -> Unit)? = null
+ private fun changed() = listeners.forEach { runCatching { it() } }
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private var appContext: Context? = null
+ private var prompts = Prompts()
private var offRouteSince = 0L
+ private var wrongWaySince = 0L
private var lastReroute = 0L
- private var spokenStep: OsmRouting.Step? = null
- private var spokenNear = false
-
- private val listener = LocationListener { onLocation(it) }
+ private var legNow = 0
+ private var rerouting = false
+ /** Failed attempts at a new route in a row (offline...): the wait before the next one grows. */
+ private var rerouteFailures = 0
+ private var saidRerouting = false
+ private var lastFixAt = 0L
+ private var stoppedNearEndSince = 0L
+ /** For the pace: when you were last standing still, and the standing time that doesn't count. */
+ private var stillSince = 0L
+ private var parkedMs = 0L
+ /** Where on the route, and when, the pace is measured from (reset when a new route replaces it). */
+ private var paceFromAlong: Double? = null
+ private var paceFromAt = 0L
+ private val listener = LocationListenerCompat { onLocation(it) }
private val userAgent get() = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}"
- /** Plans a route from [from] and starts guiding. Throws if no route is found. */
- suspend fun start(context: Context, dest: OsmRouting.Destination, from: Location) {
+ /** The route options chosen in Settings, for a route nobody has adjusted. */
+ fun defaultOptions(context: Context) = Valhalla.Options(
+ avoidTolls = Prefs.navAvoidTolls(context), avoidHighways = Prefs.navAvoidHighways(context),
+ avoidFerries = Prefs.navAvoidFerries(context))
+
+ /**
+ * Keeps what was ticked (avoid tolls, highways, ferries) as the starting choice for the next
+ * destination - the same setting as Settings > Navigation, so the two always agree.
+ */
+ fun remember(context: Context, options: Valhalla.Options) {
+ Prefs.setNavAvoidTolls(context, options.avoidTolls)
+ Prefs.setNavAvoidHighways(context, options.avoidHighways)
+ Prefs.setNavAvoidFerries(context, options.avoidFerries)
+ }
+
+ // ---- planning ---------------------------------------------------------------------------------
+
+ /** Routes from [from] to [dest] (best first); throws [Valhalla.NoRouteException] or an I/O error. */
+ suspend fun plan(context: Context, dest: Place, from: Location, options: Valhalla.Options,
+ stops: List<Place> = emptyList()): List<Route> {
+ planner?.let { return it(context, dest, from, options, stops) }
+ val miles = NavFormat.miles(context)
+ val body = Valhalla.request(from.latitude, from.longitude, headingOf(from), stops.map { it.lat to it.lon },
+ dest.lat to dest.lon, options, miles)
+ return withContext(Dispatchers.IO) { Valhalla.route(body, userAgent) }
+ }
+
+ /** Plans with the Settings defaults and starts on the best route (the car screens' one-step start). */
+ suspend fun start(context: Context, dest: Place, from: Location) {
+ val o = defaultOptions(context)
+ begin(context, dest, plan(context, dest, from, o).first(), o, emptyList(), from)
+ }
+
+ private fun headingOf(l: Location): Double? = if (l.hasBearing() && l.hasSpeed() && l.speed > 1.5f) l.bearing.toDouble() else null
+
+ // ---- guiding ----------------------------------------------------------------------------------
+
+ /** Starts guiding along [route] to [dest] (through [stops]). */
+ fun begin(context: Context, dest: Place, route: Route, options: Valhalla.Options, stops: List<Place>, from: Location?) {
val app = context.applicationContext
- val r = withContext(Dispatchers.IO) { OsmRouting.route(from.latitude, from.longitude, dest.lat, dest.lon, userAgent) }
appContext = app
- destination = dest
- route = r
+ this.destination = dest
+ this.route = route
+ this.options = options
+ this.stops = stops
+ arrived = false
+ generation++
+ prompts = Prompts(NavFormat.miles(app))
+ offRouteSince = 0L; wrongWaySince = 0L; lastReroute = clock()
+ legNow = 0; rerouting = false; status = null
+ rerouteFailures = 0; saidRerouting = false; stoppedNearEndSince = 0L; lastFixAt = 0L
+ state = null
+ pace = 1.0; paceFromAlong = null; stillSince = 0L; parkedMs = 0L
lastFix = from
- spokenStep = null; spokenNear = false; offRouteSince = 0L
- progress = progressOf(r, from.latitude, from.longitude)
- status = null
+ Prefs.addRecentDestination(app, dest)
listen(app, true)
- progress?.nextStep?.let { say(it.instruction) }
- onUpdate?.invoke()
+ NavigationService.start(app)
+ startScanToo(app)
+ from?.let { onLocation(it) }
+ changed()
+ }
+
+ /**
+ * A destination set means you are driving: the scan starts with the guidance (Settings > Navigation
+ * can turn that off). A scan already running is left as it is, and one that cannot start yet (the
+ * permissions are not given) is skipped - guidance never waits on it. The scan is not stopped on
+ * arrival; it is a scan like any other you started.
+ */
+ private fun startScanToo(app: Context) {
+ if (!Prefs.navStartScan(app) || ScanForegroundService.isRunning) return
+ scanStarter?.let { it(app); return }
+ if (Permissions.missingRequired(app).isNotEmpty()) return
+ runCatching { ScanForegroundService.start(app) }
}
+ /** Ends guiding. */
fun stop() {
- appContext?.let { listen(it, false) }
- destination = null; route = null; progress = null; status = null
- onUpdate?.invoke()
+ appContext?.let { listen(it, false); NavigationService.stop(it) }
+ generation++
+ destination = null; route = null; state = null; status = null; stops = emptyList(); rerouting = false
+ lastFix = null // a fix kept after the trip would stand in for a newer position later (the car screens take the newest of two)
+ changed()
+ }
+
+ /** Adds a stop on the way to the destination and plans again from where you are. */
+ fun addStop(context: Context, stop: Place) {
+ val dest = destination ?: return
+ val from = lastFix ?: return
+ status = "Adding stop..."
+ changed()
+ replan(context.applicationContext, from, dest, stops + stop, then = { stops = it })
+ }
+
+ /** Plans again from where you are with other route options (avoid tolls, highways or ferries). */
+ fun changeOptions(context: Context, newOptions: Valhalla.Options) {
+ val dest = destination ?: return
+ val from = lastFix ?: return
+ status = "Re-routing..."
+ options = newOptions
+ remember(context.applicationContext, newOptions)
+ changed()
+ replan(context.applicationContext, from, dest, stops)
+ }
+
+ private fun replan(app: Context, from: Location, dest: Place, via: List<Place>, then: ((List<Place>) -> Unit)? = null) {
+ if (rerouting) return
+ rerouting = true
+ lastReroute = clock()
+ val gen = generation
+ scope.launch {
+ val opts = options.copy(alternatives = 0)
+ runCatching { plan(app, dest, from, opts, via).first() }
+ .onSuccess { r -> finishReplan(gen, r, via, then) }
+ .onFailure {
+ // Only if it is still the trip that asked: a trip started or ended meanwhile owns the screen now.
+ if (gen == generation && destination != null) {
+ rerouteFailures++
+ lastReroute = clock()
+ status = "No new route (${failureText(it)}) - keeping the old one"
+ }
+ }
+ if (gen == generation) rerouting = false
+ changed()
+ }
+ }
+
+ /** Why a new route could not be had, in words for a driver: the server's reason, else "no connection" (never a host name or a stack message). */
+ internal fun failureText(e: Throwable): String = (e as? Valhalla.NoRouteException)?.message?.takeIf { it.isNotBlank() } ?: "no connection"
+
+ /** A new route came in for the trip of generation [gen]; ignored when that trip is over or another has begun. */
+ internal fun finishReplan(gen: Int, r: Route, via: List<Place>, then: ((List<Place>) -> Unit)? = null) {
+ if (gen != generation || destination == null) return
+ then?.invoke(via)
+ route = r; state = null; status = null; offRouteSince = 0L; wrongWaySince = 0L
+ rerouteFailures = 0; saidRerouting = false
+ paceFromAlong = null; stillSince = 0L; parkedMs = 0L // the pace is measured afresh on the new route
+ prompts.reset(); legNow = 0; lastFixAt = 0L
+ lastFix?.let { onLocation(it) }
}
@SuppressLint("MissingPermission") // checked via Permissions
@@ -108,86 +284,85 @@ object Navigator {
private fun onLocation(l: Location) {
val r = route ?: return
lastFix = l
- val p = progressOf(r, l.latitude, l.longitude)
- progress = p
- val now = System.currentTimeMillis()
- when {
- p.arrived -> {
- say("You have arrived")
- stop(); return
- }
- p.offRouteM > OFF_ROUTE_M -> {
- if (offRouteSince == 0L) offRouteSince = now
- if (now - offRouteSince > 5_000 && now - lastReroute > 20_000) reroute(l)
- }
- else -> offRouteSince = 0L
- }
- p.nextStep?.let { step ->
- if (step != spokenStep) { spokenStep = step; spokenNear = false; if (p.toNextStepM > 400) say("In ${roundDistance(p.toNextStepM)}, ${step.instruction}") }
- if (!spokenNear && p.toNextStepM < 150) { spokenNear = true; say(step.instruction) }
- }
- onUpdate?.invoke()
- }
+ val now = clock()
+ val moving = l.hasSpeed() && l.speed > 1.5f
+ val stopped = l.hasSpeed() && l.speed < STOPPED_MS
+ val bearing = if (moving && l.hasBearing()) l.bearing.toDouble() else null
+ // The most you could have moved along the route since the last fix (a generous allowance for speed and GPS noise).
+ val dtS = if (lastFixAt == 0L) 30.0 else ((now - lastFixAt) / 1000.0).coerceIn(0.5, 120.0)
+ lastFixAt = now
+ val speed = if (l.hasSpeed()) l.speed.toDouble() else 0.0
+ val s = RouteProgress.locate(r, l.latitude, l.longitude, bearing, state, advanceLimitM = maxOf(100.0, (speed + 10.0) * dtS * 1.5 + 50.0))
+ state = s
+ trackPace(r, s, now, moving, l.hasSpeed() && l.speed < 0.5f)
- private fun reroute(from: Location) {
- val dest = destination ?: return
- lastReroute = System.currentTimeMillis()
- status = "Re-routing..."
- onUpdate?.invoke()
- scope.launch {
- runCatching { withContext(Dispatchers.IO) { OsmRouting.route(from.latitude, from.longitude, dest.lat, dest.lon, userAgent) } }
- .onSuccess { r ->
- if (destination != null) {
- route = r; offRouteSince = 0L; status = null
- progress = progressOf(r, from.latitude, from.longitude)
- say("Route updated")
- }
- }
- .onFailure { status = "Off route - couldn't re-route (no connection?)" }
- onUpdate?.invoke()
+ // The end: at it, or stopped close to it for a few seconds (a car park off the line, a fix that won't settle).
+ val atEnd = s.remainingM < ARRIVED_M && s.offM < OFF_ROUTE_M
+ if (stopped && s.remainingM < NEAR_END_M && s.offM < OFF_ROUTE_M) { if (stoppedNearEndSince == 0L) stoppedNearEndSince = now } else stoppedNearEndSince = 0L
+ if (atEnd || (stoppedNearEndSince != 0L && now - stoppedNearEndSince > STOPPED_AT_END_MS)) {
+ arrived = true
+ say("You have arrived at your destination", urgent = true)
+ stop()
+ return
}
- }
- private fun say(text: String) {
- val ctx = appContext ?: return
- AlertPlayer.announce(ctx, text)
- }
+ // A stop on the way: the next leg begins.
+ val leg = r.steps.getOrNull(s.stepIndex)?.leg ?: legNow
+ if (leg > legNow) {
+ legNow = leg
+ stops = stops.drop(1)
+ }
- // ---- Pure geometry -------------------------------------------------------------
+ // Off the route, or going the wrong way along it, for a few seconds: plan again.
+ val off = s.offM > OFF_ROUTE_M
+ val wrong = moving && (s.headingOffDeg ?: 0.0) > 120.0 && s.offM > 20.0
+ if (off) { if (offRouteSince == 0L) offRouteSince = now } else offRouteSince = 0L
+ if (wrong) { if (wrongWaySince == 0L) wrongWaySince = now } else wrongWaySince = 0L
+ val lost = (offRouteSince != 0L && now - offRouteSince > OFF_ROUTE_AFTER_MS) ||
+ (wrongWaySince != 0L && now - wrongWaySince > WRONG_WAY_AFTER_MS)
+ // Each failed attempt (no signal...) doubles the wait, up to a minute and a half: no hammering, no nagging.
+ val wait = REROUTE_GAP_MS * (1 + rerouteFailures.coerceAtMost(4))
+ if (lost && !rerouting && now - lastReroute > wait) {
+ val app = appContext
+ val dest = destination
+ if (app != null && dest != null) {
+ status = "Re-routing..."
+ if (!saidRerouting) { saidRerouting = true; say("Re-routing", urgent = false) }
+ replan(app, l, dest, stops)
+ }
+ } else if (!off && !wrong && !rerouting) {
+ // Back on the line: a failed attempt's note goes, and the next time off the route is told afresh.
+ if (status != null && status != "Re-routing...") status = null
+ saidRerouting = false; rerouteFailures = 0
+ }
- fun roundDistance(m: Double): String = when {
- m >= 1000 -> String.format(java.util.Locale.US, "%.1f kilometres", m / 1000).replace(".0 ", " ")
- m >= 100 -> "${(m / 50).toInt() * 50} metres"
- else -> "${(m / 10).toInt() * 10} metres"
+ if (!off) prompts.next(r, s.stepIndex, s.toManeuverM, if (l.hasSpeed()) l.speed.toDouble() else 0.0)?.let { say(it.text, it.urgent) }
+ changed()
}
/**
- * Snaps the position to the nearest route vertex, then: the next manoeuvre
- * beyond it, the distance to it and to the end, and how far off the route
- * you are.
+ * The pace is measured from the first moment you move - not from when the route was chosen, which may
+ * be long before you pull out - and a long stop (parked) doesn't count against it.
*/
- fun progressOf(r: OsmRouting.Route, lat: Double, lon: Double): Progress {
- val pts = r.points
- if (pts.isEmpty()) return Progress(null, 0.0, 0.0, 0.0, true)
- var best = 0; var bestD = Double.MAX_VALUE
- pts.forEachIndexed { i, (a, b) ->
- val d = DeviceRegistry.metersBetween(lat, lon, a, b)
- if (d < bestD) { bestD = d; best = i }
+ private fun trackPace(r: Route, s: RouteProgress.State, now: Long, moving: Boolean, still: Boolean) {
+ if (still) { if (stillSince == 0L) stillSince = now }
+ else if (stillSince != 0L) {
+ val stillFor = now - stillSince
+ if (stillFor > PARK_AFTER_MS) parkedMs += stillFor - PARK_AFTER_MS
+ stillSince = 0L
}
- // Cumulative distance along the line.
- val cum = DoubleArray(pts.size)
- for (i in 1 until pts.size) cum[i] = cum[i - 1] + DeviceRegistry.metersBetween(pts[i - 1].first, pts[i - 1].second, pts[i].first, pts[i].second)
- val remaining = (cum.last() - cum[best]) + bestD
- val end = pts.last()
- val arrived = DeviceRegistry.metersBetween(lat, lon, end.first, end.second) < ARRIVED_M
- // Each step's position along the line = its nearest vertex.
- fun indexOf(s: OsmRouting.Step): Int {
- var bi = 0; var bd = Double.MAX_VALUE
- pts.forEachIndexed { i, (a, b) -> val d = DeviceRegistry.metersBetween(s.lat, s.lon, a, b); if (d < bd) { bd = d; bi = i } }
- return bi
+ if (paceFromAlong == null) {
+ if (!moving) return
+ paceFromAlong = s.alongM; paceFromAt = now; parkedMs = 0L
}
- val next = r.steps.firstOrNull { it.type != "depart" && indexOf(it) > best }
- val toNext = next?.let { (cum[indexOf(it)] - cum[best]) + bestD } ?: remaining
- return Progress(next, toNext, remaining, bestD, arrived)
+ val ongoing = if (stillSince != 0L && now - stillSince > PARK_AFTER_MS) now - stillSince - PARK_AFTER_MS else 0L
+ val elapsedS = (now - paceFromAt - parkedMs - ongoing) / 1000.0
+ RouteProgress.pace(r, paceFromAlong ?: return, s.alongM, elapsedS)?.let { pace = it }
+ }
+
+ private fun say(text: String, urgent: Boolean) {
+ speaker?.let { it(text, urgent); return }
+ val ctx = appContext ?: return
+ AlertPlayer.navigate(ctx, text, urgent)
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/OsmRouting.kt b/app/src/main/java/com/rfsentinel/app/nav/OsmRouting.kt
deleted file mode 100644
index f7f4fb0..0000000
--- a/app/src/main/java/com/rfsentinel/app/nav/OsmRouting.kt
+++ /dev/null
@@ -1,138 +0,0 @@
-package com.rfsentinel.app.nav
-
-import com.google.gson.JsonObject
-import com.google.gson.JsonParser
-import java.net.HttpURLConnection
-import java.net.URL
-import java.net.URLEncoder
-import java.util.Locale
-
-/**
- * Destination search and driving routes from OpenStreetMap's public services:
- * Nominatim (search) and the OSRM demo server (routing). Only used when you
- * look for a destination or start a route; those servers then see what you
- * searched, your position and the destination, and your IP - never your scans.
- *
- * Parsing and wording are pure Kotlin and unit-tested; the network calls are
- * plain blocking HTTP (call them off the main thread).
- */
-object OsmRouting {
-
- const val SEARCH_URL = "https://nominatim.openstreetmap.org/search"
- const val ROUTE_URL = "https://router.project-osrm.org/route/v1/driving/"
-
- data class Destination(val name: String, val address: String, val lat: Double, val lon: Double)
-
- data class Step(
- /** Where the manoeuvre happens. */
- val lat: Double, val lon: Double,
- val type: String, val modifier: String?, val road: String, val exit: Int?
- ) {
- val instruction: String get() = instructionFor(type, modifier, road, exit)
- }
-
- data class Route(
- val points: List<Pair<Double, Double>>, // lat, lon
- val distanceM: Double,
- val durationS: Double,
- val steps: List<Step>
- )
-
- // ---- Network -------------------------------------------------------------------
-
- fun search(query: String, nearLat: Double?, nearLon: Double?, userAgent: String): List<Destination> {
- val q = StringBuilder(SEARCH_URL)
- .append("?format=jsonv2&addressdetails=0&limit=6&q=").append(URLEncoder.encode(query, "UTF-8"))
- if (nearLat != null && nearLon != null) {
- // Prefer places within ~100 km, without excluding the rest.
- q.append(String.format(Locale.US, "&viewbox=%.4f,%.4f,%.4f,%.4f", nearLon - 1, nearLat + 1, nearLon + 1, nearLat - 1))
- }
- return parseSearch(get(q.toString(), userAgent))
- }
-
- fun route(fromLat: Double, fromLon: Double, toLat: Double, toLon: Double, userAgent: String): Route {
- val url = ROUTE_URL + String.format(Locale.US, "%.6f,%.6f;%.6f,%.6f", fromLon, fromLat, toLon, toLat) +
- "?overview=full&geometries=geojson&steps=true"
- return parseRoute(get(url, userAgent))
- }
-
- private fun get(url: String, userAgent: String): String {
- val c = (URL(url).openConnection() as HttpURLConnection).apply {
- connectTimeout = 10_000
- readTimeout = 20_000
- setRequestProperty("User-Agent", userAgent) // required by the OSM usage policies
- setRequestProperty("Accept-Language", Locale.getDefault().toLanguageTag())
- }
- try {
- if (c.responseCode != 200) error("OpenStreetMap server answered HTTP ${c.responseCode}")
- return c.inputStream.bufferedReader().use { it.readText() }
- } finally {
- c.disconnect()
- }
- }
-
- // ---- Parsing (pure) ---------------------------------------------------------------
-
- fun parseSearch(json: String): List<Destination> =
- JsonParser.parseString(json).asJsonArray.mapNotNull { e ->
- val o = e.asJsonObject
- val lat = o.get("lat")?.asString?.toDoubleOrNull() ?: return@mapNotNull null
- val lon = o.get("lon")?.asString?.toDoubleOrNull() ?: return@mapNotNull null
- val full = o.get("display_name")?.asString ?: return@mapNotNull null
- val name = o.get("name")?.asString?.takeIf { it.isNotBlank() } ?: full.substringBefore(',')
- // Keep the address short for a car screen: street and town (first two parts).
- val rest = full.removePrefix(name).trimStart(',', ' ').split(", ").filter { it.isNotBlank() }
- Destination(name, rest.take(2).joinToString(", "), lat, lon)
- }
-
- fun parseRoute(json: String): Route {
- val root = JsonParser.parseString(json).asJsonObject
- if (root.get("code")?.asString != "Ok") error("No route found (${root.get("code")?.asString})")
- val r = root.getAsJsonArray("routes")[0].asJsonObject
- val points = r.getAsJsonObject("geometry").getAsJsonArray("coordinates").map {
- val a = it.asJsonArray; a[1].asDouble to a[0].asDouble
- }
- val steps = r.getAsJsonArray("legs").flatMap { leg ->
- leg.asJsonObject.getAsJsonArray("steps").map { st ->
- val s = st.asJsonObject
- val m: JsonObject = s.getAsJsonObject("maneuver")
- val loc = m.getAsJsonArray("location")
- Step(
- lat = loc[1].asDouble, lon = loc[0].asDouble,
- type = m.get("type")?.asString ?: "turn",
- modifier = m.get("modifier")?.asString,
- road = s.get("name")?.asString.orEmpty(),
- exit = m.get("exit")?.asInt
- )
- }
- }
- return Route(points, r.get("distance").asDouble, r.get("duration").asDouble, steps)
- }
-
- /** Short spoken / displayed wording for an OSRM manoeuvre. */
- fun instructionFor(type: String, modifier: String?, road: String, exit: Int?): String {
- val onto = if (road.isNotBlank()) " onto $road" else ""
- val dir = when (modifier) {
- "left" -> "left"; "right" -> "right"
- "slight left" -> "slightly left"; "slight right" -> "slightly right"
- "sharp left" -> "sharp left"; "sharp right" -> "sharp right"
- "uturn" -> "a U-turn"; else -> null
- }
- return when (type) {
- "depart" -> "Head out" + (if (road.isNotBlank()) " on $road" else "")
- "arrive" -> "Arrive at your destination"
- "roundabout", "rotary" -> "At the roundabout, take exit ${exit ?: 1}$onto"
- "merge" -> "Merge$onto"
- "on ramp" -> "Take the ramp$onto"
- "off ramp" -> "Take the exit$onto"
- "fork" -> "Keep ${if (modifier?.contains("left") == true) "left" else "right"}$onto"
- "end of road" -> "At the end of the road, turn ${dir ?: "ahead"}$onto"
- "continue", "new name" -> if (dir == null || modifier == "straight") "Continue$onto" else "Keep $dir$onto"
- else -> when {
- modifier == "uturn" -> "Make a U-turn$onto"
- dir != null -> "Turn $dir$onto"
- else -> "Continue$onto"
- }
- }
- }
-}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/PlaceCategories.kt b/app/src/main/java/com/rfsentinel/app/nav/PlaceCategories.kt
new file mode 100644
index 0000000..6f5432d
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/PlaceCategories.kt
@@ -0,0 +1,141 @@
+package com.rfsentinel.app.nav
+
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+import com.rfsentinel.app.service.DeviceRegistry
+import java.util.Locale
+
+/**
+ * "Petrol near me", "food along my route": places of one kind from OpenStreetMap (Overpass, the query
+ * server the camera downloads already use), nearest first or in the order you reach them. Photon, the
+ * name search, can't do this - it matches words in names, so "gas station" finds places called that.
+ *
+ * Privacy: a nearby search sends your position rounded to about 1 km, and a search along the route
+ * sends the road ahead as points rounded to about 200 m. Pure Kotlin (queries, parsing, ranking); the
+ * request itself is made by the caller. Unit-tested.
+ */
+object PlaceCategories {
+
+ enum class Category(val label: String, val tags: List<Pair<String, String>>) {
+ FUEL("Petrol", listOf("amenity" to "fuel")),
+ CHARGING("Charging", listOf("amenity" to "charging_station")),
+ FOOD("Food", listOf("amenity" to "restaurant", "amenity" to "fast_food", "amenity" to "cafe")),
+ PARKING("Parking", listOf("amenity" to "parking")),
+ SUPERMARKET("Shops", listOf("shop" to "supermarket", "shop" to "convenience")),
+ PHARMACY("Pharmacy", listOf("amenity" to "pharmacy")),
+ HOSPITAL("Hospital", listOf("amenity" to "hospital", "amenity" to "clinic")),
+ CASH("Cash", listOf("amenity" to "atm", "amenity" to "bank")),
+ TOILETS("Toilets", listOf("amenity" to "toilets")),
+ REST("Rest stop", listOf("highway" to "services", "highway" to "rest_area"))
+ }
+
+ /** One place found: where it is, and how it relates to you / your route. */
+ data class Hit(
+ val place: Place,
+ val category: Category,
+ /** Straight-line distance from you, when searching near you. */
+ val distanceM: Double? = null,
+ /** Metres ahead of you along the route, and metres off it, when searching along the route. */
+ val aheadM: Double? = null,
+ val offM: Double? = null
+ )
+
+ /** Search this far around you. */
+ const val NEAR_RADIUS_M = 5_000
+ /** ...and this far either side of the road ahead. */
+ const val ALONG_RADIUS_M = 1_500
+ /** The road ahead is sampled this often for the query, to at most [ALONG_MAX_POINTS] points. */
+ const val ALONG_STEP_M = 1_500.0
+ const val ALONG_MAX_POINTS = 40
+ private const val MAX_RESULTS = 60
+
+ /** Rounds a coordinate to [places] decimals (2 = about 1 km, 3 = about 100 m) for the query. */
+ private fun fuzz(v: Double, places: Int): String = String.format(Locale.US, "%.${places}f", v)
+
+ /**
+ * Overpass QL for [category] in a box reaching [NEAR_RADIUS_M] each way from ([lat], [lon]): the
+ * position rounded to ~1 km, the box widened to match and rounded outward to a 1 km grid. A box is
+ * far cheaper for the busy public servers than a circle.
+ */
+ fun nearQuery(category: Category, lat: Double, lon: Double): String {
+ val r = NEAR_RADIUS_M + 1_500.0
+ val clat = Math.round(lat * 100) / 100.0; val clon = Math.round(lon * 100) / 100.0
+ val dLat = r / 110_540.0
+ val dLon = r / (111_320.0 * Math.cos(Math.toRadians(clat)).coerceAtLeast(0.05))
+ fun down(v: Double) = Math.floor(v * 100) / 100.0
+ fun up(v: Double) = Math.ceil(v * 100) / 100.0
+ val box = "${fuzz(down(clat - dLat), 2)},${fuzz(down(clon - dLon), 2)},${fuzz(up(clat + dLat), 2)},${fuzz(up(clon + dLon), 2)}"
+ val parts = category.tags.joinToString("") { (k, v) -> "nwr[\"$k\"=\"$v\"]($box);" }
+ return "[out:json][timeout:15];($parts);out center tags $MAX_RESULTS;"
+ }
+
+ /** Overpass QL for [category] within [ALONG_RADIUS_M] of [points] (lat, lon), rounded to ~200 m (the radius widened to match). */
+ fun alongQuery(category: Category, points: List<Pair<Double, Double>>): String =
+ around(category, "around:${ALONG_RADIUS_M + 250}," + points.joinToString(",") { "${fuzz(it.first, 3)},${fuzz(it.second, 3)}" })
+
+ private fun around(c: Category, area: String): String {
+ // One selector per tag: nwr["amenity"="fuel"](around:...) ... (an OR across the tags).
+ val parts = c.tags.joinToString("") { (k, v) -> "nwr[\"$k\"=\"$v\"]($area);" }
+ return "[out:json][timeout:20];($parts);out center tags $MAX_RESULTS;"
+ }
+
+ /** The route ahead of [fromAlongM] as query points, a kilometre apart, no more than [ALONG_MAX_POINTS]. */
+ fun routeSample(route: Route, fromAlongM: Double): List<Pair<Double, Double>> {
+ val out = ArrayList<Pair<Double, Double>>()
+ var m = fromAlongM.coerceAtLeast(0.0)
+ while (m < route.lengthM && out.size < ALONG_MAX_POINTS) { out += RouteProgress.pointAt(route, m); m += ALONG_STEP_M }
+ if (out.size < ALONG_MAX_POINTS) out += route.end
+ return out
+ }
+
+ // ---- reading the answer ---------------------------------------------------------------------
+
+ /** The places in an Overpass answer, for [category] (no distances yet). */
+ fun parse(json: String, category: Category): List<Place> {
+ val elements = JsonParser.parseString(json).asJsonObject.getAsJsonArray("elements") ?: return emptyList()
+ val seen = HashSet<String>()
+ return elements.mapNotNull { e ->
+ val o = e.asJsonObject
+ val tags = o.getAsJsonObject("tags") ?: JsonObject()
+ val (lat, lon) = position(o) ?: return@mapNotNull null
+ fun tag(k: String) = tags.get(k)?.takeIf { it.isJsonPrimitive }?.asString?.trim()?.takeIf { it.isNotEmpty() }
+ val name = tag("name") ?: tag("brand") ?: tag("operator") ?: category.label
+ val street = listOfNotNull(tag("addr:housenumber"), tag("addr:street")).joinToString(" ").ifEmpty { null }
+ val extra = when (category) {
+ Category.FUEL -> tag("brand")?.takeIf { it != name }
+ Category.CHARGING -> tag("operator")?.takeIf { it != name }
+ else -> null
+ }
+ val address = listOfNotNull(street, tag("addr:city"), extra).take(2).joinToString(", ")
+ // The same place twice (a building and its entrance node): once.
+ if (!seen.add("$name|${"%.4f".format(Locale.US, lat)}|${"%.4f".format(Locale.US, lon)}")) return@mapNotNull null
+ Place(name, address, lat, lon)
+ }
+ }
+
+ private fun position(o: JsonObject): Pair<Double, Double>? {
+ fun num(x: JsonObject, k: String) = x.get(k)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isNumber }?.asDouble
+ val lat = num(o, "lat") ?: o.getAsJsonObject("center")?.let { num(it, "lat") } ?: return null
+ val lon = num(o, "lon") ?: o.getAsJsonObject("center")?.let { num(it, "lon") } ?: return null
+ return lat to lon
+ }
+
+ // ---- ranking --------------------------------------------------------------------------------
+
+ /** Nearest first, within [NEAR_RADIUS_M] of the real position (the query's circle is wider). */
+ fun rankNear(places: List<Place>, category: Category, lat: Double, lon: Double): List<Hit> =
+ places.map { Hit(it, category, distanceM = DeviceRegistry.metersBetween(lat, lon, it.lat, it.lon)) }
+ .filter { it.distanceM!! <= NEAR_RADIUS_M }
+ .sortedBy { it.distanceM }
+
+ /**
+ * In the order you reach them: those within [ALONG_RADIUS_M] of the route, and ahead of [fromAlongM]
+ * (ones behind you are no use), each with how far ahead and how far off the road.
+ */
+ fun rankAlong(places: List<Place>, category: Category, route: Route, fromAlongM: Double): List<Hit> =
+ places.mapNotNull { p ->
+ val (along, off) = RouteProgress.project(route, p.lat, p.lon)
+ if (off > ALONG_RADIUS_M || along < fromAlongM + 50.0) null
+ else Hit(p, category, aheadM = along - fromAlongM, offM = off)
+ }.sortedBy { it.aheadM }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/PlaceRank.kt b/app/src/main/java/com/rfsentinel/app/nav/PlaceRank.kt
new file mode 100644
index 0000000..154a690
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/PlaceRank.kt
@@ -0,0 +1,117 @@
+package com.rfsentinel.app.nav
+
+import com.rfsentinel.app.service.DeviceRegistry
+import java.text.Normalizer
+import java.util.Locale
+
+/**
+ * Putting search results in the order a person expects (pure; unit-tested): a place whose name is what
+ * you typed, or starts with it, before one that merely mentions it, and among equals the nearest first -
+ * where the search servers only know "close to the words" or "close to you", not both. Also finds your
+ * own saved places as you type (instantly, before any server answers), drops the same place listed
+ * twice, and reads a pair of coordinates typed into the box.
+ */
+object PlaceRank {
+
+ /** Lower case, accents and punctuation gone, single spaces: "Café-Bar Zürich" -> "cafe bar zurich". */
+ fun normalize(s: String): String {
+ // Letters that don't split into a base letter and an accent.
+ val folded = s.replace("ß", "ss").replace("ø", "o").replace("Ø", "O").replace("æ", "ae").replace("Æ", "AE")
+ .replace("œ", "oe").replace("đ", "d").replace("ł", "l").replace("Ł", "L")
+ val decomposed = Normalizer.normalize(folded, Normalizer.Form.NFD)
+ val sb = StringBuilder(decomposed.length)
+ var space = true
+ for (ch in decomposed) {
+ if (Character.getType(ch) == Character.NON_SPACING_MARK.toInt()) continue
+ if (Character.isLetterOrDigit(ch)) { sb.append(ch.lowercaseChar()); space = false }
+ else if (!space) { sb.append(' '); space = true }
+ }
+ return sb.toString().trim()
+ }
+
+ /** How well [place] answers [query]: 0 its name is exactly it, 1 starts with it, 2 a word of it does, 3 it appears in the name or address, 4 not at all. */
+ fun matchClass(query: String, place: Place): Int {
+ val q = normalize(query)
+ if (q.isEmpty()) return 4
+ val name = normalize(place.name)
+ if (name == q) return 0
+ if (name.startsWith(q)) return 1
+ val words = name.split(' ')
+ val tokens = q.split(' ')
+ if (words.any { it.startsWith(q) } || tokens.all { t -> words.any { it.startsWith(t) } }) return 2
+ if (name.contains(q)) return 3
+ val all = name + " " + normalize(place.address)
+ if (tokens.all { t -> all.contains(t) }) return 3
+ return 4
+ }
+
+ /**
+ * [places] best answer first. A place's score is how well its name answers the words ([matchClass]) plus a
+ * step for how far it is from ([lat], [lon]): within 50 km none, then one for each of 250 km, 1000 km and
+ * beyond. So the Biodome 20 km away beats a place of the very same name on another continent, yet when
+ * everything is far (you are looking at a trip) the best name still wins. Ties go to the nearest, then to
+ * the server's own order; without a position only the name counts.
+ */
+ fun rank(query: String, places: List<Place>, lat: Double?, lon: Double?): List<Place> {
+ class Ranked(val place: Place, val index: Int, val score: Int, val meters: Double)
+ val located = lat != null && lon != null
+ return places.mapIndexed { i, p ->
+ val d = if (located) DeviceRegistry.metersBetween(lat!!, lon!!, p.lat, p.lon) else 0.0
+ Ranked(p, i, matchClass(query, p) + (if (located) distanceStep(d) else 0), d)
+ }.sortedWith(compareBy<Ranked> { it.score }.thenBy { it.meters }.thenBy { it.index }).map { it.place }
+ }
+
+ /** 0 within 50 km, 1 to 250 km, 2 to 1000 km, 3 beyond: how far a place is, in match-class steps. */
+ internal fun distanceStep(meters: Double): Int = when {
+ meters <= 50_000.0 -> 0
+ meters <= 250_000.0 -> 1
+ meters <= 1_000_000.0 -> 2
+ else -> 3
+ }
+
+ /** The same place once: same name within about 150 m (a park listed as a node and as an area). */
+ fun dedupe(places: List<Place>): List<Place> {
+ val kept = ArrayList<Place>()
+ for (p in places) {
+ val n = normalize(p.name)
+ if (kept.none { normalize(it.name) == n && DeviceRegistry.metersBetween(it.lat, it.lon, p.lat, p.lon) < 150.0 }) kept += p
+ }
+ return kept
+ }
+
+ /** What to keep of an earlier answer while a longer query is still being asked: what still matches it. */
+ fun stillMatching(query: String, earlier: List<Place>): List<Place> = earlier.filter { matchClass(query, it) <= 3 }
+
+ /**
+ * Your own places (Home, Work, starred, recent) that match [query], best first, each once. Home and Work
+ * are found by those words too. [limit] of them.
+ */
+ fun mine(query: String, home: Place?, work: Place?, favorites: List<Place>, recents: List<Place>, limit: Int = 4): List<Place> {
+ val q = normalize(query)
+ if (q.isEmpty()) return emptyList()
+ val tokens = q.split(' ')
+ val named = listOfNotNull(home?.let { it.copy(name = "Home", address = it.address.ifBlank { it.name }) },
+ work?.let { it.copy(name = "Work", address = it.address.ifBlank { it.name }) }) + favorites + recents
+ val matching = named.filter { p ->
+ val all = normalize(p.name) + " " + normalize(p.address)
+ tokens.all { t -> all.split(' ').any { it.startsWith(t) } }
+ }
+ return rank(query, dedupe(matching), null, null).take(limit)
+ }
+
+ /** A place for "48.137, 11.575" / "48.137 11.575" / "48.137;11.575" (latitude first), or null when [text] isn't coordinates. */
+ fun coordinates(text: String): Place? {
+ val m = COORDS.matchEntire(text.trim()) ?: return null
+ val lat = m.groupValues[1].toDoubleOrNull() ?: return null
+ val lon = m.groupValues[2].toDoubleOrNull() ?: return null
+ if (lat !in -90.0..90.0 || lon !in -180.0..180.0) return null
+ return Place(String.format(Locale.US, "%.5f, %.5f", lat, lon), "Coordinates", lat, lon)
+ }
+
+ /** Both numbers carry decimals, so "10 20" (a house number and a postcode, say) is never taken for a position. */
+ private val COORDS = Regex("""^([-+]?\d{1,3}\.\d+)\s*[,;\s]\s*([-+]?\d{1,3}\.\d+)$""")
+
+ /** The key an answer is remembered under: the words and the ~1 km cell of the position that ranked them. */
+ fun cacheKey(query: String, lat: Double?, lon: Double?): String =
+ normalize(query) + "|" + (if (lat != null && lon != null) String.format(Locale.US, "%.2f,%.2f", lat, lon) else "")
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Places.kt b/app/src/main/java/com/rfsentinel/app/nav/Places.kt
new file mode 100644
index 0000000..a069d48
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Places.kt
@@ -0,0 +1,250 @@
+package com.rfsentinel.app.nav
+
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlinx.coroutines.withTimeoutOrNull
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+import java.util.Locale
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+
+/** A place to go: what to call it, a short address, and where it is. (Same fields as saved recents always had.) */
+data class Place(val name: String, val address: String, val lat: Double, val lon: Double)
+
+/**
+ * Place search. As you type: Photon (komoot's OpenStreetMap search), which allows suggestions per
+ * keystroke. When you press search: Photon and OpenStreetMap's own Nominatim at once - Nominatim's rules
+ * forbid asking per keystroke, but a search you submit is what it is for - and whichever answers first is
+ * shown at once, the other merged in when it arrives. No key or account; the servers see what you type,
+ * the rough area to prefer (rounded to about 1 km) and your IP. Only asked while you search, or when you
+ * drop a pin and want to know what's there.
+ *
+ * Requests stop the moment a newer search replaces them. Parsing is pure Kotlin and unit-tested.
+ */
+object Places {
+
+ const val SEARCH_URL = "https://photon.komoot.io/api/"
+ const val REVERSE_URL = "https://photon.komoot.io/reverse"
+ const val NOMINATIM_URL = "https://nominatim.openstreetmap.org/search"
+ /** Suggestions start after this many characters. */
+ const val MIN_QUERY = 3
+ private const val FETCH = 10
+
+ // ---- requests -------------------------------------------------------------------------------------
+
+ private fun photonUrl(query: String, nearLat: Double?, nearLon: Double?, limit: Int): String {
+ val url = StringBuilder(SEARCH_URL).append("?q=").append(URLEncoder.encode(query.trim(), "UTF-8")).append("&limit=").append(limit)
+ if (nearLat != null && nearLon != null) url.append(String.format(Locale.US, "&lat=%.2f&lon=%.2f", nearLat, nearLon))
+ language()?.let { url.append("&lang=").append(it) }
+ return url.toString()
+ }
+
+ /** Photon's languages (checked against the live server: anything else, "it" included, is answered HTTP 400); others get the place's own name. */
+ internal fun language(tag: String = Locale.getDefault().language): String? = tag.takeIf { it in PHOTON_LANGUAGES }
+
+ private val PHOTON_LANGUAGES = setOf("en", "de", "fr")
+
+ private fun nominatimUrl(query: String, nearLat: Double?, nearLon: Double?, limit: Int): String {
+ val url = StringBuilder(NOMINATIM_URL).append("?format=jsonv2&addressdetails=1&limit=").append(limit)
+ .append("&q=").append(URLEncoder.encode(query.trim(), "UTF-8"))
+ // Prefer (not require) places within a degree of you; the position is rounded to about 1 km.
+ if (nearLat != null && nearLon != null) {
+ val la = Math.round(nearLat * 100) / 100.0; val lo = Math.round(nearLon * 100) / 100.0
+ url.append(String.format(Locale.US, "&viewbox=%.2f,%.2f,%.2f,%.2f", lo - 1, la + 1, lo + 1, la - 1))
+ }
+ url.append("&accept-language=").append(Locale.getDefault().toLanguageTag())
+ return url.toString()
+ }
+
+ /** Photon's suggestions for [query], nearest to ([nearLat], [nearLon]) preferred; stops when the calling coroutine is cancelled. */
+ suspend fun searchPhoton(query: String, nearLat: Double?, nearLon: Double?, userAgent: String, limit: Int = FETCH): List<Place> =
+ parse(fetch(photonUrl(query, nearLat, nearLon, limit), userAgent, 10_000))
+
+ /** Nominatim's answer for a search that was submitted (never per keystroke: its rules). */
+ suspend fun searchNominatim(query: String, nearLat: Double?, nearLon: Double?, userAgent: String, limit: Int = FETCH): List<Place> =
+ parseNominatim(fetch(nominatimUrl(query, nearLat, nearLon, limit), userAgent, 10_000))
+
+ /**
+ * A submitted search: Photon and Nominatim at once. [onResults] gets the merged, ranked list each time
+ * one of them answers (so the first answer is on screen at once); once one has answered the other is given
+ * [graceMs] more. Returns whether either answered; throws the last error when both failed.
+ */
+ suspend fun searchSubmitted(query: String, nearLat: Double?, nearLon: Double?, userAgent: String,
+ graceMs: Long = Long.MAX_VALUE, onResults: (List<Place>) -> Unit): Boolean = coroutineScope {
+ val results = Channel<Result<List<Place>>>(2)
+ val jobs = listOf(
+ launch { results.send(runCatching { searchPhoton(query, nearLat, nearLon, userAgent) }) },
+ launch { results.send(runCatching { searchNominatim(query, nearLat, nearLon, userAgent) }) }
+ )
+ val merged = ArrayList<Place>()
+ var answered = 0; var any = false; var lastError: Throwable? = null
+ var deadline = Long.MAX_VALUE
+ try {
+ while (answered < 2) {
+ val next = if (deadline == Long.MAX_VALUE) results.receive()
+ else withTimeoutOrNull((deadline - System.currentTimeMillis()).coerceAtLeast(0)) { results.receive() } ?: break
+ answered++
+ next.onSuccess { found ->
+ any = true
+ merged += found
+ onResults(PlaceRank.rank(query, PlaceRank.dedupe(merged), nearLat, nearLon))
+ if (deadline == Long.MAX_VALUE && graceMs != Long.MAX_VALUE) deadline = System.currentTimeMillis() + graceMs
+ }.onFailure { if (it is CancellationException) throw it; lastError = it }
+ }
+ } finally {
+ jobs.forEach { it.cancel() } // the slower one stops: its connection is closed
+ }
+ if (!any) lastError?.let { throw it }
+ any
+ }
+
+ /** What's at a point (a dropped pin): the nearest address or place, or null. */
+ fun reverse(lat: Double, lon: Double, userAgent: String): Place? =
+ parse(getBlocking(String.format(Locale.US, "%s?lat=%.6f&lon=%.6f", REVERSE_URL, lat, lon), userAgent, 12_000)).firstOrNull()
+
+ /** Blocking: for the places that already run on a background thread (the car screens). Photon only, as it is typed. */
+ fun search(query: String, nearLat: Double?, nearLon: Double?, userAgent: String, limit: Int = FETCH): List<Place> =
+ parse(getBlocking(photonUrl(query, nearLat, nearLon, limit), userAgent, 12_000))
+
+ private fun open(url: String, userAgent: String, readMs: Int): HttpURLConnection =
+ (URL(url).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 8_000
+ readTimeout = readMs
+ setRequestProperty("User-Agent", userAgent)
+ setRequestProperty("Accept", "application/json")
+ }
+
+ private fun read(c: HttpURLConnection): String {
+ try {
+ if (c.responseCode != 200) error("The search server answered HTTP ${c.responseCode}")
+ return c.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
+ } finally {
+ c.disconnect()
+ }
+ }
+
+ private fun getBlocking(url: String, userAgent: String, readMs: Int): String = read(open(url, userAgent, readMs))
+
+ /** Tests answer the requests themselves (url, user agent, read timeout). */
+ internal var fetcher: (suspend (String, String, Int) -> String)? = null
+
+ /** A GET that gives up (and closes its connection) the moment the coroutine asking is cancelled: a new keystroke. */
+ private suspend fun fetch(url: String, userAgent: String, readMs: Int): String {
+ fetcher?.let { return it(url, userAgent, readMs) }
+ return suspendCancellableCoroutine { cont ->
+ val conn = open(url, userAgent, readMs)
+ val job = CoroutineScope(Dispatchers.IO).launch {
+ try {
+ val text = read(conn)
+ if (cont.isActive) cont.resume(text)
+ } catch (e: Throwable) {
+ if (cont.isActive) cont.resumeWithException(e)
+ }
+ }
+ cont.invokeOnCancellation { job.cancel(); runCatching { conn.disconnect() } }
+ }
+ }
+
+ // ---- reading answers (pure) ---------------------------------------------------------------------
+
+ fun parse(json: String): List<Place> {
+ val features = JsonParser.parseString(json).asJsonObject.getAsJsonArray("features") ?: return emptyList()
+ return features.mapNotNull { f ->
+ val o = f.asJsonObject
+ val c = o.getAsJsonObject("geometry")?.getAsJsonArray("coordinates") ?: return@mapNotNull null
+ val p = o.getAsJsonObject("properties") ?: JsonObject()
+ val street = listOfNotNull(p.str("housenumber"), p.str("street")).joinToString(" ").ifBlank { null }
+ val town = p.str("city") ?: p.str("town") ?: p.str("village") ?: p.str("locality") ?: p.str("county")
+ // A street itself, or a house without a name, is called by its address.
+ val name = p.str("name") ?: street ?: town ?: return@mapNotNull null
+ val parts = listOfNotNull(street?.takeIf { it != name }, town?.takeIf { it != name }, p.str("state"))
+ Place(name, describe(kindLabel(p.str("osm_key"), p.str("osm_value")), parts), c[1].asDouble, c[0].asDouble)
+ }.distinctBy { "${it.name}|${it.address}" }
+ }
+
+ /** Nominatim's answer (jsonv2, with address details). */
+ fun parseNominatim(json: String): List<Place> {
+ val arr = JsonParser.parseString(json).asJsonArray
+ return arr.mapNotNull { e ->
+ val o = e.asJsonObject
+ val lat = o.str("lat")?.toDoubleOrNull() ?: return@mapNotNull null
+ val lon = o.str("lon")?.toDoubleOrNull() ?: return@mapNotNull null
+ val a = o.getAsJsonObject("address") ?: JsonObject()
+ val street = listOfNotNull(a.str("house_number"), a.str("road")).joinToString(" ").ifBlank { null }
+ val town = a.str("city") ?: a.str("town") ?: a.str("village") ?: a.str("municipality") ?: a.str("suburb") ?: a.str("county")
+ val full = o.str("display_name").orEmpty()
+ val name = o.str("name") ?: street ?: full.substringBefore(',').ifBlank { null } ?: return@mapNotNull null
+ val parts = listOfNotNull(street?.takeIf { it != name }, town?.takeIf { it != name }, a.str("state"))
+ Place(name, describe(kindLabel(o.str("category"), o.str("type")), parts), lat, lon)
+ }.distinctBy { "${it.name}|${it.address}" }
+ }
+
+ /** "Park · Munich, Bavaria": what kind of place it is, then the two most useful address parts. */
+ private fun describe(kind: String?, parts: List<String>): String {
+ val where = parts.take(2).joinToString(", ")
+ return when {
+ kind != null && where.isNotEmpty() -> "$kind · $where"
+ kind != null -> kind
+ else -> where
+ }
+ }
+
+ /** A person's word for an OpenStreetMap kind of place ("leisure=park" -> "Park"); null for houses and plain buildings (the address says it). */
+ fun kindLabel(key: String?, value: String?): String? {
+ if (key == null || value == null) return null
+ val v = value.lowercase(Locale.ROOT)
+ return when (key.lowercase(Locale.ROOT)) {
+ "building", "addr", "house" -> null
+ "place" -> when (v) {
+ "house", "plot", "yes" -> null
+ "city" -> "City"; "town" -> "Town"; "village", "hamlet" -> "Village"
+ "suburb", "neighbourhood", "quarter", "borough", "city_block" -> "Neighbourhood"
+ "state", "region", "province", "county" -> "Region"; "country" -> "Country"
+ "square" -> "Square"; "island" -> "Island"
+ else -> human(v)
+ }
+ "highway" -> when (v) {
+ "bus_stop" -> "Bus stop"; "services", "rest_area" -> "Rest stop"
+ "motorway", "trunk", "primary", "secondary", "tertiary", "residential", "unclassified", "service", "living_street",
+ "pedestrian", "footway", "cycleway", "path", "track", "road" -> "Street"
+ else -> human(v)
+ }
+ "amenity" -> when (v) {
+ "restaurant" -> "Restaurant"; "cafe" -> "Cafe"; "fast_food" -> "Fast food"; "bar", "pub" -> "Bar"
+ "fuel" -> "Petrol station"; "charging_station" -> "Charging"; "parking" -> "Parking"
+ "pharmacy" -> "Pharmacy"; "hospital" -> "Hospital"; "clinic", "doctors" -> "Clinic"
+ "bank" -> "Bank"; "atm" -> "ATM"; "post_office" -> "Post office"
+ "school", "kindergarten" -> "School"; "university", "college" -> "University"
+ "library" -> "Library"; "theatre" -> "Theatre"; "cinema" -> "Cinema"
+ "place_of_worship" -> "Place of worship"; "toilets" -> "Toilets"; "townhall" -> "Town hall"
+ else -> human(v)
+ }
+ "shop" -> when (v) { "supermarket" -> "Supermarket"; "convenience" -> "Convenience store"; "yes" -> "Shop"; else -> human(v) }
+ "tourism" -> when (v) { "hotel" -> "Hotel"; "hostel" -> "Hostel"; "museum" -> "Museum"; "attraction" -> "Attraction"
+ "viewpoint" -> "Viewpoint"; "camp_site" -> "Campsite"; "information" -> "Information"; else -> human(v) }
+ "leisure" -> when (v) { "park" -> "Park"; "garden" -> "Garden"; "stadium" -> "Stadium"; "sports_centre" -> "Sports centre"
+ "playground" -> "Playground"; "pitch" -> "Pitch"; "swimming_pool" -> "Pool"; "nature_reserve" -> "Nature reserve"; else -> human(v) }
+ "railway" -> when (v) { "station" -> "Train station"; "halt" -> "Train stop"; "tram_stop" -> "Tram stop"; "subway_entrance" -> "Metro entrance"; else -> human(v) }
+ "public_transport" -> "Transit stop"
+ "aeroway" -> when (v) { "aerodrome" -> "Airport"; "terminal" -> "Terminal"; else -> human(v) }
+ "natural" -> when (v) { "water" -> "Water"; "peak" -> "Peak"; "beach" -> "Beach"; "wood" -> "Wood"; else -> human(v) }
+ "boundary" -> if (v == "administrative") "Area" else human(v)
+ "office" -> "Office"
+ "landuse" -> null
+ else -> null
+ }
+ }
+
+ private fun human(v: String) = v.replace('_', ' ').replaceFirstChar { it.uppercase() }
+
+ private fun JsonObject.str(k: String): String? = get(k)?.takeIf { it.isJsonPrimitive }?.asString?.trim()?.ifEmpty { null }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Prompts.kt b/app/src/main/java/com/rfsentinel/app/nav/Prompts.kt
new file mode 100644
index 0000000..f0a975b
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Prompts.kt
@@ -0,0 +1,90 @@
+package com.rfsentinel.app.nav
+
+/**
+ * What to show and say as you drive (pure; unit-tested). Valhalla words each prompt and says how far
+ * before the turn it's due ("In 500 meters, keep right" from about 500 m); this decides which is due
+ * now, says it a moment early at speed (speech takes a second to start), never says a distance that is
+ * no longer true (joining a stretch at 100 m, the "In 300 meters" prompt is skipped), and adds a heads-up
+ * before a turn at the end of a long stretch, as navigation apps do.
+ */
+class Prompts(private val miles: Boolean = false) {
+
+ /** A prompt to speak; [urgent] for the last one before a turn (it may cut into other speech). */
+ data class Say(val text: String, val urgent: Boolean)
+
+ /** Prompts already handled, as "step:metres before the turn". */
+ private val handled = HashSet<String>()
+
+ /** Forget what was said (a new route). */
+ fun reset() = handled.clear()
+
+ /**
+ * The prompt due now on step [stepIndex] of [route], with the turn [toManeuverM] away, driving
+ * at [speedMs]; null when nothing is due. Each prompt is used once; of several due at once only
+ * the nearest that is still true is spoken.
+ */
+ fun next(route: Route, stepIndex: Int, toManeuverM: Double, speedMs: Double): Say? {
+ val step = route.steps.getOrNull(stepIndex) ?: return null
+ val all = withHeadsUp(step).sortedByDescending { it.beforeM }
+ if (all.isEmpty()) return null
+ // About a second and a half of travel early: speech doesn't start the instant it's asked for.
+ val lead = (speedMs * LEAD_S).coerceIn(0.0, MAX_LEAD_M)
+ val due = all.filter { toManeuverM <= it.beforeM + lead && key(stepIndex, it) !in handled }
+ if (due.isEmpty()) return null
+ due.forEach { handled += key(stepIndex, it) }
+ val last = all.last()
+ // The nearest due prompt is the one to say - if it still holds: "In 300 meters" at 100 m doesn't.
+ val say = due.last()
+ val holds = say === last || toManeuverM >= say.beforeM * STILL_TRUE
+ if (!holds) return null
+ // The route server words the end of every leg "your destination"; before the last leg it is a stop.
+ val lastLeg = route.steps.lastOrNull()?.leg ?: 0
+ val text = if (step.leg < lastLeg) say.text.replace("arrived at your destination", "arrived at your stop")
+ .replace("at your destination", "at your stop") else say.text
+ return Say(text, urgent = say === last && say.beforeM <= URGENT_WITHIN_M)
+ }
+
+ private fun key(stepIndex: Int, v: Step.Voice) = "$stepIndex:${v.beforeM}"
+
+ /** The step's prompts, plus a heads-up well before the turn at the end of a long stretch. */
+ internal fun withHeadsUp(step: Step): List<Step.Voice> {
+ val v = step.voice
+ val at = if (miles) HEADS_UP_MILE_M else HEADS_UP_KM_M
+ if (step.endM - step.startM < at * 1.6 || v.any { it.beforeM in at * 0.75..at * 1.3 }) return v
+ // Worded like Valhalla's own nearer prompt ("In 500 meters, Keep right..."), else its last one.
+ val base = v.firstOrNull { IN_DISTANCE.containsMatchIn(it.text) } ?: v.minByOrNull { it.beforeM } ?: return v
+ val far = if (miles) "1 mile" else "2 kilometers"
+ val text = if (IN_DISTANCE.containsMatchIn(base.text)) base.text.replace(IN_DISTANCE, "In $far, ")
+ else "In $far, " + base.text
+ return v + Step.Voice(at, text)
+ }
+
+ companion object {
+ private const val LEAD_S = 1.5
+ private const val MAX_LEAD_M = 60.0
+ private const val URGENT_WITHIN_M = 300.0
+ /** A prompt is still true while you're at least this share of its distance from the turn. */
+ private const val STILL_TRUE = 0.6
+ private const val HEADS_UP_KM_M = 2_000.0
+ private const val HEADS_UP_MILE_M = 1_609.0
+ private val IN_DISTANCE = Regex("^In [^,]+, ")
+
+ /** The banner to show on step [stepIndex] with the turn [toManeuverM] away (its lanes appear when they're near). */
+ fun banner(route: Route, stepIndex: Int, toManeuverM: Double): Step.Banner? {
+ val b = route.steps.getOrNull(stepIndex)?.banners ?: return null
+ return b.filter { it.beforeM >= toManeuverM - 1.0 }.minByOrNull { it.beforeM } ?: b.firstOrNull()
+ }
+
+ /**
+ * "Then" what, when the turn after the coming one follows closely (under 400 m): its banner.
+ * Null when there's room between them, or nothing after.
+ */
+ fun thenBanner(route: Route, stepIndex: Int): Step.Banner? {
+ val following = route.steps.getOrNull(stepIndex + 1) ?: return null
+ if (following.isArrival || following.endM - following.startM > THEN_WITHIN_M) return null
+ return following.banners.maxByOrNull { it.beforeM }?.takeIf { it.type != "arrive" }
+ }
+
+ private const val THEN_WITHIN_M = 400.0
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Route.kt b/app/src/main/java/com/rfsentinel/app/nav/Route.kt
new file mode 100644
index 0000000..2fa5dda
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Route.kt
@@ -0,0 +1,92 @@
+package com.rfsentinel.app.nav
+
+/**
+ * A driving route as navigation uses it: the line, and the steps along it with what to show and say
+ * before each turn. Built by [Valhalla] (pure Kotlin, unit-tested).
+ */
+data class Route(
+ /** The line, as parallel arrays (the steps' own lines joined end to end). */
+ val lats: DoubleArray,
+ val lons: DoubleArray,
+ /** Metres from the start to each point of the line (measured on it, so it matches [RouteProgress]). */
+ val along: DoubleArray,
+ /** Valhalla's own figures for the whole route. */
+ val distanceM: Double,
+ val durationS: Double,
+ val steps: List<Step>,
+ /** The main roads it takes ("Highway 40, Rue Principale"), to tell routes apart. */
+ val summary: String,
+ /** Where it ends (the last stop). */
+ val end: Pair<Double, Double>
+) {
+ val size: Int get() = lats.size
+ val lengthM: Double get() = along.lastOrNull() ?: 0.0
+
+ /** The line as (lat, lon) pairs, for drawing. */
+ fun points(): List<Pair<Double, Double>> = List(size) { lats[it] to lons[it] }
+
+ /**
+ * The line from [fromM] along it to the end (the part still ahead), at most about [maxPoints] points:
+ * a longer one is thinned out evenly (the end is always kept) - the screen can't show more.
+ */
+ fun pointsFrom(fromM: Double, maxPoints: Int = 1_500): List<Pair<Double, Double>> {
+ val i = along.indexOfFirst { it > fromM }.takeIf { it > 0 } ?: return if (fromM <= 0) thin(points(), maxPoints) else listOf(end)
+ val t = (fromM - along[i - 1]) / (along[i] - along[i - 1]).coerceAtLeast(1e-9)
+ val start = (lats[i - 1] + t * (lats[i] - lats[i - 1])) to (lons[i - 1] + t * (lons[i] - lons[i - 1]))
+ return thin(listOf(start) + (i until size).map { lats[it] to lons[it] }, maxPoints)
+ }
+
+ private fun thin(pts: List<Pair<Double, Double>>, maxPoints: Int): List<Pair<Double, Double>> {
+ if (pts.size <= maxPoints) return pts
+ val stride = (pts.size + maxPoints - 1) / maxPoints
+ return pts.filterIndexed { i, _ -> i % stride == 0 || i == pts.size - 1 }
+ }
+
+ override fun equals(other: Any?) = this === other
+ override fun hashCode() = System.identityHashCode(this)
+}
+
+/**
+ * One stretch of the route, from one manoeuvre to the next. What it [banners] and [voice] about is
+ * the manoeuvre at its END (the start of the next step), as navigation apps announce the next turn.
+ */
+data class Step(
+ /** This step's own manoeuvre (where it starts): OSRM words - "turn", "fork", "roundabout"... */
+ val type: String,
+ val modifier: String?,
+ /** The road this step is on. */
+ val name: String,
+ val exit: Int?,
+ /** Valhalla's wording of this step's own manoeuvre ("Turn right onto Rue Principale."). */
+ val instruction: String,
+ val lat: Double,
+ val lon: Double,
+ val lengthM: Double,
+ val durationS: Double,
+ /** Where it starts and ends on [Route.along]. */
+ val startM: Double,
+ val endM: Double,
+ /** The leg it belongs to: 0 up to the first stop, then 1... */
+ val leg: Int,
+ val voice: List<Voice>,
+ val banners: List<Banner>,
+ /** Which side of the road they drive on here ("right" or "left"): the way round a roundabout, which way a U-turn goes. */
+ val drivingSide: String = "right"
+) {
+ /** A spoken prompt, due when the next manoeuvre is [beforeM] away or less. */
+ data class Voice(val beforeM: Double, val text: String)
+
+ /** What the banner shows from [beforeM] before the next manoeuvre: that manoeuvre, and the lanes for it. */
+ data class Banner(
+ val beforeM: Double,
+ val text: String,
+ val type: String,
+ val modifier: String?,
+ val lanes: List<Lane>
+ )
+
+ /** One lane at the coming junction: its arrows, whether it is one to be in, and which arrow to follow if it is. */
+ data class Lane(val directions: List<String>, val active: Boolean, val activeDirection: String? = null)
+
+ val isArrival: Boolean get() = type == "arrive"
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/RouteProgress.kt b/app/src/main/java/com/rfsentinel/app/nav/RouteProgress.kt
new file mode 100644
index 0000000..7cc9da3
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/RouteProgress.kt
@@ -0,0 +1,153 @@
+package com.rfsentinel.app.nav
+
+import kotlin.math.abs
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.hypot
+
+/**
+ * Where you are on a [Route] (pure; unit-tested): the nearest point of the line to your fix - looked
+ * for just ahead of where you were first, so a road that comes back on itself or runs beside itself
+ * can't make you jump - how far along and how far off it that is, the step you're on, and what's left.
+ */
+object RouteProgress {
+
+ /** Where you are along the route. */
+ data class State(
+ /** The stretch of line you're on: from point [segment] to [segment] + 1. */
+ val segment: Int,
+ val alongM: Double,
+ /** How far off the line your fix is. */
+ val offM: Double,
+ /** Your heading against the line's direction there (0..180), when you're moving. */
+ val headingOffDeg: Double?,
+ val stepIndex: Int,
+ /** To the end of this step: the next manoeuvre. */
+ val toManeuverM: Double,
+ val remainingM: Double,
+ val remainingS: Double
+ )
+
+ /** Looked for ahead of the last match first, this far along the line. */
+ private const val WINDOW_AHEAD_M = 1_500.0
+ private const val WINDOW_BEHIND_M = 60.0
+ /** Within the window, a match this close is taken without looking at the whole route. */
+ private const val WINDOW_OK_M = 50.0
+ /** How many metres a direction against the line counts for, at 90 degrees off. */
+ private const val HEADING_WEIGHT_M = 20.0
+
+ /**
+ * Your place on [route] from a fix at ([lat], [lon]) going [bearing] (null when not moving), with
+ * [last] the previous match (null on a new route). [advanceLimitM] is the most you could have moved along
+ * the route since then (a second at 30 m/s: about 100 m): a stretch of the route further on that merely
+ * passes close by - a loop, an out-and-back road beside itself - is not where you are.
+ */
+ fun locate(route: Route, lat: Double, lon: Double, bearing: Double?, last: State?, advanceLimitM: Double = WINDOW_AHEAD_M): State {
+ val n = route.size
+ if (n < 2) return State(0, 0.0, 0.0, null, 0, 0.0, 0.0, 0.0)
+ val kx = 111_320.0 * cos(Math.toRadians(lat)); val ky = 110_540.0
+ fun x(i: Int) = (route.lons[i] - lon) * kx
+ fun y(i: Int) = (route.lats[i] - lat) * ky
+
+ class Best(var seg: Int = 0, var cost: Double = Double.MAX_VALUE, var off: Double = 0.0, var t: Double = 0.0, var dir: Double = 0.0)
+ fun scan(from: Int, to: Int, lastAlong: Double?): Best {
+ val b = Best()
+ for (i in from.coerceAtLeast(0) until to.coerceAtMost(n - 1)) {
+ val x0 = x(i); val y0 = y(i); val dx = x(i + 1) - x0; val dy = y(i + 1) - y0
+ val l2 = dx * dx + dy * dy
+ val t = if (l2 == 0.0) 0.0 else (-(x0 * dx + y0 * dy) / l2).coerceIn(0.0, 1.0)
+ val off = hypot(x0 + t * dx, y0 + t * dy)
+ val dir = (Math.toDegrees(atan2(dx, dy)) + 360) % 360
+ var cost = off
+ if (bearing != null && l2 > 0) cost += HEADING_WEIGHT_M * angleDiff(bearing, dir) / 90.0
+ // Going back along the route is unlikely: you'd have to turn round.
+ if (lastAlong != null) {
+ val a = route.along[i] + t * (route.along[i + 1] - route.along[i])
+ if (a < lastAlong - WINDOW_BEHIND_M) cost += 40.0
+ else if (a > lastAlong + advanceLimitM) cost += 60.0
+ }
+ if (cost < b.cost) { b.seg = i; b.cost = cost; b.off = off; b.t = t; b.dir = dir }
+ }
+ return b
+ }
+
+ var best: Best? = null
+ if (last != null) {
+ val lastAlong = last.alongM
+ var from = last.segment
+ while (from > 0 && route.along[from] > lastAlong - WINDOW_BEHIND_M) from--
+ var to = last.segment + 1
+ while (to < n - 1 && route.along[to] < lastAlong + WINDOW_AHEAD_M) to++
+ best = scan(from, to + 1, lastAlong).takeIf { it.off <= WINDOW_OK_M }
+ }
+ val b = best ?: scan(0, n, last?.alongM)
+ val along = route.along[b.seg] + b.t * (route.along[b.seg + 1] - route.along[b.seg])
+ val headingOff = bearing?.let { angleDiff(it, b.dir) }
+
+ val steps = route.steps
+ var si = steps.indexOfLast { it.startM <= along + 0.5 && !it.isArrival }.coerceAtLeast(0)
+ if (steps.isEmpty()) si = 0
+ val step = steps.getOrNull(si)
+ val toManeuver = ((step?.endM ?: route.lengthM) - along).coerceAtLeast(0.0)
+ val remaining = (route.lengthM - along).coerceAtLeast(0.0)
+ val remainingS = if (step == null) 0.0 else {
+ val stepLen = (step.endM - step.startM).coerceAtLeast(1.0)
+ step.durationS * (toManeuver / stepLen).coerceIn(0.0, 1.0) + steps.drop(si + 1).sumOf { it.durationS }
+ }
+ return State(b.seg, along, b.off, headingOff, si, toManeuver, remaining, remainingS)
+ }
+
+ /** Seconds the route plans to take to reach [alongM] from its start. */
+ fun plannedSecondsAt(route: Route, alongM: Double): Double {
+ var t = 0.0
+ for (s in route.steps) {
+ if (s.endM <= alongM) { t += s.durationS; continue }
+ if (s.startM >= alongM) break
+ t += s.durationS * ((alongM - s.startM) / (s.endM - s.startM).coerceAtLeast(1.0))
+ break
+ }
+ return t
+ }
+
+ /**
+ * How much slower (above 1) or faster (below 1) than the route's plan you are driving: the time
+ * you took from [fromAlongM] to [toAlongM] ([elapsedS], stops at lights included) against the time
+ * the route plans for that stretch. Null until there's enough to go on (600 m and 90 s); it counts
+ * for more the further you've driven (fully after 4 km), and stays between 0.6 and 2.
+ */
+ fun pace(route: Route, fromAlongM: Double, toAlongM: Double, elapsedS: Double): Double? {
+ val driven = toAlongM - fromAlongM
+ if (driven < PACE_MIN_M || elapsedS < PACE_MIN_S) return null
+ val planned = plannedSecondsAt(route, toAlongM) - plannedSecondsAt(route, fromAlongM)
+ if (planned < 30.0) return null
+ val raw = (elapsedS / planned).coerceIn(0.6, 2.0)
+ val weight = (driven / PACE_FULL_M).coerceIn(0.0, 1.0)
+ return 1.0 + (raw - 1.0) * weight
+ }
+
+ private const val PACE_MIN_M = 600.0
+ private const val PACE_MIN_S = 90.0
+ private const val PACE_FULL_M = 4_000.0
+
+ /** The point [m] along the route (clamped to its ends). */
+ fun pointAt(route: Route, m: Double): Pair<Double, Double> {
+ val a = route.along
+ if (m <= 0) return route.lats[0] to route.lons[0]
+ if (m >= a.last()) return route.end
+ var lo = 0; var hi = a.size - 1
+ while (hi - lo > 1) { val mid = (lo + hi) / 2; if (a[mid] <= m) lo = mid else hi = mid }
+ val t = (m - a[lo]) / (a[hi] - a[lo]).coerceAtLeast(1e-9)
+ return (route.lats[lo] + t * (route.lats[hi] - route.lats[lo])) to (route.lons[lo] + t * (route.lons[hi] - route.lons[lo]))
+ }
+
+ /**
+ * How far along [route] a point at ([lat], [lon]) lies, and how far off the line - for things on or
+ * beside the road (a camera, a Waze report). The whole route is searched.
+ */
+ fun project(route: Route, lat: Double, lon: Double): Pair<Double, Double> {
+ val s = locate(route, lat, lon, null, null)
+ return s.alongM to s.offM
+ }
+
+ internal fun angleDiff(a: Double, b: Double): Double = abs(((a - b) % 360 + 540) % 360 - 180)
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Sun.kt b/app/src/main/java/com/rfsentinel/app/nav/Sun.kt
new file mode 100644
index 0000000..8e375d5
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Sun.kt
@@ -0,0 +1,44 @@
+package com.rfsentinel.app.nav
+
+import kotlin.math.asin
+import kotlin.math.cos
+import kotlin.math.sin
+import kotlin.math.tan
+
+/**
+ * Where the sun is (pure, offline; NOAA's low-precision solar position formulas, good to about a
+ * tenth of a degree): so the map can turn to its night look after sunset while you are guided, with
+ * nothing asked of any server.
+ */
+object Sun {
+
+ /** The sun's height above the horizon in degrees (negative below it) at ([lat], [lon]) at [epochMs]. */
+ fun elevationDeg(lat: Double, lon: Double, epochMs: Long): Double {
+ val jd = epochMs / 86_400_000.0 + 2_440_587.5
+ val t = (jd - 2_451_545.0) / 36_525.0
+ val l0 = (280.46646 + t * (36_000.76983 + t * 0.0003032)).mod(360.0)
+ val m = Math.toRadians(357.52911 + t * (35_999.05029 - 0.0001537 * t))
+ val e = 0.016708634 - t * (0.000042037 + 0.0000001267 * t)
+ val c = sin(m) * (1.914602 - t * (0.004817 + 0.000014 * t)) + sin(2 * m) * (0.019993 - 0.000101 * t) + sin(3 * m) * 0.000289
+ val omega = Math.toRadians(125.04 - 1934.136 * t)
+ val lambda = Math.toRadians(l0 + c - 0.00569 - 0.00478 * sin(omega))
+ val eps0 = 23.0 + (26.0 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60.0) / 60.0
+ val eps = Math.toRadians(eps0 + 0.00256 * cos(omega))
+ val decl = asin(sin(eps) * sin(lambda))
+ val y = tan(eps / 2).let { it * it }
+ val l0r = Math.toRadians(l0)
+ val eqTimeMin = 4.0 * Math.toDegrees(
+ y * sin(2 * l0r) - 2 * e * sin(m) + 4 * e * y * sin(m) * cos(2 * l0r) - 0.5 * y * y * sin(4 * l0r) - 1.25 * e * e * sin(2 * m))
+ val utcMin = (epochMs / 60_000.0).mod(1440.0)
+ val trueSolarMin = (utcMin + eqTimeMin + 4.0 * lon).mod(1440.0)
+ val hourAngle = Math.toRadians(trueSolarMin / 4.0 - 180.0)
+ val latR = Math.toRadians(lat)
+ return Math.toDegrees(asin(sin(latR) * sin(decl) + cos(latR) * cos(decl) * cos(hourAngle)))
+ }
+
+ /** Past sunset, before sunrise: the sun is more than 3 degrees below the horizon (dusk is well on its way). */
+ fun isNight(lat: Double, lon: Double, epochMs: Long): Boolean = elevationDeg(lat, lon, epochMs) < NIGHT_BELOW_DEG
+
+ private const val NIGHT_BELOW_DEG = -3.0
+
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Valhalla.kt b/app/src/main/java/com/rfsentinel/app/nav/Valhalla.kt
new file mode 100644
index 0000000..3c5b3ef
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Valhalla.kt
@@ -0,0 +1,198 @@
+package com.rfsentinel.app.nav
+
+import com.google.gson.JsonArray
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+import com.rfsentinel.app.service.DeviceRegistry
+import org.json.JSONArray
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+
+/**
+ * Driving routes from Valhalla on the OpenStreetMap Germany (FOSSGIS) server: up to three routes,
+ * tolls, highways or ferries avoided if asked, and for each turn the lanes and ready-worded prompts
+ * ("In 500 meters, keep right"). No key or account; the server sees the start, the stops and the
+ * destination, and your IP. Only asked when you plan a route or leave it.
+ *
+ * Request building and parsing are pure Kotlin and unit-tested; [route] is plain blocking HTTP.
+ */
+object Valhalla {
+
+ const val URL = "https://valhalla1.openstreetmap.de/route"
+
+ /** Road types the route should avoid. */
+ data class Options(
+ val avoidTolls: Boolean = false,
+ val avoidHighways: Boolean = false,
+ val avoidFerries: Boolean = false,
+ /** How many other routes to offer besides the best (only with no stops on the way). */
+ val alternatives: Int = 2
+ )
+
+ class NoRouteException(message: String) : Exception(message)
+
+ // ---- the request ----------------------------------------------------------------------------
+
+ /**
+ * The request: from ([fromLat], [fromLon]) - going [headingDeg] when known, so the route doesn't
+ * begin with a U-turn - through [stops] to [to].
+ */
+ fun request(fromLat: Double, fromLon: Double, headingDeg: Double?, stops: List<Pair<Double, Double>>,
+ to: Pair<Double, Double>, options: Options, miles: Boolean = false): JSONObject {
+ val locations = JSONArray()
+ locations.put(JSONObject().put("lat", fromLat).put("lon", fromLon).apply {
+ if (headingDeg != null) { put("heading", Math.round(headingDeg).toInt()); put("heading_tolerance", 45) }
+ })
+ for ((la, lo) in stops) locations.put(JSONObject().put("lat", la).put("lon", lo).put("type", "break"))
+ locations.put(JSONObject().put("lat", to.first).put("lon", to.second))
+ fun use(avoid: Boolean) = if (avoid) 0.0 else 0.5
+ return JSONObject()
+ .put("locations", locations)
+ .put("costing", "auto")
+ .put("costing_options", JSONObject().put("auto", JSONObject()
+ .put("use_tolls", use(options.avoidTolls))
+ .put("use_highways", if (options.avoidHighways) 0.0 else 1.0)
+ .put("use_ferry", use(options.avoidFerries))))
+ .put("directions_options", JSONObject().put("units", if (miles) "miles" else "kilometers").put("language", "en-US"))
+ .put("format", "osrm")
+ .put("shape_format", "polyline6")
+ .put("banner_instructions", true)
+ .put("voice_instructions", true)
+ .put("turn_lanes", true)
+ .apply {
+ // Alternatives aren't offered on routes with stops.
+ if (stops.isEmpty() && options.alternatives > 0) put("alternates", options.alternatives)
+ }
+ }
+
+ // ---- network ----------------------------------------------------------------------------------
+
+ /** The routes, best first; throws [NoRouteException] when there is none, or on a network error. */
+ fun route(body: JSONObject, userAgent: String): List<Route> {
+ val c = (URL(URL).openConnection() as HttpURLConnection).apply {
+ requestMethod = "POST"
+ doOutput = true
+ connectTimeout = 10_000
+ readTimeout = 25_000
+ setRequestProperty("Content-Type", "application/json")
+ setRequestProperty("User-Agent", userAgent)
+ }
+ try {
+ c.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) }
+ val ok = c.responseCode in 200..299
+ val text = (if (ok) c.inputStream else c.errorStream ?: c.inputStream).bufferedReader(Charsets.UTF_8).use { it.readText() }
+ if (!ok) throw NoRouteException(errorOf(text) ?: "The route server answered HTTP ${c.responseCode}")
+ return parse(text)
+ } finally {
+ c.disconnect()
+ }
+ }
+
+ /** The server's own reason, when it gave one. */
+ internal fun errorOf(text: String): String? = runCatching {
+ val o = JsonParser.parseString(text).asJsonObject
+ (o.str("message") ?: o.str("error"))?.let { friendly(o.str("code"), it) }
+ }.getOrNull()
+
+ private fun friendly(code: String?, message: String) = when {
+ code == "NoRoute" || message.contains("No path", true) -> "No route found between these places"
+ message.contains("too far", true) || message.contains("exceeds the max", true) -> "Too far for the route server (it plans up to a few hundred km)"
+ else -> message
+ }
+
+ // ---- parsing (pure) ---------------------------------------------------------------------------
+
+ fun parse(json: String): List<Route> {
+ val root = JsonParser.parseString(json).asJsonObject
+ if (root.str("code") != "Ok") throw NoRouteException(friendly(root.str("code"), root.str("message") ?: "No route found"))
+ val routes = root.getAsJsonArray("routes") ?: throw NoRouteException("No route found")
+ return routes.map { parseRoute(it.asJsonObject) }.ifEmpty { throw NoRouteException("No route found") }
+ }
+
+ private fun parseRoute(r: JsonObject): Route {
+ val lats = ArrayList<Double>(); val lons = ArrayList<Double>(); val along = ArrayList<Double>()
+ fun add(la: Double, lo: Double) {
+ if (lats.isNotEmpty()) {
+ val d = DeviceRegistry.metersBetween(lats.last(), lons.last(), la, lo)
+ if (d < 0.01) return // the joint between two steps, already there
+ along += along.last() + d
+ } else along += 0.0
+ lats += la; lons += lo
+ }
+ val steps = ArrayList<Step>()
+ val legs = r.getAsJsonArray("legs") ?: JsonArray()
+ for ((legIndex, legEl) in legs.withIndex()) {
+ for (stEl in legEl.asJsonObject.getAsJsonArray("steps") ?: JsonArray()) {
+ val s = stEl.asJsonObject
+ val m = s.getAsJsonObject("maneuver") ?: JsonObject()
+ val loc = m.getAsJsonArray("location")
+ val startM = along.lastOrNull() ?: 0.0
+ val geometry = s.str("geometry")?.let { decodePolyline6(it) }.orEmpty()
+ if (geometry.isEmpty() && loc != null) add(loc[1].asDouble, loc[0].asDouble)
+ for ((la, lo) in geometry) add(la, lo)
+ steps += Step(
+ type = m.str("type") ?: "turn",
+ modifier = m.str("modifier"),
+ name = s.str("name").orEmpty(),
+ exit = m.get("exit")?.takeIf { it.isJsonPrimitive }?.asInt,
+ instruction = m.str("instruction").orEmpty(),
+ lat = loc?.get(1)?.asDouble ?: lats.lastOrNull() ?: 0.0,
+ lon = loc?.get(0)?.asDouble ?: lons.lastOrNull() ?: 0.0,
+ lengthM = s.num("distance") ?: 0.0,
+ durationS = s.num("duration") ?: 0.0,
+ startM = startM,
+ endM = along.lastOrNull() ?: startM,
+ leg = legIndex,
+ voice = (s.getAsJsonArray("voiceInstructions") ?: JsonArray()).mapNotNull { v ->
+ val o = v.asJsonObject
+ val text = o.str("announcement") ?: return@mapNotNull null
+ Step.Voice(o.num("distanceAlongGeometry") ?: 0.0, text)
+ }.sortedByDescending { it.beforeM },
+ banners = (s.getAsJsonArray("bannerInstructions") ?: JsonArray()).mapNotNull { b ->
+ val o = b.asJsonObject
+ val p = o.getAsJsonObject("primary") ?: return@mapNotNull null
+ val lanes = (o.getAsJsonObject("sub")?.getAsJsonArray("components") ?: JsonArray()).mapNotNull { c ->
+ val co = c.asJsonObject
+ if (co.str("type") != "lane") return@mapNotNull null
+ Step.Lane((co.getAsJsonArray("directions") ?: JsonArray()).map { it.asString },
+ co.get("active")?.takeIf { it.isJsonPrimitive }?.asBoolean == true, co.str("active_direction"))
+ }
+ Step.Banner(o.num("distanceAlongGeometry") ?: 0.0, p.str("text").orEmpty(), p.str("type") ?: "turn", p.str("modifier"), lanes)
+ }.sortedByDescending { it.beforeM },
+ drivingSide = s.str("driving_side") ?: "right"
+ )
+ }
+ }
+ if (lats.isEmpty()) throw NoRouteException("The route came back empty")
+ val summary = legs.mapNotNull { it.asJsonObject.str("summary") }.filter { it.isNotBlank() }.joinToString(", ")
+ return Route(lats.toDoubleArray(), lons.toDoubleArray(), along.toDoubleArray(),
+ r.num("distance") ?: along.last(), r.num("duration") ?: 0.0, steps, summary, lats.last() to lons.last())
+ }
+
+ /** Google's encoded-polyline format at six decimals (Valhalla's default): (lat, lon) pairs. */
+ fun decodePolyline6(s: String): List<Pair<Double, Double>> {
+ val out = ArrayList<Pair<Double, Double>>()
+ var i = 0; var lat = 0L; var lon = 0L
+ fun next(): Long {
+ var result = 0L; var shift = 0
+ while (true) {
+ val b = s[i++].code - 63
+ result = result or ((b and 0x1f).toLong() shl shift)
+ shift += 5
+ if (b < 0x20) break
+ }
+ return if (result and 1L != 0L) (result shr 1).inv() else result shr 1
+ }
+ while (i < s.length) {
+ lat += next()
+ if (i >= s.length) break
+ lon += next()
+ out += lat / 1e6 to lon / 1e6
+ }
+ return out
+ }
+
+ private fun JsonObject.str(k: String): String? = get(k)?.takeIf { it.isJsonPrimitive }?.asString
+ private fun JsonObject.num(k: String): Double? = get(k)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isNumber }?.asDouble
+}
diff --git a/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt b/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt
index 32ba863..b795b3f 100644
--- a/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt
@@ -37,7 +37,7 @@ internal class AheadOnRoad {
if (fresh != null) {
path = fresh
pathLat = me.latitude; pathLon = me.longitude; pathHeading = h; pathAt = now
- } else if (moved > KEEP_PATH_M || now - pathAt > KEEP_PATH_MS) {
+ } else if (!keepOldPath(moved, now - pathAt, RoadMatch.angleDiff(h, pathHeading))) {
// A tile that hasn't arrived yet shouldn't throw away a good answer: the last path stands
// for a short stretch, so a momentary gap doesn't drop every report to the plain corridor test.
path = null
@@ -91,6 +91,13 @@ internal class AheadOnRoad {
/** A path with no replacement yet stands for this long, and this far travelled, before it is dropped. */
private const val KEEP_PATH_MS = 15_000L
private const val KEEP_PATH_M = 100.0
+ /** ...and only while you still head the way it was worked out for: after a turn it describes a road you left. */
+ private const val KEEP_PATH_TURN_DEG = 35.0
+
+ /** Whether the path in hand may stand in for one that couldn't be worked out just now. */
+ internal fun keepOldPath(movedM: Double, ageMs: Long, headingDiffDeg: Double) =
+ movedM <= KEEP_PATH_M && ageMs <= KEEP_PATH_MS && headingDiffDeg <= KEEP_PATH_TURN_DEG
+
/** The most a fix's own accuracy widens how far from a road you can be and still be on it. */
private const val ACCURACY_ALLOWANCE_M = 30.0
/** The map is never fetched further ahead than this. */
diff --git a/app/src/main/java/com/rfsentinel/app/online/RouteAhead.kt b/app/src/main/java/com/rfsentinel/app/online/RouteAhead.kt
new file mode 100644
index 0000000..7c37b68
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/online/RouteAhead.kt
@@ -0,0 +1,46 @@
+package com.rfsentinel.app.online
+
+import com.rfsentinel.app.nav.Route
+import kotlin.math.cos
+
+/**
+ * While you are being guided, "ahead of me" is the route itself: a Waze report counts when it lies on the
+ * stretch of the route still in front of you. The route knows the turns (a report round the next corner
+ * is on your way, one on the street beside it is not) and it does not need the GPS to have a heading,
+ * which a phone standing at a light or crawling in traffic does not have.
+ */
+internal object RouteAhead {
+
+ /** A report is on the route when within this of its line: Waze puts it on the road, the line is the road's centre. */
+ const val CORRIDOR_M = 45.0
+ /** A report just behind your position still counts as here (GPS error, the report's own rounding). */
+ const val BEHIND_SLACK_M = 25.0
+
+ /**
+ * Where the report at ([lat], [lon]) is against the route, for you [alongM] along it: on your way within
+ * [reachM] ahead, behind you, or not on the route (or too far on it to matter yet). A route that passes
+ * the report twice (out and back) counts the first pass still in front of you.
+ */
+ fun verdict(route: Route, alongM: Double, lat: Double, lon: Double, reachM: Double): RoadMatch.Verdict {
+ val n = route.size
+ if (n < 2) return RoadMatch.Verdict.UNKNOWN
+ val kx = 111_320.0 * cos(Math.toRadians(lat)); val ky = 110_540.0
+ var nextAhead = Double.NaN
+ var anyBehind = false
+ for (i in 0 until n - 1) {
+ val x0 = (route.lons[i] - lon) * kx; val y0 = (route.lats[i] - lat) * ky
+ val dx = (route.lons[i + 1] - route.lons[i]) * kx; val dy = (route.lats[i + 1] - route.lats[i]) * ky
+ val l2 = dx * dx + dy * dy
+ val t = if (l2 < 1e-9) 0.0 else ((-x0 * dx - y0 * dy) / l2).coerceIn(0.0, 1.0)
+ val px = x0 + t * dx; val py = y0 + t * dy
+ if (px * px + py * py > CORRIDOR_M * CORRIDOR_M) continue
+ val a = route.along[i] + t * (route.along[i + 1] - route.along[i])
+ if (a >= alongM - BEHIND_SLACK_M) { if (nextAhead.isNaN() || a < nextAhead) nextAhead = a } else anyBehind = true
+ }
+ return when {
+ !nextAhead.isNaN() -> if (nextAhead - alongM <= reachM) RoadMatch.Verdict.ON_MY_ROAD else RoadMatch.Verdict.OTHER_ROAD
+ anyBehind -> RoadMatch.Verdict.BEHIND
+ else -> RoadMatch.Verdict.OTHER_ROAD
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt b/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt
index 1972e9c..eceed03 100644
--- a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt
@@ -164,11 +164,20 @@ object WazePolice {
val hit: Hit,
val where: Where,
val trend: WazeTrend.Trend = WazeTrend.Trend.STEADY,
- val level: Level = Level.LOUD
+ val level: Level = Level.LOUD,
+ /** On your way (ahead, on your road or your route) - only worked out, and only meaningful, when "only ahead" is on. */
+ val onMyWay: Boolean = true
) {
val distanceM: Double get() = where.distanceM
}
+ /**
+ * What the main list shows: the reports inside [alertM]; with [aheadOnly] on, the ones not on your way
+ * are left out when [hideOffWay] is set (else they are listed, quiet and marked).
+ */
+ fun forList(all: List<Shown>, alertM: Double, aheadOnly: Boolean, hideOffWay: Boolean): List<Shown> =
+ all.filter { it.distanceM <= alertM && !(aheadOnly && hideOffWay && !it.onMyWay) }
+
/** The current reports (every enabled type, inside the view range). */
@Volatile var latest: List<Shown> = emptyList()
private set
diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
index fc9f36c..94d1c85 100644
--- a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
@@ -4,6 +4,7 @@ import android.content.Context
import android.location.Location
import android.os.SystemClock
import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.nav.Navigator
import com.rfsentinel.app.online.wazert.WazeRtFetcher
import com.rfsentinel.app.util.Prefs
import com.rfsentinel.app.util.SecureStore
@@ -246,14 +247,18 @@ class WazeWatch(
}
trend.keepOnly(known.keys)
- // Only ahead: on the road you're on, ahead of you (the map's roads); where the map can't tell
+ // Only ahead: while you are guided, on the route in front of you (it knows the turns, and needs no GPS
+ // heading); otherwise on the road you're on, ahead of you (the map's roads); where the map can't tell
// (no data yet, not driving), inside a corridor along your heading.
- val verdicts = if (aheadOnly) road.verdicts(context, me, alertM, shown.map { it.report }) else emptyMap()
+ val onRoute = if (aheadOnly) routeVerdicts(shown, alertM) else emptyMap()
+ val verdicts = if (aheadOnly && onRoute.isEmpty()) road.verdicts(context, me, alertM, shown.map { it.report }) else onRoute
fun quiet(s: WazePolice.Shown) = when (verdicts[s.report.id]) {
RoadMatch.Verdict.ON_MY_ROAD -> false
RoadMatch.Verdict.OTHER_ROAD, RoadMatch.Verdict.BEHIND -> true
else -> !s.where.maybeOnMyWay()
}
+ // The list shows what counts as on your way; the map keeps the wider picture.
+ for (i in shown.indices) shown[i] = shown[i].copy(onMyWay = !(aheadOnly && quiet(shown[i])))
// In the alert range, and (if asked) ahead on your road.
fun counts(s: WazePolice.Shown) = s.distanceM <= alertM && !(aheadOnly && quiet(s))
@@ -263,7 +268,7 @@ class WazeWatch(
* is on the list and the map meanwhile, and after the wait the corridor test decides as before.
*/
fun waitingForRoad(s: WazePolice.Shown): Boolean {
- if (!aheadOnly || !road.waitingForRoads) return false
+ if (!aheadOnly || onRoute.isNotEmpty() || !road.waitingForRoads) return false // the route needs no map data
val v = verdicts[s.report.id]
if (v != null && v != RoadMatch.Verdict.UNKNOWN) return false
return now - heldSince.getOrPut(s.report.id) { now } < ROAD_HOLD_MS
@@ -327,6 +332,17 @@ class WazeWatch(
}
}
+ /**
+ * Each report's place against the route you are following ([RouteAhead]); none when you are not being
+ * guided, have just left the route (it is being re-planned), or have arrived - the roads decide then.
+ */
+ private fun routeVerdicts(shown: List<WazePolice.Shown>, alertM: Double): Map<String, RoadMatch.Verdict> {
+ val route = Navigator.route ?: return emptyMap()
+ val st = Navigator.state ?: return emptyMap()
+ if (!Navigator.active || Navigator.arrived || st.offM > Navigator.OFF_ROUTE_M) return emptyMap()
+ return shown.associate { it.report.id to RouteAhead.verdict(route, st.alongM, it.report.lat, it.report.lon, alertM * 1.5) }
+ }
+
/** Reports are dropped when no check has answered for this long (a little over three intervals, never under 10 minutes). */
private fun staleAfterMs(now: Long) = maxOf(10 * 60_000L, WazeTiming.effectiveS(
Prefs.wazeIntervalS(context, direct), motion.state(now), direct, Prefs.wazeAdaptive(context)) * 3_500L)
diff --git a/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt b/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
index dd67398..9f39b45 100644
--- a/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
@@ -5,7 +5,7 @@ import android.content.Context
import android.location.GnssMeasurementsEvent
import android.location.GnssStatus
import android.location.Location
-import android.location.LocationListener
+import androidx.core.location.LocationListenerCompat
import android.location.LocationManager
import android.os.Build
import android.os.Handler
@@ -67,7 +67,7 @@ object GnssWatch {
}
}
- private val fixListener = LocationListener { loc: Location ->
+ private val fixListener = LocationListenerCompat { loc: Location ->
if (loc.provider == LocationManager.GPS_PROVIDER)
emit(analyzer.onFix(GnssAnalyzer.Fix(loc.time, System.currentTimeMillis(), loc.latitude, loc.longitude, loc.accuracy)))
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 4282787..f27b535 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -12,7 +12,7 @@ import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.location.Location
-import android.location.LocationListener
+import androidx.core.location.LocationListenerCompat
import android.location.LocationManager
import android.os.Build
import android.os.Handler
@@ -196,7 +196,7 @@ class ScanForegroundService : Service() {
/** Radar-detector sound style: last good GPS fix, to say "GPS connected" when it locks or comes back. */
private var lastGoodGpsAt = 0L
- private val locationListener = LocationListener {
+ private val locationListener = LocationListenerCompat {
if (it.provider == LocationManager.GPS_PROVIDER && it.hasAccuracy() && it.accuracy <= 50f) {
val now = System.currentTimeMillis()
if (now - lastGoodGpsAt > GPS_RECONNECT_MS) AlertPlayer.gpsConnected(this)
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index 5ed1f4e..708f575 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -28,6 +28,7 @@ class SettingsActivity : AppCompatActivity() {
/** Opens Settings on one section (expanded and scrolled to): e.g. [SECTION_MAP] from the map. */
const val EXTRA_SECTION = "open_section"
const val SECTION_MAP = "map"
+ const val SECTION_NAV = "navigation"
const val SECTION_DATA = "data"
const val WAZE_WARNING_SHORT = "Use at your own risk. Reports come from third-party services RF Sentinel doesn't run or endorse " +
"(OpenWeb Ninja with your own key, or Waze itself); your account, your responsibility."
@@ -453,6 +454,19 @@ class SettingsActivity : AppCompatActivity() {
Section("follow", binding.headerFollow, binding.sectionFollow,
"Warns when a tracker or flagged device keeps moving with you for at least the time and distance set here.\n\n" +
"Your own tag: long-press it in the list > Ignore this tracker."),
+ Section("navigation", binding.headerNav, binding.sectionNav,
+ "Turn-by-turn directions: the search button on the map finds a place (or long-press the map), shows up to three " +
+ "routes with the time each takes, and guides you with a banner, lane arrows and spoken directions.\n\n" +
+ "Spoken directions play through the navigation voice (music dips under them, as in Maps) and follow the voice " +
+ "speed and loudness chosen under Alerts. They are separate from the alert mute and snooze.\n\n" +
+ "Network use: routes come from Valhalla on the OpenStreetMap Germany server and places from Photon (komoot), and OpenStreetMap's Nominatim too for a search you submit. They " +
+ "see what you search for, where you start, stop and finish, and your IP address - never what you scan. Nothing is " +
+ "asked until you search, long-press the map or start a route; search sends your position rounded to about 1 km.\n\n" +
+ "Looking for petrol, charging, food and the like asks OpenStreetMap's Overpass servers (as the camera downloads do): " +
+ "your position rounded to about 1 km, or the road ahead as points rounded to about 200 m.\n\n" +
+ "Not included: live traffic (the arrival time starts from the route's usual driving time and then follows how you really " +
+ "drive), speed limits and offline routes.\n\n" +
+ "Home, Work, starred and recent places are kept on this phone only."),
Section("map", binding.headerMap, binding.sectionMap,
"What the map shows.\n\n" +
"Plate, speed and red-light cameras: from OpenStreetMap (Known cameras has the downloads, warnings and CCTV).\n\n" +
@@ -903,6 +917,68 @@ class SettingsActivity : AppCompatActivity() {
}
}
+ /** Settings > Navigation: directions, route preferences, distance units and the places kept for it. */
+ private fun setupNavSection() {
+ val box = binding.sectionNav
+ val dp = resources.displayMetrics.density
+ fun label(t: String, small: Boolean = false) = android.widget.TextView(this).apply {
+ text = t; textSize = if (small) 12f else 14f
+ if (small) alpha = 0.75f
+ setPadding(0, (if (small) 0 else 10 * dp).toInt(), 0, (2 * dp).toInt())
+ }.also { box.addView(it) }
+ fun switch(t: String, on: Boolean, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
+ text = t; isChecked = on
+ setOnCheckedChangeListener { _, v -> save(v) }
+ }.also { box.addView(it) }
+
+ switch("Spoken directions", Prefs.navVoice(this)) { Prefs.setNavVoice(this, it) }
+ switch("Start scanning when a destination is started", Prefs.navStartScan(this)) { Prefs.setNavStartScan(this, it) }
+ label("A scan that is already running is left alone, and the scan keeps going after you arrive.", small = true)
+ switch("Keep the screen on while guiding", Prefs.navKeepScreenOn(this)) { Prefs.setNavKeepScreenOn(this, it) }
+ switch("Night map after sunset while guiding", Prefs.navAutoNight(this)) { Prefs.setNavAutoNight(this, it) }
+ label("Worked out on the phone from your position and the time. Pressing the sun / moon button on the map keeps " +
+ "the look you chose instead.", small = true)
+ label("Routes avoid (ticking one while you plan a route is remembered here for the next one)")
+ switch("Tolls", Prefs.navAvoidTolls(this)) { Prefs.setNavAvoidTolls(this, it) }
+ switch("Highways", Prefs.navAvoidHighways(this)) { Prefs.setNavAvoidHighways(this, it) }
+ switch("Ferries", Prefs.navAvoidFerries(this)) { Prefs.setNavAvoidFerries(this, it) }
+
+ label("Distances in")
+ val units = listOf("auto" to "Automatic (by the phone's region)", "km" to "Kilometres", "mi" to "Miles")
+ val group = android.widget.RadioGroup(this)
+ for ((key, text) in units) {
+ group.addView(android.widget.RadioButton(this).apply {
+ id = View.generateViewId(); this.text = text; tag = key
+ isChecked = Prefs.navUnits(this@SettingsActivity) == key
+ })
+ }
+ group.setOnCheckedChangeListener { g, id -> g.findViewById<View>(id)?.tag?.let { Prefs.setNavUnits(this, it as String) } }
+ box.addView(group)
+
+ label("Places")
+ val places = android.widget.TextView(this).apply { textSize = 13f; alpha = 0.8f }
+ fun showPlaces() {
+ places.text = "Home: ${Prefs.navHome(this@SettingsActivity)?.name ?: "not set"}\n" +
+ "Work: ${Prefs.navWork(this@SettingsActivity)?.name ?: "not set"}\n" +
+ "${Prefs.navFavorites(this@SettingsActivity).size} starred · ${Prefs.recentDestinations(this@SettingsActivity).size} recent"
+ }
+ showPlaces()
+ box.addView(places)
+ box.addView(com.google.android.material.button.MaterialButton(this, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {
+ text = "Forget saved and recent places"
+ setOnClickListener {
+ AlertDialog.Builder(this@SettingsActivity)
+ .setTitle("Forget your places?")
+ .setMessage("Removes Home, Work, starred and recent destinations from this phone.")
+ .setPositiveButton("Forget") { _, _ ->
+ Prefs.clearNavPlaces(this@SettingsActivity); Prefs.clearRecentDestinations(this@SettingsActivity); showPlaces()
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+ })
+ }
+
/** Settings > Map: what the map shows (moved here from the map's menu). Saved as you switch. */
private fun setupMapSection() {
setupMapProvider()
@@ -1243,9 +1319,15 @@ class SettingsActivity : AppCompatActivity() {
Prefs.wazeAdaptive(this)) { Prefs.setWazeAdaptive(this, it) }
switchRow("Only alert for reports ahead of me",
"While you drive, only reports on the road you're on, ahead of you, alert, flash or speak - checked on the map's " +
- "roads, so one on a parallel road, a cross street, an overpass or behind you stays quiet (it stays on the list). " +
- "Where the map can't tell yet, reports behind you stay quiet.",
+ "roads, so one on a parallel road, a cross street, an overpass or behind you stays quiet (it stays on the list, " +
+ "marked \"not on your way\" unless you hide them below). While you are being guided to a destination the route " +
+ "decides: only reports on the part of it still ahead count, round corners too. Where the map can't tell yet, " +
+ "reports behind you stay quiet.",
Prefs.wazeAheadOnly(this)) { Prefs.setWazeAheadOnly(this, it) }
+ switchRow("Hide reports that aren't on my way",
+ "With the switch above on, a report behind you, on another street or off your route is left off the list (the map " +
+ "still shows it). Off: it stays listed, quiet, marked \"not on your way\".",
+ Prefs.wazeHideOffWay(this)) { Prefs.setWazeHideOffWay(this, it) }
switchRow("Call out again as I get closer",
"Speaks at 1 km, 500 m and 200 m when voice alerts are on, or in the car.",
Prefs.wazeApproach(this)) { Prefs.setWazeApproach(this, it) }
@@ -1628,6 +1710,7 @@ class SettingsActivity : AppCompatActivity() {
binding.speedCameraSwitch.isChecked = Prefs.speedCameraAlerts(this)
binding.autoCamerasSwitch.isChecked = Prefs.autoCameras(this)
setupMapSection()
+ setupNavSection()
setupRadioSection()
setupLiveExport()
binding.hideTrustedSwitch.isChecked = Prefs.hideWhitelisted(this)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt
index 78043e5..78fb589 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt
@@ -20,8 +20,10 @@ object AboutDialog {
on this phone. Internet is used only for map data: the map (OpenFreeMap, or Mapbox if
you choose it in Settings), the road tiles of your area while the Waze "only ahead"
option is on, and the list of known plate, speed and red-light cameras for the area you look at on
- screen; in Android Auto, destination search (Nominatim) and routes (OSRM) when you
- navigate. Those servers see your IP and that area or trip, never your scans or detections.
+ screen; and, when you search for a destination or start a route (on the phone or in Android
+ Auto), the place search (Photon, and Nominatim for a search you submit), places of one kind near you or ahead on your route (the same
+ OpenStreetMap servers as the cameras) and the route (Valhalla, on the OpenStreetMap Germany server).
+ Those servers see your IP and that area or trip, never your scans or detections.
Map data &copy; OpenStreetMap contributors (ODbL), &copy; OpenMapTiles; map engine
MapLibre Native (BSD-2-Clause), OpenFreeMap; Mapbox Maps SDK (Mapbox terms) when selected.<br/><br/>
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt b/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt
new file mode 100644
index 0000000..6d9ecb5
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt
@@ -0,0 +1,154 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.graphics.PorterDuff
+import android.graphics.drawable.GradientDrawable
+import android.location.Location
+import android.os.Handler
+import android.os.Looper
+import android.view.View
+import com.rfsentinel.app.R
+import com.rfsentinel.app.car.CarUi
+import com.rfsentinel.app.databinding.ActivityMapBinding
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.DeviceIntel
+import com.rfsentinel.app.detect.Tier
+import com.rfsentinel.app.nav.NavFormat
+import com.rfsentinel.app.nav.Navigator
+import com.rfsentinel.app.online.RoadMatch
+import com.rfsentinel.app.online.RouteAhead
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.util.Prefs
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * Alerts as they come in, for screens that want to show them (the full screen map): every alert RF Sentinel
+ * raises - a flagged device, a known camera, a Waze report, a cell warning - is published here once.
+ */
+object AlertCards {
+
+ data class Card(
+ val key: String, val mac: String?, val label: String, val evidence: String, val category: Category,
+ val confidence: Int, val following: Boolean, val rssi: Int?, val lat: Double?, val lon: Double?, val atMs: Long
+ )
+
+ private val main = Handler(Looper.getMainLooper())
+ private val listeners = CopyOnWriteArrayList<(Card) -> Unit>()
+
+ /** The newest alert, so a screen that opens a moment after one can still show it. */
+ @Volatile var latest: Card? = null
+ private set
+
+ /** Any thread; listeners are called on the main thread. */
+ fun publish(card: Card) {
+ latest = card
+ main.post { listeners.forEach { runCatching { it(card) } } }
+ }
+
+ /** Calls [onAlert] for each new alert; returns the function that stops it. */
+ fun addListener(onAlert: (Card) -> Unit): () -> Unit {
+ listeners.add(onAlert)
+ return { listeners.remove(onAlert) }
+ }
+}
+
+/**
+ * The alert card over the full screen map: a rounded dark card under the turn banner with what it is, how
+ * sure, and where, that goes by itself after a few seconds (longer for a strong match or something following
+ * you) or when dismissed; a tap on it looks at the place on the map. Respects Discreet mode (just "New
+ * alert") and the alert snooze. Silent: the sound and voice are the alert's own.
+ */
+internal class AlertCardController(
+ private val ctx: Context,
+ private val b: ActivityMapBinding,
+ private val fix: () -> Location?,
+ private val lookAt: (Double, Double) -> Unit
+) {
+ private val main = Handler(Looper.getMainLooper())
+ private val d = ctx.resources.displayMetrics.density
+ private val hideLater = Runnable { hide() }
+ private var current: AlertCards.Card? = null
+
+ init {
+ b.alertClose.setOnClickListener { hide() }
+ b.alertCard.setOnClickListener { current?.let { c -> if (c.lat != null && c.lon != null) lookAt(c.lat, c.lon) } }
+ }
+
+ fun show(c: AlertCards.Card) {
+ if (System.currentTimeMillis() < Prefs.alertsSnoozedUntil(ctx)) return
+ current = c
+ val discreet = Prefs.discreetMode(ctx)
+ val color = c.category.colorArgb
+
+ b.alertContext.text = contextOf(c)
+ b.alertTag.text = if (discreet) "" else c.category.shortTag
+ b.alertTag.setTextColor(color)
+ b.alertTitle.text = if (discreet) "New alert" else if (c.following) "Following you: ${c.label}" else c.label
+ val detail = if (discreet) "" else listOfNotNull(distanceOf(c), c.evidence.takeIf { it.isNotBlank() }).joinToString(" · ")
+ b.alertDetail.text = detail
+ b.alertDetail.visibility = if (detail.isBlank()) View.GONE else View.VISIBLE
+ val footer = if (discreet) "" else footerOf(c)
+ b.alertFooter.text = footer
+ b.alertFooter.visibility = if (footer.isBlank()) View.GONE else View.VISIBLE
+ b.alertFooter.setCompoundDrawablesRelativeWithIntrinsicBounds(dot(color), null, null, null)
+
+ b.alertIcon.setImageResource(iconOf(c.category))
+ b.alertIcon.setColorFilter(color, PorterDuff.Mode.SRC_IN)
+ b.alertIcon.background = GradientDrawable().apply { cornerRadius = 12 * d; setColor((color and 0x00FFFFFF) or 0x33000000) }
+
+ b.alertCard.animate().cancel()
+ if (b.alertCard.visibility != View.VISIBLE) {
+ b.alertCard.alpha = 0f; b.alertCard.translationY = -12 * d
+ b.alertCard.visibility = View.VISIBLE
+ b.alertCard.animate().alpha(1f).translationY(0f).setDuration(180).start()
+ } else b.alertCard.alpha = 1f
+ main.removeCallbacks(hideLater)
+ main.postDelayed(hideLater, if (c.following || c.confidence >= Tier.STRONG.min) LONG_MS else SHORT_MS)
+ }
+
+ fun hide() {
+ main.removeCallbacks(hideLater)
+ current = null
+ b.alertCard.animate().cancel()
+ b.alertCard.visibility = View.GONE
+ }
+
+ /** "FOLLOWING YOU", "ON YOUR ROUTE" (guided, and it is on the part still ahead), else "NEARBY". */
+ private fun contextOf(c: AlertCards.Card): String {
+ if (c.following) return "FOLLOWING YOU"
+ val route = Navigator.route; val st = Navigator.state
+ if (c.lat != null && c.lon != null && Navigator.active && route != null && st != null && st.offM <= Navigator.OFF_ROUTE_M &&
+ RouteAhead.verdict(route, st.alongM, c.lat, c.lon, 2_000.0) == RoadMatch.Verdict.ON_MY_ROAD) return "ON YOUR ROUTE"
+ return "NEARBY"
+ }
+
+ /** How far it is: a device's own estimate, or the straight line to a place on the map. */
+ private fun distanceOf(c: AlertCards.Card): String? {
+ c.mac?.let { m -> DeviceRegistry.get(m)?.distanceM?.takeIf { it > 0 }?.let { return DeviceIntel.formatDistance(it) } }
+ val me = fix() ?: return null
+ if (c.lat == null || c.lon == null) return null
+ return NavFormat.distance(DeviceRegistry.metersBetween(me.latitude, me.longitude, c.lat, c.lon), NavFormat.miles(ctx))
+ }
+
+ /** "Strong match · 2 more flagged nearby". */
+ private fun footerOf(c: AlertCards.Card): String {
+ val tier = Tier.of(c.confidence).label.substringBefore(" -").replaceFirstChar { it.uppercase() } + " match"
+ val others = DeviceRegistry.snapshot().count { CarUi.isFlagged(it) && !it.mac.equals(c.mac, ignoreCase = true) }
+ return listOfNotNull(tier, others.takeIf { it > 0 }?.let { "$it more flagged nearby" }).joinToString(" · ")
+ }
+
+ private fun iconOf(cat: Category) = when (cat) {
+ Category.DRONE -> R.drawable.ic_car_drone
+ Category.CELL_ANOMALY, Category.GNSS -> R.drawable.ic_car_tower
+ else -> R.drawable.ic_car_warning
+ }
+
+ private fun dot(color: Int) = GradientDrawable().apply {
+ shape = GradientDrawable.OVAL; setColor(color); setSize((8 * d).toInt(), (8 * d).toInt())
+ }
+
+ private companion object {
+ const val SHORT_MS = 8_000L
+ const val LONG_MS = 12_000L
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt b/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt
index 8845e7b..6a3c50b 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt
@@ -28,6 +28,23 @@ object DemoData {
*/
@Volatile var fakeLocation: android.location.Location? = null
+ private var sampleAlertNo = 0
+
+ /** DEBUG: one made-up alert for the full screen map's alert card, in turn: a device, a camera ahead, something following you. */
+ fun publishSampleAlert(anchor: Pair<Double, Double>?) {
+ val n = sampleAlertNo++ % 3
+ val card = when (n) {
+ 0 -> com.rfsentinel.app.ui.AlertCards.Card("demo:0", "60:60:1F:00:00:01", "Axon body camera", "BWCDEVICE tag in advert payload",
+ com.rfsentinel.app.detect.Category.BODY_CAM, 92, false, -58, null, null, System.currentTimeMillis())
+ 1 -> com.rfsentinel.app.ui.AlertCards.Card("demo:1", null, "Speed camera (50 km/h) ahead", "Mapped · OSM · limit 50 km/h",
+ com.rfsentinel.app.detect.Category.ALPR, 70, false, null,
+ anchor?.let { it.first + 0.0043 }, anchor?.second, System.currentTimeMillis())
+ else -> com.rfsentinel.app.ui.AlertCards.Card("demo:2", "60:60:1F:00:00:02", "Item tracker", "Seen with you for 9 minutes",
+ com.rfsentinel.app.detect.Category.TRACKER, 85, true, -70, null, null, System.currentTimeMillis())
+ }
+ com.rfsentinel.app.ui.AlertCards.publish(card)
+ }
+
/** A drone circling ~120 m from [anchor], with its operator ~80 m the other way. */
private fun demoRemoteId(anchor: Pair<Double, Double>, secondsAgo: Int): RemoteId.Info {
val angle = Math.toRadians(135.0 + secondsAgo * 2.0)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
index 018242a..af9d708 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
@@ -25,7 +25,6 @@ import android.widget.Toast
import androidx.core.content.edit
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.Prefs
-import org.maplibre.android.MapLibre
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
@@ -135,6 +134,7 @@ object FloatingMap {
runCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(r) }
view?.let { v -> runCatching { v.onPause(); v.onStop(); v.onDestroy() } }
root = null; view = null; map = null; badge = null; waiting = null; border = null
+ MapSafety.disarm(context)
ScanForegroundService.mapHidden(context)
}
@@ -161,7 +161,10 @@ object FloatingMap {
y = prefs.getInt("y", dp(context, 120f))
}
- MapLibre.getInstance(context)
+ // A start-up the app did not survive (a Vulkan phone that cannot run it): first OpenGL, then this stays off.
+ if (MapSafety.recover(context) == MapSafety.Recovery.MAP_OFF) { Prefs.setFloatingMap(context, false); return null }
+ MapSafety.arm(context, MapEngine.Provider.OPENFREEMAP)
+ MapLibreEngine.start(context)
val radius = 18f * d
val frame = FrameLayout(context).apply {
background = GradientDrawable().apply { cornerRadius = radius; setColor(Color.BLACK) }.also { border = it }
@@ -180,6 +183,7 @@ object FloatingMap {
.scrollGesturesEnabled(false).zoomGesturesEnabled(false).rotateGesturesEnabled(false).tiltGesturesEnabled(false))
m.onCreate(null)
m.getMapAsync { lm ->
+ main.postDelayed({ if (root != null) MapSafety.worked(context) }, MapSafety.SETTLE_MS) // its start-up is over
map = lm
val night = (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
lm.setStyle(Style.Builder().fromUri(if (night) MapLibreEngine.DARK_STYLE else MapLibreEngine.LIGHT_STYLE)) { style ->
diff --git a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
index 6731f8f..7edf9fd 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
@@ -2,7 +2,7 @@ package com.rfsentinel.app.ui
import android.annotation.SuppressLint
import android.graphics.Typeface
-import android.location.LocationListener
+import androidx.core.location.LocationListenerCompat
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
@@ -40,7 +40,7 @@ class GnssActivity : AppCompatActivity() {
}
private var rows: List<Row> = emptyList()
- private val gpsOn = LocationListener { }
+ private val gpsOn = LocationListenerCompat { }
private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun getItemCount() = rows.size
diff --git a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt
index bac56f8..eb5f4e5 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt
@@ -59,7 +59,7 @@ class HistoryActivity : AppCompatActivity() {
e.onClick = { x, y -> onTap(e, x, y) }
val dark = Prefs.mapDark(this) ?: ((resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==
android.content.res.Configuration.UI_MODE_NIGHT_YES)
- if (dark) { binding.mapCredit.setBackgroundColor(0x99000000.toInt()); binding.mapCredit.setTextColor(0xFFDDDDDD.toInt()) }
+ if (dark) { binding.mapCredit.setBackgroundColor(0x40000000); binding.mapCredit.setTextColor(0xFFDDDDDD.toInt()) }
// Mapbox's logo and info button, top left of the map.
binding.mapCredit.post { if (!isDestroyed) e.placeBranding(0) }
e.setStyle(dark) { fresh ->
@@ -119,8 +119,10 @@ class HistoryActivity : AppCompatActivity() {
"heatmap-color":["interpolate",["linear"],["heatmap-density"],
0,"rgba(0,0,0,0)",0.1,"rgba(32,32,160,0.13)",0.3,"rgba(0,229,255,0.44)",
0.55,"rgba(0,208,96,0.56)",0.8,"rgba(255,224,0,0.69)",1,"rgba(255,32,32,0.88)"]}}"""))
+ // Mapbox's night look is lit: a dot that gives off no light of its own goes black on it, so there it glows.
+ val glow = if (m.provider == MapEngine.Provider.MAPBOX) "\"circle-emissive-strength\":1," else ""
m.addLayer(JSONObject("""{"id":"$POINTS","type":"circle","source":"$POINTS","paint":{
- "circle-color":["to-color",["get","color"]],"circle-radius":6,
+ $glow"circle-color":["to-color",["get","color"]],"circle-radius":6,
"circle-stroke-color":"#FFFFFF","circle-stroke-width":1.5,"circle-pitch-alignment":"viewport"}}"""))
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
index b0824cb..ddd5ecc 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
@@ -23,6 +23,11 @@ class MapActivity : AppCompatActivity() {
const val EXTRA_AIRCRAFT = MapFragment.EXTRA_AIRCRAFT
/** Open the map on a Waze report (its id), with its details while it's current. */
const val EXTRA_WAZE = MapFragment.EXTRA_WAZE
+ /** Open the map on a place to plan a route to: name, address, latitude, longitude. */
+ const val EXTRA_NAV_NAME = MapFragment.EXTRA_NAV_NAME
+ const val EXTRA_NAV_ADDRESS = MapFragment.EXTRA_NAV_ADDRESS
+ const val EXTRA_NAV_LAT = MapFragment.EXTRA_NAV_LAT
+ const val EXTRA_NAV_LON = MapFragment.EXTRA_NAV_LON
/**
* The map on what an internet alert is about - [key] "air:<ICAO address>" or "waze:<report id>" -
@@ -50,12 +55,18 @@ class MapActivity : AppCompatActivity() {
val host = androidx.fragment.app.FragmentContainerView(this).apply { id = com.rfsentinel.app.R.id.mapHost }
setContentView(host)
if (savedInstanceState == null) {
- supportFragmentManager.beginTransaction()
- .replace(com.rfsentinel.app.R.id.mapHost, MapFragment.create(intent.extras ?: Bundle()))
- .commit()
+ // The app closed while the map was starting last time: say so (and try with OpenGL, or ask before trying again).
+ MapSafetyUi.tell(this, MapSafety.recover(this), onTryAgain = { addMap() }, onNotNow = { finish() })
}
}
+ private fun addMap() {
+ if (isFinishing || isDestroyed) return
+ supportFragmentManager.beginTransaction()
+ .replace(com.rfsentinel.app.R.id.mapHost, MapFragment.create(intent.extras ?: Bundle()))
+ .commitAllowingStateLoss()
+ }
+
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) { finish(); return true }
return super.onOptionsItemSelected(item)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt
index 322fa96..a7386bd 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt
@@ -78,7 +78,8 @@ internal interface MapEngine {
/** Animated; null keeps that part. [flat] also drops any padding. */
fun easeTo(lat: Double? = null, lon: Double? = null, zoom: Double? = null, bearing: Double? = null,
tilt: Double? = null, flat: Boolean = false, ms: Long = 600)
- fun fit(points: List<Pair<Double, Double>>, paddingPx: Int)
+ /** Frames [points]; [bottomPx] leaves more room at the bottom (under a card), [paddingPx] the rest. */
+ fun fit(points: List<Pair<Double, Double>>, paddingPx: Int, bottomPx: Int = paddingPx)
fun visibleBox(): Box?
fun toLatLon(x: Float, y: Float): Pair<Double, Double>?
fun setMinZoom(zoom: Double)
@@ -86,6 +87,8 @@ internal interface MapEngine {
var onCameraMove: (() -> Unit)?
var onIdle: (() -> Unit)?
var onClick: ((x: Float, y: Float) -> Unit)?
+ /** A long press on the map, at this place (to drop a pin and ask for directions). */
+ var onLongClick: ((lat: Double, lon: Double) -> Unit)?
/** A gesture (pinch...) moved the map while following. */
var onUserGesture: (() -> Unit)?
@@ -102,7 +105,7 @@ internal interface MapEngine {
/** You panned away: the map stopped following. */
var onFollowDismissed: (() -> Unit)?
/** Where the provider's logo and info button go (Mapbox: under the credit line). */
- fun placeBranding(topPx: Int)
+ fun placeBranding(topPx: Int, atEnd: Boolean = false)
companion object {
val mapboxAvailable get() = BuildConfig.MAPBOX_TOKEN.isNotEmpty()
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
index cbd81e5..e08dd29 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
@@ -3,7 +3,7 @@ package com.rfsentinel.app.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.location.Location
-import android.location.LocationListener
+import androidx.core.location.LocationListenerCompat
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
@@ -20,6 +20,7 @@ import androidx.appcompat.app.AlertDialog
import androidx.core.view.MenuProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
+import androidx.core.view.children
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
@@ -29,6 +30,10 @@ import com.rfsentinel.app.data.AppDatabase
import com.rfsentinel.app.data.TripDeviceEntity
import com.rfsentinel.app.data.TripEntity
import com.rfsentinel.app.databinding.ActivityMapBinding
+import com.rfsentinel.app.nav.NavCamera
+import com.rfsentinel.app.nav.NavSearchActivity
+import com.rfsentinel.app.nav.Navigator
+import com.rfsentinel.app.nav.Place
import com.rfsentinel.app.detect.Category
import com.rfsentinel.app.detect.Tier
import com.rfsentinel.app.service.DeviceRegistry
@@ -77,6 +82,11 @@ class MapFragment : Fragment() {
const val EXTRA_AIRCRAFT = "aircraft"
/** A Waze report's id: the map opens on it ([EXTRA_CENTER_LAT] / [EXTRA_CENTER_LON]) with its details while it's current. */
const val EXTRA_WAZE = "waze"
+ /** Open the map on a place to get directions to: plans the routes to it at once. */
+ const val EXTRA_NAV_NAME = "nav_name"
+ const val EXTRA_NAV_ADDRESS = "nav_address"
+ const val EXTRA_NAV_LAT = "nav_lat"
+ const val EXTRA_NAV_LON = "nav_lon"
/** Inside the main screen (its chips drive the filter; the menu is a button on the map). */
const val ARG_EMBEDDED = "embedded"
/** A failed camera download stays in the status line this long (the retry runs after a minute). */
@@ -141,6 +151,10 @@ class MapFragment : Fragment() {
private var userZoom = false
private var engine: MapEngine? = null
+ private var nav: MapNav? = null
+ private var navArgsHandled = false
+ private var alertCards: AlertCardController? = null
+ private var stopAlertCards: (() -> Unit)? = null
private var rf: RfMap? = null
private val map: MapEngine? get() = rf?.map
private var lastFix: Location? = null
@@ -149,6 +163,55 @@ class MapFragment : Fragment() {
private var stopObservingBulk: (() -> Unit)? = null
private val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
+ /** Where to? The search screen's answer: a destination (plan the routes) or a stop on the way. */
+ private val searchLauncher = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult()) { r ->
+ if (r.resultCode != android.app.Activity.RESULT_OK || !alive) return@registerForActivityResult
+ val place = NavSearchActivity.placeOf(r.data) ?: return@registerForActivityResult
+ when (r.data?.getStringExtra(NavSearchActivity.EXTRA_MODE)) {
+ NavSearchActivity.MODE_STOP -> Navigator.addStop(act, place)
+ // The pane on the main screen stays where it is: the card and routes open in it, and only a tap on
+ // the guidance banner or arrival time goes to the full screen map.
+ else -> nav?.showPlace(place, plan = true)
+ }
+ }
+
+ private val navHost = object : MapNav.Host {
+ override fun navLookAtRoute() {
+ if (following) { following = false; applyMode(animate = false); styleFollowButton() }
+ }
+
+ override fun navGuidingChanged(on: Boolean) {
+ if (!alive) return
+ binding.root.keepScreenOn = on && Prefs.navKeepScreenOn(act)
+ // The Record / Traces bar gives way to the arrival bar while you are being guided.
+ // In the small pane the round buttons stay while guiding: they sit just above the arrival bar.
+ if (!embedded) { binding.controls.visibility = if (on) View.GONE else View.VISIBLE; layoutBottomInset() }
+ if (on) { following = true; userZoom = false; applyMode(animate = true); styleFollowButton() }
+ else { lastZoomTarget = 0.0; applyMode(animate = true) } // the zoom for a turn goes with the guidance
+ renderLive()
+ }
+
+ override fun navCheckStyle() {
+ if (alive && rf != null && rf?.isDark != darkTiles()) loadStyle()
+ }
+
+ override fun navSearch(mode: String) = searchLauncher.launch(NavSearchActivity.intent(act, mode))
+
+ override fun navOpenFull(place: Place?) = openFullMap(place)
+
+ override fun navPanelsChanged() { if (alive) { renderLive(); fitSideButtonsSoon(); layoutBottomInset() } }
+ }
+
+ /** The map on its own screen, on [place] to plan a route to when given (else on the route being followed). */
+ private fun openFullMap(place: Place?) {
+ startActivity(Intent(act, MapActivity::class.java).apply {
+ if (place != null) {
+ putExtra(EXTRA_NAV_NAME, place.name); putExtra(EXTRA_NAV_ADDRESS, place.address)
+ putExtra(EXTRA_NAV_LAT, place.lat); putExtra(EXTRA_NAV_LON, place.lon)
+ }
+ })
+ }
+
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = ActivityMapBinding.inflate(inflater, container, false)
return binding.root
@@ -158,12 +221,16 @@ class MapFragment : Fragment() {
tripId = args.getLong(EXTRA_TRIP_ID, -1).takeIf { it > 0 }
if (!embedded) act.title = if (tripId == null) "Scan map" else "Recorded trace"
- // Full screen, edge-to-edge: keep the controls above the navigation bar.
- if (!embedded) ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->
- val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
- binding.controls.updatePadding(bottom = bars.bottom + (6 * resources.displayMetrics.density).toInt())
- binding.statusBox.translationY = bars.top.toFloat()
- insets
+ // Full screen, edge-to-edge: keep the bottom-most panel above the navigation bar.
+ if (!embedded) {
+ basePad = listOf(binding.navCard, binding.navBar, binding.mapFilterScroll, binding.controls).map { it.paddingBottom }
+ ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->
+ val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
+ bottomInset = bars.bottom
+ layoutBottomInset()
+ binding.statusBox.translationY = bars.top.toFloat()
+ insets
+ }
}
if (args.getBoolean(EXTRA_SHOW_TOWERS, false)) Prefs.setShowCellTowers(act, true)
@@ -182,8 +249,27 @@ class MapFragment : Fragment() {
setupMenu()
// The scale and the map credit sit just under the status banner, or at the very top when there is none.
binding.statusBox.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> placeScaleBar() }
+ // Wider than tall: the round buttons become a row and the turn banner leaves them the right side.
+ if (!embedded) binding.root.addOnLayoutChangeListener { _, l, t, r, bt, ol, ot, or, ob -> if (r - l != or - ol || bt - t != ob - ot) fitSideButtonsSoon() }
createEngine(savedInstanceState, null)
+ if (tripId == null) {
+ nav = MapNav(act, binding, viewLifecycleOwner.lifecycleScope, embedded, { alive }, { rf }, { lastFix ?: knownFix() }, navHost)
+ .also { it.setup() }
+ // Alerts pop up over the full screen map (the small pane on the main screen has the list under it).
+ if (!embedded) {
+ val cards = AlertCardController(act, binding, { lastFix ?: knownFix() }) { lat, lon ->
+ navHost.navLookAtRoute()
+ rf?.map?.easeTo(lat, lon, ms = 500)
+ }
+ alertCards = cards
+ stopAlertCards = AlertCards.addListener { cards.show(it) }
+ // One that came in just before this screen opened (tapping its notification, say) is still shown.
+ AlertCards.latest?.takeIf { System.currentTimeMillis() - it.atMs < 6_000L }?.let { cards.show(it) }
+ }
+ } else {
+ binding.searchButton.visibility = View.GONE
+ }
binding.map.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->
if (bottom - top != oldBottom - oldTop) applyMode(animate = false)
}
@@ -226,12 +312,36 @@ class MapFragment : Fragment() {
/** The map engine chosen in Settings > Map; [restore] is where the one it replaces was looking. */
private fun createEngine(state: Bundle?, restore: MapEngine.Camera?) {
- val e = MapEngine.create(act)
- engine = e
- binding.map.addView(e.view, 0, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
- binding.osmCredit.text = e.credit
- e.onCreate(state)
- e.whenReady { if (alive && engine === e) onMapReady(e, restore) }
+ // The map's start-up is marked on disk until it has drawn: if the app dies in it, the next launch leaves the map off.
+ safetyArmed = true
+ MapSafety.arm(act, MapEngine.chosen(act))
+ try {
+ val e = MapEngine.create(act)
+ engine = e
+ binding.map.addView(e.view, 0, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
+ binding.osmCredit.text = e.credit
+ e.onCreate(state)
+ e.whenReady { if (alive && engine === e) onMapReady(e, restore) }
+ } catch (t: Throwable) {
+ // A native library that will not load, a graphics context that cannot be made: an error that can be caught
+ // is told, not crashed on (and the saved view stops asking for the map).
+ android.util.Log.w("MapFragment", "the map could not start", t)
+ engine = null
+ safetyArmed = false
+ MapSafety.disarm(act)
+ if (embedded) Prefs.viewPanes(act).let { if ("map" in it) Prefs.setViewPanes(act, it - "map") }
+ binding.statusText.text = "The map can't start on this phone (${t.javaClass.simpleName}). Everything else works."
+ binding.statusText.visibility = View.VISIBLE
+ }
+ }
+
+ private var safetyArmed = false
+
+ /** The map has been up for a few seconds: its start-up did not take the app down. */
+ private fun mapWorked() {
+ if (!safetyArmed) return
+ safetyArmed = false
+ MapSafety.worked(act)
}
/** Back from Settings with the other map provider chosen: the map changes in place, looking at the same spot. */
@@ -247,6 +357,9 @@ class MapFragment : Fragment() {
}
private fun onMapReady(m: MapEngine, restore: MapEngine.Camera?) {
+ // The graphics crash comes the moment the map's surface is made, long before this: a few seconds on, the
+ // start-up is over. (Waiting for the camera to go idle is not enough: it never does while guiding.)
+ binding.root.postDelayed({ if (alive && engine === m) mapWorked() }, MapSafety.SETTLE_MS)
val r = RfMap(act, m).also { rf = it }
r.filter = filter
r.tripMode = tripId != null
@@ -258,27 +371,41 @@ class MapFragment : Fragment() {
m.onCameraMove = { updateScale() }
m.onIdle = { r.safe("static") { r.maybeRedrawStatic(); updateScale() } }
m.onClick = { x, y -> r.safe("tap") { r.onTap(x, y, myPosition()) } }
+ if (tripId == null) m.onLongClick = { lat, lon -> r.safe("long press") { nav?.onLongPress(lat, lon) } }
if (restore != null) { m.jumpTo(restore.lat, restore.lon, restore.zoom); centeredOnce = true }
else placeCameraAtStart(m)
placeScaleBar()
loadStyle()
}
- private fun darkTiles(): Boolean = Prefs.mapDark(act)
- ?: ((resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==
- android.content.res.Configuration.UI_MODE_NIGHT_YES)
+ private fun systemDark() = (resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==
+ android.content.res.Configuration.UI_MODE_NIGHT_YES
+
+ /** The map's look: your choice (the sun / moon button), else - while guided - day or night where you are, else the phone's. */
+ private fun darkTiles(): Boolean = Prefs.mapDark(act) ?: run {
+ val here = if (Navigator.active && Prefs.navAutoNight(act)) lastFix ?: knownFix() else null
+ if (here != null) com.rfsentinel.app.nav.Sun.isNight(here.latitude, here.longitude, System.currentTimeMillis()) else systemDark()
+ }
private fun loadStyle() {
val r = rf ?: return
val dark = darkTiles()
styleThemeButton()
- binding.osmCredit.setBackgroundColor(if (dark) 0x99000000.toInt() else 0x99FFFFFF.toInt())
+ binding.osmCredit.setBackgroundColor(if (dark) 0x40000000 else 0x99FFFFFF.toInt()) // the night one is barely there: the map shows through
binding.osmCredit.setTextColor(if (dark) 0xFFDDDDDD.toInt() else 0xFF333333.toInt())
r.loadStyle(dark) {
if (!alive) return@loadStyle
r.safe("location") { startLocation() }
if (tripId != null) loadTrip() else renderLive()
r.safe("static") { r.maybeRedrawStatic(force = true) }
+ r.safe("nav") { nav?.redraw() }
+ // Opened from a search on the main screen's map: the routes to that place.
+ // (Not again after a rotation once you are being guided: that would plan a second route over the first.)
+ if (!navArgsHandled && args.containsKey(EXTRA_NAV_LAT) && !Navigator.active) {
+ navArgsHandled = true
+ nav?.showPlace(Place(args.getString(EXTRA_NAV_NAME).orEmpty(), args.getString(EXTRA_NAV_ADDRESS).orEmpty(),
+ args.getDouble(EXTRA_NAV_LAT), args.getDouble(EXTRA_NAV_LON)), plan = true)
+ }
}
}
@@ -366,19 +493,35 @@ class MapFragment : Fragment() {
val b = _binding ?: return
val gap = (8 * resources.displayMetrics.density).toInt()
val box = b.statusBox
- val y = (if (box.height > 0) box.bottom + box.translationY.toInt() + gap else box.top + box.translationY.toInt()).coerceAtLeast(gap)
+ // On its side while guiding the banner fills the left and the arrival bar sits right under it: the credit goes
+ // to the free top right corner instead of being hidden under the bar.
+ val atEnd = wideScreen() && Navigator.active
+ val y = (if (atEnd) box.translationY.toInt() + gap / 2 else if (box.height > 0) box.bottom + box.translationY.toInt() + gap else box.top + box.translationY.toInt()).coerceAtLeast(gap)
b.scaleBar.translationY = y.toFloat()
- b.osmCredit.translationY = (y + b.scaleBar.height).toFloat()
+ // The credit wraps to a second line rather than run under the compass and follow buttons at the right.
+ val d = resources.displayMetrics.density
+ if (b.root.width > 0) b.osmCredit.maxWidth = (b.root.width - 84 * d).toInt().coerceAtLeast((140 * d).toInt())
+ val scaleH = if (b.scaleBar.visibility == View.GONE) 0 else b.scaleBar.height
+ b.osmCredit.translationY = (y + scaleH).toFloat()
+ b.osmCredit.translationX = if (atEnd && b.osmCredit.width > 0) (b.root.width - b.osmCredit.width - b.osmCredit.left - gap).toFloat() else 0f
// Mapbox's logo and info button just under the credit line.
- engine?.placeBranding(y + b.scaleBar.height + b.osmCredit.height + gap / 2)
+ engine?.placeBranding(y + scaleH + b.osmCredit.height + gap / 2, atEnd)
}
private fun updateScale() {
val m = map ?: return
val b = _binding ?: return
+ // The small pane while guiding has no room for it between the turn banner and the buttons above the
+ // arrival bar: the credit moves up in its place.
+ if ((embedded || wideScreen()) && Navigator.active) {
+ if (b.scaleBar.visibility != View.GONE) { b.scaleBar.visibility = View.GONE; placeScaleBar() }
+ return
+ }
+ val wasGone = b.scaleBar.visibility == View.GONE
// Tilted, the scale differs across the screen: no single scale to show.
- if (m.camera.tilt > 5) { b.scaleBar.visibility = View.INVISIBLE; return }
+ if (m.camera.tilt > 5) { b.scaleBar.visibility = View.INVISIBLE; if (wasGone) placeScaleBar(); return }
b.scaleBar.visibility = View.VISIBLE
+ if (wasGone) placeScaleBar()
// Measured on the ground between two points 100 px apart across the middle of the map.
val w = b.map.width; val h = b.map.height
if (w < 200 || h == 0) return
@@ -409,7 +552,7 @@ class MapFragment : Fragment() {
// A short pane has no room for five buttons stacked on the right: map settings, light / dark and
// full screen join Record and Traces along the bottom; the compass and follow stay on the right.
val gap = (8 * resources.displayMetrics.density).toInt()
- for (v in listOf(binding.mapSettingsButton, binding.themeButton, binding.fullscreenButton)) {
+ for (v in listOf(binding.searchButton, binding.mapSettingsButton, binding.themeButton, binding.fullscreenButton)) {
(v.parent as? ViewGroup)?.removeView(v)
binding.compactControls.addView(v, android.widget.LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginStart = gap })
@@ -417,6 +560,201 @@ class MapFragment : Fragment() {
binding.recordFab.backgroundTintList = android.content.res.ColorStateList.valueOf(accent)
binding.recordFab.imageTintList = android.content.res.ColorStateList.valueOf(onAccent)
binding.statusText.textSize = 12f
+ // On a narrower screen the row of round buttons would run into the compass and follow buttons at the right.
+ val relayout = View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitSideButtonsSoon() }
+ binding.root.addOnLayoutChangeListener(relayout)
+ binding.compactControls.addOnLayoutChangeListener(relayout)
+ binding.navCard.addOnLayoutChangeListener(relayout)
+ binding.navBar.addOnLayoutChangeListener(relayout)
+ }
+
+ /**
+ * Under the place card or the arrival bar, the compass and follow buttons stack in the same column and
+ * would squeeze the card's buttons off the bottom of a short pane. They give way, the compass first,
+ * when the card (at the height it needs) and they do not all fit; they come back when the card goes.
+ */
+ private fun fitSideButtons() {
+ val b = _binding ?: return
+ if (!embedded || b.root.height == 0) return
+ val d = resources.displayMetrics.density
+ val panel = listOf(b.navCard, b.navBar).firstOrNull { it.visibility == View.VISIBLE }
+ var hide = emptyList<View>()
+ if (panel != null) {
+ panel.measure(View.MeasureSpec.makeMeasureSpec(b.root.width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
+ // The turn banner (and the credit under it) take the top of the pane while guiding.
+ val top = if (b.navBanner.visibility == View.VISIBLE) b.statusBox.bottom + b.statusBox.translationY + 8 * d else 0f
+ val room = b.root.height - 8 * d - top
+ val fab = 56 * d // a button and its margin
+ // The round buttons ride above the arrival bar (the card hides them) and, when they are too wide to sit
+ // beside the compass and follow buttons, those rise above them.
+ val rowLift = if (rowCrowdsSideButtons()) b.compactControls.height + 8 * d else 0f
+ val used = panel.measuredHeight + rowLift
+ hide = when {
+ used + 2 * fab <= room -> emptyList()
+ used + fab <= room -> listOf(b.orientationButton)
+ else -> listOf(b.orientationButton, b.centerButton)
+ }
+ }
+ for (v in listOf(b.orientationButton, b.centerButton)) {
+ val want = if (v in hide) View.GONE else View.VISIBLE
+ if (v.visibility != want) v.visibility = want
+ }
+ }
+
+ private var bottomInset = 0
+ private var basePad: List<Int> = emptyList()
+
+ /**
+ * The navigation bar's height is added under the panel that is really at the bottom (the Record / Traces
+ * bar, or the filter chips while guiding), not under every panel: the place card sits above the chips and
+ * the Record bar, and carrying the inset too left a big empty band between its buttons and the chips.
+ */
+ private fun layoutBottomInset() {
+ val b = _binding ?: return
+ if (embedded || basePad.isEmpty()) return
+ val panels = listOf(b.navCard, b.navBar, b.mapFilterScroll, b.controls)
+ val last = panels.lastOrNull { it.visibility == View.VISIBLE }
+ val six = (6 * resources.displayMetrics.density).toInt()
+ panels.forEachIndexed { i, p ->
+ val want = if (p === last) bottomInset + six else basePad[i]
+ if (p.paddingBottom != want) p.updatePadding(bottom = want)
+ }
+ }
+
+ private var sidePending = false
+
+ /** Changing visibility or padding inside a layout pass is not reliably laid out again: do it right after. */
+ private fun fitSideButtonsSoon() {
+ val b = _binding ?: return
+ if (sidePending) return
+ sidePending = true
+ b.root.post { sidePending = false; if (_binding != null) { arrangeForShape(); fitCompactRow(); liftSideButtons(); fitSideButtons(); refollowForPanels() } }
+ }
+
+ /**
+ * The small pane's row of round buttons (Record, History, Search, Settings, light / dark, full screen) must fit the
+ * pane's width whatever it is: the space between them shrinks first (down to none), then the buttons themselves
+ * (down to 32 dp), so the last one is never cut off at the edge.
+ */
+ private fun fitCompactRow() {
+ val b = _binding ?: return
+ val row = b.compactControls
+ if (!embedded || row.visibility != View.VISIBLE || row.width == 0 || b.root.width == 0) return
+ val d = resources.displayMetrics.density
+ val kids = row.children.filter { it.visibility != View.GONE }.toList()
+ if (kids.size < 2) return
+ // Worked out from what is on screen now: how much room is left (or missing) between the row's end and the pane's edge.
+ val diff = b.root.width - (8 * d).toInt() - row.left - row.width
+ if (kotlin.math.abs(diff) < 2) return
+ val fabs = kids.filterIsInstance<com.google.android.material.floatingactionbutton.FloatingActionButton>()
+ val natural = (40 * d).toInt()
+ val gapMax = (8 * d).toInt()
+ val curGap = (kids[1].layoutParams as? ViewGroup.MarginLayoutParams)?.marginStart ?: return
+ val gap = curGap + diff / (kids.size - 1)
+ fun setGap(g: Int) = kids.forEachIndexed { i, v ->
+ val lp = v.layoutParams as? ViewGroup.MarginLayoutParams ?: return@forEachIndexed
+ val want = if (i == 0) 0 else g
+ if (lp.marginStart != want) { lp.marginStart = want; v.layoutParams = lp }
+ }
+ fun resize(by: Int) {
+ for (f in fabs) {
+ val now = if (f.customSize > 0) f.customSize else f.width
+ val to = (now + by).coerceIn((32 * d).toInt(), natural)
+ if (to != f.customSize) f.customSize = to
+ }
+ }
+ when {
+ gap in 0..gapMax -> setGap(gap)
+ // More room than the spacing needs: the buttons grow back to their size.
+ gap > gapMax -> { setGap(gapMax); if (fabs.isNotEmpty()) resize((diff - (gapMax - curGap) * (kids.size - 1)) / fabs.size) }
+ // Not enough even without spacing: the buttons get smaller (not under 32 dp).
+ else -> { setGap(0); if (fabs.isNotEmpty()) resize((diff + curGap * (kids.size - 1)) / fabs.size) }
+ }
+ }
+
+ private var origBasePad: List<Int>? = null
+ private var compactLand = false
+ private var landPad = -1
+
+ /**
+ * On its side every row of the screen counts: less padding in the turn banner, the arrival bar, the chips and the
+ * Record bar. The padding is a share of the screen's height (between 4 and 12 dp), so a short phone gets less and a
+ * tall tablet keeps the usual.
+ */
+ private fun compactForLandscape(on: Boolean) {
+ val b = _binding ?: return
+ val d = resources.displayMetrics.density
+ for (c in b.mapFilterChips.children) (c as? com.google.android.material.chip.Chip)?.setEnsureMinTouchTargetSize(!on)
+ val pad = if (on) (b.root.height * 0.017f).toInt().coerceIn((4 * d).toInt(), (12 * d).toInt()) else (12 * d).toInt()
+ if (on == compactLand && pad == landPad) return
+ compactLand = on; landPad = pad
+ val small = pad / 3 // the bars' own top and bottom: a third of the banner's
+ b.navBanner.setPadding(pad, pad, pad, pad)
+ b.navDistance.textSize = if (on) 22f else 28f
+ (b.navLanes.layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin = if (on) small else (8 * d).toInt()
+ (b.navThen.layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin = if (on) 0 else (6 * d).toInt()
+ b.navEta.textSize = if (on) 17f else 20f
+ b.navBar.updatePadding(top = if (on) 0 else (6 * d).toInt())
+ b.controls.updatePadding(top = if (on) small else (6 * d).toInt())
+ val orig = origBasePad ?: basePad.also { origBasePad = it }
+ basePad = orig.mapIndexed { i, v -> if (on && (i == 1 || i == 3)) small else v } // the arrival bar and the Record bar
+ layoutBottomInset()
+ b.root.requestLayout()
+ }
+
+ /** The full screen map is wider than tall (a phone on its side). */
+ private fun wideScreen(): Boolean { val b = _binding ?: return false; return !embedded && b.root.width > b.root.height && b.root.height > 0 }
+
+ /**
+ * On its side the screen has no height for a column of five round buttons under the turn banner (they climbed
+ * under the toolbar and the banner's mute button): they become a row above the bottom panels, at the right, and
+ * the banner and the alert card stop at about half the width so the two never meet. Upright: the column as before.
+ */
+ private fun arrangeForShape() {
+ val b = _binding ?: return
+ if (embedded || b.root.width == 0) return
+ val wide = wideScreen()
+ val want = if (wide) android.widget.LinearLayout.HORIZONTAL else android.widget.LinearLayout.VERTICAL
+ if (b.sideButtons.orientation != want) b.sideButtons.orientation = want
+ val d = resources.displayMetrics.density
+ // The banner gets what the row of buttons leaves (each is about 62 dp with its margin), not less than 40% of the width.
+ val shown = b.sideButtons.children.count { it.visibility != View.GONE }
+ val rowW = (shown * 62 * d + 24 * d).toInt()
+ val width = if (wide) (b.root.width - rowW).coerceIn((b.root.width * 0.4f).toInt(), (520 * d).toInt().coerceAtLeast((b.root.width * 0.4f).toInt()))
+ else ViewGroup.LayoutParams.MATCH_PARENT
+ val lp = b.statusBox.layoutParams
+ if (lp.width != width) { lp.width = width; b.statusBox.layoutParams = lp }
+ compactForLandscape(wide)
+ updateScale() // while guiding on its side the scale gives its place to the credit, as in the small pane
+ placeScaleBar()
+ }
+
+ /**
+ * The compass and follow buttons sit at the right edge, the round buttons along the bottom-left. When the
+ * pane is too narrow for both side by side the compass and follow buttons move up above the row instead of
+ * lying under it. Worked out from sizes alone, so it settles in one pass.
+ */
+ private fun liftSideButtons() {
+ val b = _binding ?: return
+ val row = b.compactControls
+ val d = resources.displayMetrics.density
+ // While guiding, the row rides just above the arrival bar instead of under it.
+ row.translationY = if (row.visibility == View.VISIBLE && b.navBar.visibility == View.VISIBLE) -b.navBar.height.toFloat() else 0f
+ // Crowded: the compass and follow buttons rise by the row's height (their own bottom margin, so the panel's
+ // card or bar below them stays where it is).
+ val lift = if (rowCrowdsSideButtons()) (row.height + 8 * d).toInt() else 0
+ val lp = b.centerButton.layoutParams as? android.widget.LinearLayout.LayoutParams ?: return
+ val want = (8 * d).toInt() + lift
+ if (lp.bottomMargin != want) { lp.bottomMargin = want; b.centerButton.layoutParams = lp }
+ }
+
+ /** The row of round buttons is too long to sit beside the compass and follow buttons (worked out from sizes alone). */
+ private fun rowCrowdsSideButtons(): Boolean {
+ val b = _binding ?: return false
+ val row = b.compactControls
+ val d = resources.displayMetrics.density
+ val rightZone = (14 + 48 + 8) * d // the buttons' margin, their width and a gap
+ return row.visibility == View.VISIBLE && row.width > 0 && row.width + 10 * d + rightZone > b.root.width
}
// ---- Your position --------------------------------------------------------------------------------
@@ -438,7 +776,7 @@ class MapFragment : Fragment() {
return Location(fix).apply { lastBearing?.let { bearing = it } }
}
- private val gpsListener = LocationListener { fix -> rf?.safe("fix") { onFix(fix) } ?: onFix(fix) }
+ private val gpsListener = LocationListenerCompat { fix -> rf?.safe("fix") { onFix(fix) } ?: onFix(fix) }
private fun onFix(fix: Location) {
if (!alive) return
@@ -457,8 +795,18 @@ class MapFragment : Fragment() {
// 3D: re-aim only when the speed changed enough to matter (no constant zoom pumping).
val base = Prefs.mapDefaultZoom(act)
val drives = is3d() || (tripId == null && Prefs.mapHeadingUp(act))
- if (drives && (before < 0f || kotlin.math.abs(zoomFor(smoothKmh, base) - zoomFor(before.coerceAtLeast(0f), base)) > 0.1)) applyMode(animate = true)
+ // Zoom in as a turn comes up while guided, out again after it (the speed's own zoom otherwise).
+ val target = (if (drives) zoomFor(smoothKmh, base) else base) + turnBoost()
+ val moved = kotlin.math.abs(target - lastZoomTarget) > 0.1
+ if ((drives && before < 0f) || (moved && (drives || Navigator.active))) { lastZoomTarget = target; applyMode(animate = true) }
+ }
+
+ /** Zoom levels added for the turn coming up (only while guiding). */
+ private fun turnBoost(): Double {
+ val s = Navigator.state ?: return 0.0
+ return if (Navigator.active) NavCamera.turnBoost(s.toManeuverM, smoothKmh.coerceAtLeast(0f)) else 0.0
}
+ private var lastZoomTarget = 0.0
// ---- Battery: the map's own GPS ---------------------------------------------------------------------
@@ -527,16 +875,52 @@ class MapFragment : Fragment() {
val h = binding.map.height
val base = Prefs.mapDefaultZoom(act)
val kmh = smoothKmh.coerceAtLeast(0f)
+ val boost = turnBoost()
if (is3d()) {
- m.follow(MapEngine.Follow.HEADING, if (h > 0) topPaddingFor(h) else null, tiltFor(kmh, Prefs.map3dTilt(act)), if (userZoom) null else zoomFor(kmh, base), ms)
+ val pad = followPadding(h, ARROW_HEIGHT)
+ lastFollowPad = pad
+ m.follow(MapEngine.Follow.HEADING, pad, tiltFor(kmh, Prefs.map3dTilt(act)), if (userZoom) null else zoomFor(kmh, base) + boost, ms)
} else if (Prefs.mapHeadingUp(act)) {
// Turning with you: pulls back at speed like the 3D view; a pinch is yours until the follow button.
- m.follow(MapEngine.Follow.HEADING, 0.0, 0.0, if (userZoom) null else zoomFor(kmh, base) - FLAT_ZOOM_OFFSET, ms)
+ lastFollowPad = followPadding(h, 0.5)
+ m.follow(MapEngine.Follow.HEADING, lastFollowPad ?: 0.0, 0.0, if (userZoom) null else zoomFor(kmh, base) - FLAT_ZOOM_OFFSET + boost, ms)
} else {
- m.follow(MapEngine.Follow.NORTH, 0.0, 0.0, if (userZoom) null else base - FLAT_ZOOM_OFFSET, ms)
+ lastFollowPad = followPadding(h, 0.5)
+ m.follow(MapEngine.Follow.NORTH, lastFollowPad ?: 0.0, 0.0, if (userZoom) null else base - FLAT_ZOOM_OFFSET + boost, ms)
}
}
+ private var lastFollowPad: Double? = null
+
+ /**
+ * The camera's top padding that puts your arrow [fraction] of the way down the part of the map you can see.
+ * Full screen that is the whole map (as ever). In the small pane the turn banner covers the top and the
+ * round buttons and the arrival bar the bottom, so the arrow is placed in what is left between them -
+ * otherwise it sits behind the buttons.
+ */
+ private fun followPadding(h: Int, fraction: Double): Double? {
+ if (h <= 0) return null
+ if (!embedded) return if (fraction == ARROW_HEIGHT) topPaddingFor(h) else 0.0
+ val b = _binding ?: return if (fraction == ARROW_HEIGHT) topPaddingFor(h) else 0.0
+ val mapTop = IntArray(2).also { b.map.getLocationInWindow(it) }[1]
+ fun top(v: View) = IntArray(2).also { v.getLocationInWindow(it) }[1] - mapTop.toFloat()
+ val topLimit = if (b.navBanner.visibility == View.VISIBLE) top(b.statusBox) + b.statusBox.height else 0f
+ var bottomLimit = h.toFloat()
+ for (v in listOf(b.navBar, b.compactControls, b.navCard)) if (v.visibility == View.VISIBLE && v.height > 0) bottomLimit = minOf(bottomLimit, top(v))
+ if (bottomLimit <= topLimit + 40) return if (fraction == ARROW_HEIGHT) topPaddingFor(h) else 0.0 // no room to speak of
+ val y = topLimit + fraction * (bottomLimit - topLimit)
+ return (2 * y - h).coerceAtLeast(0.0)
+ }
+
+ /** After the pane's panels moved (the arrival bar and the buttons above it appeared), the arrow is placed again if it should move. */
+ private fun refollowForPanels() {
+ val b = _binding ?: return
+ if (!embedded || !following || tripId != null || b.map.height == 0) return
+ val want = followPadding(b.map.height, if (is3d()) ARROW_HEIGHT else 0.5)
+ val had = lastFollowPad
+ if (want != null && (had == null || kotlin.math.abs(want - had) > 8.0)) applyMode(animate = false)
+ }
+
/** The map button: north up -> heading up -> 3D driving view -> north up. */
private fun setupOrientationButton() {
val btn = binding.orientationButton
@@ -653,9 +1037,11 @@ class MapFragment : Fragment() {
if (rf != null && rf?.isDark != darkTiles()) loadStyle()
styleOrientationButton()
applyMode(animate = false)
+ nav?.refresh()
}
override fun onPause() {
+ if (safetyArmed) { safetyArmed = false; MapSafety.disarm(act) } // paused normally: not a crash
saveView()
stopGps()
if (tripId == null) ScanForegroundService.mapHidden(act)
@@ -673,6 +1059,10 @@ class MapFragment : Fragment() {
}
override fun onDestroyView() {
+ if (safetyArmed) { safetyArmed = false; MapSafety.disarm(act) } // leaving normally is not a crash
+ stopAlertCards?.invoke(); stopAlertCards = null
+ alertCards?.hide(); alertCards = null
+ nav?.destroy(); nav = null
stopObservingBulk?.invoke()
com.rfsentinel.app.alpr.CctvStore.onChanged = null
stopGps()
@@ -757,6 +1147,9 @@ class MapFragment : Fragment() {
bulkStatus() != null -> bulkStatus() // a camera download's progress wins
System.currentTimeMillis() - com.rfsentinel.app.alpr.AlprStore.lastAutoFailureAt < CAMERA_FAIL_SHOWN_MS ->
"Couldn't download the cameras for this area (map server busy or offline) - retrying"
+ Navigator.active && !recording -> null // the guidance banner is the status
+ // In the small pane the place card needs the room: the scan status is on the main screen above it anyway.
+ embedded && nav?.cardShown == true && !recording -> null
!ScanForegroundService.isRunning -> "Not scanning - start scanning, then Record trace to save your route"
recording -> {
val mins = (System.currentTimeMillis() - TripRecorder.startedAt) / 60000
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
index 08ebef1..3299d94 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
@@ -11,6 +11,7 @@ import com.rfsentinel.app.util.Permissions
import org.json.JSONArray
import org.json.JSONObject
import org.maplibre.android.MapLibre
+import org.maplibre.android.WellKnownTileServer
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
@@ -53,6 +54,11 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
/** Style properties whose value is a plain array, not an expression. */
private val ARRAY_PROPERTIES = setOf("text-font", "text-offset", "icon-offset", "line-dasharray", "text-variable-anchor", "text-translate", "icon-translate", "circle-translate", "fill-translate", "line-translate")
+ /** MapLibre's one-time set-up, with the renderer [MapSafety] allows: Vulkan where the phone has it, else OpenGL. */
+ internal fun start(context: Context) {
+ MapLibre.getInstance(context.applicationContext, null, WellKnownTileServer.MapLibre, MapSafety.renderer(context))
+ }
+
/** A style JSON value as MapLibre wants it: expressions, float numbers, typed arrays. */
internal fun value(name: String, v: Any?): Any? = when {
v is JSONArray && name in ARRAY_PROPERTIES ->
@@ -68,7 +74,7 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
override val credit = CREDIT
override val labelFont = listOf("Noto Sans Regular")
- init { MapLibre.getInstance(context.applicationContext) }
+ init { start(context) }
override val view = MapView(context, MapLibreMapOptions.createFromAttributes(context))
private var map: MapLibreMap? = null
@@ -76,6 +82,7 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
override var onCameraMove: (() -> Unit)? = null
override var onIdle: (() -> Unit)? = null
override var onClick: ((Float, Float) -> Unit)? = null
+ override var onLongClick: ((Double, Double) -> Unit)? = null
override var onUserGesture: (() -> Unit)? = null
override var onFollowDismissed: (() -> Unit)? = null
@@ -105,6 +112,10 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
onClick?.invoke(p.x, p.y)
false
}
+ m.addOnMapLongClickListener { at ->
+ onLongClick?.invoke(at.latitude, at.longitude)
+ onLongClick != null
+ }
ready()
}
}
@@ -269,12 +280,12 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
m.animateCamera(CameraUpdateFactory.newCameraPosition(b.build()), ms.toInt().coerceAtLeast(1))
}
- override fun fit(points: List<Pair<Double, Double>>, paddingPx: Int) {
+ override fun fit(points: List<Pair<Double, Double>>, paddingPx: Int, bottomPx: Int) {
val m = map ?: return
if (points.isEmpty()) return
if (points.size == 1) { jumpTo(points[0].first, points[0].second); return }
val b = LatLngBounds.Builder().apply { points.forEach { include(LatLng(it.first, it.second)) } }.build()
- m.moveCamera(CameraUpdateFactory.newLatLngBounds(b, paddingPx))
+ m.moveCamera(CameraUpdateFactory.newLatLngBounds(b, paddingPx, paddingPx, paddingPx, bottomPx))
}
override fun visibleBox(): MapEngine.Box? {
@@ -353,5 +364,5 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
if (mode == MapEngine.Follow.NORTH && m != null && m.cameraPosition.bearing != 0.0) m.animateCamera(CameraUpdateFactory.bearingTo(0.0), 600)
}
- override fun placeBranding(topPx: Int) {}
+ override fun placeBranding(topPx: Int, atEnd: Boolean) {}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt b/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt
new file mode 100644
index 0000000..5a4840a
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt
@@ -0,0 +1,527 @@
+package com.rfsentinel.app.ui
+
+import android.content.res.ColorStateList
+import android.location.Location
+import android.view.Gravity
+import android.view.HapticFeedbackConstants
+import android.view.View
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.PopupMenu
+import android.widget.TextView
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.button.MaterialButton
+import com.google.android.material.chip.Chip
+import com.rfsentinel.app.BuildConfig
+import com.rfsentinel.app.R
+import com.rfsentinel.app.databinding.ActivityMapBinding
+import com.rfsentinel.app.nav.HandOff
+import com.rfsentinel.app.nav.NavFormat
+import com.rfsentinel.app.nav.Navigator
+import com.rfsentinel.app.nav.Place
+import com.rfsentinel.app.nav.Places
+import com.rfsentinel.app.nav.Prompts
+import com.rfsentinel.app.nav.Route
+import com.rfsentinel.app.nav.Valhalla
+import com.rfsentinel.app.util.Prefs
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.text.DateFormat
+import java.util.Date
+
+/**
+ * Getting somewhere on the map screen: a place card (from a search, or a long press on the map), the
+ * routes to it to choose from, and then guidance - the banner with the next turn at the top, the
+ * arrival bar at the bottom. [Navigator] does the guiding; this shows it.
+ *
+ * On the main screen's small map pane there is only the arrival bar (tap it for the full screen map).
+ */
+internal class MapNav(
+ private val act: AppCompatActivity,
+ private val b: ActivityMapBinding,
+ private val scope: CoroutineScope,
+ private val embedded: Boolean,
+ private val alive: () -> Boolean,
+ private val rf: () -> RfMap?,
+ private val fix: () -> Location?,
+ private val host: Host
+) {
+ interface Host {
+ /** Looking at a route (not at yourself): stop following. */
+ fun navLookAtRoute()
+ /** Guidance began or ended: follow, keep the screen on, swap the bottom controls. */
+ fun navGuidingChanged(on: Boolean)
+ /** Sunset or sunrise may have passed: switch the map between its day and night look if it should. */
+ fun navCheckStyle()
+ /** Open the search screen for [mode] (see [com.rfsentinel.app.nav.NavSearchActivity]). */
+ fun navSearch(mode: String)
+ /** The small map pane: open the full screen map, on [place] when given (to plan a route to it). */
+ fun navOpenFull(place: Place?)
+ /** The place card or the arrival bar appeared or went: anything that would sit under them gives way. */
+ fun navPanelsChanged()
+ }
+
+ private val dp = act.resources.displayMetrics.density
+ private fun px(v: Int) = (v * dp).toInt()
+
+ private var place: Place? = null
+ private var routes: List<Route> = emptyList()
+ private var selected = 0
+ private var options = Navigator.defaultOptions(act)
+ private var planJob: Job? = null
+ private var removeListener: (() -> Unit)? = null
+ private var wasActive = false
+ private var drawnRoute: Route? = null
+ private var drawnAt = 0L
+ private var lanesKey = ""
+
+ val cardShown: Boolean get() = b.navCard.visibility == View.VISIBLE
+
+ /**
+ * The device filter chips float over the map; under the place card or the arrival bar they would
+ * show the map through between two solid panels. They sit on the same solid background then, so the
+ * bottom of the screen reads as one panel (and are transparent over the bare map as before).
+ */
+ private var panelsKey = -1
+
+ private fun styleBackdrop() {
+ val card = b.navCard.visibility == View.VISIBLE
+ val solid = card || b.navBar.visibility == View.VISIBLE
+ // Called at every guidance update (once a second): only when the card or the bar came or went is there anything to do
+ // (it wakes the map's redraw and a layout pass).
+ val key = (if (card) 1 else 0) + (if (solid) 2 else 0)
+ if (key == panelsKey) return
+ panelsKey = key
+ val scroll = b.mapFilterScroll
+ // In the small pane the round buttons would sit on top of the card's buttons: they wait while it shows.
+ // The arrival bar does not hide them: they ride just above it.
+ if (embedded) b.compactControls.visibility = if (b.navCard.visibility == View.VISIBLE) View.GONE else View.VISIBLE
+ host.navPanelsChanged()
+ if (solid) {
+ val tv = android.util.TypedValue()
+ act.theme.resolveAttribute(android.R.attr.colorBackground, tv, true)
+ scroll.setBackgroundColor(tv.data)
+ scroll.setPadding(px(8), 0, px(8), scroll.paddingBottom) // the chips' own touch margin is the gap; the bottom is the screen's (navigation bar)
+ } else {
+ scroll.setBackgroundColor(0x00000000)
+ scroll.setPadding(px(8), 0, px(8), scroll.paddingBottom)
+ }
+ }
+
+ // ---- set up ------------------------------------------------------------------------------------
+
+ fun setup() {
+ val ink = ColorStateList.valueOf(ChipStyle.onSurface(act))
+ for (v in listOf(b.navCardStar, b.navCardClose, b.navEnd, b.navOverview, b.navMenu)) v.imageTintList = ink
+ b.navMute.imageTintList = ColorStateList.valueOf(0xFFFFFFFF.toInt())
+ b.searchButton.backgroundTintList = ColorStateList.valueOf(ChipStyle.accent(act).first)
+ b.searchButton.imageTintList = ColorStateList.valueOf(ChipStyle.accent(act).second)
+ b.searchButton.setOnClickListener { host.navSearch(com.rfsentinel.app.nav.NavSearchActivity.MODE_GO) }
+
+ b.navCardClose.setOnClickListener { closeCard() }
+ b.navCardStar.setOnClickListener { place?.let { Prefs.toggleNavFavorite(act, it); styleStar() } }
+ b.navStart.setOnClickListener { onStartButton() }
+ b.navOpenIn.setOnClickListener { openInMenu(it) }
+ ChipStyle.accent(act).first.let { accent ->
+ b.navOpenIn.setTextColor(accent)
+ b.navOpenIn.strokeColor = ColorStateList.valueOf(accent)
+ }
+ b.navEnd.setOnClickListener { Navigator.stop() }
+ b.navMenu.setOnClickListener { menu(it) }
+ b.navOverview.setOnClickListener { overview() }
+ b.navMute.setOnClickListener { Prefs.setNavVoice(act, !Prefs.navVoice(act)); styleMute() }
+ if (embedded) {
+ b.navEtaBox.setOnClickListener { host.navOpenFull(null) }
+ b.navBanner.setOnClickListener { host.navOpenFull(null) }
+ compactBanner()
+ compactCard()
+ }
+ styleMute()
+ removeListener = Navigator.addListener { if (alive()) refresh() }
+ refresh()
+ }
+
+ /**
+ * The small map pane has little height to spare: the place card gets tighter padding, smaller buttons
+ * and drops its address line once the routes (with their time and distance) are shown.
+ */
+ private fun compactCard() {
+ b.navCard.setPadding(px(10), px(6), px(10), px(6))
+ for (v in listOf(b.navCardStar, b.navCardClose)) v.layoutParams = LinearLayout.LayoutParams(px(40), px(40))
+ for (v in listOf(b.navStart, b.navOpenIn)) { v.insetTop = 0; v.insetBottom = 0; v.minimumHeight = px(40) }
+ (b.navStart.parent as? LinearLayout)?.let { row -> (row.layoutParams as? LinearLayout.LayoutParams)?.topMargin = px(4) }
+ }
+
+ /** The small map pane: the next turn in one slim line (no lanes, no "then"); tap it for the full screen map. */
+ private fun compactBanner() {
+ b.navBanner.setPadding(px(8), px(6), px(8), px(6))
+ (b.navBanner.layoutParams as? LinearLayout.LayoutParams)?.bottomMargin = px(4)
+ b.navIcon.layoutParams = LinearLayout.LayoutParams(px(32), px(32))
+ b.navDistance.textSize = 18f
+ b.navRoad.textSize = 13f
+ b.navRoad.maxLines = 1
+ b.navMute.visibility = View.GONE
+ b.navLanes.visibility = View.GONE
+ b.navThen.visibility = View.GONE
+ }
+
+ fun destroy() {
+ planJob?.cancel()
+ removeListener?.invoke(); removeListener = null
+ }
+
+ // ---- a place, and the routes to it ------------------------------------------------------------
+
+ /** A long press on the map: the card for what is there, with Directions (or Add as stop while guiding). */
+ fun onLongPress(lat: Double, lon: Double) {
+ b.map.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
+ val dropped = Place("Dropped pin", String.format(java.util.Locale.US, "%.5f, %.5f", lat, lon), lat, lon)
+ showPlace(dropped, plan = false)
+ scope.launch {
+ val found = runCatching {
+ withContext(Dispatchers.IO) { Places.reverse(lat, lon, "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}") }
+ }.getOrNull() ?: return@launch
+ // Still the same pin (not closed or replaced meanwhile): say what is there.
+ val now = place ?: return@launch
+ if (alive() && now.lat == lat && now.lon == lon) {
+ place = Place(found.name, found.address.ifBlank { now.address }, lat, lon)
+ bindCard()
+ }
+ }
+ }
+
+ /** The card for [p]; with [plan] the routes are looked for at once. */
+ fun showPlace(p: Place, plan: Boolean) {
+ planJob?.cancel()
+ routes = emptyList(); selected = 0
+ options = Navigator.defaultOptions(act)
+ place = p
+ host.navLookAtRoute()
+ b.navCard.visibility = View.VISIBLE
+ b.navRoutesScroll.visibility = View.GONE
+ b.navAvoidScroll.visibility = View.GONE
+ styleBackdrop()
+ bindCard()
+ rf()?.drawRoutes(emptyList(), 0)
+ rf()?.drawNavPlaces(emptyList(), p.lat to p.lon)
+ rf()?.map?.easeTo(p.lat, p.lon, ms = 500)
+ if (plan) plan()
+ }
+
+ private fun bindCard() {
+ val p = place ?: return
+ b.navCardTitle.text = p.name
+ b.navCardSub.text = p.address
+ b.navCardSub.visibility = if (p.address.isBlank()) View.GONE else View.VISIBLE
+ styleStar()
+ if (routes.isEmpty()) {
+ b.navStart.isEnabled = true
+ b.navStart.text = if (Navigator.active) "Add as stop" else "Directions"
+ }
+ b.navOpenIn.visibility = if (Navigator.active) View.GONE else View.VISIBLE
+ }
+
+ private fun styleStar() {
+ val p = place ?: return
+ val on = Prefs.isNavFavorite(act, p)
+ b.navCardStar.setImageResource(if (on) R.drawable.ic_nav_star else R.drawable.ic_nav_star_border)
+ b.navCardStar.imageTintList = ColorStateList.valueOf(if (on) ChipStyle.accent(act).first else ChipStyle.onSurface(act))
+ b.navCardStar.contentDescription = if (on) "Starred - tap to remove" else "Star this place"
+ }
+
+ private fun onStartButton() {
+ when {
+ routes.isNotEmpty() -> start()
+ Navigator.active -> { place?.let { Navigator.addStop(act, it) }; closeCard() }
+ else -> plan()
+ }
+ }
+
+ private fun plan() {
+ val p = place ?: return
+ val f = fix()
+ if (f == null) { Toast.makeText(act, "Waiting for a GPS fix to plan the route...", Toast.LENGTH_LONG).show(); return }
+ b.navStart.isEnabled = false
+ b.navStart.text = "Finding routes..."
+ planJob?.cancel()
+ planJob = scope.launch {
+ // Not runCatching: a plan replaced by a newer one, or dropped when the card closed, must not end up as "no connection".
+ com.rfsentinel.app.nav.attempt { Navigator.plan(act, p, f, options) }
+ .onSuccess { found ->
+ val now = place
+ if (!alive() || now == null || now.lat != p.lat || now.lon != p.lon) return@onSuccess
+ routes = found; selected = 0
+ showRoutes(refit = true)
+ }
+ .onFailure { e ->
+ if (!alive()) return@onFailure
+ b.navStart.isEnabled = true
+ // Routes already shown stay startable (a change of options failed); else ask again.
+ b.navStart.text = if (routes.isNotEmpty()) "Start · " + NavFormat.duration(routes[selected].durationS) else "Directions"
+ Toast.makeText(act, (e as? Valhalla.NoRouteException)?.message ?: "Couldn't plan the route - no connection?", Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+
+ private fun showRoutes(refit: Boolean) {
+ val p = place ?: return
+ val miles = NavFormat.miles(act)
+ b.navRoutesScroll.visibility = if (routes.size > 1) View.VISIBLE else View.GONE
+ b.navRoutes.removeAllViews()
+ val (accent, onAccent) = ChipStyle.accent(act)
+ routes.forEachIndexed { i, r ->
+ val chosen = i == selected
+ b.navRoutes.addView(MaterialButton(act, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {
+ text = NavFormat.duration(r.durationS) + "\n" + NavFormat.distance(r.distanceM, miles) +
+ (if (r.summary.isNotBlank()) " · via " + r.summary.substringBefore(',') else "")
+ isAllCaps = false
+ setTextColor(if (chosen) onAccent else accent)
+ backgroundTintList = ColorStateList.valueOf(if (chosen) accent else 0x00000000)
+ strokeColor = ColorStateList.valueOf(accent)
+ setOnClickListener { selected = i; showRoutes(refit = false) }
+ }, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { marginEnd = px(6) })
+ }
+ buildAvoidChips()
+ b.navStart.isEnabled = true
+ b.navStart.text = "Start · " + NavFormat.duration(routes[selected].durationS)
+ if (embedded) b.navCardSub.visibility = View.GONE
+ rf()?.drawRoutes(routes.map { it.points() }, selected)
+ rf()?.drawNavPlaces(emptyList(), p.lat to p.lon)
+ if (refit) fitRoute(routes[selected])
+ }
+
+ private fun buildAvoidChips() {
+ b.navAvoidScroll.visibility = View.VISIBLE
+ b.navAvoid.removeAllViews()
+ fun chip(label: String, on: Boolean, set: (Valhalla.Options, Boolean) -> Valhalla.Options) = Chip(act).apply {
+ text = label; isCheckable = true; isChecked = on; isCheckedIconVisible = false
+ setEnsureMinTouchTargetSize(false)
+ ChipStyle.apply(this)
+ setOnCheckedChangeListener { _, checked ->
+ options = set(options, checked)
+ Navigator.remember(act, options) // ticked once: the next destination starts with it too
+ plan()
+ }
+ }
+ b.navAvoid.addView(chip("Avoid tolls", options.avoidTolls) { o, v -> o.copy(avoidTolls = v) })
+ b.navAvoid.addView(chip("Avoid highways", options.avoidHighways) { o, v -> o.copy(avoidHighways = v) })
+ b.navAvoid.addView(chip("Avoid ferries", options.avoidFerries) { o, v -> o.copy(avoidFerries = v) })
+ }
+
+ private fun fitRoute(r: Route) {
+ val m = rf()?.map ?: return
+ // A coarse outline is enough to frame it (the card covers the bottom of the map).
+ val step = (r.size / 200).coerceAtLeast(1)
+ val pts = (0 until r.size step step).map { r.lats[it] to r.lons[it] } + (r.lats.last() to r.lons.last())
+ val pad = px(if (embedded) 36 else 72)
+ m.fit(pts, pad)
+ // The small pane is mostly card: once the card has its size (routes and options just appeared), frame
+ // the route in the map above it rather than behind it.
+ if (embedded) b.navCard.post {
+ if (alive() && cardShown) rf()?.map?.fit(pts, pad, pad + b.navCard.height)
+ }
+ }
+
+ private fun start() {
+ val p = place ?: return
+ val r = routes.getOrNull(selected) ?: return
+ val f = fix()
+ Navigator.begin(act, p, r, options, emptyList(), f)
+ closeCard(keepRoute = true)
+ }
+
+ fun closeCard(keepRoute: Boolean = false) {
+ planJob?.cancel()
+ b.navCard.visibility = View.GONE
+ styleBackdrop()
+ place = null; routes = emptyList()
+ if (!keepRoute && !Navigator.active) {
+ rf()?.drawRoutes(emptyList(), 0)
+ rf()?.drawNavPlaces(emptyList(), null)
+ } else if (Navigator.active) {
+ // A place looked at while guided was only a look: the route goes back on the map and you are followed again.
+ drawGuidance(force = true)
+ host.navGuidingChanged(true)
+ }
+ }
+
+ private fun openInMenu(anchor: View) {
+ val p = place ?: return
+ PopupMenu(act, anchor).apply {
+ menu.add(0, 1, 0, "Google Maps"); menu.add(0, 2, 1, "Waze"); menu.add(0, 3, 2, "Another map app")
+ setOnMenuItemClickListener {
+ HandOff.open(act, p, when (it.itemId) { 1 -> "google"; 2 -> "waze"; else -> "geo" })
+ true
+ }
+ show()
+ }
+ }
+
+ // ---- guiding -----------------------------------------------------------------------------------
+
+ /** After the map style (re)loaded: its layers are empty again. */
+ fun redraw() {
+ drawnRoute = null
+ if (Navigator.active) drawGuidance(force = true)
+ else if (routes.isNotEmpty()) place?.let {
+ rf()?.drawRoutes(routes.map { r -> r.points() }, selected); rf()?.drawNavPlaces(emptyList(), it.lat to it.lon)
+ } else if (cardShown) place?.let { rf()?.drawNavPlaces(emptyList(), it.lat to it.lon) }
+ }
+
+ private var styleCheckedAt = 0L
+
+ /** Called at every fix and change while guiding, and once the screen is up. */
+ fun refresh() {
+ val active = Navigator.active
+ if (active != wasActive) {
+ wasActive = active
+ host.navGuidingChanged(active)
+ host.navCheckStyle()
+ if (active) closeCard(keepRoute = true) else onEnded()
+ }
+ val now = System.currentTimeMillis()
+ if (active && now - styleCheckedAt > 60_000L) { styleCheckedAt = now; host.navCheckStyle() }
+ b.navBanner.visibility = if (active) View.VISIBLE else View.GONE
+ b.navBar.visibility = if (active) View.VISIBLE else View.GONE
+ styleBackdrop()
+ if (!active) return
+ val r = Navigator.route ?: return
+ val s = Navigator.state
+ val miles = NavFormat.miles(act)
+ styleMute()
+
+ if (s == null) {
+ b.navIcon.setImageResource(R.drawable.ic_nav_straight)
+ b.navDistance.text = ""
+ b.navRoad.text = Navigator.status ?: "Waiting for GPS..."
+ b.navLanes.visibility = View.GONE; b.navThen.visibility = View.GONE
+ b.navEta.text = "Arrive " + clock(System.currentTimeMillis() + (r.durationS * 1000).toLong())
+ b.navEtaSub.text = NavFormat.duration(r.durationS) + " · " + NavFormat.distance(r.distanceM, miles)
+ return
+ }
+ val banner = Prompts.banner(r, s.stepIndex, s.toManeuverM)
+ val next = r.steps.getOrNull(s.stepIndex + 1)
+ b.navIcon.setImageResource(iconRes(NavFormat.iconFor(banner?.type ?: next?.type, banner?.modifier ?: next?.modifier, next?.drivingSide)))
+ b.navDistance.text = NavFormat.distance(s.toManeuverM, miles)
+ // A roundabout names its exit ("2nd exit") ahead of the road it leads to.
+ val exit = next?.takeIf { (it.type == "roundabout" || it.type == "rotary") && (it.exit ?: 0) > 0 }?.exit?.let { NavFormat.ordinal(it) + " exit" }
+ val road = banner?.text?.takeIf { it.isNotBlank() } ?: next?.name?.takeIf { it.isNotBlank() } ?: next?.instruction?.removeSuffix(".").orEmpty()
+ b.navRoad.text = Navigator.status ?: if (exit == null) road else if (road.isBlank() || road.startsWith("Take the", true)) exit else "$exit · $road"
+ if (!embedded) bindLanes(banner?.lanes.orEmpty())
+ val then = if (embedded) null else Prompts.thenBanner(r, s.stepIndex)
+ if (then == null) b.navThen.visibility = View.GONE else {
+ b.navThen.visibility = View.VISIBLE
+ b.navThenIcon.setImageResource(iconRes(NavFormat.iconFor(then.type, then.modifier, r.steps.getOrNull(s.stepIndex + 2)?.drivingSide)))
+ b.navThenText.text = then.text
+ }
+ val left = Navigator.remainingS ?: s.remainingS
+ b.navEta.text = "Arrive " + clock(System.currentTimeMillis() + (left * 1000).toLong())
+ val stopsLeft = Navigator.stops.size
+ b.navEtaSub.text = NavFormat.duration(left) + " · " + NavFormat.distance(s.remainingM, miles) +
+ (if (stopsLeft > 0) " · $stopsLeft stop${if (stopsLeft == 1) "" else "s"}" else "")
+ drawGuidance(force = false)
+ }
+
+ private fun onEnded() {
+ rf()?.drawRoutes(emptyList(), 0)
+ rf()?.drawNavPlaces(emptyList(), null)
+ drawnRoute = null
+ if (Navigator.arrived) Toast.makeText(act, "You have arrived", Toast.LENGTH_LONG).show()
+ }
+
+ /** The part of the route still ahead, drawn again every few seconds (and when the route changes). */
+ private fun drawGuidance(force: Boolean) {
+ val r = Navigator.route ?: return
+ val now = System.currentTimeMillis()
+ if (!force && r === drawnRoute && now - drawnAt < 3_000) return
+ drawnRoute = r; drawnAt = now
+ val from = Navigator.state?.alongM ?: 0.0
+ rf()?.drawRoutes(listOf(r.pointsFrom(from)), 0)
+ rf()?.drawNavPlaces(Navigator.stops.map { it.lat to it.lon }, Navigator.destination?.let { it.lat to it.lon })
+ }
+
+ private fun bindLanes(lanes: List<com.rfsentinel.app.nav.Step.Lane>) {
+ val key = lanes.joinToString("|") { it.directions.joinToString(",") + it.active }
+ if (key == lanesKey) return
+ lanesKey = key
+ b.navLanes.removeAllViews()
+ b.navLanes.visibility = if (lanes.isEmpty()) View.GONE else View.VISIBLE
+ for (lane in lanes) {
+ b.navLanes.addView(ImageView(act).apply {
+ setImageResource(iconRes(NavFormat.laneIcon(NavFormat.laneDirection(lane))))
+ imageTintList = ColorStateList.valueOf(0xFFFFFFFF.toInt())
+ alpha = if (lane.active) 1f else 0.35f
+ setBackgroundColor(if (lane.active) 0x33FFFFFF else 0x00000000)
+ }, LinearLayout.LayoutParams(px(32), px(32)).apply { marginStart = px(2); marginEnd = px(2); gravity = Gravity.CENTER })
+ }
+ }
+
+ private fun overview() {
+ val r = Navigator.route ?: return
+ host.navLookAtRoute()
+ val from = Navigator.state?.alongM ?: 0.0
+ val pts = r.pointsFrom(from)
+ val step = (pts.size / 200).coerceAtLeast(1)
+ rf()?.map?.fit(pts.filterIndexed { i, _ -> i % step == 0 } + pts.last(), px(72))
+ }
+
+ private fun menu(anchor: View) {
+ PopupMenu(act, anchor).apply {
+ menu.add(0, 1, 0, if (Prefs.navVoice(act)) "Mute directions" else "Unmute directions")
+ menu.add(0, 2, 1, "Add a stop...")
+ menu.add(0, 3, 2, "Avoid tolls").apply { isCheckable = true; isChecked = Navigator.options.avoidTolls }
+ menu.add(0, 4, 3, "Avoid highways").apply { isCheckable = true; isChecked = Navigator.options.avoidHighways }
+ menu.add(0, 5, 4, "Avoid ferries").apply { isCheckable = true; isChecked = Navigator.options.avoidFerries }
+ menu.add(0, 6, 5, "Open in Google Maps")
+ menu.add(0, 7, 6, "Open in Waze")
+ menu.add(0, 8, 7, "End navigation")
+ setOnMenuItemClickListener { item ->
+ val dest = Navigator.destination
+ when (item.itemId) {
+ 1 -> { Prefs.setNavVoice(act, !Prefs.navVoice(act)); styleMute() }
+ 2 -> host.navSearch(com.rfsentinel.app.nav.NavSearchActivity.MODE_STOP)
+ 3 -> Navigator.changeOptions(act, Navigator.options.copy(avoidTolls = !Navigator.options.avoidTolls))
+ 4 -> Navigator.changeOptions(act, Navigator.options.copy(avoidHighways = !Navigator.options.avoidHighways))
+ 5 -> Navigator.changeOptions(act, Navigator.options.copy(avoidFerries = !Navigator.options.avoidFerries))
+ 6 -> dest?.let { HandOff.open(act, it, "google") }
+ 7 -> dest?.let { HandOff.open(act, it, "waze") }
+ 8 -> Navigator.stop()
+ }
+ true
+ }
+ show()
+ }
+ }
+
+ private fun styleMute() {
+ val on = Prefs.navVoice(act)
+ b.navMute.setImageResource(if (on) R.drawable.ic_car_volume else R.drawable.ic_car_volume_off)
+ b.navMute.contentDescription = if (on) "Mute directions" else "Unmute directions"
+ }
+
+ private fun clock(ms: Long) = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(ms))
+
+ private fun iconRes(i: NavFormat.Icon): Int = when (i) {
+ NavFormat.Icon.STRAIGHT -> R.drawable.ic_nav_straight
+ NavFormat.Icon.LEFT -> R.drawable.ic_nav_turn_left
+ NavFormat.Icon.RIGHT -> R.drawable.ic_nav_turn_right
+ NavFormat.Icon.SLIGHT_LEFT -> R.drawable.ic_nav_turn_slight_left
+ NavFormat.Icon.SLIGHT_RIGHT -> R.drawable.ic_nav_turn_slight_right
+ NavFormat.Icon.SHARP_LEFT -> R.drawable.ic_nav_turn_sharp_left
+ NavFormat.Icon.SHARP_RIGHT -> R.drawable.ic_nav_turn_sharp_right
+ NavFormat.Icon.U_TURN_LEFT -> R.drawable.ic_nav_u_turn_left
+ NavFormat.Icon.U_TURN_RIGHT -> R.drawable.ic_nav_u_turn_right
+ NavFormat.Icon.ROUNDABOUT -> R.drawable.ic_nav_roundabout_right
+ NavFormat.Icon.ROUNDABOUT_LEFT -> R.drawable.ic_nav_roundabout_left
+ NavFormat.Icon.MERGE -> R.drawable.ic_nav_merge
+ NavFormat.Icon.FORK_LEFT -> R.drawable.ic_nav_fork_left
+ NavFormat.Icon.FORK_RIGHT -> R.drawable.ic_nav_fork_right
+ NavFormat.Icon.RAMP_LEFT -> R.drawable.ic_nav_ramp_left
+ NavFormat.Icon.RAMP_RIGHT -> R.drawable.ic_nav_ramp_right
+ NavFormat.Icon.ARRIVE -> R.drawable.ic_nav_flag
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapSafety.kt b/app/src/main/java/com/rfsentinel/app/ui/MapSafety.kt
new file mode 100644
index 0000000..ab759a9
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapSafety.kt
@@ -0,0 +1,83 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import com.rfsentinel.app.util.Prefs
+import org.maplibre.android.RenderingEngine
+
+/**
+ * A map that closes the app while it starts must not do it again at every launch. The map's own start-up
+ * is marked on disk before it begins ([arm]) and cleared a few seconds after the map says it is ready (or the screen
+ * pauses normally, [disarm]). If the next launch finds the mark still there the app died in it, and [recover]
+ * steps down once at a time: the first time it makes the OpenFreeMap map use the OpenGL renderer instead of
+ * Vulkan (a phone that claims Vulkan but cannot run it), the next time it takes the map off the main screen so
+ * the rest of the app opens. The screens tell the user either way.
+ *
+ * (A phone whose graphics or native map libraries cannot run the map would otherwise crash again each time
+ * the saved view, which includes the map, is restored - until the app's data is cleared.)
+ */
+internal object MapSafety {
+ /** What [recover] did. */
+ enum class Recovery { NONE, OPENGL, MAP_OFF }
+
+ private const val FILE = "map_safety"
+ private const val ARMED = "armed_at"
+ private const val PROVIDER = "armed_provider"
+ private const val CRASHES = "crashes"
+ private const val OPENGL = "opengl"
+
+ /** How long after the map says it is ready its start-up counts as survived. */
+ const val SETTLE_MS = 3_000L
+
+ /** A map is starting in this very process (so the mark on disk is ours, not a crash's). */
+ @Volatile internal var live = false
+
+ private fun sp(context: Context) = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
+
+ /** Marks the map's start-up (synchronously: it must be on disk before a native crash can end the process). */
+ fun arm(context: Context, provider: MapEngine.Provider, now: Long = System.currentTimeMillis()) {
+ live = true
+ sp(context).edit().putLong(ARMED, now).putString(PROVIDER, provider.name).commit()
+ }
+
+ fun disarm(context: Context) {
+ live = false
+ if (sp(context).contains(ARMED)) sp(context).edit().remove(ARMED).remove(PROVIDER).apply()
+ }
+
+ /** True when the last map start-up never finished. */
+ fun crashedLastTime(context: Context): Boolean = !live && sp(context).contains(ARMED)
+
+ /** How many times in a row the map's start-up has been found unfinished (reset when it works). */
+ fun crashes(context: Context): Int = sp(context).getInt(CRASHES, 0)
+
+ /** The OpenFreeMap map has been told to use OpenGL, not Vulkan. */
+ fun openGl(context: Context): Boolean = sp(context).getBoolean(OPENGL, false)
+
+ /** The renderer MapLibre must use, or null to let it choose (Vulkan where the phone has it, else OpenGL). */
+ fun renderer(context: Context): RenderingEngine.Type? = if (openGl(context)) RenderingEngine.Type.OPENGL else null
+
+ /**
+ * If the last start-up never finished: forgets the mark and counts it. The first time for the OpenFreeMap map
+ * it switches it to OpenGL and leaves the map where it is ([Recovery.OPENGL]); otherwise it takes the map out of
+ * the saved main screen view (the list is the way back when it was the only one, [Recovery.MAP_OFF]).
+ */
+ fun recover(context: Context): Recovery {
+ if (!crashedLastTime(context)) return Recovery.NONE
+ val provider = sp(context).getString(PROVIDER, null)
+ val edit = sp(context).edit().remove(ARMED).remove(PROVIDER).putInt(CRASHES, crashes(context) + 1)
+ if (provider != MapEngine.Provider.MAPBOX.name && !openGl(context)) {
+ edit.putBoolean(OPENGL, true).commit()
+ return Recovery.OPENGL
+ }
+ edit.commit()
+ val panes = Prefs.viewPanes(context)
+ if ("map" in panes) Prefs.setViewPanes(context, panes - "map")
+ return Recovery.MAP_OFF
+ }
+
+ /** The map has been up for a few seconds: whatever came before was not a crash in it. */
+ fun worked(context: Context) {
+ disarm(context)
+ if (crashes(context) != 0) sp(context).edit().putInt(CRASHES, 0).apply()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.kt b/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.kt
new file mode 100644
index 0000000..19176a2
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.kt
@@ -0,0 +1,38 @@
+package com.rfsentinel.app.ui
+
+import android.widget.Toast
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+
+/** What the screens tell the user after [MapSafety.recover] found that the app closed while the map was starting. */
+internal object MapSafetyUi {
+
+ const val OPENGL_NOTE = "The map closed the app last time. Trying it again with the compatibility renderer."
+ const val OFF_TITLE = "The map is switched off"
+ const val OFF_MESSAGE = "The app closed twice while starting the map on this phone, so the map was taken off the " +
+ "main screen. Everything else keeps working. If it keeps happening, please send the crash log (Settings > Lists, " +
+ "tools & about > Export crash log) so the cause can be found."
+
+ /**
+ * Tells the user; [onTryAgain] (the full screen map) offers to start the map anyway, otherwise the dialog just says
+ * how it is. [onNotNow] runs when the user leaves it off.
+ */
+ fun tell(activity: AppCompatActivity, recovery: MapSafety.Recovery, onTryAgain: (() -> Unit)? = null, onNotNow: (() -> Unit)? = null) {
+ when (recovery) {
+ MapSafety.Recovery.NONE -> onTryAgain?.invoke()
+ MapSafety.Recovery.OPENGL -> {
+ Toast.makeText(activity, OPENGL_NOTE, Toast.LENGTH_LONG).show()
+ onTryAgain?.invoke()
+ }
+ MapSafety.Recovery.MAP_OFF -> {
+ val b = AlertDialog.Builder(activity).setTitle(OFF_TITLE).setCancelable(onTryAgain == null)
+ if (onTryAgain == null) b.setMessage(OFF_MESSAGE).setPositiveButton("OK", null)
+ else b.setMessage("$OFF_MESSAGE\n\nTry the map again now?")
+ .setPositiveButton("Try the map again") { _, _ -> onTryAgain() }
+ .setNegativeButton("Not now") { _, _ -> onNotNow?.invoke() }
+ .setOnCancelListener { onNotNow?.invoke() }
+ b.show()
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt
index 4ee64d8..c49b521 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt
@@ -88,6 +88,7 @@ internal class MapboxEngine(private val context: Context) : MapEngine {
override var onCameraMove: (() -> Unit)? = null
override var onIdle: (() -> Unit)? = null
override var onClick: ((Float, Float) -> Unit)? = null
+ override var onLongClick: ((Double, Double) -> Unit)? = null
override var onUserGesture: (() -> Unit)? = null
override var onFollowDismissed: (() -> Unit)? = null
@@ -117,6 +118,10 @@ internal class MapboxEngine(private val context: Context) : MapEngine {
onClick?.invoke(p.x.toFloat(), p.y.toFloat())
false
}
+ view.gestures.addOnMapLongClickListener { point ->
+ onLongClick?.invoke(point.latitude(), point.longitude())
+ onLongClick != null
+ }
view.gestures.addOnMoveListener(object : OnMoveListener {
override fun onMoveBegin(detector: MoveGestureDetector) {
onUserGesture?.invoke()
@@ -205,12 +210,12 @@ internal class MapboxEngine(private val context: Context) : MapEngine {
map.easeTo(b.build(), MapAnimationOptions.mapAnimationOptions { duration(ms) })
}
- override fun fit(points: List<Pair<Double, Double>>, paddingPx: Int) {
+ override fun fit(points: List<Pair<Double, Double>>, paddingPx: Int, bottomPx: Int) {
if (points.isEmpty()) return
if (points.size == 1) { jumpTo(points[0].first, points[0].second); return }
val p = paddingPx.toDouble()
val cam = map.cameraForCoordinates(points.map { Point.fromLngLat(it.second, it.first) },
- CameraOptions.Builder().bearing(0.0).pitch(0.0).build(), EdgeInsets(p, p, p, p), null, null)
+ CameraOptions.Builder().bearing(0.0).pitch(0.0).build(), EdgeInsets(p, p, bottomPx.toDouble(), p), null, null)
map.setCamera(cam)
}
@@ -311,16 +316,21 @@ internal class MapboxEngine(private val context: Context) : MapEngine {
}
private var brandingTop = -1
+ private var brandingAtEnd = false
- override fun placeBranding(topPx: Int) {
- if (topPx == brandingTop) return // only when it moved: setting it again asks for another layout pass
+ override fun placeBranding(topPx: Int, atEnd: Boolean) {
+ if (topPx == brandingTop && atEnd == brandingAtEnd) return // only when it moved: setting it again asks for another layout pass
brandingTop = topPx
+ brandingAtEnd = atEnd
val d = context.resources.displayMetrics.density
- view.logo.position = Gravity.TOP or Gravity.START
+ val side = if (atEnd) Gravity.END else Gravity.START
+ view.logo.position = Gravity.TOP or side
view.logo.marginTop = topPx.toFloat()
- view.logo.marginLeft = 8 * d
- view.attribution.position = Gravity.TOP or Gravity.START
+ view.logo.marginLeft = if (atEnd) 0f else 8 * d
+ view.logo.marginRight = if (atEnd) 8 * d else 0f
+ view.attribution.position = Gravity.TOP or side
view.attribution.marginTop = topPx.toFloat()
- view.attribution.marginLeft = 96 * d
+ view.attribution.marginLeft = if (atEnd) 0f else 96 * d
+ view.attribution.marginRight = if (atEnd) 96 * d else 0f
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
index ff13a97..b5671d2 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
@@ -42,6 +42,8 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
private const val DEVICES = "rf-devices"; private const val DOTS = "rf-device-dots"; private const val LABELS = "rf-device-labels"
private const val WAZE = "rf-waze"; private const val DRONE_OPS = "rf-drone-ops"; private const val DRONES = "rf-drones"
private const val AIRCRAFT = "rf-aircraft"
+ private const val NAV_ROUTES = "rf-nav-routes"; private const val NAV_PLACES = "rf-nav-places"
+ private const val NAV_ROUTE_COLOR = "#1A73E8"; private const val NAV_ALT_COLOR = "#7C8DA6"
/**
* North, east, south, west of a box grown by [fraction] on every side, clamped to valid
@@ -125,7 +127,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
/** Every layer, as map style JSON (the same on both engines). */
private fun addLayers(dark: Boolean) {
- listOf(PRECISION, CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, DEVICES, WAZE, DRONE_OPS, DRONES, AIRCRAFT)
+ listOf(NAV_ROUTES, NAV_PLACES, PRECISION, CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, DEVICES, WAZE, DRONE_OPS, DRONES, AIRCRAFT)
.forEach { map.addSource(it) }
fun get(k: String) = a("get", k)
val color = a("to-color", get("color"))
@@ -133,10 +135,32 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
val font = JSONArray(map.labelFont)
val (ink, halo) = labelColors(dark)
val overlap = arrayOf<Pair<String, Any?>>("icon-allow-overlap" to true, "icon-ignore-placement" to true)
+ // Mapbox's night look is lit like a real night: a layer that gives off no light of its own goes almost
+ // black on it (the route showed as dark navy, the Waze dots as black). Every overlay is given full
+ // brightness there, whatever kind of layer it is; only Mapbox knows these properties, so the other
+ // engine never sees them.
+ val lit = map.provider == MapEngine.Provider.MAPBOX
+ fun glow(type: String): List<String> = when (type) {
+ "line" -> listOf("line-emissive-strength")
+ "circle" -> listOf("circle-emissive-strength")
+ "fill" -> listOf("fill-emissive-strength")
+ "symbol" -> listOf("icon-emissive-strength", "text-emissive-strength")
+ else -> emptyList()
+ }
fun layer(id: String, type: String, source: String = id, minzoom: Double? = null, filter: JSONArray? = null,
- layout: JSONObject? = null, paint: JSONObject? = null) =
- o("id" to id, "type" to type, "source" to source, "minzoom" to minzoom, "filter" to filter, "layout" to layout, "paint" to paint)
+ layout: JSONObject? = null, paint: JSONObject? = null): JSONObject {
+ val lightedPaint = if (lit && glow(type).isNotEmpty()) (paint ?: JSONObject()).also { p -> glow(type).forEach { p.put(it, 1.0) } } else paint
+ return o("id" to id, "type" to type, "source" to source, "minzoom" to minzoom, "filter" to filter, "layout" to layout, "paint" to lightedPaint)
+ }
+ val routeLine = o("line-cap" to "round", "line-join" to "round")
listOf(
+ // A route to follow: the other routes offered under it, in grey, then the chosen one with a white edge.
+ layer("$NAV_ROUTES-alt", "line", NAV_ROUTES, filter = a("==", get("sel"), false), layout = routeLine,
+ paint = o("line-color" to NAV_ALT_COLOR, "line-width" to 6.0, "line-opacity" to 0.85)),
+ layer("$NAV_ROUTES-edge", "line", NAV_ROUTES, filter = a("==", get("sel"), true), layout = routeLine,
+ paint = o("line-color" to "#FFFFFF", "line-width" to 11.0)),
+ layer("$NAV_ROUTES-line", "line", NAV_ROUTES, filter = a("==", get("sel"), true), layout = routeLine,
+ paint = o("line-color" to NAV_ROUTE_COLOR, "line-width" to 7.0)),
// Pinpointed devices: the circle each is very likely in, in its colour.
layer("$PRECISION-fill", "fill", PRECISION, paint = o("fill-color" to color, "fill-opacity" to 0.18)),
layer("$PRECISION-line", "line", PRECISION, paint = o("line-color" to color, "line-width" to 1.5, "line-opacity" to 0.7)),
@@ -167,6 +191,10 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
layer(DRONES, "symbol", layout = o("icon-image" to "rf-drone", "icon-rotate" to get("dir"),
"icon-rotation-alignment" to "map", *overlap)),
// Aircraft: police / government ones bold purple with their agency and altitude, others small and grey.
+ // Where the route ends (red) and the stops on the way (white with a blue edge), above everything else.
+ layer("$NAV_PLACES-pin", "circle", NAV_PLACES, paint = o(
+ "circle-color" to a("case", a("==", get("end"), true), "#D93025", "#FFFFFF"), "circle-radius" to 9.0,
+ "circle-stroke-color" to a("case", a("==", get("end"), true), "#FFFFFF", NAV_ROUTE_COLOR), "circle-stroke-width" to 3.0)),
layer(AIRCRAFT, "symbol", layout = o("icon-image" to get("icon"), "icon-rotate" to get("track"),
"icon-rotation-alignment" to "map",
"icon-size" to a("interpolate", a("linear"), a("zoom"), 9, 0.5, 12, 1.0, 16, 2.0),
@@ -199,6 +227,24 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
})
}
+ /**
+ * Routes to follow: [lines] as (lat, lon) lists, the one at [selected] on top in blue and the
+ * others grey. Empty clears them.
+ */
+ fun drawRoutes(lines: List<List<Pair<Double, Double>>>, selected: Int) {
+ if (!ready()) return
+ set(NAV_ROUTES, lines.mapIndexedNotNull { i, pts ->
+ if (pts.size < 2) null else GeoJson.feature(GeoJson.line(pts), "sel" to (i == selected), "idx" to i)
+ })
+ }
+
+ /** The destination and the stops on the way ([stops] white, [end] red). Null clears them. */
+ fun drawNavPlaces(stops: List<Pair<Double, Double>>, end: Pair<Double, Double>?) {
+ if (!ready()) return
+ set(NAV_PLACES, stops.map { GeoJson.feature(GeoJson.point(it.first, it.second), "end" to false) } +
+ listOfNotNull(end?.let { GeoJson.feature(GeoJson.point(it.first, it.second), "end" to true) }))
+ }
+
/** A route: the trace being recorded (orange) or a saved one (blue). */
fun drawTrace(points: List<Pair<Double, Double>>, color: String) {
if (!ready()) return
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
index 85e5cf2..d2c16b0 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
@@ -126,7 +126,7 @@ class SetupActivity : AppCompatActivity() {
header("Welcome to RF Sentinel", "A quick setup - about a minute. You can change everything later in Settings.")
para("RF Sentinel listens - passively - to the Bluetooth and WiFi signals devices around you already broadcast, and flags equipment such as body cameras, license-plate cameras, drones, trackers following you and camera glasses.")
bullet("It never transmits to, connects to or interferes with any device.")
- bullet("Scans, detections and history stay on this phone. Internet is only used for OpenStreetMap maps (including known plate, speed and red-light camera locations for the area you look at - can be turned off in Settings - and, in Android Auto, destination search and routes when you navigate) and GitHub when you check for updates. Police aircraft and Waze reports are optional online sources, off until you turn them on in Settings.")
+ bullet("Scans, detections and history stay on this phone. Internet is only used for OpenStreetMap maps (including known plate, speed and red-light camera locations for the area you look at - can be turned off in Settings - and destination search and routes when you navigate, on the phone or in Android Auto) and GitHub when you check for updates. Police aircraft and Waze reports are optional online sources, off until you turn them on in Settings.")
bullet("A match means a device with that signature is nearby - not proof of who is there.")
para("Check your local laws before use. This is not legal advice.", small = true)
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
index aff9a2f..338af6e 100644
--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
@@ -196,6 +196,16 @@ object AlertPlayer {
Voice.say(context.applicationContext, text, VoiceQueue.STRONG, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)
}
+ /**
+ * A spoken driving direction. Not an alert: it follows the navigation voice setting, not the alert
+ * mute or snooze, and plays as navigation guidance (the car's speakers, music ducked, the
+ * navigation volume) on the phone too.
+ */
+ fun navigate(context: Context, text: String, urgent: Boolean) {
+ if (!Prefs.navVoice(context)) return
+ Voice.sayNav(context.applicationContext, text, urgent, carSpeechAttributes)
+ }
+
/**
* A spoken call-out only, no beep or vibration (Waze reports getting closer). It follows the voice
* settings: spoken when voice alerts are on or Android Auto is connected, and never when muted or snoozed.
diff --git a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
index 7c3cd94..3d35995 100644
--- a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
@@ -22,6 +22,7 @@ import com.rfsentinel.app.ui.DeviceDetailActivity
object NotificationHelper {
const val CHANNEL_SERVICE = "rf_sentinel_service"
const val CHANNEL_ALERTS = "rf_sentinel_alerts"
+ const val CHANNEL_NAV = "rf_sentinel_navigation"
private const val ALERT_NOTIFICATION_ID_BASE = 1000
const val SERVICE_NOTIFICATION_ID = 1
@@ -45,8 +46,13 @@ object NotificationHelper {
CHANNEL_DOWNLOADS, "Camera downloads", NotificationManager.IMPORTANCE_LOW
).apply { description = "Progress while known cameras are downloaded from OpenStreetMap" }
+ val navChannel = NotificationChannel(
+ CHANNEL_NAV, "Navigation", NotificationManager.IMPORTANCE_LOW
+ ).apply { description = "The next turn and your arrival time while you are being guided" }
+
nm.createNotificationChannel(serviceChannel)
nm.createNotificationChannel(alertChannel)
+ nm.createNotificationChannel(navChannel)
nm.createNotificationChannel(downloadChannel)
}
@@ -204,6 +210,11 @@ object NotificationHelper {
if (tag) lat ?: here?.latitude else null, if (tag) lon ?: here?.longitude else null
)
}
+ // The full screen map shows it as a card (nothing is stored there: it is gone when the card is).
+ runCatching {
+ com.rfsentinel.app.ui.AlertCards.publish(com.rfsentinel.app.ui.AlertCards.Card(
+ key, mac, hit.label, hit.evidence, hit.category, hit.confidence, following, rssi, lat, lon, System.currentTimeMillis()))
+ }
}
/**
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 17363db..5cc3b64 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -119,6 +119,9 @@ object Prefs {
/** Alert only for reports that are not behind you while you drive. Off by default. */
fun wazeAheadOnly(context: Context): Boolean = bool(context, "waze_ahead_only", false)
fun setWazeAheadOnly(context: Context, value: Boolean) = setBool(context, "waze_ahead_only", value)
+ /** With "only ahead" on, reports that are not on your way are left off the list (the map keeps them). On by default. */
+ fun wazeHideOffWay(context: Context): Boolean = bool(context, "waze_hide_off_way", true)
+ fun setWazeHideOffWay(context: Context, value: Boolean) = setBool(context, "waze_hide_off_way", value)
/** Speak again as a report gets closer (1 km, 500 m, 200 m). On by default. */
fun wazeApproach(context: Context): Boolean = bool(context, "waze_approach", true)
fun setWazeApproach(context: Context, value: Boolean) = setBool(context, "waze_approach", value)
@@ -266,16 +269,86 @@ object Prefs {
fun mapFilter(context: Context): String =
sp(context).getString("map_filter", null) ?: if (bool(context, "map_show_all", true)) "ALL" else "FLAGGED"
- fun setMapFilter(context: Context, name: String) = sp(context).edit { putString("map_filter", name) } /** Last destinations picked in the car (newest first, kept on this phone only). */
- fun recentDestinations(context: Context): List<com.rfsentinel.app.nav.OsmRouting.Destination> = runCatching {
- val json = sp(context).getString("recent_destinations", null) ?: return emptyList()
- com.google.gson.Gson().fromJson(json, Array<com.rfsentinel.app.nav.OsmRouting.Destination>::class.java).toList()
+ fun setMapFilter(context: Context, name: String) = sp(context).edit { putString("map_filter", name) }
+
+ /** Last destinations picked (newest first, kept on this phone only). */
+ fun recentDestinations(context: Context): List<com.rfsentinel.app.nav.Place> = places(context, "recent_destinations")
+ fun addRecentDestination(context: Context, d: com.rfsentinel.app.nav.Place) {
+ val list = (listOf(d) + recentDestinations(context).filterNot { sameSpot(it, d) }).take(8)
+ savePlaces(context, "recent_destinations", list)
+ }
+ fun clearRecentDestinations(context: Context) = placesSp(context).edit { remove("recent_destinations") }
+
+ // ---- navigation ----
+
+ /**
+ * Home, Work, starred and recent places live in a file of their own, which the cloud backup rules leave out
+ * (an address is not something to upload to a Google account). Recents used to sit in the main file, which is
+ * backed up: they are moved over the first time this is opened.
+ */
+ private fun placesSp(c: Context): android.content.SharedPreferences {
+ val own = c.getSharedPreferences(PLACES_FILE, Context.MODE_PRIVATE)
+ val main = sp(c)
+ for (key in PLACE_KEYS) if (main.contains(key)) {
+ if (!own.contains(key)) main.getString(key, null)?.let { v -> own.edit { putString(key, v) } }
+ main.edit { remove(key) }
+ }
+ return own
+ }
+ private const val PLACES_FILE = "nav_places"
+ private val PLACE_KEYS = listOf("recent_destinations", "nav_home", "nav_work", "nav_favorites")
+
+ private fun places(c: Context, key: String): List<com.rfsentinel.app.nav.Place> = runCatching {
+ val json = placesSp(c).getString(key, null) ?: return emptyList()
+ com.google.gson.Gson().fromJson(json, Array<com.rfsentinel.app.nav.Place>::class.java).toList()
}.getOrDefault(emptyList())
- fun addRecentDestination(context: Context, d: com.rfsentinel.app.nav.OsmRouting.Destination) {
- val list = (listOf(d) + recentDestinations(context).filterNot { it.lat == d.lat && it.lon == d.lon }).take(5)
- sp(context).edit { putString("recent_destinations", com.google.gson.Gson().toJson(list)) }
+ private fun savePlaces(c: Context, key: String, list: List<com.rfsentinel.app.nav.Place>) =
+ placesSp(c).edit { putString(key, com.google.gson.Gson().toJson(list)) }
+ private fun sameSpot(a: com.rfsentinel.app.nav.Place, b: com.rfsentinel.app.nav.Place) =
+ kotlin.math.abs(a.lat - b.lat) < 0.0002 && kotlin.math.abs(a.lon - b.lon) < 0.0002
+
+ /** Home and Work, saved from the search screen (null = not set). Kept on this phone only. */
+ fun navHome(context: Context): com.rfsentinel.app.nav.Place? = places(context, "nav_home").firstOrNull()
+ fun setNavHome(context: Context, p: com.rfsentinel.app.nav.Place?) =
+ if (p == null) placesSp(context).edit { remove("nav_home") } else savePlaces(context, "nav_home", listOf(p))
+ fun navWork(context: Context): com.rfsentinel.app.nav.Place? = places(context, "nav_work").firstOrNull()
+ fun setNavWork(context: Context, p: com.rfsentinel.app.nav.Place?) =
+ if (p == null) placesSp(context).edit { remove("nav_work") } else savePlaces(context, "nav_work", listOf(p))
+
+ /** Starred places. */
+ fun navFavorites(context: Context): List<com.rfsentinel.app.nav.Place> = places(context, "nav_favorites")
+ fun isNavFavorite(context: Context, p: com.rfsentinel.app.nav.Place) = navFavorites(context).any { sameSpot(it, p) }
+ /** Stars [p], or un-stars it when it already is. Returns whether it is a favourite now. */
+ fun toggleNavFavorite(context: Context, p: com.rfsentinel.app.nav.Place): Boolean {
+ val list = navFavorites(context)
+ val now = list.none { sameSpot(it, p) }
+ savePlaces(context, "nav_favorites", if (now) (listOf(p) + list).take(40) else list.filterNot { sameSpot(it, p) })
+ return now
}
- fun clearRecentDestinations(context: Context) = sp(context).edit { remove("recent_destinations") }
+ fun clearNavPlaces(context: Context) = placesSp(context).edit { remove("nav_home"); remove("nav_work"); remove("nav_favorites") }
+
+ /** Spoken driving directions (default on). Separate from the alert voice and its mute / snooze. */
+ fun navVoice(context: Context): Boolean = bool(context, "nav_voice", true)
+ fun setNavVoice(context: Context, v: Boolean) = setBool(context, "nav_voice", v)
+ /** While guiding, a map left on "automatic" turns to its night look after sunset (default on). */
+ fun navAutoNight(context: Context): Boolean = bool(context, "nav_auto_night", true)
+ fun setNavAutoNight(context: Context, v: Boolean) = setBool(context, "nav_auto_night", v)
+ /** Starting guidance to a destination starts the scan too (default on); a scan already running is left alone. */
+ fun navStartScan(context: Context): Boolean = bool(context, "nav_start_scan", true)
+ fun setNavStartScan(context: Context, v: Boolean) = setBool(context, "nav_start_scan", v)
+ /** Keep the screen on while guiding (default on, as navigation apps do). */
+ fun navKeepScreenOn(context: Context): Boolean = bool(context, "nav_keep_screen_on", true)
+ fun setNavKeepScreenOn(context: Context, v: Boolean) = setBool(context, "nav_keep_screen_on", v)
+ /** Routes avoid tolls / highways / ferries when these are on (defaults for every route; each can be changed per route). */
+ fun navAvoidTolls(context: Context): Boolean = bool(context, "nav_avoid_tolls", false)
+ fun setNavAvoidTolls(context: Context, v: Boolean) = setBool(context, "nav_avoid_tolls", v)
+ fun navAvoidHighways(context: Context): Boolean = bool(context, "nav_avoid_highways", false)
+ fun setNavAvoidHighways(context: Context, v: Boolean) = setBool(context, "nav_avoid_highways", v)
+ fun navAvoidFerries(context: Context): Boolean = bool(context, "nav_avoid_ferries", false)
+ fun setNavAvoidFerries(context: Context, v: Boolean) = setBool(context, "nav_avoid_ferries", v)
+ /** Distance units for guidance: "auto" (miles where the phone's region uses them), "km" or "mi". */
+ fun navUnits(context: Context): String = sp(context).getString("nav_units", "auto") ?: "auto"
+ fun setNavUnits(context: Context, v: String) = sp(context).edit { putString("nav_units", v) }
/** Tracker "following you" warnings paused until this time (epoch ms). */
fun trackerFollowPausedUntil(context: Context): Long = sp(context).getLong("tracker_follow_paused_until", 0L)
fun setTrackerFollowPausedUntil(context: Context, value: Long) = sp(context).edit { putLong("tracker_follow_paused_until", value) }
diff --git a/app/src/main/java/com/rfsentinel/app/util/Voice.kt b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
index cc9a2f1..a464a8a 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Voice.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
@@ -38,6 +38,9 @@ object Voice {
private var focus: AudioFocusRequest? = null
/** Attributes for queued items (the latest caller's: car or phone). */
private var nextAttrs: AudioAttributes? = null
+ /** The latest settings an alert / a driving direction asked for: each is spoken with its own kind's, whoever called last. */
+ private var alertAttrs: AudioAttributes? = null
+ private var navAttrs: AudioAttributes? = null
/** The audio session speech plays in, with a loudness boost on it ([Prefs.voiceBoostDb]). */
private var sessionId = 0
@@ -50,7 +53,7 @@ object Voice {
/** Queues [text] with a [VoiceQueue] priority; it's spoken as soon as nothing more urgent is. */
fun say(context: Context, text: String, priority: Int, attrs: AudioAttributes) = main.post {
app = context.applicationContext
- nextAttrs = attrs
+ nextAttrs = attrs; alertAttrs = attrs
val now = System.currentTimeMillis()
if (!queue.add(text, priority, now)) return@post
val current = speaking
@@ -61,13 +64,29 @@ object Voice {
pump()
}
+ /**
+ * Queues a driving direction. [urgent] ones (the last prompt before a turn) cut into an alert
+ * that is being read - except a "following you" alert, which a direction never interrupts.
+ */
+ fun sayNav(context: Context, text: String, urgent: Boolean, attrs: AudioAttributes) = main.post {
+ app = context.applicationContext
+ nextAttrs = attrs; navAttrs = attrs
+ if (!queue.addNav(text, System.currentTimeMillis())) return@post
+ val current = speaking
+ if (urgent && current != null && !current.nav && current.priority < VoiceQueue.FOLLOWING) {
+ tts?.stop()
+ done()
+ }
+ pump()
+ }
+
/** Says [text] right away, replacing anything queued (the Settings "Test voice" button). */
fun test(context: Context, text: String, attrs: AudioAttributes) = main.post {
app = context.applicationContext
queue.clear()
tts?.stop()
done()
- nextAttrs = attrs
+ nextAttrs = attrs; alertAttrs = attrs
// Bypasses the repeat filter: the button can be pressed again and again.
pending = VoiceQueue.Item(text, VoiceQueue.FOLLOWING + 1, System.currentTimeMillis())
pendingTries = 0
@@ -105,7 +124,7 @@ object Voice {
val retryTries = pendingTries
pending = null
val item = retry ?: queue.next(now) ?: run { releaseFocus(); return }
- val attrs = nextAttrs ?: return
+ val attrs = pickAttrs(item.nav, alertAttrs, navAttrs, nextAttrs) ?: return
tries = if (retry != null) retryTries else 0
speaking = item
speakingAttrs = attrs
@@ -303,3 +322,6 @@ object Voice {
sessionId = 0
}
}
+
+/** The audio settings an item is spoken with: its own kind's ([nav] or an alert's), else the latest caller's. */
+internal fun <T> pickAttrs(nav: Boolean, alert: T?, navigation: T?, latest: T?): T? = (if (nav) navigation else alert) ?: latest
diff --git a/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.kt b/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.kt
index 45e8b6e..2d432d1 100644
--- a/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/VoiceQueue.kt
@@ -10,16 +10,21 @@ class VoiceQueue(
private val maxAgeMs: Long = MAX_AGE_MS,
private val repeatGapMs: Long = REPEAT_GAP_MS
) {
- data class Item(val text: String, val priority: Int, val time: Long)
+ /** [nav]: a driving direction - never merged into "3 alerts", never dropped as a repeat. */
+ data class Item(val text: String, val priority: Int, val time: Long, val nav: Boolean = false)
companion object {
const val MAX_AGE_MS = 12_000L
+ /** A driving direction is useless once the turn is past: it waits less than an alert does. */
+ const val NAV_MAX_AGE_MS = 6_000L
const val REPEAT_GAP_MS = 30_000L
/** From this many waiting, they're merged into one announcement. */
const val MERGE_FROM = 3
// Priorities.
const val FOLLOWING = 4
+ /** Driving directions: level with a strong alert (a following alert still goes first). */
+ const val NAV = 3
const val STRONG = 3
const val PROBABLE = 2
const val WEAK = 1
@@ -39,6 +44,17 @@ class VoiceQueue(
return true
}
+ /**
+ * Queues a driving direction. Unlike an alert it is said again if it comes round again ("Turn
+ * left" twice in a minute are two turns); only the same words already waiting are dropped.
+ */
+ fun addNav(text: String, now: Long): Boolean {
+ val key = text.trim().lowercase()
+ if (waiting.any { it.nav && it.text.trim().lowercase() == key }) return false
+ waiting += Item(text, NAV, now, nav = true)
+ return true
+ }
+
/** True when [priority] should interrupt something of [speaking] priority. */
fun preempts(priority: Int, speaking: Int) = priority >= FOLLOWING && priority > speaking
@@ -47,23 +63,25 @@ class VoiceQueue(
* (then oldest) goes first, and a pile-up becomes one sentence.
*/
fun next(now: Long): Item? {
- waiting.removeAll { now - it.time > maxAgeMs }
+ waiting.removeAll { now - it.time > if (it.nav) NAV_MAX_AGE_MS else maxAgeMs }
if (waiting.isEmpty()) return null
val ordered = waiting.sortedWith(compareByDescending<Item> { it.priority }.thenBy { it.time })
- val item = if (ordered.size >= MERGE_FROM && ordered.first().priority < FOLLOWING) {
+ val alerts = ordered.filter { !it.nav }
+ val item = if (!ordered.first().nav && alerts.size >= MERGE_FROM && ordered.first().priority < FOLLOWING) {
// "3 alerts: Axon body camera nearby, Flock camera nearby and Drone overhead"
- val names = ordered.take(3).map { it.text.trim().trimEnd('.') }
- val more = ordered.size - names.size
+ // (driving directions waiting stay as they are, said after it.)
+ val names = alerts.take(3).map { it.text.trim().trimEnd('.') }
+ val more = alerts.size - names.size
val list = names.dropLast(1).joinToString(", ") + " and " + names.last() +
(if (more > 0) ", and $more more" else "")
- waiting.clear()
- Item("${ordered.size} alerts: $list.", ordered.first().priority, now)
- .also { ordered.forEach { o -> lastSaid[o.text.trim().lowercase()] = now } }
+ waiting.removeAll(alerts.toSet())
+ Item("${alerts.size} alerts: $list.", alerts.first().priority, now)
+ .also { alerts.forEach { o -> lastSaid[o.text.trim().lowercase()] = now } }
} else {
waiting.remove(ordered.first())
ordered.first()
}
- lastSaid[item.text.trim().lowercase()] = now
+ if (!item.nav) lastSaid[item.text.trim().lowercase()] = now
// Keep the repeat memory small.
if (lastSaid.size > 64) lastSaid.entries.removeAll { now - it.value > repeatGapMs }
return item
diff --git a/app/src/main/res/drawable/alert_card_bg.xml b/app/src/main/res/drawable/alert_card_bg.xml
new file mode 100644
index 0000000..830ac5c
--- /dev/null
+++ b/app/src/main/res/drawable/alert_card_bg.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="#F01B2127" />
+ <corners android:radius="16dp" />
+</shape>
diff --git a/app/src/main/res/drawable/ic_nav_alt_route.xml b/app/src/main/res/drawable/ic_nav_alt_route.xml
new file mode 100644
index 0000000..653ac62
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_alt_route.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M9.78,11.16l-1.42,1.42c-0.68-0.69-1.34-1.58-1.79-2.94l1.94-0.49C8.83,10.04,9.28,10.65,9.78,11.16z M11,6L7,2L3,6h3.02 C6.04,6.81,6.1,7.54,6.21,8.17l1.94-0.49C8.08,7.2,8.03,6.63,8.02,6H11z M21,6l-4-4l-4,4h2.99c-0.1,3.68-1.28,4.75-2.54,5.88 c-0.5,0.44-1.01,0.92-1.45,1.55c-0.34-0.49-0.73-0.88-1.13-1.24L9.46,13.6C10.39,14.45,11,15.14,11,17c0,0,0,0,0,0h0v5h2v-5 c0,0,0,0,0,0c0-2.02,0.71-2.66,1.79-3.63c1.38-1.24,3.08-2.78,3.2-7.37H21z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_close.xml b/app/src/main/res/drawable/ic_nav_close.xml
new file mode 100644
index 0000000..897e346
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_close.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_flag.xml b/app/src/main/res/drawable/ic_nav_flag.xml
new file mode 100644
index 0000000..6edd189
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_flag.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_fork_left.xml b/app/src/main/res/drawable/ic_nav_fork_left.xml
new file mode 100644
index 0000000..793e279
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_fork_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M9.41,15.59L8,17l-4-4l4-4l1.41,1.41L7.83,12c1.51-0.33,3.73,0.08,5.17,1.36l0-6.53l-1.59,1.59L10,7l4-4l4,4l-1.41,1.41 L15,6.83V21l-2,0v-4c-0.73-2.58-3.07-3.47-5.17-3L9.41,15.59z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_fork_right.xml b/app/src/main/res/drawable/ic_nav_fork_right.xml
new file mode 100644
index 0000000..c086530
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_fork_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M14.59,15.59L16,17l4-4l-4-4l-1.41,1.41L16.17,12c-1.51-0.33-3.73,0.08-5.17,1.36l0-6.53l1.59,1.59L14,7l-4-4L6,7 l1.41,1.41L9,6.83V21l2,0v-4c0.73-2.58,3.07-3.47,5.17-3L14.59,15.59z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_history.xml b/app/src/main/res/drawable/ic_nav_history.xml
new file mode 100644
index 0000000..5ab31b5
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_history.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_home.xml b/app/src/main/res/drawable/ic_nav_home.xml
new file mode 100644
index 0000000..49d529d
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_home.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_merge.xml b/app/src/main/res/drawable/ic_nav_merge.xml
new file mode 100644
index 0000000..752731d
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_merge.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M6.41,21L5,19.59l4.83-4.83c0.75-0.75,1.17-1.77,1.17-2.83v-5.1L9.41,8.41L8,7l4-4l4,4l-1.41,1.41L13,6.83v5.1 c0,1.06,0.42,2.08,1.17,2.83L19,19.59L17.59,21L12,15.41L6.41,21z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_navigation.xml b/app/src/main/res/drawable/ic_nav_navigation.xml
new file mode 100644
index 0000000..6731bea
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_navigation.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M12 2L4.5 20.29l.71.71L12 18l6.79 3 .71-.71z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_place.xml b/app/src/main/res/drawable/ic_nav_place.xml
new file mode 100644
index 0000000..49cfbd4
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_place.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_ramp_left.xml b/app/src/main/res/drawable/ic_nav_ramp_left.xml
new file mode 100644
index 0000000..6017568
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_ramp_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M13,21h-2V6.83L9.41,8.41L8,7l4-4l4,4l-1.41,1.41L13,6.83V9c0,4.27,4.03,7.13,6,8.27l-1.46,1.46 c-1.91-1.16-3.44-2.53-4.54-4.02L13,21z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_ramp_right.xml b/app/src/main/res/drawable/ic_nav_ramp_right.xml
new file mode 100644
index 0000000..253c79d
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_ramp_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M11,21h2V6.83l1.59,1.59L16,7l-4-4L8,7l1.41,1.41L11,6.83V9c0,4.27-4.03,7.13-6,8.27l1.46,1.46 C8.37,17.56,9.9,16.19,11,14.7L11,21z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_roundabout_left.xml b/app/src/main/res/drawable/ic_nav_roundabout_left.xml
new file mode 100644
index 0000000..82956ab
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_roundabout_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M10.08,8c0.48-2.84,2.94-5,5.92-5c3.31,0,6,2.69,6,6c0,2.97-2.16,5.44-5,5.92L17,21h-2l0-6.09c0-0.98,0.71-1.8,1.67-1.97 C18.56,12.63,20,10.98,20,9c0-2.21-1.79-4-4-4c-1.98,0-3.63,1.44-3.94,3.33C11.89,9.29,11.07,10,10.09,10l-4.26,0l1.59,1.59L6,13 L2,9l4-4l1.41,1.41L5.83,8L10.08,8z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_roundabout_right.xml b/app/src/main/res/drawable/ic_nav_roundabout_right.xml
new file mode 100644
index 0000000..90c9216
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_roundabout_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M13.92,8C13.44,5.16,10.97,3,8,3C4.69,3,2,5.69,2,9c0,2.97,2.16,5.44,5,5.92L7,21h2l0-6.09c0-0.98-0.71-1.8-1.67-1.97 C5.44,12.63,4,10.98,4,9c0-2.21,1.79-4,4-4c1.98,0,3.63,1.44,3.94,3.33C12.11,9.29,12.93,10,13.91,10l4.26,0l-1.59,1.59L18,13l4-4 l-4-4l-1.41,1.41L18.17,8L13.92,8z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_star.xml b/app/src/main/res/drawable/ic_nav_star.xml
new file mode 100644
index 0000000..a7c0166
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_star.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_star_border.xml b/app/src/main/res/drawable/ic_nav_star_border.xml
new file mode 100644
index 0000000..ee147e2
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_star_border.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_straight.xml b/app/src/main/res/drawable/ic_nav_straight.xml
new file mode 100644
index 0000000..82c91f8
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_straight.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M11,6.83 L9.41,8.41 L8,7 L12,3 L16,7 L14.59,8.41 L13,6.83 L13,21 L11,21z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_turn_left.xml b/app/src/main/res/drawable/ic_nav_turn_left.xml
new file mode 100644
index 0000000..6fec4b3
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_turn_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M6.83,11l1.59,1.59L7,14l-4-4l4-4l1.41,1.41L6.83,9L15,9c1.1,0,2,0.9,2,2v9h-2v-9L6.83,11z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_turn_right.xml b/app/src/main/res/drawable/ic_nav_turn_right.xml
new file mode 100644
index 0000000..6de1362
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_turn_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M17.17,11l-1.59,1.59L17,14l4-4l-4-4l-1.41,1.41L17.17,9L9,9c-1.1,0-2,0.9-2,2v9h2v-9L17.17,11z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_turn_sharp_left.xml b/app/src/main/res/drawable/ic_nav_turn_sharp_left.xml
new file mode 100644
index 0000000..381a232
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_turn_sharp_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M6,6.83L4.41,8.41L3,7l4-4l4,4L9.59,8.41L8,6.83V13h8c1.1,0,2,0.9,2,2v6h-2v-6H8c-1.1,0-2-0.9-2-2V6.83z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_turn_sharp_right.xml b/app/src/main/res/drawable/ic_nav_turn_sharp_right.xml
new file mode 100644
index 0000000..9007b79
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_turn_sharp_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M18,6.83l1.59,1.59L21,7l-4-4l-4,4l1.41,1.41L16,6.83V13H8c-1.1,0-2,0.9-2,2v6h2v-6h8c1.1,0,2-0.9,2-2V6.83z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_turn_slight_left.xml b/app/src/main/res/drawable/ic_nav_turn_slight_left.xml
new file mode 100644
index 0000000..a5e7b4b
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_turn_slight_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M11.66,6V4H6v5.66h2V7.41l5,5V20h2v-7.58c0-0.53-0.21-1.04-0.59-1.41l-5-5H11.66z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_turn_slight_right.xml b/app/src/main/res/drawable/ic_nav_turn_slight_right.xml
new file mode 100644
index 0000000..98b574f
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_turn_slight_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M12.34,6V4H18v5.66h-2V7.41l-5,5V20H9v-7.58c0-0.53,0.21-1.04,0.59-1.41l5-5H12.34z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_u_turn_left.xml b/app/src/main/res/drawable/ic_nav_u_turn_left.xml
new file mode 100644
index 0000000..dfa80f2
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_u_turn_left.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M18,9v12h-2V9c0-2.21-1.79-4-4-4S8,6.79,8,9v4.17l1.59-1.59L11,13l-4,4l-4-4l1.41-1.41L6,13.17V9c0-3.31,2.69-6,6-6 S18,5.69,18,9z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_u_turn_right.xml b/app/src/main/res/drawable/ic_nav_u_turn_right.xml
new file mode 100644
index 0000000..bb0f99f
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_u_turn_right.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M6,9v12h2V9c0-2.21,1.79-4,4-4s4,1.79,4,4v4.17l-1.59-1.59L13,13l4,4l4-4l-1.41-1.41L18,13.17V9c0-3.31-2.69-6-6-6 S6,5.69,6,9z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_nav_work.xml b/app/src/main/res/drawable/ic_nav_work.xml
new file mode 100644
index 0000000..a72c1f6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_work.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), for navigation. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z" />
+</vector>
diff --git a/app/src/main/res/drawable/nav_banner_bg.xml b/app/src/main/res/drawable/nav_banner_bg.xml
new file mode 100644
index 0000000..f12b506
--- /dev/null
+++ b/app/src/main/res/drawable/nav_banner_bg.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="#F01B2A33" />
+ <corners android:radius="14dp" />
+</shape>
diff --git a/app/src/main/res/layout/activity_history.xml b/app/src/main/res/layout/activity_history.xml
index 3196eec..29c040f 100644
--- a/app/src/main/res/layout/activity_history.xml
+++ b/app/src/main/res/layout/activity_history.xml
@@ -88,11 +88,11 @@
android:layout_gravity="bottom|start"
android:layout_margin="4dp"
android:background="#99FFFFFF"
- android:paddingStart="4dp"
- android:paddingEnd="4dp"
+ android:paddingStart="3dp"
+ android:paddingEnd="3dp"
android:text="© OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"
android:textColor="#333333"
- android:textSize="9sp" />
+ android:textSize="7sp" />
</FrameLayout>
<LinearLayout
diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xml
index be5d294..750efbc 100644
--- a/app/src/main/res/layout/activity_map.xml
+++ b/app/src/main/res/layout/activity_map.xml
@@ -27,11 +27,11 @@
android:layout_gravity="top|start"
android:layout_marginStart="10dp"
android:background="#99FFFFFF"
- android:paddingStart="4dp"
- android:paddingEnd="4dp"
+ android:paddingStart="3dp"
+ android:paddingEnd="3dp"
android:text="© OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"
android:textColor="#333333"
- android:textSize="9sp" />
+ android:textSize="7sp" />
<!-- Status card, with the camera-download progress bar under it -->
<LinearLayout
@@ -42,6 +42,110 @@
android:layout_margin="10dp"
android:orientation="vertical">
+ <!-- Turn-by-turn: the next turn, the lanes for it, and the one after it. -->
+ <LinearLayout
+ android:id="@+id/navBanner"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="6dp"
+ android:background="@drawable/nav_banner_bg"
+ android:orientation="vertical"
+ android:padding="12dp"
+ android:visibility="gone">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <ImageView
+ android:id="@+id/navIcon"
+ android:layout_width="52dp"
+ android:layout_height="52dp"
+ android:contentDescription="Next turn"
+ app:tint="#FFFFFF" />
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="12dp"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/navDistance"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:textColor="#FFFFFF"
+ android:textSize="28sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/navRoad"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="2"
+ android:textColor="#FFFFFF"
+ android:textSize="17sp" />
+ </LinearLayout>
+
+ <ImageButton
+ android:id="@+id/navMute"
+ android:layout_width="44dp"
+ android:layout_height="44dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="Mute directions"
+ app:tint="#FFFFFF" />
+ </LinearLayout>
+
+ <LinearLayout
+ android:id="@+id/navLanes"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:gravity="center"
+ android:orientation="horizontal"
+ android:visibility="gone" />
+
+ <LinearLayout
+ android:id="@+id/navThen"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="6dp"
+ android:gravity="center_vertical"
+ android:orientation="horizontal"
+ android:visibility="gone">
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Then"
+ android:textColor="#CCFFFFFF"
+ android:textSize="14sp" />
+
+ <ImageView
+ android:id="@+id/navThenIcon"
+ android:importantForAccessibility="no"
+ android:layout_width="22dp"
+ android:layout_height="22dp"
+ android:layout_marginStart="8dp"
+ app:tint="#FFFFFF" />
+
+ <TextView
+ android:id="@+id/navThenText"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="6dp"
+ android:layout_weight="1"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textColor="#CCFFFFFF"
+ android:textSize="14sp" />
+ </LinearLayout>
+ </LinearLayout>
+
<TextView
android:id="@+id/statusText"
android:layout_width="match_parent"
@@ -65,6 +169,101 @@
app:trackColor="#660B5C63"
app:trackCornerRadius="3dp"
app:trackThickness="6dp" />
+
+ <!-- An alert, as it comes in: what it is, where, how sure. Full screen map only (AlertCardController). -->
+ <LinearLayout
+ android:id="@+id/alertCard"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="6dp"
+ android:accessibilityLiveRegion="polite"
+ android:background="@drawable/alert_card_bg"
+ android:gravity="center_vertical"
+ android:orientation="horizontal"
+ android:padding="12dp"
+ android:visibility="gone">
+
+ <ImageView
+ android:id="@+id/alertIcon"
+ android:layout_width="44dp"
+ android:layout_height="44dp"
+ android:importantForAccessibility="no"
+ android:padding="10dp" />
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="12dp"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/alertContext"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:letterSpacing="0.08"
+ android:maxLines="1"
+ android:textColor="#9AA5AD"
+ android:textSize="11sp" />
+
+ <TextView
+ android:id="@+id/alertTag"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="8dp"
+ android:maxLines="1"
+ android:textSize="12sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/alertTitle"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="2"
+ android:textColor="#FFFFFF"
+ android:textSize="17sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/alertDetail"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="2"
+ android:textColor="#B0BAC1"
+ android:textSize="13sp" />
+
+ <TextView
+ android:id="@+id/alertFooter"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="6dp"
+ android:drawablePadding="6dp"
+ android:ellipsize="end"
+ android:gravity="center_vertical"
+ android:maxLines="1"
+ android:textColor="#8E9AA3"
+ android:textSize="12sp" />
+ </LinearLayout>
+
+ <ImageButton
+ android:id="@+id/alertClose"
+ android:layout_width="40dp"
+ android:layout_height="40dp"
+ android:layout_marginStart="4dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="Dismiss"
+ android:src="@drawable/ic_nav_close"
+ app:tint="#B0BAC1" />
+ </LinearLayout>
</LinearLayout>
<!-- Bottom: follow button, device filter chips, controls -->
@@ -75,6 +274,27 @@
android:layout_gravity="bottom"
android:orientation="vertical">
+ <!-- The round buttons: a column at the right, a row when the screen is wider than tall (code, arrangeForShape). -->
+ <LinearLayout
+ android:id="@+id/sideButtons"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="end"
+ android:orientation="vertical">
+
+ <!-- Where to? Search a destination (Home, Work, starred, recent). -->
+ <com.google.android.material.floatingactionbutton.FloatingActionButton
+ android:id="@+id/searchButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="end"
+ android:layout_marginEnd="14dp"
+ android:layout_marginBottom="8dp"
+ android:contentDescription="Search a destination"
+ android:src="@drawable/ic_search"
+ app:fabSize="mini"
+ app:tint="#FFFFFF" />
+
<!-- On the main screen: open the map full screen. -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fullscreenButton"
@@ -138,6 +358,186 @@
android:src="@drawable/ic_my_location"
app:fabSize="mini"
app:tint="#FFFFFF" />
+ </LinearLayout>
+
+ <!-- A place or the routes to it: pick one and start. -->
+ <LinearLayout
+ android:id="@+id/navCard"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:background="?android:attr/colorBackground"
+ android:orientation="vertical"
+ android:paddingStart="12dp"
+ android:paddingTop="12dp"
+ android:paddingEnd="12dp"
+ android:paddingBottom="0dp"
+ android:visibility="gone">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/navCardTitle"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textSize="18sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/navCardSub"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:alpha="0.7"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textSize="13sp" />
+ </LinearLayout>
+
+ <ImageButton
+ android:id="@+id/navCardStar"
+ android:layout_width="44dp"
+ android:layout_height="44dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="Star this place" />
+
+ <ImageButton
+ android:id="@+id/navCardClose"
+ android:layout_width="44dp"
+ android:layout_height="44dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="Close"
+ android:src="@drawable/ic_nav_close" />
+ </LinearLayout>
+
+ <HorizontalScrollView
+ android:id="@+id/navRoutesScroll"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="6dp"
+ android:scrollbars="none"
+ android:visibility="gone">
+
+ <LinearLayout
+ android:id="@+id/navRoutes"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" />
+ </HorizontalScrollView>
+
+ <HorizontalScrollView
+ android:id="@+id/navAvoidScroll"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:scrollbars="none"
+ android:visibility="gone">
+
+ <LinearLayout
+ android:id="@+id/navAvoid"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal" />
+ </HorizontalScrollView>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:orientation="horizontal">
+
+ <com.google.android.material.button.MaterialButton
+ android:id="@+id/navStart"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginEnd="6dp"
+ android:layout_weight="1"
+ android:text="Start"
+ app:icon="@drawable/ic_nav_navigation" />
+
+ <com.google.android.material.button.MaterialButton
+ android:id="@+id/navOpenIn"
+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Open in..." />
+ </LinearLayout>
+ </LinearLayout>
+
+ <!-- While guiding: arrival time, time and distance left, and the menu. -->
+ <LinearLayout
+ android:id="@+id/navBar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:background="?android:attr/colorBackground"
+ android:gravity="center_vertical"
+ android:orientation="horizontal"
+ android:paddingStart="8dp"
+ android:paddingTop="6dp"
+ android:paddingEnd="4dp"
+ android:paddingBottom="6dp"
+ android:visibility="gone">
+
+ <ImageButton
+ android:id="@+id/navEnd"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="End navigation"
+ android:src="@drawable/ic_nav_close" />
+
+ <LinearLayout
+ android:id="@+id/navEtaBox"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="8dp"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/navEta"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textSize="20sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/navEtaSub"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:alpha="0.7"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textSize="13sp" />
+ </LinearLayout>
+
+ <ImageButton
+ android:id="@+id/navOverview"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="Show the whole route"
+ android:src="@drawable/ic_nav_alt_route" />
+
+ <ImageButton
+ android:id="@+id/navMenu"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:background="?attr/selectableItemBackgroundBorderless"
+ android:contentDescription="Navigation menu"
+ android:src="@drawable/ic_car_more" />
+ </LinearLayout>
<HorizontalScrollView
android:id="@+id/mapFilterScroll"
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 1904479..55cf391 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -443,6 +443,10 @@
android:text="Clear ignored trackers" />
</LinearLayout>
+ <!-- ================= Navigation ================= -->
+ <TextView android:id="@+id/headerNav" style="@style/SettingsHeader" android:text="Navigation" />
+ <LinearLayout android:id="@+id/sectionNav" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" />
+
<!-- ================= Known cameras ================= -->
<TextView android:id="@+id/headerMap" style="@style/SettingsHeader" android:text="Map" />
<LinearLayout android:id="@+id/sectionMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml
index f2eb4ee..9010b64 100644
--- a/app/src/main/res/xml/backup_rules.xml
+++ b/app/src/main/res/xml/backup_rules.xml
@@ -5,4 +5,6 @@
<exclude domain="database" path="." />
<!-- Encrypted with a Keystore key that never leaves this phone: useless elsewhere. -->
<exclude domain="sharedpref" path="secure_store.xml" />
+ <!-- Home, Work, starred and recent destinations: addresses stay on this phone. -->
+ <exclude domain="sharedpref" path="nav_places.xml" />
</full-backup-content>
diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml
index ce9b802..5655ee4 100644
--- a/app/src/main/res/xml/data_extraction_rules.xml
+++ b/app/src/main/res/xml/data_extraction_rules.xml
@@ -6,6 +6,8 @@
<exclude domain="database" path="." />
<!-- Encrypted with a Keystore key that never leaves this phone: useless elsewhere. -->
<exclude domain="sharedpref" path="secure_store.xml" />
+ <!-- Home, Work, starred and recent destinations: addresses stay on this phone. -->
+ <exclude domain="sharedpref" path="nav_places.xml" />
</cloud-backup>
<device-transfer>
<include domain="database" path="." />
diff --git a/app/src/test/java/com/rfsentinel/app/nav/AttemptTest.kt b/app/src/test/java/com/rfsentinel/app/nav/AttemptTest.kt
new file mode 100644
index 0000000..0802e8d
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/AttemptTest.kt
@@ -0,0 +1,47 @@
+package com.rfsentinel.app.nav
+
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** A request replaced by a newer one must not be reported as a failure. */
+class AttemptTest {
+
+ @Test
+ fun aResultAndAnOrdinaryFailureAreReturned() {
+ assertEquals(5, attempt { 5 }.getOrNull())
+ val failed = attempt<Int> { throw java.io.IOException("offline") }
+ assertTrue(failed.isFailure)
+ assertEquals("offline", failed.exceptionOrNull()?.message)
+ }
+
+ @Test
+ fun aCancelledCoroutineStaysCancelledAndNeverReachesTheFailureBranch() = runBlocking {
+ var reachedFailure = false
+ var finished = false
+ val job = launch {
+ attempt { delay(10_000) }.onFailure { reachedFailure = true }
+ finished = true
+ }
+ delay(50)
+ job.cancel(); job.join()
+ assertFalse("cancellation is not a failure to report", reachedFailure)
+ assertFalse("nothing after it runs", finished)
+ assertTrue(job.isCancelled)
+ }
+
+ @Test
+ fun runCatchingWouldHaveGotItWrong() = runBlocking {
+ // The behaviour being avoided: plain runCatching turns cancellation into a failure and carries on.
+ var reachedFailure = false
+ val job = launch { runCatching { delay(10_000) }.onFailure { reachedFailure = it is CancellationException } }
+ delay(50)
+ job.cancel(); job.join()
+ assertTrue(reachedFailure)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/NavExtrasTest.kt b/app/src/test/java/com/rfsentinel/app/nav/NavExtrasTest.kt
new file mode 100644
index 0000000..2132eb5
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/NavExtrasTest.kt
@@ -0,0 +1,228 @@
+package com.rfsentinel.app.nav
+
+import com.rfsentinel.app.service.DeviceRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import java.time.LocalDateTime
+import java.time.ZoneOffset
+
+/** The turn zoom, the sun, the pace-based arrival time, roundabouts and the category search. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = android.app.Application::class)
+class NavExtrasTest {
+
+ private fun utc(y: Int, mo: Int, d: Int, h: Int, mi: Int = 0) =
+ LocalDateTime.of(y, mo, d, h, mi).toInstant(ZoneOffset.UTC).toEpochMilli()
+
+ // ---- zooming in for a turn ----
+
+ @Test
+ fun theMapZoomsInAsATurnComesUp() {
+ assertEquals(0.0, NavCamera.turnBoost(1_000.0, 30f), 0.0)
+ assertEquals(0.0, NavCamera.turnBoost(350.0, 30f), 0.0)
+ val mid = NavCamera.turnBoost(200.0, 30f)
+ assertTrue(mid > 0.3 && mid < NavCamera.MAX_BOOST)
+ assertEquals(NavCamera.MAX_BOOST, NavCamera.turnBoost(60.0, 30f), 1e-9)
+ assertEquals("closer than that: no further", NavCamera.MAX_BOOST, NavCamera.turnBoost(5.0, 30f), 1e-9)
+ assertTrue("it grows as you get nearer", NavCamera.turnBoost(100.0, 30f) > NavCamera.turnBoost(250.0, 30f))
+ }
+
+ @Test
+ fun fastRoadsGetLessAndMotorwaySpeedNone() {
+ val slow = NavCamera.turnBoost(100.0, 40f)
+ val quick = NavCamera.turnBoost(100.0, 70f)
+ assertTrue(quick < slow)
+ assertEquals(0.0, NavCamera.turnBoost(100.0, 90f), 0.0)
+ assertEquals(0.0, NavCamera.turnBoost(100.0, 130f), 0.0)
+ }
+
+ // ---- the sun ----
+
+ @Test
+ fun sunHeightAtKnownTimesAndPlaces() {
+ // Greenwich, midsummer noon: about 90 - 51.5 + 23.4 = 62 degrees.
+ assertEquals(61.9, Sun.elevationDeg(51.5, 0.0, utc(2026, 6, 21, 12)), 1.5)
+ // The same place at midnight: about 51.5 + 23.4 - 90 = -15 degrees.
+ assertEquals(-15.1, Sun.elevationDeg(51.5, 0.0, utc(2026, 6, 21, 0)), 1.5)
+ // The equator at the March equinox, noon: nearly overhead.
+ assertTrue(Sun.elevationDeg(0.0, 0.0, utc(2026, 3, 20, 12)) > 85.0)
+ // Midwinter noon in the north: low.
+ assertEquals(15.1, Sun.elevationDeg(51.5, 0.0, utc(2026, 12, 21, 12)), 1.5)
+ }
+
+ @Test
+ fun longitudeShiftsTheLocalHour() {
+ // 6 pm UTC in the east of Asia is the middle of the night; in the west of Europe it's evening light.
+ assertTrue(Sun.isNight(35.0, 135.0, utc(2026, 3, 20, 18)))
+ assertFalse(Sun.isNight(48.1, 11.6, utc(2026, 3, 20, 12)))
+ }
+
+ @Test
+ fun nightStartsAfterSunsetNotAtIt() {
+ // Munich, late June: sunset about 19:25 UTC. At 19:00 it's light, at 21:30 it's dark, noon is day.
+ assertFalse(Sun.isNight(48.1, 11.6, utc(2026, 6, 21, 19)))
+ assertTrue(Sun.isNight(48.1, 11.6, utc(2026, 6, 21, 21, 30)))
+ assertFalse(Sun.isNight(48.1, 11.6, utc(2026, 6, 21, 12)))
+ assertTrue(Sun.isNight(48.1, 11.6, utc(2026, 6, 21, 1)))
+ }
+
+ // ---- arrival time at your pace ----
+
+ private val lat0 = 10.0; private val lon0 = 20.0
+ private fun step(startM: Double, endM: Double, durationS: Double, type: String = "turn") =
+ Step(type, null, "", null, "", 0.0, 0.0, endM - startM, durationS, startM, endM, 0, emptyList(), emptyList())
+
+ /** 10 km north that the route plans to take 600 s (50 km/h... 16.7 m/s), in 10 steps. */
+ private val tenKm by lazy {
+ val ys = (0..100).map { it * 100.0 }
+ val lats = ys.map { lat0 + it / 111_194.9 }.toDoubleArray(); val lons = DoubleArray(ys.size) { lon0 }
+ val along = DoubleArray(ys.size)
+ for (i in 1 until ys.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ val steps = (0 until 10).map { step(it * 1000.0, (it + 1) * 1000.0, 60.0) }
+ Route(lats, lons, along, along.last(), 600.0, steps, "", lats.last() to lons.last())
+ }
+
+ @Test
+ fun plannedTimeIsSummedOverTheSteps() {
+ assertEquals(0.0, RouteProgress.plannedSecondsAt(tenKm, 0.0), 0.5)
+ assertEquals(30.0, RouteProgress.plannedSecondsAt(tenKm, 500.0), 1.0)
+ assertEquals(150.0, RouteProgress.plannedSecondsAt(tenKm, 2_500.0), 1.0)
+ assertEquals(600.0, RouteProgress.plannedSecondsAt(tenKm, 10_000.0), 1.0)
+ }
+
+ @Test
+ fun noPaceUntilThereIsEnoughToGoOn() {
+ assertNull("too short", RouteProgress.pace(tenKm, 0.0, 400.0, 200.0))
+ assertNull("too soon", RouteProgress.pace(tenKm, 0.0, 2_000.0, 60.0))
+ }
+
+ @Test
+ fun aSlowDriveStretchesTheTimeLeftAFastOneShrinksIt() {
+ // 2 km planned in 120 s; it took 180 s: a half slower. With 2 km of 4 km behind the weight is half.
+ val slow = RouteProgress.pace(tenKm, 0.0, 2_000.0, 180.0)!!
+ assertTrue(slow > 1.1 && slow < 1.5)
+ // After 4 km at the same relative slowness it counts in full.
+ val slower = RouteProgress.pace(tenKm, 0.0, 4_000.0, 360.0)!!
+ assertEquals(1.5, slower, 0.01)
+ val fast = RouteProgress.pace(tenKm, 0.0, 4_000.0, 180.0)!!
+ assertEquals(0.75, fast, 0.01)
+ }
+
+ @Test
+ fun paceStaysWithinReason() {
+ assertEquals("a crawl: at most twice as slow", 2.0, RouteProgress.pace(tenKm, 0.0, 5_000.0, 5_000.0)!!, 0.001)
+ assertEquals("a rocket: at most 40 percent quicker", 0.6, RouteProgress.pace(tenKm, 0.0, 5_000.0, 10.0.coerceAtLeast(90.0))!!, 0.001)
+ }
+
+ @Test
+ fun paceIsMeasuredFromWhereYouStartedOnThisRoute() {
+ // Joined 5 km in (a new route after a re-route), then 2 km took the planned 120 s: as planned.
+ assertEquals(1.0, RouteProgress.pace(tenKm, 5_000.0, 7_000.0, 120.0)!!, 0.001)
+ }
+
+ // ---- roundabouts and U-turns ----
+
+ @Test
+ fun ordinalNumbers() {
+ assertEquals(listOf("1st", "2nd", "3rd", "4th", "11th", "12th", "13th", "21st", "22nd", "101st", "111th"),
+ listOf(1, 2, 3, 4, 11, 12, 13, 21, 22, 101, 111).map { NavFormat.ordinal(it) })
+ }
+
+ @Test
+ fun leftHandTrafficTurnsTheOtherWay() {
+ assertEquals(NavFormat.Icon.ROUNDABOUT, NavFormat.iconFor("roundabout", "right", "right"))
+ assertEquals(NavFormat.Icon.ROUNDABOUT, NavFormat.iconFor("roundabout", "right"))
+ assertEquals(NavFormat.Icon.ROUNDABOUT_LEFT, NavFormat.iconFor("roundabout", "left", "left"))
+ assertEquals(NavFormat.Icon.U_TURN_LEFT, NavFormat.iconFor("turn", "uturn", "right"))
+ assertEquals(NavFormat.Icon.U_TURN_RIGHT, NavFormat.iconFor("turn", "uturn", "left"))
+ assertEquals("ordinary turns don't change", NavFormat.Icon.LEFT, NavFormat.iconFor("turn", "left", "left"))
+ }
+
+ @Test
+ fun theDrivingSideIsReadFromTheRoute() {
+ val json = """{"code":"Ok","routes":[{"distance":50.0,"duration":10.0,"geometry":"x","legs":[{"summary":"","steps":[
+ {"maneuver":{"type":"depart","modifier":"left","location":[0.0,51.0]},"name":"A","distance":50.0,"duration":10.0,"driving_side":"left","geometry":"_izlhA_ulvUonqC_ulvU"},
+ {"maneuver":{"type":"arrive","location":[0.0,51.0]},"name":"","distance":0.0,"duration":0.0,"geometry":"_izlhA_ulvU"}]}]}]}"""
+ val r = Valhalla.parse(json).single()
+ assertEquals("left", r.steps[0].drivingSide)
+ assertEquals("right", r.steps[1].drivingSide) // not given: the common case
+ }
+
+ // ---- places of one kind ----
+
+ private val overpass = """{"elements":[
+ {"type":"node","lat":48.1400,"lon":11.5800,"tags":{"amenity":"fuel","name":"Example Fuel","brand":"Brandco","addr:street":"Main Street","addr:housenumber":"4","addr:city":"Exampletown"}},
+ {"type":"way","center":{"lat":48.1500,"lon":11.5900},"tags":{"amenity":"fuel","brand":"Brandco"}},
+ {"type":"node","lat":48.1400,"lon":11.5800,"tags":{"amenity":"fuel","name":"Example Fuel"}},
+ {"type":"node","lat":48.3000,"lon":11.9000,"tags":{"amenity":"fuel","name":"Far Away"}},
+ {"type":"relation","tags":{"amenity":"fuel","name":"No position"}}]}"""
+
+ @Test
+ fun overpassAnswersBecomePlaces() {
+ val places = PlaceCategories.parse(overpass, PlaceCategories.Category.FUEL)
+ assertEquals("the duplicate and the one with no position are left out", 3, places.size)
+ assertEquals("Example Fuel", places[0].name)
+ assertEquals("4 Main Street, Exampletown", places[0].address)
+ assertEquals("a way is placed at its centre, named by its brand", "Brandco", places[1].name)
+ assertEquals(48.15, places[1].lat, 1e-9)
+ }
+
+ @Test
+ fun nearbyIsNearestFirstAndWithinReach() {
+ val places = PlaceCategories.parse(overpass, PlaceCategories.Category.FUEL)
+ val hits = PlaceCategories.rankNear(places, PlaceCategories.Category.FUEL, 48.1380, 11.5780)
+ assertEquals(listOf("Example Fuel", "Brandco"), hits.map { it.place.name })
+ assertTrue(hits[0].distanceM!! < hits[1].distanceM!!)
+ assertTrue("Far Away is 30 km off", hits.none { it.place.name == "Far Away" })
+ }
+
+ @Test
+ fun theQueriesAskForTheRightThingsAndFuzzThePosition() {
+ val near = PlaceCategories.nearQuery(PlaceCategories.Category.FOOD, 48.137412, 11.575534)
+ assertTrue(near, near.contains("\"amenity\"=\"restaurant\"") && near.contains("\"amenity\"=\"cafe\""))
+ assertTrue("a box on a 1 km grid, not the exact spot: $near", near.contains("(48.08,11.49,48.20,11.67)") && !near.contains("48.1374"))
+ assertFalse("a box, not a circle", near.contains("around"))
+ assertTrue(near.contains("out center tags"))
+ val along = PlaceCategories.alongQuery(PlaceCategories.Category.FUEL, listOf(48.137412 to 11.575534, 48.2 to 11.6))
+ assertTrue(along, along.contains("around:1750,48.137,11.576,48.200,11.600"))
+ }
+
+ // ---- along the route ----
+
+ private val northRoad by lazy {
+ val ys = (0..50).map { it * 100.0 }
+ val lats = ys.map { 48.0 + it / 111_194.9 }.toDoubleArray(); val lons = DoubleArray(ys.size) { 11.5 }
+ val along = DoubleArray(ys.size)
+ for (i in 1 until ys.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ Route(lats, lons, along, along.last(), 300.0, listOf(step(0.0, along.last(), 300.0)), "", lats.last() to lons.last())
+ }
+
+ private fun placeAt(name: String, northM: Double, eastM: Double) =
+ Place(name, "", 48.0 + northM / 111_194.9, 11.5 + eastM / (111_194.9 * Math.cos(Math.toRadians(48.0))))
+
+ @Test
+ fun alongTheRouteIsInTheOrderYouReachThem() {
+ val places = listOf(placeAt("Second", 3_000.0, 200.0), placeAt("Behind", 200.0, 0.0), placeAt("First", 1_500.0, -100.0),
+ placeAt("Too far off", 2_000.0, 4_000.0), placeAt("Last", 4_500.0, 0.0))
+ val hits = PlaceCategories.rankAlong(places, PlaceCategories.Category.FUEL, northRoad, fromAlongM = 1_000.0)
+ assertEquals(listOf("First", "Second", "Last"), hits.map { it.place.name })
+ assertEquals(500.0, hits[0].aheadM!!, 10.0)
+ assertEquals(100.0, hits[0].offM!!, 5.0)
+ }
+
+ @Test
+ fun theRouteAheadIsSampledEveryKilometre() {
+ val pts = PlaceCategories.routeSample(northRoad, 1_000.0)
+ assertTrue(pts.size in 4..6)
+ assertEquals("the first point is where you are", 48.0 + 1_000.0 / 111_194.9, pts[0].first, 0.0002)
+ assertEquals("and the last the end", northRoad.end, pts.last())
+ assertNotNull(pts)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt b/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt
new file mode 100644
index 0000000..646fd98
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt
@@ -0,0 +1,461 @@
+package com.rfsentinel.app.nav
+
+import android.app.Application
+import android.app.Notification
+import android.location.Location
+import android.os.Looper
+import com.rfsentinel.app.online.AheadOnRoad
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.service.ScanForegroundService
+import com.rfsentinel.app.util.Prefs
+import com.rfsentinel.app.util.pickAttrs
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import java.io.File
+
+/** Bugs found in a review of the navigation code: each has a test that fails without its fix. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class NavQaTest {
+ private val ctx get() = RuntimeEnvironment.getApplication()
+ private val lat0 = 10.0; private val lon0 = 20.0
+ private val mPerDeg = 111_194.9
+ private fun lat(y: Double) = lat0 + y / mPerDeg
+ private fun lon(x: Double) = lon0 + x / (mPerDeg * Math.cos(Math.toRadians(lat0)))
+
+ private var t = 1_000_000L
+ private val spoken = ArrayList<String>()
+ private var plannerCalls = 0
+
+ @Before
+ fun setUp() {
+ Navigator.stop()
+ Prefs.setNavVoice(ctx, false)
+ t = 1_000_000L
+ spoken.clear(); plannerCalls = 0
+ Navigator.clock = { t }
+ Navigator.speaker = { text, _ -> spoken += text }
+ Navigator.planner = null
+ Navigator.scanStarter = null
+ ScanForegroundService.isRunning = false
+ NavigationService.up = false
+ }
+
+ @After
+ fun tearDown() {
+ Navigator.scanStarter = null
+ ScanForegroundService.isRunning = false
+ Navigator.stop()
+ Navigator.clock = { System.currentTimeMillis() }
+ Navigator.speaker = null
+ Navigator.planner = null
+ }
+
+ // ---- helpers ----
+
+ private fun step(type: String, startM: Double, endM: Double, durationS: Double, leg: Int = 0) =
+ Step(type, null, "", null, "", 0.0, 0.0, endM - startM, durationS, startM, endM, leg, emptyList(), emptyList())
+
+ /** A road north of [km] kilometres that the route plans to drive at 16.7 m/s, in one-kilometre steps. */
+ private fun northRoad(km: Int): Route {
+ val ys = (0..km * 10).map { it * 100.0 }
+ val lats = ys.map { lat(it) }.toDoubleArray(); val lons = DoubleArray(ys.size) { lon0 }
+ val along = DoubleArray(ys.size)
+ for (i in 1 until ys.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ val total = along.last()
+ val steps = (0 until km).map { step("depart", it * 1000.0, (it + 1) * 1000.0, 60.0) } + step("arrive", total, total, 0.0)
+ return Route(lats, lons, along, total, km * 60.0, steps, "", lats.last() to lons.last())
+ }
+
+ private fun fix(y: Double, x: Double = 0.0, speed: Float = 15f, bearing: Float = 0f) = Location("test").apply {
+ latitude = lat(y); longitude = lon(x); this.speed = speed; this.bearing = bearing; accuracy = 5f
+ }
+
+ private fun feed(l: Location) {
+ val m = Navigator::class.java.getDeclaredMethod("onLocation", Location::class.java)
+ m.isAccessible = true
+ m.invoke(Navigator, l)
+ }
+
+ private fun idle() = shadowOf(Looper.getMainLooper()).idle()
+
+ private val dest = Place("Library", "1 Main Street", lat(2000.0), lon0)
+
+ private fun begin(r: Route, from: Location? = fix(0.0)) =
+ Navigator.begin(ctx, dest, r, Navigator.defaultOptions(ctx), emptyList(), from)
+
+ // ---- a route that passes close by itself further on does not move you along it ----
+
+ private fun outAndBack(): Route {
+ val out = (0..10).map { 0.0 to it * 100.0 }
+ val back = (0..10).map { 30.0 to 1000.0 - it * 100.0 }
+ val pts = out + back
+ val lats = pts.map { lat(it.second) }.toDoubleArray(); val lons = pts.map { lon(it.first) }.toDoubleArray()
+ val along = DoubleArray(pts.size)
+ for (i in 1 until pts.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ return Route(lats, lons, along, along.last(), 200.0, listOf(step("depart", 0.0, along.last(), 200.0)), "", lats.last() to lons.last())
+ }
+
+ @Test
+ fun standingBesideALaterStretchOfTheRouteDoesNotJumpYouOntoIt() {
+ val r = outAndBack()
+ val before = RouteProgress.locate(r, lat(800.0), lon(0.0), null, null)
+ assertEquals(800.0, before.alongM, 5.0)
+ // Parked 25 m to the east: the way back (30 m east) is closer than the way out (0 m)... a moment later.
+ val parked = RouteProgress.locate(r, lat(800.0), lon(22.0), null, before, advanceLimitM = 130.0)
+ assertEquals("still on the way out", 800.0, parked.alongM, 10.0)
+ // Without the limit the later stretch wins, which put you 400 m on and skipped the turn: the bug.
+ val old = RouteProgress.locate(r, lat(800.0), lon(22.0), null, before)
+ assertTrue("it would have jumped to the way back (${old.alongM})", old.alongM > 1_000.0)
+ }
+
+ @Test
+ fun theAllowanceGrowsWithTimeAndSpeedSoARealJumpAfterATunnelStillWorks() {
+ val r = outAndBack()
+ val before = RouteProgress.locate(r, lat(100.0), lon(0.0), null, null)
+ // 90 s in a tunnel at 15 m/s: you really could be 1.4 km on, on the way back.
+ val after = RouteProgress.locate(r, lat(600.0), lon(30.0), 180.0, before, advanceLimitM = (15.0 + 10.0) * 90 * 1.5 + 50)
+ assertTrue(after.alongM > 1_400.0)
+ }
+
+ // ---- a late answer from an earlier trip is ignored ----
+
+ @Test
+ fun aRouteForAnEarlierTripDoesNotReplaceTheCurrentOne() {
+ val a = northRoad(2); val b = northRoad(3); val late = northRoad(1)
+ begin(a)
+ val asked = Navigator.generation
+ begin(b, fix(0.0)) // another trip begins while a new route for the first was being looked for
+ Navigator.finishReplan(asked, late, emptyList())
+ assertTrue("trip B keeps its route", Navigator.route === b)
+ Navigator.finishReplan(Navigator.generation, late, emptyList())
+ assertTrue("an answer to the current trip is taken", Navigator.route === late)
+ Navigator.stop()
+ Navigator.finishReplan(Navigator.generation, northRoad(2), emptyList())
+ assertNull("nothing comes back from the dead", Navigator.route)
+ }
+
+ // ---- no nagging, no hammering when there is no signal ----
+
+ @Test
+ fun withNoSignalTheNewRouteIsAskedForLessAndLessOftenAndSaidOnce() {
+ Navigator.planner = { _, _, _, _, _ -> plannerCalls++; throw java.io.IOException("offline") }
+ begin(northRoad(2))
+ repeat(60) { t += 1_000; feed(fix(800.0, x = 300.0)); idle() } // a minute, 300 m off the road
+ assertEquals("asked at 15 s, then after waiting twice as long", 2, plannerCalls)
+ assertEquals("said once", 1, spoken.count { it == "Re-routing" })
+ assertTrue(Navigator.status.orEmpty(), Navigator.status!!.contains("keeping the old one"))
+ }
+
+ @Test
+ fun aFailedRerouteNeverShowsAHostNameOrStackText() {
+ Navigator.planner = { _, _, _, _, _ -> throw java.net.UnknownHostException("Unable to resolve host \"valhalla1.openstreetmap.de\"") }
+ begin(northRoad(2))
+ repeat(20) { t += 1_000; feed(fix(800.0, x = 300.0)); idle() }
+ assertEquals("No new route (no connection) - keeping the old one", Navigator.status)
+ assertEquals("No route found between these places", Navigator.failureText(Valhalla.NoRouteException("No route found between these places")))
+ }
+
+ @Test
+ fun backOnTheRouteTheNextTimeOffItIsSaidAfresh() {
+ Navigator.planner = { _, _, _, _, _ -> plannerCalls++; throw java.io.IOException("offline") }
+ begin(northRoad(2))
+ repeat(20) { t += 1_000; feed(fix(800.0, x = 300.0)); idle() }
+ assertEquals(1, spoken.count { it == "Re-routing" })
+ t += 1_000; feed(fix(850.0)); idle() // back on the road
+ assertNull(Navigator.status)
+ repeat(60) { t += 1_000; feed(fix(900.0, x = 300.0)); idle() }
+ assertEquals("a new episode is told again", 2, spoken.count { it == "Re-routing" })
+ }
+
+ // ---- arriving when you stop near the end ----
+
+ @Test
+ fun stoppingCloseToTheEndIsArriving() {
+ begin(northRoad(2))
+ // Parked in a bay 80 m short of the end of the line (the fix never gets inside 35 m).
+ repeat(12) { t += 1_000; feed(fix(1_920.0, speed = 0f)) }
+ assertTrue(Navigator.arrived)
+ assertFalse(Navigator.active)
+ assertTrue(spoken.any { it.startsWith("You have arrived") })
+ }
+
+ @Test
+ fun slowingCloseToTheEndIsNotArrivingAndNeitherIsStoppingFarFromIt() {
+ begin(northRoad(2))
+ repeat(12) { t += 1_000; feed(fix(1_920.0, speed = 6f)) } // still driving
+ assertTrue(Navigator.active)
+ repeat(12) { t += 1_000; feed(fix(1_200.0, speed = 0f)) } // a red light 800 m before it
+ assertTrue(Navigator.active)
+ assertFalse(Navigator.arrived)
+ }
+
+ // ---- the arrival time is not inflated by waiting before you set off ----
+
+ private fun drive(fromM: Double, toM: Double, speed: Float = 16.7f) {
+ var m = fromM
+ while (m < toM) { t += 1_000; m += speed; feed(fix(m.coerceAtMost(toM), speed = speed)) }
+ }
+
+ @Test
+ fun sittingParkedBeforeYouSetOffDoesNotMakeTheTripLookSlow() {
+ begin(northRoad(10), fix(0.0, speed = 0f))
+ repeat(200) { t += 1_000; feed(fix(0.0, speed = 0f)) } // over three minutes with the route chosen, the engine on
+ drive(0.0, 4_200.0)
+ assertEquals("driven at the planned speed: as planned", 1.0, Navigator.pace, 0.06)
+ }
+
+ @Test
+ fun aLongStopOnTheWayIsNotCountedAgainstThePace() {
+ begin(northRoad(10))
+ drive(0.0, 2_000.0)
+ repeat(300) { t += 1_000; feed(fix(2_000.0, speed = 0f)) } // five minutes parked
+ drive(2_000.0, 4_300.0)
+ assertTrue("the stop counted in full would make it ${Navigator.pace}", Navigator.pace < 1.3)
+ }
+
+ @Test
+ fun aSlowDriveStillShowsAsSlow() {
+ begin(northRoad(10))
+ drive(0.0, 4_200.0, speed = 11f) // two thirds of the planned speed
+ assertTrue(Navigator.pace > 1.3)
+ }
+
+ // ---- the foreground service must always become one ----
+
+ @Test
+ fun theNavigationServiceGoesToTheForegroundEvenIfTheRouteHasAlreadyEnded() {
+ Navigator.stop()
+ val controller = Robolectric.buildService(NavigationService::class.java).create()
+ val service = controller.get()
+ controller.startCommand(0, 1) // as startForegroundService would, when arriving ended the trip before it started
+ assertNotNull("startForeground was called", shadowOf(service).lastForegroundNotification)
+ }
+
+ @Test
+ fun guidanceEndingAtOnceDoesNotStopTheServiceBeforeItHasStartedForeground() {
+ // Starting next to the destination: arriving on the first fix ends the trip while the service is still
+ // starting. A stopService now crashes the app ("did not then call startForeground"); the service ends
+ // itself when it starts (see the test above).
+ val app = shadowOf(RuntimeEnvironment.getApplication())
+ while (app.nextStoppedService != null) { /* drain */ }
+ begin(northRoad(2))
+ Navigator.stop()
+ assertNull("no stopService while the start is pending", app.nextStoppedService)
+ }
+
+ @Test
+ fun onceInTheForegroundTheServiceIsStoppedWithTheTrip() {
+ val app = shadowOf(RuntimeEnvironment.getApplication())
+ while (app.nextStoppedService != null) { /* drain */ }
+ begin(northRoad(2))
+ val controller = Robolectric.buildService(NavigationService::class.java).create()
+ controller.startCommand(0, 1)
+ assertTrue(NavigationService.up)
+ Navigator.stop()
+ val stopped = app.nextStoppedService
+ assertNotNull("the running service is stopped", stopped)
+ assertTrue(stopped!!.component!!.className.endsWith("NavigationService"))
+ }
+
+ @Test
+ fun discreetModeKeepsTheTripOffTheNotification() {
+ Prefs.setDiscreetMode(ctx, true)
+ try {
+ begin(northRoad(2))
+ val controller = Robolectric.buildService(NavigationService::class.java).create()
+ controller.startCommand(0, 1)
+ val n = shadowOf(controller.get()).lastForegroundNotification
+ assertEquals("Navigation active", n.extras.getString(Notification.EXTRA_TITLE))
+ } finally {
+ Prefs.setDiscreetMode(ctx, false)
+ }
+ }
+
+ // ---- places are kept out of the cloud backup ----
+
+ @Test
+ fun placesLiveInTheirOwnFileAndLeaveTheMainOneAlone() {
+ val a = Place("Home street", "1 Example Road", 10.0, 20.0)
+ Prefs.setNavHome(ctx, a)
+ Prefs.addRecentDestination(ctx, Place("Somewhere", "", 10.1, 20.1))
+ val main = ctx.getSharedPreferences("rf_sentinel_prefs", 0)
+ val own = ctx.getSharedPreferences("nav_places", 0)
+ assertTrue(own.contains("nav_home") && own.contains("recent_destinations"))
+ assertFalse(main.contains("nav_home") || main.contains("recent_destinations"))
+ Prefs.clearNavPlaces(ctx); Prefs.clearRecentDestinations(ctx)
+ }
+
+ @Test
+ fun recentsFromTheMainFileAreMovedOverOnce() {
+ val main = ctx.getSharedPreferences("rf_sentinel_prefs", 0)
+ main.edit().putString("recent_destinations", com.google.gson.Gson().toJson(listOf(Place("Old one", "x", 1.0, 2.0)))).commit()
+ assertEquals("Old one", Prefs.recentDestinations(ctx).single().name)
+ assertFalse("gone from the backed-up file", main.contains("recent_destinations"))
+ assertTrue(ctx.getSharedPreferences("nav_places", 0).contains("recent_destinations"))
+ Prefs.clearRecentDestinations(ctx)
+ }
+
+ @Test
+ fun bothBackupRuleFilesLeaveThePlacesOut() {
+ val dir = File("src/main/res/xml")
+ for (name in listOf("backup_rules.xml", "data_extraction_rules.xml")) {
+ val xml = File(dir, name).readText()
+ assertTrue("$name excludes nav_places.xml", xml.contains("""<exclude domain="sharedpref" path="nav_places.xml" />"""))
+ }
+ // On a direct phone-to-phone transfer (your own new phone) they may go along; the cloud section is the one that matters.
+ val cloud = File(dir, "data_extraction_rules.xml").readText().substringAfter("<cloud-backup>").substringBefore("</cloud-backup>")
+ assertTrue(cloud.contains("nav_places.xml"))
+ }
+
+ // ---- avoid options are remembered for the next destination ----
+
+ @Test
+ fun aTickedAvoidOptionIsTheStartingChoiceForTheNextDestination() {
+ Prefs.setNavAvoidTolls(ctx, false); Prefs.setNavAvoidHighways(ctx, false); Prefs.setNavAvoidFerries(ctx, false)
+ assertFalse(Navigator.defaultOptions(ctx).avoidTolls)
+ // Ticked while planning (the preview's chips)...
+ Navigator.remember(ctx, Valhalla.Options(avoidTolls = true, avoidHighways = true))
+ val next = Navigator.defaultOptions(ctx)
+ assertTrue(next.avoidTolls); assertTrue(next.avoidHighways); assertFalse(next.avoidFerries)
+ // ...and un-ticked again.
+ Navigator.remember(ctx, Valhalla.Options(avoidTolls = true))
+ assertFalse(Navigator.defaultOptions(ctx).avoidHighways)
+ Navigator.remember(ctx, Valhalla.Options())
+ }
+
+ @Test
+ fun changingOptionsOnTheTripMenuIsRememberedToo() {
+ Navigator.remember(ctx, Valhalla.Options())
+ Navigator.planner = { _, _, _, _, _ -> plannerCalls++; listOf(northRoad(2)) }
+ begin(northRoad(2))
+ Navigator.changeOptions(ctx, Valhalla.Options(avoidFerries = true))
+ idle()
+ assertEquals("a new route was asked for with them", 1, plannerCalls)
+ assertTrue(Navigator.defaultOptions(ctx).avoidFerries)
+ Navigator.remember(ctx, Valhalla.Options())
+ }
+
+ // ---- the scan starts with the guidance ----
+
+ private fun startedServices(): List<String> {
+ val app = shadowOf(RuntimeEnvironment.getApplication())
+ val names = ArrayList<String>()
+ while (true) { names += (app.nextStartedService ?: break).component?.className.orEmpty() }
+ return names
+ }
+
+ @Test
+ fun startingADestinationStartsTheScanByDefault() {
+ assertTrue("the default is on", Prefs.navStartScan(ctx))
+ var started = 0
+ Navigator.scanStarter = { started++ }
+ begin(northRoad(2))
+ assertEquals(1, started)
+ assertTrue(Navigator.active)
+ }
+
+ @Test
+ fun turnedOffInSettingsGuidanceLeavesTheScanAlone() {
+ Prefs.setNavStartScan(ctx, false)
+ var started = 0
+ Navigator.scanStarter = { started++ }
+ begin(northRoad(2))
+ assertEquals(0, started)
+ assertTrue("guidance itself is unaffected", Navigator.active)
+ }
+
+ @Test
+ fun aScanAlreadyRunningIsNotStartedAgain() {
+ ScanForegroundService.isRunning = true
+ var started = 0
+ Navigator.scanStarter = { started++ }
+ begin(northRoad(2))
+ assertEquals(0, started)
+ }
+
+ @Test
+ fun withoutThePermissionsGuidanceStartsAndTheScanIsSkipped() {
+ startedServices() // what earlier steps started
+ begin(northRoad(2))
+ assertTrue(Navigator.active)
+ val started = startedServices()
+ assertTrue("guidance service started: $started", started.any { it.endsWith("NavigationService") })
+ assertFalse("the scan was not: $started", started.any { it.endsWith("ScanForegroundService") })
+ }
+
+ @Test
+ fun withThePermissionsTheRealScanServiceIsStarted() {
+ shadowOf(RuntimeEnvironment.getApplication()).grantPermissions(*com.rfsentinel.app.util.Permissions.required().toTypedArray())
+ startedServices()
+ begin(northRoad(2))
+ val started = startedServices()
+ assertTrue("scan service started: $started", started.any { it.endsWith("ScanForegroundService") })
+ }
+
+ @Test
+ fun theLastGuidanceFixIsForgottenWhenTheTripEnds() {
+ begin(northRoad(2))
+ assertNotNull("guidance has a position", Navigator.lastFix)
+ Navigator.stop()
+ assertNull("it must not stand in for a newer position afterwards", Navigator.lastFix)
+ }
+
+ // ---- smaller things ----
+
+ @Test
+ fun eachKindOfSpeechUsesItsOwnAudioSettings() {
+ assertEquals("nav", pickAttrs(true, "alert", "nav", "latest"))
+ assertEquals("alert", pickAttrs(false, "alert", "nav", "latest"))
+ assertEquals("latest", pickAttrs(true, "alert", null, "latest"))
+ assertEquals("latest", pickAttrs(false, null, "nav", "latest"))
+ }
+
+ @Test
+ fun theOldRoadIsKeptThroughAGapInTheMapButNotThroughATurn() {
+ assertTrue(AheadOnRoad.keepOldPath(movedM = 30.0, ageMs = 4_000, headingDiffDeg = 5.0))
+ assertFalse("after a turn it describes a road you left", AheadOnRoad.keepOldPath(30.0, 4_000, 60.0))
+ assertFalse("too long ago", AheadOnRoad.keepOldPath(30.0, 20_000, 5.0))
+ assertFalse("too far", AheadOnRoad.keepOldPath(150.0, 4_000, 5.0))
+ }
+
+ @Test
+ fun aLongRouteIsDrawnThinnedOutButKeepsItsEnds() {
+ val r = northRoad(10)
+ assertEquals(101, r.pointsFrom(0.0).size) // short enough: every point
+ val thin = r.pointsFrom(0.0, maxPoints = 30)
+ assertTrue(thin.size in 20..32)
+ assertEquals(r.end, thin.last())
+ assertEquals(lat(0.0), thin.first().first, 1e-6)
+ assertTrue(r.pointsFrom(5_000.0).first().first > lat(4_900.0))
+ }
+
+ @Test
+ fun theEndOfAnEarlierLegIsAStopNotTheDestination() {
+ val steps = listOf(
+ Step("depart", null, "", null, "", 0.0, 0.0, 1000.0, 60.0, 0.0, 1000.0, 0,
+ listOf(Step.Voice(40.0, "You have arrived at your destination.")), emptyList()),
+ Step("arrive", null, "", null, "", 0.0, 0.0, 0.0, 0.0, 1000.0, 1000.0, 0, emptyList(), emptyList()),
+ Step("depart", null, "", null, "", 0.0, 0.0, 1000.0, 60.0, 1000.0, 2000.0, 1,
+ listOf(Step.Voice(40.0, "You have arrived at your destination.")), emptyList()),
+ Step("arrive", null, "", null, "", 0.0, 0.0, 0.0, 0.0, 2000.0, 2000.0, 1, emptyList(), emptyList()))
+ val ys = (0..20).map { it * 100.0 }
+ val lats = ys.map { lat(it) }.toDoubleArray(); val lons = DoubleArray(ys.size) { lon0 }
+ val along = DoubleArray(ys.size) { it * 100.0 }
+ val route = Route(lats, lons, along, 2000.0, 120.0, steps, "", lats.last() to lons.last())
+ assertEquals("You have arrived at your stop.", Prompts().next(route, 0, 30.0, 10.0)?.text)
+ assertEquals("You have arrived at your destination.", Prompts().next(route, 2, 30.0, 10.0)?.text)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/NavigatorTest.kt b/app/src/test/java/com/rfsentinel/app/nav/NavigatorTest.kt
new file mode 100644
index 0000000..6c8e7fd
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/NavigatorTest.kt
@@ -0,0 +1,163 @@
+package com.rfsentinel.app.nav
+
+import android.app.Application
+import android.location.Location
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.util.Prefs
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.annotation.Config
+
+/** Following a route from fix to fix: where you are, a stop on the way, the end, and ending it. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class NavigatorTest {
+ private val ctx get() = RuntimeEnvironment.getApplication()
+ private val lat0 = 10.0; private val lon0 = 20.0
+ private val mPerDeg = 111_194.9
+ private fun lat(y: Double) = lat0 + y / mPerDeg
+
+ private var updates = 0
+ private var remove: (() -> Unit)? = null
+
+ @Before
+ fun setUp() {
+ Navigator.stop()
+ Prefs.setNavVoice(ctx, false) // no speech engine in a unit test; the prompts have their own tests
+ updates = 0
+ remove = Navigator.addListener { updates++ }
+ }
+
+ @After
+ fun tearDown() {
+ remove?.invoke()
+ Navigator.stop()
+ }
+
+ private fun step(type: String, startM: Double, endM: Double, leg: Int = 0) =
+ Step(type, null, "", null, "", 0.0, 0.0, endM - startM, (endM - startM) / 15.0, startM, endM, leg, emptyList(), emptyList())
+
+ /** North for 2 km; a stop at 1 km (end of the first leg) when [withStop]. */
+ private fun route(withStop: Boolean): Route {
+ val ys = (0..20).map { it * 100.0 }
+ val lats = ys.map { lat(it) }.toDoubleArray(); val lons = DoubleArray(ys.size) { lon0 }
+ val along = DoubleArray(ys.size)
+ for (i in 1 until ys.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ val steps = if (withStop) listOf(
+ step("depart", 0.0, 1000.0, 0), step("arrive", 1000.0, 1000.0, 0),
+ step("depart", 1000.0, 2000.0, 1), step("arrive", 2000.0, 2000.0, 1))
+ else listOf(step("depart", 0.0, 2000.0), step("arrive", 2000.0, 2000.0))
+ return Route(lats, lons, along, along.last(), along.last() / 15.0, steps, "", lats.last() to lons.last())
+ }
+
+ private fun fix(y: Double, x: Double = 0.0, speed: Float = 15f, bearing: Float = 0f) = Location("test").apply {
+ latitude = lat(y); longitude = lon0 + x / (mPerDeg * Math.cos(Math.toRadians(lat0)))
+ this.speed = speed; this.bearing = bearing
+ accuracy = 5f
+ }
+
+ private fun feed(l: Location) {
+ val m = Navigator::class.java.getDeclaredMethod("onLocation", Location::class.java)
+ m.isAccessible = true
+ m.invoke(Navigator, l)
+ }
+
+ private val dest = Place("Example Library", "1 Main Street", lat(2000.0), lon0)
+
+ @Test
+ fun followsTheRouteAndCountsDown() {
+ val r = route(false)
+ Navigator.begin(ctx, dest, r, Navigator.defaultOptions(ctx), emptyList(), fix(0.0))
+ assertTrue(Navigator.active)
+ assertEquals(dest, Navigator.destination)
+ assertNotNull("the start fix already placed you", Navigator.state)
+ val before = Navigator.state!!.remainingM
+ feed(fix(600.0))
+ val s = Navigator.state!!
+ assertEquals(600.0, s.alongM, 8.0)
+ assertTrue(s.remainingM < before)
+ assertEquals(1400.0, s.remainingM, 10.0)
+ assertTrue("listeners hear every fix", updates >= 2)
+ assertFalse(Navigator.arrived)
+ }
+
+ @Test
+ fun theDestinationIsRememberedForNextTime() {
+ Prefs.clearRecentDestinations(ctx)
+ Navigator.begin(ctx, dest, route(false), Navigator.defaultOptions(ctx), emptyList(), null)
+ assertEquals(dest.name, Prefs.recentDestinations(ctx).first().name)
+ }
+
+ @Test
+ fun arrivingEndsTheGuidance() {
+ Navigator.begin(ctx, dest, route(false), Navigator.defaultOptions(ctx), emptyList(), fix(0.0))
+ feed(fix(1_990.0))
+ assertFalse("done", Navigator.active)
+ assertTrue(Navigator.arrived)
+ assertNull(Navigator.route)
+ assertNull(Navigator.destination)
+ }
+
+ @Test
+ fun aStopOnTheWayIsDroppedOnceYouAreOnTheNextLeg() {
+ val stop = Place("Stop", "", lat(1000.0), lon0)
+ Navigator.begin(ctx, dest, route(true), Navigator.defaultOptions(ctx), listOf(stop), fix(0.0))
+ assertEquals(1, Navigator.stops.size)
+ feed(fix(500.0))
+ assertEquals("still heading for the stop", 1, Navigator.stops.size)
+ feed(fix(1_100.0))
+ assertTrue("past the stop: on to the destination", Navigator.stops.isEmpty())
+ assertTrue(Navigator.active)
+ feed(fix(1_990.0))
+ assertTrue(Navigator.arrived)
+ }
+
+ @Test
+ fun farFromTheRouteYouAreOffIt() {
+ Navigator.begin(ctx, dest, route(false), Navigator.defaultOptions(ctx), emptyList(), fix(0.0))
+ feed(fix(800.0, x = 250.0))
+ assertTrue(Navigator.state!!.offM > Navigator.OFF_ROUTE_M)
+ assertTrue("still guiding while a new route is looked for", Navigator.active)
+ }
+
+ @Test
+ fun stoppingClearsEverything() {
+ Navigator.begin(ctx, dest, route(false), Navigator.defaultOptions(ctx), emptyList(), fix(0.0))
+ Navigator.stop()
+ assertFalse(Navigator.active)
+ assertNull(Navigator.state)
+ assertTrue(Navigator.stops.isEmpty())
+ assertFalse("ended by hand: not an arrival", Navigator.arrived)
+ }
+
+ @Test
+ fun theSettingsDefaultsShapeEveryRoute() {
+ Prefs.setNavAvoidTolls(ctx, true)
+ Prefs.setNavAvoidFerries(ctx, true)
+ val o = Navigator.defaultOptions(ctx)
+ assertTrue(o.avoidTolls); assertTrue(o.avoidFerries); assertFalse(o.avoidHighways)
+ Prefs.setNavAvoidTolls(ctx, false); Prefs.setNavAvoidFerries(ctx, false)
+ }
+
+ @Test
+ fun placesAreKeptStarredAndForgotten() {
+ Prefs.clearNavPlaces(ctx)
+ val a = Place("A", "x", 10.001, 20.001)
+ assertTrue(Prefs.toggleNavFavorite(ctx, a))
+ assertTrue(Prefs.isNavFavorite(ctx, a))
+ assertFalse("again: no longer starred", Prefs.toggleNavFavorite(ctx, a))
+ Prefs.setNavHome(ctx, a)
+ assertEquals("A", Prefs.navHome(ctx)?.name)
+ Prefs.clearNavPlaces(ctx)
+ assertNull(Prefs.navHome(ctx))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/OsmRoutingTest.kt b/app/src/test/java/com/rfsentinel/app/nav/OsmRoutingTest.kt
deleted file mode 100644
index 9b03d11..0000000
--- a/app/src/test/java/com/rfsentinel/app/nav/OsmRoutingTest.kt
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.rfsentinel.app.nav
-
-import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-class OsmRoutingTest {
-
- // Synthetic responses (made-up places and coordinates).
- private val search = """
- [{"lat":"10.5100","lon":"-20.5000","name":"Example Library","display_name":"Example Library, 1 Main Street, Exampletown"},
- {"lat":"10.6000","lon":"-20.4000","name":"","display_name":"Main Street, Othertown"},
- {"lat":"bad","lon":"-20.4","display_name":"skipped"}]
- """.trimIndent()
-
- // A straight road north, then a left turn west, then arrival.
- private val route = """
- {"code":"Ok","routes":[{"distance":2200.0,"duration":180.0,
- "geometry":{"coordinates":[[-20.5,10.50],[-20.5,10.505],[-20.5,10.51],[-20.505,10.51],[-20.51,10.51]]},
- "legs":[{"steps":[
- {"name":"Main Street","maneuver":{"type":"depart","location":[-20.5,10.50]}},
- {"name":"Oak Road","maneuver":{"type":"turn","modifier":"left","location":[-20.5,10.51]}},
- {"name":"","maneuver":{"type":"arrive","location":[-20.51,10.51]}}
- ]}]}]}
- """.trimIndent()
-
- @Test
- fun parsesSearchResults() {
- val r = OsmRouting.parseSearch(search)
- assertEquals(2, r.size)
- assertEquals("Example Library", r[0].name)
- assertEquals("1 Main Street, Exampletown", r[0].address) // first two parts only
- assertEquals("Main Street", r[1].name) // no name: first part of the address
- assertEquals(10.51, r[0].lat, 1e-9)
- }
-
- @Test
- fun parsesRouteAndWordsInstructions() {
- val r = OsmRouting.parseRoute(route)
- assertEquals(5, r.points.size)
- assertEquals(10.505 to -20.5, r.points[1])
- assertEquals(3, r.steps.size)
- assertEquals("Turn left onto Oak Road", r.steps[1].instruction)
- assertEquals("Arrive at your destination", r.steps[2].instruction)
- assertEquals("At the roundabout, take exit 2 onto A Road", OsmRouting.instructionFor("roundabout", "right", "A Road", 2))
- assertEquals("Keep slightly right", OsmRouting.instructionFor("continue", "slight right", "", null))
- }
-
- @Test
- fun noRouteIsAnError() {
- assertTrue(runCatching { OsmRouting.parseRoute("""{"code":"NoRoute","routes":[]}""") }.isFailure)
- }
-
- @Test
- fun progressFindsNextTurnRemainingAndOffRoute() {
- val r = OsmRouting.parseRoute(route)
- // Halfway up the first road: next is the left turn ~550 m ahead.
- val p = Navigator.progressOf(r, 10.505, -20.5)
- assertEquals("Turn left onto Oak Road", p.nextStep?.instruction)
- assertEquals(556.0, p.toNextStepM, 15.0)
- assertTrue(p.offRouteM < 1.0)
- assertFalse(p.arrived)
- // 300 m beside the road: off route.
- assertTrue(Navigator.progressOf(r, 10.505, -20.4973).offRouteM > Navigator.OFF_ROUTE_M)
- // At the end: arrived.
- assertTrue(Navigator.progressOf(r, 10.51, -20.51).arrived)
- assertEquals("1.5 kilometres", Navigator.roundDistance(1500.0))
- assertEquals("250 metres", Navigator.roundDistance(260.0))
- }
-}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/PlaceSearchTest.kt b/app/src/test/java/com/rfsentinel/app/nav/PlaceSearchTest.kt
new file mode 100644
index 0000000..fac02bf
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/PlaceSearchTest.kt
@@ -0,0 +1,299 @@
+package com.rfsentinel.app.nav
+
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.util.concurrent.atomic.AtomicBoolean
+
+/** Place search: putting results in the order a person expects, reading both servers' answers, and the submitted race. */
+class PlaceSearchTest {
+
+ @After
+ fun tearDown() { Places.fetcher = null }
+
+ private fun p(name: String, lat: Double = 48.0, lon: Double = 11.0, address: String = "") = Place(name, address, lat, lon)
+
+ // ---- reading words ----
+
+ @Test
+ fun accentsCaseAndPunctuationAreIgnored() {
+ assertEquals("cafe bar zurich", PlaceRank.normalize("Café-Bar Zürich"))
+ assertEquals("strasse", PlaceRank.normalize("Straße"))
+ assertEquals("lodz", PlaceRank.normalize("Łódź"))
+ assertEquals("orsted", PlaceRank.normalize("Ørsted"))
+ assertEquals("", PlaceRank.normalize(" - "))
+ }
+
+ @Test
+ fun howWellAPlaceAnswersTheWords() {
+ assertEquals(0, PlaceRank.matchClass("olympiapark", p("Olympiapark")))
+ assertEquals(1, PlaceRank.matchClass("olympia", p("Olympiapark")))
+ assertEquals(2, PlaceRank.matchClass("park", p("Olympia Park")))
+ assertEquals("inside a word", 3, PlaceRank.matchClass("park", p("Olympiapark")))
+ assertEquals("every word is somewhere in name or address", 3, PlaceRank.matchClass("cafe munich", p("Cafe Luitpold", address = "Munich")))
+ assertEquals(4, PlaceRank.matchClass("zoo", p("Olympiapark")))
+ assertEquals(4, PlaceRank.matchClass(" ", p("Olympiapark")))
+ }
+
+ @Test
+ fun typingWithoutAccentsFindsTheAccentedName() {
+ assertEquals(1, PlaceRank.matchClass("cafe lu", p("Café Luitpold")))
+ }
+
+ // ---- order ----
+
+ @Test
+ fun theNameYouTypedBeatsAPlaceThatOnlyMentionsIt() {
+ val list = listOf(p("Park Hotel"), p("Central Park"), p("Park"), p("Parkside Mall"))
+ val ranked = PlaceRank.rank("park", list, null, null).map { it.name }
+ assertEquals("Park", ranked[0])
+ assertEquals(setOf("Park Hotel", "Parkside Mall"), ranked.subList(1, 3).toSet())
+ assertEquals("Central Park", ranked[3])
+ }
+
+ @Test
+ fun amongEqualsTheNearestComesFirst() {
+ val far = p("Starbucks", lat = 48.50)
+ val near = p("Starbucks", lat = 48.001)
+ val mid = p("Starbucks", lat = 48.10)
+ assertEquals(listOf(near, mid, far), PlaceRank.rank("starbucks", listOf(far, mid, near), 48.0, 11.0))
+ }
+
+ @Test
+ fun aNearbyPlaceBeatsTheSameNameFarAway() {
+ // Looking for "biodome" from (10, 10): the one 20 km off, then one 500 km off, before two on another continent.
+ val here = 10.0 to 10.0
+ val farExact = p("Biodome", lat = 55.0, lon = 12.0)
+ val farExact2 = p("Biodome", lat = -30.0, lon = 100.0)
+ val nearStart = p("Biodome de Ville", lat = 10.15, lon = 10.1)
+ val nearWord = p("Parc Biodome", lat = 10.1, lon = 10.2)
+ val midExact = p("Biodome", lat = 14.0, lon = 10.0) // ~440 km
+ val ranked = PlaceRank.rank("biodome", listOf(farExact, nearWord, farExact2, midExact, nearStart), here.first, here.second)
+ assertEquals(listOf(nearStart, nearWord, midExact), ranked.take(3))
+ assertEquals("the far ones keep their name order, nearest first among equals", setOf(farExact, farExact2), ranked.drop(3).toSet())
+ }
+
+ @Test
+ fun whenEverythingIsFarTheBestNameStillWins() {
+ val far = listOf(p("Park Hotel", lat = 55.0, lon = 12.0), p("Park", lat = 56.0, lon = 13.0), p("Central Park", lat = 55.5, lon = 12.5))
+ assertEquals("Park", PlaceRank.rank("park", far, 10.0, 10.0).first().name)
+ }
+
+ @Test
+ fun theDistanceStepsAreFiftyTwoFiftyAndAThousandKilometres() {
+ assertEquals(0, PlaceRank.distanceStep(49_000.0)); assertEquals(1, PlaceRank.distanceStep(51_000.0))
+ assertEquals(1, PlaceRank.distanceStep(249_000.0)); assertEquals(2, PlaceRank.distanceStep(251_000.0))
+ assertEquals(2, PlaceRank.distanceStep(999_000.0)); assertEquals(3, PlaceRank.distanceStep(1_001_000.0))
+ }
+
+ @Test
+ fun withoutAPositionTheServersOrderStays() {
+ val list = listOf(p("Cafe A", lat = 49.0), p("Cafe B", lat = 48.0), p("Cafe C", lat = 50.0))
+ assertEquals(list, PlaceRank.rank("cafe", list, null, null))
+ }
+
+ @Test
+ fun theSamePlaceListedTwiceCountsOnce() {
+ val a = p("Olympiapark", 48.1687, 11.5503)
+ val twin = p("olympiapark", 48.1690, 11.5510) // an area and a point for one park
+ val farAway = p("Olympiapark", 52.5, 13.4)
+ val other = p("Olympiapark Nord", 48.1688, 11.5504)
+ assertEquals(listOf(a, farAway, other), PlaceRank.dedupe(listOf(a, twin, farAway, other)))
+ }
+
+ @Test
+ fun aLongerQueryKeepsWhatStillFits() {
+ val earlier = listOf(p("Olympiapark"), p("Olympia Mall"), p("Odeon"))
+ assertEquals(listOf("Olympiapark"), PlaceRank.stillMatching("olympiap", earlier).map { it.name })
+ assertEquals(listOf("Olympiapark", "Olympia Mall"), PlaceRank.stillMatching("olympia", earlier).map { it.name })
+ }
+
+ // ---- your own places ----
+
+ @Test
+ fun yourOwnPlacesAreFoundByNameAddressAndByHomeAndWork() {
+ val home = Place("12 Example Street", "Exampletown", 48.0, 11.0)
+ val work = Place("Office", "Business Road, Workville", 48.5, 11.5)
+ val fav = Place("Café Luitpold", "Munich", 48.14, 11.57)
+ val recent = Place("Library", "1 Main Street", 48.2, 11.6)
+ val none = emptyList<Place>()
+
+ assertEquals("Home", PlaceRank.mine("ho", home, work, none, none).first().name)
+ assertEquals("the address is shown for it", "Exampletown", PlaceRank.mine("home", home, work, none, none).first().address)
+ assertEquals(listOf("Home"), PlaceRank.mine("exam", home, work, none, none).map { it.name })
+ assertEquals(listOf("Work"), PlaceRank.mine("work", home, work, none, none).map { it.name })
+ assertEquals(listOf("Café Luitpold"), PlaceRank.mine("cafe", home, work, listOf(fav), listOf(recent)).map { it.name })
+ assertEquals(listOf("Library"), PlaceRank.mine("main", null, null, listOf(fav), listOf(recent)).map { it.name })
+ assertTrue(PlaceRank.mine("zzz", home, work, listOf(fav), listOf(recent)).isEmpty())
+ assertTrue(PlaceRank.mine("", home, work, listOf(fav), listOf(recent)).isEmpty())
+ }
+
+ @Test
+ fun aStarredPlaceThatIsAlsoRecentIsListedOnceAndAtMostFourShow() {
+ val fav = p("Cafe One", 48.0, 11.0)
+ val many = (1..8).map { p("Cafe ${it + 1}", 48.0 + it, 11.0) }
+ val found = PlaceRank.mine("cafe", null, null, listOf(fav), listOf(fav) + many)
+ assertEquals(4, found.size)
+ assertEquals(1, found.count { it.name == "Cafe One" })
+ }
+
+ // ---- coordinates ----
+
+ @Test
+ fun aPairOfCoordinatesIsAPlace() {
+ val c = PlaceRank.coordinates("48.137, 11.575")!!
+ assertEquals(48.137, c.lat, 1e-9); assertEquals(11.575, c.lon, 1e-9)
+ assertEquals("Coordinates", c.address)
+ assertEquals(11.575, PlaceRank.coordinates("48.137 11.575")!!.lon, 1e-9)
+ assertEquals(11.575, PlaceRank.coordinates("48.137;11.575")!!.lon, 1e-9)
+ val south = PlaceRank.coordinates("-33.8688, 151.2093")!!
+ assertEquals(-33.8688, south.lat, 1e-9); assertEquals(151.2093, south.lon, 1e-9)
+ }
+
+ @Test
+ fun otherNumbersAreNotCoordinates() {
+ assertNull("out of range", PlaceRank.coordinates("91.5, 10.5"))
+ assertNull("out of range", PlaceRank.coordinates("45.5, 190.5"))
+ assertNull("a house number and a postcode", PlaceRank.coordinates("10 20"))
+ assertNull(PlaceRank.coordinates("12 Main Street"))
+ assertNull(PlaceRank.coordinates("1.5, 2.5, 3.5"))
+ assertNull(PlaceRank.coordinates("Cafe 48.137, 11.575"))
+ }
+
+ @Test
+ fun anAnswerIsRememberedPerWordsAndPerKilometreOfPosition() {
+ assertEquals(PlaceRank.cacheKey("Café Bar", 48.1371, 11.5721), PlaceRank.cacheKey("cafe-bar", 48.1374, 11.5719))
+ assertNotEquals(PlaceRank.cacheKey("cafe", 48.13, 11.57), PlaceRank.cacheKey("cafe", 48.25, 11.57))
+ assertNotEquals(PlaceRank.cacheKey("cafe", 48.13, 11.57), PlaceRank.cacheKey("cafe", null, null))
+ }
+
+ @Test
+ fun onlyLanguagesPhotonAcceptsAreAsked() {
+ // Found against the live server: "it", "es" and "pt" are answered HTTP 400, which broke search on those phones.
+ assertEquals("en", Places.language("en")); assertEquals("de", Places.language("de")); assertEquals("fr", Places.language("fr"))
+ for (l in listOf("it", "es", "pt", "ja", "")) assertNull(l, Places.language(l))
+ }
+
+ // ---- reading the servers' answers ----
+
+ @Test
+ fun photonSaysWhatKindOfPlaceItIs() {
+ val found = Places.parse(javaClass.getResource("/photon_search.json")!!.readText())
+ assertEquals("Park · Munich, Bavaria", found[0].address)
+ assertEquals("a house or a street keeps just its address", null, Places.kindLabel("building", "yes"))
+ assertEquals("Petrol station", Places.kindLabel("amenity", "fuel"))
+ assertEquals("Cafe", Places.kindLabel("amenity", "cafe"))
+ assertEquals("Train station", Places.kindLabel("railway", "station"))
+ assertEquals("Hot spring", Places.kindLabel("natural", "hot_spring"))
+ assertNull(Places.kindLabel(null, "park"))
+ }
+
+ @Test
+ fun nominatimAnswersBecomePlacesToo() {
+ val json = """[
+ {"place_id":1,"lat":"48.1687059","lon":"11.5503638","category":"leisure","type":"park","name":"Olympiapark",
+ "display_name":"Olympiapark, Milbertshofen, Munich, Bavaria, Germany",
+ "address":{"leisure":"Olympiapark","suburb":"Milbertshofen","city":"Munich","state":"Bavaria","country":"Germany"}},
+ {"place_id":2,"lat":"48.1","lon":"11.5","category":"building","type":"house","name":"",
+ "display_name":"12, Example Street, Exampletown, Region, Country",
+ "address":{"house_number":"12","road":"Example Street","town":"Exampletown","state":"Region"}},
+ {"place_id":3,"lat":"x","lon":"11.5","name":"Broken"}
+ ]"""
+ val found = Places.parseNominatim(json)
+ assertEquals(2, found.size)
+ assertEquals("Olympiapark", found[0].name)
+ assertEquals("Park · Munich, Bavaria", found[0].address)
+ assertEquals(48.1687059, found[0].lat, 1e-6) // lat first: not mixed up with Photon's lon, lat
+ assertEquals(11.5503638, found[0].lon, 1e-6)
+ assertEquals("12 Example Street", found[1].name)
+ assertEquals("Exampletown, Region", found[1].address)
+ assertTrue(Places.parseNominatim("[]").isEmpty())
+ }
+
+ // ---- the submitted search: both servers at once ----
+
+ private val photon = """{"features":[{"geometry":{"coordinates":[11.55,48.17]},"properties":{"name":"Olympiapark","city":"Munich","osm_key":"leisure","osm_value":"park"}},
+ {"geometry":{"coordinates":[13.4,52.5]},"properties":{"name":"Olympia Stadium","city":"Berlin","osm_key":"leisure","osm_value":"stadium"}}]}"""
+ private val nominatim = """[{"lat":"48.1701","lon":"11.5511","category":"leisure","type":"park","name":"Olympiapark","address":{"city":"Munich"}},
+ {"lat":"48.2","lon":"11.6","category":"tourism","type":"attraction","name":"Olympia Tower","address":{"city":"Munich"}}]"""
+
+ private fun fake(photonMs: Long, nominatimMs: Long, photonOk: Boolean = true, nominatimOk: Boolean = true) {
+ Places.fetcher = { url, _, _ ->
+ if (url.startsWith(Places.NOMINATIM_URL)) {
+ delay(nominatimMs); if (!nominatimOk) error("nominatim down"); nominatim
+ } else {
+ delay(photonMs); if (!photonOk) error("photon down"); photon
+ }
+ }
+ }
+
+ @Test
+ fun theFirstAnswerShowsAtOnceAndTheOtherIsMergedIn() = runBlocking {
+ fake(photonMs = 300, nominatimMs = 20)
+ val shown = ArrayList<List<String>>()
+ val any = Places.searchSubmitted("olympia", 48.0, 11.0, "test") { shown += it.map { p -> p.name } }
+ assertTrue(any)
+ assertEquals("one update per answer", 2, shown.size)
+ assertEquals("Nominatim's answer first", setOf("Olympiapark", "Olympia Tower"), shown[0].toSet())
+ assertTrue("then Photon's joined in", shown[1].contains("Olympia Stadium"))
+ assertEquals("the same park from both is one row", 1, shown[1].count { it == "Olympiapark" })
+ assertEquals("nearest first among equals", "Olympiapark", shown[1][0])
+ }
+
+ @Test
+ fun aSlowSecondServerIsNotWaitedForBeyondTheGrace() = runBlocking {
+ val cancelled = AtomicBoolean(false)
+ Places.fetcher = { url, _, _ ->
+ if (url.startsWith(Places.NOMINATIM_URL)) { delay(10); nominatim }
+ else try { delay(10_000); photon } catch (e: CancellationException) { cancelled.set(true); throw e }
+ }
+ val started = System.currentTimeMillis()
+ var updates = 0
+ val any = Places.searchSubmitted("olympia", null, null, "test", graceMs = 150) { updates++ }
+ val took = System.currentTimeMillis() - started
+ assertTrue(any)
+ assertEquals(1, updates)
+ assertTrue("returned after the grace, not 10 s ($took ms)", took < 3_000)
+ assertTrue("and the slow request was stopped", cancelled.get())
+ }
+
+ @Test
+ fun oneServerDownIsNotAnError() = runBlocking {
+ fake(photonMs = 10, nominatimMs = 10, photonOk = false)
+ var last = emptyList<Place>()
+ assertTrue(Places.searchSubmitted("olympia", null, null, "test") { last = it })
+ assertEquals(2, last.size)
+ }
+
+ @Test
+ fun bothDownIsAnErrorTheCallerCanShow() = runBlocking {
+ fake(photonMs = 10, nominatimMs = 10, photonOk = false, nominatimOk = false)
+ var updates = 0
+ val failed = runCatching { Places.searchSubmitted("olympia", null, null, "test") { updates++ } }.exceptionOrNull()
+ assertTrue(failed is IllegalStateException)
+ assertEquals(0, updates)
+ }
+
+ @Test
+ fun aNewerSearchStopsTheOlderOnesRequests() = runBlocking {
+ val photonStopped = AtomicBoolean(false)
+ val nominatimStopped = AtomicBoolean(false)
+ Places.fetcher = { url, _, _ ->
+ val flag = if (url.startsWith(Places.NOMINATIM_URL)) nominatimStopped else photonStopped
+ try { delay(10_000); "[]" } catch (e: CancellationException) { flag.set(true); throw e }
+ }
+ val job = launch { Places.searchSubmitted("x", null, null, "test") { } }
+ delay(100)
+ job.cancel(); job.join()
+ assertTrue(photonStopped.get()); assertTrue(nominatimStopped.get())
+ assertFalse(job.isActive)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/PlacesAndFormatTest.kt b/app/src/test/java/com/rfsentinel/app/nav/PlacesAndFormatTest.kt
new file mode 100644
index 0000000..5d0a20f
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/PlacesAndFormatTest.kt
@@ -0,0 +1,102 @@
+package com.rfsentinel.app.nav
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Place search replies (real ones, trimmed), distance / time wording and the arrow chosen for a turn. */
+class PlacesAndFormatTest {
+
+ @Test
+ fun searchResultsBecomePlaces() {
+ val found = Places.parse(javaClass.getResource("/photon_search.json")!!.readText())
+ assertEquals(2, found.size)
+ assertEquals("Olympiapark", found[0].name)
+ assertEquals("Park \u00b7 Munich, Bavaria", found[0].address)
+ assertEquals(48.1687, found[0].lat, 0.001) // Photon gives lon, lat: not mixed up
+ assertEquals(11.5503, found[0].lon, 0.001)
+ }
+
+ @Test
+ fun aDroppedPinIsNamedByWhatIsThere() {
+ val p = Places.parse(javaClass.getResource("/photon_reverse.json")!!.readText()).single()
+ assertEquals("Marienplatz", p.name)
+ assertTrue(p.address, p.address.contains("Munich"))
+ }
+
+ @Test
+ fun aHouseWithoutANameIsCalledByItsAddress() {
+ val json = """{"features":[{"geometry":{"coordinates":[11.5,48.1]},"properties":{"housenumber":"12","street":"Example Street","city":"Exampletown","state":"Region"}},
+ {"geometry":{"coordinates":[11.6,48.2]},"properties":{}},
+ {"properties":{"name":"No position"}}]}"""
+ val found = Places.parse(json)
+ assertEquals("only the one that can be told apart and placed", 1, found.size)
+ assertEquals("12 Example Street", found[0].name)
+ assertEquals("Exampletown, Region", found[0].address)
+ }
+
+ @Test
+ fun noFeaturesIsNoPlaces() {
+ assertTrue(Places.parse("""{"features":[]}""").isEmpty())
+ assertTrue(Places.parse("""{}""").isEmpty())
+ }
+
+ @Test
+ fun distancesAreRoundedTheWayADriverReadsThem() {
+ assertEquals("40 m", NavFormat.distance(38.0, false))
+ assertEquals("300 m", NavFormat.distance(310.0, false))
+ assertEquals("950 m", NavFormat.distance(951.0, false))
+ assertEquals("1.2 km", NavFormat.distance(1240.0, false))
+ assertEquals("12 km", NavFormat.distance(12_345.0, false))
+ assertEquals("100 ft", NavFormat.distance(30.0, true))
+ assertEquals("0.6 mi", NavFormat.distance(1000.0, true))
+ assertEquals("8.0 mi", NavFormat.distance(12_875.0, true))
+ assertEquals("20 mi", NavFormat.distance(32_187.0, true))
+ assertEquals("0 m", NavFormat.distance(-5.0, false))
+ }
+
+ @Test
+ fun timesAreShortAndNeverZero() {
+ assertEquals("1 min", NavFormat.duration(10.0))
+ assertEquals("18 min", NavFormat.duration(1090.0))
+ assertEquals("a half minute rounds up", "19 min", NavFormat.duration(1110.0))
+ assertEquals("1 h 05 min", NavFormat.duration(3900.0))
+ assertEquals("2 h 00 min", NavFormat.duration(7200.0))
+ }
+
+ @Test
+ fun speed() {
+ assertEquals("90 km/h", NavFormat.speed(25.0, false))
+ assertEquals("56 mph", NavFormat.speed(25.0, true))
+ }
+
+ @Test
+ fun manoeuvresGetTheRightArrow() {
+ assertEquals(NavFormat.Icon.LEFT, NavFormat.iconFor("turn", "left"))
+ assertEquals(NavFormat.Icon.SLIGHT_RIGHT, NavFormat.iconFor("turn", "slight right"))
+ assertEquals(NavFormat.Icon.SHARP_LEFT, NavFormat.iconFor("end of road", "sharp left"))
+ assertEquals(NavFormat.Icon.STRAIGHT, NavFormat.iconFor("continue", "straight"))
+ assertEquals(NavFormat.Icon.STRAIGHT, NavFormat.iconFor("depart", null))
+ assertEquals(NavFormat.Icon.FORK_RIGHT, NavFormat.iconFor("fork", "slight right"))
+ assertEquals(NavFormat.Icon.RAMP_LEFT, NavFormat.iconFor("off ramp", "slight left"))
+ assertEquals(NavFormat.Icon.ROUNDABOUT, NavFormat.iconFor("roundabout", "right"))
+ assertEquals(NavFormat.Icon.ARRIVE, NavFormat.iconFor("arrive", null))
+ assertEquals(NavFormat.Icon.U_TURN_LEFT, NavFormat.iconFor("turn", "uturn"))
+ assertEquals(NavFormat.Icon.MERGE, NavFormat.iconFor("merge", "left"))
+ }
+
+ @Test
+ fun anActiveLaneShowsTheDirectionToTake() {
+ val two = Step.Lane(listOf("straight", "right"), active = true, activeDirection = "right")
+ assertEquals("right", NavFormat.laneDirection(two))
+ assertEquals("straight", NavFormat.laneDirection(Step.Lane(listOf("straight", "right"), active = false)))
+ assertEquals(NavFormat.Icon.SLIGHT_LEFT, NavFormat.laneIcon("slight left"))
+ }
+
+ @Test
+ fun handOffLinks() {
+ assertEquals("google.navigation:q=48.137400,11.575500&mode=d", HandOff.googleMapsUri(48.1374, 11.5755))
+ assertEquals("waze://?ll=48.137400,11.575500&navigate=yes", HandOff.wazeUri(48.1374, 11.5755))
+ assertEquals("geo:48.137400,11.575500?q=48.137400,11.575500(Mari%20Platz)", HandOff.geoUri(48.1374, 11.5755, "Mari Platz"))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/RouteProgressAndPromptsTest.kt b/app/src/test/java/com/rfsentinel/app/nav/RouteProgressAndPromptsTest.kt
new file mode 100644
index 0000000..bf64993
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/RouteProgressAndPromptsTest.kt
@@ -0,0 +1,206 @@
+package com.rfsentinel.app.nav
+
+import com.rfsentinel.app.service.DeviceRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Where you are on a route, and which spoken prompt is due - on made-up roads in metres around (10, 20). */
+class RouteProgressAndPromptsTest {
+
+ private val lat0 = 10.0; private val lon0 = 20.0
+ // Metres as the great-circle formula counts them (what a route's own distances use).
+ private val mPerDeg = 111_194.9
+ private fun lat(y: Double) = lat0 + y / mPerDeg
+ private fun lon(x: Double) = lon0 + x / (mPerDeg * Math.cos(Math.toRadians(lat0)))
+
+ private fun step(type: String, mod: String?, startM: Double, endM: Double, leg: Int = 0,
+ voice: List<Step.Voice> = emptyList(), banners: List<Step.Banner> = emptyList()) =
+ Step(type, mod, "", null, "", 0.0, 0.0, endM - startM, (endM - startM) / 15.0, startM, endM, leg, voice, banners)
+
+ /** A route through [pts] (x east, y north, metres) with [steps]. */
+ private fun route(pts: List<Pair<Double, Double>>, steps: List<Step>): Route {
+ val lats = pts.map { lat(it.second) }.toDoubleArray(); val lons = pts.map { lon(it.first) }.toDoubleArray()
+ val along = DoubleArray(pts.size)
+ for (i in 1 until pts.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ return Route(lats, lons, along, along.last(), along.last() / 15.0, steps, "", lats.last() to lons.last())
+ }
+
+ /** North for 2 km: depart 0-500, then a long stretch 500-1500, then 1500-2000, then arrive. */
+ private val straight by lazy {
+ route((0..20).map { 0.0 to it * 100.0 }, listOf(
+ step("depart", null, 0.0, 500.0),
+ step("turn", "right", 500.0, 1500.0),
+ step("turn", "left", 1500.0, 2000.0),
+ step("arrive", null, 2000.0, 2000.0)))
+ }
+
+ private fun locate(r: Route, x: Double, y: Double, bearing: Double? = null, last: RouteProgress.State? = null) =
+ RouteProgress.locate(r, lat(y), lon(x), bearing, last)
+
+ @Test
+ fun knowsTheStepAndWhatIsLeft() {
+ val s = locate(straight, 3.0, 700.0, 0.0)
+ assertEquals(700.0, s.alongM, 3.0)
+ assertEquals(1, s.stepIndex)
+ assertEquals("to the turn at the end of the step", 800.0, s.toManeuverM, 3.0)
+ assertEquals(1300.0, s.remainingM, 3.0)
+ assertEquals(3.0, s.offM, 1.0)
+ assertTrue("time left is about what's left at the route's speed", Math.abs(s.remainingS - 1300.0 / 15.0) < 8.0)
+ }
+
+ @Test
+ fun stepsChangeWhenYouPassTheirStart() {
+ assertEquals(0, locate(straight, 0.0, 400.0, 0.0).stepIndex)
+ assertEquals(1, locate(straight, 0.0, 600.0, 0.0).stepIndex)
+ assertEquals(2, locate(straight, 0.0, 1600.0, 0.0).stepIndex)
+ }
+
+ @Test
+ fun howFarOffTheLineYouAre() {
+ assertEquals(45.0, locate(straight, 45.0, 900.0, 0.0).offM, 2.0)
+ assertTrue(locate(straight, 400.0, 900.0).offM > 300)
+ }
+
+ @Test
+ fun headingAgainstTheLineIsMeasured() {
+ assertEquals(0.0, locate(straight, 0.0, 900.0, 0.0).headingOffDeg!!, 1.0)
+ assertEquals(180.0, locate(straight, 0.0, 900.0, 180.0).headingOffDeg!!, 1.0)
+ assertNull("not moving: no heading to compare", locate(straight, 0.0, 900.0, null).headingOffDeg)
+ }
+
+ @Test
+ fun aRoadThatDoublesBackDoesNotMakeYouJump() {
+ // North for 1 km, across 20 m, and back south beside itself: both stretches are 20 m apart.
+ val out = (0..10).map { 0.0 to it * 100.0 }
+ val back = (0..10).map { 20.0 to 1000.0 - it * 100.0 }
+ val u = route(out + back, listOf(step("depart", null, 0.0, 1020.0), step("turn", "right", 1020.0, 2020.0), step("arrive", null, 2020.0, 2020.0)))
+ // On the way out at 500 m, then a moment later still on the way out.
+ val first = locate(u, 0.0, 500.0, 0.0)
+ assertEquals(500.0, first.alongM, 5.0)
+ val next = locate(u, 0.0, 520.0, 0.0, first)
+ assertEquals(520.0, next.alongM, 5.0)
+ // On the way back at the same spot (heading south): the later half, not the first.
+ val coming = locate(u, 20.0, 500.0, 180.0, locate(u, 20.0, 700.0, 180.0, locate(u, 20.0, 900.0, 180.0, null)))
+ assertEquals(1020.0 + 500.0, coming.alongM, 10.0)
+ }
+
+ @Test
+ fun withoutAPreviousMatchTheWholeRouteIsSearched() {
+ val s = locate(straight, 0.0, 1800.0, 0.0, null)
+ assertEquals(1800.0, s.alongM, 3.0)
+ }
+
+ @Test
+ fun pointsAlongTheRoute() {
+ val p = RouteProgress.pointAt(straight, 750.0)
+ assertEquals(lat(750.0), p.first, 0.0001)
+ assertEquals(straight.end, RouteProgress.pointAt(straight, 99_999.0))
+ val ahead = straight.pointsFrom(1_950.0)
+ assertEquals("from where you are to the end", 2, ahead.size)
+ }
+
+ @Test
+ fun aPlaceBesideTheRouteIsProjectedOnto() {
+ val (along, off) = RouteProgress.project(straight, lat(1200.0), lon(25.0))
+ assertEquals(1200.0, along, 3.0)
+ assertEquals(25.0, off, 2.0)
+ }
+
+ // ---- spoken prompts ----
+
+ private fun voices() = listOf(Step.Voice(1000.0, "Continue for 1 kilometer."), Step.Voice(500.0, "In 500 meters, turn right."), Step.Voice(80.0, "Turn right."))
+
+ private val promptRoute by lazy {
+ route((0..20).map { 0.0 to it * 100.0 }, listOf(
+ step("depart", null, 0.0, 500.0),
+ step("turn", "right", 500.0, 1500.0, voice = voices()),
+ step("arrive", null, 1500.0, 2000.0)))
+ }
+
+ @Test
+ fun eachPromptIsSpokenOnceAsTheTurnComesNearer() {
+ val p = Prompts()
+ assertEquals("Continue for 1 kilometer.", p.next(promptRoute, 1, 1000.0, 15.0)?.text)
+ assertNull(p.next(promptRoute, 1, 900.0, 15.0))
+ val mid = p.next(promptRoute, 1, 520.0, 15.0)!!
+ assertEquals("In 500 meters, turn right.", mid.text)
+ assertFalse("not the last one before the turn", mid.urgent)
+ assertNull(p.next(promptRoute, 1, 400.0, 15.0))
+ val last = p.next(promptRoute, 1, 100.0, 15.0)!! // a little early: speech takes a moment to start
+ assertEquals("Turn right.", last.text)
+ assertTrue("the last prompt before a turn may cut into other speech", last.urgent)
+ assertNull("never twice", p.next(promptRoute, 1, 90.0, 15.0))
+ }
+
+ @Test
+ fun joiningAStepLateSkipsWhatIsNoLongerTrue() {
+ // 250 m from the turn: "In 500 meters" would be wrong, and so would "Continue for 1 kilometer".
+ val p = Prompts()
+ assertNull(p.next(promptRoute, 1, 250.0, 15.0))
+ assertEquals("Turn right.", p.next(promptRoute, 1, 100.0, 15.0)?.text)
+ // Straight into the last 100 m: only the last prompt.
+ assertEquals("Turn right.", Prompts().next(promptRoute, 1, 60.0, 15.0)?.text)
+ }
+
+ @Test
+ fun aFasterCarIsToldEarlier() {
+ val slow = Prompts().next(promptRoute, 1, 110.0, 5.0)
+ val fast = Prompts().next(promptRoute, 1, 110.0, 30.0)
+ assertNull("5 m/s: the prompt is due at 87 m", slow)
+ assertEquals("Turn right.", fast?.text) // 30 m/s: due at 80 + 45
+ }
+
+ @Test
+ fun promptsForAnotherStepAreIndependent() {
+ val p = Prompts()
+ assertNotNull(p.next(promptRoute, 1, 1000.0, 15.0))
+ assertNull("the arrival step has no prompts of its own", p.next(promptRoute, 2, 400.0, 15.0))
+ p.reset()
+ assertNotNull("a new route starts afresh", p.next(promptRoute, 1, 1000.0, 15.0))
+ }
+
+ private val longStretch by lazy {
+ route((0..40).map { 0.0 to it * 100.0 }, listOf(
+ step("depart", null, 0.0, 100.0),
+ step("turn", "right", 100.0, 4100.0, voice = listOf(
+ Step.Voice(3990.0, "Continue for 4 kilometers."), Step.Voice(500.0, "In 500 meters, keep right."), Step.Voice(150.0, "Keep right."))),
+ step("arrive", null, 4100.0, 4100.0)))
+ }
+
+ @Test
+ fun aLongStretchGetsAHeadsUpTwoKilometersOut() {
+ val withUp = Prompts().withHeadsUp(longStretch.steps[1])
+ assertEquals(4, withUp.size)
+ assertEquals("In 2 kilometers, keep right.", withUp.first { it.beforeM == 2000.0 }.text)
+ assertEquals("In 1 mile, keep right.", Prompts(miles = true).withHeadsUp(longStretch.steps[1]).first { it.beforeM == 1609.0 }.text)
+ val p = Prompts()
+ p.next(longStretch, 1, 3990.0, 15.0)
+ assertEquals("In 2 kilometers, keep right.", p.next(longStretch, 1, 2_010.0, 15.0)?.text)
+ assertEquals("In 500 meters, keep right.", p.next(longStretch, 1, 520.0, 15.0)?.text)
+ }
+
+ @Test
+ fun noHeadsUpOnAShortStretchOrWhenOneIsAlreadyThere() {
+ assertEquals(3, Prompts().withHeadsUp(promptRoute.steps[1]).size)
+ val near = longStretch.steps[1].copy(voice = longStretch.steps[1].voice + Step.Voice(1800.0, "In 2 kilometers, keep right."))
+ assertEquals(4, Prompts().withHeadsUp(near).size)
+ }
+
+ @Test
+ fun theComingTurnAndTheOneAfterIt() {
+ val banners = listOf(Step.Banner(400.0, "Main Street", "turn", "right", emptyList()))
+ val r = route((0..20).map { 0.0 to it * 100.0 }, listOf(
+ step("depart", null, 0.0, 500.0),
+ step("turn", "right", 500.0, 800.0, banners = listOf(Step.Banner(300.0, "Oak Road", "turn", "left", emptyList()))),
+ step("turn", "left", 800.0, 1200.0),
+ step("arrive", null, 1200.0, 1200.0)))
+ assertEquals("Oak Road", Prompts.banner(r, 1, 250.0)?.text)
+ assertEquals("a short step after the coming turn is worth a 'then'", null, Prompts.thenBanner(r, 0)?.takeIf { it.text != "Oak Road" })
+ assertNull("room before the next turn: no 'then'", Prompts.thenBanner(r, 2))
+ assertNull(Prompts.thenBanner(r, 3))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/nav/ValhallaTest.kt b/app/src/test/java/com/rfsentinel/app/nav/ValhallaTest.kt
new file mode 100644
index 0000000..9a5af02
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/ValhallaTest.kt
@@ -0,0 +1,155 @@
+package com.rfsentinel.app.nav
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/** The route service's reply (a real one, trimmed: public map data) and the request we send. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = android.app.Application::class)
+class ValhallaTest {
+
+ private val json = javaClass.getResource("/valhalla_route.json")!!.readText()
+ private val routes = Valhalla.parse(json)
+ private val route = routes[0]
+
+ @Test
+ fun readsEveryRouteOffered() {
+ assertEquals(2, routes.size)
+ assertEquals(8124.0, route.distanceM, 1.0)
+ assertEquals(1110.0, route.durationS, 1.0)
+ assertTrue(route.summary, route.summary.contains("Bayerstra"))
+ assertEquals(12, route.steps.size)
+ }
+
+ @Test
+ fun theLineIsContinuousAndMeasuredAlongItself() {
+ assertTrue(route.size > 30)
+ assertEquals(0.0, route.along[0], 0.0)
+ for (i in 1 until route.size) assertTrue("along rises at $i", route.along[i] > route.along[i - 1])
+ // The measured length matches the service's own figure (it rounds, and the line is an approximation).
+ assertEquals(route.distanceM, route.lengthM, route.distanceM * 0.02)
+ // Starts in the city centre it was asked for.
+ assertEquals(48.1374, route.lats[0], 0.001)
+ assertEquals(11.5755, route.lons[0], 0.001)
+ }
+
+ @Test
+ fun stepsFollowOnFromEachOther() {
+ for (i in 1 until route.steps.size) {
+ assertEquals("step $i starts where step ${i - 1} ended", route.steps[i - 1].endM, route.steps[i].startM, 0.5)
+ }
+ assertEquals("depart", route.steps.first().type)
+ assertTrue(route.steps.last().isArrival)
+ assertEquals(route.lengthM, route.steps.last().endM, 1.0)
+ // A step's own length is about what its line measures.
+ for (s in route.steps) assertEquals(s.lengthM, s.endM - s.startM, maxOf(8.0, s.lengthM * 0.05))
+ }
+
+ @Test
+ fun voicePromptsComeFarthestFirstWithTheirWords() {
+ val step = route.steps[6] // the long stretch with the ramp to take at its end
+ assertTrue(step.voice.size >= 3)
+ assertEquals(step.voice.sortedByDescending { it.beforeM }, step.voice)
+ assertTrue(step.voice.first().text, step.voice.first().text.startsWith("Continue for"))
+ assertTrue(step.voice.any { it.text.startsWith("In 300 meters") })
+ assertTrue(step.voice.last().text, step.voice.last().text.contains("ramp"))
+ }
+
+ @Test
+ fun lanesAreReadFromTheBannerAndShowWhichToBeIn() {
+ val step = route.steps[6]
+ val withLanes = step.banners.first { it.lanes.isNotEmpty() }
+ assertEquals(3, withLanes.lanes.size)
+ assertEquals(listOf("left"), withLanes.lanes[0].directions)
+ assertFalse(withLanes.lanes[0].active)
+ assertEquals(listOf("straight", "right"), withLanes.lanes[2].directions)
+ assertTrue(withLanes.lanes[2].active)
+ assertEquals("right", withLanes.lanes[2].activeDirection)
+ // The farther banner (no lanes yet) comes first; the lanes appear closer to the turn.
+ assertTrue(step.banners.first().beforeM > withLanes.beforeM)
+ // A lane that serves two directions names the one to take.
+ val two = route.steps.flatMap { it.banners }.flatMap { it.lanes }.first { it.directions.size == 2 && it.active }
+ assertNotNull(two.activeDirection)
+ }
+
+ @Test
+ fun bannerChoiceFollowsTheDistanceToTheTurn() {
+ val far = Prompts.banner(route, 6, 2_000.0)!!
+ val near = Prompts.banner(route, 6, 300.0)!!
+ assertTrue("far: no lanes yet", far.lanes.isEmpty())
+ assertTrue("near: lanes shown", near.lanes.isNotEmpty())
+ }
+
+ @Test
+ fun polylineSixDecodes() {
+ // The first step's own line.
+ val pts = Valhalla.decodePolyline6("qt_yzAsmmaU|CoAfB}@pFsB^OzAk@")
+ assertEquals(6, pts.size)
+ assertEquals(48.1365, pts[0].first, 0.001)
+ assertEquals(11.5745, pts[0].second, 0.001)
+ // Each point is a little way from the last (a short city street).
+ for (i in 1 until pts.size) assertTrue(Math.abs(pts[i].first - pts[i - 1].first) < 0.002)
+ }
+
+ @Test
+ fun anErrorReplyBecomesAReadableMessage() {
+ val e = runCatching { Valhalla.parse("""{"code":"NoRoute","message":"No path could be found for input"}""") }.exceptionOrNull()
+ assertTrue(e is Valhalla.NoRouteException)
+ assertEquals("No route found between these places", e!!.message)
+ assertEquals("Too far for the route server (it plans up to a few hundred km)",
+ Valhalla.errorOf("""{"code":"Other","message":"Path distance exceeds the max distance limit"}"""))
+ assertNull(Valhalla.errorOf("not json"))
+ }
+
+ // ---- the request ----
+
+ private val opts = Valhalla.Options()
+
+ @Test
+ fun theRequestAsksForEverythingNavigationNeeds() {
+ val r = Valhalla.request(48.0, 11.0, 90.0, emptyList(), 48.1 to 11.1, opts)
+ assertEquals("auto", r.getString("costing"))
+ assertEquals("osrm", r.getString("format"))
+ assertEquals("polyline6", r.getString("shape_format"))
+ assertTrue(r.getBoolean("banner_instructions"))
+ assertTrue(r.getBoolean("voice_instructions"))
+ assertTrue(r.getBoolean("turn_lanes"))
+ assertEquals(2, r.getInt("alternates"))
+ val from = r.getJSONArray("locations").getJSONObject(0)
+ assertEquals(90, from.getInt("heading")) // not to start with a U-turn
+ assertEquals(2, r.getJSONArray("locations").length())
+ assertEquals("kilometers", r.getJSONObject("directions_options").getString("units"))
+ }
+
+ @Test
+ fun noHeadingWhenNotMovingAndNoAlternativesWithStops() {
+ val r = Valhalla.request(48.0, 11.0, null, listOf(48.05 to 11.05), 48.1 to 11.1, opts, miles = true)
+ assertFalse(r.getJSONArray("locations").getJSONObject(0).has("heading"))
+ assertFalse("alternatives aren't offered on a route with a stop", r.has("alternates"))
+ val locs = r.getJSONArray("locations")
+ assertEquals(3, locs.length())
+ assertEquals("break", locs.getJSONObject(1).getString("type"))
+ assertEquals("miles", r.getJSONObject("directions_options").getString("units"))
+ }
+
+ @Test
+ fun avoidingTollsHighwaysAndFerries() {
+ val r = Valhalla.request(48.0, 11.0, null, emptyList(), 48.1 to 11.1,
+ Valhalla.Options(avoidTolls = true, avoidHighways = true, avoidFerries = true, alternatives = 0))
+ val auto = r.getJSONObject("costing_options").getJSONObject("auto")
+ assertEquals(0.0, auto.getDouble("use_tolls"), 0.0)
+ assertEquals(0.0, auto.getDouble("use_highways"), 0.0)
+ assertEquals(0.0, auto.getDouble("use_ferry"), 0.0)
+ assertFalse(r.has("alternates"))
+ val plain = Valhalla.request(48.0, 11.0, null, emptyList(), 48.1 to 11.1, opts).getJSONObject("costing_options").getJSONObject("auto")
+ assertEquals(1.0, plain.getDouble("use_highways"), 0.0)
+ assertEquals(0.5, plain.getDouble("use_tolls"), 0.0)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/online/RouteAheadTest.kt b/app/src/test/java/com/rfsentinel/app/online/RouteAheadTest.kt
new file mode 100644
index 0000000..8fa4215
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/online/RouteAheadTest.kt
@@ -0,0 +1,85 @@
+package com.rfsentinel.app.online
+
+import com.rfsentinel.app.nav.Route
+import com.rfsentinel.app.nav.Step
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.online.RoadMatch.Verdict
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** While guided, a report counts when it is on the stretch of the route still ahead of you. */
+class RouteAheadTest {
+ private val lat0 = 10.0; private val lon0 = 20.0
+ private val mPerDegLat = 110_540.0
+ private fun lat(north: Double) = lat0 + north / mPerDegLat
+ private fun lon(east: Double) = lon0 + east / (111_320.0 * Math.cos(Math.toRadians(lat0)))
+
+ /** A route through the given (north, east) points in metres, with its distances along. */
+ private fun route(vararg pts: Pair<Double, Double>): Route {
+ val lats = DoubleArray(pts.size) { lat(pts[it].first) }; val lons = DoubleArray(pts.size) { lon(pts[it].second) }
+ val along = DoubleArray(pts.size)
+ for (i in 1 until pts.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])
+ val step = Step("depart", null, "", null, "", 0.0, 0.0, along.last(), 60.0, 0.0, along.last(), 0, emptyList(), emptyList())
+ return Route(lats, lons, along, along.last(), 120.0, listOf(step), "", lats.last() to lons.last())
+ }
+
+ private fun straightNorth(km: Int) = route(*(0..km * 10).map { it * 100.0 to 0.0 }.toTypedArray())
+
+ private fun v(r: Route, alongM: Double, north: Double, east: Double, reach: Double = 3_000.0) =
+ RouteAhead.verdict(r, alongM, lat(north), lon(east), reach)
+
+ @Test
+ fun aReportOnTheRouteAheadIsOnYourWay() {
+ assertEquals(Verdict.ON_MY_ROAD, v(straightNorth(3), 0.0, 800.0, 6.0))
+ }
+
+ @Test
+ fun aReportOnAnotherStreetIsNot() {
+ // 800 m away as the crow flies, off to the north-west: nowhere near the route.
+ assertEquals(Verdict.OTHER_ROAD, v(straightNorth(3), 0.0, 300.0, -700.0))
+ // A parallel street 120 m beside the route.
+ assertEquals(Verdict.OTHER_ROAD, v(straightNorth(3), 0.0, 500.0, 120.0))
+ }
+
+ @Test
+ fun aReportYouHavePassedIsBehind() {
+ assertEquals(Verdict.BEHIND, v(straightNorth(3), 1_500.0, 1_100.0, 4.0))
+ // Just behind your position is still "here" (GPS error, the report's own rounding).
+ assertEquals(Verdict.ON_MY_ROAD, v(straightNorth(3), 1_500.0, 1_485.0, 4.0))
+ }
+
+ @Test
+ fun aReportFartherOnThanTheAlertReachesIsNotYet() {
+ assertEquals(Verdict.OTHER_ROAD, v(straightNorth(3), 0.0, 2_500.0, 3.0, reach = 1_500.0))
+ assertEquals(Verdict.ON_MY_ROAD, v(straightNorth(3), 1_200.0, 2_500.0, 3.0, reach = 1_500.0))
+ }
+
+ @Test
+ fun aReportRoundTheNextCornerIsOnYourWayThoughItIsToTheSide() {
+ // North 500 m, then west for a kilometre. A report on the west leg, 300 m past the corner: straight-line it
+ // is 580 m away to the north-north-west - sideways to a car heading north - but it is on the route.
+ val l = route(0.0 to 0.0, 500.0 to 0.0, 500.0 to -1_000.0)
+ assertEquals(Verdict.ON_MY_ROAD, v(l, 0.0, 500.0, -300.0, reach = 1_500.0))
+ // The same place for a route that turns the other way is another street.
+ val r = route(0.0 to 0.0, 500.0 to 0.0, 500.0 to 1_000.0)
+ assertEquals(Verdict.OTHER_ROAD, v(r, 0.0, 500.0, -300.0, reach = 1_500.0))
+ }
+
+ @Test
+ fun aRouteThatPassesTheReportTwiceCountsThePassStillAhead() {
+ // Out along one street and back along another 30 m away.
+ val r = route(0.0 to 0.0, 1_000.0 to 0.0, 1_000.0 to 30.0, 0.0 to 30.0)
+ // At the start the first pass (30 m from it, going out) is the one still in front of you.
+ assertEquals(Verdict.ON_MY_ROAD, v(r, 0.0, 400.0, 30.0, reach = 3_000.0))
+ // Coming back, 70 m short of it: ahead.
+ assertEquals(Verdict.ON_MY_ROAD, v(r, 1_560.0, 400.0, 30.0, reach = 3_000.0))
+ // Past it on the way back: both passes are behind you.
+ assertEquals(Verdict.BEHIND, v(r, 1_750.0, 400.0, 30.0, reach = 3_000.0))
+ }
+
+ @Test
+ fun aRouteWithoutLengthSaysNothing() {
+ val r = route(0.0 to 0.0)
+ assertEquals(Verdict.UNKNOWN, v(r, 0.0, 10.0, 0.0))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt
index 672e71b..d68e67d 100644
--- a/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt
@@ -2,6 +2,11 @@ package com.rfsentinel.app.online
import android.app.Application
import android.location.Location
+import com.rfsentinel.app.nav.Navigator
+import com.rfsentinel.app.nav.Place
+import com.rfsentinel.app.nav.Route
+import com.rfsentinel.app.nav.Step
+import com.rfsentinel.app.nav.Valhalla
import com.rfsentinel.app.online.WazePolice.Level
import com.rfsentinel.app.online.WazePolice.Type
import com.rfsentinel.app.util.Prefs
@@ -12,6 +17,7 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
+import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -51,6 +57,13 @@ class WazeWatchTest {
watch = WazeWatch(ctx, CoroutineScope(Job()), { here }, { alerts += it }, { calls += it })
}
+ @After
+ fun tearDown() {
+ Navigator.stop()
+ Navigator.speaker = null
+ Navigator.planner = null
+ }
+
@Test
fun aReportInRangeAlertsOnceAndIsShown() {
watch.ingest(listOf(report("a", 800.0)), WazePolice.VIA_DIRECT, 1_000L)
@@ -245,4 +258,88 @@ class WazeWatchTest {
assertTrue("$first -> $second", first - second in 290.0..310.0)
assertEquals(WazePolice.Side.AHEAD, WazePolice.latest.single().where.side)
}
+
+ // ---- while guided, "ahead" is the route ----
+
+ /** Guidance along a road running 3 km due north from the origin, starting from [from]. */
+ private fun guidedNorth(from: Location) {
+ val ys = (0..30).map { it * 100.0 }
+ val lats = DoubleArray(ys.size) { 10.0 + ys[it] / 110_540.0 }
+ val lons = DoubleArray(ys.size) { 10.0 }
+ val along = DoubleArray(ys.size) { ys[it] }
+ val step = Step("depart", null, "", null, "", 0.0, 0.0, 3_000.0, 180.0, 0.0, 3_000.0, 0, emptyList(), emptyList())
+ val route = Route(lats, lons, along, 3_000.0, 180.0, listOf(step), "", lats.last() to 10.0)
+ Navigator.speaker = { _, _ -> }
+ Prefs.setNavStartScan(ctx, false)
+ Navigator.begin(ctx, Place("Destination", "", lats.last(), 10.0), route, Valhalla.Options(), emptyList(), from)
+ }
+
+ @Test
+ fun whileGuidedAReportOffTheRouteIsQuietEvenWhenTheGpsHasNoHeading() {
+ Prefs.setWazeAheadOnly(ctx, true)
+ here = fix(10.0, 10.0) // at a light, or crawling: no bearing and no speed
+ guidedNorth(here)
+ watch.ingest(listOf(report("onroute", 800.0), reportAt("beside", 300.0, -700.0)), WazePolice.VIA_DIRECT, 1_000L)
+ // The route needs no map data, so the one on it alerts at once; the one 700 m off to the side never does.
+ assertEquals(listOf("waze:onroute"), alerts.map { it.key })
+ assertEquals("both stay on the map", 2, WazePolice.latest.size)
+ assertEquals("the list keeps only what is on your way", listOf("onroute"),
+ WazePolice.latest.filter { it.onMyWay }.map { it.report.id })
+ }
+
+ @Test
+ fun whileGuidedAReportYouHavePassedIsQuiet() {
+ Prefs.setWazeAheadOnly(ctx, true)
+ here = fix(10.0 + 1_500.0 / 110_540.0, 10.0) // 1.5 km along the route
+ guidedNorth(here)
+ watch.ingest(listOf(report("passed", 1_100.0), report("coming", 2_000.0)), WazePolice.VIA_DIRECT, 1_000L)
+ assertEquals(listOf("waze:coming"), alerts.map { it.key })
+ assertEquals(listOf("coming"), WazePolice.latest.filter { it.onMyWay }.map { it.report.id })
+ }
+
+ @Test
+ fun withOnlyAheadOffGuidanceChangesNothing() {
+ Prefs.setWazeAheadOnly(ctx, false)
+ here = fix(10.0, 10.0)
+ guidedNorth(here)
+ watch.ingest(listOf(report("onroute", 800.0), reportAt("beside", 300.0, -700.0)), WazePolice.VIA_DIRECT, 1_000L)
+ assertEquals("everything in range, as chosen", 2, alerts.size)
+ assertTrue(WazePolice.latest.all { it.onMyWay })
+ }
+
+ @Test
+ fun leavingTheRouteHandsOverToTheRoadsAndTheHeadingAgain() {
+ Prefs.setWazeAheadOnly(ctx, true)
+ here = fix(10.0, 10.0)
+ guidedNorth(here)
+ // 400 m east of the route (off it, being re-planned): the route no longer decides.
+ Navigator.planner = { _, _, _, _, _ -> throw java.io.IOException("offline") }
+ here = fix(10.0, 10.0 + 400.0 / (111_320.0 * Math.cos(Math.toRadians(10.0))), bearing = 0f, speed = 12f)
+ val onLocation = Navigator::class.java.getDeclaredMethod("onLocation", Location::class.java)
+ onLocation.isAccessible = true
+ onLocation.invoke(Navigator, here)
+ assertTrue("the guidance knows it is off the route", Navigator.state!!.offM > Navigator.OFF_ROUTE_M)
+ // A report 700 m ahead on that road, beside where you now are.
+ watch.ingest(listOf(reportAt("beside", 300.0, 410.0)), WazePolice.VIA_DIRECT, 1_000L)
+ // No verdict from the route; the (empty here) map decides after its wait, as before guidance existed.
+ assertTrue(alerts.isEmpty())
+ watch.evaluate(1_000L + WazeWatch.ROAD_HOLD_MS, publish = false)
+ assertEquals(1, alerts.size)
+ }
+
+ @Test
+ fun theListLeavesOutWhatIsNotOnYourWayByDefaultAndTheSettingBringsItBack() {
+ assertTrue("hidden by default", Prefs.wazeHideOffWay(ctx))
+ Prefs.setWazeAheadOnly(ctx, true)
+ here = fix(10.0, 10.0)
+ guidedNorth(here)
+ watch.ingest(listOf(report("onroute", 800.0), reportAt("beside", 300.0, -700.0)), WazePolice.VIA_DIRECT, 1_000L)
+ val all = WazePolice.latest
+ assertEquals(listOf("onroute"), WazePolice.forList(all, 2_000.0, aheadOnly = true, hideOffWay = true).map { it.report.id })
+ assertEquals("the setting off: listed again (quiet, marked)", setOf("onroute", "beside"),
+ WazePolice.forList(all, 2_000.0, aheadOnly = true, hideOffWay = false).map { it.report.id }.toSet())
+ assertEquals("with only-ahead off nothing is hidden", 2,
+ WazePolice.forList(all, 2_000.0, aheadOnly = false, hideOffWay = true).size)
+ assertEquals("the alert range still applies", 0, WazePolice.forList(all, 100.0, aheadOnly = false, hideOffWay = true).size)
+ }
}
diff --git a/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.kt b/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.kt
new file mode 100644
index 0000000..cb43f97
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.kt
@@ -0,0 +1,148 @@
+package com.rfsentinel.app.ui
+
+import android.app.Application
+import android.location.Location
+import android.os.Looper
+import android.view.LayoutInflater
+import android.view.View
+import androidx.appcompat.app.AppCompatActivity
+import com.rfsentinel.app.R
+import com.rfsentinel.app.databinding.ActivityMapBinding
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.util.Prefs
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+
+/** Alerts as a card over the full screen map: what it shows, when it goes, and when it stays quiet. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class AlertCardTest {
+ private lateinit var activity: AppCompatActivity
+ private lateinit var b: ActivityMapBinding
+ private lateinit var card: AlertCardController
+ private var looked: Pair<Double, Double>? = null
+
+ private fun alert(
+ label: String = "Axon body camera", category: Category = Category.BODY_CAM, confidence: Int = 90, following: Boolean = false,
+ lat: Double? = null, lon: Double? = null, evidence: String = "BWCDEVICE tag in advert payload"
+ ) = AlertCards.Card("k1", null, label, evidence, category, confidence, following, -58, lat, lon, System.currentTimeMillis())
+
+ @Before
+ fun setUp() {
+ activity = Robolectric.buildActivity(AppCompatActivity::class.java).create().get()
+ activity.setTheme(R.style.Theme_RFSentinel)
+ b = ActivityMapBinding.inflate(LayoutInflater.from(activity))
+ looked = null
+ Prefs.setDiscreetMode(activity, false)
+ Prefs.setAlertsSnoozedUntil(activity, 0L)
+ card = AlertCardController(activity, b, { Location("t").apply { latitude = 10.0; longitude = 20.0 } }) { la, lo -> looked = la to lo }
+ }
+
+ @After
+ fun tearDown() {
+ card.hide()
+ Prefs.setDiscreetMode(activity, false)
+ Prefs.setAlertsSnoozedUntil(activity, 0L)
+ }
+
+ @Test
+ fun theCardShowsWhatWasDetectedAndHowSure() {
+ assertEquals("hidden until an alert comes", View.GONE, b.alertCard.visibility)
+ card.show(alert())
+ assertEquals(View.VISIBLE, b.alertCard.visibility)
+ assertEquals("NEARBY", b.alertContext.text.toString())
+ assertEquals("Axon body camera", b.alertTitle.text.toString())
+ assertEquals(Category.BODY_CAM.shortTag, b.alertTag.text.toString())
+ assertTrue(b.alertDetail.text.toString(), b.alertDetail.text.toString().contains("BWCDEVICE"))
+ assertTrue(b.alertFooter.text.toString(), b.alertFooter.text.toString().startsWith("Strong match"))
+ }
+
+ @Test
+ fun somethingFollowingYouSaysSo() {
+ card.show(alert(label = "Item tracker", category = Category.TRACKER, following = true))
+ assertEquals("FOLLOWING YOU", b.alertContext.text.toString())
+ assertEquals("Following you: Item tracker", b.alertTitle.text.toString())
+ }
+
+ @Test
+ fun aPlaceOnTheMapShowsHowFarItIs() {
+ // About 1.1 km north of the fix the card is given.
+ card.show(alert(label = "Speed camera ahead", category = Category.ALPR, lat = 10.01, lon = 20.0, evidence = "Mapped · OSM · limit 50 km/h"))
+ val detail = b.alertDetail.text.toString()
+ assertTrue(detail, Regex("""\d+(\.\d+)? (km|mi|m|ft)""").containsMatchIn(detail) && detail.contains("limit 50"))
+ }
+
+ @Test
+ fun aNewerAlertReplacesTheCardAndTheCloseButtonDismissesIt() {
+ card.show(alert(label = "First"))
+ card.show(alert(label = "Second"))
+ assertEquals("Second", b.alertTitle.text.toString())
+ b.alertClose.performClick()
+ assertEquals(View.GONE, b.alertCard.visibility)
+ }
+
+ @Test
+ fun itGoesByItselfAfterAFewSecondsAndLongerWhenStrong() {
+ card.show(alert(confidence = 60))
+ shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofSeconds(9))
+ assertEquals("a probable match goes after about 8 s", View.GONE, b.alertCard.visibility)
+ card.show(alert(confidence = 95))
+ shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofSeconds(9))
+ assertEquals("a strong one stays longer", View.VISIBLE, b.alertCard.visibility)
+ shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofSeconds(5))
+ assertEquals(View.GONE, b.alertCard.visibility)
+ }
+
+ @Test
+ fun tappingTheCardLooksAtThePlaceWhenThereIsOne() {
+ card.show(alert(lat = 10.5, lon = 20.5))
+ b.alertCard.performClick()
+ assertEquals(10.5 to 20.5, looked)
+ looked = null
+ card.show(alert(lat = null, lon = null))
+ b.alertCard.performClick()
+ assertNull("nothing to look at for a device with no position", looked)
+ }
+
+ @Test
+ fun discreetModeShowsOnlyThatSomethingHappened() {
+ Prefs.setDiscreetMode(activity, true)
+ card.show(alert())
+ assertEquals("New alert", b.alertTitle.text.toString())
+ assertEquals("", b.alertTag.text.toString())
+ assertEquals(View.GONE, b.alertDetail.visibility)
+ assertEquals(View.GONE, b.alertFooter.visibility)
+ }
+
+ @Test
+ fun aSnoozedAlertStaysOffTheMap() {
+ Prefs.setAlertsSnoozedUntil(activity, System.currentTimeMillis() + 60_000L)
+ card.show(alert())
+ assertFalse(b.alertCard.visibility == View.VISIBLE)
+ }
+
+ @Test
+ fun theFeedHandsEachAlertToWhoeverListensAndRemembersTheNewest() {
+ val seen = ArrayList<String>()
+ val stop = AlertCards.addListener { seen += it.label }
+ AlertCards.publish(alert(label = "One"))
+ AlertCards.publish(alert(label = "Two"))
+ shadowOf(Looper.getMainLooper()).idle()
+ assertEquals(listOf("One", "Two"), seen)
+ assertEquals("Two", AlertCards.latest?.label)
+ stop()
+ AlertCards.publish(alert(label = "Three"))
+ shadowOf(Looper.getMainLooper()).idle()
+ assertEquals("a stopped listener hears nothing more", listOf("One", "Two"), seen)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/ui/MapSafetyScreenTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MapSafetyScreenTest.kt
new file mode 100644
index 0000000..c45d81a
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/MapSafetyScreenTest.kt
@@ -0,0 +1,82 @@
+package com.rfsentinel.app.ui
+
+import android.app.Application
+import android.content.Context
+import android.content.DialogInterface
+import androidx.appcompat.app.AlertDialog
+import androidx.test.core.app.ApplicationProvider
+import com.rfsentinel.app.util.Prefs
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowDialog
+
+/** What the full screen map and the main screen say when the map closed the app while starting. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class MapSafetyScreenTest {
+ private lateinit var ctx: Context
+
+ @Before
+ fun setUp() {
+ ctx = ApplicationProvider.getApplicationContext()
+ ctx.getSharedPreferences("map_safety", Context.MODE_PRIVATE).edit().clear().commit()
+ MapSafety.live = false
+ Prefs.setViewPanes(ctx, setOf("map", "list"))
+ }
+
+ private fun titleOf(d: AlertDialog) = d.findViewById<android.widget.TextView>(androidx.appcompat.R.id.alertTitle)!!.text.toString()
+
+ /** A second start-up crash in a row (OpenGL already tried). */
+ private fun secondCrash() {
+ ctx.getSharedPreferences("map_safety", Context.MODE_PRIVATE).edit()
+ .putBoolean("opengl", true).putLong("armed_at", 1L).putString("armed_provider", "OPENFREEMAP").commit()
+ }
+
+ @Test
+ fun theFullScreenMapAsksBeforeTryingAgainAndLeavesWhenNotNow() {
+ secondCrash()
+ val controller = Robolectric.buildActivity(MapActivity::class.java).create()
+ val activity = controller.get()
+ val dialog = ShadowDialog.getLatestDialog() as AlertDialog
+ assertTrue(dialog.isShowing)
+ assertEquals(MapSafetyUi.OFF_TITLE, titleOf(dialog))
+ assertEquals("Try the map again", dialog.getButton(DialogInterface.BUTTON_POSITIVE).text.toString())
+ assertNotNull(dialog.getButton(DialogInterface.BUTTON_NEGATIVE))
+ assertTrue("the map is not started behind the question",
+ activity.supportFragmentManager.findFragmentById(com.rfsentinel.app.R.id.mapHost) == null)
+ assertEquals("the saved main screen view lost the map", setOf("list"), Prefs.viewPanes(ctx))
+
+ dialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick()
+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()
+ assertTrue("Not now closes the screen", activity.isFinishing)
+ }
+
+ @Test
+ fun theMainScreenJustSaysSo() {
+ val activity = Robolectric.buildActivity(androidx.appcompat.app.AppCompatActivity::class.java).create().get()
+ activity.setTheme(com.rfsentinel.app.R.style.Theme_RFSentinel)
+ MapSafetyUi.tell(activity, MapSafety.Recovery.MAP_OFF)
+ val dialog = ShadowDialog.getLatestDialog() as AlertDialog
+ assertEquals(MapSafetyUi.OFF_TITLE, titleOf(dialog))
+ assertEquals("OK", dialog.getButton(DialogInterface.BUTTON_POSITIVE).text.toString())
+ assertFalse("nothing to try again from here", dialog.getButton(DialogInterface.BUTTON_NEGATIVE).visibility == android.view.View.VISIBLE)
+ }
+
+ @Test
+ fun theOpenGlRetryIsATextNoteNotADialog() {
+ val activity = Robolectric.buildActivity(androidx.appcompat.app.AppCompatActivity::class.java).create().get()
+ activity.setTheme(com.rfsentinel.app.R.style.Theme_RFSentinel)
+ var started = 0
+ MapSafetyUi.tell(activity, MapSafety.Recovery.OPENGL, onTryAgain = { started++ })
+ assertEquals("the map starts right away", 1, started)
+ assertEquals(MapSafetyUi.OPENGL_NOTE, org.robolectric.shadows.ShadowToast.getTextOfLatestToast())
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/ui/MapSafetyTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MapSafetyTest.kt
new file mode 100644
index 0000000..672af25
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/MapSafetyTest.kt
@@ -0,0 +1,125 @@
+package com.rfsentinel.app.ui
+
+import android.app.Application
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.rfsentinel.app.util.Prefs
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.maplibre.android.RenderingEngine
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/**
+ * A map that took the app down while it started (BV9100, Android 9: MapLibre's Vulkan renderer threw "No Vulkan compatible
+ * GPU found" on its render thread, and the saved view asked for the map again at every launch).
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class MapSafetyTest {
+ private lateinit var ctx: Context
+
+ @Before
+ fun setUp() {
+ ctx = ApplicationProvider.getApplicationContext()
+ ctx.getSharedPreferences("map_safety", Context.MODE_PRIVATE).edit().clear().commit()
+ MapSafety.live = false
+ Prefs.setViewPanes(ctx, setOf("map", "list"))
+ }
+
+ /** The app starts again after dying: nothing is live in the new process. */
+ private fun newProcess() { MapSafety.live = false }
+
+ @Test
+ fun aCleanStartChangesNothing() {
+ assertEquals(MapSafety.Recovery.NONE, MapSafety.recover(ctx))
+ assertNull("MapLibre chooses (Vulkan where it exists)", MapSafety.renderer(ctx))
+ assertEquals(setOf("map", "list"), Prefs.viewPanes(ctx))
+ }
+
+ @Test
+ fun aMapThatSettledOrWasLeftIsNotACrash() {
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP)
+ MapSafety.worked(ctx)
+ newProcess()
+ assertEquals(MapSafety.Recovery.NONE, MapSafety.recover(ctx))
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP)
+ MapSafety.disarm(ctx) // the screen paused normally
+ newProcess()
+ assertEquals(MapSafety.Recovery.NONE, MapSafety.recover(ctx))
+ assertEquals(setOf("map", "list"), Prefs.viewPanes(ctx))
+ }
+
+ @Test
+ fun theFirstCrashTriesOpenGlAndKeepsTheMap() {
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP)
+ newProcess()
+ assertTrue(MapSafety.crashedLastTime(ctx))
+ assertEquals(MapSafety.Recovery.OPENGL, MapSafety.recover(ctx))
+ assertEquals(RenderingEngine.Type.OPENGL, MapSafety.renderer(ctx))
+ assertEquals("the map stays on the main screen for the retry", setOf("map", "list"), Prefs.viewPanes(ctx))
+ assertFalse("the mark is used up", MapSafety.crashedLastTime(ctx))
+ assertEquals(1, MapSafety.crashes(ctx))
+ }
+
+ @Test
+ fun aSecondCrashTakesTheMapOffTheMainScreen() {
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP); newProcess()
+ assertEquals(MapSafety.Recovery.OPENGL, MapSafety.recover(ctx))
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP); newProcess()
+ assertEquals(MapSafety.Recovery.MAP_OFF, MapSafety.recover(ctx))
+ assertEquals(setOf("list"), Prefs.viewPanes(ctx))
+ assertEquals(2, MapSafety.crashes(ctx))
+ assertEquals("and the next launch is quiet", MapSafety.Recovery.NONE, MapSafety.recover(ctx))
+ }
+
+ @Test
+ fun theMapOnlyViewFallsBackToTheList() {
+ Prefs.setViewPanes(ctx, setOf("map"))
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP); newProcess(); MapSafety.recover(ctx)
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP); newProcess(); MapSafety.recover(ctx)
+ assertEquals(setOf("list"), Prefs.viewPanes(ctx))
+ }
+
+ @Test
+ fun aMapboxCrashCannotBeHelpedByOpenGl() {
+ MapSafety.arm(ctx, MapEngine.Provider.MAPBOX); newProcess()
+ assertEquals(MapSafety.Recovery.MAP_OFF, MapSafety.recover(ctx))
+ assertNull("MapLibre's renderer was not to blame", MapSafety.renderer(ctx))
+ assertEquals(setOf("list"), Prefs.viewPanes(ctx))
+ }
+
+ @Test
+ fun aMapStillStartingInThisProcessIsNotACrash() {
+ // The main screen opening (a notification tap) while the full screen map is still drawing its first frame.
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP)
+ assertFalse(MapSafety.crashedLastTime(ctx))
+ assertEquals(MapSafety.Recovery.NONE, MapSafety.recover(ctx))
+ assertEquals(setOf("map", "list"), Prefs.viewPanes(ctx))
+ assertNull(MapSafety.renderer(ctx))
+ }
+
+ @Test
+ fun aMapThatWorksAfterTheRetryResetsTheCountAndStaysOnOpenGl() {
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP); newProcess(); MapSafety.recover(ctx)
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP)
+ MapSafety.worked(ctx)
+ assertEquals(0, MapSafety.crashes(ctx))
+ assertEquals("OpenGL worked, so it stays", RenderingEngine.Type.OPENGL, MapSafety.renderer(ctx))
+ newProcess()
+ assertEquals(MapSafety.Recovery.NONE, MapSafety.recover(ctx))
+ }
+
+ @Test
+ fun theMarkIsOnDiskBeforeTheMapStarts() {
+ MapSafety.arm(ctx, MapEngine.Provider.OPENFREEMAP, now = 1234L)
+ val sp = ctx.getSharedPreferences("map_safety", Context.MODE_PRIVATE)
+ assertEquals(1234L, sp.getLong("armed_at", 0L))
+ assertEquals("OPENFREEMAP", sp.getString("armed_provider", null))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/util/NavVoiceQueueTest.kt b/app/src/test/java/com/rfsentinel/app/util/NavVoiceQueueTest.kt
new file mode 100644
index 0000000..ee2c986
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/util/NavVoiceQueueTest.kt
@@ -0,0 +1,73 @@
+package com.rfsentinel.app.util
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Driving directions share the voice with alerts but are not alerts: never merged, never "a repeat", gone once stale. */
+class NavVoiceQueueTest {
+
+ @Test
+ fun theSameDirectionTwiceIsTwoTurns() {
+ val q = VoiceQueue()
+ assertTrue(q.addNav("Turn left.", 0))
+ assertEquals("Turn left.", q.next(1_000)?.text)
+ // An alert's repeat gap would drop this; a second left turn a few seconds later is real.
+ assertTrue(q.addNav("Turn left.", 5_000))
+ assertEquals("Turn left.", q.next(5_100)?.text)
+ }
+
+ @Test
+ fun theSameWordsAlreadyWaitingAreNotQueuedTwice() {
+ val q = VoiceQueue()
+ assertTrue(q.addNav("Turn left.", 0))
+ assertFalse(q.addNav("turn left.", 100))
+ assertEquals(1, q.size)
+ }
+
+ @Test
+ fun directionsAreNeverMergedIntoAlerts() {
+ val q = VoiceQueue()
+ q.add("Axon body camera nearby", VoiceQueue.WEAK, 0)
+ q.add("Flock camera nearby", VoiceQueue.WEAK, 0)
+ q.add("Drone overhead", VoiceQueue.WEAK, 0)
+ q.addNav("In 500 meters, keep right.", 0)
+ // The direction first (it ties with a strong alert and is older than nothing), the alerts merged after it.
+ val first = q.next(100)!!
+ assertTrue(first.text, first.nav && first.text.startsWith("In 500 meters"))
+ val second = q.next(200)!!
+ assertTrue(second.text, second.text.startsWith("3 alerts:"))
+ assertFalse(second.nav)
+ assertNull(q.next(300))
+ }
+
+ @Test
+ fun aDirectionGoesStaleSoonerThanAnAlert() {
+ val q = VoiceQueue()
+ q.addNav("Turn right.", 0)
+ q.add("Axon body camera nearby", VoiceQueue.WEAK, 0)
+ // 8 s later: the turn is behind you; the alert is still worth saying.
+ val next = q.next(8_000)!!
+ assertEquals("Axon body camera nearby", next.text)
+ assertNull(q.next(8_100))
+ }
+
+ @Test
+ fun aFollowingAlertStillGoesFirst() {
+ val q = VoiceQueue()
+ q.addNav("Turn right.", 0)
+ q.add("Something is following you", VoiceQueue.FOLLOWING, 10)
+ assertEquals("Something is following you", q.next(100)?.text)
+ assertEquals("Turn right.", q.next(200)?.text)
+ }
+
+ @Test
+ fun aDirectionIsNotRememberedAsSaidSoAnAlertOfTheSameWordsStillSpeaks() {
+ val q = VoiceQueue()
+ q.addNav("Drone overhead", 0)
+ q.next(100)
+ assertTrue(q.add("Drone overhead", VoiceQueue.WEAK, 1_000))
+ }
+}
diff --git a/app/src/test/resources/photon_reverse.json b/app/src/test/resources/photon_reverse.json
new file mode 100644
index 0000000..ee91d3c
--- /dev/null
+++ b/app/src/test/resources/photon_reverse.json
@@ -0,0 +1 @@
+{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"osm_type":"W","osm_id":1102285748,"osm_key":"highway","osm_value":"pedestrian","type":"street","name":"Marienplatz","locality":"Kreuzviertel","district":"Old Town","city":"Munich","state":"Bavaria","country":"Germany","postcode":"80331","countrycode":"DE","extent":[11.575473,48.1374492,11.5754791,48.1374355]},"geometry":{"type":"Point","coordinates":[11.5754761,48.1374424]}}]}
\ No newline at end of file
diff --git a/app/src/test/resources/photon_search.json b/app/src/test/resources/photon_search.json
new file mode 100644
index 0000000..626d540
--- /dev/null
+++ b/app/src/test/resources/photon_search.json
@@ -0,0 +1 @@
+{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"osm_type":"W","osm_id":10053878,"osm_key":"leisure","osm_value":"park","type":"other","name":"Olympiapark","city":"Munich","state":"Bavaria","country":"Germany","countrycode":"DE","extent":[11.5383427,48.1760673,11.5609628,48.1614965]},"geometry":{"type":"Point","coordinates":[11.5503638,48.1687059]}},{"type":"Feature","properties":{"osm_type":"R","osm_id":12914182,"osm_key":"leisure","osm_value":"park","type":"other","name":"Olympiapark Nord","district":"Milbertshofen","city":"Munich","state":"Bavaria","country":"Germany","countrycode":"DE","extent":[11.540046,48.1861835,11.5559887,48.1763027]},"geometry":{"type":"Point","coordinates":[11.547403,48.1811905]}}]}
\ No newline at end of file
diff --git a/app/src/test/resources/valhalla_route.json b/app/src/test/resources/valhalla_route.json
new file mode 100644
index 0000000..0f9ee86
--- /dev/null
+++ b/app/src/test/resources/valhalla_route.json
@@ -0,0 +1 @@
+{"routes":[{"voiceLocale":"en-US","weight_name":"auto","weight":2188.04,"duration":1110.053,"distance":8124.077,"legs":[{"weight":2188.04,"duration":1110.053,"steps":[{"bannerInstructions":[{"primary":{"type":"turn","modifier":"left","text":"Turn left.","components":[{"text":"Turn left.","type":"text"}]},"distanceAlongGeometry":37.076}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Drive southwest. Then Turn left.</speak>","announcement":"Drive southwest. Then Turn left.","distanceAlongGeometry":37.1},{"ssmlAnnouncement":"<speak>Turn left.</speak>","announcement":"Turn left.","distanceAlongGeometry":9.3}],"maneuver":{"instruction":"Drive southwest.","type":"depart","bearing_after":238,"bearing_before":0,"location":[11.574857,48.13675]},"name":"","duration":16.684,"distance":37.076,"geometry":"{a`yzAqcnaUNpBpHxOfBp@"},{"bannerInstructions":[{"primary":{"type":"end of road","modifier":"right","text":"Rindermarkt","components":[{"text":"Rindermarkt","type":"text"}]},"distanceAlongGeometry":36.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Turn right onto Rindermarkt.</speak>","announcement":"Turn right onto Rindermarkt.","distanceAlongGeometry":22.0}],"maneuver":{"modifier":"left","instruction":"Turn left.","type":"turn","bearing_after":160,"bearing_before":217,"location":[11.574506,48.136537]},"name":"","duration":17.445,"distance":36.0,"geometry":"qt_yzAsmmaU|CoAfB}@pFsB^OzAk@"},{"bannerInstructions":[{"primary":{"type":"turn","modifier":"right","text":"Hermann-Sack-Stra\u00dfe","components":[{"text":"Hermann-Sack-Stra\u00dfe","type":"text"}]},"distanceAlongGeometry":257.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>In 200 meters, Turn right onto Hermann-Sack-Stra\u00dfe.</speak>","announcement":"In 200 meters, Turn right onto Hermann-Sack-Stra\u00dfe.","distanceAlongGeometry":155.1},{"ssmlAnnouncement":"<speak>Turn right onto Hermann-Sack-Stra\u00dfe.</speak>","announcement":"Turn right onto Hermann-Sack-Stra\u00dfe.","distanceAlongGeometry":44.3}],"maneuver":{"modifier":"right","instruction":"Turn right onto Rindermarkt.","type":"end of road","bearing_after":237,"bearing_before":162,"location":[11.574665,48.136223]},"name":"Rindermarkt","duration":58.884,"distance":257.0,"geometry":"}`_yzAqwmaU|BbHdBvFz@lDrFxWlCvKjDnJdAzC|CfItDnJpE|LxA~DxApDv@jCxAxEl@xDl@nGHfADX`@xFb@|EL`Af@lDx@pDdBdG"},{"bannerInstructions":[{"primary":{"type":"turn","modifier":"slight right","text":"Brunnstra\u00dfe","components":[{"text":"Brunnstra\u00dfe","type":"text"}]},"distanceAlongGeometry":235.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>In 200 meters, Bear right onto Brunnstra\u00dfe.</speak>","announcement":"In 200 meters, Bear right onto Brunnstra\u00dfe.","distanceAlongGeometry":155.3},{"ssmlAnnouncement":"<speak>Bear right onto Brunnstra\u00dfe.</speak>","announcement":"Bear right onto Brunnstra\u00dfe.","distanceAlongGeometry":44.4}],"maneuver":{"modifier":"right","instruction":"Turn right onto Hermann-Sack-Stra\u00dfe.","type":"turn","bearing_after":324,"bearing_before":241,"location":[11.571656,48.135131]},"name":"Hermann-Sack-Stra\u00dfe","duration":54.405,"distance":235.0,"geometry":"u||xzAo{gaU_BfBgYf[wFvF}DtHsF|PsJx_@kGtYMlBJvA~A`GzBrJ"},{"bannerInstructions":[{"sub":{"text":"","components":[{"active":false,"text":"","directions":["straight"],"type":"lane"},{"active_direction":"right","active":true,"text":"","directions":["straight","right"],"type":"lane"},{"active_direction":"right","active":false,"text":"","directions":["right"],"type":"lane"}]},"primary":{"type":"turn","modifier":"right","text":"Sonnenstra\u00dfe","components":[{"text":"Sonnenstra\u00dfe","type":"text"}]},"distanceAlongGeometry":301.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Continue for 300 meters.</speak>","announcement":"Continue for 300 meters.","distanceAlongGeometry":291.0},{"ssmlAnnouncement":"<speak>In 200 meters, Turn right onto Sonnenstra\u00dfe.</speak>","announcement":"In 200 meters, Turn right onto Sonnenstra\u00dfe.","distanceAlongGeometry":154.9},{"ssmlAnnouncement":"<speak>Turn right onto Sonnenstra\u00dfe.</speak>","announcement":"Turn right onto Sonnenstra\u00dfe.","distanceAlongGeometry":44.0}],"maneuver":{"modifier":"slight right","instruction":"Bear right onto Brunnstra\u00dfe.","type":"turn","bearing_after":274,"bearing_before":243,"location":[11.56922,48.136151]},"name":"Brunnstra\u00dfe","duration":67.939,"distance":301.0,"geometry":"m|~xzAgccaUPdB?vAOhBsFdc@m@zDwOx}AFdEFbEW`PInE}@rUWnAq@pCgAn\\MtD"},{"bannerInstructions":[{"sub":{"text":"","components":[{"active_direction":"left","active":true,"text":"","directions":["left"],"type":"lane"},{"active":false,"text":"","directions":["straight"],"type":"lane"},{"active":false,"text":"","directions":["straight"],"type":"lane"},{"active":false,"text":"","directions":["straight"],"type":"lane"}]},"primary":{"type":"turn","modifier":"slight left","text":"Bayerstra\u00dfe","components":[{"text":"Bayerstra\u00dfe","type":"text"}]},"distanceAlongGeometry":267.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>In 200 meters, Bear left onto Bayerstra\u00dfe.</speak>","announcement":"In 200 meters, Bear left onto Bayerstra\u00dfe.","distanceAlongGeometry":247.0},{"ssmlAnnouncement":"<speak>Bear left onto Bayerstra\u00dfe.</speak>","announcement":"Bear left onto Bayerstra\u00dfe.","distanceAlongGeometry":77.7}],"maneuver":{"modifier":"right","instruction":"Turn right onto Sonnenstra\u00dfe.","type":"turn","bearing_after":6,"bearing_before":277,"location":[11.56527,48.136683]},"name":"Sonnenstra\u00dfe","duration":42.2,"distance":267.0,"geometry":"u}_yzAkl{`UpBxFkBM{Ec@y^aD}B[_LoAkPaA_CW{j@sGiIcAoGe@"},{"bannerInstructions":[{"primary":{"type":"turn","modifier":"right","text":"A 9: N\u00fcrnberg, Flughafen M\u00fcnchen","components":[{"text":"A 9: N\u00fcrnberg, Flughafen M\u00fcnchen","type":"text"},{"text":"/","type":"delimiter"},{"text":"B 2R","type":"text"}]},"distanceAlongGeometry":2329.0},{"distanceAlongGeometry":400.0,"primary":{"type":"turn","modifier":"right","text":"A 9: N\u00fcrnberg, Flughafen M\u00fcnchen","components":[{"text":"A 9: N\u00fcrnberg, Flughafen M\u00fcnchen","type":"text"},{"text":"/","type":"delimiter"},{"text":"B 2R","type":"text"}]},"sub":{"text":"","components":[{"active":false,"text":"","directions":["left"],"type":"lane"},{"active":false,"text":"","directions":["straight"],"type":"lane"},{"active_direction":"right","active":true,"text":"","directions":["straight","right"],"type":"lane"}]}}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Continue for 2.5 kilometers.</speak>","announcement":"Continue for 2.5 kilometers.","distanceAlongGeometry":2319.0},{"ssmlAnnouncement":"<speak>In 300 meters, Turn right to take the A 9 ramp.</speak>","announcement":"In 300 meters, Turn right to take the A 9 ramp.","distanceAlongGeometry":271.8},{"ssmlAnnouncement":"<speak>Turn right to take the A 9 ramp toward N\u00fcrnberg, Flughafen M\u00fcnchen.</speak>","announcement":"Turn right to take the A 9 ramp toward N\u00fcrnberg, Flughafen M\u00fcnchen.","distanceAlongGeometry":77.6}],"maneuver":{"modifier":"slight left","instruction":"Bear left onto Bayerstra\u00dfe.","type":"turn","bearing_after":349,"bearing_before":5,"location":[11.565541,48.138915]},"name":"Bayerstra\u00dfe","duration":351.735,"distance":2329.0,"geometry":"eidyzAi}{`UiBNiANsAZyAd@yA|@mAdAUZW\\S^S`@S^Sb@Wx@Wx@[jAYlAg@hCUbCMhCIvQCvEIrPDlCJrCXjGBhC[jOq@ne@K~CKrCOzBo@pKKjCGlC@tADbALvBLdCHdCDpCDdQ?fEElDEjCg@xRGdDAh@IdDC~BCdDAr@?R?~@B|ABpALpCFn@JnAd@pEZjDJlBF~ABxBDzEBdEAzEFpERvRT|_@DvH?~AAtGCjCMjEGlBAzAFlDPvDb@tHb@tFb@dGZ|Fr@rSH|l@Dj\\DnGBvEFnGTrLfAdKTvBFvHj@nh@b@pb@\\|ZX~Wj@ni@d@|a@@lBHjHH`HB~BZjYDbEDzBPrOJvVAvCC~GEvHC~DGbOOjPM~HIpDYbG_Hb{@iDn`@UbCs@hGo@|Iq@fQa@~PQtM}@ha@iBhw@MpGgDpwAkAtf@MxDQ|EMlEa@~L[tJO|EUfHIhDQdH}@j_@iEbgBcBtq@EbBWnKElBAd@kBzu@aEtbB_Bx`@MfDw@lI"},{"voiceInstructions":[{"ssmlAnnouncement":"<speak>Continue for 4 kilometers.</speak>","announcement":"Continue for 4 kilometers.","distanceAlongGeometry":3630.0},{"ssmlAnnouncement":"<speak>In 500 meters, Keep right to stay on B 2R.</speak>","announcement":"In 500 meters, Keep right to stay on B 2R.","distanceAlongGeometry":506.2},{"ssmlAnnouncement":"<speak>Keep right to stay on B 2R toward Passau, N\u00fcrnberg.</speak>","announcement":"Keep right to stay on B 2R toward Passau, N\u00fcrnberg.","distanceAlongGeometry":177.8}],"bannerInstructions":[{"primary":{"type":"fork","modifier":"slight right","text":"Passau, N\u00fcrnberg","components":[{"text":"Passau, N\u00fcrnberg","type":"text"},{"text":"/","type":"delimiter"},{"text":"B 2R","type":"text"}]},"distanceAlongGeometry":3640.0},{"distanceAlongGeometry":400.0,"primary":{"type":"fork","modifier":"slight right","text":"Passau, N\u00fcrnberg","components":[{"text":"Passau, N\u00fcrnberg","type":"text"},{"text":"/","type":"delimiter"},{"text":"B 2R","type":"text"}]},"sub":{"text":"","components":[{"active":false,"text":"","directions":["straight"],"type":"lane"},{"active_direction":"slight right","active":true,"text":"","directions":["straight","slight right"],"type":"lane"},{"active_direction":"slight right","active":true,"text":"","directions":["slight right"],"type":"lane"}]}}],"destinations":"A 9: N\u00fcrnberg, Flughafen M\u00fcnchen","maneuver":{"modifier":"right","instruction":"Turn right to take the A 9 ramp toward N\u00fcrnberg/Flughafen M\u00fcnchen.","type":"turn","bearing_after":359,"bearing_before":284,"location":[11.534717,48.140116]},"name":"","duration":365.988,"distance":3640.0,"ref":"B 2R","geometry":"gtfyzAyv__UgC@eODcKBaQBkNXePZwJ@cKB{Qz@u`@aEk]iD}MEqE]yKaA_NkAqQ_BcQ{A_TwBoNgCsJkDyHaDwEeCmGeEkJwGiGmFgN_N}M_LmLuH}PkI}I}CmKgCkK{AsJu@qOu@cLq@ePDoUaAqbDcLijEiL{~CkHkCGySu@cPa@iWs@gWs@yf@aB_R_@iTq@y^gAwz@iCuc@eAoACw[u@qWo@icCkHqo@mBqp@yBopAaEaM_@_i@qCof@wEuSuA_x@oGuWoCc\\iFq\\oH{XqG"},{"voiceInstructions":[{"ssmlAnnouncement":"<speak>Continue for 700 meters.</speak>","announcement":"Continue for 700 meters.","distanceAlongGeometry":732.0},{"ssmlAnnouncement":"<speak>In 500 meters, Take the exit.</speak>","announcement":"In 500 meters, Take the exit.","distanceAlongGeometry":453.5},{"ssmlAnnouncement":"<speak>Take the exit.</speak>","announcement":"Take the exit.","distanceAlongGeometry":113.7}],"bannerInstructions":[{"primary":{"type":"off ramp","modifier":"slight right","text":"Sapporobogen","components":[{"text":"Sapporobogen","type":"text"}]},"distanceAlongGeometry":742.0}],"destinations":"Passau, N\u00fcrnberg","maneuver":{"modifier":"slight right","instruction":"Keep right to stay on B 2R toward Passau/N\u00fcrnberg.","type":"fork","bearing_after":20,"bearing_before":12,"location":[11.538978,48.17249]},"name":"","duration":51.238,"distance":742.0,"ref":"B 2R","geometry":"s{e{zAcah_UmXgMqQwImMsHeO{KmM}K{L_LaMkNqRcWc^qp@s]oq@sIqS{E{NqC{LuBsLsAmMe@uKi@}X}@}Sb@ieB"},{"bannerInstructions":[{"primary":{"type":"turn","modifier":"left","text":"Turn left.","components":[{"text":"Turn left.","type":"text"}]},"distanceAlongGeometry":155.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Turn left.</speak>","announcement":"Turn left.","distanceAlongGeometry":52.7}],"maneuver":{"modifier":"slight right","instruction":"Take the exit.","type":"off ramp","bearing_after":114,"bearing_before":91,"location":[11.54623,48.17617]},"name":"Sapporobogen","duration":29.403,"distance":155.0,"geometry":"sam{zAkfv_UlFgXnAgBbAaAxAm@hA_@rCArBb@rAbAhAdArAvBbAdDh@lDDbDMnD_@rCm@tCuC|G{DbL"},{"bannerInstructions":[{"primary":{"type":"arrive","text":"You have arrived at your destination.","components":[{"text":"You have arrived at your destination.","type":"text"}]},"distanceAlongGeometry":125.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>In 90 meters, You will arrive at your destination.</speak>","announcement":"In 90 meters, You will arrive at your destination.","distanceAlongGeometry":87.3},{"ssmlAnnouncement":"<speak>You have arrived at your destination.</speak>","announcement":"You have arrived at your destination.","distanceAlongGeometry":40.0}],"maneuver":{"modifier":"left","instruction":"Turn left.","type":"turn","bearing_after":216,"bearing_before":305,"location":[11.54577,48.175799]},"name":"","duration":54.132,"distance":125.0,"geometry":"mjl{zAsiu_UfF`JzD|ElLpE`Jn@hFqBpPoK"},{"voiceInstructions":[],"bannerInstructions":[],"maneuver":{"instruction":"You have arrived at your destination.","type":"arrive","bearing_after":0,"bearing_before":155,"location":[11.54561,48.174799]},"name":"","duration":0.0,"distance":0.0,"geometry":"}kj{zAs_u_U??"}],"distance":8124.077,"summary":"Bayerstra\u00dfe, B 2R"}],"geometry":"{a`yzAqcnaUNpBpHxOfBp@|CoAfB}@pFsB^OzAk@|BbHdBvFz@lDrFxWlCvKjDnJdAzC|CfItDnJpE|LxA~DxApDv@jCxAxEl@xDl@nGHfADX`@xFb@|EL`Af@lDx@pDdBdG_BfBgYf[wFvF}DtHsF|PsJx_@kGtYMlBJvA~A`GzBrJPdB?vAOhBsFdc@m@zDwOx}AFdEFbEW`PInE}@rUWnAq@pCgAn\\MtDpBxFkBM{Ec@y^aD}B[_LoAkPaA_CW{j@sGiIcAoGe@iBNiANsAZyAd@yA|@mAdAUZW\\S^S`@S^Sb@Wx@Wx@[jAYlAg@hCUbCMhCIvQCvEIrPDlCJrCXjGBhC[jOq@ne@K~CKrCOzBo@pKKjCGlC@tADbALvBLdCHdCDpCDdQ?fEElDEjCg@xRGdDAh@IdDC~BCdDAr@?R?~@B|ABpALpCFn@JnAd@pEZjDJlBF~ABxBDzEBdEAzEFpERvRT|_@DvH?~AAtGCjCMjEGlBAzAFlDPvDb@tHb@tFb@dGZ|Fr@rSH|l@Dj\\DnGBvEFnGTrLfAdKTvBFvHj@nh@b@pb@\\|ZX~Wj@ni@d@|a@@lBHjHH`HB~BZjYDbEDzBPrOJvVAvCC~GEvHC~DGbOOjPM~HIpDYbG_Hb{@iDn`@UbCs@hGo@|Iq@fQa@~PQtM}@ha@iBhw@MpGgDpwAkAtf@MxDQ|EMlEa@~L[tJO|EUfHIhDQdH}@j_@iEbgBcBtq@EbBWnKElBAd@kBzu@aEtbB_Bx`@MfDw@lIgC@eODcKBaQBkNXePZwJ@cKB{Qz@u`@aEk]iD}MEqE]yKaA_NkAqQ_BcQ{A_TwBoNgCsJkDyHaDwEeCmGeEkJwGiGmFgN_N}M_LmLuH}PkI}I}CmKgCkK{AsJu@qOu@cLq@ePDoUaAqbDcLijEiL{~CkHkCGySu@cPa@iWs@gWs@yf@aB_R_@iTq@y^gAwz@iCuc@eAoACw[u@qWo@icCkHqo@mBqp@yBopAaEaM_@_i@qCof@wEuSuA_x@oGuWoCc\\iFq\\oH{XqGmXgMqQwImMsHeO{KmM}K{L_LaMkNqRcWc^qp@s]oq@sIqS{E{NqC{LuBsLsAmMe@uKi@}X}@}Sb@ieBlFgXnAgBbAaAxAm@hA_@rCArBb@rAbAhAdArAvBbAdDh@lDDbDMnD_@rCm@tCuC|G{DbLfF`JzD|ElLpE`Jn@hFqBpPoK"},{"voiceLocale":"en-US","weight_name":"auto","weight":2375.714,"duration":1326.832,"distance":11102.076,"legs":[{"weight":2375.714,"duration":1326.832,"steps":[{"bannerInstructions":[{"primary":{"type":"turn","modifier":"left","text":"Turn left.","components":[{"text":"Turn left.","type":"text"}]},"distanceAlongGeometry":37.076}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Drive southwest. Then Turn left.</speak>","announcement":"Drive southwest. Then Turn left.","distanceAlongGeometry":37.1},{"ssmlAnnouncement":"<speak>Turn left.</speak>","announcement":"Turn left.","distanceAlongGeometry":9.3}],"maneuver":{"instruction":"Drive southwest.","type":"depart","bearing_after":238,"bearing_before":0,"location":[11.574857,48.13675]},"name":"","duration":16.684,"distance":37.076,"geometry":"{a`yzAqcnaUNpBpHxOfBp@"},{"bannerInstructions":[{"primary":{"type":"end of road","modifier":"right","text":"Rindermarkt","components":[{"text":"Rindermarkt","type":"text"}]},"distanceAlongGeometry":36.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Turn right onto Rindermarkt.</speak>","announcement":"Turn right onto Rindermarkt.","distanceAlongGeometry":22.0}],"maneuver":{"modifier":"left","instruction":"Turn left.","type":"turn","bearing_after":160,"bearing_before":217,"location":[11.574506,48.136537]},"name":"","duration":17.445,"distance":36.0,"geometry":"qt_yzAsmmaU|CoAfB}@pFsB^OzAk@"},{"bannerInstructions":[{"primary":{"type":"turn","modifier":"left","text":"Rosental","components":[{"text":"Rosental","type":"text"}]},"distanceAlongGeometry":104.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Turn left onto Rosental.</speak>","announcement":"Turn left onto Rosental.","distanceAlongGeometry":44.4}],"maneuver":{"modifier":"right","instruction":"Turn right onto Rindermarkt.","type":"end of road","bearing_after":237,"bearing_before":162,"location":[11.574665,48.136223]},"name":"Rindermarkt","duration":24.369,"distance":104.0,"geometry":"}`_yzAqwmaU|BbHdBvFz@lDrFxWlCvKjDnJdAzC"},{"bannerInstructions":[{"primary":{"type":"turn","modifier":"right","text":"Pr\u00e4lat-Zistl-Stra\u00dfe","components":[{"text":"Pr\u00e4lat-Zistl-Stra\u00dfe","type":"text"}]},"distanceAlongGeometry":131.0}],"voiceInstructions":[{"ssmlAnnouncement":"<speak>Turn right onto Pr\u00e4lat-Zistl-Stra\u00dfe.</speak>","announcement":"Turn right onto Pr\u00e4lat-Zistl-Stra\u00dfe.","distanceAlongGeometry":44.1}],"maneuver":{"modifier":"left","instruction":"Turn left onto Rosental.","type":"turn","bearing_after":140,"bearing_before":236,"location":[11.573445,48.135765]},"name":"Rosental","duration":35.743,"distance":131.0,"geometry":"id~xzAikkaUjBeCRY|AuBfCaEdCyErCmJ|AsFrA}K|@cNd@iQJuEFgB"}],"distance":11102.076,"summary":"Widenmayerstra\u00dfe, Isarring"}],"geometry":"{a`yzAqcnaUNpBpHxOfBp@|CoAfB}@pFsB^OzAk@|BbHdBvFz@lDrFxWlCvKjDnJdAzCjBeCRY|AuBfCaEdCyErCmJ|AsFrA}K|@cNd@iQJuEFgBlD`@nANzAZlA\\nDtAdE~BtEnD|LhOxGrLnAxBbPpYdChEhLtUrDhIdI_Ol@{@lDcFiDqGiAuBgKeR_LeTqIaOwD_HS[mFsJuOsY{@wB[cB@q@?c@J}Aj@_DfG_PrAuEbA_GJkB`@qGDsH@_BFwODy^A{BE{N]sNyAsa@uB{m@\\wLCyAGeFo@kGWaCOaMKa_@GsYMeFUcFm@kHw@{G{@gG{@uG{@wF_BiIaBmH_BmGeAcEsBeHoBeFuCcHaBkCoBkDqEsG_DeEoB{ByDkEwB_CiDcDiCcCgFeEoE_DeGqDgHiDiHoCsHeCcHsBcJaCyOiDeDq@}Dw@qGqAcAU_FeAmVkFuAYuGu@z@}GdGej@jN}oAlEs]XmBp@sEZqBF[x@{E`FqR`AoFn@cGViEB_BLwF@kC?}D?s@@y@BcBJeK@yDBUX_C`@yDx@iHbAqI`BaOMYiBaEeDuFeDwF{IsPe\\en@_CqEa[sl@aG_LmA_CeBaDqNoWeXqZyZaVmLyG_H}DuDwB{EgBo^aNee@qOiGyBoEoA{EcBce@}OwSmEaYaGkd@cHgsA{RwY}Dud@kG_IgAmq@oH{Fo@{AQsJgBeK_EuFgBwFkCiMiJojAicAgMqKwvAemAav@qo@i]eWs@i@ep@cf@iAy@cFuD}EqDaS}NiCmBm`Acq@ig@k_@{{AghAgGaDsQkJuGgCiCcAoMmCeKk@gKLgK~@qK`FmKxIgG~HsGnOoC`JgB~Ks@zNE~Id@rQSvKy@~HcCfI}C~EmLjJgCbFwClCkN|MgJ~JiHvJyHnKoInNmD|FsBxDaHrMo\\hr@u]tw@cL~VoKjTgHnN_LnO_KnJsOtLgIvEiMpFmIfC_MpBwZh@{[yE_r@qVqj@}[}sAcz@sTmNwNmJeDuB_h@{Z}CsB_Ao@mPwKePaJkP{JgDmAqC}AyHwE}KsGkEwBmJiDuDaA_Es@sCYkDMaEBcDTsD^cGxAuDtAsH~DsGbFuDzDwDpFcG`KuGjNgSng@uX`q@cF`MgVdm@yQzc@sQzc@}GpOeVln@aKpYyGbSqIzWeFhOoCtJiKj\\{GpSuEbJ{Pbi@wMzb@{If[uFdSaApD{FrTaAzIwFbUwBrJwGh^oEh_@qCh^oApWo@dTK`n@TrmAZdlA@jh@Bhv@Sxe@m@re@qAhg@{A`h@mKlqCaEf|@q@rZSlXC|[FjXHlV`@|Ux@bRpClc@tBjWbC~UxC~Rbc@|cCrc@~dC|J~k@`Knm@tA`NlAfPl@dTEnYeAnvAMtWr@dRe@v{@yA`uC]`~@kA|~DgAhUEtUaApkEsErT{CdHgWze@oAzEgA`CoAnFY~FVlGlAvGfBtEd[jp@`Vvd@`Zrn@jChGdAzEb@|DJlE_@jFeA~F_H`KeGpHfF`JzD|ElLpE`Jn@hFqBpPoK"}],"code":"Ok"}
\ No newline at end of file
diff --git a/docs/android-auto.html b/docs/android-auto.html
index 99c9275..ec35b41 100644
--- a/docs/android-auto.html
+++ b/docs/android-auto.html
@@ -69,7 +69,7 @@
<li><b>Cameras:</b> tap one to see it alone on the map, navigate to it, or tap its row to turn its alerts off or back on (faded on the maps).</li>
<li><b>More:</b> snooze alerts for 30 minutes, spoken alerts in the car, short spoken alerts, whether AirTags count as trackers, <b>cell towers</b> (fake-cell check status, serving cell and neighbours) and <b>hardware</b> status (phone radios and the scan watchdog, ESP32 / Marauder / Flipper on USB, OUI-SPY over Bluetooth, USB WiFi adapter).</li>
<li><b>Live map:</b> RF Sentinel's own OpenStreetMap map on the car screen with devices in list / radar colours, plate-reader, speed and red-light cameras, and your position. Drag, pinch or <b>+ / −</b>; <b>◎</b> follows the car again. Needs car API level 7; older Android Auto gets car-drawn maps with device and camera lists.</li>
-<li><b>Navigation:</b> <i>Navigate to...</i> searches with Nominatim (on submit only, no search-as-you-type), keeps recent destinations on the phone, routes with OSRM, draws the route with next turn, ETA and distance, speaks turns and re-routes.</li>
+<li><b>Navigation:</b> <i>Navigate to...</i> starts from Home, Work, starred and recent places kept on the phone or a search with Photon and Nominatim (on submit only), routes with Valhalla, draws the route with next turn, ETA and distance, speaks turns and re-routes. The same navigation is on the phone.</li>
<li><b>Alerts:</b> heads-up cards on the car screen with <b>Mute 30 min</b> and <b>Ignore</b> buttons, spoken through the car speakers as navigation guidance audio, briefly lowering music.</li>
<li><b>Phone screen off:</b> Android limits Bluetooth scanning then. The car warns you when a scan starts that way and shows "Bluetooth limited" on its home screen; WiFi, cell checks and known cameras keep working.</li>
</ul>
@@ -89,7 +89,7 @@
<p>Settings → <b>Start scanning automatically in the car</b>: scanning starts when the phone connects to your car's Bluetooth or to Android Auto, and stops when you leave if the car started it.</p>
<h2 id="privacy-nav">Navigation privacy</h2>
-<p>Nominatim and OSRM see the search, your position and destination, and your IP address, only when you search or start a route. They never see your scans.</p>
+<p>Photon, Nominatim and Valhalla see the search, your start and destination, and your IP address, only when you search or start a route. They never see your scans.</p>
<section class="community" aria-label="Community">
<a class="dc" href="https://discord.gg/NDTjn8HMGq" rel="noopener"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20.3 4.4A19.8 19.8 0 0 0 15.4 2.9l-.6 1.3a18.3 18.3 0 0 0-5.5 0L8.7 2.9a19.7 19.7 0 0 0-4.9 1.5C.5 9-.3 13.6.1 18.1a19.9 19.9 0 0 0 6 3l1.3-2a12.9 12.9 0 0 1-1.9-.9l.4-.3a14.2 14.2 0 0 0 12.1 0l.4.3c-.6.4-1.2.7-1.9.9l1.3 2a19.8 19.8 0 0 0 6-3c.5-5.2-.8-9.7-3.5-13.7zM8 15.3c-1.2 0-2.2-1.1-2.2-2.4S6.8 10.5 8 10.5s2.2 1.1 2.2 2.4-1 2.4-2.2 2.4zm8 0c-1.2 0-2.2-1.1-2.2-2.4s1-2.4 2.2-2.4 2.2 1.1 2.2 2.4-1 2.4-2.2 2.4z"/></svg><span><strong>Join the Discord</strong>Help, ideas, new signatures, field captures and ESP32 builds.</span></a>
<a class="gh" href="https://github.com/CIS-C0/RFSentinel" rel="noopener"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1 1.8 2.8 1.3 3.5 1 0-.8.4-1.3.7-1.6-2.7-.3-5.5-1.3-5.5-5.9 0-1.3.5-2.4 1.2-3.2 0-.3-.5-1.5.2-3.2 0 0 1-.3 3.3 1.2a11.5 11.5 0 0 1 6 0c2.3-1.5 3.3-1.2 3.3-1.2.6 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.6-2.8 5.6-5.5 5.9.5.4.9 1.1.9 2.2v3.3c0 .3.1.7.8.6A12 12 0 0 0 12 .3"/></svg><span><strong>CIS-C0/RFSentinel on GitHub</strong>Source code, releases, issues. A star helps others find it.</span></a>
diff --git a/docs/index.html b/docs/index.html
index 589bb91..935dac8 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -24,7 +24,7 @@
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin>
<link rel="stylesheet" href="assets/style.css">
-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.19.0", "dateModified": "2026-10-10", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>
+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.20.0", "dateModified": "2026-10-13", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
@@ -96,6 +96,7 @@
<div class="grid">
<div class="card"><h3>Live list, radar &amp; map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div>
<div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>
+ <div class="card"><h3>Navigation</h3><p>Turn-by-turn directions on the map: search a place (Home, Work, starred and recent places are kept on the phone; or long-press the map), pick one of up to three routes, avoid tolls, highways or ferries, and go. A banner shows the next turn, lane arrows and the turn after it; spoken directions play as navigation audio so your music dips under them; it re-routes by itself, takes stops, and finds petrol, charging or food along your route. Your arrival time follows how you really drive. Open the destination in Google Maps or Waze if you prefer. No live traffic. The map goes to its night look after sunset.</p></div>
<div class="card"><h3>Map &amp; traces</h3><p>A vector map (OpenFreeMap, OpenStreetMap data, or Mapbox if you prefer) with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view like a navigation app that zooms with your speed, with the default zoom and angle in Settings; a light map and a readable night map with shops, landmarks and one-way arrows. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>
<div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div>
<div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div>
@@ -155,7 +156,7 @@
<ul>
<li><b>Receive-only.</b> The app never transmits, jams, spoofs or connects to the devices it detects.</li>
<li><b>No accounts, no cloud, no analytics.</b> Detections live in a local database excluded from cloud backup.</li>
- <li><b>Network use:</b> the map (vector tiles from OpenFreeMap, OpenStreetMap data, or from Mapbox if you pick it in Settings with Mapbox's own usage statistics switched off), camera data (Overpass API, DeFlock CDN), the roads of your area while the Waze option to alert only for reports on your road is on, and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li>
+ <li><b>Network use:</b> the map (vector tiles from OpenFreeMap, OpenStreetMap data, or from Mapbox if you pick it in Settings with Mapbox's own usage statistics switched off), camera data (Overpass API, DeFlock CDN), the roads of your area while the Waze option to alert only for reports on your road is on, and, when you search for a destination or start a route, Photon and Nominatim (place search) and Valhalla (routes), only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li>
<li><b>Data leaves the phone only when you export or share it.</b></li>
</ul>
<section class="community" aria-label="Community">
diff --git a/docs/qa.html b/docs/qa.html
index 4d8890f..6d74e99 100644
--- a/docs/qa.html
+++ b/docs/qa.html
@@ -24,7 +24,7 @@
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin>
<link rel="stylesheet" href="assets/style.css">
-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not currently. The signed APK is published on GitHub Releases for every version. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any 64-bit ARM phone with Bluetooth LE (almost every phone since 2017; old 32-bit phones are not supported): Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute 30 min and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to silence alerts for 30 minutes. Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "Start scanning with the board on, then Settings → Pair OUI-SPY board and pick OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one)."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works experimentally on 2.4, 5 and 6 GHz, with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script>
+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not currently. The signed APK is published on GitHub Releases for every version. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any 64-bit ARM phone with Bluetooth LE (almost every phone since 2017; old 32-bit phones are not supported): Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "The map closes the app (or the app closes when I open the map). What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "This happened on some older phones (seen on Android 9) whose graphics chip has no Vulkan: earlier builds drew the map with Vulkan only, so opening the map closed the app, and it did it again at every launch until the app's data was cleared. Version 2.20 picks Vulkan only where the phone has it and OpenGL everywhere else. If the app closes while the map starts for any other reason, it now tries the map again with OpenGL at the next launch, and after a second failure it takes the map off the main screen and tells you, so the rest of the app opens (add it back with the Map view button). On an earlier build, clearing the app's data (Android Settings → Apps → RF Sentinel → Storage) opens the app again, but the map will close it again. If it still happens, Settings → Lists, tools & about → Export crash log and send it: it helps to know the phone model and Android version."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute 30 min and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to silence alerts for 30 minutes. Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "Start scanning with the board on, then Settings → Pair OUI-SPY board and pick OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one)."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works experimentally on 2.4, 5 and 6 GHz, with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, navigation (on the phone or in Android Auto), Photon and Nominatim for place search and Valhalla for routes. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
@@ -494,6 +494,13 @@
<p>Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to <b>Unrestricted</b>. Settings has a shortcut to Android's battery optimization screen.</p>
</div>
</details>
+
+<details class="faq" id="map-closes-app">
+<summary>The map closes the app (or the app closes when I open the map). What do I do?</summary>
+<div>
+<p>This happened on some older phones (seen on Android 9) whose graphics chip has no Vulkan: earlier builds drew the map with Vulkan only, so opening the map closed the app, and it did it again at every launch until the app's data was cleared. Version 2.20 picks Vulkan only where the phone has it and OpenGL everywhere else. If the app closes while the map starts for any other reason, it now tries the map again with OpenGL at the next launch, and after a second failure it takes the map off the main screen and tells you, so the rest of the app opens (add it back with the Map view button). On an earlier build, clearing the app's data (Android Settings → Apps → RF Sentinel → Storage) opens the app again, but the map will close it again. If it still happens, Settings → Lists, tools &amp; about → <b>Export crash log</b> and send it: it helps to know the phone model and Android version.</p>
+</div>
+</details>
</section>
<section class="faq-group" id="tech">
@@ -713,7 +720,7 @@
<details class="faq" id="data-collected">
<summary>What data does it collect?</summary>
<div>
-<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p>
+<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, navigation (on the phone or in Android Auto), Photon and Nominatim for place search and Valhalla for routes. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p>
</div>
</details>
diff --git a/docs/sitemap.xml b/docs/sitemap.xml
index 08bc01b..4997d3b 100644
--- a/docs/sitemap.xml
+++ b/docs/sitemap.xml
@@ -1,16 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://cis-c0.github.io/RFSentinel/alternatives.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
- <url><loc>https://cis-c0.github.io/RFSentinel/android-auto.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
+ <url><loc>https://cis-c0.github.io/RFSentinel/android-auto.html</loc><lastmod>2026-10-13</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/drone-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/esp32.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/flock-camera-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/how-it-works.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/imsi-catcher-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
- <url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-10</lastmod><priority>1.0</priority></url>
+ <url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-13</lastmod><priority>1.0</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/police-detector.html</loc><lastmod>2026-10-07</lastmod><priority>0.8</priority></url>
- <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-10</lastmod><priority>0.9</priority></url>
+ <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-13</lastmod><priority>0.9</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/smart-glasses-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/sophia-alternative.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/tracker-detector.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>
diff --git a/site/pages/android-auto.html b/site/pages/android-auto.html
index 21c8217..03ead71 100644
--- a/site/pages/android-auto.html
+++ b/site/pages/android-auto.html
@@ -29,7 +29,7 @@
<li><b>Cameras:</b> tap one to see it alone on the map, navigate to it, or tap its row to turn its alerts off or back on (faded on the maps).</li>
<li><b>More:</b> snooze alerts for 30 minutes, spoken alerts in the car, short spoken alerts, whether AirTags count as trackers, <b>cell towers</b> (fake-cell check status, serving cell and neighbours) and <b>hardware</b> status (phone radios and the scan watchdog, ESP32 / Marauder / Flipper on USB, OUI-SPY over Bluetooth, USB WiFi adapter).</li>
<li><b>Live map:</b> RF Sentinel's own OpenStreetMap map on the car screen with devices in list / radar colours, plate-reader, speed and red-light cameras, and your position. Drag, pinch or <b>+ / −</b>; <b>◎</b> follows the car again. Needs car API level 7; older Android Auto gets car-drawn maps with device and camera lists.</li>
-<li><b>Navigation:</b> <i>Navigate to...</i> searches with Nominatim (on submit only, no search-as-you-type), keeps recent destinations on the phone, routes with OSRM, draws the route with next turn, ETA and distance, speaks turns and re-routes.</li>
+<li><b>Navigation:</b> <i>Navigate to...</i> starts from Home, Work, starred and recent places kept on the phone or a search with Photon and Nominatim (on submit only), routes with Valhalla, draws the route with next turn, ETA and distance, speaks turns and re-routes. The same navigation is on the phone.</li>
<li><b>Alerts:</b> heads-up cards on the car screen with <b>Mute 30 min</b> and <b>Ignore</b> buttons, spoken through the car speakers as navigation guidance audio, briefly lowering music.</li>
<li><b>Phone screen off:</b> Android limits Bluetooth scanning then. The car warns you when a scan starts that way and shows "Bluetooth limited" on its home screen; WiFi, cell checks and known cameras keep working.</li>
</ul>
@@ -49,4 +49,4 @@
<p>Settings → <b>Start scanning automatically in the car</b>: scanning starts when the phone connects to your car's Bluetooth or to Android Auto, and stops when you leave if the car started it.</p>
<h2 id="privacy-nav">Navigation privacy</h2>
-<p>Nominatim and OSRM see the search, your position and destination, and your IP address, only when you search or start a route. They never see your scans.</p>
+<p>Photon, Nominatim and Valhalla see the search, your start and destination, and your IP address, only when you search or start a route. They never see your scans.</p>
diff --git a/site/pages/index.html b/site/pages/index.html
index 1ee3535..7197b41 100644
--- a/site/pages/index.html
+++ b/site/pages/index.html
@@ -56,6 +56,7 @@
<div class="grid">
<div class="card"><h3>Live list, radar &amp; map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div>
<div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>
+ <div class="card"><h3>Navigation</h3><p>Turn-by-turn directions on the map: search a place (Home, Work, starred and recent places are kept on the phone; or long-press the map), pick one of up to three routes, avoid tolls, highways or ferries, and go. A banner shows the next turn, lane arrows and the turn after it; spoken directions play as navigation audio so your music dips under them; it re-routes by itself, takes stops, and finds petrol, charging or food along your route. Your arrival time follows how you really drive. Open the destination in Google Maps or Waze if you prefer. No live traffic. The map goes to its night look after sunset.</p></div>
<div class="card"><h3>Map &amp; traces</h3><p>A vector map (OpenFreeMap, OpenStreetMap data, or Mapbox if you prefer) with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view like a navigation app that zooms with your speed, with the default zoom and angle in Settings; a light map and a readable night map with shops, landmarks and one-way arrows. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>
<div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div>
<div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div>
@@ -115,6 +116,6 @@
<ul>
<li><b>Receive-only.</b> The app never transmits, jams, spoofs or connects to the devices it detects.</li>
<li><b>No accounts, no cloud, no analytics.</b> Detections live in a local database excluded from cloud backup.</li>
- <li><b>Network use:</b> the map (vector tiles from OpenFreeMap, OpenStreetMap data, or from Mapbox if you pick it in Settings with Mapbox's own usage statistics switched off), camera data (Overpass API, DeFlock CDN), the roads of your area while the Waze option to alert only for reports on your road is on, and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li>
+ <li><b>Network use:</b> the map (vector tiles from OpenFreeMap, OpenStreetMap data, or from Mapbox if you pick it in Settings with Mapbox's own usage statistics switched off), camera data (Overpass API, DeFlock CDN), the roads of your area while the Waze option to alert only for reports on your road is on, and, when you search for a destination or start a route, Photon and Nominatim (place search) and Valhalla (routes), only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li>
<li><b>Data leaves the phone only when you export or share it.</b></li>
</ul>
diff --git a/site/pages/qa.html b/site/pages/qa.html
index 41d1433..2eb52a8 100644
--- a/site/pages/qa.html
+++ b/site/pages/qa.html
@@ -454,6 +454,13 @@
<p>Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to <b>Unrestricted</b>. Settings has a shortcut to Android's battery optimization screen.</p>
</div>
</details>
+
+<details class="faq" id="map-closes-app">
+<summary>The map closes the app (or the app closes when I open the map). What do I do?</summary>
+<div>
+<p>This happened on some older phones (seen on Android 9) whose graphics chip has no Vulkan: earlier builds drew the map with Vulkan only, so opening the map closed the app, and it did it again at every launch until the app's data was cleared. Version 2.20 picks Vulkan only where the phone has it and OpenGL everywhere else. If the app closes while the map starts for any other reason, it now tries the map again with OpenGL at the next launch, and after a second failure it takes the map off the main screen and tells you, so the rest of the app opens (add it back with the Map view button). On an earlier build, clearing the app's data (Android Settings → Apps → RF Sentinel → Storage) opens the app again, but the map will close it again. If it still happens, Settings → Lists, tools &amp; about → <b>Export crash log</b> and send it: it helps to know the phone model and Android version.</p>
+</div>
+</details>
</section>
<section class="faq-group" id="tech">
@@ -673,7 +680,7 @@
<details class="faq" id="data-collected">
<summary>What data does it collect?</summary>
<div>
-<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p>
+<p>None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, navigation (on the phone or in Android Auto), Photon and Nominatim for place search and Valhalla for routes. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk.</p>
</div>
</details>