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.

Locate chest sweep locks a direction (radar shows it), Settings › Radar, alert volume choice, pull-down refreshes everything, WiFi bands for USB adapters only

CIS-C011f83b2a94d0
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index b405e57..983c019 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -169,13 +169,8 @@ class MainActivity : AppCompatActivity() {
if (!rv.canScrollVertically(-1)) showNewAlertPill(false)
}
})
- binding.wazeSwipe.setColorSchemeColors(com.rfsentinel.app.ui.ChipStyle.accent(this).first)
- binding.wazeSwipe.setOnRefreshListener {
- if (com.rfsentinel.app.ui.WazeUi.checkNow(this)) {
- refreshAskedAt = System.currentTimeMillis()
- binding.wazeSwipe.postDelayed({ binding.wazeSwipe.isRefreshing = false }, 12_000) // never spin for ever
- } else binding.wazeSwipe.isRefreshing = false
- }
+ binding.refreshSwipe.setColorSchemeColors(com.rfsentinel.app.ui.ChipStyle.accent(this).first)
+ binding.refreshSwipe.setOnRefreshListener { refreshAll() }
// 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
@@ -700,7 +695,7 @@ class MainActivity : AppCompatActivity() {
runOnUiThread {
if (!lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) return@runOnUiThread
// The answer to a pull-down check ends the spinner.
- if (binding.wazeSwipe.isRefreshing && com.rfsentinel.app.online.WazePolice.latestAt >= refreshAskedAt) binding.wazeSwipe.isRefreshing = false
+ if (binding.refreshSwipe.isRefreshing && com.rfsentinel.app.online.WazePolice.latestAt >= refreshAskedAt) binding.refreshSwipe.isRefreshing = false
render()
}
}
@@ -731,7 +726,7 @@ class MainActivity : AppCompatActivity() {
// Devices swiped left ([hideRow]) are listed as ordinary ones (no flag, banner or radar alert). Waze, aircraft, radio: see their rows.
val all = if (hiddenRows.isEmpty()) live else live.map { if (hidden(it.mac, now)) it.copy(hits = emptyList(), following = false) else it }
val threshold = Prefs.alertThreshold(this)
- binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && panes.listShown
+ binding.refreshSwipe.isEnabled = panes.listShown
deviceCount = all.size
adapter.visual = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.DEVICE_LIST)
// The banner and radar alert only for flagged devices still in range.
@@ -787,12 +782,14 @@ 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
+ // The device being located, once a chest sweep found its side.
+ val swept = if (at == null) com.rfsentinel.app.ui.LiveRead.sweptBearing(s.mac) else null
RadarView.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() },
+ at?.let { com.rfsentinel.app.alpr.KnownCameras.bearingTo(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() } ?: swept,
at?.let { DeviceRegistry.metersBetween(fix!!.latitude, fix.longitude, it.first, it.second).toFloat() },
now - s.lastSeen
)
@@ -871,6 +868,26 @@ class MainActivity : AppCompatActivity() {
/** When the list was last pulled down to check Waze. */
private var refreshAskedAt = 0L
+ /**
+ * The list's pull-down: WiFi scan, cell check and Waze check (when on) all at once, then the list redraws.
+ * The spinner stops when Waze answers, else after a WiFi scan's time.
+ */
+ private fun refreshAll() {
+ val swipe = binding.refreshSwipe
+ if (!ScanForegroundService.isRunning) {
+ android.widget.Toast.makeText(this, "Start scanning first", android.widget.Toast.LENGTH_SHORT).show()
+ swipe.isRefreshing = false
+ return
+ }
+ ScanForegroundService.rescan(this)
+ refreshAskedAt = System.currentTimeMillis()
+ val waze = com.rfsentinel.app.online.WazePolice
+ val wazeAsked = com.rfsentinel.app.ui.WazeUi.on(this) && waze.running && !Prefs.wazePaused(this) &&
+ waze.requestCheckNow(com.rfsentinel.app.online.WazeTiming.minGapS(Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT)) == null
+ swipe.postDelayed({ swipe.isRefreshing = false; render() }, if (wazeAsked) 12_000L else 4_000L) // never spin for ever
+ render()
+ }
+
/**
* The Waze reports inside the alert range (Settings > Waze), kept live by the checker: distance, direction
* and score follow you as you drive. The map still shows the wider view range.
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 3ab6d0f..54fe8f0 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -92,6 +92,7 @@ class ScanForegroundService : Service() {
const val ACTION_REFRESH_LOCATION = "com.rfsentinel.app.action.REFRESH_LOCATION"
/** Re-applies Sentinel Link (joined, left, sharing switched) to a running scan. */
const val ACTION_REFRESH_LINK = "com.rfsentinel.app.action.REFRESH_LINK"
+ const val ACTION_RESCAN = "com.rfsentinel.app.action.RESCAN"
/** Android downgrades an unfiltered BLE scan to opportunistic after ~30 min; restart before. */
private const val BLE_RESTART_INTERVAL_MS = 25 * 60 * 1000L
@@ -186,6 +187,12 @@ class ScanForegroundService : Service() {
context.stopService(Intent(context, ScanForegroundService::class.java))
}
+ /** The list's pull-down: a running scan scans WiFi and checks the cells right now (never starts a scan). */
+ fun rescan(context: Context) {
+ if (!isRunning) return
+ runCatching { context.startService(Intent(context, ScanForegroundService::class.java).setAction(ACTION_RESCAN)) }
+ }
+
/** Sentinel Link changed: a running scan starts or stops linking (never starts a scan). */
fun refreshLink(context: Context) {
if (!isRunning) return
@@ -348,6 +355,13 @@ class ScanForegroundService : Service() {
updateLocationUpdates()
return START_STICKY
}
+ if (intent?.action == ACTION_RESCAN) {
+ if (!isRunning) { stopSelf(); return START_NOT_STICKY }
+ // Bluetooth and the external boards report all the time; WiFi and the cells are polled.
+ if (wifiPollJob?.isActive == true) wifiEngine.requestScan()
+ if (cellJob?.isActive == true) startCellChecks()
+ return START_STICKY
+ }
if (intent?.action == ACTION_REFRESH_LINK) {
if (!isRunning) { stopSelf(); return START_NOT_STICKY }
updateLink()
@@ -1723,7 +1737,8 @@ class ScanForegroundService : Service() {
while (isActive) {
val ctx = this@ScanForegroundService
val now = System.currentTimeMillis()
- val target = if (!Prefs.radarBeep(ctx)) null else lastAlerted.entries
+ // Silent while Locate beeps, so the two never play over each other.
+ val target = if (!Prefs.radarBeep(ctx) || com.rfsentinel.app.ui.LiveRead.locating != null) null else lastAlerted.entries
.filter { now - it.value in RADAR_QUIET_MS..RADAR_HOLD_MS && !WhitelistCache.contains(it.key) &&
!com.rfsentinel.app.data.AlertMutes.isMuted(ctx, it.key, now) }
.mapNotNull { DeviceRegistry.get(it.key) }
diff --git a/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
index cad7488..412a5fc 100644
--- a/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
@@ -36,9 +36,8 @@ class WifiScanEngine(
// current position and could fake a device following you.
try {
val nowUs = SystemClock.elapsedRealtime() * 1000
- val band = com.rfsentinel.app.util.Prefs.wifiBand(context)
- val fresh = wifiManager.scanResults.filter { nowUs - it.timestamp <= MAX_RESULT_AGE_US &&
- (band == com.rfsentinel.app.util.Prefs.WifiBand.ALL || (band == com.rfsentinel.app.util.Prefs.WifiBand.HIGH) == (it.frequency > 3000)) }
+ // Every band, always: the WiFi bands setting is for external adapters only.
+ val fresh = wifiManager.scanResults.filter { nowUs - it.timestamp <= MAX_RESULT_AGE_US }
if (fresh.isNotEmpty()) onResults(fresh)
} catch (e: SecurityException) {
// Missing location permission - caller should have requested it already.
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 1ed802f..f1c261c 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -551,6 +551,14 @@ class SettingsActivity : AppCompatActivity() {
"Not included: live traffic (the arrival time starts from the route's usual driving time and then follows how you really " +
"drive), speed limits and offline routes.\n\n" +
"Home, Work, starred and recent places are kept on this phone only."),
+ Section("radar", binding.headerRadar, binding.sectionRadar,
+ "The radar on the main screen: closer to the centre = stronger signal.\n\n" +
+ "Top of the radar: the way you face (it turns with the phone, from the compass, set right by the GPS while you " +
+ "drive) or north.\n\n" +
+ "Dots without a direction: a phone can't tell which way a signal comes from, so most dots sit at a made-up " +
+ "angle. They can stay put on screen, or turn with north like the dots whose direction is known.\n\n" +
+ "Directions on the radar: alerts that broadcast their position or were pinpointed, and the device you " +
+ "locate once a turn with the phone on your chest has found its side."),
Section("map", binding.headerMap, binding.sectionMap,
"What the map shows.\n\n" +
"Plate, speed and red-light cameras: from OpenStreetMap (Known cameras has the downloads, warnings and CCTV).\n\n" +
@@ -890,7 +898,7 @@ class SettingsActivity : AppCompatActivity() {
info(binding.rotationLabel, "Normal follows the phone's auto-rotate.\n\nAuto-rotate, upside down too: also turns upside down, which phones like the Pixel never do on their own.\n\nAlways upside down: the USB-C port at the top, for an antenna or adapter plugged in.")
info(binding.bannerLabel, "A picture across the header of the styled themes (a logo or artwork you own). Your custom themes have their own banner, set in the theme maker.")
info(binding.hideTrustedSwitch, "Devices on your whitelist are left off the list and radar.")
- info(binding.wifiBandLabel, "Which WiFi networks and devices are listed. On a USB WiFi adapter it also sets the channels it hops: 5 and 6 GHz only gives those channels more listening time (police in-car networks are usually on 5 GHz). Adapters that only do 2.4 GHz keep scanning 2.4 GHz.\n\nThe phone's own WiFi scan always covers every band; the others are only left out of the list. A USB adapter picks up a change when it next starts.")
+ info(binding.wifiBandLabel, "The channels a USB WiFi adapter hops. 5 and 6 GHz only gives those channels more listening time (police in-car networks are usually on 5 GHz). Adapters that only do 2.4 GHz keep scanning 2.4 GHz.\n\nThe phone's own WiFi always shows every band. An adapter picks up a change when it next starts.")
info(binding.scanModeLabel, "Maximum finds devices fastest and uses the most battery. Battery saver notices them later.")
info(binding.intervalLabel, "How often WiFi is scanned. Android allows an app 4 scans in 2 minutes unless WiFi scan throttling is turned off in Developer options.")
withUnit(binding.intervalInput, "s")
@@ -902,6 +910,12 @@ class SettingsActivity : AppCompatActivity() {
"Probable and Strong only don't alert on a vehicle router (Cradlepoint, Sierra Wireless) you hear day after day, " +
"like one in a shop, unless something else backs it. Weak alerts on all of them.")
binding.thresholdMedium.text = tagged("Probable", "recommended")
+ info(binding.alertVolumeLabel, "Which volume the alert sounds, Locate beeps and the alert voice follow on the phone. " +
+ "Navigation is the volume Maps' directions use (on most phones the media volume), and music dips under it. " +
+ "Alarm is often the loudest.\n\nSilent, vibrate and Do Not Disturb still mute alerts. In the car they always " +
+ "play through the car's speakers.")
+ info(binding.radarTopLabel, "The way you face: the radar turns with the phone, like a compass, so N moves. North: N stays at the top.")
+ info(binding.radarDotsLabel, "Most dots have no real direction (one antenna can't tell). Stay in place keeps them still; turn with north moves them with the compass.")
info(binding.radarBeepSwitch, "Beeps faster as a flagged device gets closer, like a radar detector.")
info(binding.detectorSoundSwitch, "Alerts use radar-detector tones (Ka, K and X) and say \"GPS connected\" when the first GPS fix comes in.")
info(binding.gpsVoiceSwitch, "With the radar-detector sound: says \"GPS connected\" when the GPS locks, and again when it comes back after losing the fix.")
@@ -956,6 +970,10 @@ class SettingsActivity : AppCompatActivity() {
* Shows or hides a setting for the app's own reasons (a switch turned off, nothing to say...). It
* also takes the setting off the search's list, so clearing the search leaves it the way this set it.
*/
+ /** Radio buttons listed in the order of the choices they stand for. */
+ private fun android.widget.RadioGroup.checkIndex(i: Int) = check(getChildAt(i).id)
+ private val android.widget.RadioGroup.checkedIndex get() = indexOfChild(findViewById(checkedRadioButtonId))
+
private fun View.shownIf(on: Boolean) {
setTag(R.id.search_hidden, null)
visibility = if (on) View.VISIBLE else View.GONE
@@ -2411,6 +2429,16 @@ class SettingsActivity : AppCompatActivity() {
}
)
binding.soundSwitch.isChecked = Prefs.soundEnabled(this)
+ binding.alertVolumeGroup.checkIndex(Prefs.alertVolume(this).ordinal)
+ // Each choice plays the alert sound at that volume.
+ binding.alertVolumeGroup.setOnCheckedChangeListener { g, _ ->
+ Prefs.setAlertVolume(this, Prefs.AlertVolume.entries[g.checkedIndex.coerceAtLeast(0)])
+ com.rfsentinel.app.util.AlertPlayer.previewEffect(this, Prefs.detectorEffect(this))
+ }
+ binding.radarTopGroup.checkIndex(if (Prefs.radarNorthUp(this)) 1 else 0)
+ binding.radarDotsGroup.checkIndex(if (Prefs.radarSpinDots(this)) 1 else 0)
+ binding.radarNamesSwitch.isChecked = Prefs.radarNames(this)
+ binding.radarSweepSwitch.isChecked = Prefs.radarSweepLine(this)
binding.vibrateSwitch.isChecked = Prefs.vibrateEnabled(this)
setupSnoozeLength()
binding.radarBeepSwitch.isChecked = Prefs.radarBeep(this)
@@ -2764,6 +2792,10 @@ class SettingsActivity : AppCompatActivity() {
}
)
Prefs.setSoundEnabled(this, binding.soundSwitch.isChecked)
+ Prefs.setRadarNorthUp(this, binding.radarTopGroup.checkedIndex == 1)
+ Prefs.setRadarSpinDots(this, binding.radarDotsGroup.checkedIndex == 1)
+ Prefs.setRadarNames(this, binding.radarNamesSwitch.isChecked)
+ Prefs.setRadarSweepLine(this, binding.radarSweepSwitch.isChecked)
Prefs.setRadarBeep(this, binding.radarBeepSwitch.isChecked)
Prefs.setDetectorSound(this, binding.detectorSoundSwitch.isChecked)
Prefs.setStartupSweep(this, binding.startupSweepSwitch.isChecked)
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 90255da..b174ec1 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
@@ -3,8 +3,6 @@ package com.rfsentinel.app.ui
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PixelFormat
-import android.media.AudioManager
-import android.media.ToneGenerator
import android.os.Build
import android.os.Handler
import android.os.Looper
@@ -43,6 +41,9 @@ object LiveRead {
)
private const val TICK_MS = 1_000L
+ private const val SAMPLE_MS = 200L
+ /** Walked this far since the lock: the direction is old, sweep again. */
+ const val SWEEP_STALE_M = 25f
/** Heard within this: its signal is live. */
private const val HEARD_MS = 10_000L
/** A pinpointed device unheard this long gives way to another flagged one. */
@@ -60,7 +61,6 @@ object LiveRead {
private set
/** The address it is heard under now (it changes when the device rotates its address). */
private var followed: String? = null
- private var tone: ToneGenerator? = null
private var appContext: Context? = null
// ---- Sweep (main thread): compass heading + each new signal reading while locating ----
@@ -68,8 +68,15 @@ object LiveRead {
/** 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. */
- private val heading get() = compass?.degrees
+ val heading get() = compass?.degrees
private var sweepFed = 0L
+ /** The direction the sweep locked on (kept until Sweep again or Locate stops), and where you stood then. */
+ private var lock: Sweep.Estimate? = null
+ private var lockedAt: android.location.Location? = null
+
+ /** The sweep as the Locate guide draws it. [moved]: metres walked since it locked. */
+ class SweepState(val heading: Float?, val sectors: Array<Float?>, val covered: Int,
+ val estimate: Sweep.Estimate?, val locked: Sweep.Estimate?, val moved: Float?)
// ---- Pinpoint (the scan's pipeline thread) ----
private var pinMac: String? = null
@@ -86,22 +93,42 @@ object LiveRead {
appContext = context.applicationContext
locating = mac
followed = null
- tone = runCatching { ToneGenerator(AudioManager.STREAM_MUSIC, 80) }.getOrNull()
- sweep.clear(); sweepFed = 0L
+ sweep.clear(); sweepFed = 0L; lock = null; lockedAt = null
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)
+ main.post(sample)
tick()
}
+ /** Forgets the sweep and its lock, for a fresh turn (somewhere new, or a lock that looks wrong). Main thread. */
+ fun sweepAgain() {
+ sweep.clear(); sweepFed = 0L; lock = null; lockedAt = null
+ tick()
+ }
+
+ /** 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)
+ }
+
+ /** 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 null
+ val m = locating ?: return null
+ return l.bearing.takeIf { mac == m || mac == followed }
+ }
+
/** Main thread. */
fun stopLocate() {
main.removeCallbacks(beep)
+ main.removeCallbacks(sample)
val was = locating != null
locating = null; followed = null
- tone?.release(); tone = null
compass?.stop(); compass = null
if (was) tick()
}
@@ -118,14 +145,34 @@ object LiveRead {
}
// Out of range (gone from the list): Locate ends, as on the device screen.
val s = DeviceRegistry.get(liveMac) ?: DeviceRegistry.get(mac) ?: run { stopLocate(); return }
- // Each new reading, with the way the phone faces now (a slow turn barely moves between the two).
- heading?.let { h -> if (s.lastSeen != sweepFed) { sweepFed = s.lastSeen; sweep.add(s.lastSeen, h, s.rssi) } }
- if (!AlertPlayer.locateTick(ctx)) tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)
+ AlertPlayer.locateTick(ctx)
// Faster as the signal gets stronger (same curve as the radar beeps).
main.postDelayed(this, Beeper.tickIntervalMs(s.rssi))
}
}
+ /**
+ * Five times a second: each new signal reading with the way the phone faces now (a slow turn barely moves
+ * between the two). Locks the direction once the turn makes it clear, with a short buzz.
+ */
+ private val sample = object : Runnable {
+ override fun run() {
+ val mac = locating ?: return
+ main.postDelayed(this, SAMPLE_MS)
+ val h = heading ?: return
+ val s = DeviceRegistry.get(followed ?: mac) ?: return
+ if (s.lastSeen == sweepFed) return
+ sweepFed = s.lastSeen
+ sweep.add(s.lastSeen, h, s.rssi)
+ if (lock != null) return
+ val e = sweep.estimate(s.lastSeen)?.takeIf { Sweep.locks(it) } ?: return
+ lock = e
+ lockedAt = com.rfsentinel.app.service.ScanForegroundService.lastFix
+ appContext?.let { AlertPlayer.vibrate(it, longArrayOf(0, 60, 90, 60)) }
+ tick()
+ }
+ }
+
/**
* A flagged device was heard while pinpointing is on (any thread): it becomes the one read, unless the one
* already read was heard in the last [PINPOINT_SWITCH_MS]. [until]: when pinpointing ends unless heard again.
@@ -181,17 +228,20 @@ object LiveRead {
)
}
- /** The sweep's hint while locating: how to turn, then the direction. Null without a compass. Main thread. */
+ /** 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 dir = sweep.direction(now) ?: return "Sweep: phone flat in front of you, turn slowly " +
- "(${sweep.covered(now) * 360 / Sweep.SECTORS}° of 360°)"
- val turn = Sweep.turn(h, dir)
- return "Strongest facing ${Sweep.compassPoint(dir)} · " + when {
- kotlin.math.abs(turn) <= 20 -> "ahead"
- turn > 0 -> "turn right $turn°"
- else -> "turn left ${-turn}°"
- }
+ val l = lock ?: 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))} · " +
+ if (moved != null) "you moved, sweep again" else "${(l.confidence * 100).toInt()}% sure"
+ }
+
+ /** "ahead", "turn right 40°" or "turn left 40°". */
+ fun turnText(turn: Int) = when {
+ kotlin.math.abs(turn) <= 20 -> "ahead"
+ turn > 0 -> "turn right $turn°"
+ else -> "turn left ${-turn}°"
}
/** 1 getting closer, -1 moving away, 0 steady: the newest reading against the few before it. */
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 dad37cd..8ebadba 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
@@ -40,6 +40,12 @@ class RadarView @JvmOverloads constructor(
/** Pinpoint is off in Settings: located alerts can't show, and the footer says how to turn it on. */
var pinpointOff = false
+ // Settings › Radar, read again with each [setBlips].
+ private var northUp = false
+ private var spinDots = false
+ private var names = true
+ private var sweepLine = true
+
/** 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()
@@ -112,6 +118,10 @@ class RadarView @JvmOverloads constructor(
fun ordinaryColor() = ordinaryColor
fun setBlips(list: List<Blip>) {
+ northUp = com.rfsentinel.app.util.Prefs.radarNorthUp(context)
+ spinDots = com.rfsentinel.app.util.Prefs.radarSpinDots(context)
+ names = com.rfsentinel.app.util.Prefs.radarNames(context)
+ sweepLine = com.rfsentinel.app.util.Prefs.radarSweepLine(context)
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)
@@ -157,7 +167,9 @@ class RadarView @JvmOverloads constructor(
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)
+ // A made-up angle: still on screen, or turned with north as if it were a bearing (same place facing north).
+ val a = it.b.bearing?.let { screenAngle(it) }
+ ?: if (spinDots) screenAngle(Math.toDegrees(angleOf(it.b.mac)).toFloat() + 90f) else angleOf(it.b.mac)
xs[i] = cx + (r * cos(a)).toFloat()
ys[i] = cy + (r * sin(a)).toFloat()
}
@@ -176,7 +188,7 @@ class RadarView @JvmOverloads constructor(
if (rad <= 0) return
val now = System.currentTimeMillis()
fusion.compass(compass.degrees)
- heading = fusion.heading(now)
+ heading = if (northUp) null else fusion.heading(now)
// Signal bands: Near (>= -60), Nearby (>= -80), Far.
val near = rad * rssiToFraction(-60)
@@ -190,11 +202,12 @@ class RadarView @JvmOverloads constructor(
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()
- canvas.rotate(sweep, cx, cy)
- canvas.drawCircle(cx, cy, rad, sweepPaint)
- canvas.restore()
+ if (sweepLine) {
+ canvas.save()
+ canvas.rotate(sweep, cx, cy)
+ canvas.drawCircle(cx, cy, rad, sweepPaint)
+ canvas.restore()
+ }
// North on the outer ring (it turns with the heading), and which way the radar is turned.
val n = screenAngle(0f)
@@ -223,7 +236,7 @@ class RadarView @JvmOverloads constructor(
}
}
canvas.drawCircle(cx, cy, 5 * density, youPaint)
- drawLabels(canvas)
+ if (names) drawLabels(canvas)
val footer = footer(width - 16 * density, now)
canvas.drawText(footer, 8 * density, height - 8 * density, textPaint)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt b/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt
index 31cde12..d054d43 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt
@@ -1,15 +1,27 @@
package com.rfsentinel.app.ui
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.hypot
import kotlin.math.roundToInt
+import kotlin.math.sin
+import kotlin.math.sqrt
/**
- * On-foot direction finding while Locate runs: hold the phone flat in front of you and turn slowly. Your body
- * blocks the signal from behind, so the device is heard strongest when you face it. Readings go into
- * [SECTORS] compass sectors; once most of a turn is covered, the strongest sector is the direction.
- * Pure (unit-tested): the compass and signal readings come from [LiveRead].
+ * On-foot direction finding while Locate runs: hold the phone against your chest and turn slowly on the spot.
+ * Your body blocks the signal from behind, so over one full turn the signal rises once (facing the device) and
+ * falls once (your back to it). Readings go into [SECTORS] compass sectors; [estimate] fits that one rise and fall
+ * and gives the direction with a confidence. Pure (unit-tested): the heading (gyro + magnetometer, [Compass]) and
+ * signal readings come from [LiveRead].
*/
class Sweep {
+ /**
+ * [bearing]: compass degrees the device most likely is; [confidence] 0..1 (how much of the turn is covered and
+ * how well one rise and fall explains the readings); [frontBackDb]: how much stronger facing it than turned away.
+ */
+ data class Estimate(val bearing: Float, val confidence: Float, val frontBackDb: Float)
+
private class Reading(val time: Long, val heading: Float, val rssi: Int)
private val readings = ArrayDeque<Reading>()
@@ -22,36 +34,62 @@ class Sweep {
fun clear() = readings.clear()
/** Sectors with a reading in the last [WINDOW_MS] (out of [SECTORS]). */
- fun covered(now: Long) = strongest(now).count { it != null }
-
- /** Compass degrees of the strongest sector's centre, or null until a turn is covered and one sector stands out. */
- fun direction(now: Long): Float? {
- val best = strongest(now)
- val heard = best.filterNotNull()
- if (heard.size < MIN_SECTORS) return null
- val peak = heard.max()
- if (peak - heard.sorted()[heard.size / 2] < MIN_LEAD_DB) return null
- return best.indexOf(peak) * SECTOR_DEG + SECTOR_DEG / 2
- }
+ fun covered(now: Long) = sectors(now).count { it != null }
- private fun strongest(now: Long): Array<Int?> {
- val best = arrayOfNulls<Int>(SECTORS)
+ /** The average signal (dBm) heard facing each sector, null where you haven't faced yet. Sector i is centred on [centre]. */
+ fun sectors(now: Long): Array<Float?> {
+ val sum = FloatArray(SECTORS)
+ val n = IntArray(SECTORS)
for (r in readings) if (now - r.time <= WINDOW_MS) {
val i = (r.heading / SECTOR_DEG).toInt().coerceIn(0, SECTORS - 1)
- best[i] = maxOf(best[i] ?: Int.MIN_VALUE, r.rssi)
+ sum[i] += r.rssi; n[i]++
}
- return best
+ return Array(SECTORS) { if (n[it] == 0) null else sum[it] / n[it] }
+ }
+
+ /**
+ * Fits one rise and fall over the turn (the first harmonic of the signal against the heading): its peak is the
+ * direction. Null until [MIN_SECTORS] are covered.
+ */
+ fun estimate(now: Long): Estimate? {
+ val m = sectors(now)
+ val k = m.indices.filter { m[it] != null }
+ if (k.size < MIN_SECTORS) return null
+ val mean = k.sumOf { m[it]!!.toDouble() } / k.size
+ var a = 0.0; var b = 0.0
+ for (i in k) {
+ val t = Math.toRadians(centre(i).toDouble())
+ val d = m[i]!! - mean
+ a += d * cos(t); b += d * sin(t)
+ }
+ a *= 2.0 / k.size; b *= 2.0 / k.size
+ val amp = hypot(a, b)
+ val peak = atan2(b, a)
+ // What the one rise and fall leaves unexplained: fading and reflections.
+ val rest = sqrt(k.sumOf { i ->
+ val r = m[i]!! - mean - amp * cos(Math.toRadians(centre(i).toDouble()) - peak); r * r
+ } / k.size)
+ val confidence = k.size.toFloat() / SECTORS * (amp / (amp + rest + NOISE_DB)).toFloat()
+ return Estimate(((Math.toDegrees(peak) % 360 + 360) % 360).toFloat(), confidence.coerceIn(0f, 1f), (2 * amp).toFloat())
}
companion object {
const val SECTORS = 12
const val SECTOR_DEG = 360f / SECTORS
- /** A turn covers this many sectors (240°) before a direction is given. */
- const val MIN_SECTORS = 8
- /** The strongest sector must beat the typical one by this much, else the body shadow didn't show. */
- const val MIN_LEAD_DB = 4
+ /** A turn covers this many sectors (300°) before a direction is given. */
+ const val MIN_SECTORS = 10
/** Readings older than this drop out, so walking somewhere new starts a fresh sweep. */
- const val WINDOW_MS = 30_000L
+ const val WINDOW_MS = 45_000L
+ /** Locked once this sure, and the body shadow shows by at least [LOCK_MIN_DB]. */
+ const val LOCK_CONFIDENCE = 0.6f
+ const val LOCK_MIN_DB = 4f
+ /** Signal readings jump about this much on their own; keeps a tiny wave on a quiet signal from looking sure. */
+ private const val NOISE_DB = 0.5
+
+ fun centre(sector: Int) = sector * SECTOR_DEG + SECTOR_DEG / 2
+
+ /** Good enough to lock on and keep. */
+ fun locks(e: Estimate) = e.confidence >= LOCK_CONFIDENCE && e.frontBackDb >= LOCK_MIN_DB
private val POINTS = arrayOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")
fun compassPoint(deg: Float) = POINTS[(((deg % 360f + 360f) % 360f) / 45f).roundToInt() % 8]
diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
index bb6921f..53be49d 100644
--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
@@ -27,14 +27,22 @@ import com.rfsentinel.app.detect.Tier
object AlertPlayer {
/**
- * Phone beeps use the navigation-guidance usage too: it follows the media
- * volume (like Locate), which is usually up while driving, and dips music.
+ * Phone sounds and voice play on the volume chosen in Settings › Alerts ([Prefs.AlertVolume]). The default,
+ * navigation guidance, follows the media volume on most phones (usually up while driving) and dips music.
*/
- private val phoneToneAttributes = AudioAttributes.Builder()
- .setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
- .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
+ private fun phoneAttributes(context: Context, contentType: Int): AudioAttributes = AudioAttributes.Builder()
+ .setUsage(Prefs.alertVolume(context).usage)
+ .setContentType(contentType)
.build()
+ /** Alert beeps and ticks: the car's speakers in the car, else the chosen phone volume. */
+ private fun toneAttributes(context: Context, inCar: Boolean = CarState.connected) =
+ if (inCar) carToneAttributes else phoneAttributes(context, AudioAttributes.CONTENT_TYPE_SONIFICATION)
+
+ /** Alert speech: navigation guidance in the car, else the chosen phone volume. */
+ private fun alertSpeech(context: Context) =
+ if (CarState.connected) speechAttributes else phoneAttributes(context, AudioAttributes.CONTENT_TYPE_SPEECH)
+
/**
* On Android Auto, alerts use the navigation-guidance usage: the car plays
* it through its speakers and ducks the music, exactly like a turn prompt.
@@ -69,7 +77,7 @@ object AlertPlayer {
// Our own beeps (1 weak, 2 probable, 3 strong, long-short-long following) at
// media volume, like Locate: the notification chime was too soft and too quiet.
val beeps = when (tier) { Tier.STRONG -> 3; Tier.MEDIUM -> 2; else -> 1 }
- val attrs = if (inCar) carToneAttributes else phoneToneAttributes
+ val attrs = toneAttributes(context, inCar)
beepMs = if (detector) {
val chosen = Prefs.detectorEffect(context)
val clip = SoundClips.Clip.effect(when {
@@ -95,7 +103,7 @@ object AlertPlayer {
}
if (willSpeak) {
val app = context.applicationContext
- val attrs = speechAttributes
+ val attrs = alertSpeech(context)
val priority = when {
following -> VoiceQueue.FOLLOWING
tier == Tier.STRONG -> VoiceQueue.STRONG
@@ -118,7 +126,7 @@ object AlertPlayer {
if (Prefs.alertsSilenced(context) || !Prefs.soundEnabled(context) || !(inCar || ringerAllowsSound(context))) return
// Never over an alert sound that is still playing.
if (System.currentTimeMillis() < alertSoundUntil) return
- val attrs = if (inCar) carToneAttributes else phoneToneAttributes
+ val attrs = toneAttributes(context, inCar)
if (Prefs.detectorSound(context)) detectorTick(context, attrs) else Beeper.play(attrs, listOf(70 to 0))
}
@@ -132,9 +140,10 @@ object AlertPlayer {
fun previewEffect(context: Context, effect: Int) {
main.removeCallbacks(retryPreview)
val clip = SoundClips.Clip.effect(effect.takeIf { it != 0 } ?: 1)
- if (SoundClips.playPreview(context, phoneToneAttributes, clip)) return
+ val attrs = toneAttributes(context, false)
+ if (SoundClips.playPreview(context, attrs, clip)) return
// First use: the clips are still loading.
- retryPreview = Runnable { SoundClips.playPreview(context, phoneToneAttributes, clip) }
+ retryPreview = Runnable { SoundClips.playPreview(context, attrs, clip) }
main.postDelayed(retryPreview, 250L)
}
@@ -151,7 +160,7 @@ object AlertPlayer {
fun testIntro(context: Context, onDone: () -> Unit): Boolean {
stopPreview(false)
if (SoundClips.introPlaying()) { SoundClips.stopIntro(); return false }
- SoundClips.playIntro(context, phoneToneAttributes) { main.post(onDone) }
+ SoundClips.playIntro(context, toneAttributes(context, false)) { main.post(onDone) }
return true
}
@@ -159,16 +168,15 @@ object AlertPlayer {
@Volatile private var alertSoundUntil = 0L
/** Loads the recorded sounds so the first alert can use them. */
- fun preload(context: Context) = SoundClips.preload(context, phoneToneAttributes)
+ fun preload(context: Context) = SoundClips.preload(context, toneAttributes(context))
/**
- * One Locate tick (the device screen's proximity beeps) in the radar-detector sound style.
- * Started by the user, so it plays whatever the alert settings; false when the style is off.
+ * One Locate tick (the device screen's proximity beeps): a pulse in the radar-detector sound style, else a
+ * short beep. Started by the user, so it plays whatever the alert settings, on the chosen phone volume.
*/
- fun locateTick(context: Context): Boolean {
- if (!Prefs.detectorSound(context)) return false
- detectorTick(context, phoneToneAttributes)
- return true
+ fun locateTick(context: Context) {
+ val attrs = toneAttributes(context, false)
+ if (Prefs.detectorSound(context)) detectorTick(context, attrs) else Beeper.play(attrs, listOf(60 to 0))
}
/**
@@ -181,7 +189,7 @@ object AlertPlayer {
// The power-on sweep only with the detector sound style and its start beep on (off by default).
if (!intro && !(Prefs.detectorSound(context) && Prefs.startupSweep(context))) return
if (Prefs.alertsSilenced(context) || !Prefs.soundEnabled(context) || !(inCar || ringerAllowsSound(context))) return
- val attrs = if (inCar) carToneAttributes else phoneToneAttributes
+ val attrs = toneAttributes(context, inCar)
if (intro) SoundClips.playIntro(context, attrs) else Beeper.playTones(attrs, Beeper.detectorStartup)
}
@@ -195,7 +203,7 @@ object AlertPlayer {
/** A spoken navigation instruction (no beep, no vibration); silent when alerts are muted. */
fun announce(context: Context, text: String) {
if (Prefs.alertsSilenced(context)) return
- Voice.say(context.applicationContext, text, VoiceQueue.STRONG, speechAttributes)
+ Voice.say(context.applicationContext, text, VoiceQueue.STRONG, alertSpeech(context))
}
/**
@@ -215,13 +223,13 @@ object AlertPlayer {
fun callout(context: Context, text: String) {
val inCar = CarState.connected
if (Prefs.alertsSilenced(context) || !(Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))) return
- Voice.say(context.applicationContext, text, VoiceQueue.STRONG, speechAttributes)
+ Voice.say(context.applicationContext, text, VoiceQueue.STRONG, alertSpeech(context))
}
/** The Settings "Test voice" button: speaks right away with the chosen voice and speed. */
fun testVoice(context: Context, short: Boolean = Prefs.shortVoice(context)) {
Voice.test(context.applicationContext, if (short) "Body cam" else "RF Sentinel voice alerts. Axon body camera nearby.",
- speechAttributes)
+ alertSpeech(context))
}
/**
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 e5a4ae5..1da2f8b 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -69,6 +69,18 @@ object Prefs {
fun soundEnabled(context: Context): Boolean = bool(context, "sound_enabled", true)
fun setSoundEnabled(context: Context, value: Boolean) = setBool(context, "sound_enabled", value)
+ /** Which phone volume alert sounds, Locate beeps and the alert voice follow. In the car they always use the car's speakers. */
+ enum class AlertVolume(val usage: Int) {
+ NAVIGATION(android.media.AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE),
+ MEDIA(android.media.AudioAttributes.USAGE_MEDIA),
+ ALARM(android.media.AudioAttributes.USAGE_ALARM),
+ NOTIFICATION(android.media.AudioAttributes.USAGE_NOTIFICATION),
+ RING(android.media.AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
+ }
+ fun alertVolume(context: Context): AlertVolume =
+ runCatching { AlertVolume.valueOf(sp(context).getString("alert_volume", null)!!) }.getOrDefault(AlertVolume.NAVIGATION)
+ fun setAlertVolume(context: Context, v: AlertVolume) = sp(context).edit { putString("alert_volume", v.name) }
+
fun vibrateEnabled(context: Context): Boolean = bool(context, "vibrate_enabled", true)
fun setVibrateEnabled(context: Context, value: Boolean) = setBool(context, "vibrate_enabled", value)
@@ -429,14 +441,13 @@ object Prefs {
fun setOuiSpyBoard(context: Context, address: String?) = sp(context).edit {
if (address == null) remove("ouispy_board") else putString("ouispy_board", address)
}
- /** Have the OUI-SPY board relay every network and Bluetooth device it hears (its Wardrive engine). */
- /** Whether the screen stays on while an RF Sentinel screen is open. */
- /** WiFi bands scanned (Settings > Scanning): the phone's results and the USB adapters' channel hopping. */
+ /** The channels USB WiFi adapters hop (Settings › External hardware). The phone's own WiFi always lists every band. */
enum class WifiBand { ALL, LOW, HIGH }
fun wifiBand(context: Context): WifiBand =
runCatching { WifiBand.valueOf(sp(context).getString("wifi_band", null)!!) }.getOrDefault(WifiBand.ALL)
fun setWifiBand(context: Context, band: WifiBand) = sp(context).edit { putString("wifi_band", band.name) }
+ /** Whether the screen stays on while an RF Sentinel screen is open. */
enum class ScreenMode { ALWAYS_ON, ON_WHILE_CHARGING, NORMAL }
fun screenMode(context: Context): ScreenMode =
runCatching { ScreenMode.valueOf(sp(context).getString("screen_mode", null)!!) }.getOrDefault(ScreenMode.ON_WHILE_CHARGING)
@@ -444,6 +455,7 @@ object Prefs {
/** When the US & Canada plate readers were last downloaded from DeFlock (0 = never). */
fun deflockUpdated(context: Context): Long = sp(context).getLong("deflock_updated", 0L)
fun setDeflockUpdated(context: Context, time: Long) = sp(context).edit { putLong("deflock_updated", time) }
+ /** Have the OUI-SPY board relay every network and Bluetooth device it hears (its Wardrive engine). */
fun ouiSpyRelayAll(context: Context): Boolean = bool(context, "ouispy_relay_all", true)
fun setOuiSpyRelayAll(context: Context, value: Boolean) = setBool(context, "ouispy_relay_all", value)
/** The OUI-SPY detection engines to switch on (all by default; Flock off where there are no Flock cameras). */
@@ -647,6 +659,17 @@ object Prefs {
fun onboardingDone(context: Context): Boolean = bool(context, "setup_wizard_done", false)
fun setOnboardingDone(context: Context) = setBool(context, "setup_wizard_done", true)
+ /** Settings › Radar: north at the top instead of the way you face. */
+ fun radarNorthUp(context: Context): Boolean = bool(context, "radar_north_up", false)
+ fun setRadarNorthUp(context: Context, value: Boolean) = setBool(context, "radar_north_up", value)
+ /** Settings › Radar: dots without a known direction turn with north instead of staying put on screen. */
+ fun radarSpinDots(context: Context): Boolean = bool(context, "radar_spin_dots", false)
+ fun setRadarSpinDots(context: Context, value: Boolean) = setBool(context, "radar_spin_dots", value)
+ fun radarNames(context: Context): Boolean = bool(context, "radar_names", true)
+ fun setRadarNames(context: Context, value: Boolean) = setBool(context, "radar_names", value)
+ fun radarSweepLine(context: Context): Boolean = bool(context, "radar_sweep_line", true)
+ fun setRadarSweepLine(context: Context, value: Boolean) = setBool(context, "radar_sweep_line", value)
+
fun radarView(context: Context): Boolean = bool(context, "radar_view", false)
fun setRadarView(context: Context, value: Boolean) = setBool(context, "radar_view", value)
diff --git a/app/src/main/java/com/rfsentinel/app/util/SoundClips.kt b/app/src/main/java/com/rfsentinel/app/util/SoundClips.kt
index d419b37..d448d98 100644
--- a/app/src/main/java/com/rfsentinel/app/util/SoundClips.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/SoundClips.kt
@@ -30,46 +30,50 @@ object SoundClips {
}
}
- private var pool: SoundPool? = null
- private val ids = HashMap<Clip, Int>()
- private val ready = HashSet<Int>()
+ /** The clips loaded into one SoundPool, with the ids that finished loading. */
+ private class Pool(val sound: SoundPool, val ids: Map<Clip, Int>, val ready: MutableSet<Int>)
+ /** One pool per audio usage: a SoundPool's volume is fixed when it is built (the car's, the chosen phone volume). */
+ private val pools = HashMap<Int, Pool>()
private var intro: MediaPlayer? = null
+ private var previewPool: Pool? = null
private var previewStream = 0
/** Loads the clips (async); call early, e.g. when a scan starts. */
@Synchronized
- fun preload(context: Context, attributes: AudioAttributes) {
- if (pool != null) return
+ fun preload(context: Context, attributes: AudioAttributes) { pool(context, attributes) }
+
+ private fun pool(context: Context, attributes: AudioAttributes): Pool = pools.getOrPut(attributes.usage) {
val p = SoundPool.Builder().setMaxStreams(2).setAudioAttributes(attributes).build()
+ val ready = HashSet<Int>()
p.setOnLoadCompleteListener { _, id, status -> if (status == 0) synchronized(this) { ready += id } }
val app = context.applicationContext
- for (c in Clip.entries) ids[c] = p.load(app, c.res, 1)
- pool = p
+ Pool(p, Clip.entries.associateWith { p.load(app, it.res, 1) }, ready)
}
/** Plays a clip; returns its length (ms), or 0 if it isn't loaded yet (caller falls back). */
@Synchronized
fun play(context: Context, attributes: AudioAttributes, clip: Clip): Int {
- preload(context, attributes)
- val id = ids[clip] ?: return 0
- if (id !in ready) return 0
- return if ((pool?.play(id, 1f, 1f, 1, 0, 1f) ?: 0) != 0) clip.ms else 0
+ val p = pool(context, attributes)
+ val id = p.ids[clip] ?: return 0
+ if (id !in p.ready) return 0
+ return if (p.sound.play(id, 1f, 1f, 1, 0, 1f) != 0) clip.ms else 0
}
/** A Settings preview: stops the previous preview first so two never overlap. */
@Synchronized
fun playPreview(context: Context, attributes: AudioAttributes, clip: Clip): Boolean {
stopPreview()
- preload(context, attributes)
- val id = ids[clip] ?: return false
- if (id !in ready) return false
- previewStream = pool?.play(id, 1f, 1f, 1, 0, 1f) ?: 0
+ val p = pool(context, attributes)
+ val id = p.ids[clip] ?: return false
+ if (id !in p.ready) return false
+ previewPool = p
+ previewStream = p.sound.play(id, 1f, 1f, 1, 0, 1f)
return previewStream != 0
}
@Synchronized
fun stopPreview() {
- if (previewStream != 0) pool?.stop(previewStream)
+ if (previewStream != 0) previewPool?.sound?.stop(previewStream)
previewStream = 0
}
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
index 179323a..3848013 100644
--- a/app/src/main/res/layout/activity_main.xml
+++ b/app/src/main/res/layout/activity_main.xml
@@ -241,9 +241,9 @@
android:layout_height="0dp"
android:layout_weight="1">
- <!-- Pull down to check Waze right now (only while Waze reports are on). -->
+ <!-- Pull down to scan WiFi, check the cells and Waze right now (MainActivity.refreshAll). -->
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
- android:id="@+id/wazeSwipe"
+ android:id="@+id/refreshSwipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 918665a..486e2ed 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -115,18 +115,6 @@
android:layout_height="wrap_content"
android:text="WiFi scanning" />
- <TextView android:id="@+id/wifiBandLabel" style="@style/SettingsLabel" android:text="WiFi bands" />
-
- <RadioGroup
- android:id="@+id/wifiBandGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
-
- <RadioButton android:id="@+id/wifiBandAll" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="All bands" />
- <RadioButton android:id="@+id/wifiBandLow" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="2.4 GHz only" />
- <RadioButton android:id="@+id/wifiBandHigh" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="5 and 6 GHz only" />
- </RadioGroup>
-
<TextView android:id="@+id/scanModeLabel" style="@style/SettingsLabel" android:text="Bluetooth scan intensity" />
<RadioGroup
@@ -251,6 +239,20 @@
android:layout_height="wrap_content"
android:text="Alert sound" />
+ <TextView android:id="@+id/alertVolumeLabel" style="@style/SettingsLabel" android:text="Alert volume" />
+
+ <RadioGroup
+ android:id="@+id/alertVolumeGroup"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <RadioButton android:id="@+id/alertVolumeNav" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Navigation" />
+ <RadioButton android:id="@+id/alertVolumeMedia" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Media" />
+ <RadioButton android:id="@+id/alertVolumeAlarm" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Alarm" />
+ <RadioButton android:id="@+id/alertVolumeNotification" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Notification" />
+ <RadioButton android:id="@+id/alertVolumeRing" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Ringtone" />
+ </RadioGroup>
+
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/vibrateSwitch"
android:layout_width="match_parent"
@@ -472,6 +474,45 @@
<TextView android:id="@+id/headerNav" style="@style/SettingsHeader" android:text="Navigation" />
<LinearLayout android:id="@+id/sectionNav" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" />
+ <!-- ================= Radar ================= -->
+ <TextView android:id="@+id/headerRadar" style="@style/SettingsHeader" android:text="Radar" />
+ <LinearLayout android:id="@+id/sectionRadar" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+
+ <TextView android:id="@+id/radarTopLabel" style="@style/SettingsLabel" android:text="Top of the radar" />
+
+ <RadioGroup
+ android:id="@+id/radarTopGroup"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <RadioButton android:id="@+id/radarTopFacing" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="The way you face" />
+ <RadioButton android:id="@+id/radarTopNorth" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="North" />
+ </RadioGroup>
+
+ <TextView android:id="@+id/radarDotsLabel" style="@style/SettingsLabel" android:text="Dots without a direction" />
+
+ <RadioGroup
+ android:id="@+id/radarDotsGroup"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <RadioButton android:id="@+id/radarDotsFixed" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stay in place" />
+ <RadioButton android:id="@+id/radarDotsNorth" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Turn with north" />
+ </RadioGroup>
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/radarNamesSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Names beside alerts" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/radarSweepSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Sweep line" />
+ </LinearLayout>
+
<!-- ================= Known cameras ================= -->
<TextView android:id="@+id/headerMap" style="@style/SettingsHeader" android:text="Map" />
<LinearLayout android:id="@+id/sectionMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
@@ -791,6 +832,18 @@
android:layout_height="wrap_content"
android:text="Phone Bluetooth scan with OUI-SPY" />
+ <TextView android:id="@+id/wifiBandLabel" style="@style/SettingsLabel" android:text="USB WiFi bands" />
+
+ <RadioGroup
+ android:id="@+id/wifiBandGroup"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <RadioButton android:id="@+id/wifiBandAll" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="All bands" />
+ <RadioButton android:id="@+id/wifiBandLow" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="2.4 GHz only" />
+ <RadioButton android:id="@+id/wifiBandHigh" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="5 and 6 GHz only" />
+ </RadioGroup>
+
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/rtl5gSwitch"
android:layout_width="match_parent"
diff --git a/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt b/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt
index 18009bf..8df69e4 100644
--- a/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt
@@ -1,8 +1,11 @@
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
+import kotlin.math.cos
class SweepTest {
@@ -11,20 +14,32 @@ class SweepTest {
val s = Sweep()
// A slow turn: -80 dBm with your back to it, -66 facing east (about 90°).
for (h in 0 until 360 step 10) s.add(1_000L + h * 10, h.toFloat(), if (h in 90..110) -66 else -80)
- assertEquals(105f, s.direction(5_000L)!!, 0.1f)
+ assertEquals(105f, s.estimate(5_000L)!!.bearing, 0.1f)
assertEquals("E", Sweep.compassPoint(105f))
}
+ @Test
+ fun bodyShadowWithFadingLocksOnTheRightSide() {
+ val s = Sweep()
+ // Facing it (200°) 10 dB stronger than turned away, plus fading of up to ±3 dB.
+ for (h in 0 until 360 step 5) {
+ val fade = (h / 5 * 3 % 7) - 3
+ s.add(1_000L + h * 50, h.toFloat(), (-75 + 5 * cos(Math.toRadians(h - 200.0)) + fade).toInt())
+ }
+ val e = s.estimate(20_000L)!!
+ assertEquals(200f, e.bearing, 15f)
+ assertTrue(e.toString(), Sweep.locks(e))
+ }
+
@Test
fun noDirectionUntilTurnedOrWhenFlat() {
val half = Sweep()
for (h in 0 until 180 step 10) half.add(1_000L, h.toFloat(), if (h == 90) -60 else -80)
- assertNull(half.direction(1_000L)) // only half a turn
+ assertNull(half.estimate(1_000L)) // only half a turn
val flat = Sweep()
for (h in 0 until 360 step 10) flat.add(1_000L, h.toFloat(), -70 - (h / 10) % 2)
- assertNull(flat.direction(1_000L)) // no side stands out
+ assertFalse(Sweep.locks(flat.estimate(1_000L)!!)) // no side stands out
// Old readings drop out.
- for (h in 0 until 360 step 10) flat.add(1_000L, h.toFloat(), if (h == 90) -50 else -80)
assertEquals(0, flat.covered(1_000L + Sweep.WINDOW_MS + 1))
}