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.

Android Auto: pannable live map and OpenStreetMap navigation

CIS-C01c4105139d02
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index cd11498..6199a87 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -16,6 +16,8 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!-- Android Auto: the plate camera & drone map screen (PlaceListMapTemplate). -->
<uses-permission android:name="androidx.car.app.MAP_TEMPLATES" />
+ <!-- Android Auto: draw RF Sentinel's own pannable map (devices, cameras, route). -->
+ <uses-permission android:name="androidx.car.app.ACCESS_SURFACE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
new file mode 100644
index 0000000..f8478f9
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
@@ -0,0 +1,278 @@
+package com.rfsentinel.app.car
+
+import android.app.Presentation
+import android.graphics.Rect
+import android.graphics.drawable.BitmapDrawable
+import android.hardware.display.DisplayManager
+import android.hardware.display.VirtualDisplay
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import androidx.car.app.CarContext
+import androidx.car.app.SurfaceCallback
+import androidx.car.app.SurfaceContainer
+import com.rfsentinel.app.alpr.AlprStore
+import com.rfsentinel.app.alpr.KnownCamera
+import com.rfsentinel.app.data.WhitelistCache
+import com.rfsentinel.app.detect.Tier
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.ui.DeviceColors
+import com.rfsentinel.app.ui.MapIcons
+import com.rfsentinel.app.util.Prefs
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
+import org.osmdroid.tileprovider.tilesource.TileSourceFactory
+import org.osmdroid.util.GeoPoint
+import org.osmdroid.views.CustomZoomButtonsController
+import org.osmdroid.views.MapView
+import org.osmdroid.views.overlay.FolderOverlay
+import org.osmdroid.views.overlay.Marker
+import org.osmdroid.views.overlay.Polyline
+import org.osmdroid.views.overlay.TilesOverlay
+import kotlin.math.ln
+
+/**
+ * Draws RF Sentinel's own OpenStreetMap map on the car screen (Android Auto
+ * "map with content", car API 7+): every device heard around you as a dot in
+ * the list / radar colours, the known cameras, your position and, while
+ * navigating, the route. The driver drags, flings and pinches it freely;
+ * [following] keeps it centred on the car until they move it.
+ *
+ * The map is an ordinary osmdroid MapView shown on a virtual display that
+ * renders straight into the car's surface.
+ */
+class CarMapRenderer(private val carContext: CarContext, private val scope: CoroutineScope) : SurfaceCallback {
+
+ private var display: VirtualDisplay? = null
+ private var presentation: Presentation? = null
+ private var map: MapView? = null
+ // Marker groups belong to one MapView: osmdroid disables them when it's detached,
+ // so each new car surface gets fresh ones.
+ private var devices = FolderOverlay()
+ private var cameras = FolderOverlay()
+ private var me = FolderOverlay()
+ /** The navigation route; created with each map (osmdroid needs the MapView for it). */
+ private var route: Polyline? = null
+ private var visibleArea: Rect? = null
+ private val main = Handler(Looper.getMainLooper())
+
+ /** True while the map follows the car; any drag or fling turns it off until [recenter]. */
+ var following = true
+ private set
+ var onFollowingChanged: (() -> Unit)? = null
+
+ private val tick = object : Runnable {
+ override fun run() {
+ redraw()
+ main.postDelayed(this, 2_000)
+ }
+ }
+
+ override fun onSurfaceAvailable(container: SurfaceContainer) {
+ val surface = container.surface ?: return
+ release()
+ try {
+ MapIcons.configureOsm(carContext)
+ val vd = carContext.getSystemService(DisplayManager::class.java).createVirtualDisplay(
+ "RFSentinelMap", container.width, container.height, container.dpi, surface,
+ DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY
+ )
+ val p = Presentation(carContext, vd.display)
+ devices = FolderOverlay(); cameras = FolderOverlay(); me = FolderOverlay()
+ val m = MapView(p.context).apply {
+ setTileSource(TileSourceFactory.MAPNIK)
+ setMultiTouchControls(false) // touch comes from the car via onScroll/onScale
+ zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
+ minZoomLevel = 4.0
+ maxZoomLevel = 19.0
+ controller.setZoom(16.0)
+ overlays.add(cameras)
+ overlays.add(devices)
+ overlays.add(me)
+ }
+ p.setContentView(m)
+ p.show()
+ m.onResume()
+ display = vd; presentation = p; map = m
+ applyDayNight()
+ main.post(tick)
+ } catch (e: Exception) {
+ Log.w("CarMap", "Couldn't start the car map", e)
+ release()
+ }
+ }
+
+ override fun onSurfaceDestroyed(container: SurfaceContainer) = release()
+
+ override fun onVisibleAreaChanged(area: Rect) { visibleArea = area; if (following) centreOnCar() }
+
+ override fun onScroll(distanceX: Float, distanceY: Float) {
+ val m = map ?: return
+ setFollowing(false)
+ m.scrollBy(distanceX.toInt(), distanceY.toInt())
+ m.invalidate()
+ }
+
+ override fun onFling(velocityX: Float, velocityY: Float) {
+ val m = map ?: return
+ setFollowing(false)
+ m.scrollBy((-velocityX * 0.15f).toInt(), (-velocityY * 0.15f).toInt())
+ m.invalidate()
+ }
+
+ override fun onScale(focusX: Float, focusY: Float, scaleFactor: Float) {
+ val m = map ?: return
+ // Double-tap sends no focus (-1): zoom in a level around the centre.
+ val delta = if (scaleFactor <= 0f || focusX < 0) 1.0 else ln(scaleFactor.toDouble()) / ln(2.0)
+ val z = (m.zoomLevelDouble + delta).coerceIn(m.minZoomLevel, m.maxZoomLevel)
+ if (following || focusX < 0) m.controller.setZoom(z)
+ else (m.controller as org.osmdroid.views.MapController).zoomToFixing(z, focusX.toInt(), focusY.toInt(), 0L)
+ if (following) centreOnCar()
+ redraw()
+ }
+
+ fun zoomBy(levels: Double) {
+ val m = map ?: return
+ m.controller.setZoom((m.zoomLevelDouble + levels).coerceIn(m.minZoomLevel, m.maxZoomLevel))
+ if (following) centreOnCar()
+ redraw()
+ }
+
+ fun recenter() { setFollowing(true); centreOnCar(); redraw() }
+
+ /** Frames a whole route (e.g. when navigation starts); stops following. */
+ fun showWholeRoute() {
+ val m = map ?: return
+ val pts = route?.actualPoints ?: return
+ if (pts.size < 2) return
+ setFollowing(false)
+ m.zoomToBoundingBox(org.osmdroid.util.BoundingBox.fromGeoPoints(pts).increaseByScale(1.3f), false)
+ }
+
+ private fun setFollowing(on: Boolean) {
+ if (following != on) { following = on; onFollowingChanged?.invoke() }
+ }
+
+ /** Puts the car in the middle of the part of the screen the content panel doesn't cover. */
+ private fun centreOnCar() {
+ val m = map ?: return
+ val fix = CarUi.currentLocation(carContext) ?: return
+ m.controller.setCenter(GeoPoint(fix.latitude, fix.longitude))
+ visibleArea?.let { a ->
+ if (m.width > 0 && !a.isEmpty) m.scrollBy(-(a.centerX() - m.width / 2), -(a.centerY() - m.height / 2))
+ }
+ }
+
+ private fun applyDayNight() {
+ map?.overlayManager?.tilesOverlay?.setColorFilter(if (carContext.isDarkMode) TilesOverlay.INVERT_COLORS else null)
+ }
+
+ /** Re-places every marker from the live data (every 2 s and after each zoom). */
+ fun redraw() {
+ val m = map ?: return
+ val dp = m.context.resources.displayMetrics.density
+ applyDayNight()
+ if (following) centreOnCar()
+
+ syncRoute(m)
+ me.items.clear()
+ com.rfsentinel.app.nav.Navigator.destination?.let { d ->
+ me.add(Marker(m).apply {
+ position = GeoPoint(d.lat, d.lon)
+ icon = MapIcons.dot(dp, 0xFFD93025.toInt(), 20, 3f)
+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
+ setInfoWindow(null)
+ })
+ }
+ CarUi.currentLocation(carContext)?.let { fix ->
+ me.add(Marker(m).apply {
+ position = GeoPoint(fix.latitude, fix.longitude)
+ icon = MapIcons.dot(dp, 0xFF1A73E8.toInt(), 22, 3f)
+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
+ setInfoWindow(null)
+ })
+ }
+
+ devices.items.clear()
+ val list = DeviceRegistry.snapshot().filter { !WhitelistCache.contains(it.mac) }
+ // Ordinary devices first so flagged ones are drawn on top.
+ for (s in list.sortedBy { DeviceColors.isFlagged(it) }) {
+ val rid = s.remoteId?.takeIf { it.hasPosition }
+ val lat = rid?.latitude ?: s.bestPosition?.lat ?: continue
+ val lon = rid?.longitude ?: s.bestPosition?.lon ?: continue
+ val best = s.best
+ val color = when {
+ best == null -> DevicesMapScreen.ORDINARY_COLOR
+ best.tier == Tier.WEAK -> DeviceColors.WEAK
+ else -> best.category.colorArgb
+ }
+ devices.add(Marker(m).apply {
+ position = GeoPoint(lat, lon)
+ icon = MapIcons.dot(dp, color, if (DeviceColors.isFlagged(s)) 16 else 9)
+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
+ setInfoWindow(null)
+ })
+ }
+
+ cameras.items.clear()
+ if (m.zoomLevelDouble >= 9.0) {
+ val box = m.boundingBox.increaseByScale(1.4f)
+ val icons = KnownCamera.Kind.entries.associateWith { BitmapDrawable(m.context.resources, MapIcons.cameraIcon(dp, it)) }
+ AlprStore.cameras.asSequence()
+ .filter { it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast }
+ .take(600)
+ .forEach { c ->
+ cameras.add(Marker(m).apply {
+ position = GeoPoint(c.lat, c.lon)
+ icon = icons.getValue(c.type)
+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
+ setInfoWindow(null)
+ })
+ }
+ // Fetch the cameras for wherever the driver moved the map.
+ if (Prefs.autoCameras(carContext) && !AlprStore.isBusy && box.latNorth - box.latSouth <= AlprStore.MAX_SPAN_DEG) {
+ scope.launch {
+ if (AlprStore.autoDownload(carContext, box.latSouth, box.lonWest, box.latNorth, box.lonEast)) redraw()
+ }
+ }
+ }
+ m.invalidate()
+ }
+
+ private var drawnRoute: com.rfsentinel.app.nav.OsmRouting.Route? = null
+
+ /** Swaps in a new route line when the route changes (osmdroid lines are rebuilt, not edited). */
+ private fun syncRoute(m: MapView) {
+ val r = com.rfsentinel.app.nav.Navigator.route
+ if (r === drawnRoute) return
+ drawnRoute = r
+ route?.let { m.overlays.remove(it) }
+ route = null
+ if (r == null || r.points.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) })
+ setInfoWindow(null)
+ }
+ m.overlays.add(0, route) // under the markers
+ }
+
+ /** What's on the map now, for the side panel. */
+ fun counts(): Pair<Int, Int> {
+ val m = map ?: return 0 to 0
+ val box = m.boundingBox
+ val d = devices.items.size
+ val c = AlprStore.cameras.count { it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast }
+ return d to c
+ }
+
+ fun release() {
+ main.removeCallbacks(tick)
+ runCatching { map?.onPause(); map?.onDetach() }
+ runCatching { presentation?.dismiss() }
+ runCatching { display?.release() }
+ map = null; presentation = null; display = null; route = null; drawnRoute = null
+ }
+
+}
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
index 983140a..4b14e25 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
@@ -30,7 +30,10 @@ object CarUi {
/** Where the driver is: the scanner's latest fix, else the phone's last known position. */
@android.annotation.SuppressLint("MissingPermission") // checked via Permissions
fun currentLocation(context: CarContext): android.location.Location? {
- com.rfsentinel.app.service.ScanForegroundService.lastFix?.let { return it }
+ // Navigation keeps its own 1 s GPS fixes; use whichever fix is newer.
+ val nav = com.rfsentinel.app.nav.Navigator.lastFix
+ val scan = com.rfsentinel.app.service.ScanForegroundService.lastFix
+ listOfNotNull(nav, scan).maxByOrNull { it.elapsedRealtimeNanos }?.let { return it }
if (!com.rfsentinel.app.util.Permissions.granted(context, android.Manifest.permission.ACCESS_FINE_LOCATION)) return null
val lm = context.getSystemService(android.location.LocationManager::class.java) ?: return null
return listOf(android.location.LocationManager.GPS_PROVIDER, android.location.LocationManager.NETWORK_PROVIDER)
diff --git a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
new file mode 100644
index 0000000..2d88820
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
@@ -0,0 +1,124 @@
+package com.rfsentinel.app.car
+
+import androidx.car.app.CarContext
+import androidx.car.app.CarToast
+import androidx.car.app.Screen
+import androidx.car.app.model.Action
+import androidx.car.app.model.ItemList
+import androidx.car.app.model.Row
+import androidx.car.app.model.SearchTemplate
+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.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.
+ */
+class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen) : Screen(carContext) {
+
+ private var results: List<OsmRouting.Destination>? = null
+ private var loading = false
+ private var query = ""
+ /** What's typed so far (searched only when submitted or tapped - no search-as-you-type). */
+ private var typed = ""
+
+ override fun onGetTemplate(): Template {
+ val list = ItemList.Builder()
+ val shown = results ?: Prefs.recentDestinations(carContext)
+ val me = CarUi.currentLocation(carContext)
+ // Some cars' keyboards don't send "submit": offer the search as a row too.
+ if (typed.isNotBlank() && typed != query) {
+ list.addItem(Row.Builder()
+ .setTitle("Search \"${typed.trim()}\"")
+ .addText("in OpenStreetMap")
+ .setOnClickListener { search(typed) }
+ .build())
+ }
+ shown.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" }
+ row.addText(
+ if (me != null) NearbyMapScreen.distanceText(DeviceRegistry.metersBetween(me.latitude, me.longitude, d.lat, d.lon)) + " · " + where
+ else where
+ )
+ row.setOnClickListener { go(d) }
+ list.addItem(row.build())
+ }
+ if (shown.isEmpty() && !loading && (typed.isBlank() || typed == query)) {
+ list.setNoItemsMessage(if (results == null) "Search for an address or a place" else "Nothing found for \"$query\"")
+ }
+ return SearchTemplate.Builder(object : SearchTemplate.SearchCallback {
+ override fun onSearchSubmitted(searchText: String) = search(searchText)
+ override fun onSearchTextChanged(searchText: String) {
+ val was = typed.isNotBlank() && typed != query
+ typed = searchText
+ // Only re-render when the row appears / its text changes (no network here).
+ if (was || typed.isNotBlank()) invalidate()
+ }
+ })
+ .setInitialSearchText(typed)
+ .setHeaderAction(Action.BACK)
+ .setSearchHint("Destination (searched in OpenStreetMap)")
+ .setShowKeyboardByDefault(results == null && Prefs.recentDestinations(carContext).isEmpty())
+ .setLoading(loading)
+ .apply { if (!loading) setItemList(list.build()) }
+ .build()
+ }
+
+ private fun search(text: String) {
+ val q = text.trim()
+ if (q.isEmpty()) return
+ query = q
+ loading = true
+ invalidate()
+ val me = CarUi.currentLocation(carContext)
+ lifecycleScope.launch {
+ val found = runCatching {
+ withContext(Dispatchers.IO) {
+ OsmRouting.search(q, me?.latitude, me?.longitude, "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")
+ }
+ }
+ 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()
+ CarToast.makeText(carContext, "Search failed - no connection?", CarToast.LENGTH_LONG).show()
+ }
+ invalidate()
+ }
+ }
+
+ private fun go(d: OsmRouting.Destination) {
+ val from = CarUi.currentLocation(carContext)
+ if (from == null) {
+ CarToast.makeText(carContext, "Waiting for your location...", CarToast.LENGTH_SHORT).show(); return
+ }
+ loading = true
+ invalidate()
+ lifecycleScope.launch {
+ runCatching { Navigator.start(carContext, d, from) }
+ .onSuccess {
+ Prefs.addRecentDestination(carContext, d)
+ screenManager.pop()
+ map.onNavigationStarted()
+ }
+ .onFailure {
+ loading = false
+ CarToast.makeText(carContext, "No route: ${it.message ?: "no connection"}", CarToast.LENGTH_LONG).show()
+ invalidate()
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
index 3f2f7ed..afb4fd7 100644
--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
@@ -56,12 +56,16 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {
items.addItem(navRow("Flagged nearby", flagged, R.drawable.ic_car_warning, DeviceListScreen.Filter.FLAGGED))
items.addItem(navRow("Drones & trackers", dronesTrackers, R.drawable.ic_car_drone, DeviceListScreen.Filter.DRONES_TRACKERS))
items.addItem(navRow("All nearby devices", devices.size, R.drawable.ic_car_list, DeviceListScreen.Filter.ALL))
+ val liveMap = runCatching { carContext.carAppApiLevel >= androidx.car.app.versioning.CarAppApiLevels.LEVEL_7 }.getOrDefault(false)
items.addItem(
Row.Builder()
- .setTitle("Map: devices & cameras around me")
+ .setTitle(if (liveMap) "Live map & navigation" else "Map: devices & cameras around me")
.setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
.setBrowsable(true)
- .setOnClickListener { screenManager.push(DevicesMapScreen(carContext)) }
+ .setOnClickListener {
+ // Our own pannable map needs car API 7; older cars get the car-drawn map.
+ screenManager.push(if (liveMap) LiveMapScreen(carContext) else DevicesMapScreen(carContext))
+ }
.build()
)
diff --git a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
new file mode 100644
index 0000000..82d49cc
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
@@ -0,0 +1,130 @@
+package com.rfsentinel.app.car
+
+import androidx.car.app.AppManager
+import androidx.car.app.CarContext
+import androidx.car.app.model.Action
+import androidx.car.app.model.ActionStrip
+import androidx.car.app.model.ItemList
+import androidx.car.app.model.ListTemplate
+import androidx.car.app.model.Row
+import androidx.car.app.model.Template
+import androidx.car.app.navigation.model.MapController
+import androidx.car.app.navigation.model.MapWithContentTemplate
+import androidx.lifecycle.DefaultLifecycleObserver
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.lifecycleScope
+import com.rfsentinel.app.R
+import com.rfsentinel.app.nav.Navigator
+import com.rfsentinel.app.service.ScanForegroundService
+import java.text.DateFormat
+import java.util.Date
+
+/**
+ * Android Auto (car API 7+): RF Sentinel's own map, which the driver can drag
+ * and zoom freely - every device heard around you in the list / radar colours,
+ * the known cameras and your position, nothing to select. Beside it: a summary,
+ * or turn-by-turn guidance to a destination found in OpenStreetMap.
+ */
+class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 3_000L, preciseLocation = true) {
+
+ private val renderer = CarMapRenderer(carContext, lifecycleScope)
+
+ 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() }
+ }
+ override fun onDestroy(owner: LifecycleOwner) {
+ carContext.getCarService(AppManager::class.java).setSurfaceCallback(null)
+ renderer.release()
+ Navigator.onUpdate = null
+ }
+ })
+ }
+
+ /** Called by the destination screen once a route has started. */
+ fun onNavigationStarted() {
+ renderer.recenter()
+ invalidate()
+ }
+
+ override fun onGetTemplate(): Template {
+ val list = ItemList.Builder()
+ if (Navigator.active) guidanceRows(list) else summaryRows(list)
+
+ val content = ListTemplate.Builder()
+ .setTitle(if (Navigator.active) Navigator.destination?.name ?: "Navigation" else "Live map")
+ .setHeaderAction(Action.BACK)
+ .setSingleList(list.build())
+ .build()
+
+ // Map buttons: PAN (lets the car send drags), zoom, and back to following the car.
+ val mapActions = ActionStrip.Builder()
+ .addAction(Action.PAN)
+ .addAction(Action.Builder().setIcon(CarUi.icon(carContext, R.drawable.ic_car_zoom_in))
+ .setOnClickListener { renderer.zoomBy(1.0) }.build())
+ .addAction(Action.Builder().setIcon(CarUi.icon(carContext, R.drawable.ic_car_zoom_out))
+ .setOnClickListener { renderer.zoomBy(-1.0) }.build())
+ .addAction(Action.Builder().setIcon(CarUi.icon(carContext, R.drawable.ic_car_my_location))
+ .setOnClickListener { renderer.recenter(); invalidate() }.build())
+ .build()
+
+ return MapWithContentTemplate.Builder()
+ .setContentTemplate(content)
+ .setMapController(MapController.Builder().setMapActionStrip(mapActions).build())
+ .build()
+ }
+
+ private fun summaryRows(list: ItemList.Builder) {
+ val (devices, cameras) = renderer.counts()
+ list.addItem(Row.Builder()
+ .setTitle(if (ScanForegroundService.isRunning) "$devices devices · $cameras cameras on the map" else "Not scanning")
+ .addText(if (renderer.following) "Drag or pinch the map to look around" else "Tap ◎ to follow the car again")
+ .build())
+ list.addItem(Row.Builder()
+ .setTitle("Navigate to...")
+ .addText("Search a destination (OpenStreetMap)")
+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
+ .setBrowsable(true)
+ .setOnClickListener { screenManager.push(DestinationScreen(carContext, this)) }
+ .build())
+ list.addItem(Row.Builder()
+ .setTitle("Device list")
+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_list))
+ .setBrowsable(true)
+ .setOnClickListener { screenManager.push(DevicesMapScreen(carContext)) }
+ .build())
+ list.addItem(Row.Builder()
+ .setTitle("Camera list")
+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning))
+ .setBrowsable(true)
+ .setOnClickListener { screenManager.push(NearbyMapScreen(carContext)) }
+ .build())
+ }
+
+ private fun guidanceRows(list: ItemList.Builder) {
+ val p = Navigator.progress
+ val step = p?.nextStep
+ 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...")
+ .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()))
+ list.addItem(Row.Builder()
+ .setTitle("Arrive $eta")
+ .addText("${NearbyMapScreen.distanceText(p.remainingM)} · ${(leftS / 60).toInt().coerceAtLeast(1)} min")
+ .build())
+ }
+ list.addItem(Row.Builder()
+ .setTitle("Stop navigation")
+ .setOnClickListener { Navigator.stop(); renderer.recenter(); invalidate() }
+ .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
new file mode 100644
index 0000000..52b6b32
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
@@ -0,0 +1,193 @@
+package com.rfsentinel.app.nav
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.location.Location
+import android.location.LocationListener
+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.util.AlertPlayer
+import com.rfsentinel.app.util.Permissions
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * 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.
+ */
+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
+ const val ARRIVED_M = 35.0
+
+ @Volatile var destination: OsmRouting.Destination? = null
+ private set
+ @Volatile var route: OsmRouting.Route? = null
+ private set
+ @Volatile var progress: Progress? = null
+ private set
+ @Volatile var lastFix: Location? = null
+ private set
+ @Volatile var status: String? = null
+ private set
+
+ val active: Boolean get() = destination != null
+
+ /** Called on every change (main thread). */
+ var onUpdate: (() -> Unit)? = null
+
+ private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
+ private var appContext: Context? = null
+ private var offRouteSince = 0L
+ private var lastReroute = 0L
+ private var spokenStep: OsmRouting.Step? = null
+ private var spokenNear = false
+
+ private val listener = LocationListener { 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) {
+ 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
+ lastFix = from
+ spokenStep = null; spokenNear = false; offRouteSince = 0L
+ progress = progressOf(r, from.latitude, from.longitude)
+ status = null
+ listen(app, true)
+ progress?.nextStep?.let { say(it.instruction) }
+ onUpdate?.invoke()
+ }
+
+ fun stop() {
+ appContext?.let { listen(it, false) }
+ destination = null; route = null; progress = null; status = null
+ onUpdate?.invoke()
+ }
+
+ @SuppressLint("MissingPermission") // checked via Permissions
+ private fun listen(context: Context, on: Boolean) {
+ val lm = context.getSystemService(LocationManager::class.java) ?: return
+ lm.removeUpdates(listener)
+ if (!on || !Permissions.granted(context, android.Manifest.permission.ACCESS_FINE_LOCATION)) return
+ val provider = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && lm.hasProvider(LocationManager.FUSED_PROVIDER))
+ LocationManager.FUSED_PROVIDER else LocationManager.GPS_PROVIDER
+ runCatching {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ val req = android.location.LocationRequest.Builder(1_000L)
+ .setQuality(android.location.LocationRequest.QUALITY_HIGH_ACCURACY).build()
+ lm.requestLocationUpdates(provider, req, context.mainExecutor, listener)
+ } else {
+ lm.requestLocationUpdates(provider, 1_000L, 0f, listener, Looper.getMainLooper())
+ }
+ }
+ }
+
+ 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()
+ }
+
+ 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()
+ }
+ }
+
+ private fun say(text: String) {
+ val ctx = appContext ?: return
+ AlertPlayer.announce(ctx, text)
+ }
+
+ // ---- Pure geometry -------------------------------------------------------------
+
+ 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"
+ }
+
+ /**
+ * 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.
+ */
+ 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 }
+ }
+ // 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
+ }
+ 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)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/nav/OsmRouting.kt b/app/src/main/java/com/rfsentinel/app/nav/OsmRouting.kt
new file mode 100644
index 0000000..f7f4fb0
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/nav/OsmRouting.kt
@@ -0,0 +1,138 @@
+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/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
index ddb992f..718c0ef 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
@@ -92,11 +92,7 @@ class MapActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
// osmdroid: identify ourselves to the tile server (OSM tile policy) and keep
// the tile cache inside the app's private cache.
- Configuration.getInstance().apply {
- userAgentValue = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}"
- osmdroidBasePath = File(cacheDir, "osmdroid")
- osmdroidTileCache = File(cacheDir, "osmdroid/tiles")
- }
+ MapIcons.configureOsm(this)
binding = ActivityMapBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
@@ -527,24 +523,7 @@ class MapActivity : AppCompatActivity() {
map.invalidate()
}
- /** A small camera glyph, distinct from the round device dots: red plate reader, amber speed, purple red-light. */
- private fun cameraIcon(dp: Float, kind: com.rfsentinel.app.alpr.KnownCamera.Kind): android.graphics.Bitmap {
- val w = (22 * dp).toInt(); val h = (16 * dp).toInt()
- val bmp = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)
- val c = android.graphics.Canvas(bmp)
- val p = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)
- val body = android.graphics.RectF(1 * dp, 3 * dp, w - 1 * dp, h - 1 * dp)
- p.color = when (kind) {
- com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> 0xFFB3261E.toInt()
- com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> 0xFFE08A00.toInt()
- com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> 0xFF7B1FA2.toInt()
- }
- c.drawRoundRect(body, 3 * dp, 3 * dp, p)
- p.style = android.graphics.Paint.Style.STROKE; p.strokeWidth = 1.5f * dp; p.color = Color.WHITE
- c.drawRoundRect(body, 3 * dp, 3 * dp, p)
- c.drawCircle(w / 2f, (h + 2 * dp) / 2f, 3.5f * dp, p)
- return bmp
- }
+ private fun cameraIcon(dp: Float, kind: com.rfsentinel.app.alpr.KnownCamera.Kind) = MapIcons.cameraIcon(dp, kind)
private fun showKnownCamera(cam: com.rfsentinel.app.alpr.KnownCamera) {
val text = buildString {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt
new file mode 100644
index 0000000..210f628
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt
@@ -0,0 +1,56 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.drawable.GradientDrawable
+import com.rfsentinel.app.BuildConfig
+import com.rfsentinel.app.alpr.KnownCamera
+import org.osmdroid.config.Configuration
+import java.io.File
+
+/** Map pieces shared by the phone map and the Android Auto map. */
+object MapIcons {
+
+ /** osmdroid: identify ourselves to the tile server (OSM tile policy), cache tiles privately. */
+ fun configureOsm(context: Context) {
+ Configuration.getInstance().apply {
+ userAgentValue = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}"
+ osmdroidBasePath = File(context.cacheDir, "osmdroid")
+ osmdroidTileCache = File(context.cacheDir, "osmdroid/tiles")
+ }
+ }
+
+ fun cameraColor(kind: KnownCamera.Kind): Int = when (kind) {
+ KnownCamera.Kind.ALPR -> 0xFFB3261E.toInt()
+ KnownCamera.Kind.SPEED -> 0xFFE08A00.toInt()
+ KnownCamera.Kind.RED_LIGHT -> 0xFF7B1FA2.toInt()
+ }
+
+ /** A small camera glyph, distinct from the round device dots: red plate reader, amber speed, purple red-light. */
+ fun cameraIcon(dp: Float, kind: KnownCamera.Kind): Bitmap {
+ val w = (22 * dp).toInt(); val h = (16 * dp).toInt()
+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val c = Canvas(bmp)
+ val p = Paint(Paint.ANTI_ALIAS_FLAG)
+ val body = RectF(1 * dp, 3 * dp, w - 1 * dp, h - 1 * dp)
+ p.color = cameraColor(kind)
+ c.drawRoundRect(body, 3 * dp, 3 * dp, p)
+ p.style = Paint.Style.STROKE; p.strokeWidth = 1.5f * dp; p.color = Color.WHITE
+ c.drawRoundRect(body, 3 * dp, 3 * dp, p)
+ c.drawCircle(w / 2f, (h + 2 * dp) / 2f, 3.5f * dp, p)
+ return bmp
+ }
+
+ /** A round device dot with a white ring. */
+ fun dot(dp: Float, color: Int, sizeDp: Int, ringDp: Float = 2f) = GradientDrawable().apply {
+ shape = GradientDrawable.OVAL
+ setColor(color)
+ setStroke((ringDp * dp).toInt().coerceAtLeast(1), Color.WHITE)
+ val px = (sizeDp * dp).toInt()
+ setSize(px, px)
+ }
+}
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 4b4f062..b7d935e 100644
--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
@@ -91,6 +91,13 @@ object AlertPlayer {
}
}
+ /** A spoken navigation instruction (no beep, no vibration); silent when alerts are muted. */
+ fun announce(context: Context, text: String) {
+ if (Prefs.alertsMuted(context)) return
+ duckOthers(context, 5_000L)
+ speak(context.applicationContext, text, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)
+ }
+
/**
* Silent and vibrate ringer modes, and Do Not Disturb, mute the beeps on the
* phone (vibration still runs) - like the notification sound they replace.
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 7dca587..e7acd84 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -101,6 +101,16 @@ object Prefs {
/** Map: every device heard (true) or flagged ones only. */
fun mapShowAll(context: Context): Boolean = bool(context, "map_show_all", true)
fun setMapShowAll(context: Context, value: Boolean) = setBool(context, "map_show_all", value)
+ /** 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()
+ }.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)) }
+ }
+ fun clearRecentDestinations(context: Context) = sp(context).edit { remove("recent_destinations") }
fun showKnownAlpr(context: Context): Boolean = bool(context, "show_known_alpr", true)
fun setShowKnownAlpr(context: Context, value: Boolean) = setBool(context, "show_known_alpr", value)
diff --git a/app/src/main/res/drawable/ic_car_my_location.xml b/app/src/main/res/drawable/ic_car_my_location.xml
new file mode 100644
index 0000000..746302c
--- /dev/null
+++ b/app/src/main/res/drawable/ic_car_my_location.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), used on the Android Auto screens. -->
+<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,8c-2.21,0 -4,1.79 -4,4s1.79,4 4,4 4,-1.79 4,-4 -1.79,-4 -4,-4zM20.94,11c-0.46,-4.17 -3.77,-7.48 -7.94,-7.94V1h-2v2.06C6.83,3.52 3.52,6.83 3.06,11H1v2h2.06c0.46,4.17 3.77,7.48 7.94,7.94V23h2v-2.06c4.17,-0.46 7.48,-3.77 7.94,-7.94H23v-2h-2.06zM12,19c-3.87,0 -7,-3.13 -7,-7s3.13,-7 7,-7 7,3.13 7,7 -3.13,7 -7,7z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_car_zoom_in.xml b/app/src/main/res/drawable/ic_car_zoom_in.xml
new file mode 100644
index 0000000..ea60886
--- /dev/null
+++ b/app/src/main/res/drawable/ic_car_zoom_in.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), used on the Android Auto screens. -->
+<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,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_car_zoom_out.xml b/app/src/main/res/drawable/ic_car_zoom_out.xml
new file mode 100644
index 0000000..4ceffb6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_car_zoom_out.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), used on the Android Auto screens. -->
+<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,13H5v-2h14v2z" />
+</vector>
diff --git a/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt b/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt
index f176cc8..cc11f27 100644
--- a/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt
@@ -79,7 +79,7 @@ class CarScreensTest {
assertTrue(rows[1].title.toString().startsWith("Flagged nearby (2)"))
assertTrue(rows[2].title.toString().startsWith("Drones & trackers (1)"))
assertTrue(rows[3].title.toString().startsWith("All nearby devices (14)"))
- assertEquals("Map: devices & cameras around me", rows[4].title.toString())
+ assertTrue(rows[4].title.toString() in setOf("Live map & navigation", "Map: devices & cameras around me"))
val actions = t.actionStrip!!.actions
assertEquals(2, actions.size)
assertEquals("Stop", actions[0].title.toString())
@@ -171,6 +171,17 @@ class CarScreensTest {
)
}
+ @Test
+ fun liveMapBuildsWithPanZoomAndNavigationPanel() {
+ val screen = LiveMapScreen(car)
+ val t = screen.onGetTemplate() as androidx.car.app.navigation.model.MapWithContentTemplate
+ val strip = t.mapController!!.mapActionStrip!!
+ assertTrue(strip.actions.any { it.type == androidx.car.app.model.Action.TYPE_PAN })
+ assertEquals(4, strip.actions.size)
+ val rows = (t.contentTemplate as ListTemplate).singleList!!.items.map { (it as Row).title.toString() }
+ assertTrue(rows.contains("Navigate to..."))
+ }
+
@Test
fun cameraFocusScreenCentresOnOnePlaceWithNavigate() {
fun build() = PlaceFocusScreen(car, "Speed camera (50 km/h)", "Mapped in OpenStreetMap", 10.51, -20.5,
diff --git a/app/src/test/java/com/rfsentinel/app/nav/OsmRoutingTest.kt b/app/src/test/java/com/rfsentinel/app/nav/OsmRoutingTest.kt
new file mode 100644
index 0000000..9b03d11
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/nav/OsmRoutingTest.kt
@@ -0,0 +1,71 @@
+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))
+ }
+}