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.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
Android Auto rework: home by importance (next camera ahead, recent alerts, nearby filters, More), recent alerts with out-of-range details, cell towers, hardware status, snooze, tracker ignore choices, camera ignore toggle, Mute 30 min / Ignore on car alerts, change-only refreshes, crash-safe screens, cached map icons, tests
CIS-C0aafe3a361175
diff --git a/README.md b/README.mdindex f855bfe..d81b666 100644--- a/README.md+++ b/README.md@@ -133,7 +133,7 @@ Every match shows its evidence, its source and a confidence tier: **weak** (< 50- **History map & timeline:** heatmap of where flagged equipment showed up, and when (hour of day, day of week)**Driving**-- **Android Auto** app: threat headline, device lists, live map with cameras and drones, OpenStreetMap turn-by-turn navigation, alerts through the car speakers+- **Android Auto** app: threat headline, next camera ahead, recent alerts, filtered device lists, cell towers, hardware status, live map with cameras and drones, OpenStreetMap turn-by-turn navigation, alerts through the car speakers with Mute 30 min / Ignore buttons- **Starts by itself in the car** (your car's Bluetooth or Android Auto) and stops when you leave- Night Drive red-only theme; screen stays on while charging@@ -269,11 +269,27 @@ A driver-safe, template-based Android Auto app:</p><p align="center"><sub>Home, flagged devices, live map, and known cameras (demo data).</sub></p>-- **Home:** threat headline, live counts, Start/Stop, and a speaker button that- mutes or unmutes all alert sound.-- **Device lists** (flagged, drones & trackers, all nearby) and **details** with- Whitelist, Watch and Favorite. **Navigate** hands drones with a known position- to your navigation app.+- **Home**, most important first (a car shows about six rows while driving):+ the threat headline (tap for the flagged devices), the **next known camera on+ your way** with its distance, **recent alerts**, the map, nearby devices and+ **More**. Start/Stop and a speaker button that mutes or unmutes all alert+ sound sit in the header.+- **Nearby devices** with the phone's filters and live counts (flagged,+ trackers, drones, favorites, new, Bluetooth, WiFi, ESP32 / USB). Each row says+ which radio heard it.+- **Device details** with Whitelist, Watch and Favorite; trackers get the+ phone's three ignore choices (*it's mine*, *today only*, *pause follow+ warnings*). **Navigate** hands drones with a known position to your+ navigation app. A device that has left still shows its last alert.+- **Recent alerts:** the last 40 alerts (devices, cameras, cell warnings), kept+ after the device is gone.+- **Cameras:** 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).+- **More:** snooze alerts for 30 minutes, spoken alerts in the car, short+ spoken alerts, whether AirTags count as trackers, **cell towers** (fake-cell+ check status, serving cell and neighbours) and **hardware** status (phone+ radios and the scan watchdog, ESP32 / Marauder / Flipper on USB, OUI-SPY over+ Bluetooth, USB WiFi adapter).- **Live map:** RF Sentinel's own OpenStreetMap map on the car screen withdevices, known plate / speed / red-light cameras and your position. Drag,pinch or **+ / −**; **◎** follows the car again. Needs car API level 7; older@@ -281,8 +297,11 @@ A driver-safe, template-based Android Auto app:- **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.-- **Alerts** appear as heads-up cards and play through the car speakers as- navigation audio, briefly lowering your music.+- **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.+- Screens only redraw when what they show has changed, and a screen that fails+ to build shows a short message instead of closing the app.**Sideloaded apps need one-time setup:** Android Auto settings → tap **Version**ten times → **⋮ → Developer settings** → enable **Unknown sources**. Thendiff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex b106653..d11b3ca 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -149,6 +149,11 @@</intent-filter></receiver>+ <!-- "Mute 30 min" / "Ignore" buttons on alerts shown on the car screen. -->+ <receiver+ android:name=".receiver.AlertActionReceiver"+ android:exported="false" />+<receiverandroid:name=".receiver.CarBluetoothReceiver"android:exported="true">diff --git a/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt b/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.ktindex 16226c7..a813e86 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt@@ -186,6 +186,34 @@ object KnownCameras {else max(300.0, minOf(900.0, v * 30.0))}+ /**+ * The next camera on your way: the nearest within [maxM] that lies within+ * [coneDeg] of your direction of travel ([bearingDeg]). Without a bearing+ * (standing still, no GPS heading) the nearest within [maxM] / 3. [skip]+ * leaves out cameras the user silenced.+ */+ fun ahead(+ cameras: List<KnownCamera>, lat: Double, lon: Double, bearingDeg: Float?,+ maxM: Double = 3_000.0, coneDeg: Double = 45.0, skip: (KnownCamera) -> Boolean = { false }+ ): Pair<KnownCamera, Double>? {+ if (bearingDeg == null) return near(cameras, lat, lon, maxM / 3).firstOrNull { !skip(it.first) }+ return near(cameras, lat, lon, maxM).firstOrNull { (c, d) ->+ if (skip(c)) return@firstOrNull false+ if (d < 30.0) return@firstOrNull true // right here+ val diff = kotlin.math.abs(((bearingTo(lat, lon, c.lat, c.lon) - bearingDeg) % 360 + 540) % 360 - 180)+ diff <= coneDeg+ }+ }++ /** Initial great-circle bearing from one point to another, degrees from north (0-360). */+ fun bearingTo(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {+ val p1 = Math.toRadians(lat1); val p2 = Math.toRadians(lat2)+ val dl = Math.toRadians(lon2 - lon1)+ val y = kotlin.math.sin(dl) * cos(p2)+ val x = cos(p1) * kotlin.math.sin(p2) - kotlin.math.sin(p1) * cos(p2) * cos(dl)+ return (Math.toDegrees(kotlin.math.atan2(y, x)) + 360) % 360+ }+/** Cameras within [radiusM] of a point, nearest first. Cheap bounding-box prefilter. */fun near(cameras: List<KnownCamera>, lat: Double, lon: Double, radiusM: Double): List<Pair<KnownCamera, Double>> {val dLat = radiusM / 111_000.0diff --git a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.ktindex 4fa8541..8c320fe 100644--- a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt+++ b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt@@ -51,6 +51,16 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coroprivate var devices = FolderOverlay()private var cameras = FolderOverlay()private var me = FolderOverlay()+ private var towers = FolderOverlay()+ /** Icons are built once per map, not on every redraw (keyed by colour and size). */+ private val dotIcons = HashMap<Long, android.graphics.drawable.Drawable>()+ private var cameraIcons: Map<KnownCamera.Kind, BitmapDrawable> = emptyMap()+ private var fadedCameraIcons: Map<KnownCamera.Kind, BitmapDrawable> = emptyMap()+ private var towerIcon: BitmapDrawable? = null+ /** What the marker layers were last built from: unchanged data isn't rebuilt. */+ private var devicesKey: Any? = null+ private var camerasKey: Any? = null+ private var towersKey: Any? = null/** The navigation route; created with each map (osmdroid needs the MapView for it). */private var route: Polyline? = nullprivate var visibleArea: Rect? = null@@ -78,7 +88,8 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: CoroDisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY)val p = Presentation(carContext, vd.display)- devices = FolderOverlay(); cameras = FolderOverlay(); me = FolderOverlay()+ devices = FolderOverlay(); cameras = FolderOverlay(); me = FolderOverlay(); towers = FolderOverlay()+ dotIcons.clear(); devicesKey = null; camerasKey = null; towersKey = nullval m = MapView(p.context).apply {setTileSource(TileSourceFactory.MAPNIK)setMultiTouchControls(false) // touch comes from the car via onScroll/onScale@@ -86,6 +97,7 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: CorominZoomLevel = 4.0maxZoomLevel = 19.0controller.setZoom(16.0)+ overlays.add(towers)overlays.add(cameras)overlays.add(devices)overlays.add(me)@@ -93,6 +105,13 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Corop.setContentView(m)p.show()m.onResume()+ val dp = m.context.resources.displayMetrics.density+ // Car screens sit further away: bigger camera icons than on the phone.+ cameraIcons = KnownCamera.Kind.entries.associateWith { BitmapDrawable(m.context.resources, MapIcons.cameraIcon(dp * 1.6f, it)) }+ fadedCameraIcons = KnownCamera.Kind.entries.associateWith {+ BitmapDrawable(m.context.resources, MapIcons.cameraIcon(dp * 1.6f, it)).apply { alpha = 90 }+ }+ towerIcon = BitmapDrawable(m.context.resources, MapIcons.towerIcon(dp * 1.3f))display = vd; presentation = p; map = mapplyDayNight()main.post(tick)@@ -193,52 +212,89 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro})}- 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: ordinary first so flagged ones are drawn on top.+ val placed = DeviceRegistry.snapshot().filter { !WhitelistCache.contains(it.mac) }+ .sortedBy { DeviceColors.isFlagged(it) }+ .mapNotNull { s ->+ val rid = s.remoteId?.takeIf { it.hasPosition }+ val lat = rid?.latitude ?: s.bestPosition?.lat ?: return@mapNotNull null+ val lon = rid?.longitude ?: s.bestPosition?.lon ?: return@mapNotNull null+ val best = s.best+ val color = when {+ best == null -> DevicesMapScreen.ORDINARY_COLOR+ best.tier == Tier.WEAK -> DeviceColors.WEAK+ else -> best.category.colorArgb+ }+ DeviceDot(lat, lon, color, if (DeviceColors.isFlagged(s)) 18 else 11)+ }+ if (placed != devicesKey) {+ devicesKey = placed+ devices.items.clear()+ for (d in placed) {+ devices.add(Marker(m).apply {+ position = GeoPoint(d.lat, d.lon)+ icon = dotIcons.getOrPut((d.color.toLong() shl 8) or d.sizeDp.toLong()) { MapIcons.dot(dp, d.color, d.sizeDp) }+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)+ setInfoWindow(null)+ })+ }+ }++ // Cell towers (phone map menu: Show cell towers), at their estimated spots.+ val showTowers = Prefs.showCellTowers(carContext)+ val tKey = if (showTowers) com.rfsentinel.app.service.CellTowerStore.currentAt / 30_000L else null+ if (tKey != towersKey) {+ towersKey = tKey+ towers.items.clear()+ if (showTowers) com.rfsentinel.app.service.CellTowerStore.all(carContext).forEach { t ->+ val lat = t.bestLat ?: return@forEach+ val lon = t.bestLon ?: return@forEach+ towers.add(Marker(m).apply {+ position = GeoPoint(lat, lon)+ icon = towerIcon+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)+ setInfoWindow(null)+ })}- devices.add(Marker(m).apply {- position = GeoPoint(lat, lon)- icon = MapIcons.dot(dp, color, if (DeviceColors.isFlagged(s)) 18 else 11)- 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 * 1.6f, it)) } // car screens sit further away- AlprStore.cameras.asSequence()+ val inBox = AlprStore.cameras.asSequence().filter { it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast }.take(600)- .forEach { c ->+ .toList()+ // Rebuilt when the cameras in view change, not on every 2 s tick.+ val ignoredIds = inBox.filter { com.rfsentinel.app.alpr.IgnoredCameras.contains(carContext, it.osmId) }.map { it.osmId }.toSet()+ val cKey = listOf(inBox.size, inBox.firstOrNull()?.osmId, inBox.lastOrNull()?.osmId, ignoredIds)+ if (cKey != camerasKey) {+ camerasKey = cKey+ cameras.items.clear()+ inBox.forEach { c ->cameras.add(Marker(m).apply {position = GeoPoint(c.lat, c.lon)- icon = icons.getValue(c.type)+ // Silenced cameras stay on the map, faded (like on the phone).+ icon = (if (c.osmId in ignoredIds) fadedCameraIcons else cameraIcons)[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()}}+ } else if (camerasKey != null) {+ camerasKey = null+ cameras.items.clear()}m.invalidate()}+ 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/** Swaps in a new route line when the route changes (osmdroid lines are rebuilt, not edited). */diff --git a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt b/app/src/main/java/com/rfsentinel/app/car/CarUi.ktindex 4b14e25..e1cf612 100644--- a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt+++ b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt@@ -26,7 +26,6 @@ object CarUi {return b.build()}- /** Max rows the car allows in a list (typically 6 while driving). *//** Where the driver is: the scanner's latest fix, else the phone's last known position. */@android.annotation.SuppressLint("MissingPermission") // checked via Permissionsfun currentLocation(context: CarContext): android.location.Location? {@@ -53,6 +52,7 @@ object CarUi {}}+ /** Max rows the car allows in a list (typically 6 while driving). */fun listLimit(context: CarContext): Int = runCatching {context.getCarService(ConstraintManager::class.java).getContentLimit(ConstraintManager.CONTENT_LIMIT_TYPE_LIST)@@ -92,10 +92,53 @@ object CarUi {}}- fun signalLine(s: DeviceRegistry.Snapshot, now: Long = System.currentTimeMillis()): String {- val age = (now - s.lastSeen) / 1000- return "${s.rssi} dBm ${ProximityUtil.band(s.rssi)} · ${DeviceIntel.formatDistance(s.distanceM)} · " +- if (age < 2) "now" else "${age}s ago"+ /** Which radio heard it: an ESP32 board, a USB WiFi adapter, or the phone (Bluetooth / WiFi). */+ fun sourceTag(s: DeviceRegistry.Snapshot): String = when {+ com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac) -> "USB WiFi"+ com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) -> "ESP32"+ s.source == com.rfsentinel.app.detect.Advert.Source.WIFI -> "WiFi"+ else -> "Bluetooth"+ }++ /** Which radio heard it first (the line above can be cut off), then signal, distance and age. */+ fun signalLine(s: DeviceRegistry.Snapshot, now: Long = System.currentTimeMillis()): String =+ "${sourceTag(s)} · ${s.rssi} dBm ${ProximityUtil.band(s.rssi)} · ${DeviceIntel.formatDistance(s.distanceM)} · " + ageText(now - s.lastSeen)++ /** Coarse on purpose: a screen only refreshes when what it shows changes. */+ fun ageText(ms: Long): String = when {+ ms < 5_000 -> "now"+ ms < 60_000 -> "under a minute ago"+ ms < 3_600_000 -> "${ms / 60_000} min ago"+ else -> "${ms / 3_600_000} h ago"+ }++ /** What a device row shows, for a screen's refresh key (3 dB signal steps). */+ fun rowKey(s: DeviceRegistry.Snapshot, now: Long): String =+ "${s.mac}|${title(s)}|${tagLine(s)}|${sourceTag(s)}|${s.rssi / 3}|${ageText(now - s.lastSeen)}|${s.following}"++ /**+ * The next known camera on your way (see KnownCameras.ahead): needs a GPS heading+ * while moving; parked, the nearest within 1 km. Silenced cameras are left out.+ */+ fun nextCamera(context: CarContext): Pair<com.rfsentinel.app.alpr.KnownCamera, Double>? {+ val cams = com.rfsentinel.app.alpr.AlprStore.cameras+ if (cams.isEmpty()) return null+ val me = currentLocation(context) ?: return null+ val moving = me.hasBearing() && me.hasSpeed() && me.speed > 2f+ return com.rfsentinel.app.alpr.KnownCameras.ahead(+ cams, me.latitude, me.longitude, if (moving) me.bearing else null+ ) { com.rfsentinel.app.alpr.IgnoredCameras.contains(context, it.osmId) }+ }++ /** Alert sound state for the home screen and the More screen ("" when sound is on). */+ fun silencedText(context: CarContext, now: Long = System.currentTimeMillis()): String {+ val until = com.rfsentinel.app.util.Prefs.alertsSnoozedUntil(context)+ return when {+ com.rfsentinel.app.util.Prefs.alertsMuted(context) -> "Alert sound muted"+ now < until -> "Alerts snoozed until " ++ java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(until))+ else -> ""+ }}/** Headline for the home screen, mirroring the phone's threat banner. */diff --git a/app/src/main/java/com/rfsentinel/app/car/CellsScreen.kt b/app/src/main/java/com/rfsentinel/app/car/CellsScreen.ktnew file mode 100644index 0000000..fb38d75--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/car/CellsScreen.kt@@ -0,0 +1,124 @@+package com.rfsentinel.app.car++import androidx.car.app.CarContext+import androidx.car.app.model.Action+import androidx.car.app.model.CarColor+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 com.rfsentinel.app.R+import com.rfsentinel.app.detect.CellAnalyzer+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.service.CellMonitor+import com.rfsentinel.app.service.CellTowerStore+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.util.Prefs++/**+ * Cell towers in the car: the fake-cell (IMSI catcher) check status, the cell+ * serving the phone and its neighbours, live from the scanner's 15 s snapshot.+ * Read passively from what the modem reports; nothing is looked up online.+ */+class CellsScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_000L) {++ override fun contentKey(): Any = listOf(+ ScanForegroundService.isRunning, CellTowerStore.currentAt, recentWarning()?.second?.key,+ Prefs.categoryEnabled(carContext, Category.CELL_ANOMALY)+ )++ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun render(): Template {+ val items = ItemList.Builder()+ val running = ScanForegroundService.isRunning+ val checks = Prefs.categoryEnabled(carContext, Category.CELL_ANOMALY)++ // 1. Fake-cell check status.+ val warning = recentWarning()+ items.addItem(+ when {+ warning != null -> Row.Builder()+ .setTitle(warning.second.title)+ .addText(CarUi.ageText(System.currentTimeMillis() - warning.first) + " · " + warning.second.detail.take(90))+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, CarUi.DANGER_COLOR))+ .build()+ !checks -> Row.Builder()+ .setTitle("Fake cell tower checks are off")+ .addText("Turn on the category in Settings on your phone")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))+ .build()+ !running -> Row.Builder()+ .setTitle("Not scanning")+ .addText("Cells are checked every 15 s while scanning")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))+ .build()+ else -> Row.Builder()+ .setTitle("No fake-cell signs")+ .addText("Checked every 15 s - a hint, not proof")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower, CarUi.CLEAR_COLOR))+ .build()+ }+ )++ // 2. The serving cell, then the strongest neighbours.+ val cells = if (running) CellTowerStore.current else emptyList()+ cells.sortedWith(compareByDescending<CellAnalyzer.Cell> { it.registered }.thenByDescending { it.dbm ?: -999 })+ .take((CarUi.listLimit(carContext) - 1).coerceAtLeast(0))+ .forEach { c -> items.addItem(cellRow(c)) }++ return ListTemplate.Builder()+ .setTitle("Cell towers")+ .setHeaderAction(Action.BACK)+ .setSingleList(items.build())+ .build()+ }++ private fun cellRow(c: CellAnalyzer.Cell): Row {+ val row = Row.Builder()+ .setTitle(c.rat.label + if (c.registered) " · serving" else " · neighbour")+ .addText(listOfNotNull(+ c.operator,+ if (c.mcc != null || c.mnc != null) "${c.mcc ?: "?"}-${c.mnc ?: "?"}" else null,+ c.cellId?.let { "cell $it" } ?: c.pci?.let { "PCI $it" },+ c.dbm?.let { "$it dBm" }+ ).joinToString(" · ").ifEmpty { "No IDs reported" })+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower, if (c.registered) CarUi.CLEAR_COLOR else null))+ // A tower with an estimated spot (where its signal was strongest) opens on the map.+ if (c.cellId != null) {+ row.setOnClickListener {+ val t = CellTowerStore.all(carContext).firstOrNull { it.key == c.key }+ val lat = t?.bestLat+ val lon = t?.bestLon+ if (lat != null && lon != null) {+ screenManager.push(PlaceFocusScreen(carContext, "${t.ratLabel} cell ${t.cellId}",+ "Estimated: where its signal was strongest", lat, lon, CarColor.createCustom(TOWER_COLOR, TOWER_COLOR), "T"))+ } else {+ androidx.car.app.CarToast.makeText(carContext, "No position for this tower yet",+ androidx.car.app.CarToast.LENGTH_SHORT).show()+ }+ }+ }+ return row.build()+ }++ private fun recentWarning() = CellMonitor.lastAnomaly?.takeIf { System.currentTimeMillis() - it.first < WARNING_MS }++ companion object {+ /** A warning stays on top this long. */+ const val WARNING_MS = 15 * 60_000L+ const val TOWER_COLOR = 0xFF6A1B9A.toInt()++ /** One line for the home screen ("4G (LTE) · Network · -95 dBm · 4 neighbours"), null with no cells. */+ fun summary(now: Long = System.currentTimeMillis()): String? {+ CellMonitor.lastAnomaly?.takeIf { now - it.first < WARNING_MS }?.let { return "Warning: " + it.second.title }+ val cells = CellTowerStore.current+ if (cells.isEmpty()) return null+ val serving = cells.firstOrNull { it.registered }+ val neighbours = cells.count { !it.registered }+ return listOfNotNull(+ serving?.rat?.label, serving?.operator, serving?.dbm?.let { "$it dBm" },+ "$neighbours neighbour${if (neighbours == 1) "" else "s"}"+ ).joinToString(" · ")+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.ktindex 2d88820..601a974 100644--- a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt@@ -2,7 +2,6 @@ package com.rfsentinel.app.carimport androidx.car.app.CarContextimport androidx.car.app.CarToast-import androidx.car.app.Screenimport androidx.car.app.model.Actionimport androidx.car.app.model.ItemListimport androidx.car.app.model.Row@@ -23,7 +22,7 @@ import kotlinx.coroutines.withContext* 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) {+class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen) : SafeScreen(carContext) {private var results: List<OsmRouting.Destination>? = nullprivate var loading = false@@ -31,7 +30,7 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)/** What's typed so far (searched only when submitted or tapped - no search-as-you-type). */private var typed = ""- override fun onGetTemplate(): Template {+ override fun buildTemplate(): Template {val list = ItemList.Builder()val shown = results ?: Prefs.recentDestinations(carContext)val me = CarUi.currentLocation(carContext)diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.ktindex 3517ab4..5855dee 100644--- a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt@@ -1,7 +1,5 @@package com.rfsentinel.app.car-import android.content.Intent-import android.net.Uriimport androidx.car.app.CarContextimport androidx.car.app.CarToastimport androidx.car.app.model.Action@@ -14,10 +12,14 @@ import androidx.car.app.model.Rowimport androidx.car.app.model.Templateimport androidx.lifecycle.lifecycleScopeimport com.rfsentinel.app.R+import com.rfsentinel.app.data.AlertLogimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.Favorites+import com.rfsentinel.app.data.TrackerMutesimport com.rfsentinel.app.data.WhitelistCacheimport com.rfsentinel.app.data.WhitelistEntity+import com.rfsentinel.app.detect.AddressType+import com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.detect.DeviceIntelimport com.rfsentinel.app.oui.OuiEntryimport com.rfsentinel.app.oui.OuiWatchlist@@ -27,18 +29,25 @@ import kotlinx.coroutines.launchimport java.util.Locale/**- * One device on the car screen: why it's flagged, live signal, identity,- * and buttons (whitelist, watch, favorite, navigate to a drone).+ * One device on the car screen: why it's flagged, live signal, which radio heard+ * it, and buttons (whitelist / ignore a tracker, watch, favorite, navigate to a+ * drone). Once the device is out of range, its last alert is shown instead.*/class DeviceDetailScreen(carContext: CarContext, private val mac: String) : LiveScreen(carContext, 2_000L) {+ override fun contentKey(): Any {+ val now = System.currentTimeMillis()+ val s = DeviceRegistry.get(mac) ?: return listOf("gone", AlertLog.latestFor(carContext, mac)?.time,+ WhitelistCache.inTable(mac))+ return listOf(+ CarUi.rowKey(s, now), s.best?.evidence, s.bestRssi, trend(s), s.remoteId?.latitude, s.remoteId?.longitude,+ WhitelistCache.inTable(mac), TrackerMutes.isMuted(mac), OuiWatchlist.customEntry(mac) != null, Favorites.contains(mac)+ )+ }+@Suppress("DEPRECATION") // setTitle/setActionStrip keep compatibility with older Android Auto hosts- override fun onGetTemplate(): Template {- val s = DeviceRegistry.get(mac)- ?: return MessageTemplate.Builder("This device is no longer in range.")- .setTitle("Device details")- .setHeaderAction(Action.BACK)- .build()+ override fun render(): Template {+ val s = DeviceRegistry.get(mac) ?: return outOfRange()val best = s.bestval rows = mutableListOf<Row>()@@ -50,16 +59,8 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Liveif (best != null) {rows += Row.Builder().setTitle("Why").addText(best.evidence.take(120)).build()}- val trend = s.history.takeLast(6).dropLast(1).map { it.rssi }.average().let { avg ->- when {- avg.isNaN() -> ""- s.rssi > avg + 3 -> " · getting closer"- s.rssi < avg - 3 -> " · moving away"- else -> " · steady"- }- }rows += Row.Builder()- .setTitle("Signal ${s.rssi} dBm · ${ProximityUtil.band(s.rssi)}$trend")+ .setTitle("Signal ${s.rssi} dBm · ${ProximityUtil.band(s.rssi)}${trend(s)}").addText("${DeviceIntel.formatDistance(s.distanceM)} (rough) · best ${s.bestRssi} dBm").build()s.remoteId?.takeIf { it.hasPosition }?.let { r ->@@ -76,7 +77,7 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live}rows += Row.Builder().setTitle(s.vendor ?: s.deviceType)- .addText("$mac · ${s.addressType.label}")+ .addText("$mac · ${s.addressType.label} · heard by ${heardBy(s)}").build()val pane = Pane.Builder()@@ -84,20 +85,16 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live// Primary buttons (a pane allows two).val whitelisted = WhitelistCache.inTable(mac)- val ignored = com.rfsentinel.app.data.TrackerMutes.isMuted(mac)- val tracker = best?.category == com.rfsentinel.app.detect.Category.TRACKER &&- s.addressType != com.rfsentinel.app.detect.AddressType.PUBLIC+ val ignored = TrackerMutes.isMuted(mac)+ val tracker = best?.category == Category.TRACKER && s.addressType != AddressType.PUBLICpane.addAction(Action.Builder()- .setTitle(when { ignored -> "Stop ignoring"; whitelisted -> "Un-whitelist"; tracker -> "Ignore today"; else -> "Whitelist" })+ .setTitle(when { ignored -> "Stop ignoring"; whitelisted -> "Un-whitelist"; tracker -> "Ignore..."; else -> "Whitelist" }).setOnClickListener {when {- ignored -> com.rfsentinel.app.data.TrackerMutes.unmute(carContext, mac)- tracker && !whitelisted -> {- // Address changes daily: ignore until then (the phone offers "it's mine").- com.rfsentinel.app.data.TrackerMutes.mute(carContext, mac, best!!.label, s.rssi, follow = false)- toast("Ignored until its address changes (at most 24 h)")- }+ ignored -> { TrackerMutes.unmute(carContext, mac); toast("No longer ignored") }+ // Its address changes daily, so it can't be whitelisted: offer the phone's choices.+ tracker && !whitelisted -> screenManager.push(TrackerIgnoreScreen(carContext, mac))else -> toggleWhitelist(whitelisted, best?.label ?: s.name ?: "")}invalidate()@@ -149,6 +146,67 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live.build()}+ /** No longer heard: what its last alert said, with Whitelist and (when known) Navigate. */+ @Suppress("DEPRECATION")+ private fun outOfRange(): Template {+ val e = AlertLog.latestFor(carContext, mac)+ ?: return MessageTemplate.Builder("This device is no longer in range.")+ .setTitle("Device details")+ .setHeaderAction(Action.BACK)+ .build()+ val now = System.currentTimeMillis()+ val color = if (e.tierEnum == com.rfsentinel.app.detect.Tier.WEAK) CarUi.WEAK_COLOR+ else e.categoryEnum?.colorArgb ?: CarUi.DANGER_COLOR+ val pane = Pane.Builder()+ listOf(+ Row.Builder().setTitle((if (e.following) "FOLLOWING · " else "") + e.label)+ .addText("Out of range · last alert ${CarUi.ageText(now - e.time)}" + (e.rssi?.let { " · $it dBm" } ?: ""))+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color)).build(),+ Row.Builder().setTitle("Why").addText(e.evidence.take(120)).build(),+ Row.Builder().setTitle(mac).addText("${e.categoryEnum?.title ?: e.category} · ${e.confidence}%").build()+ ).take(CarUi.paneLimit(carContext)).forEach { pane.addRow(it) }++ val whitelisted = WhitelistCache.inTable(mac)+ pane.addAction(+ Action.Builder()+ .setTitle(if (whitelisted) "Un-whitelist" else "Whitelist")+ .setOnClickListener { toggleWhitelist(whitelisted, e.label) }+ .build()+ )+ val lat = e.lat+ val lon = e.lon+ if (lat != null && lon != null) {+ pane.addAction(+ Action.Builder()+ .setTitle("Navigate there")+ .setOnClickListener { CarUi.navigateTo(carContext, lat, lon) }+ .build()+ )+ }+ return PaneTemplate.Builder(pane.build())+ .setTitle("Device details")+ .setHeaderAction(Action.BACK)+ .build()+ }++ private fun trend(s: DeviceRegistry.Snapshot): String =+ s.history.takeLast(6).dropLast(1).map { it.rssi }.average().let { avg ->+ when {+ avg.isNaN() -> ""+ s.rssi > avg + 3 -> " · getting closer"+ s.rssi < avg - 3 -> " · moving away"+ else -> " · steady"+ }+ }++ private fun heardBy(s: DeviceRegistry.Snapshot): String = listOfNotNull(+ if (com.rfsentinel.app.esp.HeardBy.phone.recent(mac) || (!com.rfsentinel.app.esp.HeardBy.esp.recent(mac) &&+ !com.rfsentinel.app.esp.HeardBy.usb.recent(mac)))+ "phone " + if (s.source == com.rfsentinel.app.detect.Advert.Source.WIFI) "WiFi" else "Bluetooth" else null,+ if (com.rfsentinel.app.esp.HeardBy.esp.recent(mac)) "ESP32" else null,+ if (com.rfsentinel.app.esp.HeardBy.usb.recent(mac)) "USB WiFi" else null+ ).joinToString(" + ")+private fun toggleWhitelist(whitelisted: Boolean, label: String) {lifecycleScope.launch {val dao = AppDatabase.getInstance(carContext).whitelistDao()@@ -171,6 +229,5 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Liveinvalidate()}- /** Hands the point to the car's navigation app. */private fun toast(msg: String) = CarToast.makeText(carContext, msg, CarToast.LENGTH_SHORT).show()}diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.ktindex 6595fb5..ae48801 100644--- a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt@@ -7,35 +7,33 @@ import androidx.car.app.model.ListTemplateimport androidx.car.app.model.Rowimport androidx.car.app.model.Templateimport com.rfsentinel.app.R-import com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.service.DeviceRegistryimport com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.ui.DeviceFilter-/** A driver-safe list of nearby devices. Tapping a row opens its details. */-class DeviceListScreen(carContext: CarContext, private val filter: Filter) : LiveScreen(carContext) {+/**+ * A driver-safe list of nearby devices, filtered like the phone's chips+ * (Flagged, Trackers, Drones, Favorites, New, Bluetooth, WiFi, ESP32).+ * Tapping a row opens its details.+ */+class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter) : LiveScreen(carContext) {- enum class Filter(val title: String) {- FLAGGED("Flagged nearby"),- DRONES_TRACKERS("Drones & trackers"),- ALL("All nearby")+ private fun matching(now: Long): List<DeviceRegistry.Snapshot> {+ val all = if (ScanForegroundService.isRunning) DeviceRegistry.snapshot(now) else emptyList()+ return CarUi.sorted(all.filter { filter.matches(it) }).take(CarUi.listLimit(carContext))}- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts- override fun onGetTemplate(): Template {+ override fun contentKey(): Any {val now = System.currentTimeMillis()- val all = if (ScanForegroundService.isRunning) DeviceRegistry.snapshot(now) else emptyList()- val matching = CarUi.sorted(all.filter { s ->- when (filter) {- Filter.FLAGGED -> CarUi.isFlagged(s)- Filter.DRONES_TRACKERS -> s.remoteId != null ||- s.hits.any { it.category == Category.DRONE || it.category == Category.TRACKER }- Filter.ALL -> true- }- })+ return listOf(ScanForegroundService.isRunning) + matching(now).map { CarUi.rowKey(it, now) }+ }+ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun render(): Template {+ val now = System.currentTimeMillis()val items = ItemList.Builder()- // The car caps list length while driving; show the most important first.- matching.take(CarUi.listLimit(carContext)).forEach { s ->+ // The car caps list length while driving; the most important come first.+ matching(now).forEach { s ->items.addItem(Row.Builder().setTitle(CarUi.title(s))@@ -52,21 +50,38 @@ class DeviceListScreen(carContext: CarContext, private val filter: Filter) : Liv.build())}- items.setNoItemsMessage(- when {- !ScanForegroundService.isRunning -> "Not scanning - go back and tap Start"- filter == Filter.FLAGGED -> "Nothing flagged nearby"- filter == Filter.DRONES_TRACKERS -> "No drones or trackers nearby"- else -> "Listening... no devices heard yet"- }- )+ items.setNoItemsMessage(emptyMessage(filter))// Title stays constant: Android Auto only treats a same-title template as a// refresh rather than a new step (steps are capped for driver safety).return ListTemplate.Builder()- .setTitle(filter.title)+ .setTitle(titleOf(filter)).setHeaderAction(Action.BACK).setSingleList(items.build()).build()}++ companion object {+ /** The filters offered in the car (cell towers have their own screen). */+ val CAR_FILTERS = DeviceFilter.entries.filter { it != DeviceFilter.CELLS }++ fun titleOf(f: DeviceFilter) = when (f) {+ DeviceFilter.ALL -> "All nearby"+ DeviceFilter.FLAGGED -> "Flagged nearby"+ DeviceFilter.NEW -> "New devices"+ DeviceFilter.ESP32 -> "Heard by ESP32 / USB"+ else -> f.label+ }++ fun emptyMessage(f: DeviceFilter) = when {+ !ScanForegroundService.isRunning -> "Not scanning - go back and tap Start"+ f == DeviceFilter.FLAGGED -> "Nothing flagged nearby"+ f == DeviceFilter.TRACKERS -> "No trackers nearby"+ f == DeviceFilter.DRONES -> "No drones nearby"+ f == DeviceFilter.FAVORITES -> "No favorites nearby"+ f == DeviceFilter.ESP32 -> "Nothing from an ESP32 board or USB adapter - see More > Hardware"+ f == DeviceFilter.ALL -> "Listening... no devices heard yet"+ else -> "Nothing here right now"+ }+ }}diff --git a/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.ktindex 6018baa..315141e 100644--- a/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt@@ -37,7 +37,14 @@ class DevicesMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMsval flagged: Boolean, val color: Int, val tag: String?)- override fun onGetTemplate(): Template {+ override fun contentKey(): Any {+ val me = CarUi.currentLocation(carContext) ?: return listOf(ScanForegroundService.isRunning, "no fix")+ return listOf(ScanForegroundService.isRunning) ++ around(me.latitude, me.longitude, CarUi.listLimit(carContext).coerceAtMost(6))+ .map { "${it.mac}|${it.title}|${it.detail}|${(it.distanceM / 10).toInt()}|${it.color}" }+ }++ override fun render(): Template {val me = CarUi.currentLocation(carContext)val limit = CarUi.listLimit(carContext).coerceAtMost(6)val items = if (me == null) emptyList() else around(me.latitude, me.longitude, limit)diff --git a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.ktnew file mode 100644index 0000000..b6bc268--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt@@ -0,0 +1,63 @@+package com.rfsentinel.app.car++import androidx.car.app.CarContext+import androidx.car.app.model.Action+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 com.rfsentinel.app.R+import com.rfsentinel.app.esp.EspBoards+import com.rfsentinel.app.esp.OuiSpyBle+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.usb.UsbWifi+import com.rfsentinel.app.util.Prefs++/**+ * What is listening: the phone's own scanners (and the watchdog that restarts a+ * stalled one), ESP32 boards on USB (OUI-Spy, GhostESP, Marauder, through a+ * Flipper Zero), an OUI-SPY board over Bluetooth and a USB WiFi adapter.+ * Read-only: pairing and settings stay on the phone.+ */+class HardwareScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 3_000L) {++ private fun lines(): List<Triple<String, String, Int>> {+ val running = ScanForegroundService.isRunning+ val now = System.currentTimeMillis()+ val watchdog = ScanForegroundService.lastWatchdogRestart+ val phone = when {+ !running -> "Not scanning"+ watchdog != null && now - watchdog.first < 30 * 60_000L ->+ "Working · ${watchdog.second} scan restarted ${CarUi.ageText(now - watchdog.first)} (it had stalled)"+ else -> "Working · Bluetooth and WiFi"+ }+ val board = Prefs.ouiSpyBoard(carContext)+ return listOf(+ Triple("Phone radios", phone, R.drawable.ic_tile_scan),+ Triple("ESP32 on USB", EspBoards.status.ifBlank {+ if (running) "None connected - OUI-Spy, GhostESP or Marauder on an OTG cable" else "Connects while scanning"+ }, R.drawable.ic_car_usb),+ Triple("OUI-SPY over Bluetooth",+ if (board == null) "Not paired (pair it in Settings on the phone)"+ else "$board · " + OuiSpyBle.status.ifBlank { "connects while scanning" }, R.drawable.ic_car_usb),+ Triple("USB WiFi adapter", UsbWifi.status.ifBlank {+ if (running) "None connected (RTL8811AU / 8821AU, e.g. ALFA AWUS036ACS)" else "Connects while scanning"+ }, R.drawable.ic_car_usb)+ )+ }++ override fun contentKey(): Any = lines()++ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun render(): Template {+ val items = ItemList.Builder()+ lines().take(CarUi.listLimit(carContext)).forEach { (title, text, icon) ->+ items.addItem(Row.Builder().setTitle(title).addText(text.take(120)).setImage(CarUi.icon(carContext, icon)).build())+ }+ return ListTemplate.Builder()+ .setTitle("Hardware")+ .setHeaderAction(Action.BACK)+ .setSingleList(items.build())+ .build()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.ktindex f16979b..84e902c 100644--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt@@ -9,92 +9,153 @@ import androidx.car.app.model.ListTemplateimport androidx.car.app.model.Rowimport androidx.car.app.model.Templateimport com.rfsentinel.app.R-import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.alpr.KnownCamera+import com.rfsentinel.app.data.AlertLogimport com.rfsentinel.app.service.DeviceRegistryimport com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.ui.DeviceFilterimport com.rfsentinel.app.util.Permissionsimport com.rfsentinel.app.util.Prefs/**- * Android Auto home: threat headline, live status, Start/Stop button, and- * navigation rows into the device lists.+ * Android Auto home. Rows in order of importance, because a car shows only a+ * few while driving (usually 6): the threat headline (opens the flagged list),+ * the next known camera on your way, recent alerts, the map, every device+ * nearby (with the phone's filters) and More (snooze, voice, cell towers,+ * hardware). Start / Stop and the mute button sit in the header.*/class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {- @Suppress("DEPRECATION") // setTitle/setActionStrip keep compatibility with older Android Auto hosts- override fun onGetTemplate(): Template {+ private class Model(+ val running: Boolean,+ val devices: Int,+ val flagged: Int,+ val headline: Pair<Int, String>?,+ val camera: Pair<KnownCamera, Double>?,+ val alerts: Int,+ val newestAlert: AlertLog.Entry?,+ val silenced: String,+ val liveMap: Boolean,+ val cellSummary: String?+ )++ private fun model(): Model {val running = ScanForegroundService.isRunningval devices = if (running) DeviceRegistry.snapshot() else emptyList()- val flagged = devices.count { CarUi.isFlagged(it) }- val dronesTrackers = devices.count { s ->- s.remoteId != null || s.hits.any { it.category == Category.DRONE || it.category == Category.TRACKER }- }+ val alerts = AlertLog.recent(carContext)+ return Model(+ running = running,+ devices = devices.size,+ flagged = devices.count { CarUi.isFlagged(it) },+ headline = if (running) CarUi.threat(devices, Prefs.alertThreshold(carContext)) else null,+ camera = CarUi.nextCamera(carContext),+ alerts = alerts.size,+ newestAlert = alerts.firstOrNull(),+ silenced = CarUi.silencedText(carContext),+ liveMap = liveMapAvailable(carContext),+ cellSummary = if (running) CellsScreen.summary() else null+ )+ }- val items = ItemList.Builder()+ override fun contentKey(): Any {+ val m = model()+ val now = System.currentTimeMillis()+ return listOf(+ m.running, m.devices, m.flagged, m.headline, m.camera?.first?.osmId, m.camera?.second?.let { (it / 50).toInt() },+ m.alerts, m.newestAlert?.time, m.newestAlert?.let { CarUi.ageText(now - it.time) }, m.silenced, m.liveMap,+ m.cellSummary, Prefs.alertsMuted(carContext)+ )+ }++ @Suppress("DEPRECATION") // setTitle/setActionStrip keep compatibility with older Android Auto hosts+ override fun render(): Template {+ val m = model()+ val now = System.currentTimeMillis()+ val rows = ArrayList<Row>()- // 1. Headline- if (running) {- val (color, text) = CarUi.threat(devices, Prefs.alertThreshold(carContext))- items.addItem(- Row.Builder()- .setTitle(text)- .addText("Scanning · ${devices.size} nearby · $flagged flagged")- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color))- .build()- )+ // 1. Headline: the threat level; tap for the flagged devices.+ rows += if (m.running) {+ val (color, text) = m.headline!!+ Row.Builder()+ .setTitle(text)+ .addText(listOf("Scanning · ${m.devices} nearby · ${m.flagged} flagged", m.silenced)+ .filter { it.isNotEmpty() }.joinToString(" · "))+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(DeviceListScreen(carContext, DeviceFilter.FLAGGED)) }+ .build()} else {- items.addItem(- Row.Builder()- .setTitle("Not scanning")- .addText("Tap Start to listen for nearby equipment")- .setImage(CarUi.icon(carContext, R.drawable.ic_tile_scan))- .build()- )+ Row.Builder()+ .setTitle("Not scanning")+ .addText("Tap Start to listen for nearby equipment")+ .setImage(CarUi.icon(carContext, R.drawable.ic_tile_scan))+ .build()}- // 2-4. Navigation into the lists- 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))- // Our own map needs Car API 7 and the surface permission (not every build declares it).- val liveMap = runCatching {- carContext.carAppApiLevel >= androidx.car.app.versioning.CarAppApiLevels.LEVEL_7 &&- carContext.checkSelfPermission("androidx.car.app.ACCESS_SURFACE") ==- android.content.pm.PackageManager.PERMISSION_GRANTED- }.getOrDefault(false)- items.addItem(- Row.Builder()- .setTitle(if (liveMap) "Live map & navigation" else "Map: devices & cameras around me")- .setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))+ // 2. The next known camera on your way (works without scanning too).+ m.camera?.let { (cam, d) ->+ rows += Row.Builder()+ .setTitle("${cam.label} ahead")+ .addText(NearbyMapScreen.distanceText(d) + (cam.operator?.let { " · $it" } ?: ""))+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, NearbyMapScreen.cameraColor(cam.type))).setBrowsable(true)- .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))- }+ .setOnClickListener { screenManager.push(PlaceFocusScreen.forCamera(carContext, cam)) }.build()- )+ }- // 5. Spoken announcements in the car (alongside the alert tone)- val voice = Prefs.carVoice(carContext)- val muted = Prefs.alertsMuted(carContext)- items.addItem(- Row.Builder()- .setTitle("Spoken alerts in car: ${if (voice) "On" else "Off"}")- .addText(- when {- muted -> "All alert sound is muted - tap the speaker button to unmute"- voice -> "Says e.g. \"Axon body camera nearby\" - tap to turn off"- else -> "Tone only - tap to hear what was detected"- }- )- .setImage(CarUi.icon(carContext, if (voice && !muted) R.drawable.ic_car_voice else R.drawable.ic_car_voice_off))- .setOnClickListener {- Prefs.setCarVoice(carContext, !voice)- invalidate()- }+ // 3. Recent alerts (still there after the device has left).+ rows += Row.Builder()+ .setTitle("Recent alerts (${m.alerts})")+ .addText(m.newestAlert?.let { "${it.label} · ${CarUi.ageText(now - it.time)}" } ?: "None yet")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_history))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(RecentAlertsScreen(carContext)) }+ .build()++ // 4. Map: our own pannable map when the car allows it, else the car-drawn one.+ rows += Row.Builder()+ .setTitle(if (m.liveMap) "Live map & navigation" else "Map: devices & cameras around me")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))+ .setBrowsable(true)+ .setOnClickListener {+ screenManager.push(if (m.liveMap) LiveMapScreen(carContext) else DevicesMapScreen(carContext))+ }+ .build()++ // 5. Everything nearby, filtered like the phone's chips.+ rows += Row.Builder()+ .setTitle("Nearby devices (${m.devices})")+ .addText("Flagged, trackers, drones, favorites, new, ESP32...")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_drone))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(NearbyDevicesScreen(carContext)) }+ .build()++ // 6. Cell towers when there is room (no camera row), then More.+ if (m.camera == null && m.cellSummary != null) {+ rows += Row.Builder()+ .setTitle("Cell towers")+ .addText(m.cellSummary)+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(CellsScreen(carContext)) }.build()- )+ }+ rows += Row.Builder()+ .setTitle("More")+ .addText("Snooze alerts, voice, cell towers, hardware")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_more))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(MoreScreen(carContext)) }+ .build()++ // The car shows only its row limit while driving: More must stay reachable.+ val limit = CarUi.listLimit(carContext)+ val shown = if (rows.size <= limit) rows else rows.take(limit - 1) + rows.last()+ val items = ItemList.Builder()+ shown.forEach { items.addItem(it) }+ val running = m.runningval startStop = Action.Builder().setTitle(if (running) "Stop" else "Start").setIcon(CarUi.icon(carContext, if (running) R.drawable.ic_car_stop else R.drawable.ic_car_play))@@ -103,12 +164,15 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {// Master mute: alert tone + voice (plays through the car speakers otherwise).// Icon-only: Android Auto allows a single titled button in this strip.+ val muted = Prefs.alertsMuted(carContext)val muteButton = Action.Builder().setIcon(CarUi.icon(carContext, if (muted) R.drawable.ic_car_volume_off else R.drawable.ic_car_volume)).setOnClickListener {val nowMuted = !Prefs.alertsMuted(carContext)if (nowMuted) com.rfsentinel.app.util.Voice.silence()Prefs.setAlertsMuted(carContext, nowMuted)+ // Unmuting also ends a snooze: the driver wants sound back now.+ if (!nowMuted) Prefs.setAlertsSnoozedUntil(carContext, 0L)toast(if (nowMuted) "Alert sound muted" else "Alert sound on - plays through the car speakers")invalidate()}@@ -122,14 +186,6 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {.build()}- private fun navRow(title: String, count: Int, icon: Int, filter: DeviceListScreen.Filter) =- Row.Builder()- .setTitle("$title ($count)")- .setImage(CarUi.icon(carContext, icon))- .setBrowsable(true)- .setOnClickListener { screenManager.push(DeviceListScreen(carContext, filter)) }- .build()-private fun start() {val missing = Permissions.missingRequired(carContext)if (missing.isNotEmpty()) {@@ -160,4 +216,13 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {}private fun toast(msg: String) = CarToast.makeText(carContext, msg, CarToast.LENGTH_LONG).show()++ companion object {+ /** Our own pannable map needs car API 7 and the surface permission (not every build declares it). */+ fun liveMapAvailable(carContext: CarContext): Boolean = runCatching {+ carContext.carAppApiLevel >= androidx.car.app.versioning.CarAppApiLevels.LEVEL_7 &&+ carContext.checkSelfPermission("androidx.car.app.ACCESS_SURFACE") ==+ android.content.pm.PackageManager.PERMISSION_GRANTED+ }.getOrDefault(false)+ }}diff --git a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.ktindex 0d533b9..13feae4 100644--- a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt@@ -50,7 +50,14 @@ class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =invalidate()}- override fun onGetTemplate(): Template {+ 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() })+ else listOf(ScanForegroundService.isRunning, renderer.counts(), renderer.following)+ }++ override fun render(): Template {val list = ItemList.Builder()if (Navigator.active) guidanceRows(list) else summaryRows(list)diff --git a/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt b/app/src/main/java/com/rfsentinel/app/car/LiveScreen.ktindex 97982c0..f3b2f87 100644--- a/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt@@ -1,7 +1,11 @@package com.rfsentinel.app.car+import android.util.Logimport androidx.car.app.CarContextimport androidx.car.app.Screen+import androidx.car.app.model.Action+import androidx.car.app.model.MessageTemplate+import androidx.car.app.model.Templateimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycle@@ -9,16 +13,68 @@ import kotlinx.coroutines.delayimport kotlinx.coroutines.launch/**- * A car screen that re-renders on a timer while visible. Android Auto treats a- * refresh of the same template type and title as an update, not a new step, so- * this doesn't use up the driver's navigation-depth budget.+ * A car screen that never takes the car app down: if building its template+ * fails (bad data, a template limit the car enforces), it shows a short message+ * with Back instead, and the error is logged.+ */+abstract class SafeScreen(carContext: CarContext) : Screen(carContext) {++ /** Builds this screen's template (may throw; [onGetTemplate] catches it). */+ protected abstract fun buildTemplate(): Template++ final override fun onGetTemplate(): Template = try {+ buildTemplate()+ } catch (e: Exception) {+ Log.w("CarScreen", "${javaClass.simpleName} failed to render", e)+ lastError = "${javaClass.simpleName}: ${e.javaClass.simpleName}"+ MessageTemplate.Builder("Something went wrong showing this screen. Go back and try again.")+ .setTitle("RF Sentinel")+ .setHeaderAction(Action.BACK)+ .build()+ }++ companion object {+ /** Last screen error, for tests and troubleshooting. */+ @Volatile var lastError: String? = null+ }+}++/**+ * A car screen that keeps itself current while visible. Every [periodMs] it+ * asks [contentKey] what it would show; only when that changed does it re-render+ * (Android Auto throttles apps that refresh too often, and redrawing an+ * unchanged map makes some cars flicker). A refresh of the same template type+ * and title doesn't count as a new step against the driver's screen budget.*/abstract class LiveScreen(carContext: CarContext,private val periodMs: Long = 3_000L,/** Map screens: precise GPS while shown, so devices are placed where they were heard. */preciseLocation: Boolean = false-) : Screen(carContext) {+) : SafeScreen(carContext) {++ /**+ * A cheap summary of what this screen shows (counts, rounded distances...);+ * equal keys mean nothing visible changed. Null: refresh every period.+ */+ protected open fun contentKey(): Any? = null++ private var shownKey: Any? = null++ /** Builds the template and remembers the content it was built from. */+ protected abstract fun render(): Template++ final override fun buildTemplate(): Template {+ shownKey = runCatching { contentKey() }.getOrNull()+ return render()+ }++ /** True when the content changed since the last render (always true without a key). */+ internal fun needsRefresh(): Boolean {+ val key = runCatching { contentKey() }.getOrNull() ?: return true+ return key != shownKey+ }+init {if (preciseLocation) lifecycle.addObserver(object : androidx.lifecycle.DefaultLifecycleObserver {override fun onStart(owner: androidx.lifecycle.LifecycleOwner) =@@ -30,7 +86,7 @@ abstract class LiveScreen(repeatOnLifecycle(Lifecycle.State.STARTED) {while (true) {delay(periodMs)- invalidate()+ if (needsRefresh()) invalidate()}}}diff --git a/app/src/main/java/com/rfsentinel/app/car/MoreScreen.kt b/app/src/main/java/com/rfsentinel/app/car/MoreScreen.ktnew file mode 100644index 0000000..a83bbb8--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/car/MoreScreen.kt@@ -0,0 +1,105 @@+package com.rfsentinel.app.car++import androidx.car.app.CarContext+import androidx.car.app.CarToast+import androidx.car.app.model.Action+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 com.rfsentinel.app.R+import com.rfsentinel.app.receiver.AlertActionReceiver+import com.rfsentinel.app.util.Prefs++/**+ * Quick settings and status for the car: snooze alerts for 30 minutes, the+ * spoken-alert options, cell towers, the connected hardware and whether+ * AirTags count as trackers. Everything else stays in the phone's Settings.+ */+class MoreScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_000L) {++ override fun contentKey(): Any = listOf(+ CarUi.silencedText(carContext), Prefs.carVoice(carContext), Prefs.shortVoice(carContext),+ Prefs.excludeAirTags(carContext), CellsScreen.summary()+ )++ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun render(): Template {+ val now = System.currentTimeMillis()+ val snoozed = now < Prefs.alertsSnoozedUntil(carContext)+ val voice = Prefs.carVoice(carContext)+ val short = Prefs.shortVoice(carContext)+ val noAirTags = Prefs.excludeAirTags(carContext)+ val items = ItemList.Builder()++ items.addItem(Row.Builder()+ .setTitle(if (snoozed) "Resume alert sound" else "Snooze alerts 30 min")+ .addText(if (snoozed) CarUi.silencedText(carContext) else "No alert sound or voice for half an hour")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_snooze))+ .setOnClickListener {+ if (snoozed) {+ Prefs.setAlertsSnoozedUntil(carContext, 0L)+ toast("Alert sound back on")+ } else {+ AlertActionReceiver.snooze(carContext)+ toast("Alerts snoozed for 30 minutes")+ }+ invalidate()+ }+ .build())++ items.addItem(Row.Builder()+ .setTitle("Spoken alerts in car: ${if (voice) "On" else "Off"}")+ .addText(if (voice) "Says what was detected - tap to turn off" else "Tone only - tap to hear what was detected")+ .setImage(CarUi.icon(carContext, if (voice) R.drawable.ic_car_voice else R.drawable.ic_car_voice_off))+ .setOnClickListener { Prefs.setCarVoice(carContext, !voice); invalidate() }+ .build())++ items.addItem(Row.Builder()+ .setTitle("Short spoken alerts: ${if (short) "On" else "Off"}")+ .addText(if (short) "\"Body cam\", \"Police car\", \"Speed camera, 50\"" else "Full labels, e.g. \"Axon body camera nearby\"")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_voice))+ .setOnClickListener {+ Prefs.setShortVoice(carContext, !short)+ com.rfsentinel.app.util.AlertPlayer.testVoice(carContext, !short)+ invalidate()+ }+ .build())++ items.addItem(Row.Builder()+ .setTitle("Cell towers")+ .addText(CellsScreen.summary() ?: "Serving cell, neighbours and fake-cell checks")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(CellsScreen(carContext)) }+ .build())++ items.addItem(Row.Builder()+ .setTitle("Hardware")+ .addText("ESP32, Marauder, OUI-SPY, USB WiFi adapter")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_usb))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(HardwareScreen(carContext)) }+ .build())++ items.addItem(Row.Builder()+ .setTitle("AirTags count as trackers: ${if (noAirTags) "No" else "Yes"}")+ .addText(if (noAirTags) "Apple Find My tags are left out - tap to include" else "Tap to leave Apple Find My tags out")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_drone))+ .setOnClickListener { Prefs.setExcludeAirTags(carContext, !noAirTags); invalidate() }+ .build())++ val list = ItemList.Builder()+ // Keep the car's row limit (the order above is by importance).+ val built = items.build().items.take(CarUi.listLimit(carContext))+ built.forEach { list.addItem(it) }++ return ListTemplate.Builder()+ .setTitle("More")+ .setHeaderAction(Action.BACK)+ .setSingleList(list.build())+ .build()+ }++ private fun toast(msg: String) = CarToast.makeText(carContext, msg, CarToast.LENGTH_SHORT).show()+}diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.ktnew file mode 100644index 0000000..2d2feb4--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt@@ -0,0 +1,54 @@+package com.rfsentinel.app.car++import androidx.car.app.CarContext+import androidx.car.app.model.Action+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 com.rfsentinel.app.R+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.ui.DeviceFilter++/**+ * The phone's filter chips as car rows, with live counts: pick one to list+ * those devices. The most useful filters come first (the car may show only six).+ */+class NearbyDevicesScreen(carContext: CarContext) : LiveScreen(carContext) {++ private fun counts(): List<Pair<DeviceFilter, Int>> {+ val all = if (ScanForegroundService.isRunning) DeviceRegistry.snapshot() else emptyList()+ return DeviceListScreen.CAR_FILTERS.map { f -> f to all.count { f.matches(it) } }+ }++ override fun contentKey(): Any = listOf(ScanForegroundService.isRunning, counts())++ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun render(): Template {+ val items = ItemList.Builder()+ counts().take(CarUi.listLimit(carContext)).forEach { (f, n) ->+ items.addItem(+ Row.Builder()+ .setTitle("${DeviceListScreen.titleOf(f)} ($n)")+ .setImage(CarUi.icon(carContext, iconOf(f)))+ .setBrowsable(true)+ .setOnClickListener { screenManager.push(DeviceListScreen(carContext, f)) }+ .build()+ )+ }+ return ListTemplate.Builder()+ .setTitle("Nearby devices")+ .setHeaderAction(Action.BACK)+ .setSingleList(items.build())+ .build()+ }++ private fun iconOf(f: DeviceFilter) = when (f) {+ DeviceFilter.FLAGGED -> R.drawable.ic_car_warning+ DeviceFilter.TRACKERS, DeviceFilter.DRONES -> R.drawable.ic_car_drone+ DeviceFilter.FAVORITES -> R.drawable.ic_car_star+ DeviceFilter.ESP32 -> R.drawable.ic_car_usb+ else -> R.drawable.ic_car_list+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.ktindex 4c148d9..c1f1de3 100644--- a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt@@ -38,10 +38,20 @@ class NearbyMapScreen(/** One row: a camera or a drone. */data class Item(val title: String, val detail: String, val lat: Double, val lon: Double, val distanceM: Double,val drone: Boolean, val mac: String?, val kind: com.rfsentinel.app.alpr.KnownCamera.Kind? = null,+ /** The known camera this row shows (opens its own view with the ignore toggle). */+ val camera: com.rfsentinel.app.alpr.KnownCamera? = null,/** Flagged device: its list / radar colour (category, or amber when weak). */val deviceColor: Int? = null)- override fun onGetTemplate(): Template {+ override fun contentKey(): Any {+ val me = CarUi.currentLocation(carContext) ?: return "no fix"+ val items = nearby(me.latitude, me.longitude, CarUi.listLimit(carContext).coerceAtMost(6))+ return listOf(AlprStore.cameras.size) + items.map {+ "${it.title}|${(it.distanceM / 10).toInt()}|${it.camera?.let { c -> com.rfsentinel.app.alpr.IgnoredCameras.contains(carContext, c.osmId) }}"+ }+ }++ override fun render(): Template {val me = CarUi.currentLocation(carContext)if (me != null) autoDownloadAround(me)val limit = CarUi.listLimit(carContext).coerceAtMost(6)@@ -76,24 +86,21 @@ class NearbyMapScreen(}private fun row(it: Item): Row {+ val ignored = it.camera != null && com.rfsentinel.app.alpr.IgnoredCameras.contains(carContext, it.camera.osmId)val color = when {it.drone -> CarColor.BLUEit.deviceColor != null -> CarColor.createCustom(it.deviceColor, it.deviceColor)- it.kind == com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> CarColor.RED+ ignored -> CarColor.createCustom(0xFF9E9E9E.toInt(), 0xFF9E9E9E.toInt())+ it.kind != null -> cameraColor(it.kind).let { c -> CarColor.createCustom(c, c) }else -> CarColor.YELLOW}- val label = when (it.kind) {- null -> if (it.drone) "D" else "!"- com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "S"- com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> "R"- com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "P"- }+ val label = it.kind?.let { k -> cameraLabel(k) } ?: if (it.drone) "D" else "!"val place = Place.Builder(CarLocation.create(it.lat, it.lon)).setMarker(PlaceMarker.Builder().setColor(color).setLabel(label).build()).build()// Android Auto requires every place row on a map template to carry its distance// as a DistanceSpan (the host formats it in the driver's units); plain text throws.- val text = android.text.SpannableString(" · " + it.detail)+ val text = android.text.SpannableString(" · " + it.detail + if (ignored) " · alerts off" else "")text.setSpan(androidx.car.app.model.DistanceSpan.create(distanceOf(it.distanceM)), 0, 1,android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE)return Row.Builder()@@ -102,6 +109,7 @@ class NearbyMapScreen(.setMetadata(Metadata.Builder().setPlace(place).build()).setOnClickListener {if (it.mac != null) screenManager.push(DeviceDetailScreen(carContext, it.mac))+ else if (it.camera != null) screenManager.push(PlaceFocusScreen.forCamera(carContext, it.camera))else screenManager.push(PlaceFocusScreen(carContext, it.title, it.detail, it.lat, it.lon, color, label))}.build()@@ -127,7 +135,7 @@ class NearbyMapScreen(fun nearby(lat: Double, lon: Double, limit: Int): List<Item> {val cams = KnownCameras.near(AlprStore.cameras, lat, lon, SEARCH_RADIUS_M).map { (c, d) ->Item(c.label, c.operator ?: (c.direction?.let { "faces $it°" } ?: "mapped in OpenStreetMap"),- c.lat, c.lon, d, drone = false, mac = null, kind = c.type)+ c.lat, c.lon, d, drone = false, mac = null, kind = c.type, camera = c)}val drones = DeviceRegistry.snapshot().mapNotNull { s ->val r = s.remoteId ?: return@mapNotNull null@@ -153,6 +161,16 @@ class NearbyMapScreen(return (drones.sortedBy { it.distanceM } + devices.sortedBy { it.distanceM } + cams).take(limit)}+ /** Marker colour of a camera kind: the same as the phone map's camera icons. */+ fun cameraColor(kind: com.rfsentinel.app.alpr.KnownCamera.Kind): Int = com.rfsentinel.app.ui.MapIcons.cameraColor(kind)++ /** Marker letter: P(late reader), S(peed), R(ed light). */+ fun cameraLabel(kind: com.rfsentinel.app.alpr.KnownCamera.Kind) = when (kind) {+ com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "S"+ com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> "R"+ com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "P"+ }+/** Metres below 1 km (rounded to 10 m), else kilometres with one decimal. */fun distanceOf(m: Double): androidx.car.app.model.Distance =if (m < 1000) androidx.car.app.model.Distance.create(((m / 10).roundToInt() * 10).toDouble(), androidx.car.app.model.Distance.UNIT_METERS)diff --git a/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt b/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.ktindex dd5c3b6..2e290ce 100644--- a/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt@@ -3,6 +3,7 @@ package com.rfsentinel.app.carimport android.text.SpannableStringimport android.text.Spannedimport androidx.car.app.CarContext+import androidx.car.app.CarToastimport androidx.car.app.model.Actionimport androidx.car.app.model.ActionStripimport androidx.car.app.model.CarColor@@ -16,12 +17,15 @@ import androidx.car.app.model.PlaceMarkerimport androidx.car.app.model.Rowimport androidx.car.app.model.Templateimport com.rfsentinel.app.R+import com.rfsentinel.app.alpr.IgnoredCameras+import com.rfsentinel.app.alpr.KnownCameraimport com.rfsentinel.app.service.DeviceRegistry/**- * One place on its own (e.g. a camera tapped in the list): the car map centres- * on it. Android Auto only lets navigation apps pan and zoom their map, so- * "Navigate" hands the spot to your navigation app, where you can move freely.+ * One place on its own (a camera, a tower, an alert): the car map centres on+ * it. Android Auto only lets navigation apps pan and zoom their map, so+ * "Navigate" hands the spot to your navigation app. For a known camera, tapping+ * its row turns its alerts off or back on (like "Ignore alerts" on the phone map).*/class PlaceFocusScreen(carContext: CarContext,@@ -30,22 +34,46 @@ class PlaceFocusScreen(private val lat: Double,private val lon: Double,private val color: CarColor,- private val label: String?+ private val label: String?,+ /** OpenStreetMap id of a known camera, for its ignore toggle. */+ private val cameraId: String? = null) : LiveScreen(carContext, periodMs = 5_000L) {- override fun onGetTemplate(): Template {+ override fun contentKey(): Any {val me = CarUi.currentLocation(carContext)- val marker = PlaceMarker.Builder().setColor(color)+ return listOf(+ me?.let { (DeviceRegistry.metersBetween(it.latitude, it.longitude, lat, lon) / 10).toInt() },+ cameraId?.let { IgnoredCameras.contains(carContext, it) }+ )+ }++ override fun render(): Template {+ val me = CarUi.currentLocation(carContext)+ val ignored = cameraId?.let { IgnoredCameras.contains(carContext, it) } ?: false+ val marker = PlaceMarker.Builder().setColor(if (ignored) IGNORED_COLOR else color)label?.let { marker.setLabel(it) }val place = Place.Builder(CarLocation.create(lat, lon)).setMarker(marker.build()).build()+ val shownDetail = when {+ cameraId == null -> detail+ ignored -> "Alerts off - tap to turn them back on"+ else -> "$detail · tap to ignore its alerts"+ }val row = Row.Builder().setTitle(title).setMetadata(Metadata.Builder().setPlace(place).build())if (me != null) {// Map rows carry their distance as a DistanceSpan (the car formats it).- val text = SpannableString(" · $detail")+ val text = SpannableString(" · $shownDetail")val d = DeviceRegistry.metersBetween(me.latitude, me.longitude, lat, lon)text.setSpan(DistanceSpan.create(NearbyMapScreen.distanceOf(d)), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)row.addText(text)+ if (cameraId != null) row.setOnClickListener {+ val nowIgnored = !IgnoredCameras.contains(carContext, cameraId)+ IgnoredCameras.set(carContext, cameraId, nowIgnored)+ CarToast.makeText(carContext,+ if (nowIgnored) "You won't be warned about this camera" else "Alerts for this camera are back on",+ CarToast.LENGTH_SHORT).show()+ invalidate()+ }} else {// No position yet, so no distance: Android Auto only accepts a map row// without a DistanceSpan when it's browsable - let it start navigation.@@ -71,4 +99,19 @@ class PlaceFocusScreen(.setItemList(ItemList.Builder().addItem(row.build()).build()).build()}++ companion object {+ /** A silenced camera's marker: grey, like the faded dot on the phone map. */+ private val IGNORED_COLOR = CarColor.createCustom(0xFF9E9E9E.toInt(), 0xFF9E9E9E.toInt())++ /** A known camera, with its alerts toggle. */+ fun forCamera(carContext: CarContext, cam: KnownCamera): PlaceFocusScreen {+ val c = NearbyMapScreen.cameraColor(cam.type)+ return PlaceFocusScreen(+ carContext, cam.label,+ cam.operator ?: (cam.direction?.let { "faces $it°" } ?: "mapped in OpenStreetMap"),+ cam.lat, cam.lon, CarColor.createCustom(c, c), NearbyMapScreen.cameraLabel(cam.type), cam.osmId+ )+ }+ }}diff --git a/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.kt b/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.ktnew file mode 100644index 0000000..8cf6eeb--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.kt@@ -0,0 +1,71 @@+package com.rfsentinel.app.car++import androidx.car.app.CarContext+import androidx.car.app.model.Action+import androidx.car.app.model.CarColor+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 com.rfsentinel.app.R+import com.rfsentinel.app.alpr.AlprStore+import com.rfsentinel.app.data.AlertLog+import com.rfsentinel.app.detect.Tier+import com.rfsentinel.app.service.DeviceRegistry++/**+ * The latest alerts, newest first - still listed after the device has left,+ * so a pop-up missed while driving can be looked at later. A device opens its+ * details (its last alert once out of range), a camera its place on the map,+ * a cell warning the cell towers.+ */+class RecentAlertsScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_000L) {++ private fun entries() = AlertLog.recent(carContext).take(CarUi.listLimit(carContext))++ override fun contentKey(): Any {+ val now = System.currentTimeMillis()+ return entries().map { "${it.key}|${it.time}|${CarUi.ageText(now - it.time)}" }+ }++ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun render(): Template {+ val now = System.currentTimeMillis()+ val me = CarUi.currentLocation(carContext)+ val items = ItemList.Builder()+ entries().forEach { e ->+ val color = when {+ e.tierEnum == Tier.WEAK -> CarUi.WEAK_COLOR+ else -> e.categoryEnum?.colorArgb ?: CarUi.DANGER_COLOR+ }+ val where = if (me != null && e.lat != null && e.lon != null)+ " · " + NearbyMapScreen.distanceText(DeviceRegistry.metersBetween(me.latitude, me.longitude, e.lat, e.lon)) + " away"+ else ""+ val row = Row.Builder()+ .setTitle((if (e.following) "FOLLOWING · " else "") + e.label)+ .addText("${e.categoryEnum?.shortTag ?: "Alert"} · ${CarUi.ageText(now - e.time)}$where")+ .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color))+ target(e, CarColor.createCustom(color, color))?.let { open -> row.setOnClickListener { open() } }+ items.addItem(row.build())+ }+ items.setNoItemsMessage("No alerts yet")+ return ListTemplate.Builder()+ .setTitle("Recent alerts")+ .setHeaderAction(Action.BACK)+ .setSingleList(items.build())+ .build()+ }++ /** Where tapping an alert goes, or null when there is nothing more to show. */+ private fun target(e: AlertLog.Entry, color: CarColor): (() -> Unit)? {+ e.mac?.let { mac -> return { screenManager.push(DeviceDetailScreen(carContext, mac)) } }+ if (e.key.startsWith("alpr:")) {+ val cam = AlprStore.cameras.firstOrNull { "alpr:" + it.osmId == e.key }+ if (cam != null) return { screenManager.push(PlaceFocusScreen.forCamera(carContext, cam)) }+ }+ if (e.key.startsWith("cell")) return { screenManager.push(CellsScreen(carContext)) }+ val lat = e.lat ?: return null+ val lon = e.lon ?: return null+ return { screenManager.push(PlaceFocusScreen(carContext, e.label, e.evidence.take(80), lat, lon, color, "!")) }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.kt b/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.ktnew file mode 100644index 0000000..cdc9a6c--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.kt@@ -0,0 +1,61 @@+package com.rfsentinel.app.car++import androidx.car.app.CarContext+import androidx.car.app.CarToast+import androidx.car.app.model.Action+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 com.rfsentinel.app.data.TrackerMutes+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.util.Prefs++/**+ * Ignoring a tracker from the car, with the phone's three choices: AirTags and+ * other tags change their address about daily, so they can't be whitelisted.+ * Only ignore a tag you know - a hidden tracker would stay silent too.+ */+class TrackerIgnoreScreen(carContext: CarContext, private val mac: String) : SafeScreen(carContext) {++ @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts+ override fun buildTemplate(): Template {+ val items = ItemList.Builder()+ items.addItem(Row.Builder()+ .setTitle("It's mine - keep ignoring it")+ .addText("Follows it when its address changes (best effort)")+ .setOnClickListener { mute(follow = true, "Ignored - followed when its address changes") }+ .build())+ items.addItem(Row.Builder()+ .setTitle("Ignore it today only")+ .addText("Until its address changes, at most 24 h")+ .setOnClickListener { mute(follow = false, "Ignored until its address changes (at most 24 h)") }+ .build())+ items.addItem(Row.Builder()+ .setTitle("Pause all tracker follow warnings for 24 h")+ .addText("Only ignore a tag you know - a hidden tracker would stay silent too")+ .setOnClickListener {+ Prefs.setTrackerFollowPausedUntil(carContext, System.currentTimeMillis() + 24 * 3_600_000L)+ done("Tracker follow warnings paused for 24 hours")+ }+ .build())+ return ListTemplate.Builder()+ .setTitle("Ignore this tracker?")+ .setHeaderAction(Action.BACK)+ .setSingleList(items.build())+ .build()+ }++ private fun mute(follow: Boolean, message: String) {+ val snap = DeviceRegistry.get(mac)+ if (snap == null) { done("Tracker no longer in range"); return }+ TrackerMutes.mute(carContext, mac, snap.best?.label ?: "Tracker", snap.rssi, follow)+ done(message)+ }++ private fun done(message: String) {+ CarToast.makeText(carContext, message, CarToast.LENGTH_LONG).show()+ // Back to the device (only if this screen is still on top).+ runCatching { if (screenManager.top === this) screenManager.pop() }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/data/AlertLog.kt b/app/src/main/java/com/rfsentinel/app/data/AlertLog.ktnew file mode 100644index 0000000..553ca29--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/data/AlertLog.kt@@ -0,0 +1,94 @@+package com.rfsentinel.app.data++import android.content.Context+import com.google.gson.Gson+import com.google.gson.reflect.TypeToken+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.detect.Tier++/**+ * The alerts RF Sentinel raised recently (devices, known cameras, cell warnings),+ * newest first, kept on the phone only. Android Auto lists them, and a device's+ * car screen falls back to its last alert once the device is out of range.+ */+object AlertLog {++ data class Entry(+ /** Device MAC, or "alpr:<osm id>" / "cell:<key>" for map alerts. */+ val key: String,+ /** The device's MAC when the alert is about a device. */+ val mac: String?,+ val label: String,+ val category: String,+ val tier: String,+ val confidence: Int,+ val evidence: String,+ val rssi: Int?,+ val time: Long,+ val following: Boolean = false,+ /** Where it is (a camera, a drone) or where your phone was when it alerted. */+ val lat: Double? = null,+ val lon: Double? = null+ ) {+ val categoryEnum: Category? get() = runCatching { Category.valueOf(category) }.getOrNull()+ val tierEnum: Tier? get() = runCatching { Tier.valueOf(tier) }.getOrNull()+ }++ private const val PREFS = "alert_log"+ private const val KEY = "entries"+ const val MAX = 40++ private val gson = Gson()+ private val listType = object : TypeToken<List<Entry>>() {}.type+ private var entries: MutableList<Entry>? = null++ /** Tests: start empty without touching storage. */+ @Synchronized+ fun resetForTest() { entries = ArrayList() }++ @Synchronized+ private fun list(context: Context?): MutableList<Entry> {+ entries?.let { return it }+ val loaded: List<Entry> = context?.let { c ->+ runCatching {+ c.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null)+ ?.let { gson.fromJson<List<Entry>>(it, listType) }+ }.getOrNull()+ }.orEmpty()+ return ArrayList(loaded.filterNotNull()).also { entries = it }+ }++ @Synchronized+ fun add(+ context: Context, key: String, mac: String?, hit: Hit, rssi: Int?, following: Boolean,+ lat: Double?, lon: Double?, now: Long = System.currentTimeMillis()+ ) {+ val l = list(context)+ // The same thing alerting again replaces its older entry (newest on top).+ l.removeAll { it.key == key }+ l.add(0, Entry(key, mac, hit.label, hit.category.name, hit.tier.name, hit.confidence, hit.evidence,+ rssi, now, following, lat, lon))+ while (l.size > MAX) l.removeAt(l.size - 1)+ save(context, l)+ }++ @Synchronized+ fun recent(context: Context?): List<Entry> = list(context).toList()++ @Synchronized+ fun latestFor(context: Context?, mac: String): Entry? = list(context).firstOrNull { it.mac.equals(mac, ignoreCase = true) }++ @Synchronized+ fun clear(context: Context) {+ list(context).clear()+ save(context, emptyList())+ }++ private fun save(context: Context, l: List<Entry>) {+ runCatching {+ context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+ .edit().putString(KEY, gson.toJson(l)).apply()+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/receiver/AlertActionReceiver.kt b/app/src/main/java/com/rfsentinel/app/receiver/AlertActionReceiver.ktnew file mode 100644index 0000000..34d9ca5--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/receiver/AlertActionReceiver.kt@@ -0,0 +1,95 @@+package com.rfsentinel.app.receiver++import android.app.NotificationManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.rfsentinel.app.data.AlertLog+import com.rfsentinel.app.data.AppDatabase+import com.rfsentinel.app.data.TrackerMutes+import com.rfsentinel.app.data.WhitelistEntity+import com.rfsentinel.app.detect.AddressType+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.util.Prefs+import com.rfsentinel.app.util.Voice+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * The buttons on an alert shown on the car screen: "Mute 30 min" silences alert+ * sound and voice for half an hour; "Ignore" stops alerting about that device+ * (a rotating tracker until its address changes, anything else via the+ * whitelist - undo from the device's details).+ */+class AlertActionReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ val app = context.applicationContext+ when (intent.action) {+ ACTION_SNOOZE -> snooze(app)+ ACTION_IGNORE -> {+ val mac = intent.getStringExtra(EXTRA_MAC) ?: return+ val pending = goAsync()+ scope.launch {+ try { ignore(app, mac) } finally { pending.finish() }+ }+ }+ else -> return+ }+ val id = intent.getIntExtra(EXTRA_NOTIFICATION, 0)+ if (id != 0) runCatching { app.getSystemService(NotificationManager::class.java).cancel(id) }+ }++ companion object {+ const val ACTION_SNOOZE = "com.rfsentinel.app.action.SNOOZE_ALERTS"+ const val ACTION_IGNORE = "com.rfsentinel.app.action.IGNORE_DEVICE"+ private const val EXTRA_MAC = "mac"+ private const val EXTRA_NOTIFICATION = "notification"+ const val SNOOZE_MS = 30 * 60_000L++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ fun snoozeIntent(context: Context, notificationId: Int): PendingIntent = PendingIntent.getBroadcast(+ context, notificationId,+ Intent(context, AlertActionReceiver::class.java).setAction(ACTION_SNOOZE)+ .putExtra(EXTRA_NOTIFICATION, notificationId),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )++ fun ignoreIntent(context: Context, mac: String, notificationId: Int): PendingIntent = PendingIntent.getBroadcast(+ context, mac.hashCode(),+ Intent(context, AlertActionReceiver::class.java).setAction(ACTION_IGNORE)+ .putExtra(EXTRA_MAC, mac).putExtra(EXTRA_NOTIFICATION, notificationId),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )++ /** Silences alert sound and voice for [SNOOZE_MS] (also from the car's "More" screen). */+ fun snooze(context: Context, now: Long = System.currentTimeMillis()) {+ Prefs.setAlertsSnoozedUntil(context, now + SNOOZE_MS)+ Voice.silence()+ }++ /**+ * Stops alerting about [mac]: a tracker whose address rotates is ignored until the+ * address changes (it can't be whitelisted); anything else is whitelisted.+ * Returns what was done, for a toast.+ */+ suspend fun ignore(context: Context, mac: String): String {+ val snap = DeviceRegistry.get(mac)+ val label = snap?.best?.label ?: AlertLog.latestFor(context, mac)?.label ?: ""+ val rotatingTracker = snap != null && snap.best?.category == Category.TRACKER &&+ snap.addressType != AddressType.PUBLIC+ return if (rotatingTracker) {+ TrackerMutes.mute(context, mac, label, snap!!.rssi, follow = false)+ "Ignored until its address changes (at most 24 h)"+ } else {+ AppDatabase.getInstance(context).whitelistDao().add(WhitelistEntity(mac, label))+ "Whitelisted - won't alert again"+ }+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 79af326..3e7e1d6 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -607,7 +607,7 @@ class ScanForegroundService : Service() {". Mapped in OpenStreetMap" + (if (alpr) " - it may not broadcast any signal." else "."),"OpenStreetMap (" + (if (alpr) "surveillance:type=ALPR" else "highway=speed_camera / enforcement") + "), ODbL")- NotificationHelper.sendMapAlert(this, "alpr:" + cam.osmId, hit)+ NotificationHelper.sendMapAlert(this, "alpr:" + cam.osmId, hit, lat = cam.lat, lon = cam.lon)AlertPlayer.play(this, hit.tier, com.rfsentinel.app.util.Spoken.camera(this, cam))break // one warning per fix is enough}diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 099e0fb..be4ee2d 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -503,6 +503,7 @@ class SettingsActivity : AppCompatActivity() {confirm("Clear match history?", "Deletes every logged match. Export first if you need a copy.") {lifecycleScope.launch {AppDatabase.getInstance(this@SettingsActivity).detectionDao().clearAll()+ com.rfsentinel.app.data.AlertLog.clear(this@SettingsActivity)Toast.makeText(this@SettingsActivity, "Match history cleared", Toast.LENGTH_SHORT).show()}}diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.ktindex 86ed8f2..a96d0f3 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt@@ -53,7 +53,10 @@ class DetectionLogActivity : AppCompatActivity() {.setTitle("Clear match history?").setMessage("This deletes every logged match on this device. Export first if you need a copy.").setPositiveButton("Clear") { _, _ ->- lifecycleScope.launch { AppDatabase.getInstance(this@DetectionLogActivity).detectionDao().clearAll() }+ lifecycleScope.launch {+ AppDatabase.getInstance(this@DetectionLogActivity).detectionDao().clearAll()+ com.rfsentinel.app.data.AlertLog.clear(this@DetectionLogActivity)+ }}.setNegativeButton("Cancel", null).show()diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.ktindex c0f9e95..fa94532 100644--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt@@ -57,7 +57,7 @@ object AlertPlayer {fun play(context: Context, tier: Tier, spoken: String?, following: Boolean = false) {val inCar = CarState.connected- val muted = Prefs.alertsMuted(context)+ val muted = Prefs.alertsSilenced(context)val willSpeak = !muted && spoken != null && (Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))var beepMs = 0if (!muted && Prefs.soundEnabled(context) && (inCar || ringerAllowsSound(context))) {@@ -94,7 +94,7 @@ 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+ if (Prefs.alertsSilenced(context)) returnVoice.say(context.applicationContext, text, VoiceQueue.STRONG, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)}diff --git a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.ktindex d06cc83..54fe513 100644--- a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt+++ b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt@@ -139,8 +139,11 @@ object NotificationHelper {*/fun sendMapAlert(context: Context, key: String, hit: Hit,- target: Class<out android.app.Activity> = com.rfsentinel.app.ui.MapActivity::class.java+ target: Class<out android.app.Activity> = com.rfsentinel.app.ui.MapActivity::class.java,+ /** Where the thing is (a camera); else where you were. */+ lat: Double? = null, lon: Double? = null) {+ recordAlert(context, key, null, hit, null, false, lat, lon)val nm = context.getSystemService(NotificationManager::class.java)val discreet = Prefs.discreetMode(context)val open = PendingIntent.getActivity(@@ -166,6 +169,8 @@ object NotificationHelper {.setContentText(if (discreet) "New alert" else hit.evidence).setSmallIcon(R.drawable.ic_tile_scan).setImportance(NotificationManagerCompat.IMPORTANCE_HIGH)+ .addAction(R.drawable.ic_car_volume_off, "Mute 30 min",+ com.rfsentinel.app.receiver.AlertActionReceiver.snoozeIntent(context, ALERT_NOTIFICATION_ID_BASE + key.hashCode())).build())try {@@ -175,8 +180,29 @@ object NotificationHelper {}}+ /**+ * Adds the alert to the recent-alerts list (Android Auto). Positions are kept only+ * with Settings > GPS tagging on, like the match history.+ */+ private fun recordAlert(+ context: Context, key: String, mac: String?, hit: Hit, rssi: Int?, following: Boolean,+ lat: Double?, lon: Double?+ ) {+ runCatching {+ val tag = Prefs.gpsTaggingEnabled(context)+ val here = ScanForegroundService.lastFix+ com.rfsentinel.app.data.AlertLog.add(+ context, key, mac, hit, rssi, following,+ if (tag) lat ?: here?.latitude else null, if (tag) lon ?: here?.longitude else null+ )+ }+ }+/** Posts the match notification; sound/vibration/voice are played by the caller. */fun sendAlert(context: Context, mac: String, hit: Hit, rssi: Int, following: Boolean = false) {+ // A drone with a Remote ID position is logged where it is; anything else where you were.+ val rid = com.rfsentinel.app.service.DeviceRegistry.get(mac)?.remoteId?.takeIf { it.hasPosition }+ recordAlert(context, mac, mac, hit, rssi, following, rid?.latitude, rid?.longitude)val nm = context.getSystemService(NotificationManager::class.java)val discreet = Prefs.discreetMode(context)val detail = PendingIntent.getActivity(@@ -228,6 +254,12 @@ object NotificationHelper {PendingIntent.FLAG_UPDATE_CURRENT))+ // One tap from the car screen: silence alerts for a while, or stop+ // alerting about this device (undo from its details).+ .addAction(R.drawable.ic_car_volume_off, "Mute 30 min",+ com.rfsentinel.app.receiver.AlertActionReceiver.snoozeIntent(context, ALERT_NOTIFICATION_ID_BASE + mac.hashCode()))+ .addAction(R.drawable.ic_car_star_outline, "Ignore",+ com.rfsentinel.app.receiver.AlertActionReceiver.ignoreIntent(context, mac, ALERT_NOTIFICATION_ID_BASE + mac.hashCode())).build())try {diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex f584a16..4c71e4a 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -70,6 +70,14 @@ object Prefs {fun alertsMuted(context: Context): Boolean = bool(context, "alerts_muted", false)fun setAlertsMuted(context: Context, value: Boolean) = setBool(context, "alerts_muted", value)+ /** Alert sound and voice snoozed until this time (Android Auto "Mute 30 min"); 0 = not snoozed. */+ fun alertsSnoozedUntil(context: Context): Long = sp(context).getLong("alerts_snoozed_until", 0L)+ fun setAlertsSnoozedUntil(context: Context, time: Long) = sp(context).edit { putLong("alerts_snoozed_until", time) }++ /** Muted, or snoozed for a while: no alert sound or voice. */+ fun alertsSilenced(context: Context, now: Long = System.currentTimeMillis()): Boolean =+ alertsMuted(context) || now < alertsSnoozedUntil(context)+/** Speak alerts whenever Android Auto is connected, even if phone voice alerts are off. */fun carVoice(context: Context): Boolean = bool(context, "car_voice", true)fun setCarVoice(context: Context, value: Boolean) = setBool(context, "car_voice", value)diff --git a/app/src/main/res/drawable/ic_car_history.xml b/app/src/main/res/drawable/ic_car_history.xmlnew file mode 100644index 0000000..dc64311--- /dev/null+++ b/app/src/main/res/drawable/ic_car_history.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="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.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,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />+</vector>diff --git a/app/src/main/res/drawable/ic_car_more.xml b/app/src/main/res/drawable/ic_car_more.xmlnew file mode 100644index 0000000..a6449aa--- /dev/null+++ b/app/src/main/res/drawable/ic_car_more.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="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" />+</vector>diff --git a/app/src/main/res/drawable/ic_car_snooze.xml b/app/src/main/res/drawable/ic_car_snooze.xmlnew file mode 100644index 0000000..3734006--- /dev/null+++ b/app/src/main/res/drawable/ic_car_snooze.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="M9,11h3.63L9,15.2V17h6v-2h-3.63L15,10.8V9H9v2zM16.56,2.44l-1.29,1.53 4.6,3.85 1.29,-1.53zM7.44,2.44L2.85,6.29l1.29,1.53 4.6,-3.86zM12,4c-4.97,0 -9,4.03 -9,9s4.02,9 9,9c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,20c-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_tower.xml b/app/src/main/res/drawable/ic_car_tower.xmlnew file mode 100644index 0000000..fbd4998--- /dev/null+++ b/app/src/main/res/drawable/ic_car_tower.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,5c-3.87,0 -7,3.13 -7,7h2c0,-2.76 2.24,-5 5,-5s5,2.24 5,5h2c0,-3.87 -3.13,-7 -7,-7zM13,14.29c0.88,-0.39 1.5,-1.26 1.5,-2.29 0,-1.38 -1.12,-2.5 -2.5,-2.5S9.5,10.62 9.5,12c0,1.02 0.62,1.9 1.5,2.29v3.3L7.59,21 9,22.41l3,-3 3,3L16.41,21 13,17.59v-3.3zM12,1C5.93,1 1,5.93 1,12h2c0,-4.97 4.03,-9 9,-9s9,4.03 9,9h2c0,-6.07 -4.93,-11 -11,-11z" />+</vector>diff --git a/app/src/main/res/drawable/ic_car_usb.xml b/app/src/main/res/drawable/ic_car_usb.xmlnew file mode 100644index 0000000..183f306--- /dev/null+++ b/app/src/main/res/drawable/ic_car_usb.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="M15,7v4h1v2h-3V5h2l-3,-4 -3,4h2v8H8v-2.07c0.7,-0.37 1.2,-1.08 1.2,-1.93 0,-1.21 -0.99,-2.2 -2.2,-2.2 -1.21,0 -2.2,0.99 -2.2,2.2 0,0.85 0.5,1.56 1.2,1.93V13c0,1.11 0.89,2 2,2h3v3.05c-0.71,0.37 -1.2,1.1 -1.2,1.95 0,1.22 0.99,2.2 2.2,2.2 1.21,0 2.2,-0.98 2.2,-2.2 0,-0.85 -0.49,-1.58 -1.2,-1.95V15h3c1.11,0 2,-0.89 2,-2v-2h1V7h-4z" />+</vector>diff --git a/app/src/test/java/com/rfsentinel/app/car/CarReworkTest.kt b/app/src/test/java/com/rfsentinel/app/car/CarReworkTest.ktnew file mode 100644index 0000000..bb5ce14--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/car/CarReworkTest.kt@@ -0,0 +1,343 @@+package com.rfsentinel.app.car++import android.app.Application+import androidx.car.app.OnDoneCallback+import androidx.car.app.model.ListTemplate+import androidx.car.app.model.PaneTemplate+import androidx.car.app.model.PlaceListMapTemplate+import androidx.car.app.model.Row+import androidx.car.app.model.Template+import androidx.car.app.testing.TestCarContext+import androidx.car.app.testing.TestScreenManager+import androidx.test.core.app.ApplicationProvider+import com.rfsentinel.app.alpr.AlprStore+import com.rfsentinel.app.alpr.KnownCamera+import com.rfsentinel.app.alpr.KnownCameras+import com.rfsentinel.app.data.AlertLog+import com.rfsentinel.app.detect.AddressType+import com.rfsentinel.app.detect.Advert+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.CellAnalyzer+import com.rfsentinel.app.detect.DeviceIntel+import com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.detect.RemoteId+import com.rfsentinel.app.receiver.AlertActionReceiver+import com.rfsentinel.app.service.CellTowerStore+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.ui.DeviceFilter+import com.rfsentinel.app.util.Prefs+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+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.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * The reworked Android Auto screens: home rows and limits, the new screens+ * (recent alerts, nearby filters, cell towers, hardware, more, tracker ignore),+ * screen depth, change-only refreshes, alert buttons and robustness with no+ * data or a lot of it. Every test fails if any screen fell back to its error page.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class CarReworkTest {++ private lateinit var car: TestCarContext+ private val axonMac = "00:25:DF:11:22:33"+ private val droneMac = "60:60:1F:12:34:56"++ @Before+ fun setUp() {+ car = TestCarContext.createCarContext(ApplicationProvider.getApplicationContext())+ SafeScreen.lastError = null+ AlertLog.resetForTest()+ DeviceRegistry.startSession()+ ScanForegroundService.isRunning = true+ DeviceRegistry.report(+ Advert(axonMac, Advert.Source.BLE, -58, "Axon Body 4"),+ listOf(Hit(Category.BODY_CAM, "Axon body camera", 90, "BWCDEVICE tag in advert payload", "test")),+ DeviceIntel.Identity("Body camera", emptyList()), "Axon Enterprise, Inc.", null, null+ )+ DeviceRegistry.report(+ Advert(droneMac, Advert.Source.BLE, -75),+ listOf(Hit(Category.DRONE, "Drone broadcasting Remote ID", 95, "ASTM F3411", "test")),+ DeviceIntel.Identity("Drone", emptyList()), "DJI",+ RemoteId.Info(uasId = "1581F5FJD123", latitude = 10.5, longitude = -20.5, heightM = 60.0), null+ )+ repeat(12) { i ->+ DeviceRegistry.report(Advert(String.format("C0:00:00:00:00:%02X", i), Advert.Source.BLE, -80 - i, "Device $i"),+ emptyList(), DeviceIntel.Identity("Phone", emptyList()), null, null, null)+ }+ }++ @After+ fun tearDown() {+ ScanForegroundService.isRunning = false+ ScanForegroundService.setLastFixForTest(null)+ AlprStore.setForTest(emptyList())+ Prefs.setAlertsSnoozedUntil(car, 0L)+ DeviceRegistry.clear()+ assertNull("a car screen failed to render", SafeScreen.lastError)+ }++ private val done = object : OnDoneCallback {}+ private fun click(row: Row) = row.onClickDelegate!!.sendClick(done)+ private fun rows(t: Template) = (t as ListTemplate).singleList!!.items.map { it as Row }+ private fun screens(c: TestCarContext = car) = c.getCarService(TestScreenManager::class.java)+ private fun fix(lat: Double, lon: Double, bearing: Float? = null, speed: Float? = null) =+ ScanForegroundService.setLastFixForTest(android.location.Location("test").apply {+ latitude = lat; longitude = lon+ bearing?.let { this.bearing = it }+ speed?.let { this.speed = it }+ })++ @Test+ fun homeShowsNextCameraAheadAndKeepsMoreWithinTheRowLimit() {+ AlprStore.setForTest(listOf(+ KnownCamera("node/9", 10.504, -20.5, null, "Example DOT", null, KnownCamera.Kind.SPEED, 50)+ ))+ fix(10.5, -20.5, bearing = 0f, speed = 15f) // driving north, the camera ~440 m ahead+ val r = rows(HomeScreen(car).onGetTemplate())+ assertTrue(r.size <= CarUi.listLimit(car))+ assertEquals("Speed camera (50 km/h) ahead", r[1].title.toString())+ assertTrue(r[1].texts[0].toString().startsWith("440 m"))+ assertEquals("More", r.last().title.toString())+ click(r[1])+ assertTrue(screens().top is PlaceFocusScreen)+ }++ @Test+ fun cameraAheadFollowsTheHeading() {+ val cams = listOf(+ KnownCamera("node/n", 10.505, -20.5, null, null, null),+ KnownCamera("node/s", 10.4975, -20.5, null, null, null)+ )+ assertEquals("node/n", KnownCameras.ahead(cams, 10.5, -20.5, 0f)!!.first.osmId)+ assertEquals("node/s", KnownCameras.ahead(cams, 10.5, -20.5, 180f)!!.first.osmId)+ assertEquals("node/s", KnownCameras.ahead(cams, 10.5, -20.5, null)!!.first.osmId) // parked: nearest (~280 m)+ assertNull(KnownCameras.ahead(cams, 10.5, -20.5, 90f)) // nothing to the east+ assertNull(KnownCameras.ahead(cams, 10.5, -20.5, 180f) { it.osmId == "node/s" }) // silenced+ assertEquals(90.0, KnownCameras.bearingTo(0.0, 0.0, 0.0, 1.0), 0.01)+ }++ @Test+ fun cameraViewTogglesItsAlerts() {+ val cam = KnownCamera("node/7", 10.503, -20.5, "Flock Safety", null, null)+ fix(10.5, -20.5)+ val screen = PlaceFocusScreen.forCamera(car, cam)+ val row = (screen.onGetTemplate() as PlaceListMapTemplate).itemList!!.items.single() as Row+ click(row)+ assertTrue(com.rfsentinel.app.alpr.IgnoredCameras.contains(car, "node/7"))+ val again = (screen.onGetTemplate() as PlaceListMapTemplate).itemList!!.items.single() as Row+ assertTrue(again.texts[0].toString().contains("Alerts off"))+ click(again)+ assertFalse(com.rfsentinel.app.alpr.IgnoredCameras.contains(car, "node/7"))+ }++ @Test+ fun recentAlertsStayAfterTheDeviceLeaves() {+ val gone = "D4:00:00:00:00:01"+ AlertLog.add(car, gone, gone, Hit(Category.PUBLIC_SAFETY, "Police vehicle equipment", 85, "Router and printer together", "test"),+ -70, following = false, lat = 10.51, lon = -20.5)+ AlertLog.add(car, "alpr:node/1", null, Hit(Category.ALPR, "Known plate camera ahead", 80, "Plate reader, ~200 m away", "test"),+ null, following = false, lat = 10.503, lon = -20.5)+ val r = rows(RecentAlertsScreen(car).onGetTemplate())+ assertEquals(listOf("Known plate camera ahead", "Police vehicle equipment"), r.map { it.title.toString() })++ // Out of range: its details come from the last alert, with Whitelist + Navigate there.+ val pane = DeviceDetailScreen(car, gone).onGetTemplate() as PaneTemplate+ assertEquals(listOf("Whitelist", "Navigate there"), pane.pane.actions.map { it.title.toString() })+ assertTrue(pane.pane.rows[0].texts[0].toString().startsWith("Out of range"))++ click(r[1])+ assertTrue(screens().top is DeviceDetailScreen)+ }++ @Test+ fun alertLogKeepsNewestFirstWithoutDuplicates() {+ val hit = Hit(Category.BODY_CAM, "Axon body camera", 90, "x", "test")+ repeat(50) { i -> AlertLog.add(car, "K$i", "K$i", hit, -60, false, null, null, now = 1_000L + i) }+ AlertLog.add(car, "K3", "K3", hit, -55, true, null, null, now = 9_999L)+ val all = AlertLog.recent(car)+ assertEquals(AlertLog.MAX, all.size)+ assertEquals("K3", all[0].key)+ assertEquals(1, all.count { it.key == "K3" })+ assertTrue(all[0].following)+ }++ @Test+ fun nearbyDevicesOffersThePhoneFiltersWithCounts() {+ val r = rows(NearbyDevicesScreen(car).onGetTemplate())+ assertTrue(r.size <= CarUi.listLimit(car))+ val titles = r.map { it.title.toString() }+ assertEquals("All nearby (14)", titles[0])+ assertEquals("Flagged nearby (2)", titles[1])+ assertTrue("Drones (1)" in titles)+ click(r[1])+ val list = screens().top as DeviceListScreen+ assertEquals(2, rows(list.onGetTemplate()).size)+ }++ @Test+ fun cellsHardwareAndMoreScreensBuild() {+ assertEquals(1, rows(CellsScreen(car).onGetTemplate()).size) // status row only+ val serving = CellAnalyzer.Cell(CellAnalyzer.Rat.LTE, true, "001", "01", 100, 12345L, -95, operator = "Test Net")+ val neighbour = CellAnalyzer.Cell(CellAnalyzer.Rat.LTE, false, null, null, null, null, -110, pci = 7)+ CellTowerStore.record(car, listOf(serving, neighbour), null)+ val c = rows(CellsScreen(car).onGetTemplate())+ assertEquals(3, c.size)+ assertTrue(c[1].title.toString().endsWith("serving"))+ assertTrue(CellsScreen.summary()!!.contains("1 neighbour"))+ // With cells known and no camera ahead, home lists them too.+ assertTrue(rows(HomeScreen(car).onGetTemplate()).any { it.title.toString() == "Cell towers" })+ CellTowerStore.forget(car)++ val hw = rows(HardwareScreen(car).onGetTemplate()).map { it.title.toString() }+ assertEquals(listOf("Phone radios", "ESP32 on USB", "OUI-SPY over Bluetooth", "USB WiFi adapter"), hw)++ val more = rows(MoreScreen(car).onGetTemplate())+ assertTrue(more.size <= CarUi.listLimit(car))+ assertEquals("Snooze alerts 30 min", more[0].title.toString())+ }++ @Test+ fun snoozeSilencesAlertsAndResumes() {+ val screen = MoreScreen(car)+ click(rows(screen.onGetTemplate())[0])+ val now = System.currentTimeMillis()+ assertTrue(Prefs.alertsSilenced(car))+ assertFalse(Prefs.alertsMuted(car)) // a snooze, not the mute switch+ assertTrue(Prefs.alertsSilenced(car, now + 29 * 60_000L))+ assertFalse(Prefs.alertsSilenced(car, now + 31 * 60_000L))+ val r = rows(screen.onGetTemplate())+ assertEquals("Resume alert sound", r[0].title.toString())+ assertTrue(rows(HomeScreen(car).onGetTemplate())[0].texts[0].toString().contains("snoozed"))+ click(r[0])+ assertFalse(Prefs.alertsSilenced(car))+ }++ @Test+ fun trackerIgnoreOffersThePhonesThreeChoices() {+ val tag = "D1:22:33:44:55:66"+ DeviceRegistry.report(+ Advert(tag, Advert.Source.BLE, -60, addressType = AddressType.RANDOM_STATIC),+ listOf(Hit(Category.TRACKER, "Apple Find My tracker away from its owner (AirTag or compatible)", 70, "x", "test")),+ DeviceIntel.Identity("Tracker", emptyList()), null, null, null+ )+ val detail = DeviceDetailScreen(car, tag).onGetTemplate() as PaneTemplate+ assertEquals("Ignore...", detail.pane.actions[0].title.toString())+ val sm = screens()+ sm.push(DeviceDetailScreen(car, tag))+ sm.push(TrackerIgnoreScreen(car, tag))+ val r = rows(sm.top.onGetTemplate())+ assertEquals(3, r.size)+ click(r[1]) // today only+ assertTrue(com.rfsentinel.app.data.TrackerMutes.isMuted(tag))+ assertTrue(sm.top is DeviceDetailScreen) // back to the device+ com.rfsentinel.app.data.TrackerMutes.unmute(car, tag)+ }++ @Test+ fun deepestPathsStayWithinTheFiveScreenLimit() {+ // Home > Nearby devices > Flagged > a device: the longest list path (+ tracker Ignore = 5).+ val sm = screens()+ sm.push(HomeScreen(car))+ click(rows(sm.top.onGetTemplate()).first { it.title.toString().startsWith("Nearby devices") })+ click(rows(sm.top.onGetTemplate())[1])+ click(rows(sm.top.onGetTemplate())[0])+ assertTrue(sm.top is DeviceDetailScreen)+ assertTrue(sm.stackSize <= 4)++ // Home > devices map > its Cameras > a camera: the car-drawn map path (+ live map = 5).+ AlprStore.setForTest(listOf(KnownCamera("node/1", 10.503, -20.5, "Flock Safety", null, null)))+ fix(10.5, -20.5)+ val car2 = TestCarContext.createCarContext(ApplicationProvider.getApplicationContext())+ val sm2 = screens(car2)+ sm2.push(HomeScreen(car2))+ sm2.push(DevicesMapScreen(car2))+ (sm2.top.onGetTemplate() as PlaceListMapTemplate).actionStrip!!.actions[0].onClickDelegate!!.sendClick(done)+ val camRow = (sm2.top.onGetTemplate() as PlaceListMapTemplate).itemList!!.items+ .map { it as Row }.first { it.title.toString().contains("Flock") }+ click(camRow)+ assertTrue(sm2.top is PlaceFocusScreen)+ assertTrue(sm2.stackSize <= 4)+ }++ @Test+ fun screensOnlyRefreshWhenTheirContentChanges() {+ val home = HomeScreen(car)+ home.onGetTemplate()+ assertFalse(home.needsRefresh())+ DeviceRegistry.report(Advert("C1:00:00:00:00:01", Advert.Source.BLE, -70, "New"), emptyList(),+ DeviceIntel.Identity("Phone", emptyList()), null, null, null)+ assertTrue(home.needsRefresh())++ val list = DeviceListScreen(car, DeviceFilter.FLAGGED)+ list.onGetTemplate()+ assertFalse(list.needsRefresh())+ }++ @Test+ fun everyScreenBuildsWhenEmptyNotScanningAndWithoutLocation() {+ ScanForegroundService.isRunning = false+ DeviceRegistry.clear()+ val all = listOf(+ HomeScreen(car), NearbyDevicesScreen(car), RecentAlertsScreen(car), CellsScreen(car), HardwareScreen(car),+ MoreScreen(car), DevicesMapScreen(car), NearbyMapScreen(car), LiveMapScreen(car),+ DeviceDetailScreen(car, axonMac), TrackerIgnoreScreen(car, axonMac)+ ) + DeviceFilter.entries.map { DeviceListScreen(car, it) }+ all.forEach { it.onGetTemplate() }+ }++ @Test+ fun manyDevicesStayWithinLimits() {+ repeat(500) { i ->+ val a = Advert(String.format("E0:00:00:00:%02X:%02X", i / 256, i % 256),+ if (i % 2 == 0) Advert.Source.BLE else Advert.Source.WIFI, -40 - (i % 60), "Dev $i")+ val hits = if (i % 7 == 0) listOf(Hit(Category.BODY_CAM, "Body cam $i", 50 + i % 50, "x", "test")) else emptyList()+ DeviceRegistry.report(a, hits, DeviceIntel.Identity("Phone", emptyList()), null, null,+ DeviceRegistry.GeoSample(System.currentTimeMillis(), 10.5 + i * 1e-5, -20.5))+ }+ fix(10.5, -20.5)+ val limit = CarUi.listLimit(car)+ assertTrue(rows(HomeScreen(car).onGetTemplate()).size <= limit)+ assertTrue(rows(NearbyDevicesScreen(car).onGetTemplate()).size <= limit)+ assertEquals(limit, rows(DeviceListScreen(car, DeviceFilter.ALL).onGetTemplate()).size)+ val map = DevicesMapScreen(car).onGetTemplate() as PlaceListMapTemplate+ assertTrue(map.itemList!!.items.size <= 6)+ }++ @Test+ fun alertButtonsSnoozeAndIgnore() {+ val ctx = ApplicationProvider.getApplicationContext<Application>()+ AlertActionReceiver().onReceive(ctx, android.content.Intent(AlertActionReceiver.ACTION_SNOOZE))+ assertTrue(Prefs.alertsSilenced(ctx))+ Prefs.setAlertsSnoozedUntil(ctx, 0L)++ val msg = runBlocking { AlertActionReceiver.ignore(ctx, axonMac) }+ assertTrue(msg.startsWith("Whitelisted"))+ val wl = runBlocking { com.rfsentinel.app.data.AppDatabase.getInstance(ctx).whitelistDao().all().first() }+ assertTrue(wl.any { it.mac == axonMac })+ }++ @Test+ fun alertNotificationIsLoggedAndHasCarButtons() {+ val ctx = ApplicationProvider.getApplicationContext<Application>()+ com.rfsentinel.app.util.NotificationHelper.createChannels(ctx)+ val hit = Hit(Category.BODY_CAM, "Axon body camera", 90, "BWCDEVICE tag", "test")+ com.rfsentinel.app.util.NotificationHelper.sendAlert(ctx, axonMac, hit, -58)+ assertEquals(axonMac, AlertLog.recent(ctx).first().mac)+ val nm = ctx.getSystemService(android.app.NotificationManager::class.java)+ val posted = org.robolectric.Shadows.shadowOf(nm).allNotifications.last()+ val actions = androidx.car.app.notification.CarAppExtender(posted).actions+ assertEquals(listOf("Mute 30 min", "Ignore"), actions.map { it.title.toString() })+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt b/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.ktindex cc11f27..3b23dbb 100644--- a/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt+++ b/app/src/test/java/com/rfsentinel/app/car/CarScreensTest.kt@@ -42,6 +42,8 @@ class CarScreensTest {@Beforefun setUp() {car = TestCarContext.createCarContext(ApplicationProvider.getApplicationContext())+ SafeScreen.lastError = null+ com.rfsentinel.app.data.AlertLog.resetForTest()DeviceRegistry.startSession()ScanForegroundService.isRunning = true@@ -67,19 +69,22 @@ class CarScreensTest {@Afterfun tearDown() {ScanForegroundService.isRunning = false+ ScanForegroundService.setLastFixForTest(null)+ com.rfsentinel.app.alpr.AlprStore.setForTest(emptyList())DeviceRegistry.clear()+ // A screen that failed to build shows an error message instead of crashing: catch that here.+ org.junit.Assert.assertNull("a car screen failed to render", SafeScreen.lastError)}@Testfun homeScreenShowsStatusNavigationAndButtons() {val t = HomeScreen(car).onGetTemplate() as ListTemplateval rows = t.singleList!!.items.map { it as Row }- assertEquals(6, rows.size)+ assertEquals(listOf("Recent alerts (0)", "Nearby devices (14)", "More"),+ listOf(rows[1], rows[3], rows[4]).map { it.title.toString() })assertTrue(rows[0].title.toString().startsWith("Strong match")) // threat headline- 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)"))- assertTrue(rows[4].title.toString() in setOf("Live map & navigation", "Map: devices & cameras around me"))+ assertTrue(rows[0].texts[0].toString().contains("2 flagged"))+ assertTrue(rows[2].title.toString() in setOf("Live map & navigation", "Map: devices & cameras around me"))val actions = t.actionStrip!!.actionsassertEquals(2, actions.size)assertEquals("Stop", actions[0].title.toString())@@ -93,7 +98,7 @@ class CarScreensTest {mute.onClickDelegate!!.sendClick(object : OnDoneCallback {})assertTrue(Prefs.alertsMuted(car))val t = screen.onGetTemplate() as ListTemplate- assertTrue((t.singleList!!.items[5] as Row).texts[0].toString().contains("muted"))+ assertTrue((t.singleList!!.items[0] as Row).texts[0].toString().contains("muted"))val relabeled = t.actionStrip!!.actions[1]relabeled.onClickDelegate!!.sendClick(object : OnDoneCallback {})assertTrue(!Prefs.alertsMuted(car))@@ -101,13 +106,13 @@ class CarScreensTest {@Testfun listsRespectCarRowLimitAndOrder() {- val t = DeviceListScreen(car, DeviceListScreen.Filter.ALL).onGetTemplate() as ListTemplate+ val t = DeviceListScreen(car, com.rfsentinel.app.ui.DeviceFilter.ALL).onGetTemplate() as ListTemplateval rows = t.singleList!!.items.map { it as Row }assertTrue(rows.size <= CarUi.listLimit(car))assertEquals("Drone broadcasting Remote ID", rows[0].title.toString()) // strongest evidence (95) firstassertEquals("Axon body camera", rows[1].title.toString())- val flagged = DeviceListScreen(car, DeviceListScreen.Filter.FLAGGED).onGetTemplate() as ListTemplate+ val flagged = DeviceListScreen(car, com.rfsentinel.app.ui.DeviceFilter.FLAGGED).onGetTemplate() as ListTemplateassertEquals(2, flagged.singleList!!.items.size)}