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.

Requested networks: WiGLE search with map pins, and the list by device

CIS-C0b5fb32b214b7
diff --git a/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt b/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt
index cff9a6b..e0c41f8 100644
--- a/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/ProbeLog.kt
@@ -15,6 +15,7 @@ import java.io.File
object ProbeLog {
private const val FILE = "probed_networks.json"
+ private const val DEVICES_FILE = "probing_devices.json"
private const val SAVE_EVERY_MS = 30_000L
private val book = ProbeBook()
@@ -24,15 +25,18 @@ object ProbeLog {
private val gson = Gson()
/**
- * Records that [mac] asked for each of [ssids]. Only while recording is on, or [force]d:
- * a map trace recording keeps them too.
+ * Records that [mac] asked for each of [ssids], with what else its frames said about it ([wps],
+ * [fingerprint]: kept for a device that asked for a name). Only while recording is on, or
+ * [force]d: a map trace recording keeps them too.
*/
@Synchronized
fun record(context: Context, mac: String, ssids: Collection<String>, rssi: Int, now: Long = System.currentTimeMillis(),
- force: Boolean = false) {
- if (ssids.isEmpty() || !(force || com.rfsentinel.app.util.Prefs.recordProbes(context))) return
+ force: Boolean = false, wps: com.rfsentinel.app.usb.ProbeIntel.Wps? = null, fingerprint: String? = null) {
+ if (ssids.isEmpty() && wps == null && fingerprint == null) return
+ if (!(force || com.rfsentinel.app.util.Prefs.recordProbes(context))) return
ensureLoaded(context)
ssids.forEach { book.record(it, mac, rssi, now) }
+ if (!book.recordDevice(mac, ssids, rssi, now, wps?.deviceName, wps?.product, fingerprint)) return
dirty = true
if (now - lastSave > SAVE_EVERY_MS) save(context, now)
}
@@ -40,6 +44,17 @@ object ProbeLog {
@Synchronized
fun all(context: Context): List<ProbeBook.Network> { ensureLoaded(context); return book.all() }
+ /** The devices that asked, grouped ([ProbeBook.groups]), newest first. */
+ @Synchronized
+ fun groups(context: Context): List<ProbeBook.Group> {
+ ensureLoaded(context)
+ return book.groups({ com.rfsentinel.app.util.MacUtil.isRandomized(it) })
+ }
+
+ /** Recorded addresses whose probe requests have the fingerprint [fp]. */
+ @Synchronized
+ fun sharing(context: Context, fp: String): Int { ensureLoaded(context); return book.sharing(fp) }
+
@Synchronized
fun remove(context: Context, ssid: String) { ensureLoaded(context); book.remove(ssid); dirty = true; save(context) }
@@ -60,22 +75,34 @@ object ProbeLog {
book.restore(list.orEmpty())
}
}
+ runCatching {
+ val f = File(context.filesDir, DEVICES_FILE)
+ if (f.exists()) {
+ val list: List<ProbeBook.Device> = gson.fromJson(f.readText(), object : TypeToken<List<ProbeBook.Device>>() {}.type)
+ book.restoreDevices(list.orEmpty())
+ }
+ }
}
private fun save(context: Context, now: Long = System.currentTimeMillis()) {
lastSave = now
dirty = false
+ write(context, FILE, gson.toJson(book.all()))
+ write(context, DEVICES_FILE, gson.toJson(book.devices()))
+ }
+
+ private fun write(context: Context, name: String, text: String) {
runCatching {
- val f = File(context.filesDir, FILE)
- val tmp = File(context.filesDir, "$FILE.tmp")
- tmp.writeText(gson.toJson(book.all()))
+ val f = File(context.filesDir, name)
+ val tmp = File(context.filesDir, "$name.tmp")
+ tmp.writeText(text)
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
}
}
}
-/** The requested-network list itself (no Android), capped to the most recent names. */
-class ProbeBook(private val maxNetworks: Int = 1000, private val maxDevices: Int = 50) {
+/** The requested-network list itself (no Android), capped to the most recent names and devices. */
+class ProbeBook(private val maxNetworks: Int = 1000, private val maxDevices: Int = 50, private val maxProbers: Int = 2000) {
data class Network(
val ssid: String,
@@ -88,7 +115,37 @@ class ProbeBook(private val maxNetworks: Int = 1000, private val maxDevices: Int
val devices: MutableList<String>
)
+ /** A device that asked for networks: what it asked for and what its frames said about it. */
+ data class Device(
+ val mac: String,
+ var firstSeen: Long,
+ var lastSeen: Long,
+ /** Separate encounters: heard again after a [GAP_MS] pause. */
+ var encounters: Int,
+ var lastRssi: Int,
+ /** Network names it asked for, most recent last. */
+ val ssids: MutableList<String>,
+ /** The name its WPS block gave (e.g. a computer name). */
+ var wpsName: String? = null,
+ /** Maker, model and number from its WPS block. */
+ var wpsProduct: String? = null,
+ /** How it builds its probe requests ([com.rfsentinel.app.usb.ProbeIntel.fingerprint]). */
+ var fingerprint: String? = null
+ )
+
+ /**
+ * Devices shown together: one address, or random addresses with the same rare probe fingerprint that
+ * asked for a network name in common ([likelySame]).
+ */
+ data class Group(val devices: List<Device>, val likelySame: Boolean) {
+ val lastSeen get() = devices.maxOf { it.lastSeen }
+ /** Every name the group asked for, most recent first. */
+ val ssids: List<String> get() = devices.sortedByDescending { it.lastSeen }
+ .flatMap { it.ssids.reversed() }.distinctBy { it.lowercase() }
+ }
+
private val nets = LinkedHashMap<String, Network>()
+ private val probers = LinkedHashMap<String, Device>()
fun record(ssid: String, mac: String, rssi: Int, now: Long) {
val key = ssid.lowercase()
@@ -106,12 +163,80 @@ class ProbeBook(private val maxNetworks: Int = 1000, private val maxDevices: Int
while (n.devices.size > maxDevices) n.devices.removeAt(0)
}
+ /**
+ * Notes what [mac] asked for and said about itself. A device that never asked for a name isn't
+ * kept; returns false when nothing was noted.
+ */
+ fun recordDevice(mac: String, ssids: Collection<String>, rssi: Int, now: Long,
+ wpsName: String? = null, wpsProduct: String? = null, fingerprint: String? = null): Boolean {
+ val m = mac.uppercase()
+ val d = probers[m] ?: run {
+ if (ssids.isEmpty()) return false
+ Device(m, now, now, 1, rssi, mutableListOf()).also { probers[m] = it }
+ }
+ if (now - d.lastSeen > GAP_MS) d.encounters++
+ d.lastSeen = now
+ d.lastRssi = rssi
+ ssids.forEach { s -> d.ssids.removeAll { it.equals(s, ignoreCase = true) }; d.ssids.add(s) }
+ while (d.ssids.size > maxDevices) d.ssids.removeAt(0)
+ wpsName?.let { d.wpsName = it }
+ wpsProduct?.let { d.wpsProduct = it }
+ fingerprint?.let { d.fingerprint = it }
+ if (probers.size > maxProbers) {
+ probers.values.sortedBy { it.lastSeen }.take(probers.size - maxProbers).forEach { probers.remove(it.mac) }
+ }
+ return true
+ }
+
+ /** Newest first. */
+ fun devices(): List<Device> = probers.values.sortedByDescending { it.lastSeen }.map { it.copy(ssids = it.ssids.toMutableList()) }
+
+ /** Addresses whose probe requests have the fingerprint [fp]. */
+ fun sharing(fp: String): Int = probers.values.count { it.fingerprint == fp }
+
+ /**
+ * The devices as groups, newest first: random addresses ([isRandom]) with the same fingerprint, shared
+ * by at most [rareMax] addresses, that asked for at least one name in common are likely one device
+ * changing its address. Fixed addresses always stand alone.
+ */
+ fun groups(isRandom: (String) -> Boolean, rareMax: Int = 20): List<Group> {
+ val list = devices()
+ val counts = list.mapNotNull { it.fingerprint }.groupingBy { it }.eachCount()
+ val parent = IntArray(list.size) { it }
+ fun root(i: Int): Int { var r = i; while (parent[r] != r) r = parent[r]; return r }
+ list.indices
+ .filter { i -> list[i].fingerprint.let { it != null && counts.getValue(it) in 2..rareMax } && isRandom(list[i].mac) }
+ .groupBy { list[it].fingerprint }
+ .values.forEach { same ->
+ for (x in same.indices) for (y in x + 1 until same.size) {
+ val asked = list[same[x]].ssids.map { it.lowercase() }.toSet()
+ if (list[same[y]].ssids.any { it.lowercase() in asked }) parent[root(same[y])] = root(same[x])
+ }
+ }
+ return list.indices.groupBy { root(it) }.values
+ .map { idx -> Group(idx.map { list[it] }, likelySame = idx.size > 1) }
+ .sortedByDescending { it.lastSeen }
+ }
+
/** Newest first. */
fun all(): List<Network> = nets.values.sortedByDescending { it.lastSeen }.map { it.copy(devices = it.devices.toMutableList()) }
- fun remove(ssid: String) { nets.remove(ssid.lowercase()) }
+ /** Forgets [ssid], and the devices that asked for nothing else. */
+ fun remove(ssid: String) {
+ nets.remove(ssid.lowercase())
+ probers.values.forEach { d -> d.ssids.removeAll { it.equals(ssid, ignoreCase = true) } }
+ probers.values.removeAll { it.ssids.isEmpty() }
+ }
+
+ fun clear() { nets.clear(); probers.clear() }
- fun clear() = nets.clear()
+ fun restoreDevices(list: List<Device>) {
+ probers.clear()
+ @Suppress("SENSELESS_COMPARISON", "USELESS_ELVIS") // Gson can leave fields null
+ list.filter { it.mac != null }.forEach {
+ probers[it.mac.uppercase()] = it.copy(mac = it.mac.uppercase(), ssids = (it.ssids ?: mutableListOf()).toMutableList())
+ }
+ }
fun restore(list: List<Network>) {
nets.clear()
diff --git a/app/src/main/java/com/rfsentinel/app/online/Wigle.kt b/app/src/main/java/com/rfsentinel/app/online/Wigle.kt
new file mode 100644
index 0000000..5f567fc
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/online/Wigle.kt
@@ -0,0 +1,185 @@
+package com.rfsentinel.app.online
+
+import android.content.Context
+import android.util.Base64
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.rfsentinel.app.BuildConfig
+import com.rfsentinel.app.util.SecureStore
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+import java.io.File
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+import java.util.Locale
+import kotlin.math.cos
+import kotlin.math.max
+
+/**
+ * Where a WiFi network name (SSID) or access point address (BSSID) has been seen, from WiGLE's
+ * database of wardriving uploads (api.wigle.net, network/search). Needs the user's own WiGLE
+ * API name and token (wigle.net/account), stored encrypted on this phone. What's sent: the name
+ * or address searched and, for a search near you, a box around your position rounded to ~10 km.
+ * WiGLE gives new accounts only a few searches a day, so each answer is kept here for a day.
+ */
+object Wigle {
+
+ const val NAME_KEY = "wigle_api_name"
+ const val TOKEN_KEY = "wigle_api_token"
+
+ private const val ENDPOINT = "https://api.wigle.net/api/v2/network/search"
+ /** A search near you covers this far around you. */
+ const val NEAR_KM = 50.0
+ private const val RESULTS = 25
+ private const val CACHE_FILE = "wigle_cache.json"
+ private const val CACHE_MS = 24 * 3600_000L
+ private const val CACHE_MAX = 200
+
+ /** One access point WiGLE knows: [lat] / [lon] is its estimated position. */
+ data class Net(
+ val ssid: String?,
+ val bssid: String,
+ val lat: Double,
+ val lon: Double,
+ val encryption: String?,
+ val channel: Int?,
+ /** When WiGLE last saw it, as WiGLE writes it (e.g. "2025-06-01T12:00:00.000Z"). */
+ val lastSeen: String?,
+ /** Road, city, region and country, when WiGLE has them. */
+ val place: String?
+ )
+
+ data class Answer(val nets: List<Net>, val total: Int, val near: Boolean, val cached: Boolean)
+
+ class Failure(message: String) : Exception(message)
+
+ private data class Cached(val at: Long, val total: Int, val nets: List<Net>)
+
+ private val gson = Gson()
+ private var cache: MutableMap<String, Cached>? = null
+
+ fun hasAccount(context: Context) = auth(context) != null
+
+ private fun auth(context: Context): String? {
+ val name = SecureStore.get(context, NAME_KEY)?.trim()?.takeIf { it.isNotEmpty() } ?: return null
+ val token = SecureStore.get(context, TOKEN_KEY)?.trim()?.takeIf { it.isNotEmpty() } ?: return null
+ return "Basic " + Base64.encodeToString("$name:$token".toByteArray(), Base64.NO_WRAP)
+ }
+
+ /** True for an access point address: 12 hex digits, with or without ':' / '-' between pairs. */
+ fun isBssid(text: String): Boolean = BSSID.matches(text.trim())
+
+ private val BSSID = Regex("(?i)^[0-9a-f]{2}([:-]?[0-9a-f]{2}){5}$")
+
+ /** "aa-bb-cc..." or "aabbcc..." as "AA:BB:CC:DD:EE:FF". */
+ fun bssid(text: String): String =
+ text.trim().replace(":", "").replace("-", "").uppercase(Locale.US).chunked(2).joinToString(":")
+
+ /** ~10 km grid: the exact position never leaves the phone. */
+ fun snap(lat: Double, lon: Double) = Math.round(lat * 10) / 10.0 to Math.round(lon * 10) / 10.0
+
+ /**
+ * The search URL: an address by itself, a name exactly (or with * as a wildcard), within
+ * [NEAR_KM] of [near] when given.
+ */
+ internal fun url(text: String, near: Pair<Double, Double>?): String {
+ val q = StringBuilder(ENDPOINT).append("?onlymine=false&resultsPerPage=").append(RESULTS)
+ val t = text.trim()
+ when {
+ isBssid(t) -> q.append("&netid=").append(enc(bssid(t)))
+ '*' in t -> q.append("&ssidlike=").append(enc(t.replace('*', '%')))
+ else -> q.append("&ssid=").append(enc(t))
+ }
+ if (near != null) {
+ val (lat, lon) = near
+ val dLat = NEAR_KM / 111.0
+ val dLon = NEAR_KM / (111.0 * max(cos(Math.toRadians(lat)), 0.05))
+ fun f(v: Double) = String.format(Locale.US, "%.3f", v)
+ q.append("&latrange1=").append(f((lat - dLat).coerceIn(-90.0, 90.0)))
+ .append("&latrange2=").append(f((lat + dLat).coerceIn(-90.0, 90.0)))
+ .append("&longrange1=").append(f((lon - dLon).coerceIn(-180.0, 180.0)))
+ .append("&longrange2=").append(f((lon + dLon).coerceIn(-180.0, 180.0)))
+ }
+ return q.toString()
+ }
+
+ private fun enc(s: String) = URLEncoder.encode(s, "UTF-8")
+
+ /** WiGLE's answer: how many it has in all, and the ones sent (those without a position left out). */
+ internal fun parse(json: String): Pair<Int, List<Net>> {
+ val o = JSONObject(json)
+ if (!o.optBoolean("success", false)) throw Failure(o.optString("message").ifBlank { "WiGLE couldn't search" })
+ val arr = o.optJSONArray("results") ?: return 0 to emptyList()
+ val nets = (0 until arr.length()).mapNotNull { i ->
+ val r = arr.optJSONObject(i) ?: return@mapNotNull null
+ val lat = r.optDouble("trilat", Double.NaN); val lon = r.optDouble("trilong", Double.NaN)
+ val id = r.optString("netid").takeIf { it.isNotBlank() } ?: return@mapNotNull null
+ if (lat.isNaN() || lon.isNaN() || (lat == 0.0 && lon == 0.0)) return@mapNotNull null
+ fun s(k: String) = r.optString(k).takeIf { it.isNotBlank() && it != "null" && it != "?" }
+ Net(s("ssid"), id.uppercase(Locale.US), lat, lon, s("encryption"), r.optInt("channel", 0).takeIf { it > 0 },
+ s("lastupdt") ?: s("lasttime"),
+ listOfNotNull(s("road"), s("city"), s("region"), s("country")).distinct().joinToString(", ").ifEmpty { null })
+ }
+ return max(o.optInt("totalResults", nets.size), nets.size) to nets
+ }
+
+ /**
+ * 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.
+ */
+ suspend fun search(context: Context, text: String, near: Pair<Double, Double>?): 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) }
+ 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
+ setRequestProperty("Authorization", authHeader)
+ setRequestProperty("Accept", "application/json")
+ setRequestProperty("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")
+ }
+ val body = try {
+ when (c.responseCode) {
+ 200 -> c.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
+ 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}")
+ }
+ } catch (e: java.io.IOException) {
+ throw Failure("Couldn't reach WiGLE: ${e.message ?: "no connection"}")
+ } finally {
+ c.disconnect()
+ }
+ val (total, nets) = parse(body)
+ remember(context, key, Cached(now, total, nets))
+ Answer(nets, total, area != null, cached = false)
+ }
+
+ @Synchronized
+ private fun cached(context: Context, key: String, now: Long): Cached? =
+ load(context)[key]?.takeIf { now - it.at < CACHE_MS }
+
+ @Synchronized
+ private fun remember(context: Context, key: String, value: Cached) {
+ val m = load(context)
+ m[key] = value
+ val now = System.currentTimeMillis()
+ m.entries.removeAll { now - it.value.at >= CACHE_MS }
+ while (m.size > CACHE_MAX) m.remove(m.entries.minByOrNull { it.value.at }!!.key)
+ runCatching { File(context.filesDir, CACHE_FILE).writeText(gson.toJson(m)) }
+ }
+
+ private fun load(context: Context): MutableMap<String, Cached> = cache ?: run {
+ val m = runCatching {
+ val f = File(context.filesDir, CACHE_FILE)
+ if (!f.exists()) null
+ else gson.fromJson<Map<String, Cached>>(f.readText(), object : TypeToken<Map<String, Cached>>() {}.type)
+ }.getOrNull().orEmpty().toMutableMap()
+ cache = m
+ m
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/online/WiglePins.kt b/app/src/main/java/com/rfsentinel/app/online/WiglePins.kt
new file mode 100644
index 0000000..5b4ef13
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/online/WiglePins.kt
@@ -0,0 +1,62 @@
+package com.rfsentinel.app.online
+
+import android.content.Context
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import java.io.File
+
+/**
+ * WiGLE results pinned on the map ("Show on map"), with the name or address that was searched.
+ * They stay until removed. Kept only on this phone.
+ */
+object WiglePins {
+
+ data class Pin(val net: Wigle.Net, val searched: String, val at: Long)
+
+ private const val FILE = "wigle_pins.json"
+ private const val MAX = 500
+
+ private val gson = Gson()
+ private var pins: MutableList<Pin>? = null
+
+ /** Bumped on every change, so the map redraws only then. */
+ @Volatile var version = 0; private set
+
+ @Synchronized
+ fun all(context: Context): List<Pin> = load(context).toList()
+
+ /** Pins [nets] (an address pinned again moves to its new answer). */
+ @Synchronized
+ fun add(context: Context, nets: List<Wigle.Net>, searched: String, now: Long = System.currentTimeMillis()) {
+ val list = load(context)
+ val ids = nets.map { it.bssid }.toSet()
+ list.removeAll { it.net.bssid in ids }
+ nets.forEach { list += Pin(it, searched, now) }
+ while (list.size > MAX) list.removeAt(0)
+ save(context)
+ }
+
+ @Synchronized
+ fun remove(context: Context, bssid: String) { if (load(context).removeAll { it.net.bssid == bssid }) save(context) }
+
+ @Synchronized
+ fun clear(context: Context) { load(context).clear(); save(context) }
+
+ @Synchronized
+ fun find(context: Context, bssid: String): Pin? = load(context).firstOrNull { it.net.bssid == bssid }
+
+ private fun load(context: Context): MutableList<Pin> = pins ?: run {
+ val list = runCatching {
+ val f = File(context.filesDir, FILE)
+ if (!f.exists()) null else gson.fromJson<List<Pin>>(f.readText(), object : TypeToken<List<Pin>>() {}.type)
+ }.getOrNull().orEmpty()
+ @Suppress("SENSELESS_COMPARISON") // Gson can leave fields null
+ pins = list.filter { it.net != null && it.net.bssid != null }.toMutableList()
+ pins!!
+ }
+
+ private fun save(context: Context) {
+ version++
+ runCatching { File(context.filesDir, FILE).writeText(gson.toJson(pins.orEmpty())) }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt b/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt
index 3947efd..c4d1376 100644
--- a/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt
@@ -4,14 +4,21 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
+import android.view.Menu
+import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.chip.Chip
+import com.google.android.material.chip.ChipGroup
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rfsentinel.app.data.ProbeBook
import com.rfsentinel.app.data.ProbeLog
@@ -28,13 +35,15 @@ import java.util.Date
/**
* Requested networks: the WiFi network names devices around you asked for, newest
- * first. Watch one to get an alert whenever a device asks for it (a "probe:" rule in
- * the watchlist).
+ * first, by network or by the device that asked. Watch one to get an alert whenever a
+ * device asks for it (a "probe:" rule in the watchlist); find where a name is on WiGLE.
*/
class ProbeListActivity : AppCompatActivity() {
private lateinit var binding: ActivityProbeListBinding
private val adapter = Adapter()
+ private val deviceAdapter = DeviceAdapter()
+ private var byDevice = false
private val main = Handler(Looper.getMainLooper())
private val tick = object : Runnable {
override fun run() { refresh(); main.postDelayed(this, 3000) }
@@ -56,17 +65,36 @@ class ProbeListActivity : AppCompatActivity() {
if (on) Toast.makeText(this, "Recording while scanning with a USB WiFi adapter or an ESP32 Marauder board", Toast.LENGTH_LONG).show()
refresh()
}
+ binding.viewToggle.addOnButtonCheckedListener { _, id, checked ->
+ if (!checked) return@addOnButtonCheckedListener
+ byDevice = id == binding.byDeviceButton.id
+ binding.recyclerView.adapter = if (byDevice) deviceAdapter else adapter
+ binding.filterInput.hint = if (byDevice) "Filter by name, address or model" else "Filter by name"
+ refresh()
+ }
binding.filterInput.doAfterTextChanged { refresh() }
binding.clearButton.setOnClickListener {
MaterialAlertDialogBuilder(this)
.setTitle("Clear the list?")
- .setMessage("Removes every recorded network name. Watched names stay on the watchlist.")
+ .setMessage("Removes every recorded network name and device. Watched names stay on the watchlist.")
.setPositiveButton("Clear") { _, _ -> ProbeLog.clear(this); refresh() }
.setNegativeButton("Cancel", null)
.show()
}
}
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menu.add(0, MENU_SEARCH, 0, "Search WiGLE")
+ menu.add(0, MENU_ACCOUNT, 1, "WiGLE account")
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
+ MENU_SEARCH -> { WigleUi.ask(this); true }
+ MENU_ACCOUNT -> { WigleUi.account(this); true }
+ else -> super.onOptionsItemSelected(item)
+ }
+
override fun onResume() { super.onResume(); main.post(tick) }
override fun onPause() {
@@ -79,17 +107,32 @@ class ProbeListActivity : AppCompatActivity() {
private fun refresh() {
val filter = binding.filterInput.text.toString().trim()
- val all = ProbeLog.all(this)
- val shown = if (filter.isEmpty()) all else all.filter { it.ssid.contains(filter, ignoreCase = true) }
- adapter.submit(shown)
- binding.emptyText.visibility = if (shown.isEmpty()) View.VISIBLE else View.GONE
+ val count: Int
+ val any: Boolean
+ if (byDevice) {
+ val all = ProbeLog.groups(this)
+ val shown = if (filter.isEmpty()) all else all.filter { g -> matches(g, filter) }
+ deviceAdapter.submit(shown)
+ count = shown.size; any = all.isNotEmpty()
+ } else {
+ val all = ProbeLog.all(this)
+ val shown = if (filter.isEmpty()) all else all.filter { it.ssid.contains(filter, ignoreCase = true) }
+ adapter.submit(shown)
+ count = shown.size; any = all.isNotEmpty()
+ }
+ binding.emptyText.visibility = if (count == 0) View.VISIBLE else View.GONE
binding.emptyText.text = when {
- all.isNotEmpty() -> "No name matches the filter."
+ any -> "Nothing matches the filter."
!Prefs.recordProbes(this) -> "Recording is off. Turn it on above, then scan with a USB WiFi adapter or an ESP32 Marauder board plugged in."
else -> "Nothing yet. Names appear while scanning with a USB WiFi adapter or an ESP32 Marauder board plugged in."
}
}
+ private fun matches(g: ProbeBook.Group, filter: String): Boolean = g.devices.any { d ->
+ d.mac.contains(filter, ignoreCase = true) || d.wpsName?.contains(filter, ignoreCase = true) == true ||
+ d.wpsProduct?.contains(filter, ignoreCase = true) == true || maker(d.mac).contains(filter, ignoreCase = true)
+ } || g.ssids.any { it.contains(filter, ignoreCase = true) }
+
private fun meta(n: ProbeBook.Network, now: Long): String = listOf(
if (n.devices.size == 1) "1 device" else "${n.devices.size} devices",
if (n.encounters == 1) "seen once" else "seen ${n.encounters} times",
@@ -104,6 +147,33 @@ class ProbeListActivity : AppCompatActivity() {
else -> "${ms / 86_400_000} d ago"
}
+ private fun maker(mac: String) = if (MacUtil.isRandomized(mac)) "random address" else VendorDb.macVendor(mac) ?: "unknown maker"
+
+ /** A group's title: its WPS name or model when it gave one, else its maker. */
+ private fun title(g: ProbeBook.Group): String {
+ val named = g.devices.firstNotNullOfOrNull { it.wpsName } ?: g.devices.firstNotNullOfOrNull { it.wpsProduct }
+ return when {
+ named != null -> named
+ g.likelySame -> "Likely the same device"
+ else -> g.devices.first().mac
+ }
+ }
+
+ private fun groupMeta(g: ProbeBook.Group, now: Long): String {
+ val d = g.devices.maxBy { it.lastSeen }
+ val lines = mutableListOf<String>()
+ if (g.likelySame) lines += "Likely the same device · ${g.devices.size} random addresses"
+ else lines += listOfNotNull(if (title(g) != d.mac) d.mac else null, maker(d.mac)).joinToString(" · ")
+ g.devices.firstNotNullOfOrNull { it.wpsProduct }?.takeIf { it != title(g) }?.let { lines += it }
+ lines += listOf(
+ if (g.ssids.size == 1) "asked for 1 network" else "asked for ${g.ssids.size} networks",
+ "last ${ago(now - g.lastSeen)}",
+ "${d.lastRssi} dBm"
+ ).joinToString(" · ")
+ lines += g.ssids.take(4).joinToString(", ") { "\"$it\"" } + if (g.ssids.size > 4) " …" else ""
+ return lines.joinToString("\n")
+ }
+
/** Watch [ssid]: the user names what it is; the label is what alerts say. */
private fun watch(ssid: String) {
val input = EditText(this).apply { setText("Asks for \"$ssid\""); setSelectAllOnFocus(true) }
@@ -133,19 +203,71 @@ class ProbeListActivity : AppCompatActivity() {
private fun details(n: ProbeBook.Network) {
val df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
- val devices = n.devices.reversed().joinToString("\n") { mac ->
- mac + " " + (if (MacUtil.isRandomized(mac)) "random address" else VendorDb.macVendor(mac) ?: "unknown maker")
- }
+ val devices = n.devices.reversed().joinToString("\n") { mac -> "$mac ${maker(mac)}" }
val watched = OuiWatchlist.isProbeWatched(n.ssid)
MaterialAlertDialogBuilder(this)
.setTitle(n.ssid)
.setMessage("First seen ${df.format(Date(n.firstSeen))}\nLast seen ${df.format(Date(n.lastSeen))}\n\nDevices that asked for it:\n$devices")
.setPositiveButton(if (watched) "Stop watching" else "Watch") { _, _ -> if (watched) unwatch(n.ssid) else watch(n.ssid) }
.setNeutralButton("Remove from list") { _, _ -> ProbeLog.remove(this, n.ssid); refresh() }
+ .setNegativeButton("Find on WiGLE") { _, _ -> WigleUi.search(this, n.ssid) }
+ .show()
+ }
+
+ /** A device (or a group of addresses likely to be one): what it is, and every name it asked for as chips. */
+ private fun deviceDetails(g: ProbeBook.Group) {
+ val df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
+ val dp = resources.displayMetrics.density
+ val text = buildString {
+ if (g.likelySame) append("These random addresses have the same rare probe fingerprint and asked for a network " +
+ "name in common, so they are likely one device changing its address.\n\n")
+ g.devices.forEach { d ->
+ append(d.mac).append(" ").append(maker(d.mac)).append('\n')
+ d.wpsName?.let { append(" Name: $it\n") }
+ d.wpsProduct?.let { append(" Model: $it\n") }
+ d.fingerprint?.let { fp ->
+ val n = ProbeLog.sharing(this@ProbeListActivity, fp)
+ append(" Probe fingerprint: $fp" + if (n > 1) " (shared by $n addresses)\n" else "\n")
+ }
+ append(" First seen ${df.format(Date(d.firstSeen))}\n Last seen ${df.format(Date(d.lastSeen))}\n")
+ append(" " + (if (d.encounters == 1) "Seen once" else "Seen ${d.encounters} times") + " · ${d.lastRssi} dBm\n")
+ }
+ append("\nNetworks it asked for (tap one):")
+ }
+ val chips = ChipGroup(this).apply {
+ g.ssids.forEach { ssid ->
+ addView(Chip(this@ProbeListActivity).apply {
+ // ★ = watched: alerts when a device asks for it.
+ this.text = if (OuiWatchlist.isProbeWatched(ssid)) "★ $ssid" else ssid
+ setOnClickListener { ssidActions(ssid) }
+ })
+ }
+ }
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ val pad = (20 * dp).toInt(); setPadding(pad, (8 * dp).toInt(), pad, 0)
+ addView(TextView(this@ProbeListActivity).apply { this.text = text; setTextIsSelectable(true) })
+ addView(chips)
+ }
+ MaterialAlertDialogBuilder(this)
+ .setTitle(title(g))
+ .setView(ScrollView(this).apply { addView(body) })
.setNegativeButton("Close", null)
.show()
}
+ private fun ssidActions(ssid: String) {
+ val network = ProbeLog.all(this).firstOrNull { it.ssid.equals(ssid, ignoreCase = true) }
+ val items = listOfNotNull(
+ network?.let { "Show this network" to { details(it) } },
+ "Find on WiGLE" to { WigleUi.search(this, ssid) }
+ )
+ MaterialAlertDialogBuilder(this)
+ .setTitle(ssid)
+ .setItems(items.map { it.first }.toTypedArray()) { _, which -> items[which].second() }
+ .show()
+ }
+
private inner class Adapter : RecyclerView.Adapter<Adapter.VH>() {
private var items: List<ProbeBook.Network> = emptyList()
@@ -168,4 +290,31 @@ class ProbeListActivity : AppCompatActivity() {
holder.b.root.setOnClickListener { details(n) }
}
}
+
+ private inner class DeviceAdapter : RecyclerView.Adapter<DeviceAdapter.VH>() {
+ private var items: List<ProbeBook.Group> = emptyList()
+
+ inner class VH(val b: ItemProbeBinding) : RecyclerView.ViewHolder(b.root)
+
+ fun submit(list: List<ProbeBook.Group>) { items = list; notifyDataSetChanged() }
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
+ VH(ItemProbeBinding.inflate(LayoutInflater.from(parent.context), parent, false).also {
+ it.watchButton.visibility = View.GONE
+ })
+
+ override fun getItemCount() = items.size
+
+ override fun onBindViewHolder(holder: VH, position: Int) {
+ val g = items[position]
+ holder.b.ssidText.text = title(g)
+ holder.b.metaText.text = groupMeta(g, System.currentTimeMillis())
+ holder.b.root.setOnClickListener { deviceDetails(g) }
+ }
+ }
+
+ private companion object {
+ const val MENU_SEARCH = 1
+ const val MENU_ACCOUNT = 2
+ }
}
diff --git a/app/src/main/java/com/rfsentinel/app/probes/WigleUi.kt b/app/src/main/java/com/rfsentinel/app/probes/WigleUi.kt
new file mode 100644
index 0000000..277851d
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/probes/WigleUi.kt
@@ -0,0 +1,179 @@
+package com.rfsentinel.app.probes
+
+import android.content.Context
+import android.content.Intent
+import android.location.Location
+import android.location.LocationManager
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.TextView
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.lifecycleScope
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.rfsentinel.app.online.Wigle
+import com.rfsentinel.app.online.WiglePins
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.service.ScanForegroundService
+import com.rfsentinel.app.ui.MapActivity
+import com.rfsentinel.app.util.Permissions
+import com.rfsentinel.app.util.SecureStore
+import com.rfsentinel.app.util.Units
+import kotlinx.coroutines.launch
+
+/**
+ * WiGLE screens: the account (API name and token), a search for a network name or an access point
+ * address near you then worldwide, its answers, and pinning them on the map.
+ */
+object WigleUi {
+
+ const val PRIVACY = "Searches WiGLE's database of networks mapped by wardrivers. Needs your own free WiGLE " +
+ "account: the API name and token from wigle.net/account (not your login), stored encrypted on this phone.\n\n" +
+ "What's sent to WiGLE: the name or address you search and, for a search near you, your position rounded " +
+ "to about 10 km. New accounts get only a few searches a day; an answer is kept on this phone for a day."
+
+ /** The WiGLE account fields; [then] runs after saving when both are filled in. */
+ fun account(a: AppCompatActivity, then: (() -> Unit)? = null) {
+ val dp = a.resources.displayMetrics.density
+ fun field(hint: String, key: String, password: Boolean) = EditText(a).apply {
+ this.hint = hint
+ setText(SecureStore.get(a, key).orEmpty())
+ isSingleLine = true
+ inputType = android.text.InputType.TYPE_CLASS_TEXT or
+ (if (password) android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD else android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
+ importantForAutofill = android.view.View.IMPORTANT_FOR_AUTOFILL_NO
+ }
+ val name = field("API name (starts with AID)", Wigle.NAME_KEY, false)
+ val token = field("API token", Wigle.TOKEN_KEY, true)
+ val box = LinearLayout(a).apply {
+ orientation = LinearLayout.VERTICAL
+ val pad = (20 * dp).toInt()
+ setPadding(pad, (8 * dp).toInt(), pad, 0)
+ addView(TextView(a).apply { text = PRIVACY; textSize = 13f; alpha = 0.8f })
+ addView(name); addView(token)
+ }
+ MaterialAlertDialogBuilder(a)
+ .setTitle("WiGLE account")
+ .setView(box)
+ .setPositiveButton("Save") { _, _ ->
+ SecureStore.put(a, Wigle.NAME_KEY, name.text.toString().trim())
+ SecureStore.put(a, Wigle.TOKEN_KEY, token.text.toString().trim())
+ if (Wigle.hasAccount(a)) then?.invoke()
+ }
+ .setNeutralButton("Remove") { _, _ ->
+ SecureStore.put(a, Wigle.NAME_KEY, ""); SecureStore.put(a, Wigle.TOKEN_KEY, "")
+ Toast.makeText(a, "WiGLE account removed from this phone", Toast.LENGTH_SHORT).show()
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ /** Asks for a name or an address to search. */
+ fun ask(a: AppCompatActivity) {
+ val input = EditText(a).apply {
+ hint = "Network name or address"
+ isSingleLine = true
+ inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
+ }
+ val dp = a.resources.displayMetrics.density
+ val box = LinearLayout(a).apply {
+ val pad = (20 * dp).toInt(); setPadding(pad, (8 * dp).toInt(), pad, 0)
+ addView(input, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
+ }
+ MaterialAlertDialogBuilder(a)
+ .setTitle("Search WiGLE")
+ .setMessage("A WiFi network name (SSID), * as a wildcard, or an access point address (BSSID).")
+ .setView(box)
+ .setPositiveButton("Search") { _, _ -> input.text.toString().trim().takeIf { it.isNotEmpty() }?.let { search(a, it) } }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ /** Searches [text] near you (worldwide when your position isn't known), offering worldwide when nothing is near. */
+ fun search(a: AppCompatActivity, text: String, worldwide: Boolean = false) {
+ if (!Wigle.hasAccount(a)) { account(a) { search(a, text, worldwide) }; return }
+ val me = myPosition(a)
+ val near = if (worldwide) null else me
+ val progress = MaterialAlertDialogBuilder(a)
+ .setTitle("Searching WiGLE…")
+ .setMessage(if (near != null) "\"$text\" within ${Wigle.NEAR_KM.toInt()} km of you" else "\"$text\" worldwide")
+ .setCancelable(false)
+ .show()
+ a.lifecycleScope.launch {
+ val result = runCatching { Wigle.search(a, text, near) }
+ progress.dismiss()
+ if (a.isFinishing || a.isDestroyed) return@launch
+ result.onSuccess { answer ->
+ if (answer.nets.isEmpty() && answer.near) {
+ MaterialAlertDialogBuilder(a)
+ .setTitle("Nothing near you")
+ .setMessage("WiGLE has no \"$text\" within ${Wigle.NEAR_KM.toInt()} km of you. Search worldwide?")
+ .setPositiveButton("Search worldwide") { _, _ -> search(a, text, worldwide = true) }
+ .setNegativeButton("Cancel", null)
+ .show()
+ } else {
+ results(a, text, answer, me)
+ }
+ }.onFailure { e ->
+ MaterialAlertDialogBuilder(a)
+ .setTitle("WiGLE search failed")
+ .setMessage(e.message ?: "Unknown error")
+ .apply { if (e.message?.contains("API name") == true) setPositiveButton("Account") { _, _ -> account(a) } }
+ .setNegativeButton("Close", null)
+ .show()
+ }
+ }
+ }
+
+ private fun results(a: AppCompatActivity, text: String, answer: Wigle.Answer, me: Pair<Double, Double>?) {
+ if (answer.nets.isEmpty()) {
+ MaterialAlertDialogBuilder(a).setTitle("Not found")
+ .setMessage("WiGLE has no network \"$text\" with a position.")
+ .setNegativeButton("Close", null).show()
+ return
+ }
+ val nets = if (me == null) answer.nets
+ else answer.nets.sortedBy { DeviceRegistry.metersBetween(me.first, me.second, it.lat, it.lon) }
+ val rows = nets.map { n -> line(n, me) }.toTypedArray()
+ val where = if (answer.near) "within ${Wigle.NEAR_KM.toInt()} km" else "worldwide"
+ val more = if (answer.total > nets.size) " (${nets.size} of ${answer.total} shown)" else ""
+ MaterialAlertDialogBuilder(a)
+ .setTitle("\"$text\" $where$more")
+ .setItems(rows) { _, which -> pinAndShow(a, listOf(nets[which]), text, nets[which]) }
+ .setPositiveButton("Pin all on map") { _, _ -> pinAndShow(a, nets, text, nets.first()) }
+ .apply { if (answer.near) setNeutralButton("Worldwide") { _, _ -> search(a, text, worldwide = true) } }
+ .setNegativeButton("Close", null)
+ .show()
+ }
+
+ /** One answer as a list row: name and address, then where, when and how far. */
+ internal fun line(n: Wigle.Net, me: Pair<Double, Double>?): String {
+ val details = listOfNotNull(
+ n.place,
+ n.lastSeen?.take(10)?.let { "seen $it" },
+ me?.let { Units.distance(DeviceRegistry.metersBetween(it.first, it.second, n.lat, n.lon)) + " away" }
+ ).joinToString(" · ")
+ return "${n.ssid ?: "Hidden network"} ${n.bssid}" + if (details.isEmpty()) "" else "\n$details"
+ }
+
+ private fun pinAndShow(a: AppCompatActivity, nets: List<Wigle.Net>, searched: String, focus: Wigle.Net) {
+ WiglePins.add(a, nets, searched)
+ Toast.makeText(a, if (nets.size == 1) "Pinned on the map" else "${nets.size} networks pinned on the map", Toast.LENGTH_SHORT).show()
+ a.startActivity(Intent(a, MapActivity::class.java)
+ .putExtra(MapActivity.EXTRA_CENTER_LAT, focus.lat)
+ .putExtra(MapActivity.EXTRA_CENTER_LON, focus.lon))
+ }
+
+ /** Where you are: the scan's last fix, else the phone's last known position. */
+ @android.annotation.SuppressLint("MissingPermission") // checked just before
+ private fun myPosition(context: Context): Pair<Double, Double>? {
+ ScanForegroundService.lastFix?.let { return it.latitude to it.longitude }
+ if (!Permissions.granted(context, android.Manifest.permission.ACCESS_FINE_LOCATION) &&
+ !Permissions.granted(context, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return null
+ val lm = context.getSystemService(LocationManager::class.java) ?: return null
+ val best: Location? = runCatching { lm.getProviders(true) }.getOrNull().orEmpty()
+ .mapNotNull { runCatching { lm.getLastKnownLocation(it) }.getOrNull() }
+ .maxByOrNull { it.time }
+ return best?.let { it.latitude to it.longitude }
+ }
+}
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 a6dd8f7..bba5b5d 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -712,7 +712,8 @@ class ScanForegroundService : Service() {
skeleton: Long? = null) {
com.rfsentinel.app.usb.ProbeIntel.note(mac, wps, fingerprint, ssids, hidden, skeleton)
// Kept in the requested-networks list when that's on, and always while a trace records.
- if (ssids.isNotEmpty()) com.rfsentinel.app.data.ProbeLog.record(this, mac, ssids, rssi, now, force = TripRecorder.isRecording)
+ com.rfsentinel.app.data.ProbeLog.record(this, mac, ssids, rssi, now, force = TripRecorder.isRecording,
+ wps = wps, fingerprint = fingerprint)
val hits = OuiWatchlist.probeHits(ssids) + OuiWatchlist.fingerprintHits(fingerprint) + OuiWatchlist.wpsHits(wps) +
OuiWatchlist.fingerprintHits(skeleton?.let { com.rfsentinel.app.usb.ProbeIntel.shapeKey(it) })
if (hits.isEmpty()) 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 6bacb7c..4c89b66 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -1252,6 +1252,18 @@ class SettingsActivity : AppCompatActivity() {
for ((field, key) in secretFields) com.rfsentinel.app.util.SecureStore.put(this, key, field.text.toString().trim())
}
+ /** Settings > Data: the WiGLE account used by "Find on WiGLE" (requested networks, WiFi devices). */
+ private fun setupWigleAccount() {
+ val box = binding.sectionData
+ val button = com.google.android.material.button.MaterialButton(this, null,
+ com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {
+ text = "WiGLE account"
+ setOnClickListener { com.rfsentinel.app.probes.WigleUi.account(this@SettingsActivity) }
+ }
+ box.addView(infoRow(button, com.rfsentinel.app.probes.WigleUi.PRIVACY, "WiGLE account"),
+ box.indexOfChild(binding.importHistoryButton))
+ }
+
// ---- Live export (Settings > Data) ---------------------------------------------------
private val liveExportFolder = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocumentTree()) { uri ->
@@ -2245,6 +2257,7 @@ class SettingsActivity : AppCompatActivity() {
setupDeviceUnits()
setupRadioSection()
setupLiveExport()
+ setupWigleAccount()
addDetails()
binding.hideTrustedSwitch.isChecked = Prefs.hideWhitelisted(this)
binding.hideTrustedSwitch.setOnCheckedChangeListener { _, on -> Prefs.setHideWhitelisted(this, on) }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
index 5494fa4..61a93f8 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
@@ -97,6 +97,10 @@ object DeviceActions {
if (snap?.advert != null && snap.best == null) {
items += "Report unknown device..." to { reportUnknown(activity, mac) }
}
+ // An access point's address is what WiGLE maps; a phone or laptop (client) isn't on it.
+ if (snap?.advert?.isWifi == true && snap.advert.wifi?.client != true) {
+ items += "Find on WiGLE" to { com.rfsentinel.app.probes.WigleUi.search(activity, mac) }
+ }
items += "Copy address" to { copy(activity, mac) }
MaterialAlertDialogBuilder(activity)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt b/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt
index ee829e6..0005d84 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt
@@ -89,6 +89,27 @@ internal object MapDialogs {
.show()
}
+ /** A network pinned from a WiGLE search; [remove] takes the pin off the map. */
+ fun showWigle(a: AppCompatActivity, p: com.rfsentinel.app.online.WiglePins.Pin, me: Pair<Double, Double>?, remove: () -> Unit) {
+ val n = p.net
+ val text = buildString {
+ append("Address (BSSID): ${n.bssid}\n")
+ n.encryption?.let { append("Security: $it\n") }
+ n.channel?.let { append("Channel: $it\n") }
+ n.place?.let { append("Where: $it\n") }
+ n.lastSeen?.let { append("Last seen by WiGLE: ${it.take(10)}\n") }
+ me?.let { append("Distance: " + com.rfsentinel.app.util.Units.distance(
+ DeviceRegistry.metersBetween(it.first, it.second, n.lat, n.lon)) + "\n") }
+ append("\nFrom a WiGLE search for \"${p.searched}\". WiGLE's position is an estimate from wardriving uploads.")
+ }
+ MaterialAlertDialogBuilder(a)
+ .setTitle(n.ssid ?: "Hidden network")
+ .setMessage(text)
+ .setPositiveButton("Remove pin") { _, _ -> remove() }
+ .setNegativeButton("Close", null)
+ .show()
+ }
+
/** [me] = your position (lat, lon) for the distance, when known. */
fun showAircraft(a: AppCompatActivity, p: com.rfsentinel.app.online.PoliceAircraft.Plane, hit: com.rfsentinel.app.detect.Hit?,
me: Pair<Double, Double>?) {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
index c589e15..85ae495 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
@@ -9,6 +9,7 @@ import com.rfsentinel.app.alpr.CctvStore
import com.rfsentinel.app.alpr.KnownCamera
import com.rfsentinel.app.online.PoliceAircraft
import com.rfsentinel.app.online.WazePolice
+import com.rfsentinel.app.online.WiglePins
import com.rfsentinel.app.service.CellTowerStore
import com.rfsentinel.app.service.DeviceRegistry
import com.rfsentinel.app.service.ScanForegroundService
@@ -48,6 +49,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
private const val DEVICES = "rf-devices"; private const val DOTS = "rf-device-dots"; private const val LABELS = "rf-device-labels"
private const val WAZE = "rf-waze"; private const val DRONE_OPS = "rf-drone-ops"; private const val DRONES = "rf-drones"
private const val AIRCRAFT = "rf-aircraft"
+ private const val WIGLE = "rf-wigle"; private const val WIGLE_COLOR = "#8E24AA"
private const val NAV_ROUTES = "rf-nav-routes"; private const val NAV_PLACES = "rf-nav-places"
private const val NAV_ROUTE_COLOR = "#1A73E8"; private const val NAV_ALT_COLOR = "#7C8DA6"
@@ -87,6 +89,9 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
private var cameras: Map<String, KnownCamera> = emptyMap()
private var cctvs: Map<String, com.rfsentinel.app.alpr.CctvCamera> = emptyMap()
private var towers: Map<String, CellTowerStore.Tower> = emptyMap()
+ private var wigle: Map<String, WiglePins.Pin> = emptyMap()
+ /** What the WiGLE layer was drawn for (pins' version, filter, trace mode): redrawn only when it changes. */
+ private var wigleDrawn: String? = null
/** The area the camera, CCTV and tower layers were drawn for (redrawn when the view leaves it). */
private var staticBox: MapEngine.Box? = null
private var staticAt = 0L
@@ -107,8 +112,10 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
// The same map turned night (Mapbox): the labels' colours follow.
val (ink, halo) = labelColors(dark)
map.setPaint(LABELS, "text-color", ink); map.setPaint(LABELS, "text-halo-color", halo)
+ map.setPaint("$WIGLE-labels", "text-color", ink); map.setPaint("$WIGLE-labels", "text-halo-color", halo)
}
staticBox = null
+ wigleDrawn = null
safe("loaded") { onLoaded() }
}
}
@@ -136,7 +143,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
/** Every layer, as map style JSON (the same on both engines). */
private fun addLayers(dark: Boolean) {
- listOf(NAV_ROUTES, NAV_PLACES, PRECISION, CONES, CAM_CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, DEVICES, WAZE, DRONE_OPS, DRONES, AIRCRAFT)
+ listOf(NAV_ROUTES, NAV_PLACES, PRECISION, CONES, CAM_CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, DEVICES, WIGLE, WAZE, DRONE_OPS, DRONES, AIRCRAFT)
.forEach { map.addSource(it) }
fun get(k: String) = a("get", k)
val color = a("to-color", get("color"))
@@ -195,6 +202,13 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
layout = o("text-field" to get("label"), "text-font" to font, "text-size" to 12.0, "text-anchor" to "top",
"text-offset" to a(0.0, 1.1), "text-optional" to true),
paint = o("text-color" to ink, "text-halo-color" to halo, "text-halo-width" to 1.5)),
+ // Networks pinned from a WiGLE search: purple, with their name.
+ layer(WIGLE, "circle", paint = o("circle-color" to WIGLE_COLOR, "circle-radius" to 7.0,
+ "circle-stroke-color" to "#FFFFFF", "circle-stroke-width" to 2.0)),
+ layer("$WIGLE-labels", "symbol", WIGLE,
+ layout = o("text-field" to get("label"), "text-font" to font, "text-size" to 12.0, "text-anchor" to "top",
+ "text-offset" to a(0.0, 1.0), "text-optional" to true),
+ paint = o("text-color" to ink, "text-halo-color" to halo, "text-halo-width" to 1.5)),
// Waze reports: blue police, red accident, orange hazard, brown closure, purple jam.
layer(WAZE, "circle", paint = o("circle-color" to color, "circle-radius" to 9.0,
"circle-stroke-color" to "#FFFFFF", "circle-stroke-width" to 2.0)),
@@ -314,11 +328,26 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
).joinToString(" · "))
})
+ drawWigle()
val trace = if (TripRecorder.isRecording) TripRecorder.livePoints() else emptyList()
drawTrace(trace.map { it.lat to it.lon }, TRACE_COLOR)
return shown
}
+ /** Networks pinned from WiGLE searches (the All and WiFi views), when they changed. */
+ fun drawWigle() {
+ if (!ready()) return
+ val key = "${WiglePins.version}|$filter|$tripMode"
+ if (key == wigleDrawn) return
+ wigleDrawn = key
+ val show = !tripMode && (filter == DeviceFilter.ALL || filter == DeviceFilter.WIFI)
+ val list = if (show) WiglePins.all(activity) else emptyList()
+ wigle = list.associateBy { it.net.bssid }
+ set(WIGLE, list.map { p ->
+ GeoJson.feature(GeoJson.point(p.net.lat, p.net.lon), "id" to p.net.bssid, "label" to (p.net.ssid ?: p.net.bssid).take(32))
+ })
+ }
+
/**
* Cameras, CCTV and cell towers: many, and they don't move - drawn for the area in view (and
* around it), again once the view leaves that area or every 15 s for new downloads.
@@ -464,7 +493,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
val r = 22f * activity.resources.displayMetrics.density
val box = RectF(x - r, y - r, x + r, y + r)
val asked = listOf(AIRCRAFT to "hex", WAZE to "id", DRONES to "mac", DRONE_OPS to "mac", DOTS to "mac",
- CAMERAS to "id", CCTV to "id", TOWERS to "id")
+ CAMERAS to "id", CCTV to "id", TOWERS to "id", WIGLE to "id")
map.query(box, asked) { found ->
if (activity.isFinishing || activity.isDestroyed) return@query
safe("tap") { showTapped(found, me) }
@@ -475,6 +504,10 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
val (air, waze, drone, op, dots, cams, cctv, tower) = found
air.firstNotNullOfOrNull { planes[it] }?.let { s -> MapDialogs.showAircraft(activity, s.plane, s.hit, me); return }
waze.firstNotNullOfOrNull { wazeShown[it] }?.let { MapDialogs.showWaze(activity, it); return }
+ found[8].firstNotNullOfOrNull { wigle[it] }?.let { p ->
+ MapDialogs.showWigle(activity, p, me) { WiglePins.remove(activity, p.net.bssid); drawWigle() }
+ return
+ }
(drone + op).firstNotNullOfOrNull { drones[it] }?.let { s ->
MapDialogs.showDrone(activity, s.mac, MapDialogs.droneDetails(s, s.remoteId!!)); return
}
diff --git a/app/src/main/res/layout/activity_probe_list.xml b/app/src/main/res/layout/activity_probe_list.xml
index bd68859..3deaf4f 100644
--- a/app/src/main/res/layout/activity_probe_list.xml
+++ b/app/src/main/res/layout/activity_probe_list.xml
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
@@ -19,7 +20,32 @@
android:paddingBottom="8dp"
android:textSize="@dimen/text_caption"
android:textColor="?android:attr/textColorSecondary"
- android:text="Phones and laptops ask by name for WiFi networks they joined before. A USB WiFi adapter or an ESP32 Marauder board hears these requests. Kept only on this phone; a map trace recording always keeps them, with the trace. Tap a name to watch it: you get an alert whenever a device asks for it." />
+ android:text="Phones and laptops ask by name for WiFi networks they joined before. A USB WiFi adapter or an ESP32 Marauder board hears these requests. Kept only on this phone; a map trace recording always keeps them, with the trace. Tap a name to watch it: you get an alert whenever a device asks for it, or to find where it is on WiGLE. By device shows each device and every name it asked for." />
+
+ <com.google.android.material.button.MaterialButtonToggleGroup
+ android:id="@+id/viewToggle"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ app:singleSelection="true"
+ app:selectionRequired="true"
+ app:checkedButton="@id/byNetworkButton">
+
+ <Button
+ android:id="@+id/byNetworkButton"
+ style="?attr/materialButtonOutlinedStyle"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="By network" />
+
+ <Button
+ android:id="@+id/byDeviceButton"
+ style="?attr/materialButtonOutlinedStyle"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="By device" />
+ </com.google.android.material.button.MaterialButtonToggleGroup>
<EditText
android:id="@+id/filterInput"
diff --git a/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.kt b/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.kt
new file mode 100644
index 0000000..17abb4d
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/data/ProbeDevicesTest.kt
@@ -0,0 +1,77 @@
+package com.rfsentinel.app.data
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProbeDevicesTest {
+
+ private val random = { mac: String -> (mac.take(2).toInt(16) and 0x02) != 0 }
+
+ @Test
+ fun recordsWhatEachDeviceAskedForAndSaid() {
+ val b = ProbeBook()
+ assertTrue(b.recordDevice("02:00:00:00:00:01", listOf("PD-MDT"), -70, 0))
+ assertTrue(b.recordDevice("02:00:00:00:00:01", listOf("Home", "pd-mdt"), -60, 1_000,
+ wpsName = "UNIT12", wpsProduct = "Panasonic CF-33", fingerprint = "abcd1234"))
+ // A wildcard probe (no names) only adds to a known device.
+ assertTrue(b.recordDevice("02:00:00:00:00:01", emptyList(), -55, 2_000 + ProbeBook.GAP_MS + 1))
+ assertFalse(b.recordDevice("02:00:00:00:00:09", emptyList(), -55, 3_000, fingerprint = "ffff0000"))
+ val d = b.devices().single()
+ assertEquals(listOf("Home", "pd-mdt"), d.ssids)
+ assertEquals("UNIT12", d.wpsName)
+ assertEquals("Panasonic CF-33", d.wpsProduct)
+ assertEquals("abcd1234", d.fingerprint)
+ assertEquals(2, d.encounters)
+ assertEquals(-55, d.lastRssi)
+ assertEquals(1, b.sharing("abcd1234"))
+ }
+
+ @Test
+ fun randomAddressesWithARareFingerprintAndACommonNameAreOneDevice() {
+ val b = ProbeBook()
+ b.recordDevice("02:00:00:00:00:01", listOf("PD-MDT", "Home"), -70, 0, fingerprint = "f1")
+ b.recordDevice("06:00:00:00:00:02", listOf("pd-mdt"), -70, 1_000, fingerprint = "f1")
+ b.recordDevice("0A:00:00:00:00:03", listOf("Cafe"), -70, 2_000, fingerprint = "f1") // nothing in common
+ val groups = b.groups(random)
+ assertEquals(2, groups.size)
+ val merged = groups.single { it.likelySame }
+ assertEquals(setOf("02:00:00:00:00:01", "06:00:00:00:00:02"), merged.devices.map { it.mac }.toSet())
+ assertEquals(listOf("pd-mdt", "Home"), merged.ssids)
+ }
+
+ @Test
+ fun fixedAddressesAndCommonFingerprintsStandAlone() {
+ val b = ProbeBook()
+ // Fixed (maker) addresses with the same fingerprint and name: two devices of one model.
+ b.recordDevice("00:11:22:00:00:01", listOf("Office"), -70, 0, fingerprint = "f2")
+ b.recordDevice("00:11:22:00:00:02", listOf("Office"), -70, 0, fingerprint = "f2")
+ // A fingerprint shared by more addresses than rareMax says nothing.
+ for (i in 1..4) b.recordDevice("02:00:00:00:01:0$i", listOf("Starbucks"), -70, i.toLong(), fingerprint = "common")
+ val groups = b.groups(random, rareMax = 3)
+ assertEquals(6, groups.size)
+ assertTrue(groups.none { it.likelySame })
+ }
+
+ @Test
+ fun removingANameDropsDevicesThatAskedForNothingElse() {
+ val b = ProbeBook()
+ b.record("PD-MDT", "02:00:00:00:00:01", -70, 0)
+ b.recordDevice("02:00:00:00:00:01", listOf("PD-MDT"), -70, 0)
+ b.record("Home", "02:00:00:00:00:02", -70, 0)
+ b.recordDevice("02:00:00:00:00:02", listOf("PD-MDT", "Home"), -70, 0)
+ b.remove("pd-mdt")
+ assertEquals(listOf("02:00:00:00:00:02"), b.devices().map { it.mac })
+ assertEquals(listOf("Home"), b.devices().single().ssids)
+ b.clear()
+ assertTrue(b.devices().isEmpty())
+ }
+
+ @Test
+ fun restoredDevicesSurviveMissingFields() {
+ val b = ProbeBook()
+ 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)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/online/WigleTest.kt b/app/src/test/java/com/rfsentinel/app/online/WigleTest.kt
new file mode 100644
index 0000000..2194659
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/online/WigleTest.kt
@@ -0,0 +1,72 @@
+package com.rfsentinel.app.online
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = android.app.Application::class)
+class WigleTest {
+
+ @Test
+ fun recognisesAccessPointAddresses() {
+ assertTrue(Wigle.isBssid("aa:bb:cc:dd:ee:ff"))
+ assertTrue(Wigle.isBssid("AA-BB-CC-DD-EE-FF"))
+ assertTrue(Wigle.isBssid(" aabbccddeeff "))
+ assertFalse(Wigle.isBssid("aa:bb:cc:dd:ee"))
+ assertFalse(Wigle.isBssid("PD-MDT"))
+ assertFalse(Wigle.isBssid("deadbeefcafe1"))
+ assertEquals("AA:BB:CC:DD:EE:FF", Wigle.bssid("aa-bb-cc-dd-ee-ff"))
+ assertEquals("AA:BB:CC:DD:EE:FF", Wigle.bssid("aabbccddeeff"))
+ }
+
+ @Test
+ fun searchesANameExactlyOrWithAWildcardAndAnAddressByItself() {
+ assertTrue(Wigle.url("PD MDT", null).contains("&ssid=PD+MDT"))
+ assertFalse(Wigle.url("PD MDT", null).contains("latrange"))
+ assertTrue(Wigle.url("PD*", null).contains("&ssidlike=PD%25"))
+ val byAddress = Wigle.url("aa-bb-cc-dd-ee-ff", null)
+ assertTrue(byAddress.contains("&netid=AA%3ABB%3ACC%3ADD%3AEE%3AFF"))
+ assertFalse(byAddress.contains("ssid="))
+ }
+
+ @Test
+ fun nearSearchCoversABoxAroundThePosition() {
+ val u = Wigle.url("Home", 45.0 to -73.0)
+ fun v(k: String) = Regex("[?&]$k=([-0-9.]+)").find(u)!!.groupValues[1].toDouble()
+ assertEquals(45.0 - 50 / 111.0, v("latrange1"), 0.001)
+ assertEquals(45.0 + 50 / 111.0, v("latrange2"), 0.001)
+ assertTrue(v("longrange1") < -73.5 && v("longrange2") > -72.5)
+ assertEquals(45.1 to -73.2, Wigle.snap(45.123, -73.249))
+ }
+
+ @Test
+ fun readsResultsAndLeavesOutThoseWithoutAPosition() {
+ val json = """{"success":true,"totalResults":40,"results":[
+ {"trilat":45.5,"trilong":-73.6,"ssid":"PD-MDT","netid":"aa:bb:cc:dd:ee:ff","encryption":"wpa2","channel":6,
+ "lastupdt":"2025-06-01T12:00:00.000Z","road":"Main St","city":"Town","region":"QC","country":"CA"},
+ {"trilat":0.0,"trilong":0.0,"ssid":"Nowhere","netid":"11:22:33:44:55:66"},
+ {"ssid":"NoPos","netid":"11:22:33:44:55:77"},
+ {"trilat":10.0,"trilong":20.0,"ssid":null,"netid":"11:22:33:44:55:88"}]}"""
+ val (total, nets) = Wigle.parse(json)
+ assertEquals(40, total)
+ assertEquals(2, nets.size)
+ val n = nets[0]
+ assertEquals("PD-MDT", n.ssid)
+ assertEquals("AA:BB:CC:DD:EE:FF", n.bssid)
+ assertEquals(6, n.channel)
+ assertEquals("Main St, Town, QC, CA", n.place)
+ assertNull(nets[1].ssid)
+ assertNull(nets[1].place)
+ }
+
+ @Test(expected = Wigle.Failure::class)
+ fun aRefusedSearchIsAFailure() {
+ Wigle.parse("""{"success":false,"message":"too many queries today"}""")
+ }
+}