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
WiGLE: 60 s for an answer, live search steps; By device fills from lists saved before
CIS-C06dc3235997a8
diff --git a/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt b/app/src/main/java/com/rfsentinel/app/data/ProbeLog.ktindex e0c41f8..c2df4f3 100644--- a/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt+++ b/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt@@ -82,6 +82,8 @@ object ProbeLog {book.restoreDevices(list.orEmpty())}}+ // Lists saved before devices were kept (or a device file lost) still show who asked.+ if (book.backfillDevices()) dirty = true}private fun save(context: Context, now: Long = System.currentTimeMillis()) {@@ -238,6 +240,29 @@ class ProbeBook(private val maxNetworks: Int = 1000, private val maxDevices: Int}}+ /**+ * Adds every address a network lists as having asked for it to that device's record, creating the+ * record from the network's times when missing (no WPS or fingerprint: those weren't kept). Returns+ * whether anything was added.+ */+ fun backfillDevices(): Boolean {+ var added = false+ for (n in nets.values.sortedBy { it.lastSeen }) for (mac in n.devices) {+ val m = mac.uppercase()+ val d = probers[m] ?: Device(m, n.firstSeen, n.lastSeen, 1, n.lastRssi, mutableListOf()).also { probers[m] = it; added = true }+ if (d.ssids.none { it.equals(n.ssid, ignoreCase = true) }) {+ d.ssids.add(n.ssid); added = true+ d.firstSeen = minOf(d.firstSeen, n.firstSeen)+ if (n.lastSeen > d.lastSeen) { d.lastSeen = n.lastSeen; d.lastRssi = n.lastRssi }+ }+ while (d.ssids.size > maxDevices) d.ssids.removeAt(0)+ }+ if (probers.size > maxProbers) {+ probers.values.sortedBy { it.lastSeen }.take(probers.size - maxProbers).forEach { probers.remove(it.mac) }+ }+ return added+ }+fun restore(list: List<Network>) {nets.clear()@Suppress("SENSELESS_COMPARISON", "USELESS_ELVIS") // Gson can leave fields nulldiff --git a/app/src/main/java/com/rfsentinel/app/online/Wigle.kt b/app/src/main/java/com/rfsentinel/app/online/Wigle.ktindex 5f567fc..3891970 100644--- a/app/src/main/java/com/rfsentinel/app/online/Wigle.kt+++ b/app/src/main/java/com/rfsentinel/app/online/Wigle.kt@@ -125,40 +125,74 @@ object Wigle {return max(o.optInt("totalResults", nets.size), nets.size) to nets}+ /** How long WiGLE gets to answer: a search near you over a big area can take it well over 20 s. */+ const val ANSWER_TIMEOUT_MS = 60_000+ private const val TAG = "Wigle"+/*** Searches WiGLE for [text] (a name, or an address), within [NEAR_KM] of [near] when given- * (rounded first). The same search within a day is answered from this phone.+ * (rounded first). The same search within a day is answered from this phone. [status] hears each+ * step (on this IO thread), for the progress screen. The log gets only the outcome and timings,+ * never what was searched or where.*/- suspend fun search(context: Context, text: String, near: Pair<Double, Double>?): Answer = withContext(Dispatchers.IO) {+ suspend fun search(context: Context, text: String, near: Pair<Double, Double>?,+ status: (String) -> Unit = {}): Answer = withContext(Dispatchers.IO) {val area = near?.let { snap(it.first, it.second) }val key = (if (isBssid(text)) bssid(text) else text.trim()) + "|" + (area?.let { "${it.first},${it.second}" } ?: "world")val now = System.currentTimeMillis()- cached(context, key, now)?.let { return@withContext Answer(it.nets, it.total, area != null, cached = true) }+ status(if (isBssid(text)) "Address ${bssid(text)}" else if ('*' in text) "Name like \"${text.trim()}\"" else "Name \"${text.trim()}\"")+ status(area?.let { String.format(Locale.US, "Area: %.1f, %.1f ± %.0f km (your position rounded to ~10 km)", it.first, it.second, NEAR_KM) }+ ?: "Area: worldwide")+ cached(context, key, now)?.let {+ status("Answered from this phone: the same search was done ${ago(now - it.at)} ago (WiGLE not asked)")+ return@withContext Answer(it.nets, it.total, area != null, cached = true)+ }+ status("No saved answer from today: asking WiGLE")val authHeader = auth(context) ?: throw Failure("Enter your WiGLE API name and token first")val c = (URL(url(text, area)).openConnection() as HttpURLConnection).apply {- connectTimeout = 10_000- readTimeout = 20_000+ connectTimeout = 15_000+ readTimeout = ANSWER_TIMEOUT_MSsetRequestProperty("Authorization", authHeader)setRequestProperty("Accept", "application/json")setRequestProperty("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")}+ val start = android.os.SystemClock.elapsedRealtime()+ fun secs() = String.format(Locale.US, "%.1f s", (android.os.SystemClock.elapsedRealtime() - start) / 1000.0)val body = try {- when (c.responseCode) {+ status("Connecting to api.wigle.net…")+ c.connect()+ status("Connected in ${secs()}. Waiting for WiGLE to search its database…")+ val code = c.responseCode+ status("WiGLE answered HTTP $code after ${secs()}")+ when (code) {200 -> c.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }+ .also { status("Downloaded ${(it.length + 1023) / 1024} KB in ${secs()}") }401, 403 -> throw Failure("WiGLE didn't accept the API name and token")429 -> throw Failure("WiGLE's search limit for today is used up (new accounts get only a few searches a day)")- else -> throw Failure("WiGLE answered HTTP ${c.responseCode}")+ else -> throw Failure("WiGLE answered HTTP $code")}+ } catch (e: java.net.SocketTimeoutException) {+ android.util.Log.w(TAG, "search timed out after ${secs()}")+ throw Failure("WiGLE took too long to answer (no answer in ${ANSWER_TIMEOUT_MS / 1000} s). " ++ "Its servers may be busy: try again later.")} catch (e: java.io.IOException) {+ android.util.Log.w(TAG, "search failed after ${secs()}: ${e.javaClass.simpleName}")throw Failure("Couldn't reach WiGLE: ${e.message ?: "no connection"}")+ } catch (e: Failure) {+ android.util.Log.w(TAG, "search refused after ${secs()}: HTTP ${runCatching { c.responseCode }.getOrNull()}")+ throw e} finally {c.disconnect()}val (total, nets) = parse(body)+ status("Read ${nets.size} networks with a position (WiGLE has $total in all)")+ android.util.Log.i(TAG, "search answered in ${secs()}: ${nets.size} of $total")remember(context, key, Cached(now, total, nets))Answer(nets, total, area != null, cached = false)}+ private fun ago(ms: Long) = if (ms < 3_600_000) "${ms / 60_000} min" else "${ms / 3_600_000} h"+@Synchronizedprivate fun cached(context: Context, key: String, now: Long): Cached? =load(context)[key]?.takeIf { now - it.at < CACHE_MS }diff --git a/app/src/main/java/com/rfsentinel/app/probes/WigleUi.kt b/app/src/main/java/com/rfsentinel/app/probes/WigleUi.ktindex 277851d..ada36c5 100644--- a/app/src/main/java/com/rfsentinel/app/probes/WigleUi.kt+++ b/app/src/main/java/com/rfsentinel/app/probes/WigleUi.kt@@ -94,15 +94,38 @@ object WigleUi {if (!Wigle.hasAccount(a)) { account(a) { search(a, text, worldwide) }; return }val me = myPosition(a)val near = if (worldwide) null else me+ // Every step as it happens, and how long WiGLE has been at it.+ val dp = a.resources.displayMetrics.density+ val steps = mutableListOf<String>()+ val log = TextView(a).apply { textSize = 13f; setTextIsSelectable(true) }+ val clock = TextView(a).apply { textSize = 13f; alpha = 0.75f; setPadding(0, (8 * dp).toInt(), 0, 0) }+ val box = LinearLayout(a).apply {+ orientation = LinearLayout.VERTICAL+ val pad = (20 * dp).toInt(); setPadding(pad, (8 * dp).toInt(), pad, 0)+ addView(log); addView(clock)+ }+ var cancelled = falseval progress = MaterialAlertDialogBuilder(a)- .setTitle("Searching WiGLE…")- .setMessage(if (near != null) "\"$text\" within ${Wigle.NEAR_KM.toInt()} km of you" else "\"$text\" worldwide")+ .setTitle(if (near != null) "Searching WiGLE near you…" else "Searching WiGLE worldwide…")+ .setView(box).setCancelable(false)+ .setNegativeButton("Cancel") { _, _ -> cancelled = true }.show()+ fun step(s: String) = a.runOnUiThread { steps += "• $s"; log.text = steps.joinToString("\n") }+ val started = android.os.SystemClock.elapsedRealtime()+ val ticker = a.lifecycleScope.launch {+ while (true) {+ val s = (android.os.SystemClock.elapsedRealtime() - started) / 1000+ clock.text = "$s s of up to ${Wigle.ANSWER_TIMEOUT_MS / 1000} s"+ kotlinx.coroutines.delay(1000)+ }+ }a.lifecycleScope.launch {- val result = runCatching { Wigle.search(a, text, near) }+ val result = runCatching { Wigle.search(a, text, near, ::step) }+ ticker.cancel()progress.dismiss()- if (a.isFinishing || a.isDestroyed) return@launch+ // A cancelled search still keeps a good answer for the day; it just isn't shown.+ if (cancelled || a.isFinishing || a.isDestroyed) return@launchresult.onSuccess { answer ->if (answer.nets.isEmpty() && answer.near) {MaterialAlertDialogBuilder(a)@@ -117,7 +140,7 @@ object WigleUi {}.onFailure { e ->MaterialAlertDialogBuilder(a).setTitle("WiGLE search failed")- .setMessage(e.message ?: "Unknown error")+ .setMessage((e.message ?: "Unknown error") + "\n\nWhat happened:\n" + steps.joinToString("\n")).apply { if (e.message?.contains("API name") == true) setPositiveButton("Account") { _, _ -> account(a) } }.setNegativeButton("Close", null).show()diff --git a/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.kt b/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.ktindex 17abb4d..c4c9090 100644--- a/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.kt+++ b/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.kt@@ -74,4 +74,21 @@ class ProbeDevicesTest {b.restoreDevices(listOf(ProbeBook.Device("aa:bb:cc:dd:ee:ff", 1, 2, 1, -50, mutableListOf("X"))))assertEquals("AA:BB:CC:DD:EE:FF", b.devices().single().mac)}++ @Test+ fun aListSavedBeforeDevicesWereKeptStillShowsWhoAsked() {+ val b = ProbeBook()+ b.restore(listOf(+ ProbeBook.Network("Home", 100, 200, 1, -60, mutableListOf("AA:AA:AA:AA:AA:01", "AA:AA:AA:AA:AA:02")),+ ProbeBook.Network("Office", 50, 300, 2, -70, mutableListOf("aa:aa:aa:aa:aa:01"))+ ))+ assertTrue(b.backfillDevices())+ val first = b.devices().first { it.mac == "AA:AA:AA:AA:AA:01" }+ assertEquals(listOf("Home", "Office"), first.ssids)+ assertEquals(50L, first.firstSeen)+ assertEquals(300L, first.lastSeen)+ assertEquals(2, b.devices().size)+ // Run again: nothing new.+ assertFalse(b.backfillDevices())+ }}