Skip to content

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

Known plate cameras from OpenStreetMap

CIS-C0096ad84235d7
diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
index 4d4cb6d..ba82d2d 100644
--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
@@ -26,6 +26,7 @@ class RFSentinelApp : Application() {
// ~60k vendor rows: load off the main thread; lookups return null until ready.
// A trace left "recording" by a crash / force-stop gets closed.
appScope.launch { runCatching { com.rfsentinel.app.service.TripRecorder.closeStale(this@RFSentinelApp) } }
+ appScope.launch(Dispatchers.IO) { runCatching { com.rfsentinel.app.alpr.AlprStore.load(this@RFSentinelApp) } }
appScope.launch(Dispatchers.IO) {
runCatching { VendorDb.load { assets.open(it) } }
.onFailure { Log.e("RFSentinelApp", "Vendor database failed to load", it) }
diff --git a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
new file mode 100644
index 0000000..97b8dcd
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
@@ -0,0 +1,75 @@
+package com.rfsentinel.app.alpr
+
+import android.content.Context
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.rfsentinel.app.BuildConfig
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+
+/**
+ * Offline cache of known plate-reader cameras, downloaded only when the user
+ * asks for a map area. The download tells the OpenStreetMap Overpass server
+ * which area you're looking at (like map tiles do) - nothing else is sent.
+ */
+object AlprStore {
+
+ private const val FILE = "known_alpr.json"
+ private const val ENDPOINT = "https://overpass-api.de/api/interpreter"
+ /** Largest area one download may cover (degrees of latitude / longitude). */
+ const val MAX_SPAN_DEG = 2.0
+
+ private val gson = Gson()
+ private val listType = object : TypeToken<List<KnownCamera>>() {}.type
+
+ @Volatile var cameras: List<KnownCamera> = emptyList()
+ private set
+
+ private fun file(context: Context) = File(context.filesDir, FILE)
+
+ fun load(context: Context) {
+ cameras = runCatching {
+ file(context).takeIf { it.exists() }?.readText()?.let { gson.fromJson<List<KnownCamera>>(it, listType) }
+ }.getOrNull().orEmpty()
+ }
+
+ /**
+ * Downloads the cameras in a bounding box and merges them into the cache
+ * (cameras deleted from OSM inside the box are dropped). Returns how many
+ * cameras the box contains.
+ */
+ suspend fun download(context: Context, south: Double, west: Double, north: Double, east: Double): Int =
+ withContext(Dispatchers.IO) {
+ require(north - south <= MAX_SPAN_DEG && east - west <= MAX_SPAN_DEG) { "Area too large - zoom in" }
+ val body = "data=" + URLEncoder.encode(KnownCameras.query(south, west, north, east), "UTF-8")
+ val conn = (URL(ENDPOINT).openConnection() as HttpURLConnection).apply {
+ requestMethod = "POST"
+ doOutput = true
+ connectTimeout = 20_000
+ readTimeout = 120_000
+ setRequestProperty("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")
+ setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
+ }
+ try {
+ conn.outputStream.use { it.write(body.toByteArray()) }
+ if (conn.responseCode != 200) error("OpenStreetMap server busy (HTTP ${conn.responseCode}) - try again later")
+ val found = KnownCameras.parse(conn.inputStream.bufferedReader().use { it.readText() })
+ val inBox = { c: KnownCamera -> c.lat in south..north && c.lon in west..east }
+ val merged = cameras.filterNot(inBox) + found
+ file(context).writeText(gson.toJson(merged))
+ cameras = merged
+ found.size
+ } finally {
+ conn.disconnect()
+ }
+ }
+
+ fun clear(context: Context) {
+ file(context).delete()
+ cameras = emptyList()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt b/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt
new file mode 100644
index 0000000..c60005b
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt
@@ -0,0 +1,87 @@
+package com.rfsentinel.app.alpr
+
+import com.google.gson.JsonParser
+import com.rfsentinel.app.service.DeviceRegistry
+import kotlin.math.cos
+import kotlin.math.max
+
+/**
+ * Plate-reader (ALPR) cameras mapped in OpenStreetMap - most famously by the
+ * DeFlock project - with the tag `surveillance:type=ALPR`. Most plate readers
+ * send their data over cellular and have no radio signature a phone can hear,
+ * so a map of known locations is the only way to warn about them.
+ *
+ * Pure Kotlin (parsing and geometry), so it's unit-tested on the JVM.
+ * Data © OpenStreetMap contributors, ODbL.
+ */
+data class KnownCamera(
+ val osmId: String,
+ val lat: Double,
+ val lon: Double,
+ val brand: String?,
+ val operator: String?,
+ /** Direction the camera faces, degrees from north, when mapped. */
+ val direction: Int?
+) {
+ val label: String get() = (brand ?: "Plate reader") + " (ALPR)"
+}
+
+object KnownCameras {
+
+ /** Overpass QL for every mapped plate reader in a bounding box. */
+ fun query(south: Double, west: Double, north: Double, east: Double): String =
+ "[out:json][timeout:90];nwr[\"surveillance:type\"=\"ALPR\"]" +
+ "($south,$west,$north,$east);out center tags;"
+
+ /** Parses an Overpass JSON response (nodes, and ways/relations via their centre). */
+ fun parse(json: String): List<KnownCamera> {
+ val root = JsonParser.parseString(json).asJsonObject
+ val elements = root.getAsJsonArray("elements") ?: return emptyList()
+ return elements.mapNotNull { el ->
+ val o = el.asJsonObject
+ val type = o.get("type")?.asString ?: return@mapNotNull null
+ val id = o.get("id")?.asLong ?: return@mapNotNull null
+ val pos = if (o.has("lat")) o else o.getAsJsonObject("center") ?: return@mapNotNull null
+ val lat = pos.get("lat")?.asDouble ?: return@mapNotNull null
+ val lon = pos.get("lon")?.asDouble ?: return@mapNotNull null
+ val tags = o.getAsJsonObject("tags")
+ fun tag(vararg keys: String) = keys.firstNotNullOfOrNull { k -> tags?.get(k)?.asString?.takeIf { it.isNotBlank() } }
+ KnownCamera(
+ osmId = "$type/$id", lat = lat, lon = lon,
+ brand = tag("manufacturer", "brand"),
+ operator = tag("operator"),
+ direction = parseDirection(tag("camera:direction", "direction"))
+ )
+ }
+ }
+
+ private val CARDINAL = mapOf(
+ "N" to 0, "NNE" to 22, "NE" to 45, "ENE" to 67, "E" to 90, "ESE" to 112, "SE" to 135, "SSE" to 157,
+ "S" to 180, "SSW" to 202, "SW" to 225, "WSW" to 247, "W" to 270, "WNW" to 292, "NW" to 315, "NNW" to 337
+ )
+
+ /** "135", "135.5", "SE" or "90;270" (first value) -> degrees; null otherwise. */
+ fun parseDirection(v: String?): Int? {
+ val first = v?.split(';')?.firstOrNull()?.trim()?.uppercase() ?: return null
+ first.toDoubleOrNull()?.let { return ((it % 360 + 360) % 360).toInt() }
+ return CARDINAL[first]
+ }
+
+ /**
+ * Warning distance: at least 150 m, or ~20 s of travel at your speed
+ * (capped at 600 m), so there's time to notice on a highway.
+ */
+ fun warnRadius(speedMs: Float?): Double = max(150.0, minOf(600.0, (speedMs ?: 0f) * 20.0))
+
+ /** 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.0
+ val dLon = radiusM / (111_000.0 * max(0.01, cos(Math.toRadians(lat))))
+ return cameras.asSequence()
+ .filter { kotlin.math.abs(it.lat - lat) <= dLat && kotlin.math.abs(it.lon - lon) <= dLon }
+ .map { it to DeviceRegistry.metersBetween(lat, lon, it.lat, it.lon) }
+ .filter { it.second <= radiusM }
+ .sortedBy { it.second }
+ .toList()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 656a763..d5cffe6 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -26,6 +26,8 @@ import androidx.annotation.VisibleForTesting
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import com.rfsentinel.app.RFSentinelApp
+import com.rfsentinel.app.alpr.AlprStore
+import com.rfsentinel.app.alpr.KnownCameras
import com.rfsentinel.app.data.AppDatabase
import com.rfsentinel.app.data.DetectionEntity
import com.rfsentinel.app.data.KnownDeviceEntity
@@ -81,6 +83,7 @@ class ScanForegroundService : Service() {
private const val WAKE_SLICE_MS = 10_000L
private const val HISTORY_FLUSH_MS = 60_000L
private const val DRONE_OVERHEAD_REPEAT_MS = 5 * 60_000L
+ private const val KNOWN_ALPR_REPEAT_MS = 30 * 60_000L
/** True while an instance is alive in this process. Source of truth for the UI. */
@Volatile
@@ -128,8 +131,13 @@ class ScanForegroundService : Service() {
private val locationListener = LocationListener {
lastLocation = it
TripRecorder.onLocation(it)
+ checkKnownAlpr(it)
}
+ /** Known plate cameras: distance at the previous fix, and when each last alerted. */
+ private val alprLastDistance = HashMap<String, Double>()
+ private val alprLastAlert = HashMap<String, Long>()
+
/** Starts BLE scanning if the user turns Bluetooth on after the service started. */
private val btStateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
@@ -162,7 +170,9 @@ class ScanForegroundService : Service() {
stopSelf()
return START_NOT_STICKY
}
- if (intent?.action == ACTION_REFRESH_LOCATION && isRunning) {
+ if (intent?.action == ACTION_REFRESH_LOCATION) {
+ // A settings refresh must never start a scan by itself.
+ if (!isRunning) { stopSelf(); return START_NOT_STICKY }
updateLocationUpdates()
return START_STICKY
}
@@ -279,8 +289,10 @@ class ScanForegroundService : Service() {
@SuppressLint("MissingPermission") // checked by hasFineLocation()
fun updateLocationUpdates() {
val wanted = hasFineLocation() &&
- (Prefs.gpsTaggingEnabled(this) || Prefs.followerAlerts(this) || TripRecorder.isRecording)
- val fast = TripRecorder.isRecording
+ (Prefs.gpsTaggingEnabled(this) || Prefs.followerAlerts(this) || TripRecorder.isRecording || knownAlprActive())
+ // Frequent fixes while recording a trace or watching for known plate cameras
+ // (at highway speed a 20 s interval could skip right past one).
+ val fast = TripRecorder.isRecording || knownAlprActive()
val lm = getSystemService(LOCATION_SERVICE) as LocationManager
if (locationListening && (!wanted || fast != locationFastMode)) {
lm.removeUpdates(locationListener)
@@ -414,6 +426,39 @@ class ScanForegroundService : Service() {
AlertPlayer.play(this, best.tier, "${best.label} nearby")
}
+ private fun knownAlprActive() = Prefs.knownAlprAlerts(this) &&
+ Prefs.categoryEnabled(this, Category.ALPR) && AlprStore.cameras.isNotEmpty()
+
+ /**
+ * Warns once (per camera, per 30 minutes) when you're approaching a plate
+ * reader mapped in OpenStreetMap: within ~20 s of travel and getting closer.
+ * Runs on the main thread with each location fix; the lookup is a cheap
+ * bounding-box filter.
+ */
+ private fun checkKnownAlpr(loc: Location) {
+ if (!knownAlprActive()) return
+ val now = System.currentTimeMillis()
+ val radius = KnownCameras.warnRadius(if (loc.hasSpeed()) loc.speed else null)
+ val near = KnownCameras.near(AlprStore.cameras, loc.latitude, loc.longitude, radius)
+ val nearIds = near.map { it.first.osmId }.toSet()
+ alprLastDistance.keys.retainAll(nearIds)
+ for ((cam, d) in near) {
+ val prev = alprLastDistance.put(cam.osmId, d)
+ val approaching = prev == null || d < prev - 3
+ if (!approaching || now - (alprLastAlert[cam.osmId] ?: 0L) < KNOWN_ALPR_REPEAT_MS) continue
+ alprLastAlert[cam.osmId] = now
+ val hit = Hit(
+ Category.ALPR, "Known plate camera ahead", 80,
+ "${cam.label}, ~${d.toInt()} m away" + (cam.operator?.let { ", operated by $it" } ?: "") +
+ ". Mapped in OpenStreetMap - it may not broadcast any signal.",
+ "OpenStreetMap (surveillance:type=ALPR), ODbL"
+ )
+ NotificationHelper.sendMapAlert(this, "alpr:" + cam.osmId, hit)
+ AlertPlayer.play(this, hit.tier, "Plate camera ahead")
+ break // one warning per fix is enough
+ }
+ }
+
/** Remote ID puts the drone within ~200 m of you: alert once per drone per 5 minutes. */
private fun maybeAlertDroneOverhead(a: Advert, info: RemoteId.Info, loc: Location, now: Long) {
if (!Prefs.categoryEnabled(this, Category.DRONE) || WhitelistCache.contains(a.mac)) return
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index 91c1157..397bd42 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -135,6 +135,7 @@ class SettingsActivity : AppCompatActivity() {
binding.followMetersInput.setText(Prefs.followMinMeters(this).toString())
binding.gpsSwitch.isChecked = Prefs.gpsTaggingEnabled(this)
binding.autoRecordSwitch.isChecked = Prefs.autoRecordTrace(this)
+ binding.knownAlprSwitch.isChecked = Prefs.knownAlprAlerts(this)
// Data
binding.retentionInput.setText(Prefs.retentionDays(this).toString())
@@ -261,6 +262,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setFollowMinMeters(this, (binding.followMetersInput.text.toString().toIntOrNull() ?: 800).coerceIn(100, 50_000))
Prefs.setGpsTaggingEnabled(this, binding.gpsSwitch.isChecked)
Prefs.setAutoRecordTrace(this, binding.autoRecordSwitch.isChecked)
+ Prefs.setKnownAlprAlerts(this, binding.knownAlprSwitch.isChecked)
Prefs.setRetentionDays(this, (binding.retentionInput.text.toString().toIntOrNull() ?: 90).coerceAtLeast(0))
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
index 74ac0c5..1db2f8f 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
@@ -83,6 +83,9 @@ class MapActivity : AppCompatActivity() {
private val pins = FolderOverlay()
/** Live drones from Remote ID: aircraft, operator and the line between them. */
private val drones = FolderOverlay()
+ /** Plate-reader cameras mapped in OpenStreetMap (downloaded on request). */
+ private val knownAlpr = FolderOverlay()
+ private var knownAlprDrawnFor: BoundingBox? = null
private lateinit var myLocation: MyLocationNewOverlay
private val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
@@ -110,6 +113,7 @@ class MapActivity : AppCompatActivity() {
}
setupMap()
+ binding.map.post { drawKnownAlpr() }
binding.showAllChip.setOnCheckedChangeListener { _, checked ->
showAll = checked
if (tripId != null) loadTrip() else renderLive()
@@ -146,9 +150,15 @@ class MapActivity : AppCompatActivity() {
color = if (tripId == null) TRACE_COLOR else PAST_TRACE_COLOR
strokeWidth = 7f * resources.displayMetrics.density / 2
}
+ map.overlays.add(knownAlpr)
map.overlays.add(trace)
map.overlays.add(pins)
map.overlays.add(drones)
+ // Redraw the camera layer for the visible area after panning / zooming.
+ map.addMapListener(object : org.osmdroid.events.MapListener {
+ override fun onScroll(event: org.osmdroid.events.ScrollEvent?) = false.also { drawKnownAlprSoon() }
+ override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also { drawKnownAlprSoon() }
+ })
myLocation = MyLocationNewOverlay(GpsMyLocationProvider(this), map)
if (Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
@@ -277,6 +287,8 @@ class MapActivity : AppCompatActivity() {
/** Tells the running service to switch location updates to trace mode (or back). */
private fun refreshServiceLocation() {
+ // Only a running scanner needs refreshing; sending it otherwise would start scanning.
+ if (!ScanForegroundService.isRunning) return
runCatching {
startService(Intent(this, ScanForegroundService::class.java).setAction(ScanForegroundService.ACTION_REFRESH_LOCATION))
}
@@ -444,6 +456,111 @@ class MapActivity : AppCompatActivity() {
return bmp
}
+ // ---- Known plate cameras (OpenStreetMap) --------------------------------------------
+
+ private val redrawKnownAlpr = Runnable { drawKnownAlpr() }
+
+ private fun drawKnownAlprSoon() {
+ binding.map.removeCallbacks(redrawKnownAlpr)
+ binding.map.postDelayed(redrawKnownAlpr, 250)
+ }
+
+ /** Draws the cameras in (and just around) the visible area; skipped when zoomed far out. */
+ private fun drawKnownAlpr() {
+ val map = binding.map
+ knownAlpr.items.clear()
+ if (!com.rfsentinel.app.util.Prefs.showKnownAlpr(this) || map.zoomLevelDouble < 10.0) {
+ map.invalidate(); return
+ }
+ val box = map.boundingBox.increaseByScale(1.5f)
+ val inView = com.rfsentinel.app.alpr.AlprStore.cameras.filter {
+ it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast
+ }.take(1500)
+ val dp = resources.displayMetrics.density
+ val icon = android.graphics.drawable.BitmapDrawable(resources, cameraIcon(dp))
+ for (cam in inView) {
+ knownAlpr.add(Marker(map).apply {
+ position = GeoPoint(cam.lat, cam.lon)
+ this.icon = icon
+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
+ title = cam.label
+ setOnMarkerClickListener { _, _ -> showKnownCamera(cam); true }
+ })
+ }
+ knownAlprDrawnFor = box
+ map.invalidate()
+ }
+
+ /** A small red camera glyph, distinct from the round device dots. */
+ private fun cameraIcon(dp: Float): android.graphics.Bitmap {
+ val w = (22 * dp).toInt(); val h = (16 * dp).toInt()
+ val bmp = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)
+ val c = android.graphics.Canvas(bmp)
+ val p = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)
+ val body = android.graphics.RectF(1 * dp, 3 * dp, w - 1 * dp, h - 1 * dp)
+ p.color = 0xFFB3261E.toInt(); c.drawRoundRect(body, 3 * dp, 3 * dp, p)
+ p.style = android.graphics.Paint.Style.STROKE; p.strokeWidth = 1.5f * dp; p.color = Color.WHITE
+ c.drawRoundRect(body, 3 * dp, 3 * dp, p)
+ c.drawCircle(w / 2f, (h + 2 * dp) / 2f, 3.5f * dp, p)
+ return bmp
+ }
+
+ private fun showKnownCamera(cam: com.rfsentinel.app.alpr.KnownCamera) {
+ val text = buildString {
+ append("A license-plate reader mapped in OpenStreetMap.\n\n")
+ cam.brand?.let { append("Maker: $it\n") }
+ cam.operator?.let { append("Operator: $it\n") }
+ cam.direction?.let { append("Faces: $it°\n") }
+ append("OSM: ${cam.osmId}\n\n")
+ append("Most plate readers send their data over cellular and have no Bluetooth/WiFi signature, so they can't be detected by radio - this map is the only warning.\n\nMap data © OpenStreetMap contributors (ODbL).")
+ }
+ AlertDialog.Builder(this)
+ .setTitle(cam.label)
+ .setMessage(text)
+ .setPositiveButton("Close", null)
+ .setNeutralButton("Open in OpenStreetMap") { _, _ ->
+ runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${cam.osmId}"))) }
+ }
+ .show()
+ }
+
+ /** Downloads the known cameras for the visible area, after saying what that reveals. */
+ private fun downloadKnownAlpr() {
+ val box = binding.map.boundingBox
+ val span = com.rfsentinel.app.alpr.AlprStore.MAX_SPAN_DEG
+ if (box.latNorth - box.latSouth > span || box.lonEast - box.lonWest > span) {
+ Toast.makeText(this, "Zoom in first: one download covers up to about 200 km", Toast.LENGTH_LONG).show()
+ return
+ }
+ AlertDialog.Builder(this)
+ .setTitle("Download known plate cameras?")
+ .setMessage(
+ "Fetches the license-plate readers mapped in OpenStreetMap for the area on screen, " +
+ "then keeps them on this phone for offline warnings.\n\n" +
+ "Privacy: the OpenStreetMap server (overpass-api.de) sees this area and your IP address, " +
+ "like when loading map tiles. Nothing about your scans is sent."
+ )
+ .setPositiveButton("Download") { _, _ ->
+ binding.statusText.text = "Downloading known plate cameras..."
+ lifecycleScope.launch {
+ val result = runCatching {
+ com.rfsentinel.app.alpr.AlprStore.download(this@MapActivity, box.latSouth, box.lonWest, box.latNorth, box.lonEast)
+ }
+ result.onSuccess { n ->
+ val total = com.rfsentinel.app.alpr.AlprStore.cameras.size
+ Toast.makeText(this@MapActivity, "$n plate cameras in this area ($total saved in total)", Toast.LENGTH_LONG).show()
+ com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this@MapActivity, true)
+ drawKnownAlpr()
+ refreshServiceLocation() // start watching for them while scanning
+ }.onFailure { e ->
+ Toast.makeText(this@MapActivity, "Download failed: ${e.message ?: "no connection"}", Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
private fun showPin(p: Pin) {
AlertDialog.Builder(this)
.setTitle(p.label)
@@ -462,6 +579,11 @@ class MapActivity : AppCompatActivity() {
menu.add(0, 3, 2, "Delete")
} else {
menu.add(0, 4, 0, "Recorded traces")
+ menu.add(0, 5, 1, "Download known plate cameras here")
+ menu.add(0, 6, 2, "Show known plate cameras").apply {
+ isCheckable = true; isChecked = com.rfsentinel.app.util.Prefs.showKnownAlpr(this@MapActivity)
+ }
+ menu.add(0, 7, 3, "Delete downloaded plate cameras")
}
return true
}
@@ -473,6 +595,18 @@ class MapActivity : AppCompatActivity() {
2 -> { id?.let { rename(it) }; true }
3 -> { id?.let { confirmDelete(it) }; true }
4 -> { startActivity(Intent(this, TripsActivity::class.java)); true }
+ 5 -> { downloadKnownAlpr(); true }
+ 6 -> {
+ val show = !com.rfsentinel.app.util.Prefs.showKnownAlpr(this)
+ com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this, show)
+ item.isChecked = show
+ drawKnownAlpr(); true
+ }
+ 7 -> {
+ com.rfsentinel.app.alpr.AlprStore.clear(this)
+ drawKnownAlpr(); refreshServiceLocation()
+ Toast.makeText(this, "Downloaded plate cameras deleted", Toast.LENGTH_SHORT).show(); true
+ }
android.R.id.home -> { finish(); true }
else -> super.onOptionsItemSelected(item)
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
index ccef746..d555964 100644
--- a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
@@ -92,6 +92,45 @@ object NotificationHelper {
}
}
+ /**
+ * Posts an alert about a mapped place rather than a device (e.g. a known plate
+ * camera): tapping it opens the map. Sound/vibration/voice are played by the caller.
+ */
+ fun sendMapAlert(context: Context, key: String, hit: Hit) {
+ val nm = context.getSystemService(NotificationManager::class.java)
+ val discreet = Prefs.discreetMode(context)
+ val open = PendingIntent.getActivity(
+ context, key.hashCode(),
+ Intent(context, com.rfsentinel.app.ui.MapActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ val builder = NotificationCompat.Builder(context, CHANNEL_ALERTS)
+ .setContentTitle(if (discreet) "RF Sentinel" else hit.label)
+ .setContentText(if (discreet) "New alert - tap to view" else hit.evidence)
+ .setStyle(if (discreet) null else NotificationCompat.BigTextStyle().bigText(hit.evidence))
+ .setSmallIcon(R.drawable.ic_tile_scan)
+ .setColor(hit.category.colorArgb)
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
+ .setCategory(NotificationCompat.CATEGORY_ALARM)
+ .setAutoCancel(true)
+ .setSilent(true)
+ .setContentIntent(open)
+ .setVisibility(if (discreet) NotificationCompat.VISIBILITY_SECRET else NotificationCompat.VISIBILITY_PRIVATE)
+ .extend(
+ CarAppExtender.Builder()
+ .setContentTitle(if (discreet) "RF Sentinel" else hit.label)
+ .setContentText(if (discreet) "New alert" else hit.evidence)
+ .setSmallIcon(R.drawable.ic_tile_scan)
+ .setImportance(NotificationManagerCompat.IMPORTANCE_HIGH)
+ .build()
+ )
+ try {
+ nm.notify(ALERT_NOTIFICATION_ID_BASE + key.hashCode(), builder.build())
+ } catch (e: SecurityException) {
+ // POST_NOTIFICATIONS denied - sound and voice still alert.
+ }
+ }
+
/** 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) {
val nm = context.getSystemService(NotificationManager::class.java)
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index fb46236..1674650 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -89,6 +89,12 @@ object Prefs {
fun setFollowerAlerts(context: Context, value: Boolean) = setBool(context, "follower_alerts", value)
/** Start recording a trace automatically whenever scanning starts. */
+ /** Warn when approaching a plate reader mapped in OpenStreetMap (needs downloaded data). */
+ fun knownAlprAlerts(context: Context): Boolean = bool(context, "known_alpr_alerts", true)
+ fun setKnownAlprAlerts(context: Context, value: Boolean) = setBool(context, "known_alpr_alerts", value)
+ fun showKnownAlpr(context: Context): Boolean = bool(context, "show_known_alpr", true)
+ fun setShowKnownAlpr(context: Context, value: Boolean) = setBool(context, "show_known_alpr", value)
+
fun autoRecordTrace(context: Context): Boolean = bool(context, "auto_record_trace", false)
fun setAutoRecordTrace(context: Context, value: Boolean) = setBool(context, "auto_record_trace", value)
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 70cc489..a24da5b 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -267,6 +267,12 @@
</LinearLayout>
</LinearLayout>
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/knownAlprSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Warn when approaching a known plate-reader camera (download them on the map: menu, Known plate cameras)" />
+
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/autoRecordSwitch"
android:layout_width="match_parent"
diff --git a/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.kt b/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.kt
new file mode 100644
index 0000000..d0efc9b
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.kt
@@ -0,0 +1,60 @@
+package com.rfsentinel.app.alpr
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class KnownCamerasTest {
+
+ // Synthetic positions (not real places).
+ private val sample = """
+ {"elements":[
+ {"type":"node","id":101,"lat":10.5000,"lon":-20.5000,
+ "tags":{"surveillance:type":"ALPR","manufacturer":"Flock Safety","operator":"Example PD","direction":"135"}},
+ {"type":"way","id":202,"center":{"lat":10.5020,"lon":-20.5000},
+ "tags":{"surveillance:type":"ALPR","brand":"Motorola","camera:direction":"SE"}},
+ {"type":"node","id":303,"tags":{"surveillance:type":"ALPR"}}
+ ]}
+ """.trimIndent()
+
+ @Test
+ fun parsesNodesAndWayCentres() {
+ val cams = KnownCameras.parse(sample)
+ assertEquals(2, cams.size) // the element without a position is skipped
+ val flock = cams.first { it.osmId == "node/101" }
+ assertEquals("Flock Safety (ALPR)", flock.label)
+ assertEquals("Example PD", flock.operator)
+ assertEquals(135, flock.direction)
+ val way = cams.first { it.osmId == "way/202" }
+ assertEquals(10.5020, way.lat, 1e-9)
+ assertEquals(135, way.direction) // "SE"
+ }
+
+ @Test
+ fun directionsAndQuery() {
+ assertEquals(90, KnownCameras.parseDirection("90;270"))
+ assertEquals(350, KnownCameras.parseDirection("-10"))
+ assertEquals(0, KnownCameras.parseDirection("n"))
+ assertNull(KnownCameras.parseDirection("forward"))
+ val q = KnownCameras.query(1.0, 2.0, 3.0, 4.0)
+ assertTrue(q.contains("\"surveillance:type\"=\"ALPR\"") && q.contains("(1.0,2.0,3.0,4.0)"))
+ }
+
+ @Test
+ fun warnRadiusScalesWithSpeed() {
+ assertEquals(150.0, KnownCameras.warnRadius(null), 0.0)
+ assertEquals(150.0, KnownCameras.warnRadius(3f), 0.0) // walking
+ assertEquals(400.0, KnownCameras.warnRadius(20f), 0.0) // 72 km/h
+ assertEquals(600.0, KnownCameras.warnRadius(40f), 0.0) // capped
+ }
+
+ @Test
+ fun nearFindsCamerasInRadiusNearestFirst() {
+ val cams = KnownCameras.parse(sample)
+ val found = KnownCameras.near(cams, 10.5010, -20.5000, 150.0) // ~111 m from each
+ assertEquals(2, found.size)
+ assertTrue(found[0].second <= found[1].second)
+ assertTrue(KnownCameras.near(cams, 10.6, -20.5, 150.0).isEmpty())
+ }
+}