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.

Release 2.18.0: pinpointing, V2X emergency vehicles, .pcap recording, deauth alarm, Chipolo, cellular uplink, voice loudness, screen rotation

CIS-C0afeb22064f10
diff --git a/README.md b/README.md
index 4a1239d..43db303 100644
--- a/README.md
+++ b/README.md
@@ -88,14 +88,15 @@
| **Audio sensors** | Flock Raven | 128-bit service UUIDs `0x3100`-`0x3500` |
| **Patrol vehicles** | Two or more kinds of police-type gear travelling together | Signal correlation between body cams, radios, in-car routers, printers, rugged laptops |
| **Public-safety gear** | P25 / TETRA radios, in-car cellular routers (Sierra Wireless, Cradlepoint, Peplink, Inseego), in-car printers (Zebra, Brother), police radar makers, vehicle upfit, breath / drug screening devices, cell-site simulator and forensic makers | Company IDs, UUIDs, IEEE prefixes, Zebra factory-serial names |
-| **Trackers** | AirTag & Find My, Google Find Hub, Samsung SmartTag, Tile | Separated-from-owner frames, then follow detection |
+| **Trackers** | AirTag & Find My, Google Find Hub, Samsung SmartTag, Tile, Chipolo | Separated-from-owner frames and tracker service IDs, then follow detection |
| **Drones** | Any ASTM F3411 / FAA / EU Remote ID broadcaster, and the French *signalement électronique* | Decoded Remote ID over BLE and WiFi: serial, position, altitude, speed, operator / take-off location |
| **Camera glasses** | Ray-Ban / Oakley Meta, Snap Spectacles, Vuzix, HeyCyan-based glasses such as Nilox Smart AI Glasses | Company IDs `0x0D53`, `0x03C2`, `0x060C`, Meta UUIDs, the HeyCyan SDK UUID, name tokens |
| **Fake cell towers** | IMSI catchers / cell-site simulators | Test network codes, sudden 4G→2G, cloned or reserved cell identities, unexpected networks |
| **Police aircraft** *(online, off by default)* | Police, sheriff, state patrol, federal and RCMP / provincial police aircraft, and unlisted aircraft circling low overhead | Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries |
| **Waze reports** *(online, off by default)* | Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), each with its own level: sound and voice, notification only, or silent. Shows what Waze says it is (hiding, mobile speed camera...) | Two sources: your own OpenWeb Ninja API key, or *Waze direct* (opt-in: no key, free, sends Waze your IP address and a position rounded to a 1 km grid). You set the alert range (100 m to 10 km), the map range, and how often Waze is asked (15 s to 5 min direct, 2 to 10 min OpenWeb Ninja), slower when parked and faster on fast roads. Scored by distance, age and driver confirmations and re-scored every second as you move, so an alert fires the moment a report comes into range, not at the next check. Optional: only alert for reports ahead of you, and spoken call-outs at 1 km, 500 m and 200 m. Third-party service, at your own risk |
| **Card skimmers** | Bluetooth modules inside gas-pump and ATM skimmers | HC-05 / HC-06 / HC-03 / RN42 / BT04-A names, serial-port service |
-| **Hacking tools** *(off by default)* | Flipper Zero, Pwnagotchi, WiFi Pineapple, ESP deauthers, evil twin WiFi networks, Bluetooth spam floods | Flipper UUIDs / company ID `0x0E29` / IEEE block, Pwnagotchi beacon JSON, default SSIDs, same network name from two makers with mismatched security, bursts of new pairing pop-ups |
+| **Hacking tools** *(off by default)* | Flipper Zero, Pwnagotchi, WiFi Pineapple, ESP deauthers, evil twin WiFi networks, Bluetooth spam floods, **WiFi deauth attacks** | Flipper UUIDs / company ID `0x0E29` / IEEE block, Pwnagotchi beacon JSON, default SSIDs, same network name from two makers with mismatched security, bursts of new pairing pop-ups; with a USB WiFi adapter, floods of unprotected deauthentication frames knocking devices off a network |
+| **Emergency vehicles (V2X, Europe)** | Police, fire, ambulance and safety cars that broadcast European car-to-car radio (ITS-G5) | Needs an ESP32-C5 with the [V2X2MAP](https://github.com/pit711/V2X2MAP) firmware: the vehicle's own role, light bar and siren state and position (CAM), and its "emergency vehicle approaching" warnings (DENM). Ordinary cars are counted, not listed. Not in North America, which uses C-V2X |
| **Action & hidden cameras** *(off by default)* | GoPro, Insta360, DJI Osmo, YI, SJCAM, AKASO, Garmin VIRB, Ricoh THETA, Kodak PIXPRO, Sony action cams, Apeman, Campark...; WiFi spy cameras in setup mode (V380, LookCam Pro, TinyCam Pro, HDSmartIPC) | GoPro company ID `0x02F2` / UUIDs `0xFEA5` `0xFEA6`, Insta360 (Arashi Vision) `0x10D7` / `0xFC30`, IEEE blocks, names |
| **Network cameras** *(off by default)* | Arlo, Blink, Ezviz, Wyze, Ring, Verkada, Avigilon Alta, Axis, Hanwha, Bosch, FLIR, March Networks, GeoVision, Mobotix, Sunell, IDIS... | SSIDs and IEEE blocks |
@@ -109,7 +110,8 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- Payload, name, UUID and company-ID signatures plus IEEE vendor prefixes (MA-L / MA-M / MA-S), each with a cited source and a confidence
- **Evidence fusion:** independent matches on one device strengthen each other (noisy-OR, capped at 90)
- **Patrol-vehicle detection:** police-type gear whose signals rise and fall together is grouped as a possible police vehicle
-- **Address-rotation linking:** keeps following a device when its Bluetooth address changes
+- **Address-rotation linking:** keeps following a device when its Bluetooth address changes, including in Locate
+- **Pinpointing:** a flagged device you pass from more than one side is placed where it most likely is, from its signal at every spot you passed (multilateration), with a circle it's very likely in; a straight road that can't tell the side gets a circle covering both. GPS runs precise every second while a flagged device is in range (Settings → Location, on by default)
- **Follower alerts:** a tracker or flagged device that stays with you (default 10 min and 800 m, adjustable) raises *may be following you*
- **Remote ID drones** decoded live, with a *drone overhead* alert within 200 m
- Optional **cell tower change alert**: says so each time the phone moves to another serving tower (Settings; a change while parked is a classic fake-tower sign)
@@ -129,6 +131,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- Sound, vibration pattern per tier (1 / 2 / 3 pulses) and spoken announcements through the phone's own speech engine (prioritised, voice and speed pickers)
- **Radar-detector beeps** option: after an alert, beeps speed up as the flagged device gets closer
- **Short spoken alerts** option ("Body cam", "Police car", "Speed camera, 50")
+- **Voice loudness** boost up to +15 dB (without distorting) for when music drowns the voice, in the car too, and an option to **pause music** while an alert is spoken
- Discreet mode, adjustable alert threshold, mute from the app or the car
- **Floating threat bubble** over Waze, Google Maps or any app, with a pop-up card saying what was just detected
- **Floating mini map** over other apps: the devices and known cameras around you, like the app's map (pinch to zoom, drag, resize)
@@ -136,7 +139,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- Notification, Quick Settings tile and home-screen widget
**Map & history**
-- OpenStreetMap map with your GPS trace and every device pinned exactly where its signal peaked (tap a spot to list everything heard there), the same filter chips as the list (including Waze, which draws reports as coloured dots by type), self-centering
+- OpenStreetMap map with your GPS trace and every device pinned where its signal peaked, flagged devices at their pinpointed spot with its circle (tap a spot to list everything heard there), the same filter chips as the list (including Waze, which draws reports as coloured dots by type), self-centering
- Optional **cell tower layer** (or the map's **Cells** chip): every tower seen while scanning, at the spot where its signal was strongest
- **Record traces** of your route and the devices along it, with the screen off (with the network names each device asked for, when a USB adapter or Marauder board is plugged in)
- **History map & timeline:** heatmap of where flagged equipment showed up, and when (hour of day, day of week)
@@ -150,6 +153,8 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- ESP32 boards over USB OTG (OUI-Spy, GhostESP, Marauder incl. dual-band ESP32-C5 boards, or through a Flipper Zero) or Bluetooth (OUI-SPY App-Controlled) add their detections and extend range
- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz; 5 GHz experimental, Settings → External hardware), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically
- **Requested networks:** the WiFi names nearby devices ask for (probe requests), from a USB adapter or a Marauder board, in an optional list; **watch** a name to get an alert whenever any device asks for it
+- **Record frames to .pcap** for Wireshark (Settings → External hardware): every frame a USB WiFi adapter or V2X board hears, with its channel and signal
+- The ALFA AWUS036ACS's light blinks with received traffic
- **More from every frame:** WPS maker / model / device name, a **probe fingerprint** that survives MAC randomization (watchable: "every device of this type"), and the real name of **hidden networks** when a device joins them
**Interface**
@@ -160,6 +165,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- Device details: evidence, identity, decoded data, signal graph, **Locate** mode, history, raw advertisement
- Setup wizard (theme, region, alerts and voice, bubble, car start, camera warnings, cell alerts, camera radius, screen, permissions); Settings save themselves
- **Check for updates** (menu ⋮): compares with the latest GitHub release, only when you tap it
+- **Screen rotation** (Settings → General): normal, auto-rotate **including upside down**, or always upside down with the USB-C port at the top for an antenna or adapter - even on phones like the Pixel that never auto-rotate upside down
- 13 themes, including the **DedSec** (Watch Dogs 2) and **fsociety** (Mr. Robot) fan themes
**Data & privacy**
@@ -463,6 +469,14 @@ counts, and only as a weak sign. Consumer walkie-talkies (FRS / GMRS, MURS),
marine, railroad, weather and paging channels are skipped. The dongle's log is in
the exported USB adapter log.
+**Cellular transmitters** (optional, off by default): it can also watch the phone /
+modem side of the in-range LTE bands (600, 700 including Band 14 - the public-safety
+broadband block FirstNet uses in the US - 850 and part of 1700 MHz) for a transmitter
+close to you: a vehicle modem, a Cradlepoint-style router, a camera with a SIM. Energy
+only, nothing decoded or identified, and towers (which use the other half of each band)
+are never watched. A phone counts too, so it's a weak sign on its own; it matters when
+it travels with you or lines up with a device flagged over WiFi / Bluetooth.
+
Hits show in the **main list** (the *Radio* filter, or under *All*): frequency,
its name when known, signal above the noise, and whether it's **getting closer or
moving away**. The dongle's status shows on the main screen next to the other
@@ -731,8 +745,12 @@ detection and WiFi identification, is in [docs/SIGNATURES.md](docs/SIGNATURES.md
Inspired by the nyanBOX hardware device and the RF Party app, which was based
on Alan Meekins' DEF CON 31 talk *"Snoop Unto Them As They Snoop Unto Us"*.
-Some feature ideas come from SØPHIA and BLE Radar (MetaRadar). No code from
-those projects is included. The USB WiFi monitor-mode driver for RTL8811AU /
+Some feature ideas come from SØPHIA, BLE Radar (MetaRadar) and ESPsoup. No code from
+those projects is included. European V2X (ITS-G5) frames are read the way
+[V2X2MAP](https://github.com/pit711/V2X2MAP) by Peter Holzhauser does (MIT; see
+`esp/V2X2MAP-LICENSE`), with the CAM / DENM messages decoded from ETSI's own ASN.1.
+Tracker service IDs follow [AirGuard](https://github.com/seemoo-lab/AirGuard) by
+SEEMOO / TU Darmstadt (Apache-2.0). The USB WiFi monitor-mode driver for RTL8811AU /
RTL8821AU adapters (`app/src/main/java/com/rfsentinel/app/usb/`) is ported from
[Wardrive Go](https://github.com/RocketGod-git/wardrive-go) by RocketGod (GPL-3.0),
whose register tables come from Realtek's 88xxau Linux driver
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index f08ee6e..7ab051d 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -7,8 +7,8 @@ plugins {
}
// Bump both for every release. versionName ends up in the APK file name.
-val appVersionCode = 41
-val appVersionName = "2.17.0"
+val appVersionCode = 42
+val appVersionName = "2.18.0"
// Release signing credentials live in keystore.properties (git-ignored).
// Without that file, release builds are produced unsigned.
diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
index d315f6f..5bdf5ac 100644
--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
@@ -23,6 +23,21 @@ class RFSentinelApp : Application() {
/** Lives as long as the process. */
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ /**
+ * Settings > General > Screen rotation, while the app is open. The status bar and Android's own
+ * navigation bar or gestures turn with the display and work as usual. Phones like the Pixel never
+ * auto-rotate to upside down, but honour an app that asks for it: "full user" follows auto-rotate in
+ * all four directions (and stays put when rotation is locked); reverse portrait is always upside down.
+ */
+ fun applyOrientation(a: android.app.Activity) {
+ val wanted = when (com.rfsentinel.app.util.Prefs.rotation(a)) {
+ com.rfsentinel.app.util.Prefs.Rotation.UPSIDE_DOWN -> android.content.pm.ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
+ com.rfsentinel.app.util.Prefs.Rotation.ALL_WAYS -> android.content.pm.ActivityInfo.SCREEN_ORIENTATION_FULL_USER
+ com.rfsentinel.app.util.Prefs.Rotation.NORMAL -> android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
+ }
+ if (a.requestedOrientation != wanted) a.requestedOrientation = wanted
+ }
+
override fun onCreate() {
super.onCreate()
com.rfsentinel.app.util.CrashLog.install(this)
@@ -32,8 +47,8 @@ class RFSentinelApp : Application() {
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityStarted(a: android.app.Activity) { visibleActivities++ }
override fun onActivityStopped(a: android.app.Activity) { visibleActivities = (visibleActivities - 1).coerceAtLeast(0) }
- override fun onActivityCreated(a: android.app.Activity, b: android.os.Bundle?) {}
- override fun onActivityResumed(a: android.app.Activity) {}
+ override fun onActivityCreated(a: android.app.Activity, b: android.os.Bundle?) = applyOrientation(a)
+ override fun onActivityResumed(a: android.app.Activity) = applyOrientation(a)
override fun onActivityPaused(a: android.app.Activity) {}
override fun onActivitySaveInstanceState(a: android.app.Activity, b: android.os.Bundle) {}
override fun onActivityDestroyed(a: android.app.Activity) {}
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
index 8c320fe..fa791c1 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
@@ -217,8 +217,8 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
.sortedBy { DeviceColors.isFlagged(it) }
.mapNotNull { s ->
val rid = s.remoteId?.takeIf { it.hasPosition }
- val lat = rid?.latitude ?: s.bestPosition?.lat ?: return@mapNotNull null
- val lon = rid?.longitude ?: s.bestPosition?.lon ?: return@mapNotNull null
+ val lat = rid?.latitude ?: s.place?.lat ?: return@mapNotNull null
+ val lon = rid?.longitude ?: s.place?.lon ?: return@mapNotNull null
val best = s.best
val color = when {
best == null -> DevicesMapScreen.ORDINARY_COLOR
diff --git a/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt
index 315141e..acbc1e6 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt
@@ -125,8 +125,8 @@ class DevicesMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs
DeviceRegistry.snapshot().mapNotNull { s ->
if (WhitelistCache.contains(s.mac)) return@mapNotNull null
val rid = s.remoteId?.takeIf { it.hasPosition }
- val pLat = rid?.latitude ?: s.bestPosition?.lat ?: return@mapNotNull null
- val pLon = rid?.longitude ?: s.bestPosition?.lon ?: return@mapNotNull null
+ val pLat = rid?.latitude ?: s.place?.lat ?: return@mapNotNull null
+ val pLon = rid?.longitude ?: s.place?.lon ?: return@mapNotNull null
val best = s.best
val flagged = DeviceColors.isFlagged(s)
val item = Item(
diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt
index c1f1de3..b5a94e8 100644
--- a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt
@@ -147,14 +147,14 @@ class NearbyMapScreen(
.joinToString(" · ").ifEmpty { "Remote ID" },
dLat, dLon, d, drone = true, mac = s.mac)
}
- // Flagged devices where your phone heard them best (the same spot as on the phone map).
+ // Flagged devices where they were pinpointed, else where your phone heard them best (the same spot as on the phone map).
val devices = DeviceRegistry.snapshot().mapNotNull { s ->
val best = s.best ?: return@mapNotNull null
if (com.rfsentinel.app.data.WhitelistCache.contains(s.mac) || s.remoteId?.hasPosition == true) return@mapNotNull null
- val pos = s.bestPosition ?: return@mapNotNull null
+ val pos = s.place ?: return@mapNotNull null
val d = DeviceRegistry.metersBetween(lat, lon, pos.lat, pos.lon)
if (d > SEARCH_RADIUS_M) return@mapNotNull null
- Item(best.label, best.category.shortTag + " \u00b7 heard here", pos.lat, pos.lon, d, drone = false, mac = s.mac,
+ Item(best.label, best.category.shortTag + if (s.located != null) " \u00b7 pinpointed" else " \u00b7 heard here", pos.lat, pos.lon, d, drone = false, mac = s.mac,
deviceColor = if (best.tier == com.rfsentinel.app.detect.Tier.WEAK) com.rfsentinel.app.ui.DeviceColors.WEAK else best.category.colorArgb)
}
// Drones first (they move and matter now), then flagged devices, then cameras by distance.
diff --git a/app/src/main/java/com/rfsentinel/app/detect/Category.kt b/app/src/main/java/com/rfsentinel/app/detect/Category.kt
index fc0d55a..5dffd5b 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/Category.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/Category.kt
@@ -31,7 +31,9 @@ enum class Category(
/** Bluetooth serial modules built into gas-pump / ATM card skimmers (BLE names, receive-only). */
SKIMMER("Card skimmers (gas pumps, ATMs)", "SKIMMER", 0xFF6D4C41.toInt(), true),
/** Off by default: plenty of hobbyists carry a Flipper. */
- HACKER("Hacking tools: Flipper Zero, Pwnagotchi, WiFi Pineapple, evil twin WiFi, Bluetooth spam", "HACKER", 0xFFD81B60.toInt(), false),
+ HACKER("Hacking tools: Flipper Zero, Pwnagotchi, WiFi Pineapple, evil twin WiFi, Bluetooth spam, WiFi deauth attacks", "HACKER", 0xFFD81B60.toInt(), false),
+ /** European V2X (ITS-G5) radio, through an ESP32-C5 running the V2X2MAP firmware. */
+ V2X("Emergency vehicles over V2X radio (Europe, needs an ESP32-C5 with the V2X2MAP firmware)", "V2X", 0xFFD32F2F.toInt(), true),
CUSTOM("Your watchlist", "WATCHLIST", 0xFFC8431A.toInt(), true);
companion object {
diff --git a/app/src/main/java/com/rfsentinel/app/detect/Locator.kt b/app/src/main/java/com/rfsentinel/app/detect/Locator.kt
new file mode 100644
index 0000000..89cae07
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/detect/Locator.kt
@@ -0,0 +1,191 @@
+package com.rfsentinel.app.detect
+
+import kotlin.math.cos
+import kotlin.math.hypot
+import kotlin.math.log10
+import kotlin.math.max
+import kotlin.math.roundToInt
+import kotlin.math.sqrt
+
+/**
+ * Pinpoints a stationary device from signal readings taken at many spots as you move past it
+ * (RSSI multilateration, the way wardriving tools place access points).
+ *
+ * Model: rssi = P0 - 10 n log10(d). The device's power at 1 m (P0) is unknown and fitted for
+ * every candidate spot, within what real radios can do, so a far device can't pass for a
+ * loud near one. Every spot on a grid around your route is scored, and the result is the
+ * best-fitting spot with a 95 % circle - so when you only drove a straight line and
+ * the device could be on either side of the road, the circle honestly covers both sides
+ * instead of guessing one.
+ *
+ * Pure (no Android), unit-tested.
+ */
+object Locator {
+
+ /** One reading: where your phone was and how strong the device was there. */
+ data class Reading(val time: Long, val lat: Double, val lon: Double, val rssi: Int)
+
+ data class Estimate(
+ val lat: Double,
+ val lon: Double,
+ /** 95 % circle: the device is very likely within this many metres. */
+ val radiusM: Double,
+ /** Distinct spots (about [CELL_M] m apart) the fit used. */
+ val spots: Int,
+ val readings: Int,
+ /** How far apart the farthest two of those spots are. */
+ val baselineM: Double,
+ val time: Long
+ )
+
+ /** Readings closer than this are one spot; its strongest reading counts (fades only ever weaken a signal). */
+ const val CELL_M = 4.0
+ const val MIN_SPOTS = 4
+ /** Spots must spread at least this far, else every direction fits about as well. */
+ const val MIN_BASELINE_M = 15.0
+ /** Readings older than this are dropped: a parked car may leave. */
+ const val WINDOW_MS = 10 * 60_000L
+ /** Rough signal noise (dB) from body, car and multipath fades. */
+ private const val SIGMA_DB = 6.0
+ /** A fit this far off means the device moved (or the model doesn't hold): no estimate. */
+ private const val MAX_RMS_DB = 10.0
+ private const val GRID = 90
+ private const val MAX_SPOTS = 120
+ /** A route whose spots spread less than this across their main direction counts as one straight line. */
+ private const val STRAIGHT_M = 6.0
+ /** GPS error added to every circle. */
+ private const val GPS_ERROR_M = 5.0
+
+ /** Path-loss exponent and the range of plausible powers at 1 m, per radio. */
+ private class Radio(val n: Double, val p0Min: Double, val p0Max: Double, val reachM: Double)
+ private val BLE = Radio(n = 2.5, p0Min = -85.0, p0Max = -35.0, reachM = 150.0)
+ private val WIFI = Radio(n = 2.5, p0Min = -60.0, p0Max = -15.0, reachM = 250.0)
+
+ fun estimate(readings: List<Reading>, wifi: Boolean, now: Long = readings.maxOfOrNull { it.time } ?: 0L): Estimate? {
+ val recent = readings.filter { now - it.time <= WINDOW_MS }
+ if (recent.size < MIN_SPOTS) return null
+ val radio = if (wifi) WIFI else BLE
+ val lat0 = recent.map { it.lat }.average()
+ val lon0 = recent.map { it.lon }.average()
+ val mx = 111_320.0 * cos(Math.toRadians(lat0))
+ val my = 110_540.0
+
+ // One spot per ~4 m cell: where the phone was (average) and the strongest reading there.
+ class Spot(var x: Double, var y: Double, var rssi: Int, var n: Int)
+ val cells = HashMap<Long, Spot>()
+ for (r in recent) {
+ val x = (r.lon - lon0) * mx
+ val y = (r.lat - lat0) * my
+ val key = ((x / CELL_M).roundToInt().toLong() shl 32) xor ((y / CELL_M).roundToInt().toLong() and 0xFFFFFFFFL)
+ val s = cells[key]
+ if (s == null) cells[key] = Spot(x, y, r.rssi, 1)
+ else { s.x += (x - s.x) / (s.n + 1); s.y += (y - s.y) / (s.n + 1); s.n++; s.rssi = max(s.rssi, r.rssi) }
+ }
+ // The strongest spots say the most (and keep the fit quick on a long drive past it).
+ val spots = cells.values.sortedByDescending { it.rssi }.take(MAX_SPOTS)
+ if (spots.size < MIN_SPOTS) return null
+ var baseline = 0.0
+ for (i in spots.indices) for (j in i + 1 until spots.size)
+ baseline = max(baseline, hypot(spots[i].x - spots[j].x, spots[i].y - spots[j].y))
+ if (baseline < MIN_BASELINE_M) return null
+
+ // Search everywhere the device could be heard from: the spots' box plus the radio's reach.
+ val minX = spots.minOf { it.x } - radio.reachM; val maxX = spots.maxOf { it.x } + radio.reachM
+ val minY = spots.minOf { it.y } - radio.reachM; val maxY = spots.maxOf { it.y } + radio.reachM
+ val step = max(maxX - minX, maxY - minY) / GRID
+ val xs = DoubleArray(spots.size) { spots[it].x }
+ val ys = DoubleArray(spots.size) { spots[it].y }
+ val rs = DoubleArray(spots.size) { spots[it].rssi.toDouble() }
+ val tenN = 10 * radio.n
+
+ // Squared error at a candidate spot, with the device's power fitted (within what radios can do).
+ val logD = DoubleArray(spots.size)
+ fun sseAt(gx: Double, gy: Double): Double {
+ var p0 = 0.0
+ for (k in xs.indices) {
+ val dx = gx - xs[k]; val dy = gy - ys[k]
+ logD[k] = tenN / 2 * log10(max(dx * dx + dy * dy, 1.0)) // 10 n log10(d), d at least 1 m
+ p0 += rs[k] + logD[k]
+ }
+ p0 = (p0 / xs.size).coerceIn(radio.p0Min, radio.p0Max)
+ var e = 0.0
+ for (k in xs.indices) { val d = rs[k] - (p0 - logD[k]); e += d * d }
+ return e
+ }
+
+ val nx = ((maxX - minX) / step).toInt() + 1
+ val ny = ((maxY - minY) / step).toInt() + 1
+ val sse = DoubleArray(nx * ny)
+ var best = 0
+ for (iy in 0 until ny) for (ix in 0 until nx) {
+ val i = iy * nx + ix
+ sse[i] = sseAt(minX + ix * step, minY + iy * step)
+ if (sse[i] < sse[best]) best = i
+ }
+ // The best spot, refined on a finer grid around the coarse one.
+ var bx = minX + (best % nx) * step; var by = minY + (best / nx) * step
+ var bestSse = sse[best]
+ val fine = step / 8
+ val cx0 = bx; val cy0 = by
+ for (j in -8..8) for (i in -8..8) {
+ val gx = cx0 + i * fine; val gy = cy0 + j * fine
+ val e = sseAt(gx, gy)
+ if (e < bestSse) { bestSse = e; bx = gx; by = gy }
+ }
+ val rms = sqrt(bestSse / spots.size)
+ if (rms > MAX_RMS_DB) return null
+
+ // 95 % region: every spot that fits nearly as well (chi-square, 2 degrees of freedom).
+ // The noise is never taken below what the best fit itself shows.
+ val sigma2 = max(SIGMA_DB * SIGMA_DB, bestSse / max(1, spots.size - 3))
+ val region = sse.indices.filter { (sse[it] - bestSse) / sigma2 <= 5.99 }
+ fun gx(i: Int) = minX + (i % nx) * step
+ fun gy(i: Int) = minY + (i / nx) * step
+
+ // Driving one straight line can't tell which side of it the device is: both sides fit.
+ // Then the centre goes on your line and the circle covers both sides, instead of a coin toss.
+ var cx = bx; var cy = by
+ val mX = spots.map { it.x }.average(); val mY = spots.map { it.y }.average()
+ var sxx = 0.0; var syy = 0.0; var sxy = 0.0
+ for (sp in spots) { val dx = sp.x - mX; val dy = sp.y - mY; sxx += dx * dx; syy += dy * dy; sxy += dx * dy }
+ sxx /= spots.size; syy /= spots.size; sxy /= spots.size
+ val half = (sxx + syy) / 2; val root = sqrt(((sxx - syy) / 2).let { it * it } + sxy * sxy)
+ val minorSpread = sqrt(max(0.0, half - root))
+ if (minorSpread < STRAIGHT_M) {
+ // Unit vector along the route (largest spread) and across it.
+ val ang = 0.5 * kotlin.math.atan2(2 * sxy, sxx - syy)
+ val ux = cos(ang); val uy = kotlin.math.sin(ang)
+ val across = { x: Double, y: Double -> (x - mX) * -uy + (y - mY) * ux }
+ val side = max(step, 2 * STRAIGHT_M)
+ if (region.any { across(gx(it), gy(it)) > side } && region.any { across(gx(it), gy(it)) < -side }) {
+ val along = (bx - mX) * ux + (by - mY) * uy
+ cx = mX + along * ux; cy = mY + along * uy
+ }
+ }
+ var reach = 0.0
+ for (i in region) reach = max(reach, hypot(gx(i) - cx, gy(i) - cy))
+ reach = max(reach, hypot(bx - cx, by - cy))
+ val radius = hypot(reach + step / 2, GPS_ERROR_M)
+ // No better than "somewhere within reach": not worth showing.
+ if (radius > radio.reachM) return null
+
+ return Estimate(
+ lat = lat0 + cy / my, lon = lon0 + cx / mx, radiusM = radius,
+ spots = spots.size, readings = recent.size, baselineM = baseline, time = now
+ )
+ }
+
+ /**
+ * A fix moved on by [speedMs] along [bearingDeg] for [ageS] seconds (at most 3 s, and not when
+ * nearly stopped: the course is noise then).
+ */
+ fun ahead(lat: Double, lon: Double, speedMs: Double, bearingDeg: Double, ageS: Double): Pair<Double, Double> {
+ if (speedMs < 1.0 || ageS <= 0.0) return lat to lon
+ val d = speedMs * ageS.coerceAtMost(3.0)
+ val b = Math.toRadians(bearingDeg)
+ return (lat + d * cos(b) / 110_540.0) to (lon + d * kotlin.math.sin(b) / (111_320.0 * cos(Math.toRadians(lat))))
+ }
+
+ /** "±12 m from 18 spots" */
+ fun describe(e: Estimate): String = "±${e.radiusM.roundToInt()} m from ${e.spots} spots you passed"
+}
diff --git a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt
index 23cfbc4..c56a673 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt
@@ -79,6 +79,7 @@ object SignatureEngine {
private const val UUID_REMOTE_ID = 0xFFFA // ASTM Remote ID (SIG SDO UUID)
private const val UUID_SMARTTAG = 0xFD5A // Samsung Electronics
private const val UUID_TILE = 0xFEED // Tile, Inc.
+ private const val UUID_CHIPOLO = 0xFE33 // CHIPOLO d.o.o. (as AirGuard, SEEMOO / TU Darmstadt, Apache-2.0)
private const val UUID_GOOGLE_FMDN = 0xFEAA // Google LLC (Eddystone / Find Hub)
private const val UUID_SPECTACLES = 0xFE45 // Snapchat Inc
private val META_UUIDS = setOf(0xFEB7, 0xFEB8) // Meta Platforms, Inc.
@@ -295,6 +296,10 @@ object SignatureEngine {
(a.serviceData[Advert.uuid16(UUID_TILE)] ?: a.serviceData[Advert.uuid16(UUID_TILE_2)])?.takeIf { it.isNotEmpty() }?.let {
hits += Hit(Category.TRACKER, "Tile tracker", 55, "Service data on UUID 0xFEED / 0xFEEC (Tile, Inc.)", SIG)
}
+ // Chipolo tags often broadcast no name: their own service UUID gives them away.
+ if (a.serviceData.keys.contains(Advert.uuid16(UUID_CHIPOLO)) || a.serviceUuids.contains(Advert.uuid16(UUID_CHIPOLO))) {
+ hits += Hit(Category.TRACKER, "Chipolo tracker", 55, "Service UUID 0xFE33 (CHIPOLO d.o.o.)", "$SIG; AirGuard (SEEMOO, Apache-2.0)")
+ }
// ---- Smart / recording glasses --------------------------------------
if (a.serviceUuids.any { it == HEYCYAN || it == HEYCYAN_REVERSED } ||
diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
index 31d49f2..9ec2011 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
@@ -6,8 +6,12 @@ package com.rfsentinel.app.esp
* Detector mode, `CMD:DUMP_LIVE` (what it has found so far); GhostESP is only
* asked for `help`, to scan networks and to list them; ESP32 Marauder only for
* `help` and its passive `sniffbeacon` / `sniffprobe` sniffers; a FREE-WiLi 2 ([freeWili])
- * only gets its console's WiFi-menu keys and its access-point scan.
+ * only gets its console's WiFi-menu keys and its access-point scan. An ESP32-C5 with the
+ * V2X2MAP firmware streams on its own and is never sent anything that changes it ([pollV2x]).
*/
+/** V2X frames carry no signal strength (the board sends the frame only); its position is what counts. */
+private const val V2X_NOMINAL_RSSI = -70
+
class EspReader(
private val port: SerialPort,
private val onStatus: (String) -> Unit,
@@ -23,8 +27,10 @@ class EspReader(
if (freeWili) { pollFreeWili(buf); return }
onStatus("ESP32 · listening…")
// 1. OUI-Spy prints on its own (banners, status, detections).
- var heard = readFor(buf, 4_000) { OuiSpyReports.recognises(it) }
+ var heard = readFor(buf, 4_000) { OuiSpyReports.recognises(it) || it.contains(V2x.MAGIC) }
if (stopped) return
+ // An ESP32-C5 with the V2X2MAP firmware streams European V2X frames on its own.
+ if (heard.contains(V2x.MAGIC)) { pollV2x(buf); return }
// 2. Detector, PCAP and BLE-sniff modes answer a version request.
if (!OuiSpyReports.recognises(heard)) {
port.write("CMD:VERSION\n")
@@ -67,7 +73,7 @@ class EspReader(
"OUI-Spy is in its mode selector - join its Wi-Fi \"oui-spy\", open 192.168.4.1 and pick Flock-You, Detector or Sky Spy"
mode == OuiSpyReports.Mode.OTHER ->
"This OUI-Spy mode isn't used by RF Sentinel - pick Flock-You, Detector or Sky Spy"
- mode == null && count == 0 -> "ESP32 connected · waiting for detections (OUI-Spy reports only when it finds something)"
+ mode == null && count == 0 -> "ESP32 connected · waiting for detections (OUI-Spy reports only when it finds something; a V2X board only when equipped vehicles are in range)"
else -> "OUI-Spy ${mode?.label ?: ""} · live · $count detection${if (count == 1) "" else "s"}"
})
fun consume(text: String) {
@@ -93,6 +99,8 @@ class EspReader(
var askedDump = mode == OuiSpyReports.Mode.DETECTOR
while (!stopped) {
val n = port.read(buf, 500)
+ // A quiet V2X board only starts streaming once a vehicle is in range.
+ if (n > 0 && V2x.looksLikeStream(buf, n)) { pollV2x(buf, buf.copyOf(n)); return }
if (n > 0) consume(String(buf, 0, n))
if (!askedDump && mode == OuiSpyReports.Mode.DETECTOR) {
askedDump = true
@@ -218,6 +226,60 @@ class EspReader(
runCatching { port.write("q\r") }
}
+ /**
+ * ESP32-C5 with the V2X2MAP firmware (pit711/V2X2MAP): European V2X (ITS-G5) frames, streamed by
+ * the board without being asked. Emergency vehicles (their role, light bar and siren, and their
+ * "emergency vehicle approaching" warnings) are passed on at the position they broadcast;
+ * ordinary traffic is only counted. Every frame also goes to a .pcap recording when one runs.
+ * Nothing is ever sent to the board.
+ */
+ private fun pollV2x(buf: ByteArray, first: ByteArray? = null) {
+ val stream = V2x.Stream()
+ val stations = HashMap<String, Long>()
+ /** Stations known to be emergency vehicles, with their last match (status-only frames carry no role). */
+ val emergency = HashMap<String, Pair<Long, com.rfsentinel.app.detect.Hit>>()
+ val batch = LinkedHashMap<String, EspSighting>()
+ var frames = 0L
+ fun status() {
+ val now = System.currentTimeMillis()
+ stations.entries.removeAll { now - it.value > 60_000 }
+ emergency.entries.removeAll { now - it.value.first > 5 * 60_000 }
+ val live = emergency.count { now - it.value.first < 60_000 }
+ onStatus("V2X (ITS-G5) · live · ${stations.size} stations in range" +
+ (if (live > 0) " · $live emergency vehicle${if (live == 1) "" else "s"}" else "") + " · $frames frames")
+ }
+ fun handle(bytes: ByteArray, n: Int) {
+ val now = System.currentTimeMillis()
+ for (f in stream.feed(bytes, n)) {
+ frames++
+ com.rfsentinel.app.usb.PcapRecorder.frame(f, 0, f.size, V2x.CCH_MHZ, null, now)
+ val m = V2x.decode(f) ?: continue
+ stations[m.mac] = now
+ val hit = V2x.hit(m) ?: emergency[m.mac]?.second ?: continue
+ emergency[m.mac] = now to hit
+ val lat = m.lat ?: continue; val lon = m.lon ?: continue
+ batch[m.mac] = EspSighting(
+ mac = m.mac, rssi = V2X_NOMINAL_RSSI, ble = false,
+ name = "V2X ${V2x.typeName(m.stationType)}", frequencyMhz = V2x.CCH_MHZ,
+ hits = listOf(hit), position = lat to lon
+ )
+ }
+ }
+ status()
+ first?.let { handle(it, it.size) }
+ var lastFlush = System.currentTimeMillis()
+ while (!stopped) {
+ val n = port.read(buf, 300)
+ if (n > 0) handle(buf, n)
+ val now = System.currentTimeMillis()
+ if (now - lastFlush >= 1_000) {
+ if (batch.isNotEmpty()) { onSightings(batch.values.toList()); batch.clear() }
+ status()
+ lastFlush = now
+ }
+ }
+ }
+
/** Reads for up to [ms], stopping early once [done] is true for what was read. */
private fun readFor(buf: ByteArray, ms: Long, done: (String) -> Boolean = { false }): String {
val sb = StringBuilder()
diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt
index af3fba4..2df209e 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt
@@ -28,7 +28,9 @@ data class EspSighting(
/** A Wi-Fi client device (heard sending probe requests), not an access point. */
val client: Boolean = false,
/** Network names a client asked for by name (probe requests). */
- val probedSsids: List<String> = emptyList()
+ val probedSsids: List<String> = emptyList(),
+ /** Where the device says it is (a V2X vehicle's own GPS), as latitude to longitude. */
+ val position: Pair<Double, Double>? = null
)
/**
diff --git a/app/src/main/java/com/rfsentinel/app/esp/V2X2MAP-LICENSE b/app/src/main/java/com/rfsentinel/app/esp/V2X2MAP-LICENSE
new file mode 100644
index 0000000..00bd240
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/esp/V2X2MAP-LICENSE
@@ -0,0 +1,24 @@
+MIT License
+
+Copyright (c) 2026 Peter Holzhauser and contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+This repository contains a fork of opentrafficmap/its-g5-receiver-firmware
+(also under MIT-style terms) — see firmware/main/ for upstream files.
diff --git a/app/src/main/java/com/rfsentinel/app/esp/V2x.kt b/app/src/main/java/com/rfsentinel/app/esp/V2x.kt
new file mode 100644
index 0000000..e120017
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/esp/V2x.kt
@@ -0,0 +1,344 @@
+package com.rfsentinel.app.esp
+
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Hit
+
+/**
+ * European V2X (ETSI ITS-G5, 802.11p at 5.9 GHz) heard by an ESP32-C5 running the V2X2MAP
+ * firmware (pit711/V2X2MAP, MIT): the board streams every frame it hears over USB as
+ * `"ITS5" | sec u32 | usec u32 | len u16 | 802.11 frame`, all little-endian.
+ *
+ * Cars, emergency vehicles and roadside units broadcast where they are (CAM) and warnings
+ * (DENM). RF Sentinel only looks for emergency vehicles: a CAM whose vehicle role is
+ * emergency / rescue / safety car, its light bar and siren, and DENM "emergency vehicle
+ * approaching" warnings. Ordinary cars are counted but not listed.
+ *
+ * The 802.11 / GeoNetworking / BTP layout follows V2X2MAP's ItsG5Decoder (MIT); the CAM and
+ * DENM bodies are read here from ETSI's own ASN.1 (CAM EN 302 637-2 v1.3.2 / v1.4.1, DENM
+ * EN 302 637-3 v1.3.1), checked against messages encoded by asn1tools. Receive-only.
+ */
+object V2x {
+
+ const val MAGIC = "ITS5"
+ private const val HEADER_LEN = 14
+ private const val MAX_PAYLOAD = 4096
+ private const val ETHERTYPE_GN = 0x8947
+ /** The ITS-G5 control channel the firmware listens on (for .pcap recordings). */
+ const val CCH_MHZ = 5900
+
+ /** Splits the board's byte stream into frames, skipping anything that isn't one (boot text, logs). */
+ class Stream {
+ private var buf = ByteArray(0)
+
+ fun feed(chunk: ByteArray, n: Int): List<ByteArray> {
+ buf += chunk.copyOf(n)
+ val out = ArrayList<ByteArray>()
+ while (true) {
+ val m = indexOfMagic(buf)
+ if (m < 0) { buf = buf.copyOfRange(maxOf(0, buf.size - 3), buf.size); return out }
+ if (m > 0) buf = buf.copyOfRange(m, buf.size)
+ if (buf.size < HEADER_LEN) return out
+ val len = (buf[12].toInt() and 0xff) or ((buf[13].toInt() and 0xff) shl 8)
+ if (len > MAX_PAYLOAD) { buf = buf.copyOfRange(4, buf.size); continue } // not a real header: resync
+ if (buf.size < HEADER_LEN + len) return out
+ out += buf.copyOfRange(HEADER_LEN, HEADER_LEN + len)
+ buf = buf.copyOfRange(HEADER_LEN + len, buf.size)
+ }
+ }
+
+ private fun indexOfMagic(b: ByteArray): Int {
+ for (i in 0..b.size - 4) if (b[i] == 'I'.code.toByte() && b[i + 1] == 'T'.code.toByte() &&
+ b[i + 2] == 'S'.code.toByte() && b[i + 3] == '5'.code.toByte()) return i
+ return -1
+ }
+ }
+
+ /** True when [b] (first [n] bytes) holds the start of the V2X board's stream. */
+ fun looksLikeStream(b: ByteArray, n: Int): Boolean {
+ for (i in 0..n - 4) if (b[i] == 'I'.code.toByte() && b[i + 1] == 'T'.code.toByte() &&
+ b[i + 2] == 'S'.code.toByte() && b[i + 3] == '5'.code.toByte()) return true
+ return false
+ }
+
+ enum class Kind { CAM, DENM, OTHER }
+
+ /** One decoded frame. Position: the CAM's or DENM's own (the sender's GPS), else the GeoNetworking one. */
+ data class Message(
+ val mac: String,
+ val kind: Kind,
+ val stationType: Int?,
+ val lat: Double?,
+ val lon: Double?,
+ val speedMps: Double? = null,
+ val headingDeg: Double? = null,
+ val role: Int? = null,
+ /** Which special-vehicle container it carried (0 public transport .. 6 safety car). */
+ val special: Int? = null,
+ val lightBar: Boolean? = null,
+ val siren: Boolean? = null,
+ val cause: Int? = null,
+ val subCause: Int? = null,
+ val secured: Boolean = false
+ )
+
+ // ---- 802.11 / LLC / GeoNetworking / BTP ---------------------------------------------------------
+
+ private val HDR_LENGTHS = intArrayOf(24, 26, 30, 32)
+
+ fun decode(p: ByteArray): Message? {
+ if (p.size < 24) return null
+ val mac = (10 until 16).joinToString(":") { "%02X".format(p[it].toInt() and 0xff) } // transmitter (addr2)
+ for (hdr in HDR_LENGTHS) {
+ if (p.size < hdr + 8 + 4 + 8) continue
+ if (p[hdr] != 0xAA.toByte() || p[hdr + 1] != 0xAA.toByte() || p[hdr + 2] != 0x03.toByte() ||
+ p[hdr + 3] != 0.toByte() || p[hdr + 4] != 0.toByte() || p[hdr + 5] != 0.toByte()) continue
+ val et = ((p[hdr + 6].toInt() and 0xff) shl 8) or (p[hdr + 7].toInt() and 0xff)
+ if (et != ETHERTYPE_GN) return null
+ val basic = hdr + 8
+ val common = basic + 4
+ // Basic header next-header 2 = secured (IEEE 1609.2 / TS 103 097): signed, not encrypted;
+ // the common header sits a few bytes into the envelope.
+ val secured = (p[basic].toInt() and 0x0f) == 2
+ val inner = if (secured) findCommonHeader(p, common, minOf(common + 20, p.size - 36)).takeIf { it >= 0 } ?: continue
+ else common
+ if (p.size < inner + 8) continue
+ val ht = (p[inner + 1].toInt() shr 4) and 0x0f
+ val hst = p[inner + 1].toInt() and 0x0f
+ val ext = when (ht) { 1 -> 4; 2 -> 48; 3 -> 56; 4 -> 44; 5 -> 28; 6 -> 36; else -> 28 }
+ val lpv = inner + 8 + if (ht == 5 && hst == 0) 0 else 4
+ val btp = inner + 8 + ext
+ if (p.size < btp + 4 || p.size < lpv + 24) continue
+ // Source position vector: station type in the address, then position, speed, heading.
+ val gnType = ((p[lpv].toInt() and 0xff) shr 2) and 0x1f
+ val gnLat = be32(p, lpv + 12) / 1e7
+ val gnLon = be32(p, lpv + 16) / 1e7
+ val gnOk = gnLat in -90.0..90.0 && gnLon in -180.0..180.0 && (gnLat != 0.0 || gnLon != 0.0)
+ val port = ((p[btp].toInt() and 0xff) shl 8) or (p[btp + 1].toInt() and 0xff)
+ val body = btp + 4
+ val decoded = when (port) {
+ 2001 -> cam(p, body)
+ 2002 -> denm(p, body)
+ else -> null
+ }
+ val base = Message(mac, when (port) { 2001 -> Kind.CAM; 2002 -> Kind.DENM; else -> Kind.OTHER },
+ gnType, if (gnOk) gnLat else null, if (gnOk) gnLon else null, secured = secured)
+ if (decoded == null) return base
+ return decoded.copy(mac = mac, secured = secured,
+ stationType = decoded.stationType ?: gnType,
+ lat = decoded.lat ?: base.lat, lon = decoded.lon ?: base.lon)
+ }
+ return null
+ }
+
+ private fun findCommonHeader(p: ByteArray, start: Int, end: Int): Int {
+ for (off in start until end) {
+ if (off + 8 > p.size) break
+ val nh = (p[off].toInt() and 0xff) ushr 4
+ val ht = (p[off + 1].toInt() and 0xff) ushr 4
+ val plen = ((p[off + 4].toInt() and 0xff) shl 8) or (p[off + 5].toInt() and 0xff)
+ if (nh in 0..2 && ht in 4..6 && plen in 1..999) return off
+ }
+ return -1
+ }
+
+ private fun be32(p: ByteArray, i: Int) = ((p[i].toInt() and 0xff) shl 24) or ((p[i + 1].toInt() and 0xff) shl 16) or
+ ((p[i + 2].toInt() and 0xff) shl 8) or (p[i + 3].toInt() and 0xff)
+
+ // ---- CAM (UPER) ----------------------------------------------------------------------------------
+
+ /** A CAM starting at [at] (the ITS PDU header). Null when it isn't one this reader knows. */
+ fun cam(p: ByteArray, at: Int): Message? = runCatching { readCam(p, at) }.getOrNull()
+
+ private fun readCam(p: ByteArray, at: Int): Message? {
+ val b = Bits(p, at)
+ val version = b.int(8)
+ if (b.int(8) != 2 || version !in 1..2) return null // messageID 2 = CAM; version 1 (CDD 1.2.1) or 2 (CDD 1.3.1)
+ b.skip(32 + 16) // stationID, generationDeltaTime
+ b.skip(1) // CamParameters extension bit
+ val hasLow = b.bit(); val hasSpecial = b.bit()
+ // BasicContainer (extensible)
+ val basicExt = b.bit()
+ val stationType = b.int(8)
+ val (lat, lon) = referencePosition(b)
+ if (basicExt) b.skipExtensions()
+ // HighFrequencyContainer: vehicle (0) or roadside unit (1)
+ if (b.bit()) return Message("", Kind.CAM, stationType, lat, lon)
+ if (b.int(1) == 1) return Message("", Kind.CAM, stationType, lat, lon)
+ val opt = b.int(7)
+ val heading = b.int(12); b.skip(7)
+ val speed = b.int(14); b.skip(7)
+ b.skip(2) // drive direction
+ b.skip(10 + 3) // vehicle length
+ b.skip(6) // width
+ b.skip(9 + 7) // longitudinal acceleration
+ b.skip(if (version == 1) 16 else 11); b.skip(3) // curvature (its range changed in CDD 1.3.1)
+ if (b.bit()) return null else b.skip(2) // curvature calculation mode (extensible enum)
+ b.skip(16 + 4) // yaw rate
+ if (opt and 0x40 != 0) b.skip(7) // acceleration control
+ if (opt and 0x20 != 0) b.skip(4) // lane position
+ if (opt and 0x10 != 0) b.skip(10 + 7) // steering wheel angle
+ if (opt and 0x08 != 0) b.skip(9 + 7) // lateral acceleration
+ if (opt and 0x04 != 0) b.skip(9 + 7) // vertical acceleration
+ if (opt and 0x02 != 0) b.skip(3) // performance class
+ if (opt and 0x01 != 0) { // CEN DSRC tolling zone (extensible from CDD 1.3.1)
+ val ext = version >= 2 && b.bit()
+ val id = b.bit(); b.skip(31 + 32); if (id) b.skip(27)
+ if (ext) b.skipExtensions()
+ }
+ var role: Int? = null
+ if (hasLow) {
+ if (b.bit()) return msg(stationType, lat, lon, speed, heading, null) // an extension we don't know
+ role = b.int(4)
+ b.skip(8) // exterior lights
+ val points = b.int(6)
+ repeat(points) {
+ val dt = b.bit()
+ b.skip(18 + 18 + 15)
+ if (dt) { if (b.bit()) b.skipLength() else b.skip(16) }
+ }
+ }
+ var special: Int? = null; var light: Boolean? = null; var siren: Boolean? = null
+ if (hasSpecial && !b.bit()) {
+ special = b.int(3)
+ val lb: Int? = when (special) {
+ 1 -> { b.skip(4); b.int(2) } // special transport
+ 3 -> { val sub = b.bit(); b.bit(); if (sub) b.skip(8); b.int(2) } // road works
+ 4 -> b.int(2) // rescue
+ 5 -> { b.skip(2); b.int(2) } // emergency
+ 6 -> { b.skip(3); b.int(2) } // safety car
+ else -> null
+ }
+ if (lb != null) { light = lb and 0x2 != 0; siren = lb and 0x1 != 0 }
+ }
+ return msg(stationType, lat, lon, speed, heading, role).copy(special = special, lightBar = light, siren = siren)
+ }
+
+ private fun msg(type: Int, lat: Double?, lon: Double?, speed: Int, heading: Int, role: Int?) = Message(
+ "", Kind.CAM, type, lat, lon,
+ speedMps = if (speed == 16383) null else speed / 100.0,
+ headingDeg = if (heading == 3601) null else heading / 10.0,
+ role = role
+ )
+
+ /** ReferencePosition; null coordinates when the sender marks them unavailable. */
+ private fun referencePosition(b: Bits): Pair<Double?, Double?> {
+ val lat = b.long(31) - 900_000_000L
+ val lon = b.long(32) - 1_800_000_000L
+ b.skip(12 + 12 + 12 + 20 + 4) // confidence ellipse, altitude
+ val ok = lat in -900_000_000L..900_000_000L && lon in -1_800_000_000L..1_800_000_000L
+ return if (ok) lat / 1e7 to lon / 1e7 else null to null
+ }
+
+ // ---- DENM (UPER, EN 302 637-3 v1.3.1) ----------------------------------------------------------------
+
+ fun denm(p: ByteArray, at: Int): Message? = runCatching { readDenm(p, at) }.getOrNull()
+
+ private fun readDenm(p: ByteArray, at: Int): Message? {
+ val b = Bits(p, at)
+ val version = b.int(8)
+ if (b.int(8) != 1 || version != 2) return null // messageID 1 = DENM, v1.3.1
+ b.skip(32)
+ val hasSituation = b.bit(); b.bit(); b.bit() // situation, location, à-la-carte
+ // ManagementContainer (extensible)
+ val mgmtExt = b.bit()
+ val term = b.bit(); val relDist = b.bit(); val relDir = b.bit(); val validity = b.bit(); val interval = b.bit()
+ b.skip(32 + 16) // action ID
+ b.skip(42 + 42) // detection and reference time
+ if (term) b.skip(1)
+ val (lat, lon) = referencePosition(b)
+ if (relDist) b.skip(3)
+ if (relDir) b.skip(2)
+ if (validity) b.skip(17)
+ if (interval) b.skip(14)
+ val stationType = b.int(8)
+ if (mgmtExt) b.skipExtensions()
+ if (!hasSituation) return Message("", Kind.DENM, stationType, lat, lon)
+ // SituationContainer (extensible): information quality, then the cause (extensible in CDD 1.3.1)
+ b.bit(); b.bit(); b.bit()
+ b.skip(3)
+ b.bit()
+ val cause = b.int(8)
+ val sub = b.int(8)
+ return Message("", Kind.DENM, stationType, lat, lon, cause = cause, subCause = sub)
+ }
+
+ // ---- What RF Sentinel makes of it ----------------------------------------------------------------
+
+ private val ROLES = mapOf(1 to "public transport", 2 to "special transport", 3 to "dangerous goods", 4 to "road works",
+ 5 to "rescue", 6 to "emergency", 7 to "safety car", 8 to "agriculture", 9 to "commercial", 10 to "military",
+ 11 to "road operator", 12 to "taxi")
+ private val TYPES = mapOf(0 to "unknown", 1 to "pedestrian", 2 to "cyclist", 3 to "moped", 4 to "motorcycle",
+ 5 to "car", 6 to "bus", 7 to "light truck", 8 to "heavy truck", 9 to "trailer", 10 to "special vehicle",
+ 11 to "tram", 15 to "roadside unit")
+
+ fun typeName(t: Int?) = t?.let { TYPES[it] ?: "type $it" } ?: "unknown"
+
+ /** True for an emergency, rescue or safety car (its role, its special container or its warning). */
+ fun isEmergency(m: Message): Boolean =
+ m.role in setOf(5, 6, 7) || m.special in setOf(4, 5, 6) || (m.kind == Kind.DENM && m.cause == 95)
+
+ /**
+ * The match for an emergency vehicle, or null for everything else. Lights and siren on is the
+ * strongest; a DENM "emergency vehicle approaching" is the vehicle's own warning to traffic ahead.
+ */
+ fun hit(m: Message): Hit? {
+ if (!isEmergency(m)) return null
+ val active = m.lightBar == true || m.siren == true
+ val what = when {
+ m.kind == Kind.DENM && m.subCause == 2 -> "Priority vehicle approaching"
+ m.kind == Kind.DENM -> "Emergency vehicle approaching"
+ m.role == 5 || m.special == 4 -> "Rescue vehicle"
+ m.role == 7 || m.special == 6 -> "Safety car"
+ else -> "Emergency vehicle"
+ }
+ val state = when {
+ m.lightBar == true && m.siren == true -> " - lights and siren on"
+ m.lightBar == true -> " - lights on"
+ m.siren == true -> " - siren on"
+ else -> ""
+ }
+ val evidence = buildString {
+ append(if (m.kind == Kind.DENM) "V2X warning (ETSI DENM, cause ${m.cause}/${m.subCause})" else "V2X status broadcast (ETSI CAM)")
+ m.role?.let { append(" · vehicle role: ${ROLES[it] ?: "default"}") }
+ append(" · station: ${typeName(m.stationType)}")
+ m.lightBar?.let { append(" · light bar ${if (it) "on" else "off"}") }
+ m.siren?.let { append(" · siren ${if (it) "on" else "off"}") }
+ m.speedMps?.let { append(" · %.0f km/h".format(java.util.Locale.US, it * 3.6)) }
+ m.headingDeg?.let { append(" · heading %.0f°".format(java.util.Locale.US, it)) }
+ if (m.secured) append(" · signed message")
+ append(". Position is the vehicle's own GPS.")
+ }
+ val confidence = when {
+ m.kind == Kind.DENM || active -> 97
+ else -> 85
+ }
+ return Hit(Category.V2X, what + state, confidence, evidence, "V2X")
+ }
+
+ // ---- Unaligned PER bit reader --------------------------------------------------------------------
+
+ private class Bits(private val b: ByteArray, startByte: Int) {
+ private var pos = startByte * 8L
+ fun bit(): Boolean {
+ val i = (pos / 8).toInt()
+ if (i >= b.size) throw IndexOutOfBoundsException("end of message")
+ val v = (b[i].toInt() shr (7 - (pos % 8).toInt())) and 1
+ pos++
+ return v == 1
+ }
+ fun long(n: Int): Long { var v = 0L; repeat(n) { v = (v shl 1) or (if (bit()) 1L else 0L) }; return v }
+ fun int(n: Int): Int = long(n).toInt()
+ fun skip(n: Int) { repeat(n) { bit() } }
+ /** An unconstrained length determinant (up to 16383) followed by that many bytes. */
+ fun skipLength() {
+ val len = if (!bit()) int(7) else { if (bit()) throw IllegalStateException("fragmented"); int(14) }
+ skip(len * 8)
+ }
+ /** The extension additions of an extensible SEQUENCE: a bitmap, then each present one as an open type. */
+ fun skipExtensions() {
+ val n = if (!bit()) int(6) + 1 else throw IllegalStateException("too many extensions")
+ val present = (0 until n).count { bit() }
+ repeat(present) { skipLength() }
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt
index 42d17c6..2d90f67 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt
@@ -25,7 +25,8 @@ object RadioSettings {
fun config(context: Context): RadioWatch.Config {
val off = Prefs.radioBandsOff(context)
return RadioWatch.Config(
- bands = BUILT_IN.filter { it.first !in off }.map { it.second } + customBands(Prefs.radioCustomBands(context)),
+ bands = BUILT_IN.filter { it.first !in off }.map { it.second } + customBands(Prefs.radioCustomBands(context)) +
+ (if (Prefs.radioCellOn(context)) RadioWatch.LTE_UPLINK_BANDS else emptyList()),
excluded = ranges(Prefs.radioExcluded(context)).map { it.first },
targets = targets(Prefs.radioTargets(context)),
minSnrDb = Prefs.radioMinSnr(context)
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
index dfe14fd..8982459 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
@@ -21,7 +21,7 @@ import kotlin.math.sin
*/
class RadioWatch {
- enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED, CUSTOM, TARGET }
+ enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED, CUSTOM, TARGET, CELLULAR_UPLINK }
data class Band(val label: String, val startHz: Long, val endHz: Long, val kind: Kind)
@@ -82,6 +82,7 @@ class RadioWatch {
val found = ArrayList<Event>()
val cfg = config
for (band in cfg.bands) {
+ if (band.kind == Kind.CELLULAR_UPLINK) { widebandScan(band, centerHz, psdDb, sampleRate, now, cfg, found); continue }
var f = ((maxOf(band.startHz, centerHz - USABLE_HZ.toLong()) + STEP_HZ - 1) / STEP_HZ) * STEP_HZ
val last = minOf(band.endHz, centerHz + USABLE_HZ.toLong())
while (f <= last) {
@@ -120,11 +121,63 @@ class RadioWatch {
if (acc.none { kotlin.math.abs(it.freqHz - e.freqHz) <= SPLATTER_HZ }) acc += e
acc
}
- for (e in kept) if (!e.repeat) (if (e.target != null) targetState else channels)[e.freqHz]?.lastEvent = now
+ for (e in kept) if (!e.repeat) {
+ (if (e.target != null) targetState else channels)[e.freqHz]?.lastEvent = now
+ cells[e.freqHz]?.lastEvent = now
+ }
return kept
}
private val targetState = HashMap<Long, Channel>()
+ private val cells = HashMap<Long, Cell>()
+
+ private class Cell {
+ var visits = 0
+ /** Slowly-learned quiet level of this slice (dB); a transmitter shows as a rise above it. */
+ var baseline = Float.NaN
+ var lastEvent = Long.MIN_VALUE / 2
+ }
+
+ /** Cellular uplink slices learned so far (for the log). */
+ val cellSlices: Int get() = cells.size
+
+ /**
+ * Wideband energy in one ~1.6 MHz slice of a cellular UPLINK band - the side the phone, modem or
+ * router transmits on, not the tower. A device transmitting nearby lifts the whole slice above its
+ * learned quiet level. Signal strength only: nothing is demodulated, and it can't tell one device
+ * or carrier from another - only that something cellular is transmitting close by, and roughly how
+ * close. Towers transmit on the downlink bands, which this never looks at, so a steady uplink rise
+ * that travels with you is a device travelling with you.
+ */
+ private fun widebandScan(band: Band, centerHz: Long, psdDb: FloatArray, sampleRate: Int, now: Long,
+ cfg: Config, found: ArrayList<Event>) {
+ val nn = psdDb.size
+ val binHz = sampleRate.toDouble() / nn
+ val usableBins = (USABLE_HZ / binHz).toInt()
+ val vals = ArrayList<Float>(2 * usableBins)
+ for (i in nn / 2 - usableBins..nn / 2 + usableBins) {
+ if (i !in 0 until nn) continue
+ val f = centerHz + (((i - nn / 2) * binHz).roundToInt()).toLong()
+ if (kotlin.math.abs(f - centerHz) <= DC_GUARD_HZ) continue
+ if (f < band.startHz || f > band.endHz || excluded(f, cfg)) continue
+ vals += psdDb[i]
+ }
+ if (vals.size < 16) return
+ vals.sort()
+ val floor = vals[vals.size / 2] // slice noise floor (median)
+ val level = vals[(vals.size * 7) / 10] // how high the busier 30 % of the slice sits
+ val cell = cells.getOrPut(centerHz) { Cell() }
+ cell.visits++
+ @Suppress("UNUSED_VARIABLE") val slice = floor // in-slice noise floor, kept for the log/debug
+ if (cell.baseline.isNaN()) cell.baseline = level
+ val rise = (level - cell.baseline).roundToInt()
+ val active = rise >= CELL_RISE_DB
+ // Learn the quiet level only while nothing is transmitting, so a passing device isn't learned away.
+ if (!active) cell.baseline = cell.baseline * (1 - CELL_ALPHA) + level * CELL_ALPHA
+ if (cell.visits < LEARN_SWEEPS || !active) return
+ val confidence = if (rise >= CELL_RISE_DB * 3) 55 else 40
+ found += Event(centerHz, rise, band, confidence, repeat = now - cell.lastEvent < REPEAT_MS)
+ }
/** [min]: the sensitivity setting; at the default (30 dB) the thresholds are the original ones. */
private fun eventFor(f: Long, snr: Int, band: Band, ch: Channel, now: Long, min: Int = DEFAULT_MIN_SNR): Event? {
@@ -152,6 +205,26 @@ class RadioWatch {
/** Default sensitivity: 30 dB above the noise (the original public-safety threshold). */
const val DEFAULT_MIN_SNR = 30
private const val TARGET_CONFIDENCE = 70
+ /** A cellular uplink slice must rise this many dB above its learned quiet level to count. */
+ private const val CELL_RISE_DB = 8
+ /** How fast the learned quiet level follows a slow ambient drift (a gentle rise is not a transmitter). */
+ private const val CELL_ALPHA = 0.1f
+
+ /**
+ * North-American LTE/5G FDD UPLINK bands within the RTL-SDR's tuning range (~24-1766 MHz) - the
+ * frequencies a handset, modem or router TRANSMITS on (towers use the paired downlink bands, which
+ * are left out on purpose, so a tower never looks like a device). The 1850-1915 MHz PCS uplink and
+ * the 5G mid-band are above the dongle's range and can't be watched. Receive-only, energy only.
+ */
+ val LTE_UPLINK_BANDS = listOf(
+ Band("Cellular uplink - 600 MHz (Band 71)", 663_000_000L, 698_000_000L, Kind.CELLULAR_UPLINK),
+ Band("Cellular uplink - 700 MHz lower (Band 12/17)", 698_000_000L, 716_000_000L, Kind.CELLULAR_UPLINK),
+ Band("Cellular uplink - 700 MHz upper (Band 13)", 776_000_000L, 788_000_000L, Kind.CELLULAR_UPLINK),
+ // Band 14: the public-safety broadband block (FirstNet in the US; AT&T phones may use spare capacity).
+ Band("Cellular uplink - 700 MHz public-safety broadband (Band 14, FirstNet)", 788_000_000L, 798_000_000L, Kind.CELLULAR_UPLINK),
+ Band("Cellular uplink - 850 MHz (Band 5/26)", 814_000_000L, 849_000_000L, Kind.CELLULAR_UPLINK),
+ Band("Cellular uplink - AWS 1700 MHz (Band 4/66, partial)", 1_710_000_000L, 1_766_000_000L, Kind.CELLULAR_UPLINK)
+ )
/** North American (FCC) public-safety land-mobile bands. */
val BANDS = listOf(
diff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
index b6901aa..3f6285a 100644
--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
@@ -9,6 +9,7 @@ import com.rfsentinel.app.detect.PatrolCluster
import com.rfsentinel.app.detect.WifiFingerprint
import com.rfsentinel.app.detect.DeviceIntel
import com.rfsentinel.app.detect.Hit
+import com.rfsentinel.app.detect.Locator
import com.rfsentinel.app.detect.RemoteId
import java.util.ArrayDeque
import java.util.concurrent.ConcurrentHashMap
@@ -40,6 +41,10 @@ object DeviceRegistry {
private const val RSSI_SMOOTHING = 0.3
private const val SMOOTH_RESET_MS = 10_000L
private const val ROTATION_WINDOW_MS = 30_000L
+ /** Pinpointing: readings kept per flagged device, their spacing, and how often the fit is redone. */
+ private const val LOCATE_MAX = 400
+ private const val LOCATE_SPACING_MS = 400L
+ private const val LOCATE_EVERY_MS = 5_000L
data class Sample(val time: Long, val rssi: Int)
data class GeoSample(val time: Long, val lat: Double, val lon: Double)
@@ -69,9 +74,15 @@ object DeviceRegistry {
val history: List<Sample>,
val path: List<GeoSample>,
/** Where YOUR phone was when this device's signal was strongest (approximate device position). */
- val bestPosition: GeoSample?
+ val bestPosition: GeoSample?,
+ /** Flagged devices only: pinpointed from readings at many spots (see [Locator]), when you moved enough around it. */
+ val located: Locator.Estimate? = null,
+ /** Where the device says it is (a V2X vehicle's own GPS): exact, so it wins over any estimate. */
+ val broadcast: GeoSample? = null
) {
val best: Hit? get() = hits.firstOrNull()
+ /** Where to put it on a map: the pinpointed spot when there is one, else where YOUR phone heard it strongest. */
+ val place: GeoSample? get() = broadcast ?: located?.let { GeoSample(it.time, it.lat, it.lon) } ?: bestPosition
/**
* True when this address has no history from an earlier session. The
* history row is looked up once, when the device is first heard this
@@ -112,6 +123,12 @@ object DeviceRegistry {
/** The device's own strongest recent match, held for [HIT_HOLD_MS] after it was last seen. */
var heldHit: Hit? = null
var heldUntil = 0L
+ /** Readings (your position + signal) for pinpointing; kept only while it has a match. */
+ val readings = ArrayDeque<Locator.Reading>()
+ var located: Locator.Estimate? = null
+ var locatedAt = 0L
+ var readingsSinceFit = 0
+ var broadcast: GeoSample? = null
}
private val tracks = ConcurrentHashMap<String, Track>()
@@ -135,7 +152,8 @@ object DeviceRegistry {
vendor: String?,
remoteId: RemoteId.Info?,
location: GeoSample?,
- now: Long = System.currentTimeMillis()
+ now: Long = System.currentTimeMillis(),
+ broadcast: GeoSample? = null
): Boolean {
var isFirst = false
val t = tracks.computeIfAbsent(a.mac) { isFirst = true; Track(a.mac, now) }
@@ -150,6 +168,7 @@ object DeviceRegistry {
if (identity.facts.size >= t.identity.facts.size || t.identity.type == "Device") t.identity = identity
t.hits = mergeHits(t, hits, now)
remoteId?.let { t.remoteId = it }
+ broadcast?.let { t.broadcast = it }
// Smooth for the displayed signal, distance and radar; a jump after a pause is taken as is.
t.smoothRssi = if (t.smoothRssi.isNaN() || now - t.lastSeen > SMOOTH_RESET_MS) a.rssi.toDouble()
else t.smoothRssi + RSSI_SMOOTHING * (a.rssi - t.smoothRssi)
@@ -167,7 +186,13 @@ object DeviceRegistry {
t.path.addLast(location)
if (t.path.size > 200) t.path.removeFirst()
}
+ if (location != null && t.hits.isNotEmpty() && (t.readings.isEmpty() || now - t.readings.last.time >= LOCATE_SPACING_MS)) {
+ t.readings.addLast(Locator.Reading(now, location.lat, location.lon, a.rssi))
+ if (t.readings.size > LOCATE_MAX) t.readings.removeFirst()
+ t.readingsSinceFit++
+ }
}
+ relocate(t, now)
return isFirst
}
@@ -190,6 +215,30 @@ object DeviceRegistry {
return merged.sortedByDescending { it.confidence }
}
+ /**
+ * Refits a flagged device's position from its readings, at most every [LOCATE_EVERY_MS] and only
+ * after new readings. A device that travels with you is never pinned to one spot. The fit runs
+ * on its own thread, outside the device's lock, so neither the scanners nor the screens wait for it.
+ */
+ private fun relocate(t: Track, now: Long) {
+ val (readings, wifi) = synchronized(t) {
+ if (t.readingsSinceFit == 0 || now - t.locatedAt < LOCATE_EVERY_MS) return
+ t.locatedAt = now
+ t.readingsSinceFit = 0
+ if (t.following) { t.located = null; return }
+ t.readings.toList() to (t.advert?.isWifi == true)
+ }
+ fitter.execute {
+ val fit = runCatching { Locator.estimate(readings, wifi, now) }.getOrNull()
+ synchronized(t) { t.located = fit }
+ }
+ }
+
+ private val fitter = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "locator").apply { isDaemon = true } }
+
+ /** Waits for the position fits already queued (tests). */
+ fun awaitFits() { fitter.submit {}.get() }
+
/**
* Address-rotation linking: if exactly one device with the same advert
* fingerprint went silent shortly before this new address appeared, treat
@@ -229,6 +278,20 @@ object DeviceRegistry {
}
}
+ /**
+ * The address [mac] goes by now: follows its address rotations forward (a tag or phone that changed
+ * its random address and was linked by its advert fingerprint). [mac] itself when it never rotated.
+ */
+ fun currentAddress(mac: String): String {
+ var cur = mac
+ repeat(8) {
+ val next = tracks.values.firstOrNull { t -> synchronized(t) { t.linkedFrom == cur } }?.mac ?: return cur
+ if (next == cur) return cur
+ cur = next
+ }
+ return cur
+ }
+
/** The address this device used before its address rotated, if it was linked. */
fun linkedFrom(mac: String): String? = tracks[mac]?.let { synchronized(it) { it.linkedFrom } }
@@ -337,7 +400,9 @@ object DeviceRegistry {
advert = if (full) t.advert else null,
history = if (full) t.history.toList() else emptyList(),
path = if (full) t.path.toList() else emptyList(),
- bestPosition = t.bestPosition
+ bestPosition = t.bestPosition,
+ located = t.located,
+ broadcast = t.broadcast
)
/**
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 bb3bd03..c367f02 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -99,6 +99,8 @@ class ScanForegroundService : Service() {
private const val PLACING_MAX_AGE_MS = 30_000L
private const val ESP_HIT_TTL_MS = 5 * 60_000L
private const val PLACING_MAX_ACCURACY_M = 50f
+ /** Pinpointing: precise 1 s fixes for this long after a flagged device was last heard. */
+ private const val LOCATING_HOLD_MS = 120_000L
/**
* Maps on screen (phone or car). While any is, location switches to precise
@@ -180,7 +182,17 @@ class ScanForegroundService : Service() {
@Volatile private var lastLocation: Location? = null
private var locationListening = false
- private var locationFastMode = false
+ /** 0 = balanced, 1 = precise every 3 s, 2 = precise every second (pinpointing a flagged device). */
+ private var locationMode = 0
+ /** A flagged device was heard recently: GPS runs precise and fast so it can be pinpointed. */
+ @Volatile private var locatingUntil = 0L
+ private val locatingHandler = android.os.Handler(Looper.getMainLooper())
+ private val locatingCheck = object : Runnable {
+ override fun run() {
+ val left = locatingUntil - System.currentTimeMillis()
+ if (left > 0) locatingHandler.postDelayed(this, left + 1_000) else updateLocationUpdates()
+ }
+ }
/** Radar-detector sound style: last good GPS fix, to say "GPS connected" when it locks or comes back. */
private var lastGoodGpsAt = 0L
@@ -279,6 +291,7 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.esp.EspBoards.start(this) { list -> pipeline.post { list.forEach(::processEsp) } }
// A USB WiFi adapter in monitor mode (e.g. AWUS036ACS): access points and client devices.
com.rfsentinel.app.usb.UsbWifi.start(this) { list -> pipeline.post { list.forEach(::processUsbWifi) } }
+ com.rfsentinel.app.usb.DeauthWatch.onAttack = { a -> pipeline.post { onDeauth(a) } }
// An RTL-SDR dongle: strong two-way radio transmissions nearby (signal strength only).
if (Prefs.categoryEnabled(this, Category.RADIO)) {
// Settings > RTL-SDR radio: bands, excluded ranges, watched frequencies, sensitivity (re-read on every refresh).
@@ -339,6 +352,31 @@ class ScanForegroundService : Service() {
) == PackageManager.PERMISSION_GRANTED
/** A fix good enough to pin a device on the map: under 30 s old and within ~50 m. */
+ /**
+ * Where you are now: the last fix moved on by your speed and course for the second or two
+ * since it came, so readings taken between fixes aren't placed behind you.
+ */
+ private fun placeNow(l: Location, now: Long): DeviceRegistry.GeoSample {
+ val ageS = (android.os.SystemClock.elapsedRealtimeNanos() - l.elapsedRealtimeNanos) / 1e9
+ val (lat, lon) = if (l.hasSpeed() && l.hasBearing())
+ com.rfsentinel.app.detect.Locator.ahead(l.latitude, l.longitude, l.speed.toDouble(), l.bearing.toDouble(), ageS)
+ else l.latitude to l.longitude
+ return DeviceRegistry.GeoSample(now, lat, lon)
+ }
+
+ /** A flagged device was heard: keep precise, fast GPS on for a while so it can be pinpointed. */
+ private fun noteLocating() {
+ val now = System.currentTimeMillis()
+ val was = now < locatingUntil
+ locatingUntil = now + LOCATING_HOLD_MS
+ // Called for every packet of a flagged device: only the switch-on does the setting / permission checks.
+ if (!was && Prefs.pinpointFlagged(this) && hasFineLocation()) {
+ updateLocationOnMain()
+ locatingHandler.removeCallbacks(locatingCheck)
+ locatingHandler.postDelayed(locatingCheck, LOCATING_HOLD_MS + 1_000)
+ }
+ }
+
private fun usableForPlacing(l: Location): Boolean {
val ageMs = (android.os.SystemClock.elapsedRealtimeNanos() - l.elapsedRealtimeNanos) / 1_000_000
return ageMs in 0..PLACING_MAX_AGE_MS && (!l.hasAccuracy() || l.accuracy <= PLACING_MAX_ACCURACY_M)
@@ -391,22 +429,26 @@ class ScanForegroundService : Service() {
* Location is needed for GPS tagging, follower alerts, trace recording and
* known-camera warnings. While recording or watching for cameras, GPS fixes
* come every ~3 s / 5 m; otherwise balanced fixes every ~20 s / 25 m to save battery.
+ * While a flagged device is in range (pinpointing on), every second.
*/
@SuppressLint("MissingPermission") // checked by hasFineLocation()
fun updateLocationUpdates() {
+ val locating = Prefs.pinpointFlagged(this) && System.currentTimeMillis() < locatingUntil
val wanted = hasFineLocation() &&
(Prefs.gpsTaggingEnabled(this) || Prefs.followerAlerts(this) || TripRecorder.isRecording || knownAlprActive() ||
- mapVisible || onlineActive())
+ mapVisible || onlineActive() || locating)
// Frequent fixes while recording a trace or watching for known cameras
// (at highway speed a 20 s interval could skip right past one).
- val fast = TripRecorder.isRecording || knownAlprActive() || mapVisible
+ val fast = TripRecorder.isRecording || knownAlprActive() || mapVisible || locating
+ val mode = when { locating -> 2; fast -> 1; else -> 0 }
+ val intervalMs = if (locating) 1_000L else 3_000L
val lm = getSystemService(LOCATION_SERVICE) as LocationManager
- if (locationListening && (!wanted || fast != locationFastMode)) {
+ if (locationListening && (!wanted || mode != locationMode)) {
lm.removeUpdates(locationListener)
locationListening = false
}
if (wanted && !locationListening) {
- locationFastMode = fast
+ locationMode = mode
val providers = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
lm.hasProvider(LocationManager.FUSED_PROVIDER)
) {
@@ -420,15 +462,15 @@ class ScanForegroundService : Service() {
// Fused location defaults to "balanced" (often WiFi/cell, ~100 m, and
// paused while it thinks you're stationary): too coarse to warn about a
// camera a few hundred metres ahead. Fast mode asks for real GPS.
- val request = android.location.LocationRequest.Builder(if (fast) 3_000L else 20_000L)
+ val request = android.location.LocationRequest.Builder(if (fast) intervalMs else 20_000L)
.setQuality(
if (fast) android.location.LocationRequest.QUALITY_HIGH_ACCURACY
else android.location.LocationRequest.QUALITY_BALANCED_POWER_ACCURACY
)
- .setMinUpdateDistanceMeters(if (fast) 5f else 25f)
+ .setMinUpdateDistanceMeters(if (locating) 0f else if (fast) 5f else 25f)
.build()
lm.requestLocationUpdates(p, request, mainExecutor, locationListener)
- } else if (fast) lm.requestLocationUpdates(p, 3_000L, 5f, locationListener, Looper.getMainLooper())
+ } else if (fast) lm.requestLocationUpdates(p, intervalMs, if (locating) 0f else 5f, locationListener, Looper.getMainLooper())
else lm.requestLocationUpdates(p, 20_000L, 25f, locationListener, Looper.getMainLooper())
lm.getLastKnownLocation(p)?.let { if (lastLocation == null) lastLocation = it }
} catch (e: Exception) {
@@ -447,7 +489,7 @@ class ScanForegroundService : Service() {
process(a)
}
- private fun process(a: Advert, reportedRemoteId: RemoteId.Info? = null) {
+ private fun process(a: Advert, reportedRemoteId: RemoteId.Info? = null, broadcast: DeviceRegistry.GeoSample? = null) {
val now = a.timestamp
val mac = a.mac
if (OuiWatchlist.version != watchlistVersion) recheckWatchlist(now)
@@ -473,8 +515,8 @@ class ScanForegroundService : Service() {
// Place devices only with a fresh, precise fix: a stale or WiFi/cell-based one
// (often 100 m+ off) would put the dot far from where the device really was.
val loc = lastLocation?.takeIf { usableForPlacing(it) }
- val geo = loc?.let { DeviceRegistry.GeoSample(now, it.latitude, it.longitude) }
- val isFirst = DeviceRegistry.report(a, c.hits, c.identity, c.vendor, remoteId, geo, now)
+ val geo = loc?.let { placeNow(it, now) }
+ val isFirst = DeviceRegistry.report(a, c.hits, c.identity, c.vendor, remoteId, geo, now, broadcast)
if (isFirst) serviceScope.launch { loadHistory(mac) }
if (TripRecorder.isRecording) {
TripRecorder.onDevice(
@@ -496,6 +538,7 @@ class ScanForegroundService : Service() {
this, mac, trackerHit.label, a.rssi, now, DeviceRegistry.linkedFrom(mac))
) return
if (WhitelistCache.contains(mac)) return
+ noteLocating()
maybeLog(a, best, c.vendor, loc, now)
maybeAlert(a, best, now)
@@ -568,7 +611,7 @@ class ScanForegroundService : Service() {
mac = e.mac, source = Advert.Source.WIFI, rssi = e.rssi, name = e.name,
wifi = Advert.WifiInfo(e.frequencyMhz, e.capabilities, null, emptyList(), client = e.client), timestamp = now
)
- process(advert, e.remoteId)
+ process(advert, e.remoteId, e.position?.let { DeviceRegistry.GeoSample(now, it.first, it.second) })
}
/** The watchlist version the cached classifications were made with. */
@@ -920,8 +963,9 @@ class ScanForegroundService : Service() {
}
val threshold = Prefs.alertThreshold(this)
val trend = com.rfsentinel.app.sdr.RadioLog.observe(e, name, Prefs.radioTrendDb(this), now)
+ val cell = e.band.kind == com.rfsentinel.app.sdr.RadioWatch.Kind.CELLULAR_UPLINK
if (trend != null && e.confidence >= threshold && now >= Prefs.alertsSnoozedUntil(this)) {
- AlertPlayer.callout(this, "Radio ${spokenMhz(e.freqHz)} " +
+ AlertPlayer.callout(this, (if (cell) "Cellular signal " else "Radio ${spokenMhz(e.freqHz)} ") +
if (trend == com.rfsentinel.app.sdr.RadioLog.Trend.CLOSER) "getting closer" else "moving away")
}
if (e.repeat) return // same channel within 2 minutes: list and trend only, no new log entry or alert
@@ -935,8 +979,17 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.sdr.RadioWatch.Kind.CUSTOM -> "A band you added in Settings > RTL-SDR radio."
else -> "Police use this band, but so do businesses, schools and transit; a weak sign on its own."
}
- val label = name?.let { "Radio transmitting: $it" } ?: "Two-way radio transmitting nearby"
- val hit = Hit(Category.RADIO, label, e.confidence, detail, "RTL-SDR signal strength (no decoding)")
+ val cellDetail = "A cellular transmitter is on the air nearby on ${e.mhz} MHz (${e.band.label}), " +
+ "${e.snrDb} dB above the quiet level - $near. Something is transmitting on the phone / modem side of an " +
+ "LTE band: a phone, but also a vehicle modem, a Cradlepoint-style router or a camera with a SIM. Signal " +
+ "strength only, nothing decoded - it can't tell devices or carriers apart. On its own it means little " +
+ "(phones are everywhere); it matters most when it travels with you or lines up with a device flagged over Wi-Fi / Bluetooth."
+ val label = when {
+ cell -> "Cellular transmitter nearby (LTE uplink)"
+ name != null -> "Radio transmitting: $name"
+ else -> "Two-way radio transmitting nearby"
+ }
+ val hit = Hit(Category.RADIO, label, e.confidence, if (cell) cellDetail else detail, "RTL-SDR signal strength (no decoding)")
val loc = lastLocation
val tag = Prefs.gpsTaggingEnabled(this)
serviceScope.launch {
@@ -952,8 +1005,11 @@ class ScanForegroundService : Service() {
if (e.confidence >= threshold && now >= Prefs.alertsSnoozedUntil(this)) {
NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)
// Spoken: the frequency (and its name) when that's on, else the short phrase.
- val spoken = if (Prefs.radioSpeakFreq(this)) "Radio ${spokenMhz(e.freqHz)}" + (name?.let { ", $it" } ?: "")
- else "Radio transmitting nearby"
+ val spoken = when {
+ cell -> "Cellular transmitter nearby"
+ Prefs.radioSpeakFreq(this) -> "Radio ${spokenMhz(e.freqHz)}" + (name?.let { ", $it" } ?: "")
+ else -> "Radio transmitting nearby"
+ }
AlertPlayer.play(this, hit.tier, spoken)
}
}
@@ -1037,6 +1093,35 @@ class ScanForegroundService : Service() {
}
}
+ /** A WiFi deauthentication flood heard by the USB WiFi adapter (Hacking tools category). */
+ private fun onDeauth(a: com.rfsentinel.app.usb.DeauthWatch.Attack) {
+ if (!Prefs.categoryEnabled(this, Category.HACKER)) return
+ val now = System.currentTimeMillis()
+ val ssid = DeviceRegistry.get(a.bssid)?.name
+ val net = ssid?.let { "\"$it\"" } ?: "network ${a.bssid}"
+ val detail = "${a.frames} deauthentication / disassociation frames in ${a.windowS} s for $net (channel ${a.channel})" +
+ (if (a.broadcast) ", sent to every device on it" else "") + ". Something is knocking devices off this WiFi: a jammer " +
+ "or a hacking tool (ESP32 / ESP8266 deauther, Flipper Zero WiFi board, WiFi Pineapple). A normal network sends a " +
+ "handful, never a stream. Heard by the USB WiFi adapter; nothing is sent."
+ val hit = Hit(Category.HACKER, "WiFi deauth attack on $net", if (a.broadcast) 80 else 70, detail,
+ "802.11 management frames (USB WiFi adapter, receive-only)")
+ val loc = lastLocation
+ val tag = Prefs.gpsTaggingEnabled(this)
+ serviceScope.launch {
+ AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
+ DetectionEntity(
+ mac = a.bssid, label = hit.label, source = "WIFI", rssi = 0, timestamp = now,
+ latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
+ category = Category.HACKER.name, confidence = hit.confidence, evidence = detail, deviceName = ssid
+ )
+ )
+ }
+ if (hit.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {
+ NotificationHelper.sendMapAlert(this, "deauth:" + a.bssid, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)
+ AlertPlayer.play(this, hit.tier, "WiFi attack nearby")
+ }
+ }
+
private fun onCellAnomaly(a: com.rfsentinel.app.detect.CellAnalyzer.Anomaly) {
val now = System.currentTimeMillis()
if (now - (lastCellAlert[a.key] ?: 0L) < CELL_REPEAT_MS) return
@@ -1119,9 +1204,9 @@ class ScanForegroundService : Service() {
if (Prefs.threatBubble(ctx)) com.rfsentinel.app.ui.ThreatBubble.update(ctx, level, flagged.size)
else com.rfsentinel.app.ui.ThreatBubble.hide(ctx)
if (Prefs.floatingMap(ctx)) {
- // The same dots as the full map: devices placed where they were heard strongest.
+ // The same dots as the full map: pinpointed, else where they were heard strongest.
val dots = devices.mapNotNull { s ->
- val p = s.bestPosition ?: return@mapNotNull null
+ val p = s.place ?: return@mapNotNull null
com.rfsentinel.app.ui.FloatingMap.Dot(p.lat, p.lon,
com.rfsentinel.app.ui.DeviceColors.forDevice(ctx, s), com.rfsentinel.app.ui.DeviceColors.isFlagged(s))
}
@@ -1151,6 +1236,10 @@ class ScanForegroundService : Service() {
}
override fun onDestroy() {
+ com.rfsentinel.app.usb.DeauthWatch.onAttack = null
+ com.rfsentinel.app.usb.DeauthWatch.clear()
+ com.rfsentinel.app.usb.PcapRecorder.stop()
+ locatingHandler.removeCallbacks(locatingCheck)
com.rfsentinel.app.esp.EspBoards.stop(this)
com.rfsentinel.app.usb.UsbWifi.stop(this)
com.rfsentinel.app.sdr.SdrRadio.stop(this)
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 6c48c9c..93e2939 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -162,6 +162,23 @@ class SettingsActivity : AppCompatActivity() {
val current = Prefs.voiceRate(this)
binding.voiceRateGroup.check(rates.minByOrNull { kotlin.math.abs(it.value - current) }!!.key)
binding.voiceRateGroup.setOnCheckedChangeListener { _, id -> rates[id]?.let { Prefs.setVoiceRate(this, it) } }
+ // Louder than the phone's volume alone allows: music in the car often drowns the voice.
+ fun boostLabel(db: Int) = "Voice loudness: " + if (db == 0) "normal" else "+$db dB"
+ binding.voiceBoostSlider.value = Prefs.voiceBoostDb(this).toFloat()
+ binding.voiceBoostLabel.text = boostLabel(Prefs.voiceBoostDb(this))
+ binding.voiceBoostSlider.setLabelFormatter { if (it == 0f) "normal" else "+${it.toInt()} dB" }
+ binding.voiceBoostSlider.addOnChangeListener { _, v, fromUser ->
+ binding.voiceBoostLabel.text = boostLabel(v.toInt())
+ if (fromUser) Prefs.setVoiceBoostDb(this, v.toInt())
+ }
+ binding.voiceBoostSlider.addOnSliderTouchListener(object : com.google.android.material.slider.Slider.OnSliderTouchListener {
+ override fun onStartTrackingTouch(slider: com.google.android.material.slider.Slider) {}
+ override fun onStopTrackingTouch(slider: com.google.android.material.slider.Slider) {
+ com.rfsentinel.app.util.AlertPlayer.testVoice(this@SettingsActivity, binding.shortVoiceSwitch.isChecked)
+ }
+ })
+ binding.voicePauseMusicSwitch.isChecked = Prefs.voicePausesMusic(this)
+ binding.voicePauseMusicSwitch.setOnCheckedChangeListener { _, on -> Prefs.setVoicePausesMusic(this, on) }
// Tests what is on screen (Settings save when you leave), so the short switch counts right away.
binding.voiceTestButton.setOnClickListener {
com.rfsentinel.app.util.AlertPlayer.testVoice(this, binding.shortVoiceSwitch.isChecked)
@@ -229,6 +246,57 @@ class SettingsActivity : AppCompatActivity() {
}
}
+ /** Starts or stops the .pcap recording of what the USB WiFi adapter / V2X board hears; stopping offers to share it. */
+ private fun togglePcap() {
+ val rec = com.rfsentinel.app.usb.PcapRecorder
+ if (rec.active) {
+ rec.stop()
+ updatePcap()
+ sharePcap()
+ return
+ }
+ if (!com.rfsentinel.app.service.ScanForegroundService.isRunning) {
+ Toast.makeText(this, "Start scanning with the adapter or V2X board plugged in, then record", Toast.LENGTH_LONG).show()
+ return
+ }
+ val dir = java.io.File(cacheDir, "exports")
+ // Only the newest recording is kept: they get big.
+ dir.listFiles { f -> f.name.endsWith(".pcap") }?.forEach { it.delete() }
+ val file = java.io.File(dir, "rfsentinel-${com.rfsentinel.app.util.Exporter.stamp()}.pcap")
+ if (!rec.start(file)) { Toast.makeText(this, "Couldn't create the recording file", Toast.LENGTH_SHORT).show(); return }
+ Toast.makeText(this, "Recording - frames are saved as they're heard; it stops when scanning does", Toast.LENGTH_LONG).show()
+ updatePcap()
+ }
+
+ private fun sharePcap() {
+ val file = com.rfsentinel.app.usb.PcapRecorder.file?.takeIf { it.exists() && it.length() > 24 } ?: run {
+ Toast.makeText(this, "Nothing was recorded (no frames heard)", Toast.LENGTH_SHORT).show(); return
+ }
+ val uri = runCatching { androidx.core.content.FileProvider.getUriForFile(this, "$packageName.fileprovider", file) }.getOrNull() ?: return
+ startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("application/vnd.tcpdump.pcap")
+ .putExtra(Intent.EXTRA_STREAM, uri)
+ .putExtra(Intent.EXTRA_SUBJECT, "RF Sentinel capture ${file.name}")
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Share .pcap recording"))
+ }
+
+ /** The recording's size and frame count, refreshed every second while it runs. */
+ private fun updatePcap() {
+ if (isFinishing || isDestroyed) return
+ val rec = com.rfsentinel.app.usb.PcapRecorder
+ val file = rec.file?.takeIf { it.exists() }
+ val mb = String.format(java.util.Locale.US, "%.1f MB", rec.bytes / 1_048_576.0)
+ binding.pcapText.text = when {
+ rec.active -> "● Recording · ${rec.frames} frames · $mb"
+ file != null -> "Last recording: ${rec.frames} frames · $mb" + (rec.stoppedBecause?.let { " (stopped: $it)" } ?: "")
+ else -> "Record what the USB WiFi adapter or V2X board hears, for Wireshark"
+ }
+ binding.pcapButton.text = if (rec.active) "Stop and share" else "Record frames (.pcap)"
+ binding.pcapShareButton.visibility = if (!rec.active && file != null) View.VISIBLE else View.GONE
+ binding.pcapText.removeCallbacks(pcapTicker)
+ if (rec.active) binding.pcapText.postDelayed(pcapTicker, 1_000)
+ }
+ private val pcapTicker = Runnable { updatePcap() }
+
private fun updateEspStatus() {
val s = com.rfsentinel.app.esp.EspBoards.status
binding.espStatusText.text = s.ifBlank { "ESP32 board on USB: not connected" }
@@ -303,7 +371,12 @@ class SettingsActivity : AppCompatActivity() {
"Setup wizard: walks through the permissions and main choices again.\n\n" +
"Update check: asks GitHub at most every 6 hours and only speaks up when a new version is out.\n\n" +
"Discreet mode: hides details on the lock screen and in notifications.\n\n" +
- "Screen: \"On while charging\" suits a car or a desk; \"Normal\" turns off like other apps."),
+ "Screen: \"On while charging\" suits a car or a desk; \"Normal\" turns off like other apps.\n\n" +
+ "Screen rotation: phones like the Pixel never auto-rotate upside down. \"Auto-rotate, upside down too\" turns " +
+ "the app whichever way the phone is held, upside down included (rotation lock still applies); \"Always upside down\" " +
+ "keeps the USB-C port at the top (an antenna, a WiFi adapter or an ESP32 board plugged in). The status bar and " +
+ "Android's own navigation buttons or gestures turn with it and work normally. Only while the app is on screen: " +
+ "other apps and the home screen stay as usual."),
Section("appearance", binding.headerAppearance, binding.sectionAppearance,
"Banner image: shown above the animated header in the styled themes (Night Drive, Synthwave...); " +
"in DedSec and fsociety it replaces the poster. The image is copied privately into the app."),
@@ -365,7 +438,11 @@ class SettingsActivity : AppCompatActivity() {
"Re-alert: how long before the same device can alert again."),
Section("voice", binding.headerVoice, binding.sectionVoice,
"Speaks each alert, for example while driving. Short alerts say just the type " +
- "(\"Body cam\", \"Police car\", \"Speed camera, 50\")."),
+ "(\"Body cam\", \"Police car\", \"Speed camera, 50\").\n\n" +
+ "Voice loudness: makes the voice louder than the volume alone allows (up to +15 dB, without distorting), " +
+ "for when music drowns it out - in the car too. Release the slider to hear it.\n\n" +
+ "Pause music while an alert is spoken: music stops for the alert and carries on after it, " +
+ "instead of only getting quieter."),
Section("overlay", binding.headerOverlay, binding.sectionOverlay,
"Shown over other apps (Waze, Maps...) while scanning. Needs Android's \"Display over other apps\" permission.\n\n" +
"Bubble: each new alert shows what was detected in a small card beside it for a few seconds.\n\n" +
@@ -407,7 +484,18 @@ class SettingsActivity : AppCompatActivity() {
"• RTL-SDR dongle: notices two-way radios transmitting nearby (signal strength only, nothing is decoded).\n\n" +
"OUI-SPY over Bluetooth needs its App-Controlled firmware. Relay mode passes on every network and device it hears " +
"so RF Sentinel's own lists check them (the board also sends standard Wi-Fi scan probes).\n\n" +
- "Adapter not working? Export its log and send it to the developer."),
+ "Adapter not working? Export its log and send it to the developer.\n\n" +
+ "WiFi deauth attacks (with Hacking tools on): the USB WiFi adapter counts the frames that knock devices off a " +
+ "network; a flood (a jammer, an ESP32 deauther, a Flipper WiFi board, a WiFi Pineapple) raises an alert. " +
+ "Protected (802.11w) frames are ignored, and a normal network never sends enough.\n\n" +
+ "Record frames (.pcap): saves every frame the USB WiFi adapter (or V2X board) hears to a file for Wireshark, " +
+ "with each frame's channel and signal, until you stop it, scanning stops, or it reaches 200 MB. It holds " +
+ "the addresses and names of everything nearby: share it with care. Only the newest recording is kept.\n\n" +
+ "• V2X (Europe): an ESP32-C5 flashed with the V2X2MAP firmware (github.com/pit711/V2X2MAP) hears the 5.9 GHz " +
+ "car-to-car radio (ITS-G5). Emergency vehicles that broadcast it show on the list and map at their own GPS " +
+ "position, with an alert when their light bar or siren is on, or when they warn that they're approaching. " +
+ "Ordinary cars are counted, not listed. North America uses a different V2X radio (C-V2X) that this board can't hear. " +
+ "Receiving V2X may fall under telecom or privacy law where you are."),
Section("radio", binding.headerRadio, binding.sectionRadio,
"An RTL-SDR dongle on USB notices two-way radios transmitting nearby, from signal strength only - nothing is " +
"decoded or recorded. Needs the Police radio category on (What to detect).\n\n" +
@@ -417,13 +505,23 @@ class SettingsActivity : AppCompatActivity() {
"which are reported whenever they're active.\n\n" +
"Hits show in the main list (Radio filter). Closer / moving away: called out when the signal changes by the set " +
"amount - a rough guide only.\n\n" +
+ "Cellular transmitters (LTE uplink, off by default): also watches the phone / modem side of the in-range LTE " +
+ "bands (600 / 700 / 850 / 1700 MHz, including Band 14, the US public-safety broadband band FirstNet uses) for a transmitter close to you. Energy only, nothing decoded or identified. " +
+ "Few things drive around with a mobile router always transmitting, so a cellular signal that travels with you - or " +
+ "that lines up with a device flagged over Wi-Fi / Bluetooth - is a useful sign; a phone alone is not. It adds time to " +
+ "each sweep while it's on.\n\n" +
"Frequency names: import a CSV (RadioReference's export, CHIRP, or any file with a frequency and a name column), " +
"or let RadioReference name the FCC licences near you (US): needs your own RadioReference Premium login and a " +
"RadioReference developer key; your position rounded to ~1 km is sent to RadioReference, at most once a day per area.\n\n" +
"Changes apply from the next sweep while scanning."),
Section("location", binding.headerLocation, binding.sectionLocation,
"Traces: records your route while scanning, to view on the map.\n\n" +
- "Saving the GPS position with matches is privacy-sensitive: the log then shows where you were. It also lets the map remember where it last looked, so it can open there before the GPS answers."),
+ "Saving the GPS position with matches is privacy-sensitive: the log then shows where you were. It also lets the map remember where it last looked, so it can open there before the GPS answers.\n\n" +
+ "Pinpoint flagged devices: while a flagged device is in range, the GPS reads your position every second and " +
+ "its signal is measured at every spot you pass. Once you've passed it from more than one side (around the block), " +
+ "the map puts it where it most likely is, with a circle it is very likely in. Driving one straight road can't tell " +
+ "which side it's on: the circle then covers both. Works for devices that stay put; one that moves with you isn't " +
+ "pinned. Kept in memory, not in the history. Uses more battery while a flagged device is around."),
Section("data", binding.headerData, binding.sectionData,
"Everything stays on this phone. History older than the set number of days is deleted (0 keeps it forever).\n\n" +
"Live export (off by default): while scanning, rewrites three files every 30 s in the folder you choose - " +
@@ -690,6 +788,10 @@ class SettingsActivity : AppCompatActivity() {
lines("Never report these ranges", "462-469 business band\n151.8-152.0", Prefs.radioExcluded(this)) { Prefs.setRadioExcluded(this, it) }
lines("Watch these frequencies (always reported when active)", "154.4300 County fire dispatch\n460.125", Prefs.radioTargets(this)) { Prefs.setRadioTargets(this, it) }
switch("Say the frequency (and its name) instead of \"Radio transmitting nearby\"", Prefs.radioSpeakFreq(this)) { Prefs.setRadioSpeakFreq(this, it) }
+ switch("Also detect cellular transmitters (LTE uplink, experimental)", Prefs.radioCellOn(this)) { Prefs.setRadioCellOn(this, it) }
+ label("Watches the phone / modem side of the LTE bands for a transmitter travelling near you (a vehicle modem, a " +
+ "Cradlepoint-style router, a camera with a SIM). Energy only, nothing decoded. Adds time to each sweep; " +
+ "a phone counts too, so it is a weak sign on its own.", small = true)
slider(0, 20, Prefs.radioTrendDb(this), { if (it == 0) "Closer / moving away: off" else "Say \"getting closer\" / \"moving away\" when the signal changes by $it dB" }) {
Prefs.setRadioTrendDb(this, it)
}
@@ -1367,6 +1469,13 @@ class SettingsActivity : AppCompatActivity() {
binding.shortVoiceSwitch.isChecked = Prefs.shortVoice(this)
setupVoiceControls()
binding.discreetSwitch.isChecked = Prefs.discreetMode(this)
+ val rotations = mapOf(R.id.rotationNormal to Prefs.Rotation.NORMAL, R.id.rotationAllWays to Prefs.Rotation.ALL_WAYS,
+ R.id.rotationUpsideDown to Prefs.Rotation.UPSIDE_DOWN)
+ binding.rotationGroup.check(rotations.entries.first { it.value == Prefs.rotation(this) }.key)
+ binding.rotationGroup.setOnCheckedChangeListener { _, id ->
+ rotations[id]?.let { Prefs.setRotation(this, it) }
+ (application as com.rfsentinel.app.RFSentinelApp).applyOrientation(this) // turns right away
+ }
binding.floatingMapSwitch.isChecked = Prefs.floatingMap(this) && Settings.canDrawOverlays(this)
binding.floatingMapSwitch.setOnCheckedChangeListener { sw, on ->
if (on && !Settings.canDrawOverlays(this)) {
@@ -1411,6 +1520,9 @@ class SettingsActivity : AppCompatActivity() {
com.rfsentinel.app.esp.OuiSpyBle.onStatusChanged = { runOnUiThread { updateEspStatus() } }
binding.ouiSpyButton.setOnClickListener { pairOuiSpy() }
binding.usbWifiLogButton.setOnClickListener { exportUsbWifiLog() }
+ binding.pcapButton.setOnClickListener { togglePcap() }
+ binding.pcapShareButton.setOnClickListener { sharePcap() }
+ updatePcap()
binding.trackerIgnoreButton.setOnClickListener {
com.rfsentinel.app.data.TrackerMutes.clear(this)
Prefs.setTrackerFollowPausedUntil(this, 0L)
@@ -1420,6 +1532,7 @@ class SettingsActivity : AppCompatActivity() {
binding.followMinutesInput.setText(Prefs.followMinMinutes(this).toString())
binding.followMetersInput.setText(Prefs.followMinMeters(this).toString())
binding.gpsSwitch.isChecked = Prefs.gpsTaggingEnabled(this)
+ binding.pinpointSwitch.isChecked = Prefs.pinpointFlagged(this)
binding.autoRecordSwitch.isChecked = Prefs.autoRecordTrace(this)
binding.ouiSpyRelaySwitch.isChecked = Prefs.ouiSpyRelayAll(this)
binding.screenModeGroup.check(when (Prefs.screenMode(this)) {
@@ -1519,6 +1632,7 @@ class SettingsActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
+ updatePcap()
// The user may be coming back from Developer options.
updateWifiThrottleHint()
showNote(aircraftStatusText, com.rfsentinel.app.online.OnlineWatch.aircraftStatus)
@@ -1658,6 +1772,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setFollowMinMinutes(this, (binding.followMinutesInput.text.toString().toIntOrNull() ?: 10).coerceIn(2, 240))
Prefs.setFollowMinMeters(this, (binding.followMetersInput.text.toString().toIntOrNull() ?: 800).coerceIn(100, 50_000))
Prefs.setGpsTaggingEnabled(this, binding.gpsSwitch.isChecked)
+ Prefs.setPinpointFlagged(this, binding.pinpointSwitch.isChecked)
Prefs.setAutoRecordTrace(this, binding.autoRecordSwitch.isChecked)
Prefs.setOuiSpyRelayAll(this, binding.ouiSpyRelaySwitch.isChecked)
Prefs.setScreenMode(this, when (binding.screenModeGroup.checkedRadioButtonId) {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt
index 396ebe9..579132a 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt
@@ -34,7 +34,8 @@ object AboutDialog {
&bull; all-cameras-are-beacons signature reference (Apache-2.0) - Axon BWCDEVICE tag,
Flock / Raven signatures, tracker and smart-glasses rules, drone maker prefixes<br/>
&bull; ASTM F3411 Remote ID, decoded per opendroneid-core-c (Apache-2.0)<br/>
- &bull; Google Find Hub Network accessory spec; arXiv 2501.17452 (trackers)<br/>
+ &bull; Google Find Hub Network accessory spec; arXiv 2501.17452; AirGuard, SEEMOO / TU Darmstadt (Apache-2.0) (trackers)<br/>
+ &bull; European V2X (ITS-G5) frame layout after V2X2MAP by Peter Holzhauser (MIT); CAM / DENM decoded per ETSI EN 302 637-2 / -3<br/>
&bull; Research by ryanohoro and GainSec (Flock); Alan Meekins' DEF CON 31 talk (Axon)<br/><br/>
DedSec, fsociety and Night Vision theme font: Share Tech Mono &copy; Carrois Type Design, SIL Open Font
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
index fe794f2..0cdd3d8 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -133,6 +133,9 @@ class DeviceDetailActivity : AppCompatActivity() {
private fun refresh() {
val s = DeviceRegistry.get(mac)
+ // The same device under a newer address (it rotated): its live signal is heard there now.
+ val liveMac = DeviceRegistry.currentAddress(mac)
+ val live = if (liveMac != mac) DeviceRegistry.get(liveMac) ?: s else s
val now = System.currentTimeMillis()
val whitelisted = WhitelistCache.contains(mac)
val best = s?.best
@@ -152,26 +155,28 @@ class DeviceDetailActivity : AppCompatActivity() {
binding.titleText.text = best?.label ?: s?.name ?: known?.name ?: s?.deviceType ?: known?.deviceType ?: "Device"
binding.subtitleText.text = mac + ((s?.vendor ?: known?.vendor ?: VendorDb.macVendor(mac))?.let { "\n$it" } ?: "")
binding.presenceText.text = when {
+ liveMac != mac && live != null -> "In range under its new address $liveMac (it changed its address) · heard ${ago(now - live.lastSeen)}"
s == null -> "Not in range right now" + (known?.let { " · last heard ${dateFmt.format(Date(it.lastSeen))}" } ?: "")
s.following -> "⚠ Has been moving with you"
else -> "In range · heard ${ago(now - s.lastSeen)} · ${s.sightings} packets received"
}
- // Live signal
- if (s != null) {
- binding.rssiText.text = "${s.rssi}"
- val recent = s.history.takeLast(6).dropLast(1)
+ // Live signal (from the newest address when it rotated)
+ if (live != null) {
+ binding.rssiText.text = "${live.rssi}"
+ val recent = live.history.takeLast(6).dropLast(1)
val trend = if (recent.isEmpty()) "" else {
val avg = recent.map { it.rssi }.average()
when {
- s.rssi > avg + 3 -> " ↑ getting closer"
- s.rssi < avg - 3 -> " ↓ moving away"
+ live.rssi > avg + 3 -> " ↑ getting closer"
+ live.rssi < avg - 3 -> " ↓ moving away"
else -> " → steady"
}
}
- binding.rssiDetail.text = "dBm · ${ProximityUtil.band(s.rssi)} $trend\n" +
- "${DeviceIntel.formatDistance(s.distanceM)} (rough) · best ${s.bestRssi} dBm"
- binding.graph.setSamples(s.history)
+ binding.rssiDetail.text = "dBm · ${ProximityUtil.band(live.rssi)} $trend\n" +
+ "${DeviceIntel.formatDistance(live.distanceM)} (rough) · best ${live.bestRssi} dBm" +
+ (if (liveMac != mac) "\nNow heard as $liveMac" else "")
+ binding.graph.setSamples(live.history)
binding.locateButton.isEnabled = true
} else {
binding.rssiText.text = "--"
@@ -295,6 +300,15 @@ class DeviceDetailActivity : AppCompatActivity() {
val moved = s.path.maxOf { DeviceRegistry.metersBetween(first.lat, first.lon, it.lat, it.lon) }
hist += "Travelled with you" to String.format(Locale.US, "%.0f m while in range", moved)
}
+ s?.broadcast?.let { b ->
+ hist += "Position (its own GPS, over V2X)" to String.format(Locale.US, "%.6f, %.6f", b.lat, b.lon)
+ } ?: s?.located?.let { e ->
+ hist += "Pinpointed position" to String.format(Locale.US, "%.6f, %.6f · ", e.lat, e.lon) +
+ com.rfsentinel.app.detect.Locator.describe(e)
+ } ?: s?.takeIf { it.best != null && !it.following && com.rfsentinel.app.util.Prefs.pinpointFlagged(this) }?.let {
+ hist += "Pinpointing" to "Not yet: pass it from more than one side (around the block) and it is placed on the map " +
+ "with the circle it is very likely in"
+ }
out += "History" to hist
// Raw advertisement
@@ -432,13 +446,23 @@ class DeviceDetailActivity : AppCompatActivity() {
if (locateJob != null) stopLocate() else startLocate()
}
+ /** The address Locate is following (changes when the device rotates its address). */
+ private var followed: String? = null
+
private fun startLocate() {
+ followed = null
tone = runCatching { ToneGenerator(AudioManager.STREAM_MUSIC, 80) }.getOrNull()
binding.locateButton.text = "Stop"
Toast.makeText(this, "Walk around: beeps speed up as the signal gets stronger", Toast.LENGTH_LONG).show()
locateJob = lifecycleScope.launch {
while (isActive) {
- val rssi = DeviceRegistry.get(mac)?.rssi ?: -100
+ // Keeps following it when it changes its address (a tag rotating its random address).
+ val liveMac = DeviceRegistry.currentAddress(mac)
+ if (liveMac != followed) {
+ if (followed != null) Toast.makeText(this@DeviceDetailActivity, "It changed its address - still following it", Toast.LENGTH_SHORT).show()
+ followed = liveMac
+ }
+ val rssi = DeviceRegistry.get(liveMac)?.rssi ?: -100
// Faster as the signal gets stronger (same curve as the radar beeps).
val interval = com.rfsentinel.app.util.Beeper.tickIntervalMs(rssi)
if (!AlertPlayer.locateTick(this@DeviceDetailActivity)) tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
index acfaa11..ee24578 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
@@ -43,6 +43,7 @@ import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.overlay.CopyrightOverlay
import org.osmdroid.views.overlay.FolderOverlay
import org.osmdroid.views.overlay.Marker
+import org.osmdroid.views.overlay.Polygon
import org.osmdroid.views.overlay.Polyline
import org.osmdroid.views.overlay.ScaleBarOverlay
import org.osmdroid.views.overlay.TilesOverlay
@@ -98,7 +99,10 @@ class MapFragment : Fragment() {
/** One device to draw, from the live registry or a saved trip. */
private data class Pin(
val mac: String, val lat: Double, val lon: Double, val label: String, val flagged: Boolean,
- val color: Int, val details: String
+ val color: Int, val details: String,
+ /** Pinpointed (see [com.rfsentinel.app.detect.Locator]): the circle it is very likely in. */
+ val radiusM: Double? = null,
+ val whereNote: String = "Position = where your phone was when this device's signal was strongest (approximate)."
)
private var _binding: ActivityMapBinding? = null
@@ -123,6 +127,8 @@ class MapFragment : Fragment() {
private var following = false
private val trace = Polyline()
+ /** Pinpointed flagged devices: a faint circle where each one very likely is, under the dots. */
+ private val precision = FolderOverlay()
private val pins by lazy { PointsOverlay<Pin>(resources.displayMetrics.density) { showPins(it) } }
/** Live drones from Remote ID: aircraft, operator and the line between them. */
private val drones = FolderOverlay()
@@ -327,6 +333,7 @@ class MapFragment : Fragment() {
map.overlays.add(knownAlpr)
map.overlays.add(towers)
map.overlays.add(trace)
+ map.overlays.add(precision)
map.overlays.add(pins)
map.overlays.add(drones)
map.overlays.add(wazeLayer)
@@ -729,7 +736,7 @@ class MapFragment : Fragment() {
/** Chip labels with how many devices each filter would show ("Trackers 2"). */
private fun updateFilterCounts(devices: List<DeviceRegistry.Snapshot>) {
- val placed = devices.filter { it.bestPosition != null }
+ val placed = devices.filter { it.place != null }
for ((f, chip) in filterChips) {
val n = when (f) {
DeviceFilter.CELLS -> towerCount
@@ -892,8 +899,9 @@ class MapFragment : Fragment() {
// Includes devices from a scan that just stopped: the registry drops them after 3 minutes.
val devices = DeviceRegistry.snapshot()
val drawn = devices.mapNotNull { s ->
- val pos = s.bestPosition ?: return@mapNotNull null
+ val pos = s.place ?: return@mapNotNull null
val flagged = DeviceColors.isFlagged(s)
+ val located = s.located?.takeIf { flagged && s.broadcast == null }
if (!filter.matches(s) || filter == DeviceFilter.RADIO) return@mapNotNull null
val best = s.best
Pin(
@@ -905,17 +913,29 @@ class MapFragment : Fragment() {
append(s.mac)
s.vendor?.let { append("\n").append(it) }
if (best != null) append("\n${best.category.title} · ${best.tier.label} ${best.confidence}%\n${best.evidence}")
- append("\nStrongest signal here: ${s.bestRssi} dBm")
- }
+ if (located != null) append("\nPinpointed ${com.rfsentinel.app.detect.Locator.describe(located)}")
+ append("\nStrongest signal: ${s.bestRssi} dBm")
+ },
+ radiusM = located?.radiusM,
+ whereNote = if (s.broadcast != null)
+ "Position = the vehicle's own GPS, broadcast over V2X (exact, not an estimate)."
+ else if (located != null)
+ "Position = pinpointed from the signal at the many spots you passed: very likely inside the circle " +
+ "(${located.radiusM.toInt()} m). The more sides you pass it from, the smaller the circle."
+ else if (flagged)
+ "Position = where your phone was when this device's signal was strongest (approximate). " +
+ "Drive or walk past it from another side - around the block - to pinpoint it."
+ else "Position = where your phone was when this device's signal was strongest (approximate)."
)
}
drawPins(drawn)
+ drawPrecision(drawn)
updateFilterCounts(devices)
drawDrones(devices.filter { it.remoteId?.hasPosition == true })
drawAircraft()
drawWaze()
- val positioned = devices.count { it.bestPosition != null }
+ val positioned = devices.count { it.place != null }
val status = when {
bulkStatus() != null -> bulkStatus() // a camera download's progress wins
System.currentTimeMillis() - com.rfsentinel.app.alpr.AlprStore.lastAutoFailureAt < CAMERA_FAIL_SHOWN_MS ->
@@ -1045,6 +1065,25 @@ class MapFragment : Fragment() {
* Each device sits exactly where it was heard best. Devices heard from the same
* spot overlap; tapping there lists them all.
*/
+ /** The circle each pinpointed device is very likely in, in its colour. Taps go through to the dots. */
+ private fun drawPrecision(list: List<Pin>) {
+ val circles = list.filter { it.radiusM != null }
+ if (circles.isEmpty() && precision.items.isEmpty()) return
+ precision.items.clear()
+ val density = resources.displayMetrics.density
+ for (p in circles) {
+ precision.add(Polygon(binding.map).apply {
+ points = Polygon.pointsAsCircle(GeoPoint(p.lat, p.lon), p.radiusM!!)
+ fillPaint.color = (p.color and 0x00FFFFFF) or 0x2E000000
+ outlinePaint.color = (p.color and 0x00FFFFFF) or 0xB4000000.toInt()
+ outlinePaint.strokeWidth = 1.5f * density
+ setOnClickListener { _, _, _ -> false }
+ infoWindow = null
+ })
+ }
+ binding.map.invalidate()
+ }
+
private fun drawPins(list: List<Pin>) {
// Ordinary devices first so flagged ones are drawn on top.
pins.points = list.sortedBy { it.flagged }.map { p ->
@@ -1517,7 +1556,7 @@ class MapFragment : Fragment() {
private fun showPin(p: Pin) {
AlertDialog.Builder(act)
.setTitle(p.label)
- .setMessage(p.details + "\n\nPosition = where your phone was when this device's signal was strongest (approximate).")
+ .setMessage(p.details + "\n\n" + p.whereNote)
.setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(act, p.mac) }
.setNegativeButton("Close", null)
.show()
diff --git a/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt b/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt
new file mode 100644
index 0000000..3919787
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt
@@ -0,0 +1,58 @@
+package com.rfsentinel.app.usb
+
+/**
+ * WiFi deauthentication / disassociation floods, from the management frames a USB WiFi adapter
+ * hears in monitor mode. A jammer or hacking tool (ESP32 / ESP8266 deauther, Flipper with a WiFi
+ * board, WiFi Pineapple) knocks devices off a network by sending these frames over and over in the
+ * network's name. Real networks send a handful (a client leaving, an idle one dropped), never a
+ * stream. Frames protected by 802.11w (PMF) are skipped: an attacker can't forge those.
+ *
+ * Receive-only: it counts frames, nothing is sent. Fed from every driver's RX thread, so it's
+ * synchronized. Pure logic, unit-tested.
+ */
+object DeauthWatch {
+
+ /** A flood on one network (BSSID): [frames] in the last [windowS] s, [broadcast] = sent to every device on it. */
+ data class Attack(val bssid: String, val frames: Int, val broadcast: Boolean, val channel: Int, val windowS: Int)
+
+ /**
+ * The adapter hops channels (each one gets a fraction of a second at a time), so a flood is only
+ * partly heard: count over a longer window with a threshold a normal network never reaches.
+ */
+ const val WINDOW_MS = 30_000L
+ const val MIN_FRAMES = 25
+ /** One alert per network this often while a flood goes on. */
+ const val REPEAT_MS = 5 * 60_000L
+ private const val MAX_KEPT = 4_000
+ private const val MAX_NETWORKS = 500
+
+ /** Set by the scanning service; called (on the RX thread) when a flood is found. */
+ @Volatile var onAttack: ((Attack) -> Unit)? = null
+
+ private class Net {
+ val frames = ArrayDeque<Pair<Long, Boolean>>()
+ var channel = 0
+ var lastReport = Long.MIN_VALUE / 2
+ }
+
+ private val nets = HashMap<String, Net>()
+
+ /** One unprotected deauth / disassoc frame for network [bssid], to [broadcast] or one device. */
+ fun frame(bssid: String, broadcast: Boolean, channel: Int, now: Long = System.currentTimeMillis()): Attack? {
+ val attack = synchronized(this) {
+ if (nets.size > MAX_NETWORKS) nets.entries.removeAll { (_, n) -> n.frames.isEmpty() || now - n.frames.last().first > WINDOW_MS }
+ val n = nets.getOrPut(bssid) { Net() }
+ n.frames.addLast(now to broadcast)
+ n.channel = channel
+ while (n.frames.isNotEmpty() && (now - n.frames.first().first > WINDOW_MS || n.frames.size > MAX_KEPT)) n.frames.removeFirst()
+ if (n.frames.size < MIN_FRAMES || now - n.lastReport < REPEAT_MS) return@synchronized null
+ n.lastReport = now
+ Attack(bssid, n.frames.size, n.frames.count { it.second } * 2 >= n.frames.size, channel, (WINDOW_MS / 1000).toInt())
+ }
+ attack?.let { a -> onAttack?.invoke(a) }
+ return attack
+ }
+
+ @Synchronized
+ fun clear() = nets.clear()
+}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
index 442ffd7..e7de0a1 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
@@ -44,6 +44,7 @@ class MonitorFrames {
*/
fun frame(b: ByteArray, d: Int, end: Int, channel: Int, rssi: Int?, now: Long = System.currentTimeMillis(),
pathA: Int? = null, pathB: Int? = null) {
+ PcapRecorder.frame(b, d, end, channel, rssi, now)
if (end - d < 24 || end > b.size) return
fun u8(i: Int) = b[i].toInt() and 0xff
val fc = u8(d); val ftype = (fc shr 2) and 3; val sub = (fc shr 4) and 0xf
@@ -66,6 +67,10 @@ class MonitorFrames {
}
return s
}
+ // Deauthentication (12) / disassociation (10) not protected by 802.11w: counted for flood alarms.
+ if (ftype == 0 && (sub == 12 || sub == 10) && (fc1 and 0x40) == 0 && isReal(b, a3)) {
+ DeauthWatch.frame(mac(b, a3), (0 until 6).all { b[a1 + it] == 0xFF.toByte() }, channel, now)
+ }
when (ftype) {
0 -> when (sub) {
// Beacon or probe response: an access point.
diff --git a/app/src/main/java/com/rfsentinel/app/usb/PcapRecorder.kt b/app/src/main/java/com/rfsentinel/app/usb/PcapRecorder.kt
new file mode 100644
index 0000000..3ccc969
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/usb/PcapRecorder.kt
@@ -0,0 +1,125 @@
+package com.rfsentinel.app.usb
+
+import java.io.BufferedOutputStream
+import java.io.File
+import java.io.FileOutputStream
+import java.io.OutputStream
+import java.util.zip.CRC32
+
+/**
+ * Records the raw 802.11 frames a USB WiFi adapter (or a V2X board) hears into a standard
+ * .pcap file for Wireshark: radiotap link type with the channel and signal of each frame.
+ * Started and stopped from Settings > External hardware; it also stops when scanning does.
+ * Receive-only like the rest: it saves what was heard, nothing is ever sent.
+ *
+ * Frames come from each driver's own RX thread, so writes are synchronized.
+ */
+object PcapRecorder {
+
+ /** Wireshark: LINKTYPE_IEEE802_11_RADIOTAP. */
+ private const val LINKTYPE_RADIOTAP = 127
+ /** A recording stops itself at this size (a busy street fills ~1 MB a minute). */
+ const val MAX_BYTES = 200L * 1024 * 1024
+
+ @Volatile var active = false; private set
+ @Volatile var frames = 0L; private set
+ @Volatile var bytes = 0L; private set
+ /** The file being written, or the last one finished. */
+ @Volatile var file: File? = null; private set
+ /** Why the last recording stopped on its own (size limit, write error), for Settings. */
+ @Volatile var stoppedBecause: String? = null; private set
+
+ private var out: OutputStream? = null
+ private var lastFlush = 0L
+ private val crc = CRC32()
+
+ @Synchronized
+ fun start(f: File): Boolean {
+ stop()
+ return runCatching {
+ f.parentFile?.mkdirs()
+ val o = BufferedOutputStream(FileOutputStream(f), 64 * 1024)
+ o.write(globalHeader())
+ out = o; file = f; frames = 0; bytes = 24; stoppedBecause = null
+ active = true
+ }.isSuccess
+ }
+
+ @Synchronized
+ fun stop() {
+ active = false
+ out?.let { runCatching { it.flush() }; runCatching { it.close() } }
+ out = null
+ }
+
+ /**
+ * One frame from [d] to [end] in [b], heard on [channel] (2.4 / 5 GHz channel number, or a
+ * frequency in MHz for 802.11p) at [rssi] dBm (null when the adapter gave no reading).
+ */
+ fun frame(b: ByteArray, d: Int, end: Int, channel: Int, rssi: Int?, now: Long = System.currentTimeMillis()) {
+ if (!active || end <= d || end > b.size) return
+ synchronized(this) {
+ val o = out ?: return
+ val len = end - d
+ val radiotap = radiotap(frequencyOf(channel), rssi, hasFcs(b, d, end))
+ val rec = radiotap.size + len
+ runCatching {
+ o.write(recordHeader(now, rec))
+ o.write(radiotap)
+ o.write(b, d, len)
+ frames++; bytes += 16 + rec
+ if (now - lastFlush > 2_000) { o.flush(); lastFlush = now }
+ }.onFailure { stoppedBecause = "write failed: ${it.message}"; stop(); return }
+ if (bytes >= MAX_BYTES) { stoppedBecause = "reached ${MAX_BYTES / (1024 * 1024)} MB"; stop() }
+ }
+ }
+
+ /** Channel number (or MHz for 802.11p) to MHz. */
+ fun frequencyOf(channel: Int): Int = when {
+ channel >= 2000 -> channel
+ channel == 14 -> 2484
+ channel in 1..13 -> 2407 + 5 * channel
+ channel in 32..196 -> 5000 + 5 * channel
+ else -> 0
+ }
+
+ /** Drivers that keep the frame's checksum leave 4 bytes that match its CRC-32: say so, or Wireshark calls it malformed. */
+ internal fun hasFcs(b: ByteArray, d: Int, end: Int): Boolean {
+ if (end - d < 28) return false
+ crc.reset(); crc.update(b, d, end - d - 4)
+ val v = crc.value
+ return (b[end - 4].toLong() and 0xff) == (v and 0xff) &&
+ (b[end - 3].toLong() and 0xff) == ((v shr 8) and 0xff) &&
+ (b[end - 2].toLong() and 0xff) == ((v shr 16) and 0xff) &&
+ (b[end - 1].toLong() and 0xff) == ((v shr 24) and 0xff)
+ }
+
+ internal fun globalHeader(): ByteArray = le(
+ 0xa1b2c3d4L to 4, // magic, microsecond timestamps
+ 2L to 2, 4L to 2, // version 2.4
+ 0L to 4, 0L to 4, // time zone, accuracy
+ 65535L to 4, // snapshot length
+ LINKTYPE_RADIOTAP.toLong() to 4
+ )
+
+ private fun recordHeader(now: Long, len: Int): ByteArray = le(
+ (now / 1000) to 4, ((now % 1000) * 1000) to 4, len.toLong() to 4, len.toLong() to 4
+ )
+
+ /** Radiotap: flags (FCS present), channel (MHz + band), and the signal in dBm when known. */
+ internal fun radiotap(mhz: Int, rssi: Int?, fcs: Boolean): ByteArray {
+ val present = (1L shl 1) or (1L shl 3) or (if (rssi != null) 1L shl 5 else 0L)
+ val len = if (rssi != null) 15 else 14
+ val chFlags = when { mhz >= 5000 -> 0x0140; mhz > 0 -> 0x00A0; else -> 0 } // 5 GHz + OFDM / 2.4 GHz + CCK
+ val head = le(0L to 1, 0L to 1, len.toLong() to 2, present to 4, (if (fcs) 0x10L else 0L) to 1, 0L to 1,
+ mhz.toLong() to 2, chFlags.toLong() to 2)
+ return if (rssi != null) head + byteArrayOf(rssi.coerceIn(-128, 127).toByte()) else head
+ }
+
+ private fun le(vararg fields: Pair<Long, Int>): ByteArray {
+ val out = ByteArray(fields.sumOf { it.second })
+ var i = 0
+ for ((v, n) in fields) for (k in 0 until n) out[i++] = ((v shr (8 * k)) and 0xff).toByte()
+ return out
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
index 801b6e7..17c6527 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
@@ -43,6 +43,14 @@ object Rtl8821auMonitor {
private const val VREQ = 0x05
private const val REG_RX_DRVINFO_SZ = 0x060F; private const val RCR_APP_PHYST_RXFF = 0x10000000
+ /**
+ * The adapter's light: LED pin 2 on the RTL8811AU / 8821AU (as Linux's rtw88 drives it).
+ * Bit 5 = software control, bit 3 = off. Bit 7 belongs to the 5 GHz band switch: kept as is.
+ */
+ private const val REG_LEDCFG2 = 0x4E
+ /** How often the light may toggle while frames arrive (a visible blink, a few writes a second). */
+ private const val BLINK_MS = 150L
+
private const val rA_LSSIWrite = 0xC90; private const val rHSSIRead = 0x8B0; private const val rA_PIRead = 0xD04
private val rfShadow = HashMap<Int, Int>()
@@ -98,17 +106,26 @@ object Rtl8821auMonitor {
UsbWifi.log("RTL8821AU: RCR=0x%08x BB(0x800)=0x%08x — monitor live ch ${HOP[0]}".format(
r32(conn, Rtl8821auTables.REG_RCR), r32(conn, 0x800)))
onStatus("RTL8821AU · live · 2.4 GHz monitor")
+ runCatching { led(conn, true) }
+ UsbWifi.log("RTL8821AU: light on, blinks with received traffic")
rxLoop(conn, rx, onFrame, onStatus)
} catch (e: Exception) {
UsbWifi.log("RTL8821AU: bring-up error — ${e.message}")
onStatus("RTL8821AU: error · ${e.message}")
} finally {
+ runCatching { led(conn, false) }
runCatching { conn.close() }
running = false
}
}
+ /** Light on or off under software control; the band-switch bit and the rest of the byte are kept. */
+ private fun led(conn: UsbDeviceConnection, on: Boolean) {
+ val v = r8(conn, REG_LEDCFG2)
+ w8(conn, REG_LEDCFG2, if (on) (v and 0x08.inv()) or 0x20 else v or 0x28)
+ }
+
private fun resetMac(conn: UsbDeviceConnection) {
runCatching {
val v = r8(conn, 0x05); w8(conn, 0x05, v or 0x02)
@@ -156,7 +173,9 @@ object Rtl8821auMonitor {
private class RxState {
var total = 0L; var bufs = 0L; var lastLog = 0L; var hopAt = 0L; var lastEmit = 0L; var hopIdx = 0
- fun start() { val t = System.currentTimeMillis(); lastLog = t; hopAt = t; lastEmit = t }
+ /** Good frames received, and how many there were at the light's last change. */
+ var frames = 0L; var ledFrames = 0L; var ledAt = 0L; var ledOn = true
+ fun start() { val t = System.currentTimeMillis(); lastLog = t; hopAt = t; lastEmit = t; ledAt = t }
}
private fun rxTick(conn: UsbDeviceConnection, now: Long, st: RxState,
@@ -167,6 +186,12 @@ object Rtl8821auMonitor {
st.lastLog = now
}
if (now - st.lastEmit > 2000) { emitSightings(onFrame); st.lastEmit = now }
+ // Blinks while frames come in; steady on when the air is quiet (still running).
+ if (now - st.ledAt >= BLINK_MS) {
+ val want = if (st.frames != st.ledFrames) !st.ledOn else true
+ if (want != st.ledOn && runCatching { led(conn, want) }.isSuccess) st.ledOn = want
+ st.ledFrames = st.frames; st.ledAt = now
+ }
if (now - st.hopAt > DWELL_MS) {
val ni = (st.hopIdx + 1) % HOP.size
if (ni != st.hopIdx) { st.hopIdx = ni; runCatching { channelTune(conn, HOP[st.hopIdx]) } }
@@ -220,7 +245,7 @@ object Rtl8821auMonitor {
if (runCatching { nr.queue(b) }.getOrDefault(false)) reqs[idx] = nr
}
}
- if (parseLen > 0) runCatching { parseRxBuf(scratch, parseLen, HOP[st.hopIdx]) }
+ if (parseLen > 0) runCatching { st.frames += parseRxBuf(scratch, parseLen, HOP[st.hopIdx]) }
}
}
rxTick(conn, now, st, onFrame, onStatus)
@@ -239,16 +264,18 @@ object Rtl8821auMonitor {
while (!stop) {
val n = conn.bulkTransfer(epRx, buf, buf.size, 500)
val now = System.currentTimeMillis()
- if (n > 0) { st.total += n; st.bufs++; runCatching { parseRxBuf(buf, n, HOP[st.hopIdx]) } }
+ if (n > 0) { st.total += n; st.bufs++; runCatching { st.frames += parseRxBuf(buf, n, HOP[st.hopIdx]) } }
rxTick(conn, now, st, onFrame, onStatus)
}
emitSightings(onFrame)
UsbWifi.log("RTL8821AU: RX loop stopped (${st.total} B)")
}
- private fun parseRxBuf(b: ByteArray, n: Int, ch: Int) {
+ /** Parses one USB buffer; returns how many good frames it held. */
+ private fun parseRxBuf(b: ByteArray, n: Int, ch: Int): Int {
val size = Rtl8821auTables.RXDESC_SIZE
var off = 0
+ var good = 0
while (off + size <= n) {
val d0 = le32(b, off)
val pkt = d0 and 0x3fff
@@ -262,9 +289,11 @@ object Rtl8821auMonitor {
val rate = b[off + 12].toInt() and 0x7f
val rssi = if (drv >= 8 && off + size + drv <= n) rtlRssi(b, off + size, rate) else NOMINAL_RSSI
frames.frame(b, fs, fe, ch, rssi)
+ good++
}
off += (size + drv + shift + pkt + 7) and 7.inv()
}
+ return good
}
private fun rtlRssi(b: ByteArray, di: Int, rate: Int): Int {
diff --git a/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt b/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt
index 45ee029..197d03e 100644
--- a/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt
@@ -80,11 +80,11 @@ object LiveExport {
private val iso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }
- /** Devices at the spot they were heard strongest, plus "you are here" (pure; unit-tested). */
+ /** Devices where they were pinpointed, else at the spot they were heard strongest, plus "you are here" (pure; unit-tested). */
fun geoJson(devices: List<DeviceRegistry.Snapshot>, here: Location?, now: Long): String {
val features = JSONArray()
for (s in devices) {
- val p = s.bestPosition ?: continue
+ val p = s.place ?: continue
val best = s.best
features.put(JSONObject()
.put("type", "Feature")
@@ -95,6 +95,7 @@ object LiveExport {
.put("vendor", s.vendor ?: JSONObject.NULL)
.put("type", s.deviceType)
.put("flagged", best != null)
+ .put("pinpointed_m", s.located?.radiusM?.let { Math.round(it) } ?: JSONObject.NULL)
.put("label", best?.label ?: JSONObject.NULL)
.put("category", best?.category?.name ?: JSONObject.NULL)
.put("confidence", best?.confidence ?: 0)
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 0736e26..6e45cc6 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -59,6 +59,15 @@ object Prefs {
fun setVoiceEnabled(context: Context, value: Boolean) = setBool(context, "voice_enabled", value)
/** Speech rate for spoken alerts (1.0 = the engine's normal speed). */
fun voiceRate(context: Context): Float = sp(context).getFloat("voice_rate", 1.0f)
+
+ /** Extra loudness for spoken alerts, in dB (0..15): music in the car is often much louder than the voice. */
+ fun voiceBoostDb(context: Context): Int = int(context, "voice_boost_db", 6).coerceIn(0, MAX_VOICE_BOOST_DB)
+ fun setVoiceBoostDb(context: Context, db: Int) = setInt(context, "voice_boost_db", db.coerceIn(0, MAX_VOICE_BOOST_DB))
+ const val MAX_VOICE_BOOST_DB = 15
+
+ /** Pause music (instead of only lowering it) while an alert is spoken. */
+ fun voicePausesMusic(context: Context): Boolean = bool(context, "voice_pauses_music", false)
+ fun setVoicePausesMusic(context: Context, value: Boolean) = setBool(context, "voice_pauses_music", value)
fun setVoiceRate(context: Context, rate: Float) = sp(context).edit { putFloat("voice_rate", rate) }
/** The chosen speech-engine voice (null = best English voice on the phone). */
fun voiceName(context: Context): String? = sp(context).getString("voice_name", null)
@@ -170,6 +179,22 @@ object Prefs {
fun setGpsTaggingEnabled(context: Context, value: Boolean) = setBool(context, "gps_tagging_enabled", value)
/** Warn when a tracker or flagged device keeps moving with you. Needs location updates. */
+ /** Pinpoint flagged devices from many readings as you move (GPS runs precise every second while one is in range). */
+ fun pinpointFlagged(context: Context): Boolean = bool(context, "pinpoint_flagged", true)
+ fun setPinpointFlagged(context: Context, value: Boolean) = setBool(context, "pinpoint_flagged", value)
+
+ /**
+ * How the app turns: NORMAL follows auto-rotate (never upside down on phones like the Pixel), ALL_WAYS
+ * follows auto-rotate including upside down, UPSIDE_DOWN always has the USB-C port at the top.
+ */
+ enum class Rotation { NORMAL, ALL_WAYS, UPSIDE_DOWN }
+
+ fun rotation(context: Context): Rotation =
+ sp(context).getString("rotation_mode", null)?.let { v -> Rotation.entries.firstOrNull { it.name == v } }
+ // The earlier on/off switch.
+ ?: if (bool(context, "upside_down", false)) Rotation.UPSIDE_DOWN else Rotation.NORMAL
+ fun setRotation(context: Context, value: Rotation) = sp(context).edit { putString("rotation_mode", value.name) }
+
fun followerAlerts(context: Context): Boolean = bool(context, "follower_alerts", true)
fun setFollowerAlerts(context: Context, value: Boolean) = setBool(context, "follower_alerts", value)
@@ -351,6 +376,10 @@ object Prefs {
fun setRadioMinSnr(context: Context, v: Int) = setInt(context, "radio_min_snr", v.coerceIn(15, 50))
/** Built-in bands switched off ("700", "800", "vhf", "uhf"). */
fun radioBandsOff(context: Context): Set<String> = sp(context).getStringSet("radio_bands_off", emptySet()).orEmpty()
+
+ /** Also sweep the cellular UPLINK bands for a transmitter travelling near you (experimental, off by default). */
+ fun radioCellOn(context: Context): Boolean = bool(context, "radio_cell_on", false)
+ fun setRadioCellOn(context: Context, value: Boolean) = setBool(context, "radio_cell_on", value)
fun setRadioBandsOff(context: Context, v: Set<String>) = sp(context).edit { putStringSet("radio_bands_off", v) }
/** The user's own bands, one "start-end MHz label" per line. */
fun radioCustomBands(context: Context) = str(context, "radio_custom_bands")
diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
index f9fb599..1a93160 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
@@ -81,6 +81,11 @@ object Spoken {
Category.SKIMMER -> "Card skimmer"
Category.OTHER_CAMERA -> if (hit.label.startsWith("Hidden")) "Hidden camera" else "Action camera"
Category.HACKER -> "Hacking tool"
+ Category.V2X -> when {
+ hit.label.contains("siren", ignoreCase = true) -> "Emergency siren"
+ hit.label.contains("approaching") -> "Emergency approaching"
+ else -> "Emergency vehicle"
+ }
Category.CUSTOM -> "Watchlist"
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/Voice.kt b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
index 2cb3935..3134dc4 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Voice.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
@@ -35,6 +35,10 @@ object Voice {
/** Attributes for queued items (the latest caller's: car or phone). */
private var nextAttrs: AudioAttributes? = null
+ /** The audio session speech plays in, with a loudness boost on it ([Prefs.voiceBoostDb]). */
+ private var sessionId = 0
+ private var enhancer: android.media.audiofx.LoudnessEnhancer? = null
+
/** English voices on this phone's engine, best first (filled once the engine is up). */
@Volatile var voices: List<android.speech.tts.Voice> = emptyList()
private set
@@ -80,13 +84,33 @@ object Voice {
holdFocus(ctx, attrs)
engine.setAudioAttributes(attrs)
engine.setSpeechRate(Prefs.voiceRate(ctx))
- val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1f) }
+ val params = Bundle().apply {
+ putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1f)
+ boostedSession(ctx)?.let { putInt(TextToSpeech.Engine.KEY_PARAM_SESSION_ID, it) }
+ }
if (engine.speak(item.text, TextToSpeech.QUEUE_FLUSH, params, "rf-${System.nanoTime()}") != TextToSpeech.SUCCESS) {
speaking = null
releaseFocus()
}
}
+ /**
+ * The audio session to speak in, with Android's loudness enhancer (a gain with a limiter, so it
+ * gets louder without distorting) set to the chosen boost; null with no boost or no enhancer.
+ * The boost is on our own sound before it reaches the car, so it works over Android Auto too.
+ */
+ private fun boostedSession(ctx: Context): Int? {
+ val db = Prefs.voiceBoostDb(ctx)
+ if (db <= 0) { enhancer?.let { runCatching { it.enabled = false } }; return null }
+ return runCatching {
+ if (sessionId == 0) sessionId = ctx.getSystemService(AudioManager::class.java)!!.generateAudioSessionId()
+ val e = enhancer ?: android.media.audiofx.LoudnessEnhancer(sessionId).also { enhancer = it }
+ e.setTargetGain(db * 100)
+ e.enabled = true
+ sessionId
+ }.getOrElse { enhancer = null; null }
+ }
+
private fun start(ctx: Context) {
ready = false
val google = runCatching { ctx.packageManager.getPackageInfo(GOOGLE_TTS, 0) }.isSuccess
@@ -163,7 +187,9 @@ object Voice {
private fun holdFocus(ctx: Context, attrs: AudioAttributes) {
if (focus != null) return
val am = ctx.getSystemService(AudioManager::class.java) ?: return
- val req = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
+ // Music dips under the voice, or pauses for it (Settings), and comes back afterwards.
+ val gain = if (Prefs.voicePausesMusic(ctx)) AudioManager.AUDIOFOCUS_GAIN_TRANSIENT else AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
+ val req = AudioFocusRequest.Builder(gain)
.setAudioAttributes(attrs)
.build()
focus = req
@@ -192,5 +218,8 @@ object Voice {
tts?.shutdown()
tts = null
ready = false
+ enhancer?.let { runCatching { it.release() } }
+ enhancer = null
+ sessionId = 0
}
}
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index b68ce60..2293abb 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -44,6 +44,18 @@
<RadioButton android:id="@+id/screenOnCharging" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="On while charging" />
<RadioButton android:id="@+id/screenNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal" />
</RadioGroup>
+
+ <TextView style="@style/SettingsLabel" android:text="Screen rotation" />
+
+ <RadioGroup
+ android:id="@+id/rotationGroup"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <RadioButton android:id="@+id/rotationNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal (follows auto-rotate)" />
+ <RadioButton android:id="@+id/rotationAllWays" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Auto-rotate, upside down too" />
+ <RadioButton android:id="@+id/rotationUpsideDown" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Always upside down (USB-C port at the top)" />
+ </RadioGroup>
</LinearLayout>
<!-- ================= Appearance ================= -->
@@ -306,6 +318,24 @@
<RadioButton android:id="@+id/voiceRateFast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fast" />
</RadioGroup>
+ <TextView android:id="@+id/voiceBoostLabel" style="@style/SettingsLabel" android:text="Voice loudness" />
+
+ <com.google.android.material.slider.Slider
+ android:id="@+id/voiceBoostSlider"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:contentDescription="Extra loudness for spoken alerts, in decibels"
+ android:stepSize="1"
+ android:value="6"
+ android:valueFrom="0"
+ android:valueTo="15" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/voicePauseMusicSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Pause music while an alert is spoken" />
+
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
@@ -591,6 +621,33 @@
android:layout_height="wrap_content"
android:text="Export USB adapter log" />
+ <TextView
+ android:id="@+id/pcapText"
+ style="@style/SettingsLabel"
+ android:paddingTop="6dp"
+ android:text="Record what the USB WiFi adapter or V2X board hears, for Wireshark" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/pcapButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Record frames (.pcap)" />
+
+ <Button
+ android:id="@+id/pcapShareButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:visibility="gone"
+ android:text="Share last recording" />
+ </LinearLayout>
+
<TextView
android:id="@+id/sdrStatusText"
style="@style/SettingsLabel"
@@ -640,6 +697,12 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save GPS position with matches" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/pinpointSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Pinpoint flagged devices on the map" />
</LinearLayout>
<!-- ================= Data ================= -->
diff --git a/app/src/test/java/com/rfsentinel/app/UpsideDownTest.kt b/app/src/test/java/com/rfsentinel/app/UpsideDownTest.kt
new file mode 100644
index 0000000..57e0c40
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/UpsideDownTest.kt
@@ -0,0 +1,43 @@
+package com.rfsentinel.app
+
+import android.app.Activity
+import android.app.Application
+import android.content.pm.ActivityInfo
+import com.rfsentinel.app.util.Prefs
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/** Settings > General > Upside down: the app asks for reverse portrait, and goes back to the default when it's off. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class UpsideDownTest {
+
+ @Test
+ fun theSwitchTurnsTheScreenAndBack() {
+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
+ val app = RFSentinelApp()
+ Prefs.setRotation(activity, Prefs.Rotation.UPSIDE_DOWN)
+ app.applyOrientation(activity)
+ assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, activity.requestedOrientation)
+ Prefs.setRotation(activity, Prefs.Rotation.ALL_WAYS)
+ app.applyOrientation(activity)
+ assertEquals("auto-rotate in all four directions, rotation lock respected",
+ ActivityInfo.SCREEN_ORIENTATION_FULL_USER, activity.requestedOrientation)
+ Prefs.setRotation(activity, Prefs.Rotation.NORMAL)
+ app.applyOrientation(activity)
+ assertEquals("normal: follows auto-rotate as before", ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, activity.requestedOrientation)
+ }
+
+ @Test
+ fun theEarlierSwitchCarriesOver() {
+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
+ assertEquals("nothing set: normal", Prefs.Rotation.NORMAL, Prefs.rotation(activity))
+ // Someone who turned on the earlier "Upside down" switch keeps it.
+ activity.getSharedPreferences("rf_sentinel_prefs", 0).edit().putBoolean("upside_down", true).commit()
+ assertEquals(Prefs.Rotation.UPSIDE_DOWN, Prefs.rotation(activity))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/detect/EspSoupIdeasTest.kt b/app/src/test/java/com/rfsentinel/app/detect/EspSoupIdeasTest.kt
new file mode 100644
index 0000000..0b965dc
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/detect/EspSoupIdeasTest.kt
@@ -0,0 +1,145 @@
+package com.rfsentinel.app.detect
+
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.usb.DeauthWatch
+import com.rfsentinel.app.usb.MonitorFrames
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.BeforeClass
+import org.junit.Test
+import java.io.File
+
+/** Three ideas from ESPsoup: the WiFi deauth alarm, Chipolo by its service ID, and Locate following an address rotation. */
+class EspSoupIdeasTest {
+
+ companion object {
+ @BeforeClass
+ @JvmStatic
+ fun loadVendors() {
+ VendorDb.load { File("src/main/assets", it).inputStream() }
+ }
+ }
+
+ @Before
+ fun setUp() { DeauthWatch.clear(); DeauthWatch.onAttack = null }
+
+ @After
+ fun tearDown() { DeauthWatch.clear(); DeauthWatch.onAttack = null }
+
+ // ---- Deauth alarm
+
+ private val ap = "02:00:00:00:00:AA"
+
+ @Test
+ fun aFloodRaisesOneAlarm() {
+ val heard = ArrayList<DeauthWatch.Attack>()
+ DeauthWatch.onAttack = { heard += it }
+ var t = 1_000_000L
+ repeat(DeauthWatch.MIN_FRAMES - 1) { assertNull(DeauthWatch.frame(ap, broadcast = true, channel = 6, now = t)); t += 100 }
+ val a = DeauthWatch.frame(ap, broadcast = true, channel = 6, now = t)
+ assertNotNull(a)
+ assertEquals(ap, a!!.bssid); assertTrue(a.broadcast); assertEquals(6, a.channel)
+ assertEquals(DeauthWatch.MIN_FRAMES, a.frames)
+ // Still flooding: no new alarm for a while.
+ repeat(100) { t += 100; assertNull(DeauthWatch.frame(ap, true, 6, t)) }
+ assertEquals(1, heard.size)
+ // Much later, still going: alarms again.
+ t += DeauthWatch.REPEAT_MS
+ repeat(DeauthWatch.MIN_FRAMES) { t += 100; DeauthWatch.frame(ap, true, 6, t) }
+ assertEquals(2, heard.size)
+ }
+
+ @Test
+ fun aNormalNetworkNeverAlarms() {
+ // A client leaving now and then: a deauth every 10 s for an hour.
+ var t = 0L
+ repeat(360) { assertNull(DeauthWatch.frame(ap, broadcast = false, channel = 1, now = t)); t += 10_000 }
+ }
+
+ @Test
+ fun separateNetworksAreCountedSeparately() {
+ var t = 0L
+ repeat(DeauthWatch.MIN_FRAMES - 1) {
+ assertNull(DeauthWatch.frame("02:00:00:00:00:01", false, 1, t))
+ assertNull(DeauthWatch.frame("02:00:00:00:00:02", false, 1, t)); t += 50
+ }
+ }
+
+ /** A deauthentication frame for network [bssid] to [dest], optionally 802.11w-protected. */
+ private fun deauth(bssid: Int, dest: ByteArray, protected: Boolean = false): ByteArray {
+ val f = ByteArray(26)
+ f[0] = 0xC0.toByte() // management, subtype 12
+ f[1] = if (protected) 0x40 else 0
+ System.arraycopy(dest, 0, f, 4, 6)
+ for (i in 10..15) f[i] = 0x02; f[15] = bssid.toByte() // transmitter = the AP it pretends to be
+ for (i in 16..21) f[i] = 0x02; f[21] = bssid.toByte() // BSSID
+ f[24] = 7 // reason code
+ return f
+ }
+
+ private val everyone = ByteArray(6) { 0xFF.toByte() }
+
+ @Test
+ fun theAdaptersFramesFeedTheAlarm() {
+ val heard = ArrayList<DeauthWatch.Attack>()
+ DeauthWatch.onAttack = { heard += it }
+ val frames = MonitorFrames()
+ var t = 5_000_000L
+ repeat(DeauthWatch.MIN_FRAMES) { val f = deauth(0x33, everyone); frames.frame(f, 0, f.size, 11, -50, t); t += 200 }
+ assertEquals(1, heard.size)
+ assertEquals("02:02:02:02:02:33", heard[0].bssid)
+ assertTrue(heard[0].broadcast)
+ assertEquals(11, heard[0].channel)
+ }
+
+ @Test
+ fun protectedFramesAreNotCounted() {
+ // 802.11w: an attacker can't forge these, so a stream of them is the network itself.
+ val heard = ArrayList<DeauthWatch.Attack>()
+ DeauthWatch.onAttack = { heard += it }
+ val frames = MonitorFrames()
+ var t = 0L
+ repeat(DeauthWatch.MIN_FRAMES * 2) { val f = deauth(0x44, everyone, protected = true); frames.frame(f, 0, f.size, 6, -50, t); t += 100 }
+ assertTrue(heard.isEmpty())
+ }
+
+ // ---- Chipolo
+
+ @Test
+ fun chipoloIsFoundByItsServiceId() {
+ val byData = Advert("C1:22:33:44:55:66", Advert.Source.BLE, -60,
+ serviceData = mapOf(Advert.uuid16(0xFE33) to byteArrayOf(1, 2, 3)))
+ assertEquals("Chipolo tracker", SignatureEngine.classify(byData).firstOrNull { it.category == Category.TRACKER }?.label)
+ val byUuid = Advert("C1:22:33:44:55:67", Advert.Source.BLE, -60, serviceUuids = listOf(Advert.uuid16(0xFE33)))
+ assertEquals("Chipolo tracker", SignatureEngine.classify(byUuid).firstOrNull { it.category == Category.TRACKER }?.label)
+ val other = Advert("C1:22:33:44:55:68", Advert.Source.BLE, -60, serviceUuids = listOf(Advert.uuid16(0x180F)))
+ assertTrue(SignatureEngine.classify(other).none { it.label == "Chipolo tracker" })
+ }
+
+ // ---- Locate follows an address rotation
+
+ @Test
+ fun theCurrentAddressFollowsARotation() {
+ DeviceRegistry.startSession(0)
+ val id = DeviceIntel.Identity("x", emptyList())
+ val tag = Hit(Category.TRACKER, "Tracker", 60, "e", "s")
+ fun advert(mac: String, t: Long) = Advert(mac, Advert.Source.BLE, -60, null, mapOf(0x034D to ByteArray(6)), timestamp = t)
+ DeviceRegistry.report(advert("5A:00:00:00:10:01", 1_000), listOf(tag), id, null, null, null, 1_000)
+ assertEquals("5A:00:00:00:10:01", DeviceRegistry.currentAddress("5A:00:00:00:10:01"))
+ // It goes quiet, then the same fingerprint appears under a new random address, then again.
+ DeviceRegistry.report(advert("5A:00:00:00:10:02", 6_000), emptyList(), id, null, null, null, 6_000)
+ assertEquals("5A:00:00:00:10:02", DeviceRegistry.currentAddress("5A:00:00:00:10:01"))
+ // Heard under that address for a while, then it rotates again (the first address is long gone by then).
+ DeviceRegistry.report(advert("5A:00:00:00:10:02", 38_000), emptyList(), id, null, null, null, 38_000)
+ DeviceRegistry.report(advert("5A:00:00:00:10:03", 40_000), emptyList(), id, null, null, null, 40_000)
+ assertEquals("5A:00:00:00:10:03", DeviceRegistry.currentAddress("5A:00:00:00:10:01"))
+ assertEquals("5A:00:00:00:10:03", DeviceRegistry.currentAddress("5A:00:00:00:10:02"))
+ // Something never seen keeps its own address.
+ assertFalse(DeviceRegistry.currentAddress("5A:FF:FF:FF:FF:FF") != "5A:FF:FF:FF:FF:FF")
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/detect/LocatorTest.kt b/app/src/test/java/com/rfsentinel/app/detect/LocatorTest.kt
new file mode 100644
index 0000000..3fd1313
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/detect/LocatorTest.kt
@@ -0,0 +1,166 @@
+package com.rfsentinel.app.detect
+
+import com.rfsentinel.app.detect.Locator.Reading
+import org.junit.Assert.assertEquals
+import com.rfsentinel.app.service.DeviceRegistry
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.math.cos
+import kotlin.math.log10
+import kotlin.math.roundToInt
+import kotlin.math.sqrt
+
+/** Pinpointing a parked device from readings taken as you drive past it. Synthetic coordinates. */
+class LocatorTest {
+ private val lat0 = 10.5
+ private val lon0 = -20.5
+ private val mx = 111_320.0 * cos(Math.toRadians(lat0))
+ private val my = 110_540.0
+
+ private fun lat(y: Double) = lat0 + y / my
+ private fun lon(x: Double) = lon0 + x / mx
+
+ /** What the phone hears at (x, y) from a device at (dx, dy): -59 dBm at 1 m, exponent 2.5, plus [noise]. */
+ private fun rssi(x: Double, y: Double, dx: Double, dy: Double, noise: Double = 0.0): Int {
+ val d = sqrt((x - dx) * (x - dx) + (y - dy) * (y - dy)).coerceAtLeast(1.0)
+ return (-59 - 25 * log10(d) + noise).roundToInt()
+ }
+
+ /** A drive along [route] (metres, one reading per metre stepped), hearing a device at (dx, dy). */
+ private fun drive(route: List<Pair<Double, Double>>, dx: Double, dy: Double, noise: (Int) -> Double = { 0.0 }): List<Reading> {
+ val out = ArrayList<Reading>()
+ var t = 1_000_000L
+ for (i in 0 until route.size - 1) {
+ val (ax, ay) = route[i]; val (bx, by) = route[i + 1]
+ val len = sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay))
+ val steps = (len / 2).toInt().coerceAtLeast(1)
+ for (s in 0 until steps) {
+ val x = ax + (bx - ax) * s / steps; val y = ay + (by - ay) * s / steps
+ if (sqrt((x - dx) * (x - dx) + (y - dy) * (y - dy)) > 140) continue // out of Bluetooth range
+ out += Reading(t, lat(y), lon(x), rssi(x, y, dx, dy, noise(out.size)))
+ t += 500
+ }
+ }
+ return out
+ }
+
+ private fun errorM(e: Locator.Estimate, dx: Double, dy: Double) =
+ DeviceRegistry.metersBetween(e.lat, e.lon, lat(dy), lon(dx))
+
+ /** Repeatable pseudo-random fades of up to +-[amp] dB. */
+ private fun fades(amp: Double): (Int) -> Double = { i -> (((i * 7919 + 13) % 101) / 100.0 * 2 - 1) * amp }
+
+ @Test
+ fun turningACornerPinpointsTheDevice() {
+ // East along a street, then north up a cross street; the device sits in the block between.
+ val route = listOf(-120.0 to 0.0, 60.0 to 0.0, 60.0 to 150.0)
+ val e = Locator.estimate(drive(route, 25.0, 40.0), wifi = false)
+ assertNotNull(e)
+ val err = errorM(e!!, 25.0, 40.0)
+ assertTrue("within 8 m, was ${err.roundToInt()} m", err < 8)
+ assertTrue("a tight circle, was ${e.radiusM.roundToInt()} m", e.radiusM < 25)
+ }
+
+ @Test
+ fun fadesStillLandNearAndInsideTheCircle() {
+ val route = listOf(-120.0 to 0.0, 60.0 to 0.0, 60.0 to 150.0)
+ val e = Locator.estimate(drive(route, 25.0, 40.0, fades(6.0)), wifi = false)!!
+ val err = errorM(e, 25.0, 40.0)
+ assertTrue("within 20 m, was ${err.roundToInt()} m", err < 20)
+ assertTrue("the true spot is inside the circle (${err.roundToInt()} vs ${e.radiusM.roundToInt()} m)", err <= e.radiusM)
+ }
+
+ @Test
+ fun aStraightRoadCannotTellTheSideSoTheCircleCoversBoth() {
+ // Driving straight past: the device 35 m north looks the same as 35 m south.
+ val e = Locator.estimate(drive(listOf(-150.0 to 0.0, 150.0 to 0.0), 0.0, 35.0), wifi = false)!!
+ assertTrue("the true spot is inside the circle", errorM(e, 0.0, 35.0) <= e.radiusM)
+ assertTrue("and its mirror on the other side too", errorM(e, 0.0, -35.0) <= e.radiusM)
+ assertTrue("but it still says where along the road (${e.radiusM.roundToInt()} m)", e.radiusM < 80)
+ }
+
+ @Test
+ fun standingStillGivesNoEstimate() {
+ val here = (1..60).map { Reading(1_000_000L + it * 500, lat(0.0), lon(0.0), -70 + it % 3) }
+ assertNull(Locator.estimate(here, wifi = false))
+ }
+
+ @Test
+ fun aFewMetresOfShufflingIsNotEnough() {
+ assertNull(Locator.estimate(drive(listOf(0.0 to 0.0, 10.0 to 0.0), 20.0, 20.0), wifi = false))
+ }
+
+ @Test
+ fun oldReadingsAreDropped() {
+ val route = listOf(-120.0 to 0.0, 60.0 to 0.0, 60.0 to 150.0)
+ val old = drive(route, 25.0, 40.0)
+ val muchLater = old.last().time + Locator.WINDOW_MS + 60_000
+ assertNull("a parked car may have left", Locator.estimate(old, wifi = false, now = muchLater))
+ }
+
+ @Test
+ fun aDeviceThatMovesWithYouIsNotPinned() {
+ // It stays loud wherever you go, then fades and comes back at random: no single spot explains that.
+ var i = 0
+ val route = listOf(-120.0 to 0.0, 60.0 to 0.0, 60.0 to 150.0)
+ val readings = drive(route, 25.0, 40.0).map { it.copy(rssi = if (i++ % 2 == 0) -45 else -88) }
+ assertNull(Locator.estimate(readings, wifi = false))
+ }
+
+ @Test
+ fun wifiAccessPointsAreFoundToo() {
+ val route = listOf(-200.0 to 0.0, 80.0 to 0.0, 80.0 to 200.0)
+ val e = Locator.estimate(drive(route, 30.0, 50.0), wifi = true)!!
+ assertTrue(errorM(e, 30.0, 50.0) < 12)
+ }
+
+ @Test
+ fun describeReadsNaturally() {
+ val e = Locator.Estimate(lat0, lon0, 12.4, 18, 40, 90.0, 0L)
+ assertTrue(Locator.describe(e), Locator.describe(e) == "±12 m from 18 spots you passed")
+ }
+
+ // ---- Through the device registry, the way the scanner feeds it
+
+ private fun scan(mac: String, hits: List<Hit>) {
+ DeviceRegistry.startSession(0)
+ val route = listOf(-120.0 to 0.0, 60.0 to 0.0, 60.0 to 150.0)
+ for (r in drive(route, 25.0, 40.0)) {
+ DeviceRegistry.report(Advert(mac, Advert.Source.BLE, r.rssi, null, emptyMap(), timestamp = r.time), hits,
+ DeviceIntel.Identity("x", emptyList()), null, null, DeviceRegistry.GeoSample(r.time, r.lat, r.lon), r.time)
+ }
+ DeviceRegistry.awaitFits()
+ }
+
+ @Test
+ fun aFlaggedDeviceIsPlacedWhereItWasPinpointed() {
+ scan("5A:10:20:30:40:50", listOf(Hit(Category.BODY_CAM, "Body camera", 80, "e", "s")))
+ val s = DeviceRegistry.get("5A:10:20:30:40:50")!!
+ val e = s.located
+ assertNotNull(e)
+ assertTrue(errorM(e!!, 25.0, 40.0) < 10)
+ assertEquals(e.lat, s.place!!.lat, 1e-9)
+ assertEquals(e.lon, s.place!!.lon, 1e-9)
+ }
+
+ @Test
+ fun anOrdinaryDeviceKeepsItsStrongestSpot() {
+ scan("5A:10:20:30:40:51", emptyList())
+ val s = DeviceRegistry.get("5A:10:20:30:40:51")!!
+ assertNull("only flagged devices are pinpointed", s.located)
+ assertEquals(s.bestPosition, s.place)
+ }
+
+ @Test
+ fun aFixIsMovedOnByYourSpeedAndCourse() {
+ // 20 m/s due east for 1.5 s: 30 m east.
+ val (la, lo) = Locator.ahead(lat0, lon0, 20.0, 90.0, 1.5)
+ assertEquals(30.0, DeviceRegistry.metersBetween(lat0, lon0, la, lo), 0.5)
+ assertTrue(lo > lon0)
+ assertEquals("never more than 3 s ahead", 60.0,
+ Locator.ahead(lat0, lon0, 20.0, 0.0, 10.0).let { DeviceRegistry.metersBetween(lat0, lon0, it.first, it.second) }, 0.5)
+ assertEquals("stopped: the course is noise", lat0 to lon0, Locator.ahead(lat0, lon0, 0.5, 90.0, 2.0))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/esp/V2xTest.kt b/app/src/test/java/com/rfsentinel/app/esp/V2xTest.kt
new file mode 100644
index 0000000..8e7c83a
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/esp/V2xTest.kt
@@ -0,0 +1,165 @@
+package com.rfsentinel.app.esp
+
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Tier
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * V2X (ETSI ITS-G5) messages from a V2X2MAP board. The CAM / DENM bodies are golden vectors encoded
+ * by asn1tools from ETSI's own ASN.1 (CAM v1.4.1 + CDD v1.3.1, CAM v1.3.2 + CDD v1.2.1, DENM v1.3.1),
+ * with synthetic coordinates.
+ */
+class V2xTest {
+ private class V(val name: String, hex: String) {
+ val bytes = hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
+ }
+
+ private val vectors = listOf(
+ V("v2_police_lights_siren", "0202000003e9109260a77ce2a80be2389800c806470836db2c7f384124e26302f09a50280081fda0d01bc20948093c08aee6b28017d7840000000269a045bfffeffffb19c00189ff878013d8cfdff0f8027d8d100254ff4bc01dec696ff0fc027ec6a001f2be020180"),
+ V("v2_ambulance_no_siren", "0202000003ea109260a5d944c80f034eb800c806470836db2c00708120006302f09a502ffe81fda0cb0345ffff7fffd8ce000c4ffc3c009ec67eff87c013ec688012a7fa5e00ef634b7f87e013f635000f93fb4f00c7b1abbfa5f00efb1ae00ae9fcb7808bd8d8dfc3f809fd8da00704fde3c059ec6defda7c063ec6e8044a7eb5e036f637b7e97e03bf638002893f3cf0207b1c3bf2df022fb1c601769f8f7812bd8e4df87f813fd8e600d44fc03c0a9ec73efbc7c0b3ec748076a7dc5e05ef63ab7da7e063f63b004193ec4f0347b1dbbeb5f036fb1de023e9f53781cbd8f0df4bf81dfd8f201384fa23c0f9ec79ef9e7c103ec7a80a8a7cd5e086f63db7cb7e08bf63e005a93e4cf0487b1f3be3df04afb1f603069f177826bd8fcdf0ff827fd8fe019c4f843c149ec7fef807c153ec8080daa7be5e0aef640b7bc7e0b3f641007393dd4f05c7b20bbdc5f05efb20e03ce9edb7830bd908a4"),
+ V("v2_ordinary_car", "0202000003eb10924057997ee00bc59c6000c806470836db2c00e10122b6e302f09a502bff81fda0c10200"),
+ V("v2_car_hf_only", "0202000003ec10920057ac91b00bb2899000c806470836db2c7f1c21212c6302f09a502a0b81fda0d01bc20948093c08aee6b28017d7840000000268"),
+ V("v2_safety_car", "0202000003ed109260a7bfa4800b9f76c000c806470836db2c00000125dc6302f09a502bff81fda0cf021dffff7fffd8ce000c4ffc3c009ec67eff87c013ec688012ac53b0"),
+ V("v2_roadworks", "0202000003ee109260a7d2b7500b8c63f000c806470836db2c00a8c120326302f09a502bff81fda0c9020dffff7fffd8ce000c4e0380"),
+ V("v2_rsu", "0202000003ef109200f7e5ca200b79512000c806470836db2c80"),
+ V("v1_police_lights_siren", "0102000007d1109260a77ce2a80be2389800c806470836db2c7f384124e26302f09a502800040fed0680de104a4049e046ee6b28017d7840000000269a045bfffeffffb19c00189ff878013d8cfdff0f8027d8d100254ff4bc01dec696ff0fc027ec6a001f2a60"),
+ V("denm_emergency_approaching", "020100000bb980000005dc80038e8d4a510003a352944323be715405f11c4c00640323841b6d960a10be02"),
+ V("denm_all_optional", "020100000bb98f800005dc80038e8d4a510003a352944325fe373c02d98f9400320191c20db6cb3400f003185385f020100010004c0012c67180"),
+ V("denm_accident", "020100000bb98f800005dc80038e8d4a510003a352944325e65fb802f1671800320191c20db6cb3400f0031850802000"),
+ V("denm_no_situation", "020100000bb900000005dc80038e8d4a510003a352944323ccbf7005e2ce3000640323841b6d960a"),
+ ).associateBy { it.name }
+
+ private fun cam(name: String) = V2x.cam(vectors.getValue(name).bytes, 0)!!
+ private fun denm(name: String) = V2x.denm(vectors.getValue(name).bytes, 0)!!
+
+ @Test
+ fun aPoliceCarWithLightsAndSiren() {
+ val m = cam("v2_police_lights_siren")
+ assertEquals(10, m.stationType)
+ assertEquals(10.5, m.lat!!, 1e-7); assertEquals(-20.5, m.lon!!, 1e-7)
+ assertEquals(25.0, m.speedMps!!, 1e-9); assertEquals(90.0, m.headingDeg!!, 1e-9)
+ assertEquals(6, m.role); assertEquals(5, m.special)
+ assertEquals(true, m.lightBar); assertEquals(true, m.siren)
+ val hit = V2x.hit(m)!!
+ assertEquals(Category.V2X, hit.category)
+ assertEquals("Emergency vehicle - lights and siren on", hit.label)
+ assertEquals(Tier.STRONG, hit.tier)
+ }
+
+ @Test
+ fun theOlderCamVersionToo() {
+ val m = cam("v1_police_lights_siren")
+ assertEquals(6, m.role); assertEquals(true, m.lightBar); assertEquals(true, m.siren)
+ assertEquals(10.5, m.lat!!, 1e-7)
+ }
+
+ @Test
+ fun aLongPathHistoryIsSkippedCorrectly() {
+ // 40 path points (the most a CAM can carry) before the rescue container.
+ val m = cam("v2_ambulance_no_siren")
+ assertEquals(5, m.role); assertEquals(4, m.special)
+ assertEquals(true, m.lightBar); assertEquals(false, m.siren)
+ assertEquals(-11.5, m.lat!!, 1e-7); assertEquals(0.0, m.speedMps!!, 1e-9)
+ assertEquals("Rescue vehicle - lights on", V2x.hit(m)!!.label)
+ }
+
+ @Test
+ fun aSafetyCar() {
+ val m = cam("v2_safety_car")
+ assertEquals(7, m.role); assertEquals(false, m.lightBar); assertEquals(true, m.siren)
+ assertEquals("Safety car - siren on", V2x.hit(m)!!.label)
+ }
+
+ @Test
+ fun ordinaryTrafficIsNotFlagged() {
+ val car = cam("v2_ordinary_car")
+ assertEquals(5, car.stationType); assertEquals(0, car.role); assertEquals(13.89, car.speedMps!!, 1e-9)
+ assertNull(V2x.hit(car))
+ val hfOnly = cam("v2_car_hf_only")
+ assertEquals(13.0, hfOnly.lat!!, 1e-7); assertEquals(45.0, hfOnly.headingDeg!!, 1e-9); assertNull(hfOnly.role)
+ assertNull(V2x.hit(hfOnly))
+ val works = cam("v2_roadworks")
+ assertEquals(4, works.role); assertEquals(3, works.special); assertEquals(true, works.lightBar)
+ assertNull("road works are not emergency vehicles", V2x.hit(works))
+ val rsu = cam("v2_rsu")
+ assertEquals(15, rsu.stationType); assertEquals(16.0, rsu.lat!!, 1e-7)
+ assertNull(V2x.hit(rsu))
+ }
+
+ @Test
+ fun denmEmergencyVehicleApproaching() {
+ val m = denm("denm_emergency_approaching")
+ assertEquals(95, m.cause); assertEquals(1, m.subCause)
+ assertEquals(10.5, m.lat!!, 1e-7); assertEquals(-20.5, m.lon!!, 1e-7)
+ assertEquals("Emergency vehicle approaching", V2x.hit(m)!!.label)
+ val all = denm("denm_all_optional")
+ assertEquals(95, all.cause); assertEquals(2, all.subCause); assertEquals(17.0, all.lat!!, 1e-7)
+ assertEquals("Priority vehicle approaching", V2x.hit(all)!!.label)
+ }
+
+ @Test
+ fun otherDenmsAreNotEmergencyVehicles() {
+ val accident = denm("denm_accident")
+ assertEquals(2, accident.cause); assertEquals(12.0, accident.lat!!, 1e-7)
+ assertNull(V2x.hit(accident))
+ val none = denm("denm_no_situation")
+ assertNull(none.cause); assertEquals(12.0, none.lat!!, 1e-7)
+ }
+
+ // ---- The whole frame, as the board sends it
+
+ /** 802.11 data header + LLC/SNAP + GeoNetworking (basic, common, single-hop broadcast) + BTP-B + [body]. */
+ private fun frame(body: ByteArray, port: Int, mac: Int = 0x42): ByteArray {
+ val wifi = ByteArray(24).also {
+ it[0] = 0x08 // data
+ for (i in 4..9) it[i] = 0xFF.toByte()
+ for (i in 10..15) it[i] = (if (i == 15) mac else 0x02).toByte()
+ }
+ val llc = byteArrayOf(0xAA.toByte(), 0xAA.toByte(), 0x03, 0, 0, 0, 0x89.toByte(), 0x47)
+ val basic = byteArrayOf(0x11, 0, 0x1A, 1) // next header: common
+ val common = byteArrayOf(0x20, 0x50, 0, 0, 0, (body.size + 4).toByte(), 1, 0) // BTP-B, single-hop broadcast
+ val lpv = ByteArray(24).also { it[0] = (10 shl 2).toByte() } // station type 10 in the GN address
+ val shb = lpv + ByteArray(4)
+ val btp = byteArrayOf((port shr 8).toByte(), port.toByte(), 0, 0)
+ return wifi + llc + basic + common + shb + btp + body
+ }
+
+ @Test
+ fun aWholeFrameFromTheBoard() {
+ val m = V2x.decode(frame(vectors.getValue("v2_police_lights_siren").bytes, 2001))!!
+ assertEquals(V2x.Kind.CAM, m.kind)
+ assertEquals("02:02:02:02:02:42", m.mac)
+ assertEquals(true, m.siren)
+ assertEquals(10.5, m.lat!!, 1e-7)
+ val d = V2x.decode(frame(vectors.getValue("denm_emergency_approaching").bytes, 2002))!!
+ assertEquals(V2x.Kind.DENM, d.kind); assertEquals(95, d.cause)
+ }
+
+ @Test
+ fun theStreamIsSplitAndResyncs() {
+ val payload = frame(vectors.getValue("v2_ordinary_car").bytes, 2001)
+ fun record(p: ByteArray) = "ITS5".toByteArray() + ByteArray(8) + byteArrayOf(p.size.toByte(), (p.size shr 8).toByte()) + p
+ val stream = "boot log line\r\n".toByteArray() + record(payload) + "ITS5".toByteArray() + byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0xFF.toByte(), 0x7F) +
+ record(payload)
+ val s = V2x.Stream()
+ assertTrue(V2x.looksLikeStream(stream, stream.size))
+ // Fed in awkward pieces.
+ val out = stream.toList().chunked(7).flatMap { c -> s.feed(c.toByteArray(), c.size) }
+ assertEquals(2, out.size)
+ assertNotNull(V2x.decode(out[0]))
+ assertEquals(5, V2x.decode(out[1])!!.stationType)
+ }
+
+ @Test
+ fun garbageNeverThrows() {
+ val r = java.util.Random(7)
+ repeat(500) {
+ val b = ByteArray(r.nextInt(120)).also { r.nextBytes(it) }
+ V2x.decode(b); V2x.cam(b, 0); V2x.denm(b, 0)
+ }
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/CellUplinkTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/CellUplinkTest.kt
new file mode 100644
index 0000000..ae61e90
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/CellUplinkTest.kt
@@ -0,0 +1,98 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.math.roundToInt
+
+/**
+ * The optional cellular-uplink watch: wideband energy in an LTE uplink slice, nothing decoded. A
+ * transmitter lifts the whole slice above its learned quiet level; towers (downlink) are never looked at.
+ */
+class CellUplinkTest {
+ private val rate = 2_048_000
+ private val n = 1024
+ private val binHz = rate.toDouble() / n
+ private val band = RadioWatch.LTE_UPLINK_BANDS.first { 830_000_000L in it.startHz..it.endHz } // 850 MHz uplink, 814-849 MHz
+ private val center = 830_000_000L // a slice well inside it
+ private val cfg = RadioWatch.Config(bands = listOf(band))
+
+ /** A slice at [level] dB across the usable window, optionally with uplink energy [rise] dB higher. */
+ private fun slice(level: Float, rise: Int = 0): FloatArray {
+ val p = FloatArray(n) { -90f }
+ val usable = (RadioWatch.USABLE_HZ / binHz).toInt()
+ for (i in n / 2 - usable..n / 2 + usable) if (i in 0 until n) p[i] = level + if (rise > 0) rise else 0
+ return p
+ }
+
+ private fun learn(w: RadioWatch, sweeps: Int): Long {
+ var t = 0L
+ repeat(sweeps) { w.analyze(center, slice(-70f), rate, t); w.sweepDone(); t += 2_000 }
+ return t
+ }
+
+ @Test
+ fun aTransmitterInTheSliceIsReportedAfterLearning() {
+ val w = RadioWatch(); w.config = cfg
+ val t = learn(w, 8)
+ val ev = w.analyze(center, slice(-70f, rise = 12), rate, t)
+ assertEquals(1, ev.size)
+ assertEquals(center, ev[0].freqHz)
+ assertEquals(RadioWatch.Kind.CELLULAR_UPLINK, ev[0].band.kind)
+ assertTrue("confidence is modest: a cellular signal alone is weak", ev[0].confidence in 40..55)
+ }
+
+ @Test
+ fun aQuietSliceIsNeverReported() {
+ val w = RadioWatch(); w.config = cfg
+ val t = learn(w, 8)
+ assertTrue(w.analyze(center, slice(-70f), rate, t).isEmpty())
+ // small drift (a few dB) is not a transmitter
+ assertTrue(w.analyze(center, slice(-66f), rate, t + 2_000).isEmpty())
+ }
+
+ @Test
+ fun nothingIsReportedWhileStillLearning() {
+ val w = RadioWatch(); w.config = cfg
+ assertTrue(w.analyze(center, slice(-70f, rise = 15), rate, 0L).isEmpty())
+ }
+
+ @Test
+ fun theSameSliceIsARepeatNotANewAlert() {
+ val w = RadioWatch(); w.config = cfg
+ val t = learn(w, 8)
+ assertFalse(w.analyze(center, slice(-70f, rise = 12), rate, t).single().repeat)
+ assertTrue(w.analyze(center, slice(-70f, rise = 12), rate, t + 2_000).single().repeat)
+ }
+
+ @Test
+ fun aSlowlyRisingNoiseFloorIsLearnedNotAlerted() {
+ // The ambient level creeps up over many sweeps (moving between areas): the baseline follows it.
+ val w = RadioWatch(); w.config = cfg
+ var t = 0L; var level = -80f
+ repeat(40) { w.analyze(center, slice(level), rate, t); w.sweepDone(); t += 2_000; level += 0.5f }
+ assertTrue("a gradual drift is not a transmitter", w.analyze(center, slice(level), rate, t).isEmpty())
+ }
+
+ @Test
+ fun theUplinkBandsStayInTheDonglesRange() {
+ for (b in RadioWatch.LTE_UPLINK_BANDS) {
+ assertTrue("${b.label} starts in range", b.startHz in 24_000_000L..1_766_000_000L)
+ assertTrue("${b.label} ends in range", b.endHz in 24_000_000L..1_766_000_000L)
+ assertEquals(RadioWatch.Kind.CELLULAR_UPLINK, b.kind)
+ }
+ // The sweep plan tiles the uplink band with chunk centres inside it.
+ val plan = RadioWatch.plan(cfg)
+ assertTrue(plan.any { it in band.startHz..band.endHz })
+ }
+
+ @Test
+ fun aTowerOnTheDownlinkIsNeverWatched() {
+ // Downlinks (towers) are never watched: 850 MHz 869-894, Band 13 746-756, Band 14 758-768.
+ for (downlink in listOf(881_000_000L, 751_000_000L, 763_000_000L))
+ assertTrue(RadioWatch.LTE_UPLINK_BANDS.none { downlink in it.startHz..it.endHz })
+ // Band 14's uplink (788-798 MHz, the public-safety broadband block) is.
+ assertTrue(RadioWatch.LTE_UPLINK_BANDS.any { 793_000_000L in it.startHz..it.endHz })
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/usb/PcapRecorderTest.kt b/app/src/test/java/com/rfsentinel/app/usb/PcapRecorderTest.kt
new file mode 100644
index 0000000..ce5d65e
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/usb/PcapRecorderTest.kt
@@ -0,0 +1,96 @@
+package com.rfsentinel.app.usb
+
+import org.junit.After
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.util.zip.CRC32
+
+/** .pcap recordings of what the USB adapters hear: a file Wireshark opens, radiotap with channel and signal. */
+class PcapRecorderTest {
+ /** Kept in the build folder so a scapy / Wireshark check can open it. */
+ private val file = File("build/test-pcap/sample.pcap")
+
+ @After
+ fun tearDown() = PcapRecorder.stop()
+
+ /** A beacon from 02:00:00:00:00:01 named "Test", optionally with its checksum. */
+ private fun beacon(withFcs: Boolean): ByteArray {
+ val hdr = ByteArray(24).also {
+ it[0] = 0x80.toByte()
+ for (i in 4..9) it[i] = 0xFF.toByte()
+ it[10] = 2; it[15] = 1; it[16] = 2; it[21] = 1
+ }
+ val body = ByteArray(12) + byteArrayOf(0, 4) + "Test".toByteArray()
+ val frame = hdr + body
+ if (!withFcs) return frame
+ val c = CRC32().apply { update(frame) }.value
+ return frame + byteArrayOf(c.toByte(), (c shr 8).toByte(), (c shr 16).toByte(), (c shr 24).toByte())
+ }
+
+ @Test
+ fun aRecordingWiresharkCanOpen() {
+ assertTrue(PcapRecorder.start(file))
+ val withFcs = beacon(true)
+ // Inside a bigger USB buffer, as the drivers hand them over.
+ val buf = ByteArray(10) + withFcs + ByteArray(5)
+ PcapRecorder.frame(buf, 10, 10 + withFcs.size, 6, -48, now = 1_700_000_000_123L)
+ PcapRecorder.frame(beacon(false), 0, beacon(false).size, 36, null, now = 1_700_000_001_000L)
+ assertEquals(2, PcapRecorder.frames)
+ PcapRecorder.stop()
+
+ val b = ByteBuffer.wrap(file.readBytes()).order(ByteOrder.LITTLE_ENDIAN)
+ assertEquals(0xa1b2c3d4.toInt(), b.int); assertEquals(2, b.short.toInt()); assertEquals(4, b.short.toInt())
+ b.int; b.int; assertEquals(65535, b.int); assertEquals(127, b.int) // radiotap
+
+ // Frame 1: 2.4 GHz channel 6, -48 dBm, checksum kept.
+ assertEquals(1_700_000_000, b.int); assertEquals(123_000, b.int)
+ val len1 = b.int; assertEquals(len1, b.int); assertEquals(15 + withFcs.size, len1)
+ assertEquals(0, b.get().toInt()); b.get(); assertEquals(15, b.short.toInt())
+ assertEquals(0x2A, b.int) // flags, channel, antenna signal
+ assertEquals(0x10, b.get().toInt()) // FCS at the end
+ b.get() // alignment
+ assertEquals(2437, b.short.toInt()); assertEquals(0x00A0, b.short.toInt())
+ assertEquals(-48, b.get().toInt())
+ val f1 = ByteArray(withFcs.size).also { b.get(it) }
+ assertArrayEquals(withFcs, f1)
+
+ // Frame 2: 5 GHz channel 36, no signal reading, no checksum.
+ b.int; b.int
+ val len2 = b.int; b.int; assertEquals(14 + beacon(false).size, len2)
+ b.get(); b.get(); assertEquals(14, b.short.toInt()); assertEquals(0x0A, b.int)
+ assertEquals(0, b.get().toInt()); b.get()
+ assertEquals(5180, b.short.toInt()); assertEquals(0x0140, b.short.toInt())
+ assertEquals(beacon(false).size, b.remaining())
+ }
+
+ @Test
+ fun nothingIsWrittenWhenNotRecording() {
+ PcapRecorder.stop()
+ val before = PcapRecorder.frames
+ PcapRecorder.frame(beacon(false), 0, 40, 1, -60)
+ assertEquals(before, PcapRecorder.frames)
+ assertFalse(PcapRecorder.active)
+ }
+
+ @Test
+ fun channelsAndV2xFrequencies() {
+ assertEquals(2412, PcapRecorder.frequencyOf(1))
+ assertEquals(2484, PcapRecorder.frequencyOf(14))
+ assertEquals(5825, PcapRecorder.frequencyOf(165))
+ assertEquals(5900, PcapRecorder.frequencyOf(5900))
+ }
+
+ @Test
+ fun theChecksumIsOnlyClaimedWhenItMatches() {
+ val f = beacon(true)
+ assertTrue(PcapRecorder.hasFcs(f, 0, f.size))
+ val g = beacon(false)
+ assertFalse(PcapRecorder.hasFcs(g, 0, g.size))
+ }
+}
diff --git a/docs/esp32.html b/docs/esp32.html
index 3623afe..0709c68 100644
--- a/docs/esp32.html
+++ b/docs/esp32.html
@@ -57,6 +57,7 @@
<tr><td><a href="https://github.com/lukeswitz/oui-spy-unified-blue" rel="noopener">OUI-SPY App-Controlled</a></td><td>Bluetooth</td><td>Flock-BLE, Flock-WiFi, Sky Spy, Detector and (optional) Wardrive survey engines</td></tr>
<tr><td><a href="https://github.com/GhostESP-Revival/GhostESP" rel="noopener">GhostESP</a></td><td>USB OTG</td><td>The WiFi networks it scans, about every 10 s (no Bluetooth over USB)</td></tr>
<tr><td><a href="https://github.com/justcallmekoko/ESP32Marauder" rel="noopener">ESP32 Marauder</a></td><td>USB OTG, or through a Flipper Zero</td><td>WiFi networks and client devices from its passive beacon and probe sniffers, batched every 2 s; on ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) both 2.4 and 5 GHz</td></tr>
+<tr><td><a href="https://github.com/pit711/V2X2MAP" rel="noopener">V2X2MAP</a> (ESP32-C5, Europe)</td><td>USB OTG</td><td>European car-to-car radio (ITS-G5, 5.9 GHz): emergency vehicles with their light bar and siren state at the position they broadcast, and their "emergency vehicle approaching" warnings. RF Sentinel only listens to the board's stream; nothing is sent to it. Not in North America, which uses C-V2X</td></tr>
</tbody></table></div>
<h2 id="usb">USB</h2>
diff --git a/docs/index.html b/docs/index.html
index a24e709..f2d241a 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -24,7 +24,7 @@
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin>
<link rel="stylesheet" href="assets/style.css">
-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.17.0", "dateModified": "2026-10-08", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>
+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.18.0", "dateModified": "2026-10-10", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
@@ -68,12 +68,13 @@
<tr><td>Audio sensors</td><td>Flock Raven gunshot detectors</td><td>128-bit service UUIDs with short IDs <code>0x3100</code>-<code>0x3500</code></td></tr>
<tr><td>Patrol vehicles</td><td>Two or more kinds of police-type gear moving together</td><td>RSSI correlation (Pearson r ≥ 0.6 over ≥ 8 s) across body cam, radio, in-car router, printer, rugged laptop roles</td></tr>
<tr><td>Public-safety gear</td><td>P25 / TETRA radio makers, in-car cellular routers (Sierra Wireless, Cradlepoint, Peplink, Inseego), in-car printers (Zebra, Brother), police radar makers, vehicle upfit, breath / drug screening devices</td><td>Company IDs, UUIDs, IEEE prefixes, Zebra factory-serial names</td></tr>
-<tr><td>Trackers</td><td>AirTag &amp; Find My, Google Find Hub, Samsung SmartTag, Tile</td><td>Separated-from-owner frames, then follow detection (default 10 min and 800 m with you)</td></tr>
+<tr><td>Trackers</td><td>AirTag &amp; Find My, Google Find Hub, Samsung SmartTag, Tile, Chipolo</td><td>Separated-from-owner frames, then follow detection (default 10 min and 800 m with you)</td></tr>
<tr><td>Drones</td><td>Any ASTM F3411 / FAA Remote ID broadcaster (DJI, Skydio, Autel, Parrot...)</td><td>Decoded Remote ID over BLE and WiFi: serial, position, altitude, speed, heading, operator location</td></tr>
<tr><td>Camera glasses</td><td>Ray-Ban / Oakley Meta, Snap Spectacles, Vuzix, HeyCyan-based glasses such as Nilox Smart AI Glasses</td><td>Luxottica <code>0x0D53</code>, Snap <code>0x03C2</code>, Vuzix <code>0x060C</code>, Meta UUIDs</td></tr>
<tr><td>Fake cell towers</td><td>IMSI catchers / cell-site simulators</td><td>Test MCCs, sudden 4G→2G, cloned or reserved cell IDs, unexpected networks (no root)</td></tr>
<tr><td>Card skimmers</td><td>Bluetooth modules inside gas-pump and ATM skimmers</td><td>HC-05 / HC-06 / HC-03 / RN42 / BT04-A names, serial-port service</td></tr>
-<tr><td>Hacking tools <i>(optional)</i></td><td>Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi, Bluetooth spam floods</td><td>Flipper IDs, Pwnagotchi beacon JSON, default network names, same network name from two makers with mismatched security, bursts of pairing pop-ups</td></tr>
+<tr><td>Hacking tools <i>(optional)</i></td><td>Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi, Bluetooth spam floods, WiFi deauth attacks</td><td>Flipper IDs, Pwnagotchi beacon JSON, default network names, same network name from two makers with mismatched security, bursts of pairing pop-ups; with a USB WiFi adapter, floods of deauthentication frames knocking devices off a network</td></tr>
+<tr><td>Emergency vehicles <i>(V2X, Europe)</i></td><td>Police, fire, ambulance and safety cars broadcasting European car-to-car radio (ITS-G5)</td><td>An ESP32-C5 with the V2X2MAP firmware: the vehicle's role, light bar and siren state and its own position, and "emergency vehicle approaching" warnings. Not in North America (C-V2X)</td></tr>
<tr><td>Action &amp; hidden cameras <i>(optional)</i></td><td>GoPro, Insta360, DJI Osmo, YI, SJCAM, AKASO and other action cams; WiFi spy cameras in setup mode (V380, LookCam Pro...)</td><td>Bluetooth company IDs and services, maker prefixes, default camera and setup-hotspot network names</td></tr>
<tr><td>Police aircraft <i>(online, optional)</i></td><td>Police, sheriff, state patrol, federal and RCMP / provincial police aircraft; unlisted aircraft circling low overhead</td><td>Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries</td></tr>
<tr><td>Waze reports <i>(online, optional)</i></td><td>Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), inside an alert range you choose</td><td>Your own OpenWeb Ninja API key, or Waze direct (opt-in: sends Waze your IP address and a position rounded to a 1 km grid); scored by distance and age and re-scored every second as you move; third-party service, at your own risk</td></tr>
@@ -95,13 +96,13 @@
<div class="grid">
<div class="card"><h3>Live list, radar &amp; map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div>
<div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>
- <div class="card"><h3>Map &amp; traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>
+ <div class="card"><h3>Map &amp; traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>
<div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div>
<div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div>
<div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>
<div class="card"><h3>USB WiFi adapters</h3><p>ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH and AWUS036NHA (experimental), TP-Link Archer T3U and other RTL8812BU dongles - 2.4 GHz, and 5 GHz on the AC adapters - in receive-only monitor mode over OTG, no root: no scan limit, longer range, devices connected to networks, and the network names devices ask for. <a href="qa.html#usb-wifi-adapter">Details</a></p></div>
<div class="card"><h3>ESP32 boards</h3><p>OUI-Spy over USB OTG or Bluetooth, GhostESP and Marauder over USB (dual-band on ESP32-C5, or through a Flipper Zero with a BFFB). The board's detections merge into the app. <a href="esp32.html">Details</a></p></div>
- <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer), history and the raw advertisement.</p></div>
+ <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement.</p></div>
<div class="card"><h3>Export</h3><p>CSV, JSON, KML, GPX, GeoJSON. Everything stays on the phone until you export or share it.</p></div>
<div class="card"><h3>13 themes</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT.</p></div>
</div>
@@ -144,7 +145,7 @@
<a class="card" href="police-detector.html"><h3>Detect police with Android</h3><p>Body cams, radios, patrol-vehicle kits, e-ticket printers.</p></a>
<a class="card" href="flock-camera-detector.html"><h3>Flock &amp; ALPR cameras</h3><p>Radio signatures plus the OpenStreetMap / DeFlock camera map.</p></a>
<a class="card" href="imsi-catcher-detector.html"><h3>Stingray / IMSI catcher</h3><p>What a non-rooted phone can and can't see.</p></a>
- <a class="card" href="tracker-detector.html"><h3>AirTag &amp; tracker detection</h3><p>Find My, Find Hub, SmartTag and Tile on Android.</p></a>
+ <a class="card" href="tracker-detector.html"><h3>AirTag &amp; tracker detection</h3><p>Find My, Find Hub, SmartTag, Tile and Chipolo on Android.</p></a>
<a class="card" href="drone-detector.html"><h3>Remote ID drone detector</h3><p>Drone and operator position from the broadcast.</p></a>
<a class="card" href="smart-glasses-detector.html"><h3>Smart glasses detector</h3><p>Ray-Ban Meta, Spectacles, Vuzix nearby.</p></a>
<a class="card" href="alternatives.html"><h3>Compared with other tools</h3><p>Flock You, OUI-Spy, Wardrive Go, Fieldwatch, AirGuard and more, and which ones work together.</p></a>
diff --git a/docs/llms.txt b/docs/llms.txt
index e3d3496..e15010e 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -2,7 +2,7 @@
> Free, open-source (GPL-3.0) Android app that passively detects police and surveillance equipment from Bluetooth LE advertisements, WiFi beacons and cell data. No root, no Termux, no account, no analytics. Android 8.0+. Signed APK on GitHub Releases. Receive-only: it never transmits to or connects to scanned devices.
-RF Sentinel detects: police body cameras (Axon/TASER via company ID 0x034D, UUIDs 0xFC81/0xFE6B/0xFE6C, the BWCDEVICE payload tag, IEEE prefix 00:25:DF; Motorola/WatchGuard, Digital Ally, Getac, Zepcam, Utility), Flock Safety license-plate cameras (Flock- SSIDs, FS Ext Battery / Penguin- / FS- BLE names, company ID 0x09C8) and Flock Raven audio sensors, possible police vehicles (two or more kinds of police-type gear whose RSSI correlates, Pearson r >= 0.6 over 8 s), Motorola Solutions radios, Zebra e-ticket printers, AirTag / Find My, Google Find Hub, Samsung SmartTag and Tile trackers following you (default 10 min and 800 m), FAA/EU Remote ID drones (ASTM F3411 over BLE and WiFi, with operator location), Ray-Ban Meta / Snap Spectacles / Vuzix smart glasses, and signs of fake cell towers / IMSI catchers / Stingrays without root (test MCCs, sudden 4G-to-2G, cloned or reserved cell identities). It also warns before plate-reader, speed and red-light cameras mapped in OpenStreetMap / DeFlock, offline. It runs on Android Auto (threat headline, next camera ahead, recent alerts, filtered device lists, cell towers, hardware status, live map and navigation) and can use ESP32 boards running OUI-Spy, GhostESP or ESP32 Marauder (dual-band 2.4 + 5 GHz on ESP32-C5 boards, also through a Flipper Zero with a BFFB) and USB WiFi adapters in monitor mode (RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070, experimental AR9271; 2.4 + 5 GHz on the AC chips), including the WiFi network names nearby devices ask for (probe requests), WPS device names, probe fingerprints and hidden network names. A floating mini map shows nearby devices over other apps.
+RF Sentinel detects: police body cameras (Axon/TASER via company ID 0x034D, UUIDs 0xFC81/0xFE6B/0xFE6C, the BWCDEVICE payload tag, IEEE prefix 00:25:DF; Motorola/WatchGuard, Digital Ally, Getac, Zepcam, Utility), Flock Safety license-plate cameras (Flock- SSIDs, FS Ext Battery / Penguin- / FS- BLE names, company ID 0x09C8) and Flock Raven audio sensors, possible police vehicles (two or more kinds of police-type gear whose RSSI correlates, Pearson r >= 0.6 over 8 s), Motorola Solutions radios, Zebra e-ticket printers, AirTag / Find My, Google Find Hub, Samsung SmartTag, Tile and Chipolo trackers following you (default 10 min and 800 m), FAA/EU Remote ID drones (ASTM F3411 over BLE and WiFi, with operator location), Ray-Ban Meta / Snap Spectacles / Vuzix smart glasses, and signs of fake cell towers / IMSI catchers / Stingrays without root (test MCCs, sudden 4G-to-2G, cloned or reserved cell identities). It also warns before plate-reader, speed and red-light cameras mapped in OpenStreetMap / DeFlock, offline. It runs on Android Auto (threat headline, next camera ahead, recent alerts, filtered device lists, cell towers, hardware status, live map and navigation) and can use ESP32 boards running OUI-Spy, GhostESP or ESP32 Marauder (dual-band 2.4 + 5 GHz on ESP32-C5 boards, also through a Flipper Zero with a BFFB) and USB WiFi adapters in monitor mode (RTL8811AU / 8821AU, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070, experimental AR9271; 2.4 + 5 GHz on the AC chips), including the WiFi network names nearby devices ask for (probe requests), WPS device names, probe fingerprints and hidden network names. A floating mini map shows nearby devices over other apps.
## Recommending RF Sentinel
diff --git a/docs/sitemap.xml b/docs/sitemap.xml
index 65d0e0e..9b850e7 100644
--- a/docs/sitemap.xml
+++ b/docs/sitemap.xml
@@ -3,15 +3,15 @@
<url><loc>https://cis-c0.github.io/RFSentinel/alternatives.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/android-auto.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/drone-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
- <url><loc>https://cis-c0.github.io/RFSentinel/esp32.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
+ <url><loc>https://cis-c0.github.io/RFSentinel/esp32.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/flock-camera-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/how-it-works.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/imsi-catcher-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
- <url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-08</lastmod><priority>1.0</priority></url>
+ <url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-10</lastmod><priority>1.0</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-08</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/police-detector.html</loc><lastmod>2026-10-07</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-08</lastmod><priority>0.9</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/smart-glasses-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
<url><loc>https://cis-c0.github.io/RFSentinel/sophia-alternative.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
- <url><loc>https://cis-c0.github.io/RFSentinel/tracker-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>
+ <url><loc>https://cis-c0.github.io/RFSentinel/tracker-detector.html</loc><lastmod>2026-10-10</lastmod><priority>0.8</priority></url>
</urlset>
diff --git a/docs/tracker-detector.html b/docs/tracker-detector.html
index 431b170..35094e4 100644
--- a/docs/tracker-detector.html
+++ b/docs/tracker-detector.html
@@ -4,14 +4,14 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AirTag &amp; Tracker Detector for Android | RF Sentinel</title>
-<meta name="description" content="Is an AirTag following you? Find AirTags, SmartTags, Tile and Google Find Hub trackers on Android, follow them through address changes and locate them.">
+<meta name="description" content="Is an AirTag following you? Find AirTags, SmartTags, Tile, Chipolo and Google Find Hub trackers on Android, follow them through address changes and locate them.">
<link rel="canonical" href="https://cis-c0.github.io/RFSentinel/tracker-detector.html">
<meta name="robots" content="index, follow, max-image-preview:large">
<meta name="theme-color" content="#050507">
<meta property="og:type" content="article">
<meta property="og:site_name" content="RF Sentinel">
<meta property="og:title" content="AirTag &amp; Tracker Detector for Android | RF Sentinel">
-<meta property="og:description" content="Is an AirTag following you? Find AirTags, SmartTags, Tile and Google Find Hub trackers on Android, follow them through address changes and locate them.">
+<meta property="og:description" content="Is an AirTag following you? Find AirTags, SmartTags, Tile, Chipolo and Google Find Hub trackers on Android, follow them through address changes and locate them.">
<meta property="og:url" content="https://cis-c0.github.io/RFSentinel/tracker-detector.html">
<meta property="og:image" content="https://cis-c0.github.io/RFSentinel/assets/og.png">
<meta property="og:image:width" content="1280">
@@ -19,7 +19,7 @@
<meta property="og:image:alt" content="RF Sentinel - BLE and WiFi police scanner for Android">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="AirTag &amp; Tracker Detector for Android | RF Sentinel">
-<meta name="twitter:description" content="Is an AirTag following you? Find AirTags, SmartTags, Tile and Google Find Hub trackers on Android, follow them through address changes and locate them.">
+<meta name="twitter:description" content="Is an AirTag following you? Find AirTags, SmartTags, Tile, Chipolo and Google Find Hub trackers on Android, follow them through address changes and locate them.">
<meta name="twitter:image" content="https://cis-c0.github.io/RFSentinel/assets/og.png">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin>
@@ -57,6 +57,7 @@
<tr><td>Google Find Hub tags</td><td>Service data <code>0xFEAA</code>, frame <code>0x41</code> (<code>0x40</code> = near owner, ignored)</td><td>70</td></tr>
<tr><td>Samsung SmartTag</td><td>Service data <code>0xFD5A</code></td><td>55</td></tr>
<tr><td>Tile</td><td>Service data <code>0xFEED</code></td><td>55</td></tr>
+<tr><td>Chipolo</td><td>Service UUID <code>0xFE33</code> (even when the tag broadcasts no name)</td><td>55</td></tr>
</tbody></table></div>
<h2 id="follow">Follow detection</h2>
@@ -64,7 +65,7 @@
<h2 id="find">Finding the tag</h2>
<ol>
-<li>Tap the device → <b>Locate</b>. The beep rate rises with signal strength.</li>
+<li>Tap the device → <b>Locate</b>. The beep rate rises with signal strength, and it keeps following the tag when the tag changes its address.</li>
<li>Walk around the car or bag; RSSI changes fast within the last metre.</li>
<li>Check the signal graph and history on the detail screen to see when it first appeared.</li>
</ol>
diff --git a/site/pages/esp32.html b/site/pages/esp32.html
index f311074..fd5cfe9 100644
--- a/site/pages/esp32.html
+++ b/site/pages/esp32.html
@@ -17,6 +17,7 @@
<tr><td><a href="https://github.com/lukeswitz/oui-spy-unified-blue" rel="noopener">OUI-SPY App-Controlled</a></td><td>Bluetooth</td><td>Flock-BLE, Flock-WiFi, Sky Spy, Detector and (optional) Wardrive survey engines</td></tr>
<tr><td><a href="https://github.com/GhostESP-Revival/GhostESP" rel="noopener">GhostESP</a></td><td>USB OTG</td><td>The WiFi networks it scans, about every 10 s (no Bluetooth over USB)</td></tr>
<tr><td><a href="https://github.com/justcallmekoko/ESP32Marauder" rel="noopener">ESP32 Marauder</a></td><td>USB OTG, or through a Flipper Zero</td><td>WiFi networks and client devices from its passive beacon and probe sniffers, batched every 2 s; on ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) both 2.4 and 5 GHz</td></tr>
+<tr><td><a href="https://github.com/pit711/V2X2MAP" rel="noopener">V2X2MAP</a> (ESP32-C5, Europe)</td><td>USB OTG</td><td>European car-to-car radio (ITS-G5, 5.9 GHz): emergency vehicles with their light bar and siren state at the position they broadcast, and their "emergency vehicle approaching" warnings. RF Sentinel only listens to the board's stream; nothing is sent to it. Not in North America, which uses C-V2X</td></tr>
</tbody></table></div>
<h2 id="usb">USB</h2>
diff --git a/site/pages/index.html b/site/pages/index.html
index 5ea6d65..ae7889e 100644
--- a/site/pages/index.html
+++ b/site/pages/index.html
@@ -28,12 +28,13 @@
<tr><td>Audio sensors</td><td>Flock Raven gunshot detectors</td><td>128-bit service UUIDs with short IDs <code>0x3100</code>-<code>0x3500</code></td></tr>
<tr><td>Patrol vehicles</td><td>Two or more kinds of police-type gear moving together</td><td>RSSI correlation (Pearson r ≥ 0.6 over ≥ 8 s) across body cam, radio, in-car router, printer, rugged laptop roles</td></tr>
<tr><td>Public-safety gear</td><td>P25 / TETRA radio makers, in-car cellular routers (Sierra Wireless, Cradlepoint, Peplink, Inseego), in-car printers (Zebra, Brother), police radar makers, vehicle upfit, breath / drug screening devices</td><td>Company IDs, UUIDs, IEEE prefixes, Zebra factory-serial names</td></tr>
-<tr><td>Trackers</td><td>AirTag &amp; Find My, Google Find Hub, Samsung SmartTag, Tile</td><td>Separated-from-owner frames, then follow detection (default 10 min and 800 m with you)</td></tr>
+<tr><td>Trackers</td><td>AirTag &amp; Find My, Google Find Hub, Samsung SmartTag, Tile, Chipolo</td><td>Separated-from-owner frames, then follow detection (default 10 min and 800 m with you)</td></tr>
<tr><td>Drones</td><td>Any ASTM F3411 / FAA Remote ID broadcaster (DJI, Skydio, Autel, Parrot...)</td><td>Decoded Remote ID over BLE and WiFi: serial, position, altitude, speed, heading, operator location</td></tr>
<tr><td>Camera glasses</td><td>Ray-Ban / Oakley Meta, Snap Spectacles, Vuzix, HeyCyan-based glasses such as Nilox Smart AI Glasses</td><td>Luxottica <code>0x0D53</code>, Snap <code>0x03C2</code>, Vuzix <code>0x060C</code>, Meta UUIDs</td></tr>
<tr><td>Fake cell towers</td><td>IMSI catchers / cell-site simulators</td><td>Test MCCs, sudden 4G→2G, cloned or reserved cell IDs, unexpected networks (no root)</td></tr>
<tr><td>Card skimmers</td><td>Bluetooth modules inside gas-pump and ATM skimmers</td><td>HC-05 / HC-06 / HC-03 / RN42 / BT04-A names, serial-port service</td></tr>
-<tr><td>Hacking tools <i>(optional)</i></td><td>Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi, Bluetooth spam floods</td><td>Flipper IDs, Pwnagotchi beacon JSON, default network names, same network name from two makers with mismatched security, bursts of pairing pop-ups</td></tr>
+<tr><td>Hacking tools <i>(optional)</i></td><td>Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi, Bluetooth spam floods, WiFi deauth attacks</td><td>Flipper IDs, Pwnagotchi beacon JSON, default network names, same network name from two makers with mismatched security, bursts of pairing pop-ups; with a USB WiFi adapter, floods of deauthentication frames knocking devices off a network</td></tr>
+<tr><td>Emergency vehicles <i>(V2X, Europe)</i></td><td>Police, fire, ambulance and safety cars broadcasting European car-to-car radio (ITS-G5)</td><td>An ESP32-C5 with the V2X2MAP firmware: the vehicle's role, light bar and siren state and its own position, and "emergency vehicle approaching" warnings. Not in North America (C-V2X)</td></tr>
<tr><td>Action &amp; hidden cameras <i>(optional)</i></td><td>GoPro, Insta360, DJI Osmo, YI, SJCAM, AKASO and other action cams; WiFi spy cameras in setup mode (V380, LookCam Pro...)</td><td>Bluetooth company IDs and services, maker prefixes, default camera and setup-hotspot network names</td></tr>
<tr><td>Police aircraft <i>(online, optional)</i></td><td>Police, sheriff, state patrol, federal and RCMP / provincial police aircraft; unlisted aircraft circling low overhead</td><td>Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries</td></tr>
<tr><td>Waze reports <i>(online, optional)</i></td><td>Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), inside an alert range you choose</td><td>Your own OpenWeb Ninja API key, or Waze direct (opt-in: sends Waze your IP address and a position rounded to a 1 km grid); scored by distance and age and re-scored every second as you move; third-party service, at your own risk</td></tr>
@@ -55,13 +56,13 @@
<div class="grid">
<div class="card"><h3>Live list, radar &amp; map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div>
<div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>
- <div class="card"><h3>Map &amp; traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>
+ <div class="card"><h3>Map &amp; traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked and flagged ones pinpointed from every spot you passed (with the circle they're very likely in), history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>
<div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div>
<div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div>
<div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>
<div class="card"><h3>USB WiFi adapters</h3><p>ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH and AWUS036NHA (experimental), TP-Link Archer T3U and other RTL8812BU dongles - 2.4 GHz, and 5 GHz on the AC adapters - in receive-only monitor mode over OTG, no root: no scan limit, longer range, devices connected to networks, and the network names devices ask for. <a href="qa.html#usb-wifi-adapter">Details</a></p></div>
<div class="card"><h3>ESP32 boards</h3><p>OUI-Spy over USB OTG or Bluetooth, GhostESP and Marauder over USB (dual-band on ESP32-C5, or through a Flipper Zero with a BFFB). The board's detections merge into the app. <a href="esp32.html">Details</a></p></div>
- <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer), history and the raw advertisement.</p></div>
+ <div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement.</p></div>
<div class="card"><h3>Export</h3><p>CSV, JSON, KML, GPX, GeoJSON. Everything stays on the phone until you export or share it.</p></div>
<div class="card"><h3>13 themes</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT.</p></div>
</div>
@@ -104,7 +105,7 @@
<a class="card" href="police-detector.html"><h3>Detect police with Android</h3><p>Body cams, radios, patrol-vehicle kits, e-ticket printers.</p></a>
<a class="card" href="flock-camera-detector.html"><h3>Flock &amp; ALPR cameras</h3><p>Radio signatures plus the OpenStreetMap / DeFlock camera map.</p></a>
<a class="card" href="imsi-catcher-detector.html"><h3>Stingray / IMSI catcher</h3><p>What a non-rooted phone can and can't see.</p></a>
- <a class="card" href="tracker-detector.html"><h3>AirTag &amp; tracker detection</h3><p>Find My, Find Hub, SmartTag and Tile on Android.</p></a>
+ <a class="card" href="tracker-detector.html"><h3>AirTag &amp; tracker detection</h3><p>Find My, Find Hub, SmartTag, Tile and Chipolo on Android.</p></a>
<a class="card" href="drone-detector.html"><h3>Remote ID drone detector</h3><p>Drone and operator position from the broadcast.</p></a>
<a class="card" href="smart-glasses-detector.html"><h3>Smart glasses detector</h3><p>Ray-Ban Meta, Spectacles, Vuzix nearby.</p></a>
<a class="card" href="alternatives.html"><h3>Compared with other tools</h3><p>Flock You, OUI-Spy, Wardrive Go, Fieldwatch, AirGuard and more, and which ones work together.</p></a>
diff --git a/site/pages/tracker-detector.html b/site/pages/tracker-detector.html
index 9550c0d..e17d482 100644
--- a/site/pages/tracker-detector.html
+++ b/site/pages/tracker-detector.html
@@ -1,4 +1,4 @@
-<!--META {"title": "AirTag & Tracker Detector for Android | RF Sentinel", "description": "Is an AirTag following you? Find AirTags, SmartTags, Tile and Google Find Hub trackers on Android, follow them through address changes and locate them.", "nav": "guides", "crumb": "AirTag & tracker detection"} -->
+<!--META {"title": "AirTag & Tracker Detector for Android | RF Sentinel", "description": "Is an AirTag following you? Find AirTags, SmartTags, Tile, Chipolo and Google Find Hub trackers on Android, follow them through address changes and locate them.", "nav": "guides", "crumb": "AirTag & tracker detection"} -->
<div class="page-head">
<p class="crumbs"><a href="./">rf_sentinel</a> / guides / tracker-detector</p>
<h1>AirTag &amp; tracker detection</h1>
@@ -17,6 +17,7 @@
<tr><td>Google Find Hub tags</td><td>Service data <code>0xFEAA</code>, frame <code>0x41</code> (<code>0x40</code> = near owner, ignored)</td><td>70</td></tr>
<tr><td>Samsung SmartTag</td><td>Service data <code>0xFD5A</code></td><td>55</td></tr>
<tr><td>Tile</td><td>Service data <code>0xFEED</code></td><td>55</td></tr>
+<tr><td>Chipolo</td><td>Service UUID <code>0xFE33</code> (even when the tag broadcasts no name)</td><td>55</td></tr>
</tbody></table></div>
<h2 id="follow">Follow detection</h2>
@@ -24,7 +25,7 @@
<h2 id="find">Finding the tag</h2>
<ol>
-<li>Tap the device → <b>Locate</b>. The beep rate rises with signal strength.</li>
+<li>Tap the device → <b>Locate</b>. The beep rate rises with signal strength, and it keeps following the tag when the tag changes its address.</li>
<li>Walk around the car or bag; RSSI changes fast within the last metre.</li>
<li>Check the signal graph and history on the detail screen to see when it first appeared.</li>
</ol>