RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
Keep locked alerts placed while walking: step + compass dead reckoning fused with GPS, position solved from lines and readings
CIS-C0642d0126514c
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 9faf7dc..2374606 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -782,19 +782,17 @@ class MainActivity : AppCompatActivity() {binding.radarView.setBlips(visible.take(200).map { s ->val alert = com.rfsentinel.app.ui.LiveWindow.alerting(s, now)val at = if (alert && fix != null) knownPosition(s, fix.latitude, fix.longitude) else null- // Placed by your turns on the radar (crossed into a spot once you turned at two places), or the- // device being located once a chest sweep found its side.- val tracked = if (alert && at == null) com.rfsentinel.app.ui.RadarTrack.place(s.mac, fix?.latitude, fix?.longitude, now) else null- val crossed = tracked?.takeIf { it.distanceM != null }- val swept = if (at == null) com.rfsentinel.app.ui.LiveRead.sweptBearing(s.mac) else null+ // Placed by your turns and kept placed as you walk, or the device being located once its sweep locked.+ val tracked = if (alert && at == null) com.rfsentinel.app.ui.RadarTrack.place(s.mac, now) else null+ val swept = if (at == null && tracked == null) com.rfsentinel.app.ui.LiveRead.sweptBearing(s.mac) else nullRadarView.Blip(s.mac, s.rssi,if (alert) colorFor(s) else binding.radarView.ordinaryColor(),alert,if (alert) s.best?.label else null,at?.let { com.rfsentinel.app.alpr.KnownCameras.bearingTo(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() }- ?: crossed?.bearing ?: swept ?: tracked?.bearing,- at?.let { DeviceRegistry.metersBetween(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() } ?: crossed?.distanceM,+ ?: tracked?.bearing ?: swept,+ at?.let { DeviceRegistry.metersBetween(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() } ?: tracked?.distanceM,now - s.lastSeen)} + radio)diff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.ktindex 404053b..30be96b 100644--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt@@ -725,15 +725,18 @@ object DeviceIntel {* Walls, bodies and antenna orientation easily cause 2-3x errors.*/fun distanceMeters(a: Advert, rssi: Double = a.rssi.toDouble()): Double {- if (a.isWifi) {- val f = a.wifi?.frequencyMhz?.takeIf { it > 0 } ?: 2437- val exp = (20.0 - rssi - 20 * log10(f.toDouble()) + 27.55) / 20.0- return 10.0.pow(exp).coerceIn(0.5, 500.0)- }- val measuredAt1m = a.txPower?.let { it - 41 } ?: -59- return 10.0.pow((measuredAt1m - rssi) / 25.0).coerceIn(0.1, 300.0)+ val d = 10.0.pow((powerAt1m(a) - rssi) / (10 * pathLossExponent(a)))+ return if (a.isWifi) d.coerceIn(0.5, 500.0) else d.coerceIn(0.1, 300.0)}+ /** The signal (dBm) expected 1 m away: a WiFi radio's free-space loss at its frequency, BLE's advertised power. */+ fun powerAt1m(a: Advert): Double =+ if (a.isWifi) 20.0 - 20 * log10((a.wifi?.frequencyMhz?.takeIf { it > 0 } ?: 2437).toDouble()) + 27.55+ else (a.txPower?.let { it - 41 } ?: -59).toDouble()++ /** How fast the signal falls with distance (10 n dB per tenfold). */+ fun pathLossExponent(a: Advert) = if (a.isWifi) 2.0 else 2.5+/** Device distances in feet (and miles past 1000 ft): the app's units ([com.rfsentinel.app.util.Units]). */var imperial: Booleanget() = com.rfsentinel.app.util.Units.imperialdiff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.ktindex d17116b..99dd96e 100644--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt@@ -452,8 +452,8 @@ object DeviceRegistry {/** Full snapshot (history, path, raw advert) for the detail screen. */fun get(mac: String): Snapshot? = tracks[mac]?.let { t -> synchronized(t) { snap(t, full = true) } }- /** When [mac] was last heard and its raw signal then: unsmoothed, so a direction sweep isn't seconds behind. */- fun lastHeard(mac: String): Pair<Long, Int>? = tracks[mac]?.let { t -> synchronized(t) { t.lastSeen to (t.advert?.rssi ?: t.rssi) } }+ /** When [mac] was last heard and that raw advert: unsmoothed, so a direction sweep isn't seconds behind. */+ fun lastHeard(mac: String): Pair<Long, Advert>? = tracks[mac]?.let { t -> synchronized(t) { t.advert?.let { t.lastSeen to it } } }/** Devices heard since [since] with their summary, for persisting to known_devices. */fun summaries(since: Long): List<Snapshot> =diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.ktindex 705c004..1e29668 100644--- a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt@@ -100,6 +100,7 @@ object LiveRead {com.rfsentinel.app.service.ScanForegroundService.lastFix?.let { c.setLocation(it.latitude, it.longitude, it.altitude) }c.start()}+ Motion.start(context)main.post(beep)main.post(sample)tick()@@ -114,15 +115,24 @@ object LiveRead {/** What the Locate guide shows, null when not locating. Main thread. */fun sweepState(now: Long = System.currentTimeMillis()): SweepState? {if (locating == null) return null- val moved = lockedAt?.let { a -> com.rfsentinel.app.service.ScanForegroundService.lastFix?.distanceTo(a) }- return SweepState(heading, sweep.sectors(now), sweep.covered(now), sweep.estimate(now), lock, moved)+ val mac = locating ?: return null+ // Placed (it stays put as you walk): no need to sweep again.+ val moved = if (RadarTrack.place(mac, now) != null) null+ else lockedAt?.let { a -> com.rfsentinel.app.service.ScanForegroundService.lastFix?.distanceTo(a) }+ return SweepState(heading, sweep.sectors(now), sweep.covered(now), sweep.estimate(now), held(now), moved)+ }++ /** The lock, turned to where the device is from where you stand now once [RadarTrack] placed it. */+ private fun held(now: Long): Sweep.Estimate? {+ val l = lock ?: return null+ val mac = locating ?: return l+ return RadarTrack.place(mac, now)?.let { l.copy(bearing = it.bearing) } ?: l}/** The locked direction (compass degrees) of [mac] while it is being located, for the radar. Main thread. */fun sweptBearing(mac: String): Float? {- val l = lock ?: return nullval m = locating ?: return null- return l.bearing.takeIf { mac == m || mac == followed }+ return held(System.currentTimeMillis())?.bearing?.takeIf { mac == m || mac == followed }}/** Main thread. */@@ -132,7 +142,7 @@ object LiveRead {val was = locating != nulllocating = null; followed = nullcompass?.stop(); compass = null- if (was) tick()+ if (was) { Motion.stop(); tick() }}private val beep = object : Runnable {@@ -165,14 +175,17 @@ object LiveRead {val now = System.currentTimeMillis()val t0 = tickAt; val h0 = tickHeading ?: htickAt = now; tickHeading = h- val (seen, rssi) = DeviceRegistry.lastHeard(followed ?: mac) ?: return+ val (seen, a) = DeviceRegistry.lastHeard(followed ?: mac) ?: returnif (seen == sweepFed) returnsweepFed = seen- sweep.add(seen, Sweep.headingAt(seen, t0, h0, now, h), rssi)+ val facing = Sweep.headingAt(seen, t0, h0, now, h)+ sweep.add(seen, facing, a.rssi)+ RadarTrack.reading(mac, seen, facing, a)if (lock != null) returnval e = sweep.settled(seen) ?: returnlock = elockedAt = com.rfsentinel.app.service.ScanForegroundService.lastFix+ RadarTrack.line(mac, e.bearing, e.confidence, seen)appContext?.let { AlertPlayer.vibrate(it, longArrayOf(0, 60, 90, 60)) }tick()}@@ -237,9 +250,10 @@ object LiveRead {/** The sweep's hint while locating: how to turn, then the locked direction. Null without a compass. Main thread. */fun sweepText(now: Long = System.currentTimeMillis()): String? {val h = heading ?: return null- val l = lock ?: return "Phone on your chest, turn slowly: ${sweep.covered(now) * 360 / Sweep.SECTORS}° of 360°"+ val l = held(now) ?: return "Phone on your chest, turn slowly: ${sweep.covered(now) * 360 / Sweep.SECTORS}° of 360°"val moved = sweepState(now)?.moved?.takeIf { it > SWEEP_STALE_M }- return "${Sweep.compassPoint(l.bearing)} · ${turnText(Sweep.turn(h, l.bearing))} · " ++ val far = locating?.let { RadarTrack.place(it, now) }?.let { " · ~" + DeviceIntel.formatDistance(it.distanceM.toDouble()) }.orEmpty()+ return "${Sweep.compassPoint(l.bearing)}$far · ${turnText(Sweep.turn(h, l.bearing))} · " +if (moved != null) "you moved, sweep again" else "${(l.confidence * 100).toInt()}% sure"}diff --git a/app/src/main/java/com/rfsentinel/app/ui/Motion.kt b/app/src/main/java/com/rfsentinel/app/ui/Motion.ktnew file mode 100644index 0000000..396898b--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/Motion.kt@@ -0,0 +1,157 @@+package com.rfsentinel.app.ui++import android.content.Context+import android.hardware.Sensor+import android.hardware.SensorEvent+import android.hardware.SensorEventListener+import android.hardware.SensorManager+import com.rfsentinel.app.service.ScanForegroundService+import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Where you are, to the metre, while the radar or Locate is on screen: steps from the accelerometer, walked the way+ * the compass says (dead reckoning, like phone-finding apps track you between fixes), pulled toward each GPS fix by+ * how sure that fix is. GPS alone wanders 5-10 m on foot, which swings a near device's direction; steps alone+ * drift, which GPS corrects. Positions are metres east / north in one frame ([generation]); a new frame starts when+ * it resumes with no GPS to tie the old one to. Main thread: [start] / [stop] are counted.+ */+object Motion : SensorEventListener {++ class Pos(val x: Double, val y: Double)++ private var users = 0+ private var sm: SensorManager? = null+ private var compass: Compass? = null+ private val fusion = Fusion()+ private val steps = Steps()+ /** Changes when positions from before can't be compared with positions now. */+ var generation = 0+ private set+ private var stale = false+ private var staleSince = 0L+ private var fixTime = 0L++ /** Where you are now; null while waiting for a GPS fix to place you again after a pause. */+ val position: Pos? get() = if (users == 0 || stale) null else Pos(fusion.x, fusion.y)++ fun start(context: Context) {+ if (users++ > 0) return+ val app = context.applicationContext+ sm = app.getSystemService(Context.SENSOR_SERVICE) as? SensorManager+ sm?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.let { sm?.registerListener(this, it, SensorManager.SENSOR_DELAY_GAME) }+ compass = Compass(app).also { it.start() }+ // You may have walked while it was off: the next fix places you again, else a new frame.+ if (fusion.anchored) { stale = true; staleSince = System.currentTimeMillis() } else newFrame()+ }++ fun stop() {+ if (users == 0 || --users > 0) return+ sm?.unregisterListener(this)+ compass?.stop(); compass = null+ }++ private fun newFrame() { generation++; fusion.reset(); stale = false }++ override fun onSensorChanged(e: SensorEvent) {+ val now = System.currentTimeMillis()+ ScanForegroundService.lastFix?.takeIf { it.time != fixTime }?.let { f ->+ fixTime = f.time+ compass?.setLocation(f.latitude, f.longitude, f.altitude)+ if (f.hasAccuracy() && f.accuracy <= MAX_ACCURACY_M && now - f.time < FIX_FRESH_MS) {+ fusion.gps(f.latitude, f.longitude, f.accuracy.toDouble(), snap = stale)+ stale = false+ }+ }+ if (stale && now - staleSince > STALE_MS) newFrame()+ val v = e.values+ if (!steps.add(e.timestamp / 1_000_000, sqrt((v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).toDouble()))) return+ compass?.degrees?.let { fusion.step(it) }+ }++ override fun onAccuracyChanged(s: Sensor?, accuracy: Int) {}++ /**+ * Dead reckoning fused with GPS (a one-state Kalman filter per axis): each step adds its own doubt, each fix+ * pulls by doubt / (doubt + fix error²). Pure (unit-tested).+ */+ class Fusion {+ var x = 0.0+ private set+ var y = 0.0+ private set+ private var variance = 0.0+ private var lat0 = Double.NaN+ private var lon0 = Double.NaN+ private var lastHeading: Float? = null+ val anchored get() = !lat0.isNaN()++ fun reset() { x = 0.0; y = 0.0; variance = 0.0; lat0 = Double.NaN; lon0 = Double.NaN; lastHeading = null }++ /** One step while facing [heading]. Shuffling round on the spot (a sweep) is steps too, but barely moves you. */+ fun step(heading: Float) {+ val turned = lastHeading?.let { abs(Sweep.turn(it, heading)) > TURN_DEG } ?: false+ lastHeading = heading+ val len = if (turned) STEP_M * TURN_STEP else STEP_M+ val r = Math.toRadians(heading.toDouble())+ x += len * sin(r); y += len * cos(r)+ variance += STEP_VARIANCE+ }++ /** A GPS fix [accM] metres sure; [snap] puts you there (after a pause). The first one ties the frame to the map. */+ fun gps(lat: Double, lon: Double, accM: Double, snap: Boolean = false) {+ val acc2 = accM.coerceAtLeast(MIN_ACCURACY_M).let { it * it }+ if (!anchored) {+ lat0 = lat - y / M_PER_DEG_LAT; lon0 = lon - x / mPerDegLon(lat)+ variance = acc2+ return+ }+ val gx = (lon - lon0) * mPerDegLon(lat0)+ val gy = (lat - lat0) * M_PER_DEG_LAT+ val k = if (snap) 1.0 else variance / (variance + acc2)+ x += k * (gx - x); y += k * (gy - y)+ variance = if (snap) acc2 else (1 - k) * variance+ }++ private fun mPerDegLon(lat: Double) = 111_320.0 * cos(Math.toRadians(lat))+ }++ /** Steps from the accelerometer's swing above gravity, at a walking pace at most. Pure (unit-tested). */+ class Steps {+ private var gravity = 9.81+ private var smooth = 9.81+ private var armed = false+ private var last = Long.MIN_VALUE / 2++ /** A reading ([ms] time, [mag] m/s² all axes): true at each step. */+ fun add(ms: Long, mag: Double): Boolean {+ gravity += 0.01 * (mag - gravity)+ smooth += 0.3 * (mag - smooth)+ val a = smooth - gravity+ if (a > RISE) armed = true+ else if (armed && a < FALL) {+ armed = false+ if (ms - last >= MIN_GAP_MS) { last = ms; return true }+ }+ return false+ }+ }++ // shortcut: one step length for everyone; learn it from GPS distance / steps if ranges come out scaled.+ private const val STEP_M = 0.7+ private const val TURN_DEG = 30f+ private const val TURN_STEP = 0.2+ /** Doubt each step adds (m²): length and heading errors. */+ private const val STEP_VARIANCE = 0.25+ private const val MIN_ACCURACY_M = 3.0+ private const val MAX_ACCURACY_M = 50f+ private const val FIX_FRESH_MS = 5_000L+ /** Resumed and no fix this long: start over. */+ private const val STALE_MS = 10_000L+ private const val M_PER_DEG_LAT = 110_540.0+ private const val RISE = 1.2+ private const val FALL = 0.2+ private const val MIN_GAP_MS = 280L+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/RadarTrack.kt b/app/src/main/java/com/rfsentinel/app/ui/RadarTrack.ktindex 13b3074..39b6297 100644--- a/app/src/main/java/com/rfsentinel/app/ui/RadarTrack.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/RadarTrack.kt@@ -1,115 +1,196 @@package com.rfsentinel.app.ui-import com.rfsentinel.app.alpr.KnownCameras-import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.detect.Advert+import com.rfsentinel.app.detect.DeviceIntelimport kotlin.math.abs+import kotlin.math.atan2import kotlin.math.cos-import kotlin.math.min+import kotlin.math.hypot+import kotlin.math.log10+import kotlin.math.max+import kotlin.math.roundToLongimport kotlin.math.sin+import kotlin.math.sqrt/**- * Places alerts on the main radar from the way you turn, with no Locate needed. While the radar is on screen every- * alerting device gets its own [Sweep]: the phone held in front of you, your body shadows the signal from behind,- * so a turn on the spot shows its side. Each direction a turn settles on is kept as a line from where you stood;- * two or more lines from spots apart [cross] at the device, so its dot keeps its real place (direction and- * distance) as you turn and walk. Main thread; [cross] is pure (unit-tested).+ * Keeps alerts placed on the radar (and Locate's arrow) while you walk. While the radar is on screen every alerting+ * device gets its own [Sweep]: phone held in front of you, your body shadows the signal from behind, so a turn on+ * the spot shows its side, kept as a line from where you stood. Every reading is kept too, with where you were+ * ([Motion]: steps + compass + GPS) and the way you faced. [solve] finds the spot that best explains all of it:+ * the lines' directions, and how the signal rose and fell along your path with your body's shadow, so the device+ * stays put on the map and its direction and distance from you update as you move. Main thread; [solve] is pure+ * (unit-tested).*/object RadarTrack {- /** A settled direction ([bearing], compass degrees) from where you stood (null without a GPS fix). */- class Line(val lat: Double?, val lon: Double?, val bearing: Float, val weight: Float, val time: Long)+ /** A settled direction ([bearing], compass degrees) from where you stood (metres in [Motion]'s frame). */+ class Line(val x: Double, val y: Double, val bearing: Float, val weight: Float, val time: Long)- /** Where an alert shows on the radar: its direction, and how far once lines crossed. */- class Place(val bearing: Float, val distanceM: Float?)+ /** A raw reading heard at x/y while facing [heading]. */+ class Reading(val x: Double, val y: Double, val heading: Float, val rssi: Int, val time: Long)- private class Track { val sweep = Sweep(); val lines = ArrayList<Line>(); var fed = 0L }+ /** Signal expected 1 m away ([p0], dBm) and how fast it falls ([n]). */+ class Radio(val p0: Double, val n: Double)++ /** Where an alert shows from where you are: its direction and distance. */+ class Place(val bearing: Float, val distanceM: Float)++ private class Track(val generation: Int) {+ val sweep = Sweep()+ val lines = ArrayList<Line>()+ val readings = ArrayDeque<Reading>()+ var radio = Radio(-59.0, 2.5)+ var fed = 0L+ var spot: Motion.Pos? = null+ var solvedAt = 0L+ var dirty = false+ }private val tracks = HashMap<String, Track>()- /** A new reading of [mac] ([rssi] raw, heard at [time] while facing [heading]); [lat]/[lon]: where you are. */- fun feed(mac: String, time: Long, heading: Float, rssi: Int, lat: Double?, lon: Double?) {- tracks.entries.removeAll { time - it.value.fed > LINE_MS }- val t = tracks.getOrPut(mac) { Track() }- if (time == t.fed) return+ private fun track(mac: String, now: Long): Track {+ tracks.entries.removeAll { now - it.value.fed > WINDOW_MS || it.value.generation != Motion.generation }+ return tracks.getOrPut(mac) { Track(Motion.generation) }+ }++ /** A new reading of [mac] (the raw advert [a], heard at [time] facing [heading]); false when it was already in. */+ fun reading(mac: String, time: Long, heading: Float, a: Advert): Boolean {+ val pos = Motion.position ?: return false+ val t = track(mac, time)+ if (time == t.fed) return falset.fed = time- t.sweep.add(time, heading, rssi)+ t.radio = Radio(DeviceIntel.powerAt1m(a), DeviceIntel.pathLossExponent(a))+ val last = t.readings.lastOrNull()+ if (last == null || time - last.time >= READING_GAP_MS) {+ t.readings.addLast(Reading(pos.x, pos.y, heading, a.rssi, time))+ while (t.readings.size > MAX_READINGS || time - t.readings.first().time > WINDOW_MS) t.readings.removeFirst()+ t.dirty = true+ }+ return true+ }++ /** A direction a turn settled on for [mac], from where you stand now. */+ fun line(mac: String, bearing: Float, confidence: Float, time: Long) {+ val pos = Motion.position ?: return+ val t = track(mac, time)+ // Another turn at the same spot replaces the line there.+ t.lines.removeAll { time - it.time > WINDOW_MS || hypot(it.x - pos.x, it.y - pos.y) < SAME_SPOT_M }+ t.lines += Line(pos.x, pos.y, bearing, confidence, time)+ while (t.lines.size > MAX_LINES) t.lines.removeAt(0)+ t.dirty = true+ }++ /** The radar's reading of an alert: kept, and run through its own sweep for a line. */+ fun feed(mac: String, time: Long, heading: Float, a: Advert) {+ if (!reading(mac, time, heading, a)) return+ val t = tracks[mac] ?: return+ t.sweep.add(time, heading, a.rssi)val e = t.sweep.settled(time) ?: return// The next turn gives a new, independent line.t.sweep.clear()- // Another turn at the same spot replaces the line there.- t.lines.removeAll { time - it.time > LINE_MS || near(it, lat, lon, SAME_SPOT_M) }- t.lines += Line(lat, lon, e.bearing, e.confidence, time)- while (t.lines.size > MAX_LINES) t.lines.removeAt(0)+ line(mac, e.bearing, e.confidence, time)}- /** Where [mac] shows from where you are now ([lat]/[lon], null without a fix); null when no turn settled it yet. */- fun place(mac: String, lat: Double?, lon: Double?, now: Long): Place? {- val t = tracks[mac] ?: return null- t.lines.removeAll { now - it.time > LINE_MS }- if (lat != null && lon != null) cross(t.lines)?.let { (dLat, dLon) ->- val d = DeviceRegistry.metersBetween(lat, lon, dLat, dLon).toFloat()- return Place(KnownCameras.bearingTo(lat, lon, dLat, dLon).toFloat(), d)+ /** Where [mac] is from where you stand now; null before any turn settled its side. */+ fun place(mac: String, now: Long): Place? {+ val pos = Motion.position ?: return null+ val t = tracks[mac]?.takeIf { it.generation == Motion.generation } ?: return null+ t.lines.removeAll { now - it.time > WINDOW_MS }+ if (t.lines.isEmpty()) return null+ if (t.dirty && now - t.solvedAt >= SOLVE_MS || t.spot == null) {+ t.spot = solve(t.lines, t.readings.toList(), t.radio)+ t.solvedAt = now; t.dirty = false}- // Not crossed yet: the newest direction, while you still stand about where you took it.- val l = t.lines.lastOrNull()?.takeIf { near(it, lat, lon, NEAR_M) } ?: return null- return Place(l.bearing, null)+ val s = t.spot ?: return null+ val dx = s.x - pos.x; val dy = s.y - pos.y+ return Place(((Math.toDegrees(atan2(dx, dy)) + 360) % 360).toFloat(), hypot(dx, dy).toFloat())}- /** Forgets every line and sweep (scan stopped). */fun clear() = tracks.clear()- private fun near(l: Line, lat: Double?, lon: Double?, m: Double): Boolean {- if (l.lat == null || l.lon == null || lat == null || lon == null) return l.lat == null && lat == null- return DeviceRegistry.metersBetween(l.lat, l.lon, lat, lon) <= m- }-/**- * The weighted least-squares crossing (lat to lon) of the [lines] that have a position: null unless two of them- * differ by [MIN_CROSS_DEG], and the crossing lies ahead of every line within [MAX_RANGE_M] (a crossing behind- * you means one direction is wrong).+ * The spot (metres) that best explains the [lines] (each off by about [SIGMA_DEG]) and the [readings] (path+ * loss plus your body's shadow when you faced away, off by about [SIGMA_DB]; each 3 m spot counts once, as+ * readings there fade together). The power at 1 m is fitted, held near the [radio]'s usual one. Searched within+ * [RANGE_M] of the newest line, coarse then fine. Null without a line.*/- fun cross(lines: List<Line>): Pair<Double, Double>? {- val ls = lines.filter { it.lat != null && it.lon != null }- if (ls.size < 2) return null- var spread = 0f- for (i in ls.indices) for (j in i + 1 until ls.size) {- val d = abs(Sweep.turn(ls[i].bearing, ls[j].bearing)).toFloat()- spread = maxOf(spread, min(d, 180f - d))- }- if (spread < MIN_CROSS_DEG) return null- val lat0 = ls[0].lat!!; val lon0 = ls[0].lon!!- val mx = 111_320.0 * cos(Math.toRadians(lat0)); val my = 110_540.0- fun x(l: Line) = (l.lon!! - lon0) * mx- fun y(l: Line) = (l.lat!! - lat0) * my- // Minimises the weighted squared distance across each line: sum w (I - d dT) (p - x) = 0.- var a11 = 0.0; var a12 = 0.0; var a22 = 0.0; var b1 = 0.0; var b2 = 0.0- for (l in ls) {- val r = Math.toRadians(l.bearing.toDouble()); val dx = sin(r); val dy = cos(r)- val w = l.weight.toDouble()- val m11 = 1 - dx * dx; val m12 = -dx * dy; val m22 = 1 - dy * dy- a11 += w * m11; a12 += w * m12; a22 += w * m22- b1 += w * (m11 * x(l) + m12 * y(l)); b2 += w * (m12 * x(l) + m22 * y(l))+ fun solve(lines: List<Line>, readings: List<Reading>, radio: Radio): Motion.Pos? {+ val o = lines.lastOrNull() ?: return null+ val n = readings.size+ val rx = DoubleArray(n) { readings[it].x }+ val ry = DoubleArray(n) { readings[it].y }+ val rr = DoubleArray(n) { readings[it].rssi.toDouble() }+ val fs = DoubleArray(n) { sin(Math.toRadians(readings[it].heading.toDouble())) }+ val fc = DoubleArray(n) { cos(Math.toRadians(readings[it].heading.toDouble())) }+ // Readings at one spot share their fading: together they weigh as one.+ val perCell = HashMap<Long, Int>()+ val cell = LongArray(n) { (rx[it] / CELL_M).roundToLong() * 1_000_003L + (ry[it] / CELL_M).roundToLong() }+ for (c in cell) perCell[c] = (perCell[c] ?: 0) + 1+ val w = DoubleArray(n) { 1.0 / perCell[cell[it]]!! }+ val wSum = w.sum()+ val model = DoubleArray(n)+ val tenN = 10 * radio.n+ val s2 = SIGMA_DB * SIGMA_DB+ val p2 = SIGMA_P0 * SIGMA_P0++ fun cost(px: Double, py: Double): Double {+ var c = 0.0+ for (l in lines) {+ val dx = px - l.x; val dy = py - l.y+ if (dx * dx + dy * dy < 1.0) continue+ val e = angleDiff(l.bearing.toDouble(), Math.toDegrees(atan2(dx, dy))) / SIGMA_DEG+ c += LINE_WEIGHT * l.weight * e * e+ }+ if (n == 0) return c+ var sum = 0.0+ for (k in 0 until n) {+ val dx = px - rx[k]; val dy = py - ry[k]+ val d = max(sqrt(dx * dx + dy * dy), 1.0)+ // Your body between you and it: 0 facing it, BODY_DB with your back to it.+ val facing = (dx * fs[k] + dy * fc[k]) / d+ model[k] = tenN * log10(d) + BODY_DB * (1 - facing) / 2+ sum += w[k] * (rr[k] + model[k])+ }+ val p0 = ((sum / s2 + radio.p0 / p2) / (wSum / s2 + 1 / p2)).coerceIn(radio.p0 - P0_SPAN, radio.p0 + P0_SPAN)+ for (k in 0 until n) { val r = rr[k] - (p0 - model[k]); c += w[k] * r * r / s2 }+ return c + (p0 - radio.p0) * (p0 - radio.p0) / p2}- val det = a11 * a22 - a12 * a12- if (abs(det) < 1e-9) return null- val px = (b1 * a22 - b2 * a12) / det- val py = (a11 * b2 - a12 * b1) / det- for (l in ls) {- val r = Math.toRadians(l.bearing.toDouble())- val along = (px - x(l)) * sin(r) + (py - y(l)) * cos(r)- if (along <= 0 || along > MAX_RANGE_M) return null++ fun search(cx: Double, cy: Double, half: Double, step: Double): Triple<Double, Double, Double> {+ var best = Triple(cx, cy, Double.MAX_VALUE)+ val steps = (half / step).toInt()+ for (i in -steps..steps) for (j in -steps..steps) {+ val x = cx + i * step; val y = cy + j * step+ val c = cost(x, y)+ if (c < best.third) best = Triple(x, y, c)+ }+ return best}- return lat0 + py / my to lon0 + px / mx+ val coarse = search(o.x, o.y, RANGE_M, COARSE_M)+ val fine = search(coarse.first, coarse.second, COARSE_M, FINE_M)+ return Motion.Pos(fine.first, fine.second)}- /** Lines older than this drop out: the device may have moved. */- const val LINE_MS = 5 * 60_000L+ private fun angleDiff(a: Double, b: Double) = ((b - a) % 360 + 540) % 360 - 180++ /** Lines and readings older than this drop out: the device may have moved. */+ const val WINDOW_MS = 5 * 60_000Lprivate const val MAX_LINES = 6+ private const val MAX_READINGS = 300+ private const val READING_GAP_MS = 1_000L+ private const val SOLVE_MS = 2_000L/** A turn within this of an earlier one is the same spot. */private const val SAME_SPOT_M = 8.0- /** A direction alone holds while you stay within this of where you took it. */- private const val NEAR_M = 25.0- /** Lines this close to parallel don't cross anywhere useful. */- const val MIN_CROSS_DEG = 20f- /** About as far as a phone hears Bluetooth. */- private const val MAX_RANGE_M = 300.0+ private const val CELL_M = 3.0+ /** How far off a settled line usually is, and how much it counts against a reading. */+ private const val SIGMA_DEG = 20.0+ private const val LINE_WEIGHT = 2.0+ private const val SIGMA_DB = 6.0+ /** How far a radio's power at 1 m strays from the usual, and the most it can. */+ private const val SIGMA_P0 = 8.0+ private const val P0_SPAN = 25.0+ /** Your body's shadow with your back to it (measured 5-14 dB at 2.4 GHz). */+ private const val BODY_DB = 8.0+ private const val RANGE_M = 120.0+ private const val COARSE_M = 6.0+ private const val FINE_M = 1.0}diff --git a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt b/app/src/main/java/com/rfsentinel/app/ui/RadarView.ktindex 2138618..8d8d040 100644--- a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt@@ -64,10 +64,12 @@ class RadarView @JvmOverloads constructor(private var lastFix: Location? = nullprivate var tickAt = 0Lprivate var tickHeading: Float? = null+ /** The sampler and [Motion] run (counted once per radar). */+ private var tracking = false/*** Five times a second while on screen: each alert's new raw reading with the way you faced when it was heard,- * so [RadarTrack] finds its side as you turn and crosses the lines as you walk.+ * so [RadarTrack] finds its side as you turn and keeps it placed as you walk ([Motion] tracks your steps).*/private val sampler = object : Runnable {override fun run() {@@ -80,8 +82,8 @@ class RadarView @JvmOverloads constructor(// In a car its metal, not your body, shapes the signal.if (fix != null && fix.hasSpeed() && fix.speed > WALK_MS) returnfor (it in items) if (it.b.flagged) {- val (seen, rssi) = DeviceRegistry.lastHeard(it.b.mac) ?: continue- RadarTrack.feed(it.b.mac, seen, Sweep.headingAt(seen, t0, h0, now, h), rssi, fix?.latitude, fix?.longitude)+ val (seen, a) = DeviceRegistry.lastHeard(it.b.mac) ?: continue+ RadarTrack.feed(it.b.mac, seen, Sweep.headingAt(seen, t0, h0, now, h), a)}}}@@ -132,13 +134,16 @@ class RadarView @JvmOverloads constructor(// The compass runs only while the radar is on screen.override fun onVisibilityAggregated(isVisible: Boolean) {super.onVisibilityAggregated(isVisible)+ if (isVisible == tracking) { if (isVisible) compass.start(); return }+ tracking = isVisibleremoveCallbacks(sampler)- if (isVisible) { compass.start(); post(sampler) } else compass.stop()+ if (isVisible) { compass.start(); Motion.start(context); post(sampler) } else { compass.stop(); Motion.stop() }}override fun onDetachedFromWindow() {compass.stop()removeCallbacks(sampler)+ if (tracking) { tracking = false; Motion.stop() }super.onDetachedFromWindow()}diff --git a/app/src/test/java/com/rfsentinel/app/ui/MotionTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MotionTest.ktnew file mode 100644index 0000000..735b4ff--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/MotionTest.kt@@ -0,0 +1,42 @@+package com.rfsentinel.app.ui++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import kotlin.math.sin++class MotionTest {++ @Test+ fun stepsWalkTheWayYouFaceAndGpsPullsBack() {+ val f = Motion.Fusion()+ f.gps(0.0, 0.0, 5.0) // ties the frame at 0 / 0+ repeat(10) { f.step(0f) } // 7 m north+ assertEquals(7.0, f.y, 0.01)+ assertEquals(0.0, f.x, 0.01)+ // A fix 20 m east, 5 m sure: pulled part way, not all the way.+ f.gps(7.0 / 110_540.0, 20.0 / 111_320.0, 5.0)+ assertTrue("${f.x}", f.x > 0.5 && f.x < 15)+ // After a pause, a fix snaps you there.+ f.gps(0.0, 0.0, 5.0, snap = true)+ assertEquals(0.0, f.x, 0.01)+ assertEquals(0.0, f.y, 0.01)+ }++ @Test+ fun turningOnTheSpotBarelyMoves() {+ val f = Motion.Fusion()+ for (h in 0 until 360 step 45) f.step(h.toFloat())+ assertTrue("${f.x},${f.y}", kotlin.math.hypot(f.x, f.y) < 1.5)+ }++ @Test+ fun countsWalkingSteps() {+ val s = Motion.Steps()+ // 10 s at 50 Hz: walking (2 steps a second, ±3 m/s²), then holding still.+ val walking = (0 until 500).count { s.add(it * 20L, 9.81 + 3 * sin(it * 20 / 1000.0 * 2 * Math.PI * 2)) }+ assertEquals(20.0, walking.toDouble(), 2.0)+ val still = (500 until 1000).count { s.add(it * 20L, 9.81 + 0.05 * sin(it * 1.3)) }+ assertEquals(0, still)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/RadarTrackTest.kt b/app/src/test/java/com/rfsentinel/app/ui/RadarTrackTest.ktindex 2a0a64d..39fd09f 100644--- a/app/src/test/java/com/rfsentinel/app/ui/RadarTrackTest.kt+++ b/app/src/test/java/com/rfsentinel/app/ui/RadarTrackTest.kt@@ -1,34 +1,48 @@package com.rfsentinel.app.uiimport org.junit.Assert.assertEquals-import org.junit.Assert.assertNotNullimport org.junit.Assert.assertNull+import org.junit.Assert.assertTrueimport org.junit.Test+import kotlin.math.cos+import kotlin.math.hypot+import kotlin.math.log10+import kotlin.math.sinclass RadarTrackTest {- // Metres east / north of a neutral origin (0, 0) to lat/lon.- private fun line(east: Double, north: Double, bearing: Float) =- RadarTrack.Line(north / 110_540.0, east / 111_320.0, bearing, 1f, 0L)+ private val ble = RadarTrack.Radio(-59.0, 2.5)++ /** What a phone at x/y facing [heading] hears from a device at dx/dy: path loss plus the body's shadow. */+ private fun heard(x: Double, y: Double, heading: Float, dx: Double, dy: Double, time: Long): RadarTrack.Reading {+ val d = hypot(dx - x, dy - y).coerceAtLeast(1.0)+ val r = Math.toRadians(heading.toDouble())+ val facing = ((dx - x) * sin(r) + (dy - y) * cos(r)) / d+ return RadarTrack.Reading(x, y, heading, (-59 - 25 * log10(d) - 8 * (1 - facing) / 2).toInt(), time)+ }@Testfun twoTurnsCrossAtTheDevice() {- // Device 50 m east and 50 m north: seen NE from the start, NW from 100 m further east.- val (lat, lon) = RadarTrack.cross(listOf(line(0.0, 0.0, 45f), line(100.0, 0.0, 315f)))!!- assertEquals(50.0, lat * 110_540.0, 1.0)- assertEquals(50.0, lon * 111_320.0, 1.0)- // A third, slightly off line still lands close.- val (lat3, lon3) = RadarTrack.cross(listOf(line(0.0, 0.0, 45f), line(100.0, 0.0, 315f), line(50.0, 0.0, 5f)))!!- assertEquals(50.0, lat3 * 110_540.0, 5.0)- assertEquals(50.0, lon3 * 111_320.0, 5.0)+ // Device 50 m east and 50 m north: NE from the start, NW from 100 m further east.+ val p = RadarTrack.solve(listOf(RadarTrack.Line(0.0, 0.0, 45f, 1f, 0L), RadarTrack.Line(100.0, 0.0, 315f, 1f, 0L)), emptyList(), ble)!!+ assertEquals(50.0, p.x, 2.0)+ assertEquals(50.0, p.y, 2.0)+ }++ @Test+ fun oneTurnThenWalkingGivesTheRange() {+ // Turned at the start and found it east; then walked 60 m north past it. Device 40 m east.+ val readings = (0..60 step 2).map { heard(0.0, it - 30.0, 0f, 40.0, 0.0, it * 1_000L) }+ val p = RadarTrack.solve(listOf(RadarTrack.Line(0.0, -30.0, 53f, 1f, 0L)), readings, ble)!!+ assertTrue("$p", hypot(p.x - 40.0, p.y) < 10.0)}@Test- fun noCrossingWhenParallelBehindOrAlone() {- assertNull(RadarTrack.cross(listOf(line(0.0, 0.0, 45f))))- assertNull(RadarTrack.cross(listOf(line(0.0, 0.0, 45f), line(100.0, 0.0, 50f)))) // nearly parallel- assertNull(RadarTrack.cross(listOf(line(0.0, 0.0, 45f), line(100.0, 0.0, 135f)))) // behind the second spot- assertNull(RadarTrack.cross(listOf(RadarTrack.Line(null, null, 45f, 1f, 0L), line(100.0, 0.0, 315f))))- assertNotNull(RadarTrack.cross(listOf(line(0.0, 0.0, 45f), line(100.0, 0.0, 315f))))+ fun oneTurnAloneStaysOnItsLine() {+ val readings = listOf(heard(0.0, 0.0, 90f, 20.0, 0.0, 0L))+ val p = RadarTrack.solve(listOf(RadarTrack.Line(0.0, 0.0, 90f, 1f, 0L)), readings, ble)!!+ assertTrue("${p.x}", p.x > 3)+ assertEquals(0.0, p.y, p.x * 0.2)+ assertNull(RadarTrack.solve(emptyList(), readings, ble))}}