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.

Radar: compass heading-up fused with GPS course, distance and direction on located alerts

CIS-C0bd4f6b8079fa
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 5fa21aa..b405e57 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -179,9 +179,22 @@ class MainActivity : AppCompatActivity() {
// Rows rebind every second (RSSI / "seen Xs ago"); the default change
// crossfade would make the whole list flicker and fight the match flash.
(binding.recyclerView.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
- binding.radarView.onBlipClick = {
- if (it.startsWith(RADIO_ROW)) startActivity(Intent(this, com.rfsentinel.app.ui.DetectionLogActivity::class.java))
- else DeviceActions.openDetails(this, it)
+ binding.radarView.onBlipClick = { b ->
+ val at = if (b.bearing != null) DeviceRegistry.get(b.mac)?.let { s -> s.broadcast?.let { it.lat to it.lon } ?: s.located?.let { it.lat to it.lon } } else null
+ when {
+ b.mac.startsWith(RADIO_ROW) -> startActivity(Intent(this, com.rfsentinel.app.ui.DetectionLogActivity::class.java))
+ // A located alert: its details, or where it is on the map.
+ at != null -> com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
+ .setTitle(b.label ?: b.mac)
+ .setItems(arrayOf("Show details", "Show on map")) { _, which ->
+ if (which == 0) DeviceActions.openDetails(this, b.mac)
+ else startActivity(Intent(this, com.rfsentinel.app.ui.MapActivity::class.java)
+ .putExtra(com.rfsentinel.app.ui.MapActivity.EXTRA_CENTER_LAT, at.first)
+ .putExtra(com.rfsentinel.app.ui.MapActivity.EXTRA_CENTER_LON, at.second))
+ }
+ .show()
+ else -> DeviceActions.openDetails(this, b.mac)
+ }
}
// The app closed while the map was starting last time: switch it to OpenGL, or leave it off the main screen (and say so).
val mapRecovery = com.rfsentinel.app.ui.MapSafety.recover(this)
@@ -768,16 +781,20 @@ class MainActivity : AppCompatActivity() {
val radio = radioBlips(now, threshold)
radioBlips = radio.size
val fix = if (demoMode) com.rfsentinel.app.ui.DemoData.fakeLocation else ScanForegroundService.lastFix
- // Heading-up while moving (the GPS course is steady from walking speed up), north-up otherwise.
- binding.radarView.heading = fix?.takeIf { it.hasBearing() && it.speed >= 1.5f }?.bearing
+ // Heading-up from the compass (and the GPS course while driving), north-up without either.
+ binding.radarView.setFix(fix)
+ binding.radarView.pinpointOff = !Prefs.pinpointFlagged(this)
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
RadarView.Blip(
s.mac, s.rssi,
if (alert) colorFor(s) else binding.radarView.ordinaryColor(),
alert,
if (alert) s.best?.label else null,
- if (alert && fix != null) blipBearing(s, fix.latitude, fix.longitude) else null
+ at?.let { com.rfsentinel.app.alpr.KnownCameras.bearingTo(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() },
+ at?.let { DeviceRegistry.metersBetween(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() },
+ now - s.lastSeen
)
} + radio)
}
@@ -939,20 +956,17 @@ class MainActivity : AppCompatActivity() {
}
/**
- * RTL-SDR / HackRF transmissions of the last minute on the radar, under the All and Radio filters: closer to the
- * centre the stronger the signal. One on the air right now at or above the alert threshold pulses, with its frequency.
- */
- /**
- * Compass bearing from you to an alerting device whose position is known: its own broadcast, or a
- * located estimate you are outside of (inside its circle every direction fits). Null otherwise.
+ * Where an alerting device is, for its direction on the radar: its own broadcast, or a located estimate
+ * you are outside of (inside its circle every direction fits). Null otherwise.
*/
- private fun blipBearing(s: DeviceRegistry.Snapshot, lat: Double, lon: Double): Float? {
- val at = s.broadcast?.let { it.lat to it.lon }
+ private fun knownPosition(s: DeviceRegistry.Snapshot, lat: Double, lon: Double): Pair<Double, Double>? =
+ s.broadcast?.let { it.lat to it.lon }
?: s.located?.takeIf { DeviceRegistry.metersBetween(lat, lon, it.lat, it.lon) > it.radiusM }?.let { it.lat to it.lon }
- ?: return null
- return com.rfsentinel.app.alpr.KnownCameras.bearingTo(lat, lon, at.first, at.second).toFloat()
- }
+ /**
+ * RTL-SDR / HackRF transmissions of the last minute on the radar, under the All and Radio filters: closer to the
+ * centre the stronger the signal. One on the air right now at or above the alert threshold pulses, with its frequency.
+ */
private fun radioBlips(now: Long, threshold: Int): List<RadarView.Blip> {
if ((filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.RADIO) ||
!ScanForegroundService.isRunning) return emptyList()
@@ -963,7 +977,7 @@ class MainActivity : AppCompatActivity() {
val alert = now - r.lastSeen <= RADIO_LIVE_MS && r.confidence >= threshold && !hidden(RADIO_ROW + r.freqHz, now)
// Signal above the noise as a stand-in RSSI: 40 dB lands in Near, 30 dB in Nearby (as the alert wording).
RadarView.Blip(RADIO_ROW + r.freqHz, (-115 + r.snrDb * 3 / 2).coerceIn(-100, -30), color, alert,
- if (alert) "${r.mhz} MHz" + (r.name?.let { " $it" } ?: "") else null)
+ if (alert) "${r.mhz} MHz" + (r.name?.let { " $it" } ?: "") else null, ageMs = now - r.lastSeen)
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/Compass.kt b/app/src/main/java/com/rfsentinel/app/ui/Compass.kt
new file mode 100644
index 0000000..3d4f0ed
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/Compass.kt
@@ -0,0 +1,146 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.hardware.GeomagneticField
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
+import android.view.Surface
+import android.view.WindowManager
+import kotlin.math.abs
+
+/**
+ * Which way the phone faces, in true compass degrees: the rotation-vector sensor (gyroscope, accelerometer and
+ * magnetometer fused by the phone), turned for the screen's rotation and, held upright, for the way the back camera
+ * looks. Magnetic north becomes true north with the declination at the last GPS fix ([setLocation]).
+ * Main thread: [start] when shown, [stop] when hidden.
+ */
+class Compass(context: Context) : SensorEventListener {
+ private val app = context.applicationContext
+ private val sm = app.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
+ private val sensor = sm?.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
+ private val m = FloatArray(9)
+ private val r = FloatArray(9)
+ private val o = FloatArray(3)
+ private var upright = false
+ private var declination = 0f
+ private var running = false
+
+ /** True compass degrees the phone faces, null without a compass or before its first reading. */
+ var degrees: Float? = null
+ private set
+ /** The magnetometer says it needs calibrating (wave the phone in a figure 8). */
+ var unreliable = false
+ private set
+ val available get() = sensor != null
+
+ fun start() {
+ if (running || sensor == null) return
+ running = sm?.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI) == true
+ }
+
+ fun stop() {
+ if (!running) return
+ sm?.unregisterListener(this)
+ running = false
+ degrees = null
+ }
+
+ fun setLocation(lat: Double, lon: Double, altitudeM: Double) {
+ declination = GeomagneticField(lat.toFloat(), lon.toFloat(), altitudeM.toFloat(), System.currentTimeMillis()).declination
+ }
+
+ override fun onSensorChanged(e: SensorEvent) {
+ SensorManager.getRotationMatrixFromVector(m, e.values)
+ // m[8]: how much the screen faces up. Upright (in a mount, held up to look ahead): the back camera's direction.
+ upright = abs(m[8]) < if (upright) 0.8f else 0.6f
+ @Suppress("DEPRECATION")
+ val rotation = (app.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.defaultDisplay?.rotation ?: Surface.ROTATION_0
+ val (x, y) = axes(rotation, upright)
+ SensorManager.remapCoordinateSystem(m, x, y, r)
+ SensorManager.getOrientation(r, o)
+ val now = HeadingFusion.norm(Math.toDegrees(o[0].toDouble()).toFloat() + declination)
+ // Light smoothing (the gyroscope already keeps it steady), the short way round through north.
+ degrees = degrees?.let { HeadingFusion.norm(it + SMOOTHING * HeadingFusion.diff(now, it)) } ?: now
+ }
+
+ override fun onAccuracyChanged(s: Sensor?, accuracy: Int) {
+ unreliable = accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE || accuracy == SensorManager.SENSOR_STATUS_ACCURACY_LOW
+ }
+
+ private fun axes(rotation: Int, upright: Boolean): Pair<Int, Int> {
+ val y = if (upright) SensorManager.AXIS_Z else SensorManager.AXIS_Y
+ val minusY = if (upright) SensorManager.AXIS_MINUS_Z else SensorManager.AXIS_MINUS_Y
+ return when (rotation) {
+ Surface.ROTATION_90 -> y to SensorManager.AXIS_MINUS_X
+ Surface.ROTATION_180 -> SensorManager.AXIS_MINUS_X to minusY
+ Surface.ROTATION_270 -> minusY to SensorManager.AXIS_X
+ else -> SensorManager.AXIS_X to y
+ }
+ }
+
+ private companion object { const val SMOOTHING = 0.3f }
+}
+
+/**
+ * The radar's heading-up: the phone's [Compass], set right by the GPS course while driving (a car's metal pulls
+ * the magnetometer off, and a phone in a cup holder faces anywhere). The difference between the two is learned at
+ * each fix at driving speed, so turns still show at once from the gyroscope. Without a compass: the GPS course
+ * while moving. Pure (unit-tested).
+ */
+class HeadingFusion {
+ private var compass: Float? = null
+ private var course: Float? = null
+ private var moving = false
+ private var offset: Float? = null
+ private var offsetAt = 0L
+ /** The compass when the GPS last set [offset]: a big turn since then while stopped means the phone was moved. */
+ private var anchor: Float? = null
+
+ fun compass(deg: Float?) {
+ compass = deg
+ val a = anchor
+ if (!moving && deg != null && a != null && abs(diff(deg, a)) > MOVED_DEG) { offset = null; anchor = null }
+ }
+
+ /** A GPS fix: [course] its bearing (null when it has none), [speed] in m/s. */
+ fun fix(now: Long, course: Float?, speed: Float) {
+ moving = course != null && speed >= if (moving) STOP_MS else MOVE_MS
+ this.course = course.takeIf { moving }
+ val c = compass
+ if (course != null && c != null && speed >= DRIVE_MS) {
+ val d = diff(course, c)
+ offset = offset?.let { norm180(it + GAIN * diff(d, it)) } ?: d
+ offsetAt = now
+ anchor = c
+ }
+ }
+
+ /** Compass degrees at the top of the radar, null for north-up. */
+ fun heading(now: Long): Float? {
+ val c = compass ?: return course
+ val o = offset?.takeIf { now - offsetAt <= HOLD_MS } ?: 0f
+ return norm(c + o)
+ }
+
+ /** The GPS course is setting the compass right (driving, or stopped a short while since). */
+ fun gpsSet(now: Long) = offset != null && now - offsetAt <= HOLD_MS
+
+ companion object {
+ /** GPS course counts from walking speed, and stops counting below [STOP_MS] (no flipping at the edge). */
+ const val MOVE_MS = 1.5f
+ const val STOP_MS = 1.0f
+ /** The GPS course sets the compass right from this speed up (about 15 km/h). */
+ const val DRIVE_MS = 4f
+ const val GAIN = 0.2f
+ /** Stopped (a red light) the correction holds this long, unless the phone turns [MOVED_DEG] on its own. */
+ const val HOLD_MS = 120_000L
+ const val MOVED_DEG = 45f
+
+ fun norm(d: Float) = (d % 360f + 360f) % 360f
+ private fun norm180(d: Float) = (norm(d) + 180f) % 360f - 180f
+ /** [a] - [b] the short way round, -180..180. */
+ fun diff(a: Float, b: Float) = norm180(a - b)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
index 5fe8062..90255da 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
@@ -3,10 +3,6 @@ package com.rfsentinel.app.ui
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PixelFormat
-import android.hardware.Sensor
-import android.hardware.SensorEvent
-import android.hardware.SensorEventListener
-import android.hardware.SensorManager
import android.media.AudioManager
import android.media.ToneGenerator
import android.os.Build
@@ -69,18 +65,11 @@ object LiveRead {
// ---- Sweep (main thread): compass heading + each new signal reading while locating ----
private val sweep = Sweep()
+ /** The way the phone faces (true north, flat or upright), shared with the radar. */
+ private var compass: Compass? = null
/** Compass degrees the phone faces, null without a compass or before its first reading. */
- @Volatile private var heading: Float? = null
+ private val heading get() = compass?.degrees
private var sweepFed = 0L
- private val compass = object : SensorEventListener {
- private val m = FloatArray(9); private val o = FloatArray(3)
- override fun onSensorChanged(e: SensorEvent) {
- SensorManager.getRotationMatrixFromVector(m, e.values)
- SensorManager.getOrientation(m, o)
- heading = ((Math.toDegrees(o[0].toDouble()) + 360) % 360).toFloat()
- }
- override fun onAccuracyChanged(s: Sensor?, a: Int) {}
- }
// ---- Pinpoint (the scan's pipeline thread) ----
private var pinMac: String? = null
@@ -98,9 +87,10 @@ object LiveRead {
locating = mac
followed = null
tone = runCatching { ToneGenerator(AudioManager.STREAM_MUSIC, 80) }.getOrNull()
- sweep.clear(); sweepFed = 0L; heading = null
- (context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager)?.let { sm ->
- sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)?.let { sm.registerListener(compass, it, SensorManager.SENSOR_DELAY_UI) }
+ sweep.clear(); sweepFed = 0L
+ compass = Compass(context).also { c ->
+ com.rfsentinel.app.service.ScanForegroundService.lastFix?.let { c.setLocation(it.latitude, it.longitude, it.altitude) }
+ c.start()
}
main.post(beep)
tick()
@@ -112,8 +102,7 @@ object LiveRead {
val was = locating != null
locating = null; followed = null
tone?.release(); tone = null
- (appContext?.getSystemService(Context.SENSOR_SERVICE) as? SensorManager)?.unregisterListener(compass)
- heading = null
+ compass?.stop(); compass = null
if (was) tick()
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt b/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
index efac4f1..dad37cd 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
@@ -4,12 +4,15 @@ import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
+import android.graphics.RectF
import android.graphics.SweepGradient
+import android.location.Location
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.google.android.material.color.MaterialColors
import com.rfsentinel.app.R
+import com.rfsentinel.app.detect.DeviceIntel
import kotlin.math.cos
import kotlin.math.hypot
import kotlin.math.min
@@ -21,21 +24,39 @@ import kotlin.math.sin
* derived from the address so blips don't jump around - a single phone
* antenna cannot measure direction, and the view says so. An alert whose
* position is known ([Blip.bearing]) plots in its real direction instead,
- * with a line from you.
+ * with a line from you and its distance. Heading-up from the phone's compass
+ * (set right by the GPS course while driving, [HeadingFusion]), else north-up.
*/
class RadarView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {
- /** [bearing]: compass degrees from you to the device, when its position is known. */
+ /** [bearing]: compass degrees from you to the device and [distanceM] how far, when its position is known.
+ * [ageMs]: since it was last heard (the blip fades). */
data class Blip(val mac: String, val rssi: Int, val color: Int, val flagged: Boolean, val label: String?,
- val bearing: Float? = null)
+ val bearing: Float? = null, val distanceM: Float? = null, val ageMs: Long = 0L)
- var onBlipClick: ((String) -> Unit)? = null
- /** Your course in compass degrees for heading-up; null is north-up. */
- var heading: Float? = null
+ var onBlipClick: ((Blip) -> Unit)? = null
+ /** Pinpoint is off in Settings: located alerts can't show, and the footer says how to turn it on. */
+ var pinpointOff = false
+
+ /** Drawing order (ordinary first, flagged on top) with each blip's label lines, built once per [setBlips]. */
+ private class Item(val b: Blip, val title: String?, val detail: String?)
+ private var items: List<Item> = emptyList()
+ /** Flagged ones with a label, strongest first: the closest keeps its label when two would overlap. */
+ private var labelled: List<Item> = emptyList()
+ private var xs = FloatArray(0)
+ private var ys = FloatArray(0)
+ private val placed = ArrayList<RectF>()
+ private var directional = false
+ private var unplaced = false
+
+ private val compass = Compass(context)
+ private val fusion = HeadingFusion()
+ private var fixTime = 0L
+ /** Compass degrees at the top, null for north-up. */
+ private var heading: Float? = null
- private var blips: List<Blip> = emptyList()
private var sweep = 0f
private val density = resources.displayMetrics.density
private val scope = MaterialColors.getColor(context, R.attr.rfScopeColor, 0xFF0B5C63.toInt())
@@ -56,6 +77,13 @@ class RadarView @JvmOverloads constructor(
textSize = 11f * density
isFakeBoldText = true
}
+ private val detailPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textSize = 10f * density }
+ private val northPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = 12f * density
+ isFakeBoldText = true
+ textAlign = Paint.Align.CENTER
+ color = scopeText
+ }
private val blipPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val pulsePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 2f * density }
private val sweepPaint = Paint(Paint.ANTI_ALIAS_FLAG)
@@ -65,20 +93,51 @@ class RadarView @JvmOverloads constructor(
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
- val (cx, cy) = center()
sweepPaint.shader = SweepGradient(
- cx, cy, intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, sweepColor), floatArrayOf(0f, 0.75f, 1f)
+ cx(), cy(), intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, sweepColor), floatArrayOf(0f, 0.75f, 1f)
)
}
+ // The compass runs only while the radar is on screen.
+ override fun onVisibilityAggregated(isVisible: Boolean) {
+ super.onVisibilityAggregated(isVisible)
+ if (isVisible) compass.start() else compass.stop()
+ }
+
+ override fun onDetachedFromWindow() {
+ compass.stop()
+ super.onDetachedFromWindow()
+ }
+
fun ordinaryColor() = ordinaryColor
fun setBlips(list: List<Blip>) {
- blips = list
+ items = list.sortedBy { it.flagged }.map { b ->
+ val title = b.label?.take(22)
+ Item(b, title, if (b.flagged && b.distanceM != null && b.bearing != null)
+ DeviceIntel.formatDistance(b.distanceM.toDouble()) + " " + Sweep.compassPoint(b.bearing) else null)
+ }
+ labelled = items.filter { it.b.flagged && it.title != null }.sortedByDescending { it.b.rssi }
+ if (xs.size < items.size) { xs = FloatArray(items.size); ys = FloatArray(items.size) }
+ directional = list.any { it.bearing != null }
+ unplaced = list.any { it.flagged && it.bearing == null }
+ val alerts = list.count { it.flagged }
+ contentDescription = "Radar: ${list.size} devices, $alerts alerts" + labelled.filter { it.detail != null }
+ .joinToString("") { ", ${it.title} ${it.detail}" }
invalidate()
}
- private fun center() = Pair(width / 2f, (height - 28 * density) / 2f)
+ /** The latest GPS fix: the course while driving and true north for the compass. */
+ fun setFix(fix: Location?) {
+ if (fix == null || fix.time == fixTime) return
+ fixTime = fix.time
+ compass.setLocation(fix.latitude, fix.longitude, fix.altitude)
+ val course = fix.bearing.takeIf { fix.hasBearing() && (!fix.hasBearingAccuracy() || fix.bearingAccuracyDegrees <= 30f) }
+ fusion.fix(System.currentTimeMillis(), course, if (fix.hasSpeed()) fix.speed else 0f)
+ }
+
+ private fun cx() = width / 2f
+ private fun cy() = (height - 28 * density) / 2f
private fun radius() = min(width, (height - 28 * density).toInt()) / 2f - 8 * density
/** Maps RSSI (-30 strong ... -100 weak) to 0.08..0.96 of the radius. */
@@ -93,18 +152,31 @@ class RadarView @JvmOverloads constructor(
/** Screen angle (0 = right, clockwise) of a compass bearing, with up = [heading] or north. */
private fun screenAngle(bearing: Float) = Math.toRadians((bearing - (heading ?: 0f) - 90f).toDouble())
- private fun position(b: Blip): Pair<Float, Float> {
- val (cx, cy) = center()
- val r = radius() * rssiToFraction(b.rssi)
- val a = b.bearing?.let { screenAngle(it) } ?: angleOf(b.mac)
- return Pair(cx + (r * cos(a)).toFloat(), cy + (r * sin(a)).toFloat())
+ /** Where each blip goes now, into [xs] / [ys] (the heading turns the located ones). */
+ private fun place() {
+ val cx = cx(); val cy = cy(); val rad = radius()
+ for ((i, it) in items.withIndex()) {
+ val r = rad * rssiToFraction(it.b.rssi)
+ val a = it.b.bearing?.let { screenAngle(it) } ?: angleOf(it.b.mac)
+ xs[i] = cx + (r * cos(a)).toFloat()
+ ys[i] = cy + (r * sin(a)).toFloat()
+ }
+ }
+
+ /** Full until 5 s unheard, down to a third at a minute. */
+ private fun fade(c: Int, ageMs: Long): Int {
+ val f = 1f - 0.65f * ((ageMs - 5_000L).coerceIn(0L, 55_000L) / 55_000f)
+ return alpha(c, ((c ushr 24) * f).toInt())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
- val (cx, cy) = center()
+ val cx = cx(); val cy = cy()
val rad = radius()
if (rad <= 0) return
+ val now = System.currentTimeMillis()
+ fusion.compass(compass.degrees)
+ heading = fusion.heading(now)
// Signal bands: Near (>= -60), Nearby (>= -80), Far.
val near = rad * rssiToFraction(-60)
@@ -114,9 +186,9 @@ class RadarView @JvmOverloads constructor(
canvas.drawCircle(cx, cy, rad, ringPaint)
canvas.drawLine(cx - rad, cy, cx + rad, cy, ringPaint)
canvas.drawLine(cx, cy - rad, cx, cy + rad, ringPaint)
- canvas.drawText("Near", cx + 4 * density, cy - near + 12 * density, textPaint)
- canvas.drawText("Nearby", cx + 4 * density, cy - nearby + 12 * density, textPaint)
- canvas.drawText("Far", cx + 4 * density, cy - rad + 12 * density, textPaint)
+ canvas.drawText("Near", cx + 8 * density, cy - near + 12 * density, textPaint)
+ canvas.drawText("Nearby", cx + 8 * density, cy - nearby + 12 * density, textPaint)
+ canvas.drawText("Far", cx + 8 * density, cy - rad + 12 * density, textPaint)
// Sweep.
canvas.save()
@@ -124,59 +196,99 @@ class RadarView @JvmOverloads constructor(
canvas.drawCircle(cx, cy, rad, sweepPaint)
canvas.restore()
- val directional = blips.any { it.bearing != null }
- if (directional) {
- val n = screenAngle(0f)
- canvas.drawText("N", cx + ((rad - 10 * density) * cos(n)).toFloat() - 4 * density,
- cy + ((rad - 10 * density) * sin(n)).toFloat() + 4 * density, labelPaint.apply { color = scopeText })
- }
+ // North on the outer ring (it turns with the heading), and which way the radar is turned.
+ val n = screenAngle(0f)
+ canvas.drawText("N", cx + ((rad - 12 * density) * cos(n)).toFloat(),
+ cy + ((rad - 12 * density) * sin(n)).toFloat() + 4 * density, northPaint)
+ canvas.drawText(if (heading != null) "Heading up" else "North up", 8 * density, 14 * density, textPaint)
- val t = (System.currentTimeMillis() % 1000L) / 1000f
+ val t = (now % 1000L) / 1000f
+ place()
// Ordinary devices first so flagged ones draw on top.
- for (b in blips.sortedBy { it.flagged }) {
- val (x, y) = position(b)
- blipPaint.color = b.color
+ for ((i, it) in items.withIndex()) {
+ val b = it.b
+ val x = xs[i]; val y = ys[i]
+ val color = fade(b.color, b.ageMs)
+ blipPaint.color = color
if (b.bearing != null) {
- pulsePaint.color = alpha(b.color, 0x99)
+ pulsePaint.color = fade(alpha(b.color, 0x99), b.ageMs)
canvas.drawLine(cx, cy, x, y, pulsePaint)
}
if (b.flagged) {
- pulsePaint.color = (b.color and 0x00FFFFFF) or (((1f - t) * 200).toInt() shl 24)
+ pulsePaint.color = alpha(color, ((1f - t) * 200 * (color ushr 24) / 255).toInt())
canvas.drawCircle(x, y, (7 + 14 * t) * density, pulsePaint)
canvas.drawCircle(x, y, 7 * density, blipPaint)
- b.label?.let {
- labelPaint.color = b.color
- canvas.drawText(it.take(22), x + 10 * density, y + 4 * density, labelPaint)
- }
} else {
canvas.drawCircle(x, y, 4 * density, blipPaint)
}
}
canvas.drawCircle(cx, cy, 5 * density, youPaint)
+ drawLabels(canvas)
- canvas.drawText(
- if (directional) "Closer = stronger signal · lines point to located alerts"
- else "Closer to centre = stronger signal · angle is not direction",
- 8 * density, height - 8 * density, textPaint
- )
+ val footer = footer(width - 16 * density, now)
+ canvas.drawText(footer, 8 * density, height - 8 * density, textPaint)
sweep = (sweep + 2.4f) % 360f
if (isShown) postInvalidateOnAnimation()
}
+ /** Alert names (and distance + direction when located) beside their blip, flipped left near the right edge;
+ * one that would overlap a label already drawn is left out (tap the blip for it). */
+ private fun drawLabels(canvas: Canvas) {
+ var used = 0
+ val edge = 4 * density
+ for (it in labelled) {
+ val i = items.indexOf(it)
+ val x = xs[i]; val y = ys[i]
+ val title = it.title ?: continue
+ val w = maxOf(labelPaint.measureText(title), it.detail?.let { d -> detailPaint.measureText(d) } ?: 0f)
+ val gap = 10 * density
+ var lx = if (x + gap + w > width - edge) x - gap - w else x + gap
+ lx = lx.coerceIn(edge, (width - edge - w).coerceAtLeast(edge))
+ if (used == placed.size) placed += RectF()
+ val box = placed[used]
+ box.set(lx, y - 9 * density, lx + w, y + (if (it.detail != null) 15 else 4) * density)
+ if ((0 until used).any { j -> RectF.intersects(placed[j], box) }) continue
+ used++
+ val color = fade(it.b.color, it.b.ageMs)
+ labelPaint.color = color
+ canvas.drawText(title, lx, y + 4 * density, labelPaint)
+ it.detail?.let { d ->
+ detailPaint.color = color
+ canvas.drawText(d, lx, y + 15 * density, detailPaint)
+ }
+ }
+ }
+
+ /** The hint under the radar, the long form when it fits the width, else the short one. */
+ private fun footer(room: Float, now: Long): String {
+ fun pick(long: String, short: String) = if (textPaint.measureText(long) <= room) long else short
+ return when {
+ directional && heading != null && compass.unreliable && !fusion.gpsSet(now) ->
+ pick("Compass needs calibrating: wave the phone in a figure 8", "Calibrate: wave phone in a figure 8")
+ pinpointOff && unplaced -> pick("Pinpoint is off: Settings › Location shows where alerts are", "Pinpoint off: Settings › Location")
+ directional -> pick("Closer = stronger signal · lines point to located alerts", "Lines point to located alerts")
+ else -> pick("Closer to centre = stronger signal · angle is not direction", "Closer = stronger · angle isn't direction")
+ }
+ }
+
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) return true
if (event.action == MotionEvent.ACTION_UP) {
- val hit = blips.minByOrNull { b ->
- val (x, y) = position(b)
- hypot(x - event.x, y - event.y)
+ place()
+ // Within reach, an alert beats an ordinary device next to it; then the nearest.
+ val reach = 28 * density
+ var hit = -1; var hitD = 0f
+ for (i in items.indices) {
+ val d = hypot(xs[i] - event.x, ys[i] - event.y)
+ if (d > reach) continue
+ val better = hit < 0 || (items[i].b.flagged && !items[hit].b.flagged) ||
+ (items[i].b.flagged == items[hit].b.flagged && d < hitD)
+ if (better) { hit = i; hitD = d }
}
- if (hit != null) {
- val (x, y) = position(hit)
- if (hypot(x - event.x, y - event.y) <= 28 * density) {
- performClick()
- onBlipClick?.invoke(hit.mac)
- }
+ if (hit >= 0) {
+ performClick()
+ onBlipClick?.invoke(items[hit].b)
}
return true
}
diff --git a/app/src/test/java/com/rfsentinel/app/ui/HeadingFusionTest.kt b/app/src/test/java/com/rfsentinel/app/ui/HeadingFusionTest.kt
new file mode 100644
index 0000000..e210e53
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/HeadingFusionTest.kt
@@ -0,0 +1,60 @@
+package com.rfsentinel.app.ui
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class HeadingFusionTest {
+
+ @Test
+ fun compassAloneOrNorthUp() {
+ val h = HeadingFusion()
+ assertNull(h.heading(0L)) // no compass, not moving: north-up
+ h.compass(123f)
+ assertEquals(123f, h.heading(0L)!!, 0.01f)
+ }
+
+ @Test
+ fun withoutCompassTheCourseCountsWhileMoving() {
+ val h = HeadingFusion()
+ h.fix(0L, 200f, 1.2f)
+ assertNull(h.heading(0L)) // below walking speed
+ h.fix(1_000L, 200f, 1.6f)
+ assertEquals(200f, h.heading(1_000L)!!, 0.01f)
+ h.fix(2_000L, 210f, 1.2f)
+ assertEquals(210f, h.heading(2_000L)!!, 0.01f) // still moving: no flipping at the edge
+ h.fix(3_000L, 210f, 0.8f)
+ assertNull(h.heading(3_000L))
+ }
+
+ @Test
+ fun drivingSetsTheCompassRightAndTurnsShowAtOnce() {
+ val h = HeadingFusion()
+ h.compass(80f) // the car's metal pulls it 20° off
+ h.fix(0L, 100f, 12f)
+ assertTrue(h.gpsSet(0L))
+ assertEquals(100f, h.heading(0L)!!, 0.01f)
+ h.compass(110f) // turning, between two fixes
+ assertEquals(130f, h.heading(500L)!!, 0.01f)
+ // Across north: 350° + 20° is 10°, not 370°.
+ h.compass(350f); h.fix(1_000L, 10f, 12f)
+ assertEquals(10f, h.heading(1_000L)!!, 0.5f)
+ }
+
+ @Test
+ fun stoppedTheCorrectionHoldsUntilThePhoneIsMovedOrItIsOld() {
+ val h = HeadingFusion()
+ h.compass(80f); h.fix(0L, 100f, 12f)
+ h.fix(1_000L, null, 0f) // a red light
+ h.compass(90f)
+ assertEquals(110f, h.heading(60_000L)!!, 0.01f)
+ assertFalse(h.gpsSet(HeadingFusion.HOLD_MS + 1_000L))
+ assertEquals(90f, h.heading(HeadingFusion.HOLD_MS + 1_000L)!!, 0.01f)
+ val moved = HeadingFusion()
+ moved.compass(80f); moved.fix(0L, 100f, 12f); moved.fix(1_000L, null, 0f)
+ moved.compass(200f) // taken out of the mount
+ assertEquals(200f, moved.heading(2_000L)!!, 0.01f)
+ }
+}