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.

Waze alerts only for your road ahead; 3D view restored on reopen

CIS-C0da029111fa34
diff --git a/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt b/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt
index 2df7f03..32ba863 100644
--- a/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/AheadOnRoad.kt
@@ -12,20 +12,40 @@ import android.location.Location
internal class AheadOnRoad {
private var path: RoadMatch.Path? = null
+ /** Where and when the path in hand was worked out (not merely attempted). */
private var pathLat = 0.0; private var pathLon = 0.0; private var pathHeading = 0.0; private var pathAt = 0L
+ private var triedAt = 0L
private var heading: Double? = null; private var headingAt = 0L
private var headingLat = 0.0; private var headingLon = 0.0
+ /**
+ * True when the verdicts are thin because the map along your way has not arrived yet, so a caller
+ * can wait a moment for it instead of deciding without it.
+ */
+ @Volatile var waitingForRoads = false
+ private set
+
/** Each report's verdict (by id); none while the map can't tell (no heading, no roads loaded yet). */
fun verdicts(context: Context, me: Location, alertM: Double, reports: List<WazePolice.Report>): Map<String, RoadMatch.Verdict> {
- val h = headingOf(me) ?: return emptyMap()
+ val h = headingOf(me) ?: run { waitingForRoads = false; return emptyMap() }
val now = System.currentTimeMillis()
val moved = com.rfsentinel.app.service.DeviceRegistry.metersBetween(pathLat, pathLon, me.latitude, me.longitude)
- if (path == null || moved > 25 || RoadMatch.angleDiff(h, pathHeading) > 20 || now - pathAt > 5_000) {
- path = build(context, me.latitude, me.longitude, h, alertM)
- pathLat = me.latitude; pathLon = me.longitude; pathHeading = h; pathAt = now
+ val due = path == null || moved > 25 || RoadMatch.angleDiff(h, pathHeading) > 20 || now - pathAt > 5_000
+ if (due && now - triedAt >= MIN_BUILD_GAP_MS) {
+ triedAt = now
+ val fresh = build(context, me.latitude, me.longitude, h, alertM, me)
+ if (fresh != null) {
+ path = fresh
+ pathLat = me.latitude; pathLon = me.longitude; pathHeading = h; pathAt = now
+ } else if (moved > KEEP_PATH_M || now - pathAt > KEEP_PATH_MS) {
+ // A tile that hasn't arrived yet shouldn't throw away a good answer: the last path stands
+ // for a short stretch, so a momentary gap doesn't drop every report to the plain corridor test.
+ path = null
+ }
}
- val p = path ?: return emptyMap()
+ val p = path
+ waitingForRoads = p == null || p.stoppedForData
+ if (p == null) return emptyMap()
return reports.associate { it.id to RoadMatch.check(p, it.lat, it.lon).first }
}
@@ -42,11 +62,21 @@ internal class AheadOnRoad {
}
/** Your road ahead from the roads loaded so far; asks for the map along the way (and where it ran out). */
- private fun build(context: Context, lat: Double, lon: Double, headingDeg: Double, alertM: Double): RoadMatch.Path? {
+ private fun build(context: Context, lat: Double, lon: Double, headingDeg: Double, alertM: Double, me: Location): RoadMatch.Path? {
val maxM = (alertM * 1.3).coerceIn(500.0, 6_000.0)
val tiles = corridor(lat, lon, headingDeg, maxM)
val have = RoadTiles.roads(context, tiles)
- val path = RoadMatch.pathAhead(have.values.flatten(), lat, lon, headingDeg, maxM) { la, lo -> RoadTiles.tileOf(la, lo) in have }
+ // Then the map further on, in the background, so the path is ready before you get there. Asked for
+ // after the stretch in use, which the one loading thread therefore fetches first.
+ val warm = corridor(lat, lon, headingDeg, (maxM * 2).coerceAtMost(WARM_MAX_M)) - tiles
+ if (warm.isNotEmpty()) RoadTiles.roads(context, warm)
+ // A phone's fix can sit a good way off the road it is on (buildings, trees): allow for what it
+ // admits to, or you are taken as on no road at all and every report falls back to the corridor test.
+ val meMaxM = RoadMatch.ME_MAX_M +
+ (if (me.hasAccuracy()) me.accuracy.toDouble().coerceAtMost(ACCURACY_ALLOWANCE_M) else 0.0)
+ val path = RoadMatch.pathAhead(have.values.flatten(), lat, lon, headingDeg, maxM, meMaxM) { la, lo ->
+ RoadTiles.tileOf(la, lo) in have
+ }
// The road bends out of the strip along your heading: load where it went too.
if (path != null && path.stoppedForData) {
val (la, lo) = path.endLatLon()
@@ -56,6 +86,15 @@ internal class AheadOnRoad {
}
companion object {
+ /** A path is not worked out again more often than this, however often the verdicts are asked for. */
+ private const val MIN_BUILD_GAP_MS = 1_000L
+ /** A path with no replacement yet stands for this long, and this far travelled, before it is dropped. */
+ private const val KEEP_PATH_MS = 15_000L
+ private const val KEEP_PATH_M = 100.0
+ /** The most a fix's own accuracy widens how far from a road you can be and still be on it. */
+ private const val ACCURACY_ALLOWANCE_M = 30.0
+ /** The map is never fetched further ahead than this. */
+ private const val WARM_MAX_M = 4_000.0
/** The map tiles along your heading: every 250 m out to [maxM], and 300 m either side. */
internal fun corridor(lat: Double, lon: Double, headingDeg: Double, maxM: Double): Set<RoadTiles.Tile> {
val out = LinkedHashSet<RoadTiles.Tile>()
diff --git a/app/src/main/java/com/rfsentinel/app/online/RoadMatch.kt b/app/src/main/java/com/rfsentinel/app/online/RoadMatch.kt
index 17e0bdb..946c9e9 100644
--- a/app/src/main/java/com/rfsentinel/app/online/RoadMatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/RoadMatch.kt
@@ -34,8 +34,8 @@ object RoadMatch {
fun endLatLon(): Pair<Double, Double> = frame.toLatLon(xs.last(), ys.last())
}
- /** Your position counts as on a road within this. */
- private const val ME_MAX_M = 30.0
+ /** Your position counts as on a road within this (the caller adds room for the fix's own error). */
+ internal const val ME_MAX_M = 30.0
/** A report counts as on the road within this (Waze places reports on or right beside it). */
private const val REPORT_MAX_M = 30.0
/** Your heading and the road's direction must agree within this. */
@@ -47,15 +47,16 @@ object RoadMatch {
/**
* Your road ahead from ([lat], [lon]) going [headingDeg], up to [maxM] along it; null when you're
- * not on a known road (or no roads are loaded). [loaded] says whether map data covers a point
- * (the walk stops there for want of data, not at a dead end).
+ * not on a known road (or no roads are loaded). [meMaxM] is how far from a road you can be and
+ * still be taken as on it (room for the fix's own error). [loaded] says whether map data covers a
+ * point (the walk stops there for want of data, not at a dead end).
*/
fun pathAhead(roads: List<RoadTiles.Road>, lat: Double, lon: Double, headingDeg: Double, maxM: Double,
- loaded: (Double, Double) -> Boolean = { _, _ -> true }): Path? {
+ meMaxM: Double = ME_MAX_M, loaded: (Double, Double) -> Boolean = { _, _ -> true }): Path? {
if (roads.isEmpty()) return null
val f = Frame(lat, lon)
val idx = Index(roads, f)
- val start = idx.nearest(0.0, 0.0, ME_MAX_M).mapNotNull { c ->
+ val start = idx.nearest(0.0, 0.0, meMaxM).mapNotNull { c ->
// Which way along this segment you're going, if either agrees with your heading.
val d = idx.dirDeg(c.road, c.seg)
val fwd = angleDiff(d, headingDeg); val back = angleDiff(d + 180, headingDeg)
diff --git a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt b/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt
index db4f65a..1972e9c 100644
--- a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt
@@ -78,8 +78,34 @@ object WazePolice {
data class Where(val distanceM: Double, val compass: String, val side: Side?, val relDeg: Float?) {
/** Clearly behind (more than 100 degrees off your heading); false when the heading is unknown. */
val isBehind: Boolean get() = relDeg != null && abs(relDeg) > 100f
+
+ /** How far to the side of the line you are driving the report sits, in metres; null without a heading. */
+ val lateralM: Double? get() = relDeg?.let { abs(distanceM * Math.sin(Math.toRadians(it.toDouble()))) }
+
+ /**
+ * Could it be on the road you are driving? Without the map's roads to be sure (none loaded here,
+ * or you are not moving), a report counts only while it is ahead and inside a corridor along your
+ * heading - a road's width, widening with distance to allow for bends. A parallel street, a cross
+ * street or the far side of a dual carriageway falls outside it. True when the heading is unknown:
+ * there is then nothing to go on, so nothing is ruled out.
+ */
+ fun maybeOnMyWay(): Boolean {
+ val rel = relDeg ?: return true
+ if (abs(rel) > 90f) return false
+ return (lateralM ?: return true) <= corridorM(distanceM)
+ }
}
+ /** Half-width of the "could be my road" corridor at [distanceM]: a road's width plus room for bends. */
+ fun corridorM(distanceM: Double): Double = (CORRIDOR_BASE_M + CORRIDOR_SPREAD * distanceM).coerceAtMost(CORRIDOR_MAX_M)
+
+ /** The corridor at your own position: a wide road plus the usual GPS error. */
+ private const val CORRIDOR_BASE_M = 30.0
+ /** How fast it widens with distance, for bends in the road ahead. */
+ private const val CORRIDOR_SPREAD = 0.08
+ /** It never grows past this: further out it would rule nothing out anyway. */
+ private const val CORRIDOR_MAX_M = 250.0
+
/** Works out [Where] from plain numbers; [heading] is null when the phone is not driving. */
fun where(meLat: Double, meLon: Double, heading: Double?, lat: Double, lon: Double): Where {
val d = DeviceRegistry.metersBetween(meLat, meLon, lat, lon)
diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
index 073c5dc..fc9f36c 100644
--- a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
@@ -56,6 +56,8 @@ class WazeWatch(
private val alerted = HashSet<String>()
/** The smallest call-out distance already spoken for each report. */
private val calledBand = HashMap<String, Int>()
+ /** When a report first had to wait for the map along your way (see the hold in [evaluate]). */
+ private val heldSince = HashMap<String, Long>()
private var known: Map<String, WazePolice.Report> = emptyMap()
private var via = WazePolice.VIA_DIRECT
private var lastOkAt = 0L
@@ -245,20 +247,34 @@ class WazeWatch(
trend.keepOnly(known.keys)
// Only ahead: on the road you're on, ahead of you (the map's roads); where the map can't tell
- // (no data yet, not driving), not clearly behind you.
+ // (no data yet, not driving), inside a corridor along your heading.
val verdicts = if (aheadOnly) road.verdicts(context, me, alertM, shown.map { it.report }) else emptyMap()
fun quiet(s: WazePolice.Shown) = when (verdicts[s.report.id]) {
RoadMatch.Verdict.ON_MY_ROAD -> false
RoadMatch.Verdict.OTHER_ROAD, RoadMatch.Verdict.BEHIND -> true
- else -> s.where.isBehind
+ else -> !s.where.maybeOnMyWay()
}
// In the alert range, and (if asked) ahead on your road.
fun counts(s: WazePolice.Shown) = s.distanceM <= alertM && !(aheadOnly && quiet(s))
+ /**
+ * The map hasn't answered for this one yet. Rather than speak up on geometry alone and perhaps be
+ * about a parallel road, a report not yet alerted waits [ROAD_HOLD_MS] for the roads to arrive. It
+ * is on the list and the map meanwhile, and after the wait the corridor test decides as before.
+ */
+ fun waitingForRoad(s: WazePolice.Shown): Boolean {
+ if (!aheadOnly || !road.waitingForRoads) return false
+ val v = verdicts[s.report.id]
+ if (v != null && v != RoadMatch.Verdict.UNKNOWN) return false
+ return now - heldSince.getOrPut(s.report.id) { now } < ROAD_HOLD_MS
+ }
+
var fired = false
for (s in shown) {
if (!counts(s)) continue
val id = s.report.id
+ if (id !in seen && id !in alerted && waitingForRoad(s)) continue
+
val first = id !in seen
if (first) seen[id] = now
val eligible = s.hit.confidence >= threshold
@@ -283,6 +299,7 @@ class WazeWatch(
seen.entries.removeAll { now - it.value > WazePolice.MAX_AGE_MS * 2 }
alerted.retainAll(seen.keys)
calledBand.keys.retainAll(seen.keys)
+ heldSince.keys.retainAll(known.keys)
// The threat headline: the strongest report that counts and is allowed to be loud enough to matter.
val headline = shown.filter { counts(it) && it.level != WazePolice.Level.LOG }.maxByOrNull { it.hit.confidence }
@@ -316,9 +333,11 @@ class WazeWatch(
private fun clock(t: Long) = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(t))
- private companion object {
+ internal companion object {
/** After a skipped check (no fix or key yet), look again this soon. */
const val RETRY_MS = 5_000L
+ /** How long a new report waits for the map along your way before geometry alone decides. */
+ const val ROAD_HOLD_MS = 10_000L
/** The distances at which a report coming closer is called out again. */
val APPROACH_BANDS_M = intArrayOf(200, 500, 1000)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
index 2906bf1..08ebef1 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
@@ -347,7 +347,8 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
}
look(ms)
lc.setCameraMode(if (mode == MapEngine.Follow.HEADING) CameraMode.TRACKING_GPS else CameraMode.TRACKING, ms, null, null, null, null)
- if (ms > 0) Runnable { if (component() != null) look(400) }.also { reapply = it; view.postDelayed(it, ms + 250) }
+ // Also after an instant switch (the map opening already in 3D): the angle set above was dropped.
+ Runnable { if (component() != null) look(if (ms > 0) 400 else 0) }.also { reapply = it; view.postDelayed(it, ms + 250) }
val m = map
if (mode == MapEngine.Follow.NORTH && m != null && m.cameraPosition.bearing != 0.0) m.animateCamera(CameraUpdateFactory.bearingTo(0.0), 600)
}
diff --git a/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.kt b/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.kt
index 8a449bb..3e4f4d7 100644
--- a/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/online/RoadMatchTest.kt
@@ -24,7 +24,7 @@ class RoadMatchTest {
private fun verdict(roads: List<RoadTiles.Road>, x: Double, y: Double, heading: Double = 0.0, maxM: Double = 2000.0,
loaded: (Double, Double) -> Boolean = { _, _ -> true }): Pair<Verdict, Double?> {
- val path = RoadMatch.pathAhead(roads, lat0, lon0, heading, maxM, loaded)
+ val path = RoadMatch.pathAhead(roads, lat0, lon0, heading, maxM, loaded = loaded)
val (la, lo) = frame.toLatLon(x, y)
return RoadMatch.check(path, la, lo)
}
diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.kt
index eedfba4..49d2301 100644
--- a/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.kt
@@ -35,4 +35,39 @@ class WazeRelativeTest {
// Driving east: due north is on the left.
assertTrue(WazePolice.relative(me(90f, 20f), 10.008, 10.0).endsWith("to your left"))
}
+
+ /** The corridor along your heading, used when the map's roads can't say which road a report is on. */
+ private fun where(distanceM: Double, relDeg: Float?) =
+ WazePolice.Where(distanceM, "N", null, relDeg)
+
+ @Test
+ fun theCorridorWidensWithDistanceButNeverWithoutLimit() {
+ assertEquals(30.0, WazePolice.corridorM(0.0), 0.01)
+ assertEquals(42.0, WazePolice.corridorM(150.0), 0.01)
+ assertEquals(110.0, WazePolice.corridorM(1_000.0), 0.01)
+ assertEquals("capped", 250.0, WazePolice.corridorM(50_000.0), 0.01)
+ }
+
+ @Test
+ fun sidewaysOffsetIsWhatCounts() {
+ // 150 m away, 20 degrees off: about 51 m to the side, so another road, not the one you are on.
+ assertEquals(51.3, where(150.0, 20f).lateralM!!, 0.5)
+ assertTrue(where(150.0, 5f).maybeOnMyWay()) // 13 m: your road
+ assertTrue(!where(150.0, 20f).maybeOnMyWay()) // 51 m: a parallel or crossing road
+ // The same angle a kilometre out is still within the corridor: the road may bend that way.
+ assertTrue(where(1_000.0, 5f).maybeOnMyWay())
+ assertTrue(!where(1_000.0, 20f).maybeOnMyWay()) // 342 m: too far to the side at any distance
+ }
+
+ @Test
+ fun besideAndBehindYouAreNeverOnYourWay() {
+ assertTrue(!where(150.0, 95f).maybeOnMyWay())
+ assertTrue(!where(150.0, 180f).maybeOnMyWay())
+ }
+
+ @Test
+ fun withNoHeadingNothingIsRuledOut() {
+ assertTrue(where(150.0, null).maybeOnMyWay())
+ assertEquals(null, where(150.0, null).lateralM)
+ }
}
diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt
index 6c2d1f3..672e71b 100644
--- a/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt
@@ -83,10 +83,47 @@ class WazeWatchTest {
assertTrue(alerts.isEmpty())
assertTrue("still listed", WazePolice.latest.single().where.isBehind)
here = fix(10.0, 10.0, bearing = 180f, speed = 10f) // turn round: now it is ahead
+ // No road data in a test, so it waits for the map before geometry alone decides.
watch.evaluate(2_000L, publish = false)
+ assertTrue("waiting for the map", alerts.isEmpty())
+ watch.evaluate(2_000L + WazeWatch.ROAD_HOLD_MS, publish = false)
assertEquals(1, alerts.size)
}
+ /** A report [north] of the origin and [east] of it, in metres. */
+ private fun reportAt(id: String, north: Double, east: Double) = WazePolice.Report(
+ id, 10.0 + north / 110_574.0, 10.0 + east / (111_320.0 * Math.cos(Math.toRadians(10.0))),
+ null, null, null, 0, null, Type.POLICE
+ )
+
+ @Test
+ fun aReportOffToTheSideIsNotOnYourRoadEvenThoughItIsAhead() {
+ Prefs.setWazeAheadOnly(ctx, true)
+ here = fix(10.0, 10.0, bearing = 0f, speed = 15f) // driving north
+ // 150 m up the road but 120 m to the east: a parallel street, not the one you are on.
+ watch.ingest(listOf(reportAt("beside", 150.0, 120.0)), WazePolice.VIA_DIRECT, 1_000L)
+ watch.evaluate(1_000L + WazeWatch.ROAD_HOLD_MS, publish = false)
+ assertTrue(alerts.toString(), alerts.isEmpty())
+ assertEquals("still on the list and the map", 1, WazePolice.latest.size)
+ }
+
+ @Test
+ fun aReportStraightAheadStillAlertsOnceTheWaitIsOver() {
+ Prefs.setWazeAheadOnly(ctx, true)
+ here = fix(10.0, 10.0, bearing = 0f, speed = 15f)
+ watch.ingest(listOf(reportAt("ahead", 150.0, 8.0)), WazePolice.VIA_DIRECT, 1_000L)
+ assertTrue("held while the map is awaited", alerts.isEmpty())
+ watch.evaluate(1_000L + WazeWatch.ROAD_HOLD_MS, publish = false)
+ assertEquals(1, alerts.size)
+ }
+
+ @Test
+ fun theWaitIsOnlyForOnlyAheadMode() {
+ here = fix(10.0, 10.0, bearing = 0f, speed = 15f)
+ watch.ingest(listOf(reportAt("beside", 150.0, 120.0)), WazePolice.VIA_DIRECT, 1_000L)
+ assertEquals("no road filtering asked for: alerts at once", 1, alerts.size)
+ }
+
@Test
fun behindStillAlertsWhenOnlyAheadIsOff() {
here = fix(10.0, 10.0, bearing = 0f, speed = 10f)